@codeyam/codeyam-cli 0.1.0-staging.73a4bf4 → 0.1.0-staging.78c1cad

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 (864) hide show
  1. package/analyzer-template/.build-info.json +8 -8
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/package.json +24 -24
  4. package/analyzer-template/packages/ai/package.json +3 -3
  5. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +34 -3
  6. package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +135 -0
  7. package/analyzer-template/packages/ai/src/lib/astScopes/nodeToSource.ts +19 -0
  8. package/analyzer-template/packages/ai/src/lib/astScopes/paths.ts +11 -4
  9. package/analyzer-template/packages/ai/src/lib/completionCall.ts +114 -113
  10. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +295 -14
  11. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/ParentScopeManager.ts +10 -3
  12. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +16 -6
  13. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coercePrimitivesToArraysBySchema.ts +62 -0
  14. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.ts +35 -0
  15. package/analyzer-template/packages/ai/src/lib/dataStructureChunking.ts +15 -6
  16. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +78 -2
  17. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +96 -33
  18. package/analyzer-template/packages/analyze/index.ts +4 -1
  19. package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +19 -7
  20. package/analyzer-template/packages/analyze/src/lib/asts/index.ts +7 -2
  21. package/analyzer-template/packages/analyze/src/lib/asts/nodes/getNodeType.ts +1 -0
  22. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +28 -2
  23. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +14 -37
  24. package/analyzer-template/packages/analyze/src/lib/files/analyze/dependencyResolver.ts +0 -6
  25. package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +22 -6
  26. package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +9 -12
  27. package/analyzer-template/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.ts +21 -0
  28. package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +82 -10
  29. package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +4 -0
  30. package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +4 -0
  31. package/analyzer-template/packages/analyze/src/lib/files/analyzeNextRoute.ts +8 -3
  32. package/analyzer-template/packages/analyze/src/lib/files/scenarios/TransformationTracer.ts +65 -28
  33. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +322 -58
  34. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +0 -98
  35. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +1707 -1466
  36. package/analyzer-template/packages/aws/package.json +10 -10
  37. package/analyzer-template/packages/database/index.ts +1 -0
  38. package/analyzer-template/packages/database/package.json +4 -4
  39. package/analyzer-template/packages/database/src/lib/kysely/db.ts +8 -0
  40. package/analyzer-template/packages/database/src/lib/kysely/tables/editorScenariosTable.ts +164 -0
  41. package/analyzer-template/packages/database/src/lib/loadAnalysis.ts +25 -15
  42. package/analyzer-template/packages/database/src/lib/loadCommits.ts +31 -20
  43. package/analyzer-template/packages/database/src/lib/loadEntities.ts +0 -6
  44. package/analyzer-template/packages/database/src/lib/loadEntity.ts +19 -8
  45. package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +0 -5
  46. package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +94 -143
  47. package/analyzer-template/packages/database/src/lib/updateFreshAnalysisStatus.ts +58 -42
  48. package/analyzer-template/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.ts +81 -65
  49. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +29 -1
  50. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +33 -5
  51. package/analyzer-template/packages/github/dist/database/index.d.ts +1 -0
  52. package/analyzer-template/packages/github/dist/database/index.d.ts.map +1 -1
  53. package/analyzer-template/packages/github/dist/database/index.js +1 -0
  54. package/analyzer-template/packages/github/dist/database/index.js.map +1 -1
  55. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +2 -0
  56. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts.map +1 -1
  57. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +5 -0
  58. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js.map +1 -1
  59. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts +29 -0
  60. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts.map +1 -0
  61. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js +149 -0
  62. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -0
  63. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +5 -0
  64. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  65. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.d.ts.map +1 -1
  66. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js +7 -1
  67. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js.map +1 -1
  68. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts.map +1 -1
  69. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js +23 -13
  70. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js.map +1 -1
  71. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -1
  72. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +0 -6
  73. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
  74. package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.d.ts +4 -1
  75. package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.d.ts.map +1 -1
  76. package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.js +5 -5
  77. package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.js.map +1 -1
  78. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -1
  79. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +1 -4
  80. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  81. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
  82. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +76 -90
  83. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -1
  84. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.d.ts.map +1 -1
  85. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.js +41 -30
  86. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.js.map +1 -1
  87. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.d.ts.map +1 -1
  88. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.js +68 -57
  89. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.js.map +1 -1
  90. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts.map +1 -1
  91. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +29 -1
  92. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -1
  93. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.d.ts.map +1 -1
  94. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +33 -5
  95. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  96. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.d.ts +2 -0
  97. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.d.ts.map +1 -1
  98. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.js +2 -0
  99. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.js.map +1 -1
  100. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts +1 -0
  101. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  102. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +10 -0
  103. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  104. package/analyzer-template/packages/github/package.json +1 -1
  105. package/analyzer-template/packages/types/src/enums/ProjectFramework.ts +2 -0
  106. package/analyzer-template/packages/types/src/types/ProjectMetadata.ts +1 -0
  107. package/analyzer-template/packages/types/src/types/Scenario.ts +10 -0
  108. package/analyzer-template/packages/ui-components/package.json +1 -1
  109. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.d.ts +2 -0
  110. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.d.ts.map +1 -1
  111. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.js +2 -0
  112. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.js.map +1 -1
  113. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts +1 -0
  114. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  115. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +10 -0
  116. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  117. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts +3 -1
  118. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts.map +1 -1
  119. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js +28 -3
  120. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  121. package/analyzer-template/packages/utils/src/lib/fs/rsyncCopy.ts +41 -2
  122. package/analyzer-template/playwright/captureFromUrl.ts +89 -82
  123. package/analyzer-template/project/analyzeFileEntities.ts +26 -0
  124. package/analyzer-template/project/constructMockCode.ts +168 -48
  125. package/analyzer-template/project/orchestrateCapture.ts +4 -1
  126. package/analyzer-template/project/reconcileMockDataKeys.ts +19 -14
  127. package/analyzer-template/project/runMultiScenarioServer.ts +26 -3
  128. package/analyzer-template/project/start.ts +3 -0
  129. package/analyzer-template/project/startScenarioCapture.ts +9 -0
  130. package/analyzer-template/project/writeClientLogRoute.ts +125 -0
  131. package/analyzer-template/project/writeMockDataTsx.ts +17 -0
  132. package/analyzer-template/project/writeScenarioComponents.ts +110 -17
  133. package/analyzer-template/tsconfig.json +13 -1
  134. package/background/src/lib/virtualized/project/analyzeFileEntities.js +22 -0
  135. package/background/src/lib/virtualized/project/analyzeFileEntities.js.map +1 -1
  136. package/background/src/lib/virtualized/project/constructMockCode.js +143 -39
  137. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  138. package/background/src/lib/virtualized/project/orchestrateCapture.js +4 -1
  139. package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
  140. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +17 -11
  141. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  142. package/background/src/lib/virtualized/project/runMultiScenarioServer.js +23 -3
  143. package/background/src/lib/virtualized/project/runMultiScenarioServer.js.map +1 -1
  144. package/background/src/lib/virtualized/project/start.js +2 -0
  145. package/background/src/lib/virtualized/project/start.js.map +1 -1
  146. package/background/src/lib/virtualized/project/startScenarioCapture.js +5 -0
  147. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  148. package/background/src/lib/virtualized/project/writeClientLogRoute.js +110 -0
  149. package/background/src/lib/virtualized/project/writeClientLogRoute.js.map +1 -0
  150. package/background/src/lib/virtualized/project/writeMockDataTsx.js +12 -0
  151. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  152. package/background/src/lib/virtualized/project/writeScenarioComponents.js +83 -12
  153. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  154. package/codeyam-cli/scripts/apply-setup.js +208 -11
  155. package/codeyam-cli/scripts/apply-setup.js.map +1 -1
  156. package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js +196 -0
  157. package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js.map +1 -0
  158. package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js +114 -0
  159. package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js.map +1 -0
  160. package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js +149 -0
  161. package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js.map +1 -0
  162. package/codeyam-cli/src/cli.js +56 -25
  163. package/codeyam-cli/src/cli.js.map +1 -1
  164. package/codeyam-cli/src/commands/__tests__/editor.analyzeImportsArgs.test.js +47 -0
  165. package/codeyam-cli/src/commands/__tests__/editor.analyzeImportsArgs.test.js.map +1 -0
  166. package/codeyam-cli/src/commands/__tests__/editor.auditNoAutoAnalysis.test.js +71 -0
  167. package/codeyam-cli/src/commands/__tests__/editor.auditNoAutoAnalysis.test.js.map +1 -0
  168. package/codeyam-cli/src/commands/__tests__/editor.designSystem.test.js +30 -0
  169. package/codeyam-cli/src/commands/__tests__/editor.designSystem.test.js.map +1 -0
  170. package/codeyam-cli/src/commands/__tests__/editor.isolateArgs.test.js +51 -0
  171. package/codeyam-cli/src/commands/__tests__/editor.isolateArgs.test.js.map +1 -0
  172. package/codeyam-cli/src/commands/__tests__/editor.stepDispatch.test.js +56 -0
  173. package/codeyam-cli/src/commands/__tests__/editor.stepDispatch.test.js.map +1 -0
  174. package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js +101 -47
  175. package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js.map +1 -1
  176. package/codeyam-cli/src/commands/analyze.js +17 -7
  177. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  178. package/codeyam-cli/src/commands/default.js +14 -2
  179. package/codeyam-cli/src/commands/default.js.map +1 -1
  180. package/codeyam-cli/src/commands/editor.js +5923 -0
  181. package/codeyam-cli/src/commands/editor.js.map +1 -0
  182. package/codeyam-cli/src/commands/editorAnalyzeImportsArgs.js +23 -0
  183. package/codeyam-cli/src/commands/editorAnalyzeImportsArgs.js.map +1 -0
  184. package/codeyam-cli/src/commands/editorIsolateArgs.js +25 -0
  185. package/codeyam-cli/src/commands/editorIsolateArgs.js.map +1 -0
  186. package/codeyam-cli/src/commands/init.js +109 -45
  187. package/codeyam-cli/src/commands/init.js.map +1 -1
  188. package/codeyam-cli/src/commands/memory.js +89 -75
  189. package/codeyam-cli/src/commands/memory.js.map +1 -1
  190. package/codeyam-cli/src/commands/telemetry.js +37 -0
  191. package/codeyam-cli/src/commands/telemetry.js.map +1 -0
  192. package/codeyam-cli/src/data/designSystems.js +27 -0
  193. package/codeyam-cli/src/data/designSystems.js.map +1 -0
  194. package/codeyam-cli/src/data/techStacks.js +77 -0
  195. package/codeyam-cli/src/data/techStacks.js.map +1 -0
  196. package/codeyam-cli/src/utils/__tests__/analyzerFinalization.test.js +173 -0
  197. package/codeyam-cli/src/utils/__tests__/analyzerFinalization.test.js.map +1 -0
  198. package/codeyam-cli/src/utils/__tests__/backgroundServer.test.js +46 -0
  199. package/codeyam-cli/src/utils/__tests__/backgroundServer.test.js.map +1 -0
  200. package/codeyam-cli/src/utils/__tests__/devServerState.test.js +134 -0
  201. package/codeyam-cli/src/utils/__tests__/devServerState.test.js.map +1 -0
  202. package/codeyam-cli/src/utils/__tests__/editorApi.test.js +181 -0
  203. package/codeyam-cli/src/utils/__tests__/editorApi.test.js.map +1 -0
  204. package/codeyam-cli/src/utils/__tests__/editorAudit.test.js +4024 -0
  205. package/codeyam-cli/src/utils/__tests__/editorAudit.test.js.map +1 -0
  206. package/codeyam-cli/src/utils/__tests__/editorBroadcastViewport.test.js +76 -0
  207. package/codeyam-cli/src/utils/__tests__/editorBroadcastViewport.test.js.map +1 -0
  208. package/codeyam-cli/src/utils/__tests__/editorCapture.test.js +93 -0
  209. package/codeyam-cli/src/utils/__tests__/editorCapture.test.js.map +1 -0
  210. package/codeyam-cli/src/utils/__tests__/editorCaptureScenarioSeeding.test.js +137 -0
  211. package/codeyam-cli/src/utils/__tests__/editorCaptureScenarioSeeding.test.js.map +1 -0
  212. package/codeyam-cli/src/utils/__tests__/editorDeleteScenario.test.js +100 -0
  213. package/codeyam-cli/src/utils/__tests__/editorDeleteScenario.test.js.map +1 -0
  214. package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js +304 -0
  215. package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js.map +1 -0
  216. package/codeyam-cli/src/utils/__tests__/editorEntityChangeStatus.test.js +194 -0
  217. package/codeyam-cli/src/utils/__tests__/editorEntityChangeStatus.test.js.map +1 -0
  218. package/codeyam-cli/src/utils/__tests__/editorEntityHelpers.test.js +381 -0
  219. package/codeyam-cli/src/utils/__tests__/editorEntityHelpers.test.js.map +1 -0
  220. package/codeyam-cli/src/utils/__tests__/editorGuardMiddleware.test.js +67 -0
  221. package/codeyam-cli/src/utils/__tests__/editorGuardMiddleware.test.js.map +1 -0
  222. package/codeyam-cli/src/utils/__tests__/editorImageVerifier.test.js +294 -0
  223. package/codeyam-cli/src/utils/__tests__/editorImageVerifier.test.js.map +1 -0
  224. package/codeyam-cli/src/utils/__tests__/editorJournal.test.js +542 -0
  225. package/codeyam-cli/src/utils/__tests__/editorJournal.test.js.map +1 -0
  226. package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.test.js +594 -0
  227. package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.test.js.map +1 -0
  228. package/codeyam-cli/src/utils/__tests__/editorMigration.test.js +435 -0
  229. package/codeyam-cli/src/utils/__tests__/editorMigration.test.js.map +1 -0
  230. package/codeyam-cli/src/utils/__tests__/editorMockState.test.js +270 -0
  231. package/codeyam-cli/src/utils/__tests__/editorMockState.test.js.map +1 -0
  232. package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js +217 -0
  233. package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js.map +1 -0
  234. package/codeyam-cli/src/utils/__tests__/editorPreview.test.js +361 -0
  235. package/codeyam-cli/src/utils/__tests__/editorPreview.test.js.map +1 -0
  236. package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js +153 -0
  237. package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js.map +1 -0
  238. package/codeyam-cli/src/utils/__tests__/editorScenarioLookup.test.js +139 -0
  239. package/codeyam-cli/src/utils/__tests__/editorScenarioLookup.test.js.map +1 -0
  240. package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js +291 -0
  241. package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js.map +1 -0
  242. package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js +1768 -0
  243. package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js.map +1 -0
  244. package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js +329 -0
  245. package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js.map +1 -0
  246. package/codeyam-cli/src/utils/__tests__/editorSeedAdapterPrismaValidation.test.js +143 -0
  247. package/codeyam-cli/src/utils/__tests__/editorSeedAdapterPrismaValidation.test.js.map +1 -0
  248. package/codeyam-cli/src/utils/__tests__/editorSessionFilter.test.js +66 -0
  249. package/codeyam-cli/src/utils/__tests__/editorSessionFilter.test.js.map +1 -0
  250. package/codeyam-cli/src/utils/__tests__/editorShouldRevalidate.test.js +53 -0
  251. package/codeyam-cli/src/utils/__tests__/editorShouldRevalidate.test.js.map +1 -0
  252. package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js +2121 -0
  253. package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js.map +1 -0
  254. package/codeyam-cli/src/utils/__tests__/git.editor.test.js +134 -0
  255. package/codeyam-cli/src/utils/__tests__/git.editor.test.js.map +1 -0
  256. package/codeyam-cli/src/utils/__tests__/glossaryAdd.test.js +177 -0
  257. package/codeyam-cli/src/utils/__tests__/glossaryAdd.test.js.map +1 -0
  258. package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.test.js +122 -0
  259. package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.test.js.map +1 -0
  260. package/codeyam-cli/src/utils/__tests__/manualEntityAnalysis.test.js +302 -0
  261. package/codeyam-cli/src/utils/__tests__/manualEntityAnalysis.test.js.map +1 -0
  262. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js +185 -0
  263. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js.map +1 -0
  264. package/codeyam-cli/src/utils/__tests__/parseRegisterArg.test.js +129 -0
  265. package/codeyam-cli/src/utils/__tests__/parseRegisterArg.test.js.map +1 -0
  266. package/codeyam-cli/src/utils/__tests__/pathIgnoring.test.js +9 -0
  267. package/codeyam-cli/src/utils/__tests__/pathIgnoring.test.js.map +1 -1
  268. package/codeyam-cli/src/utils/__tests__/project.test.js +65 -0
  269. package/codeyam-cli/src/utils/__tests__/project.test.js.map +1 -0
  270. package/codeyam-cli/src/utils/__tests__/registerScenarioResult.test.js +127 -0
  271. package/codeyam-cli/src/utils/__tests__/registerScenarioResult.test.js.map +1 -0
  272. package/codeyam-cli/src/utils/__tests__/routePatternMatching.test.js +118 -0
  273. package/codeyam-cli/src/utils/__tests__/routePatternMatching.test.js.map +1 -0
  274. package/codeyam-cli/src/utils/__tests__/scenarioCoverage.test.js +284 -0
  275. package/codeyam-cli/src/utils/__tests__/scenarioCoverage.test.js.map +1 -0
  276. package/codeyam-cli/src/utils/__tests__/scenarioMarkers.test.js +121 -0
  277. package/codeyam-cli/src/utils/__tests__/scenarioMarkers.test.js.map +1 -0
  278. package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js +672 -0
  279. package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js.map +1 -0
  280. package/codeyam-cli/src/utils/__tests__/screenshotHash.test.js +84 -0
  281. package/codeyam-cli/src/utils/__tests__/screenshotHash.test.js.map +1 -0
  282. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +51 -4
  283. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  284. package/codeyam-cli/src/utils/__tests__/telemetry.test.js +159 -0
  285. package/codeyam-cli/src/utils/__tests__/telemetry.test.js.map +1 -0
  286. package/codeyam-cli/src/utils/__tests__/templateConsistency.test.js +51 -0
  287. package/codeyam-cli/src/utils/__tests__/templateConsistency.test.js.map +1 -0
  288. package/codeyam-cli/src/utils/__tests__/testRunner.test.js +216 -0
  289. package/codeyam-cli/src/utils/__tests__/testRunner.test.js.map +1 -0
  290. package/codeyam-cli/src/utils/__tests__/webappDetection.test.js +148 -0
  291. package/codeyam-cli/src/utils/__tests__/webappDetection.test.js.map +1 -0
  292. package/codeyam-cli/src/utils/analysisRunner.js +39 -8
  293. package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
  294. package/codeyam-cli/src/utils/analyzer.js +19 -0
  295. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  296. package/codeyam-cli/src/utils/analyzerFinalization.js +100 -0
  297. package/codeyam-cli/src/utils/analyzerFinalization.js.map +1 -0
  298. package/codeyam-cli/src/utils/backgroundServer.js +120 -45
  299. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  300. package/codeyam-cli/src/utils/buildFlags.js +4 -0
  301. package/codeyam-cli/src/utils/buildFlags.js.map +1 -0
  302. package/codeyam-cli/src/utils/database.js +37 -2
  303. package/codeyam-cli/src/utils/database.js.map +1 -1
  304. package/codeyam-cli/src/utils/devModeEvents.js +40 -0
  305. package/codeyam-cli/src/utils/devModeEvents.js.map +1 -0
  306. package/codeyam-cli/src/utils/devServerState.js +71 -0
  307. package/codeyam-cli/src/utils/devServerState.js.map +1 -0
  308. package/codeyam-cli/src/utils/editorApi.js +95 -0
  309. package/codeyam-cli/src/utils/editorApi.js.map +1 -0
  310. package/codeyam-cli/src/utils/editorAudit.js +844 -0
  311. package/codeyam-cli/src/utils/editorAudit.js.map +1 -0
  312. package/codeyam-cli/src/utils/editorBroadcastViewport.js +26 -0
  313. package/codeyam-cli/src/utils/editorBroadcastViewport.js.map +1 -0
  314. package/codeyam-cli/src/utils/editorCapture.js +102 -0
  315. package/codeyam-cli/src/utils/editorCapture.js.map +1 -0
  316. package/codeyam-cli/src/utils/editorDeleteScenario.js +67 -0
  317. package/codeyam-cli/src/utils/editorDeleteScenario.js.map +1 -0
  318. package/codeyam-cli/src/utils/editorDevServer.js +197 -0
  319. package/codeyam-cli/src/utils/editorDevServer.js.map +1 -0
  320. package/codeyam-cli/src/utils/editorEntityChangeStatus.js +50 -0
  321. package/codeyam-cli/src/utils/editorEntityChangeStatus.js.map +1 -0
  322. package/codeyam-cli/src/utils/editorEntityHelpers.js +144 -0
  323. package/codeyam-cli/src/utils/editorEntityHelpers.js.map +1 -0
  324. package/codeyam-cli/src/utils/editorGuard.js +36 -0
  325. package/codeyam-cli/src/utils/editorGuard.js.map +1 -0
  326. package/codeyam-cli/src/utils/editorImageVerifier.js +155 -0
  327. package/codeyam-cli/src/utils/editorImageVerifier.js.map +1 -0
  328. package/codeyam-cli/src/utils/editorJournal.js +225 -0
  329. package/codeyam-cli/src/utils/editorJournal.js.map +1 -0
  330. package/codeyam-cli/src/utils/editorLoaderHelpers.js +152 -0
  331. package/codeyam-cli/src/utils/editorLoaderHelpers.js.map +1 -0
  332. package/codeyam-cli/src/utils/editorMigration.js +224 -0
  333. package/codeyam-cli/src/utils/editorMigration.js.map +1 -0
  334. package/codeyam-cli/src/utils/editorMockState.js +248 -0
  335. package/codeyam-cli/src/utils/editorMockState.js.map +1 -0
  336. package/codeyam-cli/src/utils/editorPreloadHelpers.js +135 -0
  337. package/codeyam-cli/src/utils/editorPreloadHelpers.js.map +1 -0
  338. package/codeyam-cli/src/utils/editorPreview.js +139 -0
  339. package/codeyam-cli/src/utils/editorPreview.js.map +1 -0
  340. package/codeyam-cli/src/utils/editorRecapture.js +109 -0
  341. package/codeyam-cli/src/utils/editorRecapture.js.map +1 -0
  342. package/codeyam-cli/src/utils/editorScenarioSwitch.js +134 -0
  343. package/codeyam-cli/src/utils/editorScenarioSwitch.js.map +1 -0
  344. package/codeyam-cli/src/utils/editorScenarios.js +677 -0
  345. package/codeyam-cli/src/utils/editorScenarios.js.map +1 -0
  346. package/codeyam-cli/src/utils/editorSeedAdapter.js +462 -0
  347. package/codeyam-cli/src/utils/editorSeedAdapter.js.map +1 -0
  348. package/codeyam-cli/src/utils/editorShouldRevalidate.js +21 -0
  349. package/codeyam-cli/src/utils/editorShouldRevalidate.js.map +1 -0
  350. package/codeyam-cli/src/utils/entityChangeStatus.js +394 -0
  351. package/codeyam-cli/src/utils/entityChangeStatus.js.map +1 -0
  352. package/codeyam-cli/src/utils/entityChangeStatus.server.js +227 -0
  353. package/codeyam-cli/src/utils/entityChangeStatus.server.js.map +1 -0
  354. package/codeyam-cli/src/utils/fileMetadata.js +5 -0
  355. package/codeyam-cli/src/utils/fileMetadata.js.map +1 -1
  356. package/codeyam-cli/src/utils/fileWatcher.js +63 -9
  357. package/codeyam-cli/src/utils/fileWatcher.js.map +1 -1
  358. package/codeyam-cli/src/utils/git.js +103 -0
  359. package/codeyam-cli/src/utils/git.js.map +1 -1
  360. package/codeyam-cli/src/utils/glossaryAdd.js +74 -0
  361. package/codeyam-cli/src/utils/glossaryAdd.js.map +1 -0
  362. package/codeyam-cli/src/utils/install-skills.js +71 -15
  363. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  364. package/codeyam-cli/src/utils/interactiveSyncWatcher.js +126 -0
  365. package/codeyam-cli/src/utils/interactiveSyncWatcher.js.map +1 -0
  366. package/codeyam-cli/src/utils/manualEntityAnalysis.js +196 -0
  367. package/codeyam-cli/src/utils/manualEntityAnalysis.js.map +1 -0
  368. package/codeyam-cli/src/utils/npmVersionCheck.js +76 -0
  369. package/codeyam-cli/src/utils/npmVersionCheck.js.map +1 -0
  370. package/codeyam-cli/src/utils/parseRegisterArg.js +31 -0
  371. package/codeyam-cli/src/utils/parseRegisterArg.js.map +1 -0
  372. package/codeyam-cli/src/utils/pathIgnoring.js +19 -7
  373. package/codeyam-cli/src/utils/pathIgnoring.js.map +1 -1
  374. package/codeyam-cli/src/utils/progress.js +2 -2
  375. package/codeyam-cli/src/utils/progress.js.map +1 -1
  376. package/codeyam-cli/src/utils/project.js +15 -5
  377. package/codeyam-cli/src/utils/project.js.map +1 -1
  378. package/codeyam-cli/src/utils/queue/__tests__/heartbeat.test.js +11 -11
  379. package/codeyam-cli/src/utils/queue/__tests__/heartbeat.test.js.map +1 -1
  380. package/codeyam-cli/src/utils/queue/__tests__/job.interactiveStart.test.js +159 -0
  381. package/codeyam-cli/src/utils/queue/__tests__/job.interactiveStart.test.js.map +1 -0
  382. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +22 -0
  383. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
  384. package/codeyam-cli/src/utils/queue/heartbeat.js +13 -5
  385. package/codeyam-cli/src/utils/queue/heartbeat.js.map +1 -1
  386. package/codeyam-cli/src/utils/queue/job.js +105 -7
  387. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  388. package/codeyam-cli/src/utils/queue/manager.js +7 -6
  389. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  390. package/codeyam-cli/src/utils/registerScenarioResult.js +52 -0
  391. package/codeyam-cli/src/utils/registerScenarioResult.js.map +1 -0
  392. package/codeyam-cli/src/utils/requireSimulations.js +1 -1
  393. package/codeyam-cli/src/utils/requireSimulations.js.map +1 -1
  394. package/codeyam-cli/src/utils/routePatternMatching.js +129 -0
  395. package/codeyam-cli/src/utils/routePatternMatching.js.map +1 -0
  396. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js +5 -6
  397. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js.map +1 -1
  398. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js +1 -1
  399. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js.map +1 -1
  400. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js +0 -1
  401. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js.map +1 -1
  402. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js +2 -4
  403. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js.map +1 -1
  404. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js +4 -6
  405. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js.map +1 -1
  406. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js +1 -1
  407. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js.map +1 -1
  408. package/codeyam-cli/src/utils/rules/__tests__/parser.test.js +83 -0
  409. package/codeyam-cli/src/utils/rules/__tests__/parser.test.js.map +1 -0
  410. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js +118 -0
  411. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js.map +1 -0
  412. package/codeyam-cli/src/utils/rules/__tests__/rulePlacement.test.js +72 -0
  413. package/codeyam-cli/src/utils/rules/__tests__/rulePlacement.test.js.map +1 -0
  414. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js +76 -0
  415. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js.map +1 -0
  416. package/codeyam-cli/src/utils/rules/index.js +1 -0
  417. package/codeyam-cli/src/utils/rules/index.js.map +1 -1
  418. package/codeyam-cli/src/utils/rules/parser.js +14 -4
  419. package/codeyam-cli/src/utils/rules/parser.js.map +1 -1
  420. package/codeyam-cli/src/utils/rules/pathMatcher.js +34 -3
  421. package/codeyam-cli/src/utils/rules/pathMatcher.js.map +1 -1
  422. package/codeyam-cli/src/utils/rules/rulePlacement.js +65 -0
  423. package/codeyam-cli/src/utils/rules/rulePlacement.js.map +1 -0
  424. package/codeyam-cli/src/utils/rules/sourceFiles.js +43 -0
  425. package/codeyam-cli/src/utils/rules/sourceFiles.js.map +1 -0
  426. package/codeyam-cli/src/utils/scenarioCoverage.js +77 -0
  427. package/codeyam-cli/src/utils/scenarioCoverage.js.map +1 -0
  428. package/codeyam-cli/src/utils/scenarioMarkers.js +134 -0
  429. package/codeyam-cli/src/utils/scenarioMarkers.js.map +1 -0
  430. package/codeyam-cli/src/utils/scenariosManifest.js +313 -0
  431. package/codeyam-cli/src/utils/scenariosManifest.js.map +1 -0
  432. package/codeyam-cli/src/utils/screenshotHash.js +26 -0
  433. package/codeyam-cli/src/utils/screenshotHash.js.map +1 -0
  434. package/codeyam-cli/src/utils/serverState.js +57 -2
  435. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  436. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +83 -11
  437. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  438. package/codeyam-cli/src/utils/simulationGateMiddleware.js +175 -0
  439. package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -0
  440. package/codeyam-cli/src/utils/slugUtils.js +25 -0
  441. package/codeyam-cli/src/utils/slugUtils.js.map +1 -0
  442. package/codeyam-cli/src/utils/syncMocksMiddleware.js +7 -26
  443. package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +1 -1
  444. package/codeyam-cli/src/utils/telemetry.js +106 -0
  445. package/codeyam-cli/src/utils/telemetry.js.map +1 -0
  446. package/codeyam-cli/src/utils/telemetryMiddleware.js +22 -0
  447. package/codeyam-cli/src/utils/telemetryMiddleware.js.map +1 -0
  448. package/codeyam-cli/src/utils/testResultCache.js +53 -0
  449. package/codeyam-cli/src/utils/testResultCache.js.map +1 -0
  450. package/codeyam-cli/src/utils/testResultCache.server.js +81 -0
  451. package/codeyam-cli/src/utils/testResultCache.server.js.map +1 -0
  452. package/codeyam-cli/src/utils/testResultCache.server.test.js +187 -0
  453. package/codeyam-cli/src/utils/testResultCache.server.test.js.map +1 -0
  454. package/codeyam-cli/src/utils/testResultCache.test.js +230 -0
  455. package/codeyam-cli/src/utils/testResultCache.test.js.map +1 -0
  456. package/codeyam-cli/src/utils/testRunner.js +350 -0
  457. package/codeyam-cli/src/utils/testRunner.js.map +1 -0
  458. package/codeyam-cli/src/utils/transcriptPruning.js +67 -0
  459. package/codeyam-cli/src/utils/transcriptPruning.js.map +1 -0
  460. package/codeyam-cli/src/utils/versionInfo.js +46 -0
  461. package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
  462. package/codeyam-cli/src/utils/webappDetection.js +38 -3
  463. package/codeyam-cli/src/utils/webappDetection.js.map +1 -1
  464. package/codeyam-cli/src/webserver/__tests__/api.interactive-switch-scenario.test.js +98 -0
  465. package/codeyam-cli/src/webserver/__tests__/api.interactive-switch-scenario.test.js.map +1 -0
  466. package/codeyam-cli/src/webserver/__tests__/buildPtyEnv.test.js +35 -0
  467. package/codeyam-cli/src/webserver/__tests__/buildPtyEnv.test.js.map +1 -0
  468. package/codeyam-cli/src/webserver/__tests__/clientErrors.test.js +107 -0
  469. package/codeyam-cli/src/webserver/__tests__/clientErrors.test.js.map +1 -0
  470. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js +66 -0
  471. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js.map +1 -0
  472. package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js +647 -0
  473. package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js.map +1 -0
  474. package/codeyam-cli/src/webserver/__tests__/idleDetector.test.js +315 -0
  475. package/codeyam-cli/src/webserver/__tests__/idleDetector.test.js.map +1 -0
  476. package/codeyam-cli/src/webserver/__tests__/stripClaudeCommand.test.js +135 -0
  477. package/codeyam-cli/src/webserver/__tests__/stripClaudeCommand.test.js.map +1 -0
  478. package/codeyam-cli/src/webserver/app/lib/clientErrors.js +86 -0
  479. package/codeyam-cli/src/webserver/app/lib/clientErrors.js.map +1 -0
  480. package/codeyam-cli/src/webserver/app/lib/database.js +41 -27
  481. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  482. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  483. package/codeyam-cli/src/webserver/app/lib/git.js +397 -0
  484. package/codeyam-cli/src/webserver/app/lib/git.js.map +1 -0
  485. package/codeyam-cli/src/webserver/app/routes/api.interactive-switch-scenario.js +34 -0
  486. package/codeyam-cli/src/webserver/app/routes/api.interactive-switch-scenario.js.map +1 -0
  487. package/codeyam-cli/src/webserver/app/types/editor.js +8 -0
  488. package/codeyam-cli/src/webserver/app/types/editor.js.map +1 -0
  489. package/codeyam-cli/src/webserver/backgroundServer.js +141 -42
  490. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  491. package/codeyam-cli/src/webserver/bootstrap.js +11 -0
  492. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -1
  493. package/codeyam-cli/src/webserver/build/client/assets/CopyButton-CLe80MMu.js +1 -0
  494. package/codeyam-cli/src/webserver/build/client/assets/{EntityItem-BLlhOa3C.js → EntityItem-Crt_KN_U.js} +5 -5
  495. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeBadge-CQgyEGV-.js +1 -0
  496. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeIcon-CzdG5I7z.js → EntityTypeIcon-CD7lGABo.js} +9 -9
  497. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-CgTNOhnu.js +1 -0
  498. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-DtYTSPL2.js +25 -0
  499. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-D3s1MFkb.js +3 -0
  500. package/codeyam-cli/src/webserver/build/client/assets/{LoadingDots-B1LNGboS.js → LoadingDots-By5zI316.js} +1 -1
  501. package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-B0Ll1DjK.js → LogViewer-CM5zg40N.js} +3 -3
  502. package/codeyam-cli/src/webserver/build/client/assets/MiniClaudeChat-CQENLSrF.js +36 -0
  503. package/codeyam-cli/src/webserver/build/client/assets/{ReportIssueModal-CVOvmCKb.js → ReportIssueModal-C2PLkej3.js} +4 -4
  504. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-DanvyBPb.js +1 -0
  505. package/codeyam-cli/src/webserver/build/client/assets/{ScenarioViewer-D54Mmpwi.js → ScenarioViewer-CefgqbCr.js} +3 -3
  506. package/codeyam-cli/src/webserver/build/client/assets/Spinner-Bc8BG-Lw.js +34 -0
  507. package/codeyam-cli/src/webserver/build/client/assets/TruncatedFilePath-CK7-NaPZ.js +1 -0
  508. package/codeyam-cli/src/webserver/build/client/assets/ViewportInspectBar-BA_Ry-rs.js +1 -0
  509. package/codeyam-cli/src/webserver/build/client/assets/{_index-CKTtYlBU.js → _index-C1YkzTAV.js} +4 -4
  510. package/codeyam-cli/src/webserver/build/client/assets/{activity.(_tab)-CdziRIWU.js → activity.(_tab)-yH46LLUz.js} +8 -8
  511. package/codeyam-cli/src/webserver/build/client/assets/addon-canvas-DpzMmAy5.js +1 -0
  512. package/codeyam-cli/src/webserver/build/client/assets/addon-fit-YJmn1quW.js +12 -0
  513. package/codeyam-cli/src/webserver/build/client/assets/addon-web-links-CHx25PAe.js +1 -0
  514. package/codeyam-cli/src/webserver/build/client/assets/addon-webgl-DI8QOUvO.js +58 -0
  515. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-Bg3e7q4S.js +22 -0
  516. package/codeyam-cli/src/webserver/build/client/assets/api.dev-mode-events-l0sNRNKZ.js +1 -0
  517. package/codeyam-cli/src/webserver/build/client/assets/api.editor-audit-l0sNRNKZ.js +1 -0
  518. package/codeyam-cli/src/webserver/build/client/assets/api.editor-capture-scenario-l0sNRNKZ.js +1 -0
  519. package/codeyam-cli/src/webserver/build/client/assets/api.editor-client-errors-l0sNRNKZ.js +1 -0
  520. package/codeyam-cli/src/webserver/build/client/assets/api.editor-commit-l0sNRNKZ.js +1 -0
  521. package/codeyam-cli/src/webserver/build/client/assets/api.editor-dev-server-l0sNRNKZ.js +1 -0
  522. package/codeyam-cli/src/webserver/build/client/assets/api.editor-entity-status-l0sNRNKZ.js +1 -0
  523. package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-diff-l0sNRNKZ.js +1 -0
  524. package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-l0sNRNKZ.js +1 -0
  525. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-entry-l0sNRNKZ.js +1 -0
  526. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-image._-l0sNRNKZ.js +1 -0
  527. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-l0sNRNKZ.js +1 -0
  528. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-screenshot-l0sNRNKZ.js +1 -0
  529. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-update-l0sNRNKZ.js +1 -0
  530. package/codeyam-cli/src/webserver/build/client/assets/api.editor-load-commit-l0sNRNKZ.js +1 -0
  531. package/codeyam-cli/src/webserver/build/client/assets/api.editor-project-info-l0sNRNKZ.js +1 -0
  532. package/codeyam-cli/src/webserver/build/client/assets/api.editor-recapture-stale-l0sNRNKZ.js +1 -0
  533. package/codeyam-cli/src/webserver/build/client/assets/api.editor-refresh-l0sNRNKZ.js +1 -0
  534. package/codeyam-cli/src/webserver/build/client/assets/api.editor-register-scenario-l0sNRNKZ.js +1 -0
  535. package/codeyam-cli/src/webserver/build/client/assets/api.editor-rename-scenario-l0sNRNKZ.js +1 -0
  536. package/codeyam-cli/src/webserver/build/client/assets/api.editor-save-scenario-data-l0sNRNKZ.js +1 -0
  537. package/codeyam-cli/src/webserver/build/client/assets/api.editor-save-seed-state-l0sNRNKZ.js +1 -0
  538. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-coverage-l0sNRNKZ.js +1 -0
  539. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-data-l0sNRNKZ.js +1 -0
  540. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-image._-l0sNRNKZ.js +1 -0
  541. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-prompt-l0sNRNKZ.js +1 -0
  542. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenarios-l0sNRNKZ.js +1 -0
  543. package/codeyam-cli/src/webserver/build/client/assets/api.editor-schema-l0sNRNKZ.js +1 -0
  544. package/codeyam-cli/src/webserver/build/client/assets/api.editor-session-l0sNRNKZ.js +1 -0
  545. package/codeyam-cli/src/webserver/build/client/assets/api.editor-switch-scenario-l0sNRNKZ.js +1 -0
  546. package/codeyam-cli/src/webserver/build/client/assets/api.editor-test-results-l0sNRNKZ.js +1 -0
  547. package/codeyam-cli/src/webserver/build/client/assets/api.editor-verify-routes-l0sNRNKZ.js +1 -0
  548. package/codeyam-cli/src/webserver/build/client/assets/api.interactive-switch-scenario-l0sNRNKZ.js +1 -0
  549. package/codeyam-cli/src/webserver/build/client/assets/api.rule-path-l0sNRNKZ.js +1 -0
  550. package/codeyam-cli/src/webserver/build/client/assets/{book-open-Ch8b7GyQ.js → book-open-CL-lMgHh.js} +2 -2
  551. package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-vJHJExlT.js → chevron-down-GmAjGS9-.js} +2 -2
  552. package/codeyam-cli/src/webserver/build/client/assets/chunk-JZWAC4HX-BAdwhyCx.js +43 -0
  553. package/codeyam-cli/src/webserver/build/client/assets/{circle-check-rwynPZTW.js → circle-check-DFcQkN5j.js} +2 -2
  554. package/codeyam-cli/src/webserver/build/client/assets/{copy-BBSpeBYf.js → copy-C6iF61Xs.js} +3 -3
  555. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-4ImjHTVC.js +41 -0
  556. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-Coe5NhbS.js +1 -0
  557. package/codeyam-cli/src/webserver/build/client/assets/{cy-logo-cli-CCKUIm0S.svg → cy-logo-cli-DoA97ML3.svg} +2 -2
  558. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-CRepiabR.js +1 -0
  559. package/codeyam-cli/src/webserver/build/client/assets/editor._tab-Gbk_i5Js.js +1 -0
  560. package/codeyam-cli/src/webserver/build/client/assets/editor.entity.(_sha)-CRxPi2BB.js +96 -0
  561. package/codeyam-cli/src/webserver/build/client/assets/editorPreview-CluPkvXJ.js +41 -0
  562. package/codeyam-cli/src/webserver/build/client/assets/entity._sha._-DYJRGiDI.js +24 -0
  563. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.dev-wdiwx5-Z.js +6 -0
  564. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-BrkN-40Y.js +6 -0
  565. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-DxfhekTZ.js +6 -0
  566. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.edit._scenarioId-BEqewwtZ.js → entity._sha_.edit._scenarioId-CRXJWmpB.js} +2 -2
  567. package/codeyam-cli/src/webserver/build/client/assets/{entry.client-Dxqz8ygt.js → entry.client-SuW9syRS.js} +6 -6
  568. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-Daa96Fr1.js +1 -0
  569. package/codeyam-cli/src/webserver/build/client/assets/files-D-xGrg29.js +1 -0
  570. package/codeyam-cli/src/webserver/build/client/assets/git-Bq_fbXP5.js +1 -0
  571. package/codeyam-cli/src/webserver/build/client/assets/globals-BsGHu8WX.css +1 -0
  572. package/codeyam-cli/src/webserver/build/client/assets/{index-DgAAopZk.js → index-Bp1l4hSv.js} +1 -1
  573. package/codeyam-cli/src/webserver/build/client/assets/{index-viijWaN6.js → index-CWV9XZiG.js} +1 -1
  574. package/codeyam-cli/src/webserver/build/client/assets/index-DE3jI_dv.js +15 -0
  575. package/codeyam-cli/src/webserver/build/client/assets/jsx-runtime-D_zvdyIk.js +9 -0
  576. package/codeyam-cli/src/webserver/build/client/assets/labs-B_IX45ih.js +1 -0
  577. package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-LGi2eKI5.js → loader-circle-De-7qQ2u.js} +2 -2
  578. package/codeyam-cli/src/webserver/build/client/assets/manifest-9032538f.js +1 -0
  579. package/codeyam-cli/src/webserver/build/client/assets/memory-Cx2xEx7s.js +101 -0
  580. package/codeyam-cli/src/webserver/build/client/assets/{pause-DxJFmMsK.js → pause-CFxEKL1u.js} +3 -3
  581. package/codeyam-cli/src/webserver/build/client/assets/root-dKFRTYcy.js +80 -0
  582. package/codeyam-cli/src/webserver/build/client/assets/{search-Cu3QE9E5.js → search-BdBb5aqc.js} +2 -2
  583. package/codeyam-cli/src/webserver/build/client/assets/settings-DdE-Untf.js +1 -0
  584. package/codeyam-cli/src/webserver/build/client/assets/simulations-DSCdE99u.js +1 -0
  585. package/codeyam-cli/src/webserver/build/client/assets/{terminal-dAhIBEcd.js → terminal-CrplD4b1.js} +3 -3
  586. package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-C4CYTEeP.js → triangle-alert-DqJ0j69l.js} +2 -2
  587. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-DhXHbEjP.js +1 -0
  588. package/codeyam-cli/src/webserver/build/client/assets/useLastLogLine-D9QZKaLJ.js +2 -0
  589. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-Cy5Qg_UR.js +1 -0
  590. package/codeyam-cli/src/webserver/build/client/assets/useToast-5HR2j9ZE.js +1 -0
  591. package/codeyam-cli/src/webserver/build/client/assets/xterm-BqvuqXEL.js +27 -0
  592. package/codeyam-cli/src/webserver/build/client/sound-test.html +98 -0
  593. package/codeyam-cli/src/webserver/build/server/assets/analysisRunner-B6HnVI5u.js +16 -0
  594. package/codeyam-cli/src/webserver/build/server/assets/index-rV_xLS1u.js +1 -0
  595. package/codeyam-cli/src/webserver/build/server/assets/init-BdWDvetv.js +10 -0
  596. package/codeyam-cli/src/webserver/build/server/assets/progress-CHTtrxFG.js +1 -0
  597. package/codeyam-cli/src/webserver/build/server/assets/server-build-B_jdq5dT.js +689 -0
  598. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  599. package/codeyam-cli/src/webserver/build-info.json +5 -5
  600. package/codeyam-cli/src/webserver/devServer.js +39 -5
  601. package/codeyam-cli/src/webserver/devServer.js.map +1 -1
  602. package/codeyam-cli/src/webserver/editorProxy.js +1028 -0
  603. package/codeyam-cli/src/webserver/editorProxy.js.map +1 -0
  604. package/codeyam-cli/src/webserver/idleDetector.js +130 -0
  605. package/codeyam-cli/src/webserver/idleDetector.js.map +1 -0
  606. package/codeyam-cli/src/webserver/mockStateEvents.js +28 -0
  607. package/codeyam-cli/src/webserver/mockStateEvents.js.map +1 -0
  608. package/codeyam-cli/src/webserver/public/sound-test.html +98 -0
  609. package/codeyam-cli/src/webserver/scripts/codeyam-preload.mjs +414 -0
  610. package/codeyam-cli/src/webserver/scripts/journalCapture.ts +283 -0
  611. package/codeyam-cli/src/webserver/server.js +379 -1
  612. package/codeyam-cli/src/webserver/server.js.map +1 -1
  613. package/codeyam-cli/src/webserver/terminalServer.js +952 -0
  614. package/codeyam-cli/src/webserver/terminalServer.js.map +1 -0
  615. package/codeyam-cli/templates/__tests__/editor-step-hook.prompt-capture.test.ts +118 -0
  616. package/codeyam-cli/templates/chrome-extension-react/EXTENSION_SETUP.md +75 -0
  617. package/codeyam-cli/templates/chrome-extension-react/README.md +46 -0
  618. package/codeyam-cli/templates/chrome-extension-react/gitignore +15 -0
  619. package/codeyam-cli/templates/chrome-extension-react/index.html +12 -0
  620. package/codeyam-cli/templates/chrome-extension-react/package.json +27 -0
  621. package/codeyam-cli/templates/chrome-extension-react/popup.html +12 -0
  622. package/codeyam-cli/templates/chrome-extension-react/public/manifest.json +15 -0
  623. package/codeyam-cli/templates/chrome-extension-react/src/background/service-worker.ts +7 -0
  624. package/codeyam-cli/templates/chrome-extension-react/src/globals.css +6 -0
  625. package/codeyam-cli/templates/chrome-extension-react/src/lib/storage.ts +37 -0
  626. package/codeyam-cli/templates/chrome-extension-react/src/popup/App.tsx +12 -0
  627. package/codeyam-cli/templates/chrome-extension-react/src/popup/main.tsx +10 -0
  628. package/codeyam-cli/templates/chrome-extension-react/tsconfig.json +24 -0
  629. package/codeyam-cli/templates/chrome-extension-react/vite.config.ts +41 -0
  630. package/codeyam-cli/templates/codeyam-editor-claude.md +149 -0
  631. package/codeyam-cli/templates/codeyam-editor-reference.md +216 -0
  632. package/codeyam-cli/templates/design-systems/clean-dashboard-design-system.md +255 -0
  633. package/codeyam-cli/templates/design-systems/editorial-design-system.md +267 -0
  634. package/codeyam-cli/templates/design-systems/mono-brutalist-design-system.md +256 -0
  635. package/codeyam-cli/templates/design-systems/neo-brutalist-design-system.md +294 -0
  636. package/codeyam-cli/templates/editor-step-hook.py +368 -0
  637. package/codeyam-cli/templates/expo-react-native/MOBILE_SETUP.md +203 -0
  638. package/codeyam-cli/templates/expo-react-native/README.md +41 -0
  639. package/codeyam-cli/templates/expo-react-native/__tests__/.gitkeep +0 -0
  640. package/codeyam-cli/templates/expo-react-native/app/_layout.tsx +13 -0
  641. package/codeyam-cli/templates/expo-react-native/app/index.tsx +36 -0
  642. package/codeyam-cli/templates/expo-react-native/app.json +18 -0
  643. package/codeyam-cli/templates/expo-react-native/babel.config.js +9 -0
  644. package/codeyam-cli/templates/expo-react-native/gitignore +12 -0
  645. package/codeyam-cli/templates/expo-react-native/global.css +10 -0
  646. package/codeyam-cli/templates/expo-react-native/lib/storage.ts +32 -0
  647. package/codeyam-cli/templates/expo-react-native/lib/theme.ts +73 -0
  648. package/codeyam-cli/templates/expo-react-native/metro.config.js +6 -0
  649. package/codeyam-cli/templates/expo-react-native/nativewind-env.d.ts +1 -0
  650. package/codeyam-cli/templates/expo-react-native/package.json +48 -0
  651. package/codeyam-cli/templates/expo-react-native/tailwind.config.js +10 -0
  652. package/codeyam-cli/templates/expo-react-native/tsconfig.json +10 -0
  653. package/codeyam-cli/templates/hooks/staleness-check.sh +43 -0
  654. package/codeyam-cli/templates/isolation-route/expo-router.tsx.template +54 -0
  655. package/codeyam-cli/templates/isolation-route/next-app.tsx.template +80 -0
  656. package/codeyam-cli/templates/isolation-route/next-pages.tsx.template +79 -0
  657. package/codeyam-cli/templates/isolation-route/vite-react.tsx.template +78 -0
  658. package/codeyam-cli/templates/msw/browser-setup.ts.template +47 -0
  659. package/codeyam-cli/templates/msw/handler-router.ts.template +47 -0
  660. package/codeyam-cli/templates/msw/server-setup.ts.template +52 -0
  661. package/codeyam-cli/templates/nextjs-prisma-sqlite/AUTH_PATTERNS.md +308 -0
  662. package/codeyam-cli/templates/nextjs-prisma-sqlite/AUTH_UPGRADE.md +304 -0
  663. package/codeyam-cli/templates/nextjs-prisma-sqlite/DATABASE.md +126 -0
  664. package/codeyam-cli/templates/nextjs-prisma-sqlite/FEATURE_PATTERNS.md +37 -0
  665. package/codeyam-cli/templates/nextjs-prisma-sqlite/README.md +53 -0
  666. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/api/todos/route.ts +17 -0
  667. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/codeyam-isolate/layout.tsx +12 -0
  668. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/globals.css +26 -0
  669. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/layout.tsx +34 -0
  670. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/lib/prisma.ts +24 -0
  671. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/page.tsx +10 -0
  672. package/codeyam-cli/templates/nextjs-prisma-sqlite/env +4 -0
  673. package/codeyam-cli/templates/nextjs-prisma-sqlite/eslint.config.mjs +11 -0
  674. package/codeyam-cli/templates/nextjs-prisma-sqlite/gitignore +64 -0
  675. package/codeyam-cli/templates/nextjs-prisma-sqlite/next.config.ts +14 -0
  676. package/codeyam-cli/templates/nextjs-prisma-sqlite/package.json +39 -0
  677. package/codeyam-cli/templates/nextjs-prisma-sqlite/postcss.config.mjs +7 -0
  678. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/schema.prisma +27 -0
  679. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/seed.ts +40 -0
  680. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma.config.ts +12 -0
  681. package/codeyam-cli/templates/nextjs-prisma-sqlite/seed-adapter.ts +140 -0
  682. package/codeyam-cli/templates/nextjs-prisma-sqlite/tsconfig.json +34 -0
  683. package/codeyam-cli/templates/nextjs-prisma-sqlite/vitest.config.ts +13 -0
  684. package/codeyam-cli/templates/nextjs-prisma-supabase/README.md +52 -0
  685. package/codeyam-cli/templates/nextjs-prisma-supabase/SUPABASE_SETUP.md +104 -0
  686. package/codeyam-cli/templates/nextjs-prisma-supabase/app/api/todos/route.ts +17 -0
  687. package/codeyam-cli/templates/nextjs-prisma-supabase/app/globals.css +26 -0
  688. package/codeyam-cli/templates/nextjs-prisma-supabase/app/layout.tsx +34 -0
  689. package/codeyam-cli/templates/nextjs-prisma-supabase/app/lib/prisma.ts +20 -0
  690. package/codeyam-cli/templates/nextjs-prisma-supabase/app/lib/supabase.ts +12 -0
  691. package/codeyam-cli/templates/nextjs-prisma-supabase/app/page.tsx +10 -0
  692. package/codeyam-cli/templates/nextjs-prisma-supabase/env +9 -0
  693. package/codeyam-cli/templates/nextjs-prisma-supabase/eslint.config.mjs +11 -0
  694. package/codeyam-cli/templates/nextjs-prisma-supabase/gitignore +40 -0
  695. package/codeyam-cli/templates/nextjs-prisma-supabase/next.config.ts +11 -0
  696. package/codeyam-cli/templates/nextjs-prisma-supabase/package.json +37 -0
  697. package/codeyam-cli/templates/nextjs-prisma-supabase/postcss.config.mjs +7 -0
  698. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma/schema.prisma +27 -0
  699. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma/seed.ts +39 -0
  700. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma.config.ts +12 -0
  701. package/codeyam-cli/templates/nextjs-prisma-supabase/tsconfig.json +34 -0
  702. package/codeyam-cli/templates/prompts/conversation-guidance.txt +44 -0
  703. package/codeyam-cli/templates/prompts/conversation-prompt.txt +28 -0
  704. package/codeyam-cli/templates/prompts/interruption-prompt.txt +31 -0
  705. package/codeyam-cli/templates/prompts/stale-rules-prompt.txt +24 -0
  706. package/codeyam-cli/templates/rule-notification-hook.py +44 -17
  707. package/codeyam-cli/templates/rule-reflection-hook.py +25 -5
  708. package/codeyam-cli/templates/rules-instructions.md +34 -88
  709. package/codeyam-cli/templates/seed-adapters/supabase.ts +291 -0
  710. package/codeyam-cli/templates/skills/codeyam-dev-mode/SKILL.md +237 -0
  711. package/codeyam-cli/templates/skills/codeyam-editor/SKILL.md +244 -0
  712. package/codeyam-cli/templates/{codeyam-memory.md → skills/codeyam-memory/SKILL.md} +215 -0
  713. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/deprecated-prompt.md +100 -0
  714. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/detect-deprecated-patterns.mjs +139 -0
  715. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/find-exports.mjs +52 -0
  716. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/misleading-api-prompt.md +117 -0
  717. package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/read-json-field.mjs +61 -0
  718. package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/ripgrep-fallback.mjs +155 -0
  719. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/analyze-prompt.md +46 -0
  720. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/cleanup.mjs +13 -0
  721. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/filter-session.mjs +95 -0
  722. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/preprocess.mjs +160 -0
  723. package/codeyam-cli/templates/{codeyam-new-rule.md → skills/codeyam-new-rule/SKILL.md} +0 -2
  724. package/package.json +23 -15
  725. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +22 -4
  726. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  727. package/packages/ai/src/lib/astScopes/methodSemantics.js +99 -0
  728. package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
  729. package/packages/ai/src/lib/astScopes/nodeToSource.js +16 -0
  730. package/packages/ai/src/lib/astScopes/nodeToSource.js.map +1 -1
  731. package/packages/ai/src/lib/astScopes/paths.js +12 -3
  732. package/packages/ai/src/lib/astScopes/paths.js.map +1 -1
  733. package/packages/ai/src/lib/completionCall.js +10 -7
  734. package/packages/ai/src/lib/completionCall.js.map +1 -1
  735. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +261 -13
  736. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  737. package/packages/ai/src/lib/dataStructure/equivalencyManagers/ParentScopeManager.js +9 -2
  738. package/packages/ai/src/lib/dataStructure/equivalencyManagers/ParentScopeManager.js.map +1 -1
  739. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +14 -4
  740. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  741. package/packages/ai/src/lib/dataStructure/helpers/coercePrimitivesToArraysBySchema.js +54 -0
  742. package/packages/ai/src/lib/dataStructure/helpers/coercePrimitivesToArraysBySchema.js.map +1 -0
  743. package/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.js +34 -0
  744. package/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.js.map +1 -0
  745. package/packages/ai/src/lib/dataStructureChunking.js +9 -5
  746. package/packages/ai/src/lib/dataStructureChunking.js.map +1 -1
  747. package/packages/ai/src/lib/generateEntityScenarioData.js +57 -2
  748. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  749. package/packages/ai/src/lib/generateExecutionFlows.js +81 -11
  750. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -1
  751. package/packages/analyze/index.js +1 -1
  752. package/packages/analyze/index.js.map +1 -1
  753. package/packages/analyze/src/lib/ProjectAnalyzer.js +13 -4
  754. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  755. package/packages/analyze/src/lib/asts/index.js +4 -2
  756. package/packages/analyze/src/lib/asts/index.js.map +1 -1
  757. package/packages/analyze/src/lib/asts/nodes/getNodeType.js +1 -0
  758. package/packages/analyze/src/lib/asts/nodes/getNodeType.js.map +1 -1
  759. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +16 -2
  760. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  761. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +14 -27
  762. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  763. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js +0 -5
  764. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js.map +1 -1
  765. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +12 -2
  766. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
  767. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +9 -7
  768. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
  769. package/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.js +14 -0
  770. package/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.js.map +1 -1
  771. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +44 -11
  772. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
  773. package/packages/analyze/src/lib/files/analyzeChange.js +1 -0
  774. package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
  775. package/packages/analyze/src/lib/files/analyzeInitial.js +1 -0
  776. package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
  777. package/packages/analyze/src/lib/files/analyzeNextRoute.js +5 -1
  778. package/packages/analyze/src/lib/files/analyzeNextRoute.js.map +1 -1
  779. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js +54 -27
  780. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js.map +1 -1
  781. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +185 -28
  782. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  783. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +0 -40
  784. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -1
  785. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +1386 -1197
  786. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  787. package/packages/database/index.js +1 -0
  788. package/packages/database/index.js.map +1 -1
  789. package/packages/database/src/lib/kysely/db.js +5 -0
  790. package/packages/database/src/lib/kysely/db.js.map +1 -1
  791. package/packages/database/src/lib/kysely/tables/editorScenariosTable.js +149 -0
  792. package/packages/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -0
  793. package/packages/database/src/lib/loadAnalysis.js +7 -1
  794. package/packages/database/src/lib/loadAnalysis.js.map +1 -1
  795. package/packages/database/src/lib/loadCommits.js +23 -13
  796. package/packages/database/src/lib/loadCommits.js.map +1 -1
  797. package/packages/database/src/lib/loadEntities.js +0 -6
  798. package/packages/database/src/lib/loadEntities.js.map +1 -1
  799. package/packages/database/src/lib/loadEntity.js +5 -5
  800. package/packages/database/src/lib/loadEntity.js.map +1 -1
  801. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +1 -4
  802. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  803. package/packages/database/src/lib/updateCommitMetadata.js +76 -90
  804. package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
  805. package/packages/database/src/lib/updateFreshAnalysisStatus.js +41 -30
  806. package/packages/database/src/lib/updateFreshAnalysisStatus.js.map +1 -1
  807. package/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.js +68 -57
  808. package/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.js.map +1 -1
  809. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +29 -1
  810. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -1
  811. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +33 -5
  812. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  813. package/packages/types/src/enums/ProjectFramework.js +2 -0
  814. package/packages/types/src/enums/ProjectFramework.js.map +1 -1
  815. package/packages/utils/src/lib/fs/rsyncCopy.js +28 -3
  816. package/packages/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  817. package/scripts/npm-post-install.cjs +34 -0
  818. package/codeyam-cli/src/commands/detect-universal-mocks.js +0 -120
  819. package/codeyam-cli/src/commands/detect-universal-mocks.js.map +0 -1
  820. package/codeyam-cli/src/commands/list.js +0 -31
  821. package/codeyam-cli/src/commands/list.js.map +0 -1
  822. package/codeyam-cli/src/commands/webapp-info.js +0 -146
  823. package/codeyam-cli/src/commands/webapp-info.js.map +0 -1
  824. package/codeyam-cli/src/utils/universal-mocks.js +0 -152
  825. package/codeyam-cli/src/utils/universal-mocks.js.map +0 -1
  826. package/codeyam-cli/src/webserver/build/client/assets/CopyButton-D9i_zSlY.js +0 -1
  827. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeBadge-De5b5pC7.js +0 -1
  828. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-Bclf8Hka.js +0 -34
  829. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-Ce-byqKl.js +0 -25
  830. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-DEMHrl7v.js +0 -3
  831. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-L0DWHa_L.js +0 -1
  832. package/codeyam-cli/src/webserver/build/client/assets/TruncatedFilePath-C7PFQfXy.js +0 -1
  833. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-CPXtdaWm.js +0 -17
  834. package/codeyam-cli/src/webserver/build/client/assets/chunk-JZWAC4HX-BEyX4X6_.js +0 -51
  835. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-DHVDauuc.js +0 -21
  836. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-DcX-ZS3p.js +0 -1
  837. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-B9_ZqelV.js +0 -1
  838. package/codeyam-cli/src/webserver/build/client/assets/entity._sha._-BOPComvD.js +0 -16
  839. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-Cfw__yQa.js +0 -6
  840. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-BIDUUrI3.js +0 -6
  841. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-CYnF5KWN.js +0 -1
  842. package/codeyam-cli/src/webserver/build/client/assets/files-B_dAq2PQ.js +0 -1
  843. package/codeyam-cli/src/webserver/build/client/assets/git-BHPqH3Ch.js +0 -15
  844. package/codeyam-cli/src/webserver/build/client/assets/globals-BJGhRykz.css +0 -1
  845. package/codeyam-cli/src/webserver/build/client/assets/labs-ChoAe3xq.js +0 -1
  846. package/codeyam-cli/src/webserver/build/client/assets/manifest-87493a32.js +0 -1
  847. package/codeyam-cli/src/webserver/build/client/assets/memory-D9eA6kTo.js +0 -78
  848. package/codeyam-cli/src/webserver/build/client/assets/root-C3r0p_7H.js +0 -62
  849. package/codeyam-cli/src/webserver/build/client/assets/settings-KH9TdArD.js +0 -1
  850. package/codeyam-cli/src/webserver/build/client/assets/simulations-D9Fkx0-d.js +0 -1
  851. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-CLPnITMB.js +0 -1
  852. package/codeyam-cli/src/webserver/build/client/assets/useLastLogLine-DmGI38Et.js +0 -2
  853. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-BK0S88PB.js +0 -1
  854. package/codeyam-cli/src/webserver/build/client/assets/useToast-CJ-JqR0l.js +0 -1
  855. package/codeyam-cli/src/webserver/build/server/assets/index-CkkmL6r5.js +0 -1
  856. package/codeyam-cli/src/webserver/build/server/assets/server-build-iBGjHYtO.js +0 -259
  857. package/codeyam-cli/templates/codeyam-stop-hook.sh +0 -284
  858. package/scripts/finalize-analyzer.cjs +0 -13
  859. /package/codeyam-cli/templates/{codeyam-diagnose.md → commands/codeyam-diagnose.md} +0 -0
  860. /package/codeyam-cli/templates/{codeyam-debug.md → skills/codeyam-debug/SKILL.md} +0 -0
  861. /package/codeyam-cli/templates/{codeyam-setup.md → skills/codeyam-setup/SKILL.md} +0 -0
  862. /package/codeyam-cli/templates/{codeyam-sim.md → skills/codeyam-sim/SKILL.md} +0 -0
  863. /package/codeyam-cli/templates/{codeyam-test.md → skills/codeyam-test/SKILL.md} +0 -0
  864. /package/codeyam-cli/templates/{codeyam-verify.md → skills/codeyam-verify/SKILL.md} +0 -0
@@ -0,0 +1,689 @@
1
+ var up=Object.defineProperty;var qi=e=>{throw TypeError(e)};var pp=(e,t,r)=>t in e?up(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ut=(e,t,r)=>pp(e,typeof t!="symbol"?t+"":t,r),hp=(e,t,r)=>t.has(e)||qi("Cannot "+r);var Qi=(e,t,r)=>(hp(e,t,"read from private field"),r?r.call(e):t.get(e)),Zi=(e,t,r)=>t.has(e)?qi("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);import{jsx as n,jsxs as d,Fragment as we}from"react/jsx-runtime";import{PassThrough as mp}from"node:stream";import{createReadableStreamFromReadable as fp}from"@react-router/node";import{ServerRouter as gp,useFetcher as Ke,useLocation as Rr,useNavigate as Rt,Link as Ce,UNSAFE_withComponentProps as et,Meta as yp,Links as xp,ScrollRestoration as bp,Scripts as wp,UNSAFE_withErrorBoundaryProps as vp,useRouteError as Np,isRouteErrorResponse as Ia,useLoaderData as st,useRevalidator as Ut,Outlet as Pc,data as re,useSearchParams as Zn,useRouteLoaderData as jc,useParams as Tc,useActionData as Sp,redirect as Cp}from"react-router";import{isbot as kp}from"isbot";import{renderToPipeableStream as _p}from"react-dom/server";import{useState as P,useEffect as ae,useCallback as ce,createContext as Eo,useContext as Js,useRef as fe,useMemo as ie,forwardRef as Ep,useImperativeHandle as Ap,Component as Pp}from"react";import{Settings as Xi,CheckCircle2 as Ao,Bug as Mc,AlertTriangle as Ps,Check as kt,Copy as $t,Loader2 as Mt,PencilRuler as jp,HomeIcon as Tp,GitCommitIcon as el,File as Mp,RefreshCw as $p,BookOpen as js,FlaskConical as Ip,SettingsIcon as Rp,PanelsTopLeftIcon as Dp,ComponentIcon as Fp,FileText as tl,Code as nl,Box as Op,List as Lp,BarChart3 as Bp,Tag as zp,Image as Pr,Code2 as $c,Activity as Ra,ChevronDown as St,CircleEqual as Yp,ArrowLeft as Wp,Terminal as Ts,Search as Dr,ChevronLeft as Up,ChevronRight as on,Save as Jp,MessageSquare as Hp,Pause as Ic,ListTodo as Vp,PauseCircle as Gp,FileCode as Ms,GripVertical as Kp,Ban as qp,CheckCircle as Qp,FolderOpen as Zp,CodeXml as Xp,Zap as eh,Pencil as th,Trash2 as nh,X as Xn,Folder as Rc,Info as ao,Plus as Po,Eye as rh,FolderTree as sh,ChevronsUpDown as Dc,ChevronsDownUp as Fc}from"lucide-react";import"fetch-retry";import ah from"better-sqlite3";import{Pool as oh}from"pg";import*as V from"fs";import ge,{existsSync as vt,readdirSync as ih,rmSync as Da,readFileSync as rl}from"fs";import*as U from"path";import se,{join as jr}from"path";import{OperationNodeTransformer as lh,sql as pt,Kysely as Oc,ParseJSONResultsPlugin as ch,SqliteDialect as dh,PostgresDialect as uh}from"kysely";import*as ph from"kysely/helpers/sqlite";import*as hh from"kysely/helpers/postgres";import Ze from"typescript";import*as _e from"fs/promises";import Ee,{writeFile as Nr,readFile as oo,mkdir as mh}from"fs/promises";import*as Hs from"os";import io,{homedir as fh}from"os";import gh from"prompts";import $s from"chalk";import*as jo from"crypto";import er,{randomUUID as To,createHmac as yh}from"crypto";import{execSync as Ie,spawn as ft,exec as Mo}from"child_process";import{fileURLToPath as Vs}from"url";import{promisify as $o}from"util";import xh from"dotenv";import bh,{EventEmitter as Fr}from"events";import{v4 as wh}from"uuid";import Io from"http";import Lc from"net";import{WebSocket as Ro}from"ws";import"node-pty";import vh from"openai";import Nh from"p-queue";import sl from"p-retry";import{DynamoDBClient as Gs,PutItemCommand as Sh}from"@aws-sdk/client-dynamodb";import{LRUCache as Do}from"lru-cache";import"pluralize";import"piscina";import Ch from"json5";import{marshall as kh}from"@aws-sdk/util-dynamodb";import _h from"v8";import{Prism as Eh}from"react-syntax-highlighter";import{vscDarkPlus as Ah}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as Ph}from"node:crypto";import{minimatch as lo}from"minimatch";import jh from"react-markdown";import Th from"remark-gfm";import Mh from"react-diff-viewer-continued";const Bc=5e3;function $h(e,t,r,s,a){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let l=!1,c=e.headers.get("user-agent"),p=c&&kp(c)||s.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>m(),Bc+1e3);const{pipe:h,abort:m}=_p(n(gp,{context:s,url:e.url}),{[p](){l=!0;const f=new mp({final(y){clearTimeout(u),u=void 0,y()}}),g=fp(f);r.set("Content-Type","text/html"),h(f),o(new Response(g,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const Ih=Object.freeze(Object.defineProperty({__proto__:null,default:$h,streamTimeout:Bc},Symbol.toStringTag,{value:"Module"})),Rh=2e3,Dh=5e3;function Fh(e){return e.startsWith("/editor")?Dh:Rh}function Oh(e){const{now:t,lastRevalidation:r,throttleMs:s}=e;if(r===0)return"immediate";const a=t-r;return a>=s?"immediate":{action:"deferred",delayMs:s-a}}function Lh({id:e,selected:t,onClick:r,icon:s,name:a}){const[o,i]=P(!1);ae(()=>{i(!0)},[]);const l=ce(()=>{r==null||r(e)},[r,e]);return d("button",{className:`
2
+ w-full px-1.5 py-2 cursor-pointer focus:outline-none
3
+ flex flex-col items-center justify-center gap-1 transition-colors
4
+ ${t?"text-[#CBF3FA]":"text-[#568B94] hover:text-[#CBF3FA]"}
5
+ `,onClick:l,children:[n("div",{className:`${t?"bg-[#CBF3FA] text-[#022A35]":""} w-9 h-9 rounded-lg flex items-center justify-center transition-colors`,children:o&&s}),n("span",{className:`text-[10px] font-normal text-center leading-tight ${t?"text-[#CBF3FA]":""}`,style:t?{color:"#CBF3FA !important"}:void 0,children:a})]})}const Ks="/assets/cy-logo-cli-DoA97ML3.svg";function Bh(e){return e.scenarioName&&e.entityName?`${e.entityName} → "${e.scenarioName}"`:e.entityName?e.entityName:e.scenarioId?`Scenario: ${e.scenarioId.slice(0,8)}...`:e.entitySha?`Entity: ${e.entitySha.slice(0,8)}...`:"General feedback"}function zh({content:e,className:t=""}){const[r,s]=P(!1),a=ce(()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),2e3)}).catch(o=>{console.error("Failed to copy:",o)})},[e]);return n("button",{onClick:a,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?d(we,{children:[n(kt,{size:14}),"Copied"]}):d(we,{children:[n($t,{size:14}),"Copy"]})})}function zc({isOpen:e,onClose:t,context:r,defaultEmail:s="",screenshotDataUrl:a}){const[o,i]=P(""),[l,c]=P(s),[p,u]=P(!1),[h,m]=P(!1),[f,g]=P(null),[y,x]=P(null),b=Ke(),w=b.state!=="idle",v=!!(r.scenarioId||r.analysisId),N=r.analysisId||r.scenarioId||"",S=()=>{const E=`/codeyam-diagnose ${N}`;return o.trim()?`${E} ${o.trim()}`:E};if(b.data&&!h&&!y){const E=b.data;E.success&&E.reportId?(m(!0),g(E.reportId)):E.error&&x(E.error)}const C=async()=>{x(null);const E=new FormData;if(E.append("issueType","other"),E.append("description",o),E.append("email",l),E.append("source",r.source),E.append("entitySha",r.entitySha||""),E.append("scenarioId",r.scenarioId||""),E.append("analysisId",r.analysisId||""),E.append("currentUrl",r.currentUrl),E.append("entityName",r.entityName||""),E.append("entityType",r.entityType||""),E.append("scenarioName",r.scenarioName||""),E.append("errorMessage",r.errorMessage||""),a)try{const D=await(await fetch(a)).blob();E.append("screenshot",D,"screenshot.jpg")}catch(R){console.error("Failed to convert screenshot:",R)}b.submit(E,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},A=()=>{i(""),u(!1),m(!1),g(null),x(null),t()},_=E=>{E.key==="Escape"&&A()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:_,children:d("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl max-h-[90vh] overflow-y-auto",children:[d("div",{className:"flex items-center justify-between mb-6",children:[d("div",{className:"flex items-center gap-3",children:[w?n("div",{className:"animate-spin",children:n(Xi,{size:24,style:{strokeWidth:1.5}})}):h?n(Ao,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(Mc,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:h?"Report Submitted":"Report Issue"})]}),n("button",{onClick:A,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),h?d("div",{children:[d("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[n("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),d("p",{className:"text-xs text-green-700",children:["Report ID:"," ",n("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),n("p",{className:"text-sm text-gray-600 mb-6",children:"The CodeYam team will investigate and may reach out if you provided an email address."}),n("div",{className:"flex justify-end",children:n("button",{onClick:A,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):d("div",{children:[d("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[d("div",{className:"flex items-center justify-between",children:[n("div",{className:"text-sm font-medium text-gray-900",title:`${r.source}${r.entitySha?` • Entity: ${r.entitySha}`:""}${r.scenarioId?` • Scenario: ${r.scenarioId}`:""}${r.analysisId?` • Analysis: ${r.analysisId}`:""}`,children:Bh(r)}),n("button",{type:"button",onClick:()=>u(!p),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:p?"Hide":"Details"})]}),p&&d("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[d("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),d("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&d("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&d("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&d("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),a&&d("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:a,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),d("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:o,onChange:E=>i(E.target.value),placeholder:"Optional: Describe what you expected vs what happened...",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] resize-none"})]}),v&&d(we,{children:[d("div",{className:"mb-4 p-4 bg-purple-50 rounded-lg border border-purple-200",children:[d("div",{className:"flex items-center gap-2 mb-2",children:[n("span",{className:"text-lg",children:"🔧"}),n("h3",{className:"text-sm font-semibold text-purple-900",children:"Diagnose & Fix (Recommended)"})]}),n("p",{className:"text-xs text-purple-700 mb-3",children:"Run this command in Claude Code to investigate the issue locally and potentially fix it. A detailed report will also be uploaded."}),d("div",{className:"relative",children:[n("div",{className:"bg-gray-800 text-gray-50 px-3 py-2.5 pr-20 rounded-md text-xs font-mono overflow-x-auto whitespace-nowrap",children:S()}),n(zh,{content:S(),className:"absolute top-1.5 right-2 px-2 py-1 bg-purple-600 text-white border-none rounded text-[11px] font-medium hover:bg-purple-700 transition-colors"})]})]}),d("div",{className:"relative my-5",children:[n("div",{className:"absolute inset-0 flex items-center",children:n("div",{className:"w-full border-t border-gray-300"})}),n("div",{className:"relative flex justify-center",children:n("span",{className:"bg-white px-3 text-xs text-gray-500 uppercase",children:"or"})})]})]}),d("div",{className:v?"opacity-75":"",children:[v&&d("div",{className:"flex items-center gap-2 mb-3",children:[n("span",{className:"text-lg",children:"📤"}),n("h3",{className:"text-sm font-semibold text-gray-700",children:"Quick Report"}),n("span",{className:"text-xs text-gray-500",children:"(won't investigate locally)"})]}),d("div",{className:"mb-4",children:[n("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),n("input",{id:"email",type:"email",value:l,onChange:E=>c(E.target.value),placeholder:"you@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"})]}),d("div",{className:"mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(Ps,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),d("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),w&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:b.formData?"Uploading report...":"Creating archive..."})}),y&&d("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(Ps,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),d("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:y})]})]}),d("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:A,disabled:w,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors disabled:opacity-50 cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>void C(),disabled:w,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer",children:w?d(we,{children:[n("div",{className:"animate-spin",children:n(Xi,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):y?"Try Again":"Submit Report"})]})]})]})]})}):null}const al={source:"navbar"},Fo=Eo(void 0);function Yh({children:e}){const[t,r]=P(al),s=ce(o=>{r(o)},[]),a=ce(()=>{r(al)},[]);return n(Fo.Provider,{value:{contextData:t,setContextData:s,resetContextData:a},children:e})}function Dt(e){const t=Js(Fo),r=fe(t);ae(()=>{if(r.current)return r.current.setContextData(e),()=>{var s;(s=r.current)==null||s.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId,e.entityName,e.entityType,e.scenarioName,e.errorMessage])}function Wh(){const e=Js(Fo),t=Rr();return e?{source:e.contextData.source,entitySha:e.contextData.entitySha,scenarioId:e.contextData.scenarioId,analysisId:e.contextData.analysisId,currentUrl:t.pathname,entityName:e.contextData.entityName,entityType:e.contextData.entityType,scenarioName:e.contextData.scenarioName,errorMessage:e.contextData.errorMessage}:{source:"navbar",currentUrl:t.pathname}}function Uh({labs:e,isAdmin:t,editorMode:r}){var C;const s=Rr(),a=Rt(),[o,i]=P(),[l,c]=P(!1),[p,u]=P(!1),[h,m]=P(null),f=Ke();ae(()=>{f.state==="idle"&&!f.data&&f.load("/api/generate-report")},[f]);const g=((C=f.data)==null?void 0:C.defaultEmail)||"",y={width:"20px",height:"20px",strokeWidth:1.5},x=(e==null?void 0:e.simulations)??!1,b=[{id:"editor",icon:n(jp,{style:y}),link:"/editor",name:"Editor",hidden:!r,newTab:!0},{id:"dashboard",icon:n(Tp,{style:y}),link:"/",name:"Dashboard",hidden:!x||r},{id:"simulations",icon:d("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:y,children:[n("path",{d:"M9 12.75V15.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 15.75H12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6.75 12.7498L11.325 8.17483C11.6067 7.89873 11.9858 7.7447 12.3803 7.7461C12.7747 7.74751 13.1528 7.90423 13.4325 8.18233L16.5 11.2498",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 8.25C6.82843 8.25 7.5 7.57843 7.5 6.75C7.5 5.92157 6.82843 5.25 6 5.25C5.17157 5.25 4.5 5.92157 4.5 6.75C4.5 7.57843 5.17157 8.25 6 8.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M15 2.25H3C2.17157 2.25 1.5 2.92157 1.5 3.75V11.25C1.5 12.0784 2.17157 12.75 3 12.75H15C15.8284 12.75 16.5 12.0784 16.5 11.25V3.75C16.5 2.92157 15.8284 2.25 15 2.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),link:"/simulations",name:"Simulations",hidden:!x||r},{id:"git",icon:n(el,{style:y}),link:"/git",name:"Git",hidden:!x||r},{id:"files",icon:n(Mp,{style:y}),link:"/files",name:"Files",hidden:!x||r},{id:"activity",icon:n($p,{style:y}),link:"/activity",name:"Activity",hidden:!x||r},{id:"memory",icon:n(js,{style:y}),link:"/memory",name:"Memory"},{id:"labs",icon:n(Ip,{style:y}),link:"/labs",name:"Labs"},{id:"settings",icon:n(Rp,{style:y}),link:"/settings",name:"Settings"},{id:"commits",icon:n(el,{style:y}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(Dp,{style:y}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(Fp,{style:y}),link:"/components",name:"Components",hidden:!0}],w=ce(A=>{const _=b.find(E=>E.id===A);_!=null&&_.link&&(_.newTab?window.open(_.link,"_blank"):a(_.link)),i(E=>E===A?void 0:A)},[b,a]);ae(()=>{const A={editor:["editor"],dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],memory:["memory","agent-transcripts"],files:["files"],labs:["labs"],settings:["settings"],pages:["pages"],components:["components"]};for(const[_,E]of Object.entries(A))if(E.some(R=>R==="/"?s.pathname==="/":s.pathname.includes(R))){i(_);return}i(void 0)},[s]);const v=async()=>{u(!0);try{const{default:A}=await import("html2canvas-pro"),E=(await A(document.body)).toDataURL("image/jpeg",.8);m(E),c(!0)}catch(A){console.error("Screenshot capture failed:",A),c(!0)}finally{u(!1)}},N=()=>{c(!1),m(null)},S=Wh();return d(we,{children:[d("div",{id:"sidebar",className:"sticky top-0 w-full h-screen bg-[#051C22] flex flex-col justify-between py-3",children:[d("div",{className:"w-full flex flex-col items-center",children:[n("div",{className:"py-3 mt-2 mb-4",children:n(Ce,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:Ks,alt:"CodeYam",className:"h-6"})})}),b.filter(A=>!A.hidden).map(A=>n(Lh,{id:A.id,selected:A.id===o,onClick:w,icon:A.icon,name:A.name},`sidebar-button-${A.id}`))]}),t&&n("div",{className:"w-full flex flex-col items-center pb-2",children:d("button",{onClick:()=>void v(),disabled:p,className:"w-full px-1.5 py-2 flex flex-col items-center justify-center gap-1 text-[#568B94] hover:text-[#CBF3FA] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait",children:[n("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center",children:p?n(Mt,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n(Mc,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:p?"Capturing...":`Report
6
+ Bug`})]})})]}),l&&n(zc,{isOpen:!0,onClose:N,context:S,defaultEmail:g,screenshotDataUrl:h??void 0})]})}const Yc=Eo(void 0);function Jh({children:e}){const[t,r]=P([]),s=ce((o,i="info",l=5e3)=>{const p={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:l};r(u=>[...u,p])},[]),a=ce(o=>{r(i=>i.filter(l=>l.id!==o))},[]);return n(Yc.Provider,{value:{toasts:t,showToast:s,closeToast:a},children:e})}function Oo(){const e=Js(Yc);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Hh({toast:e,onClose:t}){ae(()=>{const a=e.duration||5e3;if(a>0){const o=setTimeout(()=>{t(e.id)},a);return()=>clearTimeout(o)}},[e.id,e.duration,t]);const r={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return d("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg min-w-[320px] max-w-[500px] animate-[slideIn_0.3s_ease-out] ${{success:"bg-emerald-50 border-emerald-200 text-emerald-900",error:"bg-red-50 border-red-200 text-red-900",info:"bg-blue-50 border-blue-200 text-blue-900",warning:"bg-amber-50 border-amber-200 text-amber-900"}[e.type]}`,children:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function Vh({toasts:e,onClose:t}){return e.length===0?null:d("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
7
+ @keyframes slideIn {
8
+ from {
9
+ transform: translateX(400px);
10
+ opacity: 0;
11
+ }
12
+ to {
13
+ transform: translateX(0);
14
+ opacity: 1;
15
+ }
16
+ }
17
+ `}),e.map(r=>n(Hh,{toast:r,onClose:t},r.id))]})}function Jt(e,t){const[r,s]=P(""),[a,o]=P(!1),[i,l]=P(null),[c,p]=P(null),[u,h]=P(!1);ae(()=>{t&&(h(!1),o(!1),l(null),p(null))},[t]),ae(()=>{if(!e||!t){t||s("");return}const f=async()=>{if(!u)try{const y=await fetch(`/api/logs/${e}`);if(y.ok){const b=(await y.text()).trim().split(`
18
+ `).filter(S=>S.length>0);if(b.length<3){o(!1),h(!1),l(null),p(null),s("");return}const w=b.filter(S=>S.includes("CodeYam Log Level 1"));if(w.length>0){const S=w[w.length-1];s(S.replace(/.*CodeYam Log Level 1: /,""))}const v=b.find(S=>S.includes("$$INTERACTIVE_SERVER_URL$$:"));if(v){const S=v.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();l(S),h(!0)}const N=b.find(S=>S.includes("$$INTERACTIVE_SCENARIO_URLS$$:"));if(N)try{const S=N.split("$$INTERACTIVE_SCENARIO_URLS$$:")[1].trim();p(JSON.parse(S))}catch{}b.some(S=>S.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};f().catch(()=>{});const g=setInterval(()=>{f().catch(()=>{})},500);return()=>clearInterval(g)},[e,t,u]);const m=ce(()=>{s(""),o(!1),l(null),p(null),h(!1)},[]);return{lastLine:r,interactiveUrl:i,scenarioUrlMap:c,isCompleted:a,resetLogs:m}}function rn({projectSlug:e,onClose:t}){const[r,s]=P("Loading logs..."),[a,o]=P(!0),[i,l]=P(!0),[c,p]=P("all"),u=fe(null);return ae(()=>{const h=async()=>{try{const m=await fetch(`/api/logs/${e}`);if(m.ok){const f=await m.text();if(c==="all")s(f);else{const g=f.trim().split(`
19
+ `).filter(y=>{if(y.length===0)return!1;const x=y.match(/^.*CodeYam Log Level (\d+):/);return!!x&&Number(x[1])<=c});s(g.map(y=>y.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
20
+ `))}i&&u.current&&setTimeout(()=>{var g;(g=u.current)==null||g.scrollTo({top:u.current.scrollHeight,behavior:"smooth"})},100)}else s(`Error: ${m.status} - ${await m.text()}`)}catch(m){s(`Error fetching logs: ${m.message}`)}};if(h().catch(()=>{}),a){const m=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(m)}},[e,a,i,c]),ae(()=>{const h=m=>{m.key==="Escape"&&t()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:d("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:h=>h.stopPropagation(),children:[d("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[d("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),d("div",{className:"flex items-center gap-4",children:[d("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),d("select",{value:c,onChange:h=>p(h.target.value==="all"?"all":Number(h.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),d("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:a,onChange:h=>o(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),d("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:h=>l(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:u,children:r})]})})}function ht({type:e,size:t="default"}){const r={visual:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},library:{iconColor:"#06b6d5",bgColor:"bg-[#e6fbff]",bgHex:"#e6fbff"},type:{iconColor:"#db2627",bgColor:"bg-[#ffe1e1]",bgHex:"#ffe1e1"},data:{iconColor:"#2563eb",bgColor:"bg-blue-100",bgHex:"#dbeafe"},index:{iconColor:"#ea580c",bgColor:"bg-orange-100",bgHex:"#ffedd5"},functionCall:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},class:{iconColor:"#059669",bgColor:"bg-emerald-100",bgHex:"#d1fae5"},method:{iconColor:"#0891b2",bgColor:"bg-cyan-100",bgHex:"#cffafe"},other:{iconColor:"#6b7280",bgColor:"bg-gray-100",bgHex:"#f3f4f6"}},s=r[e]||r.other,a=t==="large"?18:14,o=t==="large"?32:18,i=()=>{switch(e){case"library":return n($c,{size:a,color:s.iconColor});case"visual":return n(Pr,{size:a,color:s.iconColor});case"type":return n(zp,{size:a,color:s.iconColor});case"data":return n(Bp,{size:a,color:s.iconColor});case"index":return n(Lp,{size:a,color:s.iconColor});case"functionCall":return n(nl,{size:a,color:s.iconColor});case"class":return n(Op,{size:a,color:s.iconColor});case"method":return n(nl,{size:a,color:s.iconColor});case"other":return n(tl,{size:a,color:s.iconColor});default:return n(tl,{size:a,color:s.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${s.bgColor}`,style:{width:`${o}px`,height:`${o}px`},children:i()})}function Wc({filePath:e,maxLength:t=60,className:r,style:s}){const o=((l,c)=>{if(l.length<=c)return l;const p="...",u=c-p.length,h=Math.ceil(u*.4),m=Math.floor(u*.6),f=l.slice(0,h),g=l.slice(-m),y=f.lastIndexOf("/"),x=g.indexOf("/"),b=y>h*.5?f.slice(0,y+1):f,w=x!==-1&&x<m*.5?g.slice(x):g;return`${b}${p}${w}`})(e,t),i=o!==e;return n("span",{className:r||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...s,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:o})}function Fa({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:s=50,showScenarioCount:a=!1,scenarioCount:o=0,additionalContent:i}){return d("div",{className:"flex flex-col gap-1",children:[d("div",{className:"flex items-center gap-1",children:[n(ht,{type:e.entityType||"other"}),d(Ce,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:t,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,a&&o>0&&` (${o})`]}),n(Wc,{filePath:e.filePath,maxLength:s,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const Oa={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function Gh({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:s=!1,queuedJobCount:a=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:l=[]}){var q,O,W;const[c,p]=P(!1),[u,h]=P(!1),[m,f]=P(null),[g,y]=P(new Set),[x,b]=P(new Set),[w,v]=P(!1),N=!!i||o.length>0,S=!!i,C=(i==null?void 0:i.entities)||r,A=!!(e!=null&&e.analysisCompletedAt),_=(e==null?void 0:e.readyToBeCaptured)??0,E=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||A&&(_===0||E>=_);const R=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,D=N,{lastLine:T}=Jt(t,D),$=S||o.length>0,L=new Set(((q=i==null?void 0:i.entities)==null?void 0:q.map(I=>I.sha))||[]),B=l.filter(I=>!(I.currentEntityShas||[]).some(k=>L.has(k))),H=(()=>{const j=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&R){const k=e.analysisCompletedAt||e.createdAt;if(new Date(k).getTime()>j)return!0}if(B.length>0){const k=B[0],Y=k.analysisCompletedAt||k.archivedAt||k.createdAt;if(Y&&new Date(Y).getTime()>j)return!0}return!1})();return ae(()=>{const I=(i==null?void 0:i.id)||null;N&&!u&&I!==m&&h(!0),!N&&m!==null&&f(null)},[N,i==null?void 0:i.id,u,m]),d(we,{children:[d("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${u?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!u&&d("div",{onClick:()=>{h(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[$?n(Mt,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(Ra,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:$?"Analyzing...":"Activity: No Activity Yet"}),$&&n("button",{onClick:I=>{I.stopPropagation(),p(!0)},className:"ml-auto px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),u&&d("div",{children:[d("div",{className:"flex items-center justify-between px-3 py-2",children:[d("div",{className:"flex items-center gap-2",children:[$?n(Mt,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(Ra,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:$?"Analyzing...":"Activity"})]}),d("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>p(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{h(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:n(St,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),d("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[$&&i&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Ra,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Current Activity"})]}),n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:C.length>0?d("div",{className:"space-y-1.5",children:[(w?C:C.slice(0,3)).map(I=>n(Fa,{entity:I,nameSize:"11px",pathSize:"10px",pathMaxLength:150},I.sha)),C.length>3&&n("button",{onClick:()=>v(I=>!I),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Oa,"aria-label":w?"Show fewer entities":`Show ${C.length-3} more entities`,children:w?"Show less":`+${C.length-3} more`}),T&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:T})]}):d("div",{children:[i.entityNames&&i.entityNames.length>0?d("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((I,j)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:I},j)),i.entityNames.length>5&&d("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):d("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((O=i.entityShas)==null?void 0:O.length)||0," ",((W=i.entityShas)==null?void 0:W.length)===1?"entity":"entities","..."]}),T&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:T})]})})]}),o.length>0&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Yp,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Queued Activity"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:o.map(I=>{var Y,G;const j=g.has(I.id),k=j?I.entities:I.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:I.entities.length>0?d("div",{className:"space-y-1.5",children:[k.map(Q=>n(Fa,{entity:Q,nameSize:"10px",pathSize:"9px",pathMaxLength:120},Q.sha)),I.entities.length>3&&n("button",{onClick:()=>{y(Q=>{const K=new Set(Q);return K.has(I.id)?K.delete(I.id):K.add(I.id),K})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Oa,"aria-label":j?"Show fewer entities":`Show ${I.entities.length-3} more entities`,children:j?"Show less":`+${I.entities.length-3} more`})]}):d("div",{style:{fontSize:"10px",color:"#343434"},children:[I.type==="analysis"&&n(we,{children:I.entityNames&&I.entityNames.length>0?d("div",{className:"space-y-0.5",children:[I.entityNames.slice(0,5).map((Q,K)=>n("div",{children:Q},K)),I.entityNames.length>5&&d("div",{className:"italic",children:["+",I.entityNames.length-5," more"]})]}):`Analyzing ${((Y=I.entityShas)==null?void 0:Y.length)||0} ${((G=I.entityShas)==null?void 0:G.length)===1?"entity":"entities"}`}),I.type==="recapture"&&"Recapturing scenario",I.type==="debug-setup"&&"Setting up debug environment"]})},I.id)})})]}),H&&B.length>0&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Ao,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Recently Completed"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:B.slice(0,3).map((I,j)=>{const k=I.entities||[],Y=I.analysisCompletedAt||I.archivedAt||I.createdAt||"",G=(()=>{if(!Y)return"";const M=Date.now()-new Date(Y).getTime(),z=Math.floor(M/6e4),J=Math.floor(M/36e5);return J>0?`${J}h ago`:z>0?`${z}m ago`:"just now"})(),Q=x.has(j),F=(Q?k:k.slice(0,3)).map(M=>{var z,J,te;return{...M,scenarioCount:((te=(J=(z=M.analyses)==null?void 0:z[0])==null?void 0:J.scenarios)==null?void 0:te.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:k.length>0&&d("div",{className:"space-y-1.5",children:[F.map((M,z)=>d("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(Fa,{entity:M,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:M.scenarioCount})}),z===0&&G&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:G})]},M.sha)),k.length>3&&n("button",{onClick:()=>{b(M=>{const z=new Set(M);return z.has(j)?z.delete(j):z.add(j),z})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Oa,"aria-label":Q?"Show fewer entities":`Show ${k.length-3} more entities`,children:Q?"Show less":`+${k.length-3} more`})]})},j)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(Ce,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),c&&t&&n(rn,{projectSlug:t,onClose:()=>p(!1)})]})}function gt(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function Or(e){const{file_id:t,project_id:r,commit_id:s,file_path:a,entity_type:o,entity_branches:i,analyses:l,commit:c,created_at:p,updated_at:u,...h}=e,m=(i??[]).map(y=>y.branch_id),f=l?l.map(Ht):void 0,g=c?Sn(c):void 0;return gt({...h,fileId:t,projectId:r,commitId:s,filePath:a,entityType:o,commit:g,analyses:f,branchIds:m,createdAt:p,updatedAt:u})}function Lo(e){return gt({id:e.id,projectId:e.project_id,name:e.name,path:e.path,deleted:!!e.deleted,metadata:e.metadata??void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0})}function qs(e){const{branches:t,files:r,analyzed_at:s,content_changed_at:a,created_at:o,updated_at:i,github_token:l,configuration:c,team_id:p,...u}=e;return gt({...u,branches:t?t.map(Cn):void 0,files:r?r.map(Lo):void 0,analyzedAt:s,contentChangedAt:a,createdAt:o,updatedAt:i})}function Kh(e){const{id:t,project_id:r,user_id:s,scenario_id:a,thumbs_up:o,user:i}=e,l=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return gt({id:t,projectId:r,userId:s,scenarioId:a,thumbsUp:!!o,user:l})}function qh(e){const{id:t,project_id:r,user_id:s,scenario_id:a,text:o,created_at:i,updated_at:l,user:c}=e,p=c?{username:c.github_username,avatarUrl:c.github_user.avatar_url}:void 0;return gt({id:t,projectId:r,userId:s,scenarioId:a,text:o,createdAt:i,updatedAt:l,user:p})}function Uc(e){const{project_id:t,analysis_id:r,previous_version_id:s,analysis:a,user_scenarios:o,scenario_comments:i,approved:l,...c}=e,p=a?Ht(a):void 0,u=o?o.map(Kh):void 0,h=i?i.map(qh):void 0;return gt({...c,projectId:t,analysisId:r,previousVersionId:s,analysis:p,userScenarios:u,comments:h})}function Qh(e){return gt({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?Ht(e.analysis):void 0,entity:e.entity?Or(e.entity):void 0,branch:e.branch?Cn(e.branch):void 0,createdAt:e.created_at})}function Ht(e){const{project_id:t,commit_id:r,file_id:s,file_path:a,entity_sha:o,entity_type:i,entity_name:l,previous_analysis_id:c,file:p,entity:u,commit:h,project:m,scenarios:f,analysis_branches:g,dependency_analyzed_tree_sha:y,analyzed_tree_sha:x,branch_commit_sha:b,committed_at:w,completed_at:v,created_at:N,updated_at:S,indirect:C,...A}=e,_=u?Or(u):void 0,E=p?Lo(p):void 0,R=m?qs(m):void 0,D=h?Sn(h):void 0,T=f?f.map(Uc):void 0,$=g?g.map(Qh):void 0,L=$?$.map(B=>B.branch):void 0;return gt({...A,projectId:t,commitId:r,fileId:s,filePath:a,entitySha:o,entityType:i,entityName:l,previousAnalysisId:c,entity:_,file:E,commit:D,project:R,scenarios:T,analysisBranches:$,branches:L,dependencyAnalyzedTreeSha:y,analyzedTreeSha:x,branchCommitSha:b,committedAt:w,completedAt:v,createdAt:N,updatedAt:S,indirect:!!C})}function Bo(e){return gt({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?Sn(e.commit):void 0,branch:e.branch?Cn(e.branch):void 0})}function Zh(e){const{project_id:t,commit_id:r,created_at:s,updated_at:a,success:o,...i}=e;return gt({...i,projectId:t,commitId:r,createdAt:s,updatedAt:a,success:!!o})}function Sn(e){const{project_id:t,branch_id:r,branch:s,background_jobs:a,merged_branch_id:o,mergedBranch:i,ai_message:l,html_url:c,author:p,analyses:u,entities:h,commit_branches:m,committed_at:f,analyzed_at:g,...y}=e,x=s?Cn(s):void 0,b=i?Cn(i):void 0,w=(a==null?void 0:a.length)>0?Zh(a[a.length-1]):void 0,v=(u??[]).map(Ht),N=(h??[]).map(Or),S=(m==null?void 0:m.length)>0?m.map(Bo):void 0;return p&&(p.username=p.preferredUsername??p.username),gt({...y,projectId:t,branchId:r,branch:x,backgroundJob:w,mergedBranchId:o,mergedBranch:b,aiMessage:l,htmlUrl:c,author:p,analyses:v,entities:N,commitBranches:S,committedAt:f,analyzedAt:g})}function Cn(e){const{project_id:t,content_changed_at:r,commits:s,analysis_branches:a,active_at:o,created_at:i,updated_at:l,primary:c,...p}=e,u=s?s.map(Sn):void 0,h=a?a.flatMap(m=>Ht(m.analysis)):void 0;return gt({...p,projectId:t,contentChangedAt:r,commits:u,analyses:h,activeAt:o,createdAt:i,updatedAt:l,primary:!!c})}var Ws;class Xh{constructor(){Zi(this,Ws,new em)}transformQuery(t){return Qi(this,Ws).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}Ws=new WeakMap;class em extends lh{transformValue(t){return{...super.transformValue(t),value:typeof t.value=="boolean"?t.value?1:0:t.value}}transformPrimitiveValueList(t){return{...t,values:t.values.map(r=>typeof r=="boolean"?r?1:0:r)}}}const be=()=>null;function ze(e=!1){return t=>(t=t.defaultTo(pt`CURRENT_TIMESTAMP`),e&&(t=t.notNull()),t)}const tm={analyzed_at:be(),configuration:be(),content_changed_at:be(),created_at:be(),description:be(),github_token:be(),id:be(),metadata:be(),name:be(),path:be(),slug:be(),team_id:be(),updated_at:be()},nm=Object.keys(tm);async function rm(e){await e.schema.createTable("projects").addColumn("id","uuid",t=>t.primaryKey()).addColumn("name","text").addColumn("slug","text",t=>t.notNull()).addColumn("github_token","text").addColumn("description","text").addColumn("path","text").addColumn("configuration","text").addColumn("metadata","text").addColumn("content_changed_at","datetime").addColumn("analyzed_at","datetime").addColumn("created_at","datetime",ze(!0)).addColumn("updated_at","datetime",ze()).addColumn("team_id","integer").ifNotExists().execute()}async function sm(e){await e.schema.createTable("analyses").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("file_id","uuid").addColumn("commit_id","uuid").addColumn("entity_sha","varchar").addColumn("entity_name","varchar").addColumn("status","text").addColumn("metadata","text").addColumn("created_at","datetime",ze(!0)).addColumn("updated_at","datetime",ze(!0)).addColumn("tree_sha","text").addColumn("analyzed_tree_sha","text").addColumn("dependency_analyzed_tree_sha","text").addColumn("previous_analysis_id","uuid").addColumn("branch_commit_sha","varchar").addColumn("indirect","boolean").addColumn("committed_at","datetime").addColumn("completed_at","datetime").addColumn("file_path","varchar").addColumn("entity_type","varchar").ifNotExists().execute()}const am={active:be(),analysis_id:be(),branch_id:be(),created_at:be(),entity_sha:be(),id:be()},om=Object.keys(am);async function im(e){await e.schema.createTable("analysis_branches").addColumn("id","uuid",t=>t.primaryKey()).addColumn("analysis_id","uuid",t=>t.notNull()).addColumn("branch_id","uuid",t=>t.notNull()).addColumn("entity_sha","varchar",t=>t.notNull()).addColumn("active","boolean",t=>t.defaultTo(!0)).addColumn("created_at","datetime",ze()).ifNotExists().execute()}async function lm(e){await e.schema.createTable("background_jobs").addColumn("commit_id","uuid",t=>t.notNull()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("progress","text").addColumn("success","boolean").addColumn("created_at","datetime",ze(!0)).addColumn("updated_at","datetime").addPrimaryKeyConstraint("background_jobs_pkey",["project_id","commit_id"]).ifNotExists().execute()}const cm={active_at:be(),content_changed_at:be(),created_at:be(),id:be(),metadata:be(),name:be(),primary:be(),project_id:be(),ref:be(),sha:be(),updated_at:be()},Jc=Object.keys(cm);async function dm(e){await e.schema.createTable("branches").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("ref","text").addColumn("name","text").addColumn("sha","text").addColumn("primary","boolean",t=>t.notNull().defaultTo(!1)).addColumn("metadata","text").addColumn("content_changed_at","datetime",ze()).addColumn("active_at","datetime").addColumn("created_at","datetime",ze(!0)).addColumn("updated_at","datetime",ze()).ifNotExists().execute()}async function um(e){await e.schema.createTable("commit_branches").addColumn("id","uuid",t=>t.primaryKey()).addColumn("branch_id","uuid").addColumn("commit_id","uuid").addColumn("active","boolean").addColumn("created_at","datetime",ze(!0)).ifNotExists().execute()}const pm={ai_message:be(),analyzed_at:be(),author_github_username:be(),branch_id:be(),committed_at:be(),created_at:be(),files:be(),html_url:be(),id:be(),merged_branch_id:be(),message:be(),metadata:be(),project_id:be(),sha:be(),title:be(),url:be()},Hc=Object.keys(pm),hm=Hc.filter(e=>e!=="files");async function mm(e){await e.schema.createTable("commits").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("branch_id","uuid").addColumn("merged_branch_id","uuid").addColumn("message","text").addColumn("ai_message","text").addColumn("title","varchar").addColumn("author_github_username","varchar").addColumn("url","varchar").addColumn("html_url","varchar").addColumn("sha","varchar",t=>t.notNull()).addColumn("files","text").addColumn("metadata","text").addColumn("committed_at","datetime").addColumn("analyzed_at","datetime").addColumn("created_at","datetime",ze(!0)).ifNotExists().execute()}async function fm(e){await e.schema.createTable("debug_reports").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_slug","varchar",t=>t.notNull()).addColumn("s3_key","varchar",t=>t.notNull()).addColumn("file_size_bytes","bigint").addColumn("metadata","text").addColumn("status","varchar").addColumn("created_at","datetime",ze(!0)).addColumn("uploaded_at","datetime").addColumn("base_sha","varchar").addColumn("delta_size_bytes","bigint").ifNotExists().execute()}async function gm(e){await e.schema.createTable("labs_requests").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_slug","varchar",t=>t.notNull().unique()).addColumn("name","varchar",t=>t.notNull()).addColumn("email","varchar",t=>t.notNull()).addColumn("org_name","varchar").addColumn("org_size","varchar").addColumn("project_size","varchar").addColumn("tech_stack","varchar").addColumn("status","varchar").addColumn("unlock_code","varchar").addColumn("created_at","datetime",ze(!0)).addColumn("approved_at","datetime").ifNotExists().execute()}const ym={commit_id:be(),created_at:be(),description:be(),documentation:be(),entity_type:be(),file_id:be(),file_path:be(),metadata:be(),name:be(),project_id:be(),quality:be(),sha:be(),updated_at:be()},Vc=Object.keys(ym);async function xm(e){await e.schema.createTable("entities").addColumn("project_id","uuid",t=>t.notNull()).addColumn("file_id","uuid").addColumn("commit_id","uuid").addColumn("name","varchar").addColumn("sha","varchar",t=>t.primaryKey()).addColumn("entity_type","varchar").addColumn("file_path","varchar").addColumn("description","text").addColumn("documentation","text").addColumn("metadata","text").addColumn("quality","text").addColumn("created_at","datetime",ze(!0)).addColumn("updated_at","datetime").ifNotExists().execute()}const bm={active:be(),branch_id:be(),entity_sha:be()},wm=Object.keys(bm);async function vm(e){await e.schema.createTable("entity_branches").addColumn("branch_id","uuid",t=>t.notNull()).addColumn("entity_sha","varchar",t=>t.notNull()).addColumn("active","boolean",t=>t.defaultTo(!0)).addPrimaryKeyConstraint("entity_branches_pkey",["branch_id","entity_sha"]).ifNotExists().execute()}async function Nm(e){await e.schema.createTable("entity_statements").addColumn("id","integer",t=>t.autoIncrement().primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("entity_sha","varchar",t=>t.notNull()).addColumn("statement_sha","varchar",t=>t.notNull()).addColumn("created_at","datetime",ze(!0)).ifNotExists().execute()}const Sm={created_at:be(),deleted:be(),id:be(),metadata:be(),name:be(),path:be(),project_id:be(),updated_at:be()},Cm=Object.keys(Sm);async function km(e){await e.schema.createTable("files").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("name","varchar").addColumn("path","varchar",t=>t.notNull()).addColumn("deleted","boolean",t=>t.defaultTo(!1)).addColumn("created_at","datetime",ze(!0)).addColumn("updated_at","datetime",ze()).addColumn("metadata","text").ifNotExists().execute()}async function _m(e){await e.schema.createTable("github_payloads").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("payload_type","varchar").addColumn("payload","text").addColumn("after","varchar").addColumn("commit_sha","varchar").addColumn("ref","varchar").addColumn("committed_at","datetime").addColumn("error","text").addColumn("created_at","datetime",ze(!0)).ifNotExists().execute()}async function Em(e){await e.schema.createTable("github_users").addColumn("username","varchar",t=>t.primaryKey()).addColumn("preferred_username","varchar").addColumn("avatar_url","varchar").addColumn("created_at","datetime",ze(!0)).addColumn("updated_at","datetime",ze()).ifNotExists().execute()}async function Am(e){await e.schema.createTable("scenario_comments").addColumn("id","serial",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("scenario_id","uuid").addColumn("user_id","uuid").addColumn("text","text").addColumn("metadata","text").addColumn("created_at","datetime",ze(!0)).addColumn("updated_at","datetime",ze(!0)).ifNotExists().execute()}async function Pm(e){await e.schema.createTable("editor_scenarios").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("name","varchar",t=>t.notNull()).addColumn("description","text").addColumn("component_name","varchar").addColumn("component_path","varchar").addColumn("url","varchar").addColumn("type","varchar").addColumn("screenshot_path","varchar").addColumn("created_at","datetime",ze(!0)).addColumn("updated_at","datetime",ze(!0)).ifNotExists().execute();for(const t of["component_name","component_path","url","type","screenshot_path"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"varchar").execute()}catch{}for(const t of["viewport_width","viewport_height"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"integer").execute()}catch{}for(const t of["dimensions","screenshot_paths"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"text").execute()}catch{}for(const t of["page_file_path","entity_sha","display_name"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"varchar").execute()}catch{}try{const t=await e.selectFrom("editor_scenarios").select(["id","dimension","dimensions"]).execute();for(const r of t){const s=r;s.dimension&&!s.dimensions&&await e.updateTable("editor_scenarios").set({dimensions:JSON.stringify([s.dimension])}).where("id","=",s.id).execute()}}catch{}try{const t=await e.selectFrom("editor_scenarios").select(["id","screenshot_path","screenshot_paths","dimensions"]).execute();for(const r of t){const s=r;if(s.screenshot_path&&!s.screenshot_paths){let a="Default";try{const o=s.dimensions?JSON.parse(s.dimensions):null;Array.isArray(o)&&o.length>0&&(a=o[0])}catch{}await e.updateTable("editor_scenarios").set({screenshot_paths:JSON.stringify({[a]:s.screenshot_path})}).where("id","=",s.id).execute()}}}catch{}}const jm={analysis_id:be(),approved:be(),created_at:be(),description:be(),id:be(),metadata:be(),name:be(),previous_version_id:be(),project_id:be()},Is=Object.keys(jm);async function Tm(e){await e.schema.createTable("scenarios").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("analysis_id","uuid").addColumn("name","varchar").addColumn("description","text").addColumn("metadata","text").addColumn("approved","boolean").addColumn("previous_version_id","uuid").addColumn("created_at","datetime",ze(!0)).ifNotExists().execute()}async function Mm(e){await e.schema.createTable("statements").addColumn("sha","varchar",t=>t.primaryKey()).addColumn("text","text",t=>t.notNull()).addColumn("llm_call_id","varchar").addColumn("results","text").addColumn("issues","text").addColumn("created_at","datetime",ze(!0)).ifNotExists().execute()}async function $m(e){await e.schema.createTable("teams").addColumn("id","serial",t=>t.primaryKey()).addColumn("name","varchar",t=>t.notNull()).addColumn("created_at","datetime",ze(!0)).ifNotExists().execute()}async function Im(e){await e.schema.createTable("user_scenarios").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("scenario_id","uuid",t=>t.notNull()).addColumn("user_id","uuid",t=>t.notNull()).addColumn("thumbs_up","boolean",t=>t.defaultTo(!1)).addColumn("created_at","datetime",ze(!0)).ifNotExists().execute()}async function Rm(e){await e.schema.createTable("user_teams").addColumn("team_id","integer",t=>t.notNull()).addColumn("user_auth_id","uuid",t=>t.notNull()).addPrimaryKeyConstraint("user_teams_pkey",["team_id","user_auth_id"]).ifNotExists().execute()}async function Dm(e){await e.schema.createTable("users").addColumn("auth_id","uuid",t=>t.primaryKey()).addColumn("email","varchar").addColumn("github_username","varchar").addColumn("github_token","varchar").addColumn("verified","boolean",t=>t.defaultTo(!1)).addColumn("created_at","datetime",ze(!0)).addColumn("updated_at","datetime",ze()).ifNotExists().execute()}const Fm=!!kn("ENABLE_QUERY_LOGGING"),Om=!!kn("ENABLE_QUERY_ERROR_LOGGING");kn("USE_LOCAL_POSTGRESQL_FOR_TESTING");let is;function Pe(){if(!is){const e=Kc();if(e==="sqlite")is=Lm();else if(e==="postgresql")is=Bm();else throw new Error(`Unknown database type: ${e}`)}return is}function Lm(e){if(e||(e=kn("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=V.existsSync(e),r=U.dirname(e);if(!V.existsSync(r))V.mkdirSync(r,{recursive:!0,mode:493});else try{V.chmodSync(r,493)}catch(a){console.warn(`Warning: Could not set permissions on database directory: ${a.message}`)}const s=new ah(e,{readonly:!1,fileMustExist:!1});if(s.pragma("journal_mode = WAL"),s.pragma("busy_timeout = 5000"),s.pragma("synchronous = FULL"),!process.env.CLAUDE_CODE_MODE)try{const a=s.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();t&&a.count===0&&(console.error("CodeYam DB ERROR: Database file existed but projects table is missing!"),console.error("This likely means SQLite created a new empty database instead of opening the existing one."),console.error("Possible causes: corruption, WAL file issues, or file locking problems."))}catch(a){console.error("CodeYam DB ERROR: Failed to verify database schema:",a)}return new Oc({dialect:new dh({database:s}),plugins:[new ch,new Xh],log:Gc})}function Bm(){const e=Ym();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new oh({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,s)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new Oc({dialect:new uh({pool:t}),log:Gc})}let La=null;function An(){return La||(La=zm(Kc())),La}function Gc(e){e.level==="error"?Om&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):Fm&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function zm(e){if(e==="sqlite")return ph;if(e==="postgresql")return hh;throw new Error(`Unknown database type: ${e}`)}function Kc(){if(kn("SQLITE_PATH"))return"sqlite";if(kn("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}async function ik(e){await rm(e),await sm(e),await im(e),await lm(e),await dm(e),await um(e),await mm(e),await fm(e),await Pm(e),await xm(e),await vm(e),await Nm(e),await km(e),await _m(e),await Em(e),await gm(e),await Am(e),await Tm(e),await Mm(e),await $m(e),await Im(e),await Rm(e),await Dm(e)}function Ym(){const e=kn("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function kn(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}const Wm=()=>crypto.randomUUID();function Um(e){const{id:t,projectId:r,activeAt:s,contentChangedAt:a,metadata:o,...i}=e;return delete i.commits,delete i.files,delete i.analyses,delete i.createdAt,delete i.updatedAt,{...i,id:t??Wm(),project_id:r,active_at:s,content_changed_at:a,metadata:o?JSON.stringify(o):null}}var nt=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Vite="Vite",e.Expo="Expo",e.Unknown="Unknown",e))(nt||{});const Qs="Default Scenario";let Jm="<main>";function Hm(){return Jm}function ol(e,...t){Fe(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function Fe(...e){const t=Hm(),r=e.map(a=>{if(a)return typeof a=="string"?a:a instanceof Error?`${a.name}: ${a.message}
21
+ ${a.stack}`:typeof a=="object"?Vm(a):String(a)}).filter(Boolean).join(`
22
+ `),s=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(s+`
23
+ `);return}console.log(s.replace(/\n/g,"\r"))}function Vm(e,t=2){function r(s,a=new WeakMap){return s===null||typeof s!="object"?s:a.has(s)?`"[Circular: ${s.constructor.name}]"`:(a.set(s,!0),Array.isArray(s)?`[${s.map(l=>{const c=r(l,a);return typeof l=="string"?`"${c}"`:c}).join(",")}]`:`{${Object.entries(s).map(([i,l])=>{let c;return typeof l>"u"?null:(typeof l=="function"?c=`"(function: ${l.name||"anonymous"})"`:l instanceof Date?c=`"${l.toISOString()}"`:typeof l=="object"&&l!==null?c=r(l,a):typeof l=="string"?c=`"${l.replace(/"/g,'\\"')}"`:c=JSON.stringify(l),`"${i.replace(/"/g,'\\"')}":${c}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(s){const a=r(e);if(!t)return a;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(o){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:o,pureStringifyError:s,serialized:a}),a}}}function Rs(e,t){try{let r=function(o){var i,l;if(Ze.isFunctionDeclaration(o)&&yr(o)){const c=((i=o.name)==null?void 0:i.text)||"default",p=o.getText(s),u=Ba(o);a.push({name:c,code:p,sha:mn(t,c,p),entityType:"function",isDefault:u})}else if(Ze.isClassDeclaration(o)&&yr(o)){const c=((l=o.name)==null?void 0:l.text)||"default",p=o.getText(s),u=Ba(o),h=p.includes("React.")||p.includes("jsx")||p.includes("tsx");a.push({name:c,code:p,sha:mn(t,c,p),entityType:h?"component":"class",isDefault:u})}else if(Ze.isInterfaceDeclaration(o)&&yr(o)){const c=o.name.text,p=o.getText(s);a.push({name:c,code:p,sha:mn(t,c,p),entityType:"interface",isDefault:!1})}else if(Ze.isTypeAliasDeclaration(o)&&yr(o)){const c=o.name.text,p=o.getText(s);a.push({name:c,code:p,sha:mn(t,c,p),entityType:"type",isDefault:!1})}else if(Ze.isVariableStatement(o)&&yr(o)){const c=Ba(o);o.declarationList.declarations.forEach(p=>{var u;if(Ze.isIdentifier(p.name)){const h=p.name.text,m=o.getText(s),f=((u=p.initializer)==null?void 0:u.getText(s))||"",g=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));a.push({name:h,code:m,sha:mn(t,h,m),entityType:g?"component":"variable",isDefault:c})}})}else if(Ze.isExportAssignment(o)){const c=o.getText(s);a.push({name:"default",code:c,sha:mn(t,"default",c),entityType:"unknown",isDefault:!0})}else if(Ze.isExportDeclaration(o)&&o.exportClause&&Ze.isNamedExports(o.exportClause)){const c=o.getText(s);for(const p of o.exportClause.elements){const u=p.name.text;a.push({name:u,code:c,sha:mn(t,u,c),entityType:"unknown",isDefault:!1})}}Ze.forEachChild(o,r)};const s=Ze.createSourceFile(t,e,Ze.ScriptTarget.Latest,!0),a=[];return r(s),a}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function yr(e){if(!Ze.canHaveModifiers(e))return!1;const t=Ze.getModifiers(e);return t?t.some(r=>r.kind===Ze.SyntaxKind.ExportKeyword):!1}function Ba(e){if(!Ze.canHaveModifiers(e))return!1;const t=Ze.getModifiers(e);return t?t.some(r=>r.kind===Ze.SyntaxKind.DefaultKeyword):!1}function mn(e,t,r){const s=er.createHash("sha256");return s.update(`${e}:${t}:${r}`),s.digest("hex").substring(0,40)}function Gm(e){var p;const{webapp:t,port:r,environmentVariables:s,packageManager:a}=e,o=t==null?void 0:t.startCommand;if(!o)return`${a} ${a==="npm"?"run ":""}dev`;const i=((p=o.args)==null?void 0:p.map(u=>u.replace(/\$PORT/g,String(r))))??[],l=[];for(const u of s)if(u.key&&u.value!==void 0){const h=String(u.value).replace(/'/g,"'\\''");l.push(`${u.key}='${h}'`)}if(o.env)for(const[u,h]of Object.entries(o.env)){const f=String(h).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");l.push(`${u}='${f}'`)}const c=l.length>0?l.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${c}sh -c "${i[1]}"`:`${c}${o.command} ${i.join(" ")}`}function Km(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=U.normalize(e),s=[...t].sort((a,o)=>{var i,l;return(((i=o.path)==null?void 0:i.length)??0)-(((l=a.path)==null?void 0:l.length)??0)});for(const a of s){const o=U.normalize(a.path??".");if(o==="."||r.startsWith(o+U.sep)||r===o)return a}return t[0]}function qm(e){const{filePath:t,webapps:r,environmentVariables:s,port:a,packageManager:o}=e;if(!r||r.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=Km(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const l=Gm({webapp:i,port:a,environmentVariables:s,packageManager:o});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??o,startCommand:l,url:`http://localhost:${a}/static/codeyam-sample`}}function tr(e,t,r=[]){const s=Array.isArray(t)?t:[t];return a=>a.columns(s).doUpdateSet(o=>{const i=Object.keys(e).filter(l=>l!==t&&!r.includes(l));return Object.fromEntries(i.map(l=>[l,o.ref(`excluded.${l}`)]))})}async function Qm(e){if(e.length===0)return[];const t=Pe(),r=e.map(Um);try{return(await t.insertInto("branches").values(r).onConflict(tr(r[0],"id",["created_at"])).returningAll().execute()).map(Cn)}catch(s){return Fe("CodeYam Error: Database error upserting branches",s,{branchCount:e.length,branchIds:e.map(a=>a.id)}),[]}}function Zm(e){const{jsonObjectFrom:t}=An();return t(e.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",e.ref("commits.author_github_username")))}async function Xm({ids:e,analysisId:t}){const r=Pe();try{let s=r.deleteFrom("scenarios");if(e){if(e.length===0)return;s=s.where("id","in",e)}else if(t)s=s.where("analysis_id","=",t);else throw Fe("CodeYam Error: No deletion criteria provided",null,{ids:e,analysisId:t}),new Error("No deletion criteria provided for scenarios");await s.execute()}catch(s){throw Fe("CodeYam Error: Database error deleting scenarios",s,{ids:e,analysisId:t}),s}}function ef(...e){try{const t=er.createHash("sha256");for(const r of e)t.update(r);return t.digest("hex")}catch(t){throw console.log("CodeYam Error: Error generating sha",e),t}}function za(e,t){return t.map(r=>tf(e,r))}function tf(e,t){return pt` ${pt.ref(e)}.${pt.ref(t)}`.as(t)}function nf(e,t,r){return t.map(s=>rf(e,s,r))}function rf(e,t,r){return pt` ${pt.ref(e)}.${pt.ref(t)}`.as(`_cy_${r}:${t}`)}function sf(e,...t){const r={};for(const[s,a]of Object.entries(e)){const o=s.match(/^_cy_(.+?):(.+)$/);if(o){const[,i,l]=o;if(t.includes(i)){r[i]||(r[i]={}),r[i][l]=a;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${s}'`);continue}r[s]=a}return r}const af=50;function of(e,t){return e.length<=t?[e]:Array.from({length:Math.ceil(e.length/t)},(r,s)=>e.slice(s*t,s*t+t))}function il({projectId:e,ids:t,fileIds:r,entityName:s,entityShas:a,commitIds:o,branchCommitSha:i,limit:l,excludeMetadata:c}){const p=Pe(),{jsonObjectFrom:u,jsonArrayFrom:h}=An();let m=c?p.selectFrom("analyses").select(["analyses.id","analyses.project_id","analyses.file_id","analyses.commit_id","analyses.entity_sha","analyses.entity_name","analyses.entity_type","analyses.file_path","analyses.status","analyses.created_at","analyses.updated_at","analyses.tree_sha","analyses.analyzed_tree_sha","analyses.dependency_analyzed_tree_sha","analyses.previous_analysis_id","analyses.branch_commit_sha","analyses.indirect","analyses.committed_at","analyses.completed_at"]):p.selectFrom("analyses").selectAll("analyses");if(e&&(m=m.where("project_id","=",e)),t){if(t.length===0)return null;m=m.where("id","in",t)}if(r){if(r.length===0)return null;m=m.where("file_id","in",r)}if(o){if(o.length===0)return null;m=m.where("commit_id","in",o)}return s&&(m=m.where("entity_name","=",s)),a&&(m=m.where("entity_sha","in",a)),i&&(m=m.where("branch_commit_sha","=",i)),l&&(m=m.limit(l)),c?p.with("filtered_analyses",()=>m).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[h(f.selectFrom("scenarios").select(za("scenarios",Is)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),h(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):p.with("filtered_analyses",()=>m).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select(za("entities",Vc)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),h(f.selectFrom("scenarios").select(za("scenarios",Is)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),h(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function an(e){const{ids:t,fileIds:r,entityShas:s,commitIds:a}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:s,key:"entityShas"},commit_id:{arr:a,key:"commitIds"}}).find(([c,{arr:p}])=>(p==null?void 0:p.length)>0);let l=[];if(i){const[c,{arr:p,key:u}]=i,h=of(p,af),m=[];for(let f=0;f<h.length;f++){const g=h[f],x=await il({...e,[u]:g}).execute();x&&m.push(...x)}l=m}else{const p=await il(e).execute();if(!p||p.length===0)return Fe("CodeYam: No analyses found",null,e),null;l=p}return l.length===0?null:l.map(Ht)}catch(o){return Fe("CodeYam Error: Database error in loadAnalyses",o,e),null}}function lf(e,t){const{jsonArrayFrom:r,jsonObjectFrom:s}=An();let a=e.selectFrom("analysis_branches").select(om).select(o=>s(o.selectFrom("branches").select(Jc).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(a=t(a)),r(a)}async function Vt({id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:c,includeProject:p,includeCommitAndBranch:u,includeScenarios:h,includeBranches:m}){const f=Pe(),g=Date.now();try{let y=f.selectFrom("analyses").selectAll("analyses");e&&(y=y.where("id","=",e)),r&&(y=y.where("project_id","=",r)),i?y=y.where("dependency_analyzed_tree_sha","=",i):l?y=y.where("analyzed_tree_sha","=",l):s&&(y=y.where("file_id","=",s)),o&&(y=y.where("entity_name","=",o)),a?y=y.where("commit_id","=",a):y=y.orderBy("created_at","desc").limit(1),t&&(y=y.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:x,jsonArrayFrom:b}=An();y=y.select(N=>{const S=[];return S.push(x(N.selectFrom("entities").select(Vc).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),c&&S.push(x(N.selectFrom("files").select(Cm).whereRef("files.id","=","analyses.file_id")).as("file")),p&&S.push(x(N.selectFrom("projects").select(nm).whereRef("projects.id","=","analyses.project_id")).as("project")),h&&S.push(b(N.selectFrom("scenarios").select(Is).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),m&&S.push(lf(N,C=>C.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&S.push(x(N.selectFrom("commits").select(Hc).select(C=>Zm(C).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),S});const w=await y.executeTakeFirst(),v=Date.now()-g;if(!w)return Fe(!!i?`CodeYam: Analysis cache miss for dependency tree SHA ${i.substring(0,12)}...`:`CodeYam Error: Analysis not found${o?` for ${o}`:""}${e?` (id=${e})`:""}`,null,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:c,includeProject:p,includeCommitAndBranch:u,includeScenarios:h,includeBranches:m}),null;if(v>100&&u){const N=w.commit,S=N!=null&&N.files?JSON.stringify(N.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${v}ms (files: ${Math.round(S/1024)}KB)`,{id:w.id,entityName:w.entity_name})}return Ht(w)}catch(y){return Fe("CodeYam Error: Database error loading analysis",y,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:c,includeProject:p,includeCommitAndBranch:u,includeScenarios:h,includeBranches:m}),null}}async function zo({projectId:e,ids:t,names:r,includeInactive:s}){const a=Pe();try{let o=a.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];o=o.where("id","in",t)}if(r){if(r.length===0)return[];o=o.where("name","in",r)}return s||(o=o.where("active_at","is not",null)),(await o.execute()).map(Cn)}catch(o){return Fe("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:s}),[]}}async function cf({projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}){const o=Pe();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(a,p=>p.select(nf("branches",Jc,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),s!==void 0&&(i=i.where("commit_branches.active","=",s));const l=await i.execute();return!l||l.length===0?null:l.map(p=>sf(p,"branch")).map(Bo)}catch(i){return Fe("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}),null}}async function df(e){if(e.length===0)return new Map;const t=Pe();try{const r=await t.selectFrom("commits").select(["id","branch_id","merged_branch_id"]).where("id","in",e).execute(),s=new Set;if(r.forEach(o=>{o.branch_id&&s.add(o.branch_id),o.merged_branch_id&&s.add(o.merged_branch_id)}),s.size===0)return new Map;const a=await t.selectFrom("branches").selectAll().where("id","in",Array.from(s)).execute();return new Map(a.map(o=>[o.id,o]))}catch(r){return Fe("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function uf(e){if(e.length===0)return new Map;const t=Pe(),{jsonObjectFrom:r,jsonArrayFrom:s}=An();try{const a=await t.selectFrom("analyses").selectAll("analyses").select(i=>[r(i.selectFrom("files").select(["id","name","path"]).whereRef("files.id","=","analyses.file_id")).as("file"),s(i.selectFrom("scenarios").select(Is).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),o=new Map;return a.forEach(i=>{const l=o.get(i.commit_id)||[];l.push(i),o.set(i.commit_id,l)}),o}catch(a){return Fe("CodeYam Error: Loading analyses for commits",a,{commitIds:e}),new Map}}async function pf(e){if(e.length===0)return new Map;const t=Pe();try{const r=await t.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),s=new Map;return r.forEach(a=>{const o=s.get(a.commit_id)||[];o.push(a),s.set(a.commit_id,o)}),s}catch(r){return Fe("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function Ds({projectId:e,branchId:t,ids:r,shas:s,fileNames:a,limit:o=10,skipRelations:i=!1}){if(!e&&!r)throw new Error("Must provide projectId or ids");const l=Pe(),{jsonObjectFrom:c}=An(),p=Date.now();try{let u;if(i){const w=hm.map(v=>`commits.${v}`);u=l.selectFrom("commits").select(w)}else u=l.selectFrom("commits").selectAll("commits").select(w=>[c(w.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",w.ref("commits.author_github_username"))).as("author")]);if(e&&(u=u.where("project_id","=",e)),r){if(r.length===0)return[];u=u.where("id","in",r)}if(s){if(s.length===0)return[];u=u.where("sha","in",s)}if(a&&a.length>0){const w=pt.join(a.map(v=>pt`${v}`),pt`, `);u=u.where(pt`
24
+ EXISTS (
25
+ SELECT 1
26
+ FROM json_each(${pt.ref("commits.files")}) AS f
27
+ WHERE json_extract(f.value, '$.fileName') IN (${w})
28
+ )
29
+ `)}t&&(u=u.where("branch_id","=",t));const h=await u.orderBy("committed_at","desc").limit(o).execute(),m=Date.now()-p;if(!h||h.length===0)return[];if(m>100){const w=h.reduce((v,N)=>v+(N.files?JSON.stringify(N.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${m}ms (${h.length} commits, totalFiles: ${Math.round(w/1024)}KB)`)}if(i)return h.map(v=>({...v,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(Sn);const f=h.map(w=>w.id),[g,y,x]=await Promise.all([df(f),uf(f),pf(f)]);return h.map(w=>{const v=w.branch_id?g.get(w.branch_id):void 0,N=w.merged_branch_id?g.get(w.merged_branch_id):void 0,S=y.get(w.id)||[],C=x.get(w.id)||[];return{...w,branch:v,mergedBranch:N,analyses:S,entities:C}}).map(Sn)}catch(u){return Fe("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:t,ids:r,shas:s,limit:o}),[]}}async function Xe({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:o,excludeMetadata:i}){if(r&&r.length==0||s&&s.length==0||a&&a.length==0||o&&o.length==0)return[];if(o&&o.length>50){const c=[];for(let p=0;p<o.length;p+=50){const u=o.slice(p,p+50),h=await Xe({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:u,excludeMetadata:i});h&&c.push(...h)}return c}const l=Pe();try{const u=await(i?l.selectFrom("entities").select(["entities.project_id","entities.file_id","entities.commit_id","entities.name","entities.sha","entities.entity_type","entities.file_path","entities.description","entities.documentation","entities.quality","entities.created_at","entities.updated_at"]):l.selectFrom("entities").selectAll("entities")).$if(!!t,h=>h.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,h=>h.where("entities.project_id","=",e)).$if(!!o,h=>h.where("entities.sha","in",o)).$if(!!s,h=>h.where("entities.file_path","in",s)).$if(!!a,h=>h.where("entities.name","in",a)).$if(!!r,h=>h.where("entities.file_id","in",r)).execute();return!u||u.length===0?null:u.map(Or)}catch(c){return console.log("Load Entities: Error occurred",c,{projectId:e,fileIds:r,filePaths:s,shas:o}),null}}function hf(e,t){const{jsonArrayFrom:r}=An();let s=e.selectFrom("entity_branches").select(wm);return t&&(s=t(s)),r(s)}async function qc({projectId:e,sha:t,silent:r}){const s=Pe();try{const a=await s.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(o=>hf(o,i=>i.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return a?Or(a):(!r&&process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&Fe(`CodeYam Error: Load Entity: Entity not found (sha=${t==null?void 0:t.substring(0,12)})`,null,{projectId:e,sha:t}),null)}catch(a){return Fe("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:t}),null}}const Ya=1e3;async function Qc({projectId:e,filePaths:t,fileIds:r,fileNames:s}){if(t&&t.length>50){const l=[];for(let c=0;c<t.length;c+=50){const p=t.slice(c,c+50),u=await Qc({projectId:e,filePaths:p,fileIds:r,fileNames:s});u&&l.push(...u)}return l}const a=Pe(),o=[];let i=0;try{for(;;){let l=a.selectFrom("files").selectAll().where("project_id","=",e).limit(Ya).offset(i);if(t){if(t.length===0)return[];l=l.where("path","in",t)}if(r){if(r.length===0)return[];l=l.where("id","in",r)}if(s){if(s.length===0)return[];l=l.where("name","in",s)}const c=await l.execute();if(!c||c.length===0||(o.push(...c),c.length<Ya))break;i+=Ya}return o==null?void 0:o.map(Lo)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function Yo({id:e,slug:t,withBranches:r,withFiles:s,silent:a}){try{let i=Pe().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(t)i=i.where("slug","=",t);else throw new Error("Either id or slug must be provided");const l=await i.executeTakeFirst();if(!l)return null;const c=qs(l);return s&&(c.files=await Qc({projectId:c.id})),r&&(c.branches=await zo({projectId:c.id,includeInactive:!1})),c}catch{return null}}function Fs(e,t){const r={...e};for(const s in t){const a=t[s],o=e[s];a!=null&&typeof a=="object"&&!Array.isArray(a)&&o!==void 0&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[s]=Fs(o,a):a!==void 0&&(r[s]=a)}return r}async function nn({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:s,archiveCurrentRun:a,updateCallback:o}){for(let c=0;c<=4;c++)try{return await Pe().transaction().execute(async p=>{const u=await p.selectFrom("commits").select(["id","metadata"]).$if(!!e,f=>f.where("id","=",e)).$if(!!t,f=>f.where("sha","=",t)).executeTakeFirst();if(!u)return Fe(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const h=u.metadata||{};if(s)s.lastUpdatedAt??(s.lastUpdatedAt=new Date().toISOString()),r=Fs(r??{},{currentRun:s});else if(!r&&!o)return h;const m=r?Fs(h,r):h;if(a&&m.currentRun){const f={...m.currentRun,archivedAt:new Date().toISOString()};m.historicalRuns=[...m.historicalRuns||[],f]}o&&await o(m);try{return await p.updateTable("commits").set({metadata:JSON.stringify(m)}).where("id","=",u.id).returning(["id"]).executeTakeFirst()?m:(Fe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),h)}catch(f){return Fe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,f),h}})}catch(p){const u=p instanceof Error&&p.message.includes("database is locked");if(u&&c<4){const h=250*Math.pow(2,c);await new Promise(m=>setTimeout(m,h));continue}return Fe(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}${u?` after ${c+1} attempts`:""}`,p),null}return null}async function Zc(e,t,r="analysis"){try{return await Pe().transaction().execute(async s=>{const a=await s.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!a)return Fe(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=Ht(a);return t(o.metadata,o),await s.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(Fe(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(s){return Fe(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,s,{analysisId:e,source:r}),null}}async function nr(e,t,r="capture"){for(let o=0;o<=4;o++)try{return await Pe().transaction().execute(async i=>{const l=await i.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!l)return Fe(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const c=Ht(l);return t(c.status,c),await i.updateTable("analyses").set({status:JSON.stringify(c.status)}).where("id","=",e).returningAll().executeTakeFirst()?c.status:(Fe(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(i){const l=i instanceof Error&&i.message.includes("database is locked");if(l&&o<4){const c=250*Math.pow(2,o);await new Promise(p=>setTimeout(p,c));continue}return Fe(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})${l?` after ${o+1} attempts`:""}`,i,{analysisId:e,source:r}),null}return null}async function Gn({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:s}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await Pe().transaction().execute(async a=>{const o=await a.selectFrom("projects").selectAll().$if(!!e,c=>c.where("id","=",e)).$if(!!t,c=>c.where("slug","=",t)).executeTakeFirst();if(!o)return Fe(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!s)return i;const l=r?Fs(i,r):i;s&&await s(l,qs(o));try{return await a.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",o.id).returningAll().executeTakeFirst()?l:(Fe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(c){return Fe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,c),null}})}catch(a){return Fe(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,a),null}}const mf=()=>crypto.randomUUID();function ff(e){const{id:t,projectId:r,analysisId:s,previousVersionId:a,analysis:o,metadata:i,data:l,...c}=e;return delete c.userScenarios,delete c.comments,"created_at"in c&&delete c.created_at,{...c,id:t??mf(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:s,previous_version_id:a}}async function gf(e){if(e.length===0)return[];const t=Pe(),r=e.map(ff);try{return(await t.insertInto("scenarios").values(r).onConflict(tr(r[0],"id",["created_at"])).returningAll().execute()).map(Uc)}catch(s){return Fe("CodeYam Error: Database error upserting scenarios",s,{scenarioCount:e.length}),null}}const yf=()=>crypto.randomUUID();function xf(e){const{id:t,commitId:r,branchId:s,...a}=e;return delete a.commit,delete a.branch,{...a,id:t??yf(),commit_id:r,branch_id:s}}async function ll(e){if(e.length===0)return[];const t=Pe(),r=e.map(xf);try{return(await t.insertInto("commit_branches").values(r).onConflict(tr(r[0],"id",["created_at"])).returningAll().execute()).map(Bo)}catch(s){return Fe("CodeYam Error: Database error upserting commit branches",s,{commitBranchCount:e.length,commitBranchIds:e.map(a=>a.id)}),[]}}async function bf(e,t){const r=Pe(),s={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(s).onConflict(tr(s,"username",[])).returningAll().executeTakeFirst()||null}catch(a){return Fe("CodeYam Error: Error upserting github user",a,{username:e,avatarUrl:t}),null}}const wf=()=>crypto.randomUUID();function vf(e,t){const{id:r,projectId:s,branchId:a,mergedBranchId:o,aiMessage:i,htmlUrl:l,analyzedAt:c,committedAt:p,author:u,metadata:h,files:m,...f}=e;return delete f.branch,delete f.mergedBranch,delete f.backgroundJob,delete f.analyses,delete f.parents,delete f.entities,delete f.commitBranches,{...f,id:r??wf(),project_id:s??String(t),metadata:h?JSON.stringify(h):void 0,files:m?JSON.stringify(m):void 0,branch_id:a,merged_branch_id:o,author_github_username:u==null?void 0:u.username,html_url:l,ai_message:i,analyzed_at:c,committed_at:p}}async function Nf({projectId:e,commits:t}){const r=Pe();try{const s=t.reduce((i,l)=>{const{author:c}=l;return c!=null&&c.username&&(c!=null&&c.avatarUrl)&&(i[c.username]=c.avatarUrl),i},{});for(const i in s)await bf(i,s[i]);const a=t.map(i=>vf(i,e));return(await r.insertInto("commits").values(a).onConflict(tr(a[0],"id",["created_at"])).returningAll().execute()).map(Sn)}catch(s){return Fe("CodeYam Error: Error saving commits",s,{projectId:e,commitCount:t.length,commitIds:t.map(a=>a.id).filter(Boolean)}),[]}}const Sf=()=>crypto.randomUUID();function Cf(e){const{id:t,files:r,branches:s,team:a,analyzedAt:o,contentChangedAt:i,createdAt:l,updatedAt:c,metadata:p,...u}=e;return{...u,id:t??Sf(),analyzed_at:o||null,content_changed_at:i||null,created_at:l||new Date().toISOString(),updated_at:c||null,metadata:p?JSON.stringify(p):null,github_token:null,configuration:null,team_id:null}}async function kf(e){try{if(e.length===0)return null;const t=Pe(),r=e.map(o=>Cf(o)),s=await t.insertInto("projects").values(r).onConflict(tr(r[0],"id",["created_at"])).returningAll().execute(),a=s==null?void 0:s[0];return a?qs(a):null}catch(t){return console.log("Error saving project",t),null}}const Os=U.join(Hs.homedir(),".codeyam","secrets.json"),Ls=U.join(process.cwd(),".codeyam","secrets.json");async function ln(){let e={};try{if(V.existsSync(Ls)){const o=await _e.readFile(Ls,"utf8");e=JSON.parse(o)}}catch{console.warn($s.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(V.existsSync(Os)){const o=await _e.readFile(Os,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn($s.yellow("⚠ Could not read home secrets file, falling back to environment variables"))}const t={},r=e.OPENAI_API_KEY||process.env.OPENAI_API_KEY;r&&(t.OPENAI_API_KEY=r);const s=e.ANTHROPIC_API_KEY||process.env.ANTHROPIC_API_KEY;s&&(t.ANTHROPIC_API_KEY=s);const a=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return a&&(t.GROQ_API_KEY=a),t}async function _f(e,t=!0){const r=t?Os:Ls,s=U.dirname(r);await _e.mkdir(s,{recursive:!0}),await _e.writeFile(r,JSON.stringify(e,null,2)),await _e.chmod(r,384)}function Ef(e=!0){return e?Os:Ls}async function cl(){const e=await ln(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function Af(e){console.log(),console.log($s.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const s=await gh({type:"password",name:"key",message:"OpenAI API Key",validate:a=>a&&!a.startsWith("sk-")?"OpenAI API key should start with sk-":!0});s.key&&(t.OPENAI_API_KEY=s.key);break}return t}async function Pf(e=!0){const t=await cl();if(t.isValid)return t.secrets;const r=await Af(t.missing),a={...await ln(),...r};await _f(a,e);const o=Ef(e);return console.log($s.green(`✓ Configuration saved to ${o}`)),(await cl()).secrets}function jf(e){const t=U.resolve(e),r=U.parse(t).root;return t===r||t===U.resolve(Hs.homedir())}function Xc(e=process.cwd()){let t=U.resolve(e);const r=U.parse(t).root;for(;t!==r;){if(jf(t))return null;const s=U.join(t,".codeyam","config.json");if(V.existsSync(s))return t;t=U.dirname(t)}return null}let ed=Xc();function Ne(){return ed}function Tf(e){ed=e}function td(e){const t={...e};for(const r in e)if(r.includes(".")){const s=r.replace(/\./g,"");t[s]=e[r]}return t}const Mf={"Accordion.Item":e=>`<CYAccordion.Root type="single" collapsible>${e}</CYAccordion.Root>`,"Accordion.Header":e=>`<CYAccordion.Root type="single" collapsible><CYAccordion.Item value="item-1">${e}</CYAccordion.Item></CYAccordion.Root>`,"Accordion.Trigger":e=>`<CYAccordion.Root type="single" collapsible><CYAccordion.Item value="item-1"><CYAccordion.Header>${e}</CYAccordion.Header></CYAccordion.Item></CYAccordion.Root>`,"Accordion.Content":e=>`<CYAccordion.Root type="single" collapsible><CYAccordion.Item value="item-1">${e}</CYAccordion.Item></CYAccordion.Root>`,"AlertDialog.Trigger":e=>`<CYAlertDialog.Root>${e}</CYAlertDialog.Root>`,"AlertDialog.Portal":e=>`<CYAlertDialog.Root>${e}</CYAlertDialog.Root>`,"AlertDialog.Overlay":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal>${e}</CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Content":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal>${e}</CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Title":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Description":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Action":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Cancel":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"Avatar.Image":e=>`<CYAvatar.Root>${e}</CYAvatar.Root>`,"Avatar.Fallback":e=>`<CYAvatar.Root>${e}</CYAvatar.Root>`,"Checkbox.Indicator":e=>`<CYCheckbox.Root>${e}</CYCheckbox.Root>`,"Collapsible.Trigger":e=>`<CYCollapsible.Root>${e}</CYCollapsible.Root>`,"Collapsible.Content":e=>`<CYCollapsible.Root>${e}</CYCollapsible.Root>`,"ContextMenu.Trigger":e=>`<CYContextMenu.Root>${e}</CYContextMenu.Root>`,"ContextMenu.Portal":e=>`<CYContextMenu.Root>${e}</CYContextMenu.Root>`,"ContextMenu.Content":e=>`<CYContextMenu.Root><CYContextMenu.Portal>${e}</CYContextMenu.Portal></CYContextMenu.Root>`,"ContextMenu.Item":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.CheckboxItem":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.RadioGroup":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.RadioItem":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.RadioGroup value="item-1">${e}</CYContextMenu.RadioGroup></CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.ItemIndicator":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.CheckboxItem checked>${e}</CYContextMenu.CheckboxItem></CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.Label":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.Separator":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.Sub":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.SubTrigger":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.Sub>${e}</CYContextMenu.Sub></CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.SubContent":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.Sub>${e}</CYContextMenu.Sub></CYContextMenu.Content></CYContextMenu.Root>`,"Dialog.Trigger":e=>`<CYDialog.Root>${e}</CYDialog.Root>`,"Dialog.Portal":e=>`<CYDialog.Root>${e}</CYDialog.Root>`,"Dialog.Overlay":e=>`<CYDialog.Root><CYDialog.Portal>${e}</CYDialog.Portal></CYDialog.Root>`,"Dialog.Content":e=>`<CYDialog.Root><CYDialog.Portal>${e}</CYDialog.Portal></CYDialog.Root>`,"Dialog.Title":e=>`<CYDialog.Root><CYDialog.Portal><CYDialog.Content>${e}</CYDialog.Content></CYDialog.Portal></CYDialog.Root>`,"Dialog.Description":e=>`<CYDialog.Root><CYDialog.Portal><CYDialog.Content>${e}</CYDialog.Content></CYDialog.Portal></CYDialog.Root>`,"Dialog.Close":e=>`<CYDialog.Root><CYDialog.Portal><CYDialog.Content>${e}</CYDialog.Content></CYDialog.Portal></CYDialog.Root>`,"DropdownMenu.Trigger":e=>`<CYDropdownMenu.Root>${e}</CYDropdownMenu.Root>`,"DropdownMenu.Portal":e=>`<CYDropdownMenu.Root>${e}</CYDropdownMenu.Root>`,"DropdownMenu.Content":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Portal>${e}</CYDropdownMenu.Portal></CYDropdownMenu.Root>`,"DropdownMenu.Item":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.CheckboxItem":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.RadioGroup":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.RadioItem":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.RadioGroup value="item-1">${e}</CYDropdownMenu.RadioGroup></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.ItemIndicator":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.CheckboxItem checked>${e}</CYDropdownMenu.CheckboxItem></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.Label":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.Separator":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.Sub":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.SubTrigger":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.Sub>${e}</CYDropdownMenu.Sub></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.SubContent":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.Sub>${e}</CYDropdownMenu.Sub></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"Form.Field":e=>`<CYForm.Root>${e}</CYForm.Root>`,"Form.Label":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.Control":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.Message":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.ValidityState":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.Submit":e=>`<CYForm.Root>${e}</CYForm.Root>`,"HoverCard.Trigger":e=>`<CYHoverCard.Root>${e}</CYHoverCard.Root>`,"HoverCard.Portal":e=>`<CYHoverCard.Root>${e}</CYHoverCard.Root>`,"HoverCard.Content":e=>`<CYHoverCard.Root><CYHoverCard.Portal>${e}</CYHoverCard.Portal></CYHoverCard.Root>`,"Menubar.Menu":e=>`<CYMenubar.Root>${e}</CYMenubar.Root>`,"Menubar.Trigger":e=>`<CYMenubar.Root><CYMenubar.Menu>${e}</CYMenubar.Menu></CYMenubar.Root>`,"Menubar.Portal":e=>`<CYMenubar.Root><CYMenubar.Menu>${e}</CYMenubar.Menu></CYMenubar.Root>`,"Menubar.Content":e=>`<CYMenubar.Root><CYMenubar.Menu>${e}</CYMenubar.Menu></CYMenubar.Root>`,"Menubar.Item":e=>`<CYMenubar.Root><CYMenubar.Menu><CYMenubar.Content>${e}</CYMenubar.Content></CYMenubar.Menu></CYMenubar.Root>`,"NavigationMenu.List":e=>`<CYNavigationMenu.Root>${e}</CYNavigationMenu.Root>`,"NavigationMenu.Item":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List>${e}</CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Trigger":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item>${e}</CYNavigationMenu.Item></CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Content":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item><CYNavigationMenu.Trigger />{/* Dummy trigger for context */}${e}</CYNavigationMenu.Item></CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Link":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item>${e}</CYNavigationMenu.Item></CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Indicator":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item><CYNavigationMenu.Trigger />{/* Dummy trigger for context */}</CYNavigationMenu.Item>${e}</CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Viewport":e=>`<CYNavigationMenu.Root>${e}</CYNavigationMenu.Root>`,"Popover.Trigger":e=>`<CYPopover.Root>${e}</CYPopover.Root>`,"Popover.Portal":e=>`<CYPopover.Root>${e}</CYPopover.Root>`,"Popover.Content":e=>`<CYPopover.Root><CYPopover.Portal>${e}</CYPopover.Portal></CYPopover.Root>`,"Popover.Close":e=>`<CYPopover.Root><CYPopover.Content>${e}</CYPopover.Content></CYPopover.Root>`,"Popover.Anchor":e=>`<CYPopover.Root>${e}</CYPopover.Root>`,"Progress.Indicator":e=>`<CYProgress.Root value={50}>${e}</CYProgress.Root>`,"RadioGroup.Item":e=>`<CYRadioGroup.Root>${e}</CYRadioGroup.Root>`,"RadioGroup.Indicator":e=>`<CYRadioGroup.Root><CYRadioGroup.Item value="item-1">${e}</CYRadioGroup.Item></CYRadioGroup.Root>`,"ScrollArea.Viewport":e=>`<CYScrollArea.Root>${e}</CYScrollArea.Root>`,"ScrollArea.Scrollbar":e=>`<CYScrollArea.Root>${e}</CYScrollArea.Root>`,"ScrollArea.Thumb":e=>`<CYScrollArea.Root><CYScrollArea.Scrollbar orientation="vertical">${e}</CYScrollArea.Scrollbar></CYScrollArea.Root>`,"ScrollArea.Corner":e=>`<CYScrollArea.Root>${e}</CYScrollArea.Root>`,"Select.Trigger":e=>`<CYSelect.Root>${e}</CYSelect.Root>`,"Select.Value":e=>`<CYSelect.Root><CYSelect.Trigger>${e}</CYSelect.Trigger></CYSelect.Root>`,"Select.Icon":e=>`<CYSelect.Root><CYSelect.Trigger>${e}</CYSelect.Trigger></CYSelect.Root>`,"Select.Portal":e=>`<CYSelect.Root>${e}</CYSelect.Root>`,"Select.Content":e=>`<CYSelect.Root><CYSelect.Portal>${e}</CYSelect.Portal></CYSelect.Root>`,"Select.Viewport":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Select.Item":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Select.ItemText":e=>`<CYSelect.Root><CYSelect.Content><CYSelect.Item value="item-1">${e}</CYSelect.Item></CYSelect.Content></CYSelect.Root>`,"Select.ItemIndicator":e=>`<CYSelect.Root><CYSelect.Content><CYSelect.Item value="item-1">${e}</CYSelect.Item></CYSelect.Content></CYSelect.Root>`,"Select.Group":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Select.Label":e=>`<CYSelect.Root><CYSelect.Content><CYSelect.Group>${e}</CYSelect.Group></CYSelect.Content></CYSelect.Root>`,"Select.Separator":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Slider.Track":e=>`<CYSlider.Root>${e}</CYSlider.Root>`,"Slider.Range":e=>`<CYSlider.Root><CYSlider.Track>${e}</CYSlider.Track></CYSlider.Root>`,"Slider.Thumb":e=>`<CYSlider.Root>${e}</CYSlider.Root>`,"Switch.Thumb":e=>`<CYSwitch.Root>${e}</CYSwitch.Root>`,"Tabs.List":e=>`<CYTabs.Root defaultValue="tab1">${e}</CYTabs.Root>`,"Tabs.Trigger":e=>`<CYTabs.Root defaultValue="tab1"><CYTabs.List>${e}</CYTabs.List></CYTabs.Root>`,"Tabs.Content":e=>`<CYTabs.Root defaultValue="tab1">${e}</CYTabs.Root>`,"Toast.Root":e=>`<CYToast.Provider>${e}</CYToast.Provider>`,"Toast.Title":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Description":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Action":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Close":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Viewport":e=>`<CYToast.Provider>${e}</CYToast.Provider>`,"ToggleGroup.Item":e=>`<CYToggleGroup.Root type="single">${e}</CYToggleGroup.Root>`,"Toolbar.Button":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.Link":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.Separator":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.ToggleGroup":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.ToggleItem":e=>`<CYToolbar.Root><CYToolbar.ToggleGroup type="single">${e}</CYToolbar.ToggleGroup></CYToolbar.Root>`,"Tooltip.Root":e=>`<CYTooltip.Provider>${e}</CYTooltip.Provider>`,"Tooltip.Trigger":e=>`<CYTooltip.Provider><CYTooltip.Root>${e}</CYTooltip.Root></CYTooltip.Provider>`,"Tooltip.Portal":e=>`<CYTooltip.Provider><CYTooltip.Root>${e}</CYTooltip.Root></CYTooltip.Provider>`,"Tooltip.Content":e=>`<CYTooltip.Provider><CYTooltip.Root><CYTooltip.Portal>${e}</CYTooltip.Portal></CYTooltip.Root></CYTooltip.Provider>`,"Tooltip.Arrow":e=>`<CYTooltip.Provider><CYTooltip.Root><CYTooltip.Content>${e}</CYTooltip.Content></CYTooltip.Root></CYTooltip.Provider>`};td(Mf);const $f={"Command.Input":e=>`<CYCommand>${e}</CYCommand>`,"Command.List":e=>`<CYCommand>${e}</CYCommand>`,"Command.Item":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Group":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Separator":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Empty":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Loading":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Shortcut":e=>`<CYCommand><CYCommand.List><CYCommand.Item value="x">${e}</CYCommand.Item></CYCommand.List></CYCommand>`,"Command.Dialog":e=>`<CYCommand.Dialog open>${e}</CYCommand.Dialog>`};td($f);function Sr(e,t,r=new WeakSet){if(!t)return e;if(!e)return t;try{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference detected during deep merge");r.add(t)}if(Array.isArray(t)){const a=Array.isArray(e)?e:[],o=[];for(let i=0;i<t.length;i++){const l=t[i];l&&typeof l=="object"&&!Array.isArray(l)||Array.isArray(l)?o[i]=Sr(a[i],l,r):o[i]=l}return o}const s={...e};for(const a in t)if(t[a]===null)s[a]=null;else if(Array.isArray(t[a])){const o=Array.isArray(e[a])?e[a]:[];s[a]=[];for(let i=0;i<t[a].length;i++){const l=t[a][i];typeof l=="object"&&l!==null?s[a][i]=Sr(o[i],l,r):s[a][i]=l}}else typeof t[a]=="object"&&t[a]!==null?s[a]=Sr(s[a]??{},t[a],r):s[a]=t[a];return s}catch(s){throw console.log("CodeYam: Error merging data",e,t),s}}async function If({projectId:e,commit:t,branch:r}){var l,c,p,u,h,m,f;let s;const a={commitId:t.id,branchId:r.id,active:!0},o=await cf({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){s=(l=o.sort((y,x)=>{var b,w,v,N;return(((w=(b=y.branch.metadata)==null?void 0:b.permanent)==null?void 0:w.order)??999)-(((N=(v=x.branch.metadata)==null?void 0:v.permanent)==null?void 0:N.order)??999)})[0])==null?void 0:l.branch,s&&((p=(c=r.metadata)==null?void 0:c.permanent)==null?void 0:p.order)!==void 0&&(((h=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:h.order)<=((f=(m=s.metadata)==null?void 0:m.permanent)==null?void 0:f.order)?s=r:a.active=!1);const g=o.filter(y=>y.active&&y.branch.id!==s.id||!y.active&&y.branch.id===s.id);g.length>0&&await ll(g.map(y=>({...y,active:y.branchId===s.id})))}(o==null?void 0:o.find(g=>g.branchId===a.branchId))||await ll([a])}let dl=!1;function cn(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=Ne();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return se.join(e,".codeyam","db.sqlite3")}async function Je(){if(!dl){dl=!0;const t=Ne();t&&await Df(t)}const e=await Pf();process.env.SQLITE_PATH=cn(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function lk(){try{return await Je(),await Yo({slug:"__test_connection__",silent:!0}),!0}catch(e){return console.error("Database connection test failed:",e),!1}}async function De(e){await Je();const t=await Yo({slug:e,silent:!0});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await zo({projectId:t.id,names:["_local"]}),s=r==null?void 0:r[0];if(!s)throw new Error(`Local development branch not found for project "${e}". Please run "codeyam init" to set up local analysis.`);return{project:t,branch:s}}async function ck(e){await Je();const t=await Yo({slug:e.slug,silent:!0});if(t)return{project:t,created:!1};const r={id:To(),name:e.slug,slug:e.slug,path:`local:${process.cwd()}`,metadata:{packageManager:e.packageManager,unapprovedPaths:e.unapprovedPaths,webapps:e.webapps}};try{return{project:await kf([r]),created:!0}}catch(s){throw new Error(`Failed to create project: ${s.message}`)}}async function dk(e){await Je();const t=await zo({projectId:e.id,names:["_local"]});if(t&&t.length>0)return{branch:t[0],created:!1};const r={projectId:e.id,name:"_local",ref:"_local",primary:!0,activeAt:new Date().toISOString(),contentChangedAt:new Date().toISOString(),metadata:{contributors:[{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"}],commits:{total:0,last7Days:[]},timeline:[{title:"Local branch created",date:new Date().toISOString(),authors:[{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"}],sha:"local-init"}]}},s=await Qm([r]);if(!s||s.length===0)throw new Error("Failed to create _local branch");return{branch:s[0],created:!0}}async function Rf(e,t,r){await Je();const s=Ne(),a=ef(`${e.slug}-local-${Date.now()}-${Math.random()}`),o=r.map(c=>{let p="";if(s)try{if(p=Ie(`git diff HEAD -- "${c}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!p)try{const u=Ie(`cat "${c}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const h=u.split(`
30
+ `);p=`@@ -0,0 +1,${h.length} @@
31
+ ${h.map(m=>`+${m}`).join(`
32
+ `)}`}}catch{}}catch{}return{fileName:c,status:"modified",patch:p}}),i={sha:a,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${a}`,htmlUrl:`local://codeyam/${e.slug}/${a}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:o,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},l=await Nf({projectId:e.id,commits:[i]});if(!l||l.length===0)throw new Error("Failed to create fake commit");return await If({projectId:e.id,commit:l[0],branch:t}),l[0]}async function Df(e){const t=se.join(e,".codeyam","db.sqlite3"),r=se.join(e,".codeyam","config.json");if(V.existsSync(t)||!V.existsSync(r))return!1;const{default:s}=await import("./init-BdWDvetv.js");return await s.handler({force:!0,autoInit:!0,$0:"",_:[]}),!0}async function Pn(){await Je();const e=await Xe({excludeMetadata:!0});if(!e||e.length===0)return[];const t=new Map;for(const c of e){const p=`${c.name}::${c.filePath}`,u=t.get(p);(!u||c.createdAt&&u.createdAt&&c.createdAt>u.createdAt)&&t.set(p,c)}const r=[...t.values()],s=e.map(c=>c.sha),a=await an({entityShas:s,excludeMetadata:!0}),o=new Map;if(a)for(const c of a)o.has(c.entitySha)||o.set(c.entitySha,[]),o.get(c.entitySha).push(c);const i=new Map;for(const c of e){const p=`${c.name}::${c.filePath}`,u=i.get(p)||[];u.push(c.sha),i.set(p,u)}return r.map(c=>{const p=o.get(c.sha)||[];if(p.length>0)return{...c,analyses:p};const u=`${c.name}::${c.filePath}`,h=i.get(u)||[];for(const m of h){if(m===c.sha)continue;const f=o.get(m);if(f&&f.length>0)return{...c,analyses:f}}return{...c,analyses:[]}})}async function Ff(e){await Je();const t=await Xe(e);return!t||t.length===0?[]:t.filter(r=>{var s;return!((s=r.metadata)!=null&&s.isSuperseded)})}async function Zs(e,t){await Je();const r=await an({entityShas:[e],limit:1});if(r&&r.length>0&&t){const s=await qc({projectId:r[0].projectId,sha:e});if(s)for(const a of r)a.entity=s}return r||[]}async function Xs(e){if(await Je(),e.name&&e.projectId){const r=await an({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const s=r.filter(o=>{const i=o.scenarios&&o.scenarios.length>0,l=!e.filePath||o.filePath===e.filePath;return i&&l});if(s.length>0)return s.sort((o,i)=>{const l=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),s[0];const a=r.filter(o=>o.scenarios&&o.scenarios.length>0);if(a.length>0)return a.sort((o,i)=>{const l=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),a[0]}}const t=await an({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function nd(e){await Je();const t=await an({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function _n(e){await Je();const t=await Ye();if(!t)return null;const{project:r}=await De(t);return await qc({projectId:r.id,sha:e})}async function rd(e){var s,a,o,i,l,c,p,u;await Je();const t=[],r=[];if((s=e.metadata)!=null&&s.importedExports&&e.metadata.importedExports.length>0){const h=e.metadata.importedExports;for(const m of h){if(!m.filePath||!m.name)continue;const f=m.resolvedFilePath??m.filePath,g=m.resolvedName??m.name;let y=await Xe({projectId:e.projectId,filePaths:[f],names:[g]});if((!y||y.length===0)&&m.resolvedIsDefault&&(y=await Xe({projectId:e.projectId,filePaths:[f],names:["default"]})),y&&y.length>0){const x=y[0],b=await an({entityShas:[x.sha],limit:1});let w,v,N;if(b&&b.length>0&&b[0].scenarios){const S=b[0],C=S.scenarios||[],A=C.length,_=C.find(R=>{var D,T;return(T=(D=R.metadata)==null?void 0:D.screenshotPaths)==null?void 0:T[0]});_&&(w=(o=(a=_.metadata)==null?void 0:a.screenshotPaths)==null?void 0:o[0],v=_.name),N={status:((i=x.metadata)==null?void 0:i.previousVersionWithAnalyses)||S.entitySha!==x.sha?"out_of_date":"up_to_date",scenarioCount:A,timestamp:S.createdAt?new Date(S.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else N={status:"not_analyzed"};t.push({...x,screenshotPath:w,scenarioName:v,analysisStatus:N})}}}if((l=e.metadata)!=null&&l.importedBy){const h=[];for(const m in e.metadata.importedBy)for(const f in e.metadata.importedBy[m]){const g=e.metadata.importedBy[m][f];g.shas&&h.push(...g.shas)}if(h.length>0){const m=await Xe({projectId:e.projectId,shas:h});if(m)for(const f of m){const g=await an({entityShas:[f.sha],limit:1});let y,x,b;if(g&&g.length>0&&g[0].scenarios){const w=g[0],v=w.scenarios||[],N=v.length,S=v.find(A=>{var _,E;return(E=(_=A.metadata)==null?void 0:_.screenshotPaths)==null?void 0:E[0]});S&&(y=(p=(c=S.metadata)==null?void 0:c.screenshotPaths)==null?void 0:p[0],x=S.name),b={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||w.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:N,timestamp:w.createdAt?new Date(w.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else b={status:"not_analyzed"};r.push({...f,screenshotPath:y,scenarioName:x,analysisStatus:b})}}}return{importedEntities:t,importingEntities:r}}async function Ye(){try{const e=Ne();if(!e)return null;const t=se.join(e,".codeyam","config.json");return JSON.parse(await Ee.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function rr(){await Je();try{const e=await Ye();if(!e)return null;const{project:t,branch:r}=await De(e),s=await Ds({projectId:t.id,branchId:r.id,limit:1,skipRelations:!0});return s&&s.length>0?s[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function ea(){try{const e=Ne();if(!e)return null;const t=se.join(e,".codeyam","config.json");return JSON.parse(await Ee.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function sd(e){try{const t=Ne();if(!t)return console.error("[getEntityCodeFromFilesystem] No project root found"),null;if(!e.filePath)return console.error("[getEntityCodeFromFilesystem] Entity has no filePath"),null;const r=se.join(t,e.filePath);return await Ee.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function ad(e){try{const t=Ne();if(!t||!e.filePath)return!1;const r=se.join(t,e.filePath),a=(await Ee.stat(r)).mtime.getTime(),o=e.updatedAt||e.createdAt;if(!o)return!1;const i=new Date(o).getTime();return a>i+1e3}catch{return!1}}async function od(e){if(await Je(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await Xe({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),s=await an({entityShas:r}),a=new Map;if(s)for(const i of s)a.has(i.entitySha)||a.set(i.entitySha,[]),a.get(i.entitySha).push(i);for(const[i,l]of a.entries())l.sort((c,p)=>{const u=new Date(c.createdAt||0).getTime();return new Date(p.createdAt||0).getTime()-u});const o=t.map(i=>({...i,analyses:a.get(i.sha)||[]}));return o.sort((i,l)=>{var u,h;const c=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",p=((h=l.analyses[0])==null?void 0:h.createdAt)||l.createdAt||"";return new Date(p).getTime()-new Date(c).getTime()}),o}async function id(e){try{const t=Ne();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=se.join(t,".codeyam","config.json"),s=await Ee.readFile(r,"utf8"),a=JSON.parse(s),o={...a,...e},i=JSON.stringify(o,null,2);if(await Ee.writeFile(r,i,"utf8"),a.projectSlug){const l={};e.universalMocks!==void 0&&(l.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(l.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(l.webapps=e.webapps),await Gn({projectSlug:a.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const Of=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:Pn,getAnalysesForEntity:Zs,getAnalysisForExactEntitySha:nd,getCurrentCommit:rr,getCurrentEntities:Ff,getEntityBySha:_n,getEntityCodeFromFilesystem:sd,getEntityHistory:od,getLatestAnalysisForEntity:Xs,getProjectConfig:ea,getProjectSlug:Ye,getRelatedEntities:rd,hasFileBeenModifiedSinceEntity:ad,requireBranchAndProject:De,updateProjectConfig:id},Symbol.toStringTag,{value:"Module"})),ld="secrets.json";function cd(e){return se.join(e,".codeyam",ld)}function dd(){return se.join(io.homedir(),".codeyam",ld)}async function ta(e){let t={};try{const r=dd(),s=await Ee.readFile(r,"utf-8");t=JSON.parse(s)}catch{}try{const r=cd(e),s=await Ee.readFile(r,"utf-8"),a=JSON.parse(s);t={...t,...a}}catch{}return t}async function Lf(e,t,r=!0){const s=r?dd():cd(e),a=se.dirname(s);await Ee.mkdir(a,{recursive:!0}),await Ee.writeFile(s,JSON.stringify(t,null,2)+`
33
+ `,"utf-8")}async function Bf(e){const t=await ta(e);return!!(t.ANTHROPIC_API_KEY&&t.ANTHROPIC_API_KEY.length>0)||!!(t.OPENAI_API_KEY&&t.OPENAI_API_KEY.length>0)||!!(t.GROQ_API_KEY&&t.GROQ_API_KEY.length>0)||!!(t.OPENROUTER_API_KEY&&t.OPENROUTER_API_KEY.length>0)}const zf=3;let xr=0;async function ls(e){if(!e||e.length===0)return[];if(xr>=zf)return console.warn(`[Loader] Circuit breaker open (${xr} consecutive timeouts), skipping entity fetch for ${e.length} entities`),[];const t=Math.min(Math.max(e.length*2e3,1e4),6e4);return new Promise(r=>{let s=!1;const a=setTimeout(()=>{s||(s=!0,xr++,console.warn(`[Loader] Entity fetch timeout after ${t}ms for ${e.length} entities`),r([]))},t);Xe({shas:e,excludeMetadata:!0}).then(o=>{s||(s=!0,clearTimeout(a),xr=0,r(o||[]))}).catch(()=>{s||(s=!0,clearTimeout(a),xr++,r([]))})})}function Yf({sourcePath:e,destinationPath:t,excludes:r,silent:s}){if(process.platform!=="darwin")return!1;if(vt(t))try{if(ih(t).length>0)return!1;Da(t,{recursive:!0})}catch{return!1}try{Ie(`cp -c -R "${e}" "${t}"`,{stdio:"pipe",timeout:3e5});for(const a of r)if(a.includes("*"))try{Ie(`rm -rf "${jr(t,a)}"`,{stdio:"pipe",shell:"/bin/sh"})}catch{}else{const o=jr(t,a);vt(o)&&Da(o,{recursive:!0,force:!0})}return s||console.log(`Directory cloned (APFS CoW) from ${e} to ${t}`),!0}catch{if(vt(t))try{Da(t,{recursive:!0})}catch{}return!1}}async function Wf({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:s=!1,silent:a=!1,extraArgs:o=[],timeoutMs:i=3e5}){const l=Date.now();if(!s&&o.length===0&&Yf({sourcePath:e,destinationPath:t,excludes:r,silent:a})){if(!a){const p=((Date.now()-l)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${p}s]`)}return}return new Promise((c,p)=>{const u=e.endsWith("/")?e:`${e}/`,h=t.endsWith("/")?t:`${t}/`,m=["-a","--no-specials"];s||m.push("--delete","--force"),m.push(...o);for(const x of r)m.push(`--exclude=${x}`);m.push(u,h);const f=ft("rsync",m);let g=!1;const y=i?setTimeout(()=>{if(!g){g=!0,f.kill("SIGKILL");const x=((Date.now()-l)/1e3).toFixed(1);p(new Error(`rsync timed out after ${x}s syncing ${e} → ${t}`))}},i):void 0;f.on("exit",x=>{if(!g)if(g=!0,y&&clearTimeout(y),x===0){if(!a){const b=((Date.now()-l)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${b}s]`)}c()}else console.error(`CodeYam Error: rsync failed with code: ${x}`,JSON.stringify({rsyncArgs:m},null,2)),p(new Error(`rsync failed with exit code ${x}`))}),f.on("error",x=>{g||(g=!0,y&&clearTimeout(y),a||console.log("Error occurred:",x),p(x))})})}const Uf=$o(Mo);async function Jf(e){return new Promise(t=>setTimeout(t,e))}function Hf(e){try{return process.kill(e,0),!0}catch{return!1}}async function ud(e){try{const{stdout:t}=await Uf(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
34
+ `).filter(a=>a.trim()).map(a=>parseInt(a.trim(),10)).filter(a=>!isNaN(a)),s=[...r];for(const a of r){const o=await ud(a);s.push(...o)}return s}catch{return[]}}function ul(e,t,r){try{process.kill(e,t)}catch(s){r==null||r(`Error sending ${t} to process ${e}: ${s}`)}}async function Vf(e,t,r){const s=await ud(e);for(const a of s.reverse())await ul(a,t,r);await ul(e,t,r)}async function Tr(e,t=console.log,r=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let s=0;async function a(o,i){await Vf(e,o,t);for(let l=0;l<i;l++)if(await Jf(1e3),s+=1e3,!await Hf(e))return t(`Process tree ${e} successfully killed with ${o} after ${s/1e3} seconds.`),!0;return t(`Process tree still running after ${o}...`),!1}if(await a("SIGINT",5)||await a("SIGTERM",5))return!0;for(let o=0;o<r;o++)if(await a("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${s/1e3} seconds.`),!1}function Gf(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:Ph(),createdAt:t}}xh.config({quiet:!0});var pd=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(pd||{});class Kf extends bh{constructor(){super(...arguments),this.processes=new Map}register(t){const r=wh(),{process:s,type:a,name:o,metadata:i,parentId:l}=t,c={id:r,type:a,name:o,pid:s.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:l,children:[]};if(this.processes.set(r,{info:c,process:s}),l){const h=this.processes.get(l);h&&(h.info.children=h.info.children||[],h.info.children.push(r))}const p=(h,m)=>{this.handleProcessExit(r,h,m)},u=h=>{this.handleProcessError(r,h)};return s.on("exit",p),s.on("error",u),s.__cleanup=()=>{s.removeListener("exit",p),s.removeListener("error",u)},this.emit("processStarted",c),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const s=this.processes.get(t);if(!s)throw new Error(`Process not found: ${t}`);const{info:a,process:o}=s;if(a.state==="completed"||a.state==="failed"||a.state==="killed")return;if(r.shutdownChildren&&a.children&&a.children.length>0&&await Promise.all(a.children.map(l=>this.shutdown(l,r))),o.pid)try{await Tr(o.pid,l=>console.log(`[Process ${t}] ${l}`))}catch(l){console.warn(`Error killing process ${t}:`,l)}await new Promise(l=>setTimeout(l,100)),a.state==="running"&&(a.state="killed",a.endedAt=Date.now());const i=o.__cleanup;i&&i()}async shutdownByType(t,r={}){const s=this.listByType(t);await Promise.all(s.map(a=>this.shutdown(a.id,r)))}async shutdownAll(t={}){const r=this.listAll();await Promise.all(r.map(s=>this.shutdown(s.id,t)))}cleanupCompleted(t={}){const{retentionMs:r=6e4}=t,s=Date.now();for(const[a,o]of this.processes.entries()){const{info:i}=o;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&s-i.endedAt>r){const l=o.process.__cleanup;l&&l(),this.processes.delete(a)}}}handleProcessExit(t,r,s){const a=this.processes.get(t);if(!a)return;const{info:o}=a;o.endedAt=Date.now(),o.exitCode=r,o.signal=s,r===0?o.state="completed":s?o.state="killed":o.state="failed",this.emit("processExited",o)}handleProcessError(t,r){const s=this.processes.get(t);if(!s)return;const{info:a}=s;a.endedAt=Date.now(),a.state="failed",a.metadata={...a.metadata,error:r.message},this.emit("processExited",a)}}let Wa=null;function qf(){return Wa||(Wa=new Kf),Wa}const Qf={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function Zf({command:e,args:t,workingDir:r,outputOptions:s=Qf,processName:a,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${a}`},l=ft(e,t,{cwd:r,env:i});return qf().register({process:l,type:pd.Other,name:a,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const h=f=>{const g=se.join(r,"log.txt");V.appendFile(g,f,y=>{y&&console.log("Error writing to log file:",y)})},m=(f,g="")=>{const y=new Date().toLocaleString();return f.split(`
35
+ `).map(b=>b.trim()?`[${y}]${g} ${b}`:b).join(`
36
+ `)};l.stdout.on("data",function(f){const g=(f==null?void 0:f.toString())??"",y=m(g);s.stdoutToConsole&&console.log(y),s.stdoutToFile&&h(y+`
37
+ `),s.stdoutCallback&&s.stdoutCallback(g)}),l.stderr.on("data",function(f){const g=(f==null?void 0:f.toString())??"",y=m(g,"<STDERR>");s.stderrToConsole&&console.error(y),s.stderrToFile&&h(y+`
38
+ `),s.stderrCallback&&s.stderrCallback(g)}),l.on("exit",function(f){u(f)})}),process:l}}function Xf(e){const t=[];return Object.keys(e).forEach(r=>{const s=e[r];s!==void 0&&(typeof s=="boolean"?s&&t.push(`--${r}`):s!==null&&t.push(`--${r}`,String(s)))}),t}function eg({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:s}){const a=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
39
+ `);V.writeFileSync(`${e}/.env`,a);const o=Xf(r);return Zf({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:s,processName:"analyzer",env:t})}const tg="/tmp/codeyam/local-dev";function hd(e){return U.join(tg,e)}function md(e){return U.join(hd(e),"codeyam")}function It(e){return U.join(hd(e),"project")}function Lr(e){return U.join(md(e),"log.txt")}const ng=[".sync-metadata.json","__codeyamMocks__"];async function rg(e,t={}){const{port:r,silent:s=!0}=t,a=It(e);if(r)try{Ie(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}try{Ie(`lsof +D "${a}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}await new Promise(o=>setTimeout(o,500))}async function sg(e,t={}){const{killProcesses:r=!0,port:s,silent:a=!0}=t,o=It(e),i=[],l=[];if(!V.existsSync(o))return{removed:i,errors:l};r&&await rg(e,{port:s,silent:a});for(const c of ng){const p=U.join(o,c);if(V.existsSync(p))try{(await _e.stat(p)).isDirectory()?await _e.rm(p,{recursive:!0,force:!0}):await _e.unlink(p),i.push(c)}catch(u){l.push(`${c}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:l}}const ag=U.dirname(Vs(import.meta.url));function og(e){let t=e;for(;t!==U.dirname(t);){const r=U.join(t,"package.json");if(V.existsSync(r))try{if(JSON.parse(V.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=U.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function na(){const e=og(ag);return U.join(e,"analyzer-template")}function sr(e){return md(e)}function ig(){const e=na();return V.existsSync(U.join(e,".finalized"))}async function pl(e){const t=na(),r=sr(e),s=Date.now(),a=()=>`${((Date.now()-s)/1e3).toFixed(1)}s`;if(!V.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await _e.mkdir(U.dirname(r),{recursive:!0}),console.log(`[createAnalyzer] Starting rsync: ${t} → ${r}`),await Wf({sourcePath:t,destinationPath:r,silent:!0}),console.log(`[createAnalyzer] rsync completed (${a()})`),V.existsSync(U.join(r,"dist"))||(console.warn("[createAnalyzer] WARNING: dist/ not found after rsync — template may not be built. Attempting build..."),Ie("npm install --include=dev && npm run build",{cwd:r,stdio:"pipe",timeout:3e5}),console.log(`[createAnalyzer] npm install + build completed (${a()})`)),console.log(`[createAnalyzer] Done (${a()})`)}function ar(e,t,r,s){const a=sr(e);if(!V.existsSync(a))throw new Error(`Analyzer not found at ${a}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const o=void 0;return eg({absoluteCodeyamRootPath:a,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function lg(e){const t=na(),r=sr(e),s=U.join(t,".build-info.json"),a=U.join(r,".build-info.json");if(!V.existsSync(s))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!V.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!V.existsSync(a))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(V.readFileSync(s,"utf8")),i=JSON.parse(V.readFileSync(a,"utf8"));return o.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${o.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(o){return{isFresh:!1,reason:`Error reading build markers: ${o.message}`}}}async function Br(e,t){const r=sr(e);if(!V.existsSync(r)){t.update("Creating analyzer..."),await pl(e);return}const s=lg(e);s.isFresh||(t.update(`Updating analyzer (${s.reason})...`),await pl(e),t.update("Analyzer updated"))}async function Wo(e){await sg(e,{killProcesses:!1})}const cg=U.dirname(Vs(import.meta.url));function ra(){let e=cg;for(;e!==U.dirname(e);){const t=U.join(e,"package.json");if(V.existsSync(t))try{if(JSON.parse(V.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=U.dirname(e)}return null}function Vn(e){if(!V.existsSync(e))return null;try{return JSON.parse(V.readFileSync(e,"utf8"))}catch{return null}}function dg(){const e=ra();if(e){const t=[U.join(e,"src/webserver/build-info.json"),U.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const s=Vn(r);if(s!=null&&s.semanticVersion)return s.semanticVersion}}return"unknown"}function ug(){const e=ra();if(e){const t=U.join(e,"package.json");try{const r=JSON.parse(V.readFileSync(t,"utf8"));if(r.version)return r.version}catch{}}return"unknown"}const Uo=dg(),Ua=ug();function Jo(){if(Ua!=="unknown"&&Ua!=="0.1.0")return Ua;const e=ra();if(e)for(const t of[U.join(e,"src/webserver/build-info.json"),U.join(e,"codeyam-cli/src/webserver/build-info.json")]){const r=Vn(t);if(r!=null&&r.buildNumber)return`dev (build ${r.buildNumber})`}return"dev"}function fd(e){const t=ra();let r=null;if(t){const c=[U.join(t,"src/webserver/build-info.json"),U.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const p of c)if(r=Vn(p),r)break}const s=na(),a=U.join(s,".build-info.json"),o=Vn(a);let i=null;if(e){const c=sr(e),p=U.join(c,".build-info.json");i=Vn(p)}let l=!1;return o&&i?l=o.buildTime>i.buildTime:o&&!i&&e&&(l=!0),{cliVersion:Uo,webserverVersion:r,templateVersion:o,cachedAnalyzerVersion:i,isCacheStale:l}}function sa(e){const t=sr(e),r=U.join(t,".build-info.json"),s=Vn(r);return(s==null?void 0:s.version)??null}function Ho(){const e=Ne();return e?U.join(e,".codeyam","server.json"):null}function uk(e){const t=Ho();t&&V.writeFileSync(t,JSON.stringify(e,null,2))}function aa(){const e=Ho();if(!e||!V.existsSync(e))return null;try{const t=V.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function Vo(){const e=Ho();if(e)try{V.unlinkSync(e)}catch{}}function gd(e){try{return process.kill(e,0),!0}catch{return!1}}function yd(){try{const e=process.platform==="win32",r=Ie(e?'tasklist /FI "IMAGENAME eq node.exe" /FO CSV /NH':"ps aux | grep codeyam-server | grep -v grep",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();if(!r)return[];const s=[];if(e)for(const a of r.split(`
40
+ `)){const o=a.match(/"[^"]*","(\d+)"/);if(o){const i=parseInt(o[1],10);if(!isNaN(i))try{Ie(`wmic process where "ProcessId=${i}" get CommandLine /FORMAT:LIST`,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).includes("codeyam-server")&&s.push(i)}catch{}}}else for(const a of r.split(`
41
+ `)){const o=a.trim().split(/\s+/);if(o.length>=2){const i=parseInt(o[1],10);isNaN(i)||s.push(i)}}return s}catch{return[]}}function pk(){const e=aa();if(e)if(!gd(e.pid))Vo();else return{running:!0,state:e};const t=yd();return t.length>0?{running:!0,pids:t}:{running:!1}}function pg(e,t=5e3){if(e.length===0)return!0;const r=Date.now()+t;for(;Date.now()<r;){if(!e.some(a=>gd(a)))return!0;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100)}return!1}function hk(){let e=!1;const t=[],r=aa();if(r){try{process.kill(r.pid,"SIGTERM"),t.push(r.pid),e=!0}catch{}Vo()}const s=yd();for(const a of s)try{process.kill(a,"SIGTERM"),t.includes(a)||t.push(a),e=!0}catch{}return pg(t),e}function mk(e,t,r=10,s=10){if(t(e))return e;for(let a=1;a<=s;a++){const o=e+a*r;if(t(o))return o}throw new Error(`Could not find a free port starting from ${e} (tried ${s} candidates)`)}function fk(e){try{return Ie(`lsof -ti:${e}`,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}),!1}catch{return!0}}const hg="/assets/globals-BsGHu8WX.css";function hl({text:e,subtext:t,linkText:r,linkTo:s}){const[a,o]=P(!1);return a?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:d("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),d("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(Ce,{to:s,className:"shrink-0 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 transition-colors",children:r})]}),n("button",{type:"button",onClick:()=>o(!0),className:"shrink-0 ml-4 p-1 rounded text-blue-600 hover:text-blue-800 hover:bg-blue-100 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}function mg({version:e}){return n("div",{className:"px-6 sm:px-12 pb-8 mt-auto pt-8",children:d("div",{className:"border-t border-cygray-30 pt-6 flex flex-wrap justify-between items-center gap-4",children:[d("div",{className:"flex items-center gap-3",children:[n("span",{className:"font-mono text-sm font-semibold tracking-widest text-cyblack-100",children:"CODEYAM"}),e&&n("span",{className:"font-mono text-xs text-gray-400",children:e})]}),d("div",{className:"flex items-center gap-4 font-mono text-xs uppercase tracking-widest",children:[n("a",{href:"https://blog.codeyam.com/",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Read the Blog"}),n("span",{className:"text-cygray-30",children:"|"}),n("a",{href:"https://discord.gg/x4uAgaRdwF",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Join Discord"})]})]})})}function fg({serverVersion:e}){const[t,r]=P("stale"),[s,a]=P(null),o=async()=>{r("restarting"),a(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let l=0;const c=30,p=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}l++,l<c?setTimeout(()=>void u(),p):(a("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void u(),500)}catch(i){a(i instanceof Error?i.message:"Failed to restart server"),r("stale")}};return n("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:n("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-amber-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),d("div",{className:"flex-1",children:[t==="stale"&&d(we,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Dashboard server is out of date"}),d("p",{className:"text-xs text-amber-700 mt-0.5",children:["Server version: ",e,". A newer version of CodeYam CLI is installed. Restart the server to get the latest features."]}),s&&n("p",{className:"text-xs text-red-600 mt-1",children:s})]}),t==="restarting"&&d(we,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Restarting server..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Please wait while the server restarts."})]}),t==="reconnecting"&&d(we,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Reconnecting..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Waiting for the server to come back online."})]})]}),t==="stale"&&n("button",{type:"button",onClick:()=>void o(),className:"shrink-0 px-4 py-2 bg-amber-600 text-white text-sm font-medium rounded hover:bg-amber-700 transition-colors cursor-pointer",children:"Restart Server"}),(t==="restarting"||t==="reconnecting")&&d("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 text-amber-700 text-sm",children:[d("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t==="restarting"?"Stopping...":"Reconnecting..."]})]})})})}function ct({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:s="",duration:a=2e3,ariaLabel:o,icon:i=!1,iconSize:l=14}){const[c,p]=P(!1),u=ce(()=>{navigator.clipboard.writeText(e).then(()=>{p(!0),setTimeout(()=>p(!1),a)}).catch(h=>{console.error("Failed to copy:",h)})},[e,a]);return n("button",{onClick:u,className:`cursor-pointer ${s}`,disabled:c,"aria-label":o||(c?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?c?n(kt,{size:l,className:"text-green-500"}):n($t,{size:l}):c?r:t})}function gg({currentVersion:e,latestVersion:t}){const[r,s]=P(!1);if(r)return null;const a="npm install -g @codeyam/codeyam-cli@latest && codeyam stop && codeyam";return n("div",{className:"bg-emerald-100 border rounded border-emerald-700 shadow-sm mx-6 mt-6",children:d("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-emerald-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M7 11l5-5m0 0l5 5m-5-5v12"})})}),d("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-emerald-900",children:"A new version of CodeYam CLI is available"}),d("p",{className:"text-xs text-emerald-700 mt-0.5",children:["Current: ",e," → Latest: ",t]})]}),d("div",{className:"shrink-0 flex items-center gap-2",children:[n("code",{className:"text-xs bg-emerald-200 text-emerald-900 px-2 py-1.5 rounded font-mono",children:a}),n(ct,{content:a,label:"Copy",copiedLabel:"Copied!",className:"px-3 py-1.5 bg-emerald-600 text-white text-xs font-medium rounded hover:bg-emerald-700 transition-colors"})]})]}),n("button",{type:"button",onClick:()=>s(!0),className:"shrink-0 ml-4 p-1 rounded text-emerald-600 hover:text-emerald-800 hover:bg-emerald-200 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}let br=null,cs=0;const yg=3600*1e3;function xg(e,t){const r=e.split(".").map(Number),s=t.split(".").map(Number);for(let a=0;a<Math.max(r.length,s.length);a++){const o=r[a]??0,i=s[a]??0;if(isNaN(o)||isNaN(i))return!1;if(o>i)return!0;if(o<i)return!1}return!1}async function bg(){const e=Jo();if(br&&Date.now()-cs<yg)return br;try{const t=new AbortController,r=setTimeout(()=>t.abort(),5e3),s=await fetch("https://registry.npmjs.org/@codeyam/codeyam-cli/latest",{signal:t.signal});if(clearTimeout(r),!s.ok){const l={updateAvailable:!1,latestVersion:null,currentVersion:e};return br=l,cs=Date.now(),l}const o=(await s.json()).version;if(!o){const l={updateAvailable:!1,latestVersion:null,currentVersion:e};return br=l,cs=Date.now(),l}const i={updateAvailable:xg(o,e),latestVersion:o,currentVersion:e};return br=i,cs=Date.now(),i}catch{return{updateAvailable:!1,latestVersion:null,currentVersion:e}}}function Bs(e){return U.join(e,".codeyam","queue.json")}function Cr(e){const t=Bs(e);if(!V.existsSync(t))return{paused:!1,jobs:[]};try{const r=V.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function wg(e,t){const r=Bs(e),s=U.dirname(r);V.existsSync(s)||V.mkdirSync(s,{recursive:!0});try{V.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(a){throw console.error("Failed to save queue state:",a),a}}const Us=class Us extends Fr{constructor(t){super(),this.watcher=null,this.debounceTimers=new Map,this.DEBOUNCE_MS=300,this.options=t}start(){try{this.watcher=ge.watch(this.options.projectRootPath,{recursive:!0},(t,r)=>{if(!r||!/\.(ts|tsx|js|jsx|css|scss|json|svg|html)$/.test(r)||Us.IGNORED_DIRS.some(a=>r.includes(a+"/")||r.includes(a+"\\")))return;const s=this.debounceTimers.get(r);s&&clearTimeout(s),this.debounceTimers.set(r,setTimeout(()=>{this.debounceTimers.delete(r),this.syncFile(r)},this.DEBOUNCE_MS))}),console.log(`[InteractiveSyncWatcher] Watching ${this.options.projectRootPath} for changes`)}catch(t){console.error("[InteractiveSyncWatcher] Failed to start:",t)}}syncFile(t){const r=se.join(this.options.projectRootPath,t),s=se.join(this.options.tmpProjectPath,t);try{if(!ge.existsSync(r)){ge.existsSync(s)&&(ge.unlinkSync(s),console.log(`[InteractiveSyncWatcher] Removed: ${t}`));return}const a=se.dirname(s);ge.existsSync(a)||ge.mkdirSync(a,{recursive:!0}),ge.copyFileSync(r,s);const o=se.basename(t);console.log(`[InteractiveSyncWatcher] Synced: ${t}`);const i={type:"file-synced",fileName:o,filePath:t,timestamp:Date.now()};this.emit("sync",i)}catch(a){console.error(`[InteractiveSyncWatcher] Error syncing ${t}:`,a);const o={type:"error",fileName:se.basename(t),filePath:t,timestamp:Date.now()};this.emit("sync",o)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null);for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),console.log("[InteractiveSyncWatcher] Stopped")}};Us.IGNORED_DIRS=["node_modules",".git",".codeyam","__codeyamMocks__",".next","dist","build",".turbo",".vercel","coverage",".cache"];let co=Us,vg=class extends Fr{constructor(){super(),this.setMaxListeners(20)}emitFileSynced(t,r){this.emit("event",{type:"file-synced",fileName:t,filePath:r,timestamp:Date.now()})}emitError(t,r){this.emit("event",{type:"sync-error",fileName:t,filePath:r,timestamp:Date.now()})}};const uo="__codeyam_dev_mode_event_emitter__";globalThis[uo]||(globalThis[uo]=new vg);const ml=globalThis[uo],po=new Map;async function Ng(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await Sg(e,t,r);else if(e.type==="baseline")await Cg(e,t,r);else if(e.type==="recapture")await kg(e,t,r);else if(e.type==="capture-only")await _g(e,t,r);else if(e.type==="debug-setup")await Eg(e,t,r);else if(e.type==="interactive-start")await Ag(e,t,r);else if(e.type==="interactive-stop")await Pg(e,t,r);else throw new Error(`Unknown job type: ${e.type}`);console.log(`[Queue] Job ${e.id} completed successfully`)}catch(s){throw console.error(`[Queue] Job ${e.id} failed:`,s),s}}async function Sg(e,t,r){var b,w,v,N;const{projectSlug:s,commitSha:a,entityShas:o}=e;if(!a)throw new Error("Analysis job missing commitSha");const i=o||[],l=e.onlyDataStructure,c=Lr(s),p=S=>{const C=`CodeYam Log Level 1: ${S}`;console.log(`[Queue] ${S}`);try{V.mkdirSync(U.dirname(c),{recursive:!0}),V.appendFileSync(c,`[${new Date().toLocaleString()}] ${C}
42
+
43
+ `)}catch{}},{project:u}=await De(s);p("Preparing project cache..."),await Wo(s),p("Preparing simulation engine..."),await Br(s,{update:S=>p(S)});const h=sa(s),m={...await ln(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:cn(),...!l&&i.length>0?{ENTITY_SHAS:i.join(",")}:{},...l?{ONLY_DATA_STRUCTURE:"true"}:{},...h?{ANALYZER_VERSION:h}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},f=(w=(b=u.metadata)==null?void 0:b.webapps)==null?void 0:w[0];if(!f)throw new Error("No webapps found in project metadata");const g={packageManager:((v=u.metadata)==null?void 0:v.packageManager)||"npm",absoluteProjectRootPath:It(s),port:0,noServer:!0,framework:f.framework,...l?{}:{orchestrateCapture:"local-sequential"}},y=ar(s,m,g),x=S=>{try{return process.kill(S,0),!0}catch{return!1}};await nn({commitSha:a,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((N=e.filePaths)==null?void 0:N.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:y.process.pid}}),r==null||r.notifyChange("commit");try{try{const S=new Promise((C,A)=>setTimeout(()=>A(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([y.promise,S]),await nn({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await nn({commitSha:a,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(C=>setTimeout(C,2e3))}finally{if(y.process.pid)try{x(y.process.pid)&&await Tr(y.process.pid,()=>{})}catch{}}}catch(S){if(console.error(`[Queue] Analysis job ${e.id} failed:`,S),y.process.pid&&x(y.process.pid))try{await Tr(y.process.pid,()=>{})}catch{}try{await nn({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:S instanceof Error?S.message:String(S)}}),r==null||r.notifyChange("commit")}catch(C){console.error("[Queue] Failed to update commit metadata after job failure:",C)}throw S}}async function Cg(e,t,r){var m,f,g;const{projectSlug:s,commitSha:a}=e;if(!a)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${s}`);const{project:o}=await De(s);await Wo(s),await Br(s,{update:y=>console.log(`[Queue] ${y}`)});const i=sa(s),l={...await ln(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:cn(),...i?{ANALYZER_VERSION:i}:{}},c=(f=(m=o.metadata)==null?void 0:m.webapps)==null?void 0:f[0];if(!c)throw new Error("No webapps found in project metadata");const p={packageManager:((g=o.metadata)==null?void 0:g.packageManager)||"npm",absoluteProjectRootPath:It(s),port:0,noServer:!0,framework:c.framework,orchestrateCapture:"local-sequential"},u=ar(s,l,p),h=y=>{try{return process.kill(y,0),!0}catch{return!1}};await nn({commitSha:a,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:u.process.pid}}),r==null||r.notifyChange("commit");try{const y=new Promise((x,b)=>setTimeout(()=>b(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([u.promise,y]),await nn({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${s}`),await new Promise(x=>setTimeout(x,2e3))}finally{if(u.process.pid)try{h(u.process.pid)&&await Tr(u.process.pid,()=>{})}catch{}}}async function kg(e,t,r){var f,g,y,x;const{projectSlug:s,analysisId:a,scenarioId:o,defaultWidth:i}=e;if(!a)throw new Error("Recapture job missing analysisId");const l=await Vt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:b}=await import("./index-rV_xLS1u.js"),w=b(),v=await w.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let N={};v!=null&&v.metadata&&(typeof v.metadata=="string"?N=JSON.parse(v.metadata):N=v.metadata),N.defaultWidth=i,await w.updateTable("entities").set({metadata:JSON.stringify(N)}).where("sha","=",l.entitySha).execute()}await nr(a,b=>{if(b.readyToBeCaptured=!0,b.scenarios)for(const w of b.scenarios)(!o||w.name===o)&&(delete w.finishedAt,delete w.startedAt,delete w.screenshotStartedAt,delete w.screenshotFinishedAt,delete w.interactiveStartedAt,delete w.interactiveFinishedAt,delete w.error,delete w.errorStack);delete b.finishedAt});const{project:c}=await De(s);await Br(s,{update:b=>console.log(`[Queue] ${b}`)});const p=sa(s),u={...await ln(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:cn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...p?{ANALYZER_VERSION:p}:{}},h={packageManager:((f=c.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:It(s),port:void 0,noServer:!0,framework:((x=(y=(g=c.metadata)==null?void 0:g.webapps)==null?void 0:y[0])==null?void 0:x.framework)??nt.Next,orchestrateCapture:"local-sequential"},m=ar(s,u,h);try{await m.promise}finally{try{m.process.kill("SIGTERM")}catch{}}}async function _g(e,t,r){var f,g,y,x;const{projectSlug:s,analysisId:a,scenarioId:o,defaultWidth:i}=e;if(!a)throw new Error("Capture-only job missing analysisId");const l=await Vt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:b}=await import("./index-rV_xLS1u.js"),w=b(),v=await w.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let N={};v!=null&&v.metadata&&(typeof v.metadata=="string"?N=JSON.parse(v.metadata):N=v.metadata),N.defaultWidth=i,await w.updateTable("entities").set({metadata:JSON.stringify(N)}).where("sha","=",l.entitySha).execute()}await nr(a,b=>{if(b.readyToBeCaptured=!0,b.scenarios)for(const w of b.scenarios)(!o||w.name===o)&&(delete w.finishedAt,delete w.startedAt,delete w.screenshotStartedAt,delete w.screenshotFinishedAt,delete w.interactiveStartedAt,delete w.interactiveFinishedAt,delete w.error,delete w.errorStack);delete b.finishedAt});const{project:c}=await De(s);await Br(s,{update:b=>console.log(`[Queue] ${b}`)});const p=sa(s);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await ln(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:cn(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...p?{ANALYZER_VERSION:p}:{}},h={packageManager:((f=c.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:It(s),port:void 0,noServer:!0,fast:!0,framework:((x=(y=(g=c.metadata)==null?void 0:g.webapps)==null?void 0:y[0])==null?void 0:x.framework)??nt.Next,orchestrateCapture:"local-sequential"},m=ar(s,u,h);try{await m.promise}finally{try{m.process.kill("SIGTERM")}catch{}}}async function Eg(e,t,r){var m,f,g,y;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Debug setup job missing analysisId");const i=await Vt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:l}=await De(s);await Wo(s),await Br(s,{update:x=>console.log(`[Queue] ${x}`)});const c={...await ln(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:cn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,PREP_ONLY:"true"};o&&(c.SCENARIO_IDS=o);const p={packageManager:((m=l.metadata)==null?void 0:m.packageManager)||"npm",absoluteProjectRootPath:It(s),port:void 0,noServer:!1,framework:((y=(g=(f=l.metadata)==null?void 0:f.webapps)==null?void 0:g[0])==null?void 0:y.framework)||nt.Next},h=await ar(s,c,p).promise;if(h!==0)throw new Error(`Prep process exited with code ${h}`)}async function Ag(e,t,r){var x,b,w,v;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Interactive start job missing analysisId");const i=await Vt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:l}=await De(s),c={...await ln(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:cn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,INTERACTIVE_MODE:"true"};o&&(c.INITIAL_SCENARIO_ID=o),i.scenarios&&i.scenarios.length>0&&(c.SCENARIO_IDS=i.scenarios.map(N=>N.id).join(","));const p=It(s),u=se.join(p,".next","dev","lock");if(ge.existsSync(u)){console.log("[Queue] Found stale .next/dev/lock, cleaning up old processes");try{const N=Ie(`pgrep -f ${JSON.stringify(p)} 2>/dev/null || true`,{encoding:"utf-8"}).trim();if(N)for(const S of N.split(`
44
+ `).filter(Boolean))try{process.kill(parseInt(S,10),"SIGTERM"),console.log(`[Queue] Killed stale process ${S}`)}catch{}}catch{}try{ge.unlinkSync(u),console.log("[Queue] Removed stale lock file")}catch{}}const h=ge.existsSync(p)&&ge.existsSync(se.join(p,"package.json")),m={packageManager:((x=l.metadata)==null?void 0:x.packageManager)||"npm",absoluteProjectRootPath:p,port:void 0,noServer:!1,fast:h,framework:((v=(w=(b=l.metadata)==null?void 0:b.webapps)==null?void 0:w[0])==null?void 0:v.framework)||nt.Next};await nr(a,N=>{N.readyToBeCaptured=!0});const f=ar(s,c,m);await Zc(a,N=>{N.interactiveMode={pid:f.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${a}, PID: ${f.process.pid}`);const g=It(s),y=new co({projectRootPath:t,tmpProjectPath:g});y.on("sync",N=>{N.type==="file-synced"?ml.emitFileSynced(N.fileName,N.filePath):N.type==="error"&&ml.emitError(N.fileName,N.filePath)}),y.start(),po.set(a,y),console.log(`[Queue] File sync watcher started for analysis ${a}`)}async function Pg(e,t,r){var p;const{projectSlug:s,analysisId:a}=e;if(!a)throw new Error("Interactive stop job missing analysisId");const o=await Vt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!o)throw new Error(`Analysis ${a} not found`);const i=(p=o.metadata)==null?void 0:p.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${a}`);return}const l=po.get(a);l&&(l.stop(),po.delete(a),console.log(`[Queue] File sync watcher stopped for analysis ${a}`));const c=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${a}, killing PID: ${c}`);try{try{process.kill(c,0)}catch{console.log(`[Queue] Process ${c} already exited`);return}await Tr(c,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${c}`)}catch(u){throw console.error(`[Queue] Failed to kill process ${c}:`,u),u}finally{await Zc(a,u=>{u.interactiveMode=null})}}class jg{constructor(t,r){this.processing=!1,this.completionCallbacks=new Map,this.completedJobs=new Map,this.projectRoot=t,this.state={paused:!1,jobs:[]},r&&(typeof r=="function"?this.notifier={notifyChange:()=>r()}:this.notifier=r)}start(){this.state=Cr(this.projectRoot),this.state.currentlyExecuting&&(console.log(`[Queue] Clearing stale currentlyExecuting job from previous session: ${this.state.currentlyExecuting.id}`),this.state.currentlyExecuting=void 0,this.save()),this.state.jobs.length>0?(this.state.paused=!0,this.save(),console.log(`[Queue] Found ${this.state.jobs.length} queued jobs from previous session (paused)`)):this.state.paused=!1}enqueue(t){const r=t.commitSha||To(),s={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(s),this.save(),console.log(`[Queue] Enqueued job ${r} (${s.type})`);const a=new Promise((o,i)=>{this.completionCallbacks.set(r,l=>{l?i(l):o()})});return this.state.paused||this.processNext().catch(o=>{console.error("[Queue] ERROR in processNext():",o)}),{jobId:r,completion:a}}resume(){console.log("[Queue] Resuming queue"),this.state.paused=!1,this.save(),this.processNext()}pause(){console.log("[Queue] Pausing queue"),this.state.paused=!0,this.save()}getState(){return{...this.state}}getJobResult(t){return this.completedJobs.get(t)}removeJob(t){const r=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(a=>a.id!==t);const s=this.state.jobs.length<r;if(s){console.log(`[Queue] Removed job ${t}`),this.save();const a=this.completionCallbacks.get(t);a&&(setImmediate(()=>a(new Error("Job cancelled by user"))),this.completionCallbacks.delete(t))}else console.log(`[Queue] Job ${t} not found in queue`);return s}clearQueue(){const t=this.state.jobs.length;return t===0?0:(this.state.jobs.forEach(r=>{const s=this.completionCallbacks.get(r.id);s&&(setImmediate(()=>s(new Error("Job cancelled by user"))),this.completionCallbacks.delete(r.id))}),this.state.jobs=[],console.log(`[Queue] Cleared ${t} jobs`),this.save(),t)}reorderJob(t,r){const s=this.state.jobs.findIndex(i=>i.id===t);if(s===-1)return console.log(`[Queue] Job ${t} not found in queue`),!1;const a=r==="up"?s-1:s+1;if(a<0||a>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const o=this.state.jobs[s];return this.state.jobs[s]=this.state.jobs[a],this.state.jobs[a]=o,console.log(`[Queue] Moved job ${t} ${r} (position ${s} -> ${a})`),this.save(),!0}async processNext(){if(this.state.paused||this.processing)return;if(this.state.jobs.length===0){console.log("[Queue] No jobs to process");return}this.processing=!0;const t=this.state.jobs[0];console.log(`[Queue] Starting job ${t.id} (${t.type})`);try{this.state.currentlyExecuting=this.state.jobs.shift(),this.save(),await Ng(t,this.projectRoot,this.notifier),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"success",completedAt:new Date().toISOString()});const r=this.completionCallbacks.get(t.id);r&&(r(),this.completionCallbacks.delete(t.id)),console.log(`[Queue] Job ${t.id} completed successfully`)}catch(r){console.error(`[Queue] Job ${t.id} failed:`,r),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"error",error:(r==null?void 0:r.message)||"Unknown error",completedAt:new Date().toISOString()});const s=this.completionCallbacks.get(t.id);s&&(s(r),this.completionCallbacks.delete(t.id))}finally{this.processing=!1,!this.state.paused&&this.state.jobs.length>0&&setImmediate(()=>void this.processNext())}}save(){wg(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class Tg{constructor(t,r,s=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=s}start(){const t=Bs(this.projectRoot);if(!V.existsSync(t)){console.log("[QueueFileWatcher] Queue file does not exist yet, will start watching when created"),this.watchDirectory();return}this.watchFile(t)}watchDirectory(){const t=Bs(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=V.watch(r,(s,a)=>{a==="queue.json"&&(this.stop(),this.watchFile(t),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(s){console.error("[QueueFileWatcher] Failed to watch directory:",s)}}watchFile(t){try{this.watcher=V.watch(t,r=>{r==="change"&&this.notifyChange()}),console.log("[QueueFileWatcher] Watching queue.json for changes")}catch(r){console.error("[QueueFileWatcher] Failed to watch queue file:",r)}}notifyChange(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.onChange(),this.debounceTimer=null},this.debounceMs)}stop(){this.watcher&&(this.watcher.close(),this.watcher=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}class Mg{constructor(t,r,s){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=s,this.cachedState=Cr(r)}start(){this.cachedState=Cr(this.projectRoot),console.log(`[ProxyQueue] Connected to background server at ${this.serverInfo.url}`),console.log(`[ProxyQueue] Current queue has ${this.cachedState.jobs.length} jobs`),this.fileWatcher=new Tg(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,s;const a=new Promise((i,l)=>{r=i,s=l}),o=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),s(i)}),{jobId:o,completion:a}}async enqueueRemote(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to enqueue: ${r.status} ${s}`)}return r.json()}resume(){console.log("[ProxyQueue] Sending resume command to background server"),this.sendAction("resume").catch(t=>{console.error("[ProxyQueue] Failed to resume:",t)})}pause(){console.log("[ProxyQueue] Sending pause command to background server"),this.sendAction("pause").catch(t=>{console.error("[ProxyQueue] Failed to pause:",t)})}async sendAction(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to ${t}: ${r.status} ${s}`)}this.refreshState()}getState(){return this.cachedState=Cr(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=Cr(this.projectRoot),this.onStateChange&&this.onStateChange()}async isServerAlive(){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),s=await fetch(`${this.serverInfo.url}/api/health`,{signal:t.signal});return clearTimeout(r),s.ok}catch{return!1}}getServerInfo(){return{...this.serverInfo}}stop(){this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null)}}function $g(e){const t=U.join(e,".codeyam","server.json");if(!V.existsSync(t))return null;try{const r=V.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function Ig(e){try{return process.kill(e,0),!0}catch{return!1}}async function Rg(e){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),s=await fetch(`${e}/api/health`,{signal:t.signal});return clearTimeout(r),s.ok}catch{return!1}}async function Dg(e){const t=$g(e);return!t||!Ig(t.pid)||!await Rg(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class Fg extends Fr{constructor(){super();ut(this,"watcher",null);ut(this,"dbPath",null);ut(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=cn();const{default:r}=await import("chokidar"),s=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=r.watch(s,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",a=>{const o=Date.now(),i=new Date(o).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${a}`),console.log(`[dbNotifier] Timestamp: ${i} (${o})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:o})}).on("error",a=>{console.error("Database watcher error:",a),this.emit("error",a)}),this.isWatching=!0}catch(r){console.error("Failed to start database watcher:",r),this.emit("error",r)}}notifyChange(r="unknown"){const s=Date.now(),a=new Date(s).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${r}`),console.log(`[dbNotifier] Timestamp: ${a} (${s})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:r,timestamp:s})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const Nt=new Fg;let vn=null,kr=null;async function Og(){if(!vn){if(kr){await kr;return}kr=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||Xc()||process.cwd();if(Tf(e),console.log(`[GlobalQueue] Project root: ${e}`),await Je(),process.env.NODE_ENV==="development")try{const r=se.join(e,".codeyam","config.json"),a=JSON.parse(await ge.promises.readFile(r,"utf8")).projectSlug;a&&(await Gn({projectSlug:a,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),console.log("[GlobalQueue] Labs & Simulations auto-enabled for dev mode"))}catch(r){console.warn("[GlobalQueue] Could not auto-enable labs:",r)}const t=await Dg(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new Mg(t,e,()=>{Nt.notifyChange("unknown")});await r.start(),vn=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new jg(e,Nt);await r.start(),vn=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await kr}}async function Gt(){return vn||await Og(),vn}function Lg(){return vn||(kr&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const Bg=()=>[{rel:"stylesheet",href:hg},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}],zg={currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[],isServerOutOfDate:!1,serverVersion:"unknown",npmUpdate:null,labs:null,simulationsEnabled:!1,isSimulationsReady:!1,isAdmin:!1,editorMode:!1,displayVersion:Jo()};async function Yg({request:e,context:t}){var r,s,a,o,i,l,c,p,u,h,m;try{const f=e.signal,g=()=>{if(f.aborted)throw new Response(null,{status:499})};g();const y=Ne()||process.cwd(),[x,b,w]=await Promise.all([Ye(),ta(y),bg().catch(()=>null)]);if(!x)throw new Error("Project slug not found");const{project:v,branch:N}=await De(x);g();const S=await Ds({projectId:v.id,branchId:N.id,limit:20,skipRelations:!0});g();const C=S.length>0?S[0]:null,A=t.analysisQueue||Lg(),_=A==null?void 0:A.getState();g();const E=await Promise.all(((_==null?void 0:_.jobs)||[]).map(async J=>{var oe;const te=await ls(J.entityShas||[]);return te.length===0&&((oe=J.entityShas)!=null&&oe.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",J.id),{...J,entities:te}}));let R=null;if(_!=null&&_.currentlyExecuting){const J=_.currentlyExecuting,te=await ls(J.entityShas||[]);te.length===0&&((r=J.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",J.id),R={...J,entities:te}}const D=R?E.filter(J=>J.id!==R.id):E;let T=((a=(s=C==null?void 0:C.metadata)==null?void 0:s.currentRun)==null?void 0:a.currentEntityShas)||[];if(T.length===0){const J=((o=C==null?void 0:C.metadata)==null?void 0:o.historicalRuns)||[];if(J.length>0){const oe=[...J].sort((de,ue)=>{const me=de.archivedAt||de.createdAt||"";return(ue.archivedAt||ue.createdAt||"").localeCompare(me)})[0];if(oe){const de=oe.analysisCompletedAt||oe.createdAt;if(de){const ue=new Date(de).getTime(),Se=Date.now()-1440*60*1e3;ue>Se&&(T=oe.currentEntityShas||[])}}}}const $=await ls(T),L=[];b.ANTHROPIC_API_KEY&&L.push("ANTHROPIC_API_KEY"),b.GROQ_API_KEY&&L.push("GROQ_API_KEY"),b.OPENAI_API_KEY&&L.push("OPENAI_API_KEY"),b.OPENROUTER_API_KEY&&L.push("OPENROUTER_API_KEY"),g();const B=[];for(const J of S){const te=((i=J.metadata)==null?void 0:i.historicalRuns)||[];for(const oe of te)B.push(oe)}B.sort((J,te)=>{const oe=J.archivedAt||J.analysisCompletedAt||J.createdAt||"";return(te.archivedAt||te.analysisCompletedAt||te.createdAt||"").localeCompare(oe)});const H=new Set(((l=R==null?void 0:R.entities)==null?void 0:l.map(J=>J.sha))||[]),O=B.filter(J=>!(J.currentEntityShas||[]).some(oe=>H.has(oe))).slice(0,3),W=new Set;for(const J of O)for(const te of J.currentEntityShas||[])W.add(te);const I=await ls(Array.from(W)),j=new Map;for(const J of I)j.set(J.sha,J);const k=O.map(J=>({...J,entities:(J.currentEntityShas||[]).map(te=>j.get(te)).filter(te=>te!=null)})),Y=aa(),G=(Y==null?void 0:Y.cliVersion)??"unknown",Q=G!=="unknown"&&G!==Uo,K=((p=(c=v.metadata)==null?void 0:c.labs)==null?void 0:p.simulations)??!1,F=K?ig():!1,M=((u=v.metadata)==null?void 0:u.editorMode)??!1,z={currentRun:(h=C==null?void 0:C.metadata)==null?void 0:h.currentRun,projectSlug:x,currentEntities:$,availableAPIKeys:L,queuedJobCount:D.length,queueJobs:D,currentlyExecuting:R,historicalRuns:k,isServerOutOfDate:Q,serverVersion:G,npmUpdate:w!=null&&w.updateAvailable&&w.latestVersion?{latestVersion:w.latestVersion,currentVersion:w.currentVersion}:null,labs:((m=v.metadata)==null?void 0:m.labs)??null,simulationsEnabled:K,isSimulationsReady:F,isAdmin:!!process.env.CODEYAM_ADMIN,editorMode:M,displayVersion:Jo()};return re(z)}catch(f){return f instanceof Response&&f.status===499||console.error("Failed to load root data:",f),re(zg)}}function Wg(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:s,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:l,isServerOutOfDate:c,serverVersion:p,npmUpdate:u,labs:h,simulationsEnabled:m,isSimulationsReady:f,isAdmin:g,editorMode:y,displayVersion:x}=st(),{toasts:b,closeToast:w}=Oo(),v=Ut(),N=fe(v),S=Rr(),C=fe(S.pathname);ae(()=>{N.current=v},[v]),ae(()=>{C.current=S.pathname},[S.pathname]);const A=S.pathname.startsWith("/entity/")&&S.pathname.includes("/edit/")||S.pathname.startsWith("/dev/")||S.pathname.startsWith("/editor"),_=S.pathname.includes("/fullscreen")||S.pathname.startsWith("/editor");return ae(()=>{let E=null,R=null,D=0;function T(){E||(E=new EventSource("/api/events"),E.addEventListener("message",B=>{const H=JSON.parse(B.data);(H.type==="queue"||H.type==="db-change")&&H.type;const q=Fh(C.current),O=Oh({now:Date.now(),lastRevalidation:D,throttleMs:q});O==="immediate"?(N.current.revalidate(),D=Date.now()):(R&&clearTimeout(R),R=setTimeout(()=>{N.current.revalidate(),D=Date.now(),R=null},O.delayMs))}),E.addEventListener("error",()=>{}))}function $(){R&&(clearTimeout(R),R=null),E&&(E.close(),E=null)}function L(){document.hidden?$():(T(),N.current.revalidate())}return document.hidden||T(),document.addEventListener("visibilitychange",L),()=>{document.removeEventListener("visibilitychange",L),$()}},[]),d(we,{children:[d("div",{className:`min-h-screen ${A?"":"grid"} bg-cygray-10`,style:A?void 0:{gridTemplateColumns:"65px minmax(0, 1fr)"},children:[!A&&n(Uh,{labs:h,isAdmin:g,editorMode:y}),d("div",{className:"max-h-screen overflow-auto bg-cygray-10 flex flex-col min-h-screen",children:[c&&n(fg,{serverVersion:p}),u&&u.currentVersion&&n(gg,{currentVersion:u.currentVersion,latestVersion:u.latestVersion}),m&&!y&&s.length===0&&n(hl,{text:"No AI API keys configured. Please provide an AI API key at your earliest convenience.",subtext:"An API key is required for stable, frequent use of CodeYam",linkText:"Configure API Keys",linkTo:"/settings"}),m&&!y&&!f&&n(hl,{text:"Simulations enabled but not yet configured",subtext:"Run /codeyam-setup in Claude Code to install the analyzer and configure your dev server",linkText:"View Labs",linkTo:"/labs"}),n("div",{className:"flex-1",children:n(Pc,{})}),n(mg,{version:x})]})]}),n(Vh,{toasts:b,onClose:w}),!_&&m&&n(Gh,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:l})]})}const Ug=et(function(){return d("html",{lang:"en",children:[d("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(yp,{}),n(xp,{})]}),d("body",{children:[n(Jh,{children:n(Yh,{children:n(Wg,{})})}),n(bp,{}),n(wp,{})]})]})});function Jg(e){if(e instanceof TypeError&&/fetch/i.test(e.message)||e instanceof Error&&/fetch/i.test(e.message))return!0;const t=String(e);return/failed to fetch|fetch.*failed|load.*chunk/i.test(t)}const Hg=vp(function(){const t=Np(),r=!Ia(t)&&Jg(t),s=Ia(t)?t.status:500,a=Ia(t)?t.statusText||"Server Error":"Something went wrong";return d("html",{lang:"en",children:[d("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),d("title",{children:[s," - CodeYam"]})]}),n("body",{style:{margin:0,fontFamily:'"IBM Plex Sans", system-ui, -apple-system, sans-serif',backgroundColor:"#1e1e1e",color:"#ffffff",minHeight:"100vh",display:"flex",alignItems:"center"},children:d("div",{style:{maxWidth:700,width:"100%",padding:"64px 80px"},children:[d("div",{style:{fontFamily:'"IBM Plex Mono", monospace',fontSize:32,fontWeight:400,color:"#8E8E8E",lineHeight:1,marginBottom:12},children:["<",s,">"]}),n("h1",{style:{fontSize:42,fontWeight:600,margin:"0 0 20px",color:"#ffffff",lineHeight:1.2},children:r?"Something went wrong :(":a}),r?d("div",{children:[n("p",{style:{fontSize:16,color:"#8E8E8E",lineHeight:1.7,margin:"0 0 28px",maxWidth:480},children:"It looks like the CodeYam server is no longer running. This usually happens when the terminal session that started it was closed."}),d("p",{style:{fontSize:16,color:"#ffffff",margin:0,lineHeight:1.7,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["Run"," ",d("button",{id:"copy-cmd-btn",type:"button",style:{display:"inline-flex",alignItems:"center",gap:8,backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:6,padding:"6px 12px",fontFamily:'"IBM Plex Mono", monospace',fontSize:13,color:"#ffffff",letterSpacing:"0.05em",textTransform:"uppercase",cursor:"pointer",minWidth:172,justifyContent:"center"},children:[n("span",{id:"copy-cmd-label",children:"codeyam editor"}),d("svg",{id:"copy-cmd-icon",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#D7FF63",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})," ","in your project directory to restart the server. Then refresh this page."]}),n("script",{dangerouslySetInnerHTML:{__html:`
45
+ document.getElementById('copy-cmd-btn').addEventListener('click', function() {
46
+ var label = document.getElementById('copy-cmd-label');
47
+ var icon = document.getElementById('copy-cmd-icon');
48
+ navigator.clipboard.writeText('codeyam editor').then(function() {
49
+ label.textContent = 'copied!';
50
+ icon.style.display = 'none';
51
+ setTimeout(function() {
52
+ label.textContent = 'codeyam editor';
53
+ icon.style.display = '';
54
+ }, 2000);
55
+ });
56
+ });
57
+ `}})]}):d("div",{children:[n("p",{style:{fontSize:16,color:"#8E8E8E",lineHeight:1.7,margin:"0 0 28px",maxWidth:480},children:"An unexpected error occurred. Try refreshing the page."}),t instanceof Error&&t.message&&n("pre",{style:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:8,padding:"16px 20px",fontFamily:'"IBM Plex Mono", monospace',fontSize:13,color:"#8E8E8E",textAlign:"left",overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},children:t.message})]})]})})]})}),Vg=Object.freeze(Object.defineProperty({__proto__:null,ErrorBoundary:Hg,default:Ug,links:Bg,loader:Yg},Symbol.toStringTag,{value:"Module"}));function ds(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}async function fl(e,t){try{await fetch("/api/interactive-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e,scenarioName:t})})}catch(r){console.error("[useInteractiveMode] Failed to seed scenario:",r)}}function jn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:o=!0,refreshTrigger:i=0}){const l=Ke(),[c,p]=P(null),[u,h]=P(!1),[m,f]=P(!1),[g,y]=P(!1),x=fe(!1),b=fe(void 0),w=fe(null),v=fe(null),N=fe(null),S=fe(null),[C,A]=P(0),[_,E]=P(0),R=fe(null),D=fe(!1),T=fe(!1),$=fe(r),{interactiveUrl:L,scenarioUrlMap:B,resetLogs:H}=Jt(a,o),q=fe(t);ae(()=>{$.current=r},[r]);const O=fe(i);ae(()=>{O.current!==i&&(O.current=i,c&&(f(!0),y(!1),A(0),E(k=>k+1),D.current=!1,T.current=!1,R.current&&(clearTimeout(R.current),R.current=null)))},[i,c]),ae(()=>{if(q.current===t||(q.current=t,!c||!t))return;f(!0),y(!1),A(0),D.current=!1,T.current=!1,$.current=r,R.current&&(clearTimeout(R.current),R.current=null),(async()=>{await fl(t,r);const Y=w.current;let G;if(Y&&Y[t])G=Y[t]+"?width=600px";else if(v.current&&N.current&&r){if(G=v.current,S.current&&s){const F=ds(S.current),M=ds(s);F!==M&&(G=G.replace(F,M))}const Q=ds(N.current),K=ds(r);G=G.replace(Q,K)}else G=c;p(G),E(Q=>Q+1)})()},[t,r,s,c]),ae(()=>{if(L){const k=L+"?width=600px";B&&(w.current=B),v.current=k,r&&(N.current=r),s&&(S.current=s),h(!1),f(!0),(async()=>{t&&r&&await fl(t,r);const G=w.current,Q=t&&G&&G[t]?G[t]+"?width=600px":k;p(Q)})()}},[L]);const W=()=>{y(!0),b.current=t;const k=$.current;requestAnimationFrame(()=>{requestAnimationFrame(()=>{$.current===k&&f(!1)})})};ae(()=>{const k=Y=>{if(Y.data.type==="codeyam-resize"){if(Y.data.name&&$.current&&Y.data.name!==$.current)return;D.current||(D.current=!0,R.current&&(clearTimeout(R.current),R.current=null),A(0),T.current&&W())}};return window.addEventListener("message",k),()=>window.removeEventListener("message",k)},[]);const I=()=>{if(T.current=!0,D.current){W();return}R.current&&clearTimeout(R.current);const k=300*Math.pow(2,C);R.current=setTimeout(()=>{D.current||(C<2?(A(Y=>Y+1),E(Y=>Y+1),f(!0),T.current=!1):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),W()))},k)};ae(()=>{o&&!x.current&&t&&e&&(x.current=!0,h(!0),y(!1),p(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(Y){console.error("[useInteractiveMode] Failed to clear log file:",Y)}H(),l.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[o,t,e,H,a]),ae(()=>{const k=e,Y=()=>{if(x.current&&k){const Q=new URLSearchParams({action:"stop",analysisId:k});navigator.sendBeacon("/api/interactive-mode",Q)||fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Q,keepalive:!0}).catch(F=>console.error("Failed to stop interactive mode:",F))}},G=()=>{Y()};return window.addEventListener("beforeunload",G),()=>{window.removeEventListener("beforeunload",G),Y()}},[e]);const j=g&&b.current===t;return{interactiveServerUrl:c,isStarting:u,isLoading:m,showIframe:j,iframeKey:_,onIframeLoad:I}}const us=10,Gg=1024;function Go({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:s,onHoverChange:a,hideLabel:o=!1,lightMode:i=!1}){const[l,c]=P(null),p=fe(null),u=ie(()=>[...s].sort((w,v)=>w.width-v.width),[s]),{fittingPresets:h,overflowPresets:m}=ie(()=>{const w=[],v=[];for(const N of u)N.width<=Gg?w.push(N):v.push(N);return v.sort((N,S)=>S.width-N.width),{fittingPresets:w,overflowPresets:v}},[u]),f=ce(w=>{if(!p.current)return null;const v=p.current.getBoundingClientRect(),N=w-v.left,S=v.width,C=S/2,_=(h.length>0?h[h.length-1].width:0)/2,E=C-_,R=C+_,D=m.length>0?(m.length-1)*us:0;if(m.length>0){if(N<E){if(N<=D){const $=Math.min(Math.floor(N/us),m.length-1);return m[$]}return m[m.length-1]}if(N>R){const $=S-N;if($<=D){const L=Math.min(Math.floor($/us),m.length-1);return m[L]}return m[m.length-1]}}const T=Math.abs(N-C);for(let $=h.length-1;$>=0;$--){const L=h[$],B=h[$-1],H=L.width/2,q=B?B.width/2:0;if(T<=H&&T>=q)return L}return h[0]||m[m.length-1]||null},[h,m]),g=ce(w=>{const v=f(w.clientX);c(v),a==null||a(v)},[f,a]),y=ce(()=>{c(null),a==null||a(null)},[a]),x=ce(w=>{const v=f(w.clientX);v&&r(v)},[f,r]),b=l||{name:t,width:e};return d("div",{ref:p,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:g,onMouseLeave:y,onClick:x,children:[l&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${l.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:h.map(w=>{const v=w.width===e,N=(l==null?void 0:l.name)===w.name,S=w.width/2;return d("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${S}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${v||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${S}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${v||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},w.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:m.map((w,v)=>{const N=v*us,S=w.width===e,C=(l==null?void 0:l.name)===w.name;return d("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${N}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${S||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{right:`${N}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${S||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},w.name)})}),!o&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:d("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${l?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[b.name," - ",b.width,"px"]})})]})}function Kg({currentWidth:e,currentHeight:t,devicePresets:r,customSizes:s,onApply:a,onSave:o,onRemove:i,onClose:l}){const[c,p]=P(String(e)),[u,h]=P(String(t)),[m,f]=P(""),[g,y]=P(!1),x=fe(null),b=fe(null);ae(()=>{const E=R=>{x.current&&!x.current.contains(R.target)&&l()};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[l]),ae(()=>{const E=R=>{R.key==="Escape"&&l()};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[l]),ae(()=>{var E;(E=b.current)==null||E.select()},[]);const w=parseInt(c,10),v=parseInt(u,10),N=w>0&&v>0,S=N&&(w!==e||v!==t),C=()=>{N&&(a({name:"Custom",width:w,height:v}),l())},A=()=>{const E=m.trim();!E||!N||(o(E,w,v),a({name:E,width:w,height:v}),l())},_=E=>{E.key==="Enter"&&(g&&m.trim()?A():S&&C())};return d("div",{ref:x,className:"absolute top-full mt-1 right-0 bg-[#2a2a2a] border border-[#444] rounded-lg shadow-xl z-50 w-64",children:[r&&r.length>0&&d("div",{className:"border-b border-[#444]",children:[n("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wider text-gray-500",children:"Presets"}),r.map(E=>d("button",{onClick:()=>{a(E),l()},className:`w-full px-3 py-1.5 text-left text-xs transition-colors cursor-pointer ${E.width===e&&E.height===t?"text-white bg-[#444]":"text-gray-300 hover:text-white hover:bg-[#333]"}`,children:[n("span",{className:"font-medium",children:E.name}),d("span",{className:"text-gray-500 ml-1.5",children:[E.width,"×",E.height]})]},E.name))]}),s.length>0&&d("div",{className:"border-b border-[#444]",children:[n("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wider text-gray-500",children:"Saved Sizes"}),s.map(E=>d("div",{className:"flex items-center group hover:bg-[#333] transition-colors",children:[d("button",{onClick:()=>{a(E),l()},className:"flex-1 px-3 py-1.5 text-left text-xs text-gray-300 hover:text-white transition-colors cursor-pointer",children:[n("span",{className:"font-medium",children:E.name}),d("span",{className:"text-gray-500 ml-1.5",children:[E.width,"×",E.height]})]}),n("button",{onClick:()=>i(E.name),className:"px-2 py-1.5 text-gray-600 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-all cursor-pointer",title:"Remove",children:n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M18 6L6 18M6 6l12 12"})})})]},E.name))]}),d("div",{className:"p-3",children:[d("div",{className:"flex items-center gap-2 mb-2",children:[n("input",{ref:b,type:"number",value:c,onChange:E=>p(E.target.value),onKeyDown:_,min:"100",max:"7680",className:"w-full px-2 py-1.5 bg-[#1a1a1a] border border-[#555] rounded text-xs text-white text-center focus:outline-none focus:border-[#007a99] [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",placeholder:"Width"}),n("span",{className:"text-gray-500 text-xs flex-shrink-0",children:"×"}),n("input",{type:"number",value:u,onChange:E=>h(E.target.value),onKeyDown:_,min:"100",max:"7680",className:"w-full px-2 py-1.5 bg-[#1a1a1a] border border-[#555] rounded text-xs text-white text-center focus:outline-none focus:border-[#007a99] [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",placeholder:"Height"})]}),d("div",{className:"flex gap-2",children:[n("button",{onClick:C,disabled:!N||!S,className:"flex-1 px-2 py-1.5 bg-[#007a99] text-white text-xs font-medium rounded hover:bg-[#006080] transition-colors cursor-pointer disabled:bg-[#333] disabled:text-gray-600 disabled:cursor-not-allowed",children:"Apply"}),g?d("div",{className:"flex gap-1",children:[n("input",{type:"text",value:m,onChange:E=>f(E.target.value),onKeyDown:_,placeholder:"Name",className:"w-20 px-2 py-1.5 bg-[#1a1a1a] border border-[#555] rounded text-xs text-white focus:outline-none focus:border-[#007a99]",autoFocus:!0}),n("button",{onClick:A,disabled:!m.trim()||!N,className:"px-2 py-1.5 bg-[#007a99] text-white text-xs rounded hover:bg-[#006080] transition-colors cursor-pointer disabled:bg-[#333] disabled:text-gray-600 disabled:cursor-not-allowed",children:"OK"})]}):n("button",{onClick:()=>y(!0),disabled:!N,className:"px-2 py-1.5 bg-[#333] text-gray-300 text-xs rounded hover:bg-[#444] transition-colors cursor-pointer disabled:text-gray-600 disabled:cursor-not-allowed",title:"Save as preset",children:"Save"})]})]})]})}function Ko({width:e,height:t,onSave:r,onCancel:s}){const[a,o]=P(""),[i,l]=P(""),c=()=>{const p=a.trim();if(!p){l("Please enter a name");return}r(p)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:d("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[d("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),d("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),d("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),d("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:a,onChange:p=>{o(p.target.value),l("")},onKeyDown:p=>{p.key==="Enter"&&a.trim()&&c(),p.key==="Escape"&&s()},placeholder:"e.g., iPhone 15 Pro",className:`w-full px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] ${i?"border-red-300":"border-gray-300"}`,autoFocus:!0}),i&&n("p",{className:"mt-1 text-sm text-red-600",children:i})]}),d("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:s,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 transition-colors cursor-pointer",children:"Cancel"}),n("button",{onClick:c,disabled:!a.trim(),className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function oa(e){const[t,r]=P([]),s=e?`codeyam-custom-sizes-${e}`:null;ae(()=>{if(!s||typeof window>"u"){r([]);return}try{const l=localStorage.getItem(s);if(l){const c=JSON.parse(l);Array.isArray(c)&&r(c)}}catch(l){console.error("[useCustomSizes] Failed to load custom sizes:",l),r([])}},[s]);const a=ce(l=>{if(!(!s||typeof window>"u"))try{localStorage.setItem(s,JSON.stringify(l))}catch(c){console.error("[useCustomSizes] Failed to save custom sizes:",c)}},[s]),o=ce((l,c,p)=>{r(u=>{const h=u.findIndex(g=>g.name===l),m={name:l,width:c,height:p};let f;return h>=0?(f=[...u],f[h]=m):f=[...u,m],a(f),f})},[a]),i=ce(l=>{r(c=>{const p=c.filter(u=>u.name!==l);return a(p),p})},[a]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}function Wt(){return d("div",{className:"spinner-container",children:[n("span",{className:"loader"}),n("style",{children:`
58
+ .loader {
59
+ width: 48px;
60
+ height: 48px;
61
+ border: 3px solid rgba(0, 92, 117, 0.2);
62
+ border-radius: 50%;
63
+ display: inline-block;
64
+ position: relative;
65
+ box-sizing: border-box;
66
+ animation: rotation 1s linear infinite;
67
+ }
68
+ .loader::after {
69
+ content: '';
70
+ box-sizing: border-box;
71
+ position: absolute;
72
+ left: 50%;
73
+ top: 50%;
74
+ transform: translate(-50%, -50%);
75
+ width: 56px;
76
+ height: 56px;
77
+ border-radius: 50%;
78
+ border: 3px solid;
79
+ border-color: #005c75 transparent;
80
+ }
81
+
82
+ @keyframes rotation {
83
+ 0% {
84
+ transform: rotate(0deg);
85
+ }
86
+ 100% {
87
+ transform: rotate(360deg);
88
+ }
89
+ }
90
+ `})]})}const gl=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],qg=80;function Kn(){const[e,t]=P(0);return ae(()=>{const r=setInterval(()=>{t(s=>(s+1)%gl.length)},qg);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:gl[e]})}async function Qg({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw re("Invalid parameters",{status:400});const s=await _n(t);if(!s)throw re("Entity not found",{status:404});const a=await Xs(s),o=((l=a==null?void 0:a.scenarios)==null?void 0:l.find(c=>c.id===r))||null;if(!o)throw re("Scenario not found",{status:404});const i=await Ye();return re({entity:s,scenario:o,analysis:a,projectSlug:i})}const Ja=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1920,height:1080}],Zg=et(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=st(),o=Rt(),[i]=Zn(),[l,c]=P(null),[p,u]=P(1920),[h,m]=P({name:"Desktop",width:1920,height:1080}),[f,g]=P(!1),[y,x]=P(null),{customSizes:b,addCustomSize:w}=oa(a),v=ie(()=>[...Ja,...b],[b]),N=fe(null),[S,C]=P(1),A=ce(()=>{if(!N.current)return;const M=32,z=N.current.clientWidth-M,J=N.current.clientHeight-M,te=h.width,oe=h.height??900,de=Math.min(1,z/te,J/oe);C(de)},[h.width,h.height]);ae(()=>(A(),window.addEventListener("resize",A),()=>window.removeEventListener("resize",A)),[A]);const{interactiveServerUrl:_,isStarting:E,isLoading:R,showIframe:D,iframeKey:T,onIframeLoad:$}=jn({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0}),{lastLine:L}=Jt(a,E||R),B=()=>{o(`/entity/${t.sha}`)},H=(M,z)=>{u(M);const J=v.find(oe=>oe.width===M&&oe.height===z);c(J||null),m({name:(J==null?void 0:J.name)||"Custom",width:M,height:z})},q=M=>{c(M),u(M.width),m({name:M.name,width:M.width,height:M.height})},O=M=>{w(M,h.width,h.height??900),g(!1),m(z=>({...z,name:M}))},W=((s==null?void 0:s.scenarios)||[]).filter(M=>{var z;return!((z=M.metadata)!=null&&z.sameAsDefault)}),I=W.findIndex(M=>M.id===(r==null?void 0:r.id)),j=I+1,k=W.length,Y=I>0,G=I<W.length-1,Q=()=>{if(Y){const M=W[I-1],z=encodeURIComponent(`/entity/${t.sha}/scenarios/${M.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${M.id}/fullscreen?from=${z}`)}},K=()=>{if(G){const M=W[I+1],z=encodeURIComponent(`/entity/${t.sha}/scenarios/${M.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${M.id}/fullscreen?from=${z}`)}},F=E||R||!D;return d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[d("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:Ks,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),d("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:Q,disabled:!Y,className:`${Y?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),d("span",{className:"text-gray-400 text-sm",children:[j,"/",k]}),n("button",{onClick:K,disabled:!G,className:`${G?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),d("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&d("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]})]}),n("button",{onClick:B,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),d("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Ja[Ja.length-1].width}px`,width:"100%"},children:n(Go,{currentViewportWidth:p,currentPresetName:h.name,onDevicePresetClick:q,devicePresets:v,hideLabel:!0,onHoverChange:x,lightMode:!0})})}),d("div",{className:"relative z-10 flex items-center gap-2",children:[d("div",{className:"relative w-28 h-5",children:[d("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(y==null?void 0:y.name)||h.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),d("select",{value:h.name,onChange:M=>{const z=v.find(J=>J.name===M.target.value);z&&q(z)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[v.map(M=>n("option",{value:M.name,children:M.name},M.name)),h.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:h.width,onChange:M=>{const z=parseInt(M.target.value,10);!isNaN(z)&&z>0&&H(z,h.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:h.height??900}),h.name==="Custom"&&n("button",{onClick:()=>g(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{ref:N,className:"flex-1 flex items-center justify-center overflow-hidden p-4",style:{backgroundImage:`
91
+ linear-gradient(45deg, #ebebeb 25%, transparent 25%),
92
+ linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
93
+ linear-gradient(45deg, transparent 75%, #ebebeb 75%),
94
+ linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
95
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:_?d("div",{className:"relative bg-white",style:{width:`${h.width}px`,height:`${h.height??900}px`,transform:`scale(${S})`,transformOrigin:"center center"},children:[F&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Wt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),L&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Kn,{}),L]})]})]})}),n("iframe",{src:_,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:$,style:{opacity:D?1:0}},T)]}):d("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Wt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),L&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Kn,{}),L]})]})]})}),f&&n(Ko,{width:h.width,height:h.height??900,onSave:O,onCancel:()=>g(!1)})]})}),Xg=Object.freeze(Object.defineProperty({__proto__:null,default:Zg,loader:Qg},Symbol.toStringTag,{value:"Module"})),Jn={sound:"soft-double-tap",systemNotification:!0},e0=[{id:"soft-double-tap",label:"Soft double tap"},{id:"gentle-chime",label:"Gentle chime"},{id:"warm-ding",label:"Warm ding"},{id:"mellow-two-tone",label:"Mellow two-tone"},{id:"triangle-bell",label:"Triangle bell"},{id:"off",label:"No sound"}],xd="codeyam-editor-notifications";function t0(){try{const e=localStorage.getItem(xd);if(!e)return Jn;const t=JSON.parse(e);return typeof t=="string"?t==="true"?Jn:{...Jn,sound:"off",systemNotification:!1}:{...Jn,...t}}catch{return Jn}}function n0(e){localStorage.setItem(xd,JSON.stringify(e))}function bd(e){var t;if(e!=="off")try{const r=new AudioContext,s={"soft-double-tap":a=>{[0,.12].forEach(o=>{const i=a.createOscillator(),l=a.createGain();i.connect(l),l.connect(a.destination),i.type="sine",i.frequency.value=392,l.gain.setValueAtTime(.25,a.currentTime+o),l.gain.exponentialRampToValueAtTime(.01,a.currentTime+o+.1),i.start(a.currentTime+o),i.stop(a.currentTime+o+.1)})},"gentle-chime":a=>{const o=a.createOscillator(),i=a.createGain();o.connect(i),i.connect(a.destination),o.type="sine",o.frequency.setValueAtTime(523,a.currentTime),o.frequency.setValueAtTime(659,a.currentTime+.15),i.gain.setValueAtTime(.3,a.currentTime),i.gain.exponentialRampToValueAtTime(.01,a.currentTime+.4),o.start(),o.stop(a.currentTime+.4)},"warm-ding":a=>{const o=a.createOscillator(),i=a.createGain();o.connect(i),i.connect(a.destination),o.type="sine",o.frequency.value=330,i.gain.setValueAtTime(.35,a.currentTime),i.gain.exponentialRampToValueAtTime(.01,a.currentTime+.6),o.start(),o.stop(a.currentTime+.6)},"mellow-two-tone":a=>{const o=a.createOscillator(),i=a.createGain();o.connect(i),i.connect(a.destination),o.type="sine",o.frequency.setValueAtTime(294,a.currentTime),o.frequency.setValueAtTime(440,a.currentTime+.18),i.gain.setValueAtTime(.3,a.currentTime),i.gain.exponentialRampToValueAtTime(.01,a.currentTime+.5),o.start(),o.stop(a.currentTime+.5)},"triangle-bell":a=>{const o=a.createOscillator(),i=a.createGain();o.connect(i),i.connect(a.destination),o.type="triangle",o.frequency.value=523,i.gain.setValueAtTime(.4,a.currentTime),i.gain.exponentialRampToValueAtTime(.01,a.currentTime+.8),o.start(),o.stop(a.currentTime+.8)}};(t=s[e])==null||t.call(s,r)}catch{}}function wd({serverUrl:e,isStarting:t,projectSlug:r,devServerError:s,onStartServer:a,notificationSettings:o,onChangeNotificationSettings:i}){const[l,c]=P(null),[p,u]=P(!1),h=fe(null),m=fe(null);ae(()=>{if(!r)return;const b=new EventSource("/api/dev-mode-events");return b.onmessage=w=>{try{const v=JSON.parse(w.data);v.type==="file-synced"&&(c(v.fileName),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{c(null)},5e3))}catch{}},()=>{b.close(),m.current&&clearTimeout(m.current)}},[r]),ae(()=>{if(!p)return;function b(w){h.current&&!h.current.contains(w.target)&&u(!1)}return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[p]);let f;s?f="error":t?f="starting":e?f="running":f="stopped";const g={starting:"bg-yellow-400",running:"bg-green-400",stopped:"bg-gray-400",error:"bg-red-400"},y={starting:"Starting...",running:e||"Running",stopped:"Stopped",error:"Error"},x=o&&(o.sound!=="off"||o.systemNotification);return d("div",{className:"bg-[#1e1e1e] border-t border-[#3d3d3d] h-7 flex items-center px-4 gap-4 shrink-0 text-xs font-mono",children:[d("div",{className:"flex items-center gap-2",children:[n("div",{className:`w-2 h-2 rounded-full ${g[f]}`}),d("span",{className:"text-gray-400",children:["Server:"," ",n("span",{className:"text-gray-300",children:y[f]})]}),(f==="stopped"||f==="error")&&a&&n("button",{onClick:a,className:"ml-1 px-2.5 py-0.5 bg-[#005c75] hover:bg-[#007a9a] text-white text-[11px] font-medium rounded transition-colors cursor-pointer border-none leading-tight",children:"Start Server"})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"}),l&&d(we,{children:[d("div",{className:"flex items-center gap-1.5",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2",children:n("path",{d:"M20 6L9 17l-5-5"})}),d("span",{className:"text-green-400",children:["Synced: ",l]})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"})]}),n("div",{className:"flex-1"}),i&&o&&d("div",{className:"relative",ref:h,children:[n("button",{onClick:()=>u(!p),className:`text-[11px] rounded transition-colors cursor-pointer ${x?"text-cygreen hover:text-cygreen/80":"text-gray-500 hover:text-gray-300"}`,children:x?"Notifications On":"Notifications Off"}),p&&d("div",{className:"absolute bottom-full right-0 mb-2 w-56 bg-[#2d2d2d] border border-[#4d4d4d] rounded-lg shadow-xl p-3 flex flex-col gap-3 z-50",children:[d("div",{children:[n("div",{className:"text-[11px] text-gray-400 mb-1.5",children:"Notification sound"}),n("div",{className:"flex flex-col gap-0.5",children:e0.map(b=>n("button",{onClick:()=>{i({...o,sound:b.id}),b.id!=="off"&&bd(b.id)},className:`text-left text-[11px] px-2 py-1 rounded cursor-pointer transition-colors ${o.sound===b.id?"bg-[#444] text-white":"text-gray-300 hover:bg-[#3a3a3a]"}`,children:b.label},b.id))})]}),d("div",{className:"border-t border-[#4d4d4d] pt-2",children:[d("label",{className:"flex items-center gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:o.systemNotification,onChange:b=>{const w=b.target.checked;i({...o,systemNotification:w}),w&&typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()},className:"accent-green-500"}),n("span",{className:"text-[11px] text-gray-300",children:"System notification"})]}),n("div",{className:"text-[10px] text-gray-500 mt-1 ml-5",children:"Shows when tab is not visible"})]})]})]})]})}async function r0(e,t){try{const{WebglAddon:s}=await import("@xterm/addon-webgl"),a=new s;return a.onContextLoss(()=>{t==null||t("webgl","canvas",new Error("WebGL context lost")),a.dispose(),yl(e).then(o=>{o||t==null||t("canvas","dom",new Error("Canvas fallback failed after context loss"))})}),e.loadAddon(a),{type:"webgl",dispose:()=>a.dispose()}}catch(s){t==null||t("webgl","canvas",s)}const r=await yl(e);return r||(t==null||t("canvas","dom",new Error("Canvas addon failed")),{type:"dom",dispose:()=>{}})}async function yl(e){try{const{CanvasAddon:t}=await import("@xterm/addon-canvas"),r=new t;return e.loadAddon(r),{type:"canvas",dispose:()=>r.dispose()}}catch{return null}}class s0{constructor(t,r){ut(this,"deferred",!1);ut(this,"userActiveSinceLastOutput",!1);ut(this,"actions");ut(this,"env");this.actions=t,this.env=r}reportUserActivity(){this.userActiveSinceLastOutput=!0}resetActivityFlag(){this.userActiveSinceLastOutput=!1}onIdle(t,r){return this.deferred=!1,r&&this.env.hasBrowserFocus()&&this.userActiveSinceLastOutput?(this.userActiveSinceLastOutput=!1,"suppressed"):this.notify(t)}onBuildTabChange(t,r){return!t&&this.deferred?(this.deferred=!1,this.notify(r),!0):!1}onActive(){this.deferred=!1}onUserEngagement(){const t=this.deferred;return this.deferred=!1,t}get isDeferred(){return this.deferred}notify(t){const r=!!(t!=null&&t.sound)&&t.sound!=="off";return r&&this.actions.playSound(t.sound),!this.env.hasBrowserFocus()&&(t!=null&&t.systemNotification)&&this.env.hasNotificationPermission()&&this.actions.showSystemNotification(),r?"played":"played-no-sound"}}class a0{constructor(t){ut(this,"_isIdle",!1);ut(this,"_isBuilding",!1);ut(this,"callbacks");this.callbacks=t}get isIdle(){return this._isIdle}get isBuilding(){return this._isBuilding}handleClaudeIdle(t,r,s){console.log("[TerminalIdleHandler] claude-idle, building: %s → false",this._isBuilding),t==null||t.onIdle(r,s),this._isIdle=!0,this._isBuilding=!1,this.callbacks.onIdleChange(!0),this.callbacks.onBuildingChange(!1)}handleClaudeActive(t){console.log("[TerminalIdleHandler] claude-active, building: %s → true",this._isBuilding),this._isIdle=!1,this._isBuilding=!0,this.callbacks.onIdleChange(!1),this.callbacks.onBuildingChange(!0),t==null||t.onActive(),t==null||t.resetActivityFlag(),this.callbacks.onCloseNotification()}handleOutput(t){this.callbacks.onIdleChange(!1),t==null||t.resetActivityFlag()}reset(){this._isBuilding&&(console.log("[TerminalIdleHandler] reset, was building: true"),this._isBuilding=!1,this.callbacks.onBuildingChange(!1))}}const o0=`
96
+ .xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
97
+ .xterm.focus, .xterm:focus { outline: none; }
98
+ .xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
99
+ .xterm .xterm-helper-textarea { padding: 0; border: 0; margin: 0; position: absolute; opacity: 0; left: -9999em; top: 0; width: 0; height: 0; z-index: -5; white-space: nowrap; overflow: hidden; resize: none; caret-color: transparent !important; clip-path: inset(100%) !important; }
100
+ .xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
101
+ .xterm .composition-view.active { display: block; }
102
+ .xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
103
+ .xterm .xterm-screen { position: relative; }
104
+ .xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
105
+ .xterm .xterm-scroll-area { visibility: hidden; }
106
+ .xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
107
+ .xterm.enable-mouse-events { cursor: default; }
108
+ .xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
109
+ .xterm.column-select.focus { cursor: crosshair; }
110
+ .xterm .xterm-accessibility:not(.debug), .xterm .xterm-message { position: absolute; left: 0; top: 0; bottom: 0; right: 0; z-index: 10; color: transparent; pointer-events: none; }
111
+ .xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
112
+ .xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
113
+ .xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
114
+ .xterm-dim { opacity: 1 !important; }
115
+ .xterm-underline-1 { text-decoration: underline; }
116
+ .xterm-underline-2 { text-decoration: double underline; }
117
+ .xterm-underline-3 { text-decoration: wavy underline; }
118
+ .xterm-underline-4 { text-decoration: dotted underline; }
119
+ .xterm-underline-5 { text-decoration: dashed underline; }
120
+ .xterm-overline { text-decoration: overline; }
121
+ .xterm-strikethrough { text-decoration: line-through; }
122
+ .xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
123
+ .xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
124
+ .xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
125
+ .xterm-decoration-top { z-index: 2; position: relative; }
126
+ `;function i0(){let e=document.getElementById("xterm-css");e||(e=document.createElement("style"),e.id="xterm-css",document.head.appendChild(e)),e.textContent=o0}const vd=Ep(function({entityName:t,entityType:r,entitySha:s,entityFilePath:a,scenarioName:o,scenarioDescription:i,analysisId:l,projectSlug:c,onRefreshPreview:p,onShowResults:u,onHideResults:h,onSetViewport:m,editorMode:f,onIdleChange:g,onBuildingChange:y,notificationSettings:x,buildTabActive:b,claudeStartMode:w,claudeSessionId:v,onDataMutationForwarded:N,resultsOpen:S,editorStepLabel:C},A){const _=fe(null),E=fe(null),R=fe(null),D=fe(null),T=fe(null),$=fe(!1),L=fe(0),B=fe(!1),H=fe(g);H.current=g;const q=fe(y);q.current=y;const O=fe(x);O.current=x;const W=fe(b);W.current=b;const I=fe(S);I.current=S;const j=fe(null),k=fe(!1),Y=fe(null);Y.current||(Y.current=new s0({playSound:M=>bd(M),showSystemNotification:()=>{j.current&&j.current.close();const M=new Notification("Claude is ready for you",{body:"Claude has finished and is waiting for your input.",tag:"claude-idle"});M.onclick=()=>{window.focus(),M.close()},j.current=M}},{hasBrowserFocus:()=>document.hasFocus(),hasNotificationPermission:()=>typeof Notification<"u"&&Notification.permission==="granted"}));const G=fe(null);G.current||(G.current=new a0({onIdleChange:M=>{var z;k.current=M,(z=H.current)==null||z.call(H,M)},onCloseNotification:()=>{j.current&&(j.current.close(),j.current=null)},onBuildingChange:M=>{var z;(z=q.current)==null||z.call(q,M)}}));function Q(){j.current&&(j.current.close(),j.current=null)}function K(){var M,z;k.current&&(k.current=!1,Q(),(M=H.current)==null||M.call(H,!1),(z=Y.current)==null||z.onUserEngagement())}ae(()=>{function M(){var oe;document.hasFocus()&&W.current&&K(),W.current&&document.hasFocus()&&((oe=Y.current)==null||oe.reportUserActivity())}function z(){!document.hidden&&W.current&&K()}function J(){var oe;document.hasFocus()&&W.current&&K(),W.current&&document.hasFocus()&&((oe=Y.current)==null||oe.reportUserActivity())}function te(){var oe;W.current&&K(),W.current&&((oe=Y.current)==null||oe.reportUserActivity())}return window.addEventListener("focus",te),document.addEventListener("visibilitychange",z),document.addEventListener("mousemove",M),document.addEventListener("mousedown",J),document.addEventListener("keydown",M),()=>{window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",z),document.removeEventListener("mousemove",M),document.removeEventListener("mousedown",J),document.removeEventListener("keydown",M)}},[]),ae(()=>{var M;b&&k.current&&document.hasFocus()&&K(),(M=Y.current)==null||M.onBuildTabChange(!!b,O.current)},[b]);const F=ce(()=>{var M;(M=R.current)==null||M.focus()},[]);return Ap(A,()=>({sendInput(M){const z=D.current;z&&z.readyState===WebSocket.OPEN&&(z.send(JSON.stringify({type:"input",data:M})),setTimeout(()=>{z.readyState===WebSocket.OPEN&&z.send(JSON.stringify({type:"input",data:"\r"}))},100))},focus(){var M;(M=R.current)==null||M.focus()},scrollToBottom(){var z;const M=(z=_.current)==null?void 0:z.querySelector(".xterm-viewport");M&&(M.scrollTop=M.scrollHeight)}})),ae(()=>{const M=_.current;if(!M)return;let z=!1;return i0(),Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit"),import("@xterm/addon-web-links")]).then(([J,te,oe])=>{if(z)return;const de=new J.Terminal({cursorBlink:!1,cursorInactiveStyle:"none",scrollback:5e3,fontSize:13,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#1e1e1e",selectionBackground:"#264f78"},linkHandler:{activate(ee,ne){try{const xe=new URL(ne),Me=xe.searchParams.get("scenario");if(Me&&xe.pathname.startsWith("/editor")){const he=new BroadcastChannel("codeyam-editor");he.postMessage({type:"switch-scenario",scenarioId:Me}),he.close();return}}catch{}window.open(ne,"_blank")}}}),ue=new te.FitAddon;de.loadAddon(ue),de.loadAddon(new oe.WebLinksAddon),de.open(M),de.attachCustomKeyEventHandler(ee=>{if(I.current&&(ee.key==="ArrowLeft"||ee.key==="ArrowRight")&&!ee.ctrlKey&&!ee.altKey&&!ee.metaKey&&ee.type==="keydown"){const ne=ee.key==="ArrowLeft"?"\x1B[D":"\x1B[C",xe=D.current;return xe&&xe.readyState===WebSocket.OPEN&&xe.send(JSON.stringify({type:"input",data:ne})),!1}return!0}),de.write("\x1B[?25l");let me=null;r0(de,(ee,ne,xe)=>{console.warn(`[Terminal] Renderer fallback: ${ee} → ${ne}`,xe)}).then(ee=>{if(z){ee.dispose();return}console.log(`[Terminal] Using ${ee.type} renderer`),me=ee.dispose}),requestAnimationFrame(()=>{try{ue.fit()}catch{}}),R.current=de,de.focus(),setTimeout(()=>de.focus(),100),setTimeout(()=>de.focus(),500);const Se=window.location.protocol==="https:"?"wss:":"ws:",Te=window.location.host;function $e(ee){const ne=new URLSearchParams;return ne.set("entityName",t),r&&ne.set("entityType",r),s&&ne.set("entitySha",s),a&&ne.set("entityFilePath",a),o&&ne.set("scenarioName",o),i&&ne.set("scenarioDescription",i),l&&ne.set("analysisId",l),c&&ne.set("projectSlug",c),f&&ne.set("editorMode","true"),ee&&ne.set("reconnectId",ee),w&&ne.set("claudeStartMode",w),v&&ne.set("claudeSessionId",v),C&&ne.set("editorStepLabel",C),`${Se}//${Te}/ws/terminal?${ne.toString()}`}function Re(ee){const ne=$e(ee),xe=new WebSocket(ne);D.current=xe,xe.onopen=()=>{L.current=0,B.current=!1,xe.send(JSON.stringify({type:"resize",cols:de.cols,rows:de.rows}))},xe.onmessage=Me=>{var he,He,Ve;try{const Oe=JSON.parse(Me.data);if(Oe.type==="session-id"){T.current=Oe.sessionId;return}if(Oe.type==="refresh-preview"){p==null||p(Oe.path,Oe.scenarioId);return}if(Oe.type==="show-results"){u==null||u();return}if(Oe.type==="hide-results"){h==null||h();return}if(Oe.type==="data-mutation-forwarded"){N==null||N();return}if(Oe.type==="set-viewport"){m==null||m({name:Oe.name,width:Oe.width,height:Oe.height});return}if(Oe.type==="claude-idle"){(he=G.current)==null||he.handleClaudeIdle(Y.current,O.current,W.current??!1);return}if(Oe.type==="claude-active"){(He=G.current)==null||He.handleClaudeActive(Y.current);return}Oe.type==="output"&&(de.write(Oe.data),(Ve=G.current)==null||Ve.handleOutput(Y.current))}catch{de.write(Me.data)}},xe.onclose=()=>{var he,He;if(console.log("[Terminal] WS closed, intentional=%s",$.current),$.current){de.write(`\r
127
+ \x1B[90m[Terminal session ended]\x1B[0m\r
128
+ `),(he=G.current)==null||he.reset();return}const Me=L.current;if(Me<5&&T.current){const Ve=1e3*Math.pow(2,Math.min(Me,3));L.current=Me+1,de.write(`\r
129
+ \x1B[33m[Reconnecting...]\x1B[0m\r
130
+ `),setTimeout(()=>{$.current||Re(T.current)},Ve)}else B.current?(de.write(`\r
131
+ \x1B[90m[Terminal session ended]\x1B[0m\r
132
+ `),(He=G.current)==null||He.reset()):(B.current=!0,de.write(`\r
133
+ \x1B[33m[Starting new session...]\x1B[0m\r
134
+ `),T.current=null,L.current=0,Re())},xe.onerror=()=>{}}Re(),de.onData(ee=>{const ne=D.current;ne&&ne.readyState===WebSocket.OPEN&&ne.send(JSON.stringify({type:"input",data:ee})),K()});let X=null;const ye=new ResizeObserver(()=>{X&&clearTimeout(X),X=setTimeout(()=>{let ee;try{ee=ue.proposeDimensions()}catch{return}if(!ee||ee.cols===de.cols&&ee.rows===de.rows)return;const ne=M.querySelector(".xterm-viewport");let xe,Me=!0;ne&&(xe=ne.scrollTop,Me=ne.scrollTop+ne.clientHeight>=ne.scrollHeight-10),ue.fit(),ne&&xe!==void 0&&(Me?ne.scrollTop=ne.scrollHeight:ne.scrollTop=xe);const he=D.current;he&&he.readyState===WebSocket.OPEN&&he.send(JSON.stringify({type:"resize",cols:de.cols,rows:de.rows}))},150)});ye.observe(M),E.current=()=>{var ee;X&&clearTimeout(X),ye.disconnect(),$.current=!0,(ee=D.current)==null||ee.close(),D.current=null,me==null||me(),de.dispose(),R.current=null}}),()=>{var J;z=!0,(J=E.current)==null||J.call(E),E.current=null}},[]),n("div",{ref:_,onClick:F,className:"w-full h-full relative overflow-hidden",style:{padding:"4px 0 0 8px"}})});function lt({screenshotPath:e,cacheBuster:t,alt:r,className:s="",title:a}){const[o,i]=P("loading"),[l,c]=P(!1),p=fe(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,h=()=>{i("success"),c(!0)},m=()=>{i("error"),c(!1)};return ae(()=>{i("loading"),c(!1);const f=p.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),c(!0)):(i("error"),c(!1)))},[u]),e?d("div",{className:"relative w-full h-full flex items-center justify-center",title:a,children:[n("img",{ref:p,src:u,alt:r,onLoad:h,onError:m,className:s||"max-w-full max-h-full object-contain",style:{visibility:l?"visible":"hidden",position:l?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&d("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:a,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}function l0({scenarios:e,currentScenarioId:t,entitySha:r,cacheBuster:s}){const a=Rt();return e.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8",children:n("p",{className:"text-gray-500 text-sm",children:"No scenarios found"})}):n("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:e.map(o=>{var c,p;const i=o.id===t,l=(p=(c=o.metadata)==null?void 0:c.screenshotPaths)==null?void 0:p[0];return d("button",{onClick:()=>{a(`/entity/${r}/scenarios/${o.id}/dev`)},className:`w-full text-left rounded-lg overflow-hidden border transition-colors cursor-pointer flex ${i?"border-[#005c75] bg-[#1a3a44]":"border-[#3d3d3d] bg-[#252525] hover:border-[#555]"}`,children:[n("div",{className:"w-24 h-20 shrink-0 bg-[#1a1a1a]",children:n(lt,{screenshotPath:l,cacheBuster:s,alt:o.name,className:"w-full h-full object-cover object-top"})}),d("div",{className:"p-2.5 min-w-0 flex-1",children:[d("div",{className:"text-white text-sm font-medium truncate",children:[i&&n("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-[#005c75] mr-1.5 relative top-[-1px]"}),o.name]}),o.description&&n("div",{className:"text-gray-400 text-xs mt-1 line-clamp-2",children:o.description})]})]},o.id)})})}function _t(e){var l;if(!e.startsWith("app/")&&!e.startsWith("("))return"/";const r=e.replace(/^app\//,"").split("/"),s=r.pop(),a=((l=s.match(/\.(tsx?|jsx?|js)$/))==null?void 0:l[0])||"",o=s.slice(0,-a.length);let i;return o==="page"||o==="index"?i=r:i=[...r,o],i=i.filter(c=>!c.startsWith("(")),i.length===0?"/":"/"+i.join("/")}function Ft(e){return e==="/"?"Home":e.replace(/^\//,"").split("/").map(r=>r.startsWith("[")?r:r.charAt(0).toUpperCase()+r.slice(1)).join(" / ")}function Nd(e,t){if(!e)return null;const r=e.split("?")[0].replace(/\/+$/,"")||"/",s=t.map(l=>({filePath:l,pattern:_t(l)})),a=r==="/"?[]:r.replace(/^\//,"").split("/");let o=null,i=-1;for(const l of s){const c=l.pattern==="/"?[]:l.pattern.replace(/^\//,"").split("/");if(c.length!==a.length)continue;let p=!0,u=0;for(let h=0;h<c.length;h++){const m=c[h],f=a[h];if(!(m.startsWith("[")&&m.endsWith("]")))if(m===f)u++;else{p=!1;break}}p&&u>i&&(i=u,o=l.filePath)}return o}function Sd(e,t){const r=new Map;for(const s of e)s.status!=="deleted"&&(t||s.status==="added"||s.status==="untracked"?r.set(s.path,"new"):s.status==="modified"&&r.set(s.path,"edited"));return r}function mt(e){if(!e||e==="/")return"Home";const t=e.split("?")[0].replace(/^\//,"");if(!t)return"Home";const r=t.split("/")[0].replace(/\.[^.]+$/,"");return r.charAt(0).toUpperCase()+r.slice(1)}function ia(e){return e?e.includes("/isolated-components")||e.includes("/codeyam-isolate"):!1}function Kt(e){return e.componentName?e.componentName:e.pageFilePath?Ft(_t(e.pageFilePath)):mt(e.url)}function Cd(e,t,r){var o;const s=[],a=new Set;for(const i of e){let l=null,c=null;if(i.componentName&&i.componentPath)l=i.componentName,c=i.componentPath;else if(!i.componentName&&i.pageFilePath)l=i.displayName||(i.pageFilePath.startsWith("app/")?Ft(_t(i.pageFilePath)):mt(i.url)),c=i.pageFilePath;else if(!i.componentName&&i.url!==void 0){const p=mt(i.url);t[p]&&(l=p,c=t[p])}if(l&&c&&!a.has(l)){a.add(l);const p=r.find(u=>u.name===l)||(c?r.find(u=>u.filePath===c):void 0);s.push({name:l,filePath:c,importedBy:(o=p==null?void 0:p.metadata)==null?void 0:o.importedBy})}}return s}function c0(e,t){const r=[],s=new Set(t);for(const a of e)s.has(a.name)||(s.add(a.name),r.push({name:a.name,filePath:a.filePath}));return r}function d0(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>t[r.name])}function u0(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>{if("componentName"in r){const a=Kt(r);return!!t[a]}const s=r.name.indexOf(" - ");if(s!==-1){const a=r.name.slice(0,s);return!!t[a]}return!!t.Home})}function p0(e){const t=new Set,r=new Map;for(const a of e)t.add(a.name),a.filePath&&r.set(a.filePath,a.name);const s=new Map;for(const a of e){const o=a.importedBy;if(!o||typeof o!="object")continue;const i=new Set;for(const l of Object.keys(o))for(const c of Object.keys(o[l]))if(t.has(c))i.add(c);else{const p=r.get(l);p&&p!==a.name?i.add(p):i.add(c)}i.size>0&&s.set(a.name,i)}return s}function h0(e,t){const r=new Map;for(const s of t){const a=e.get(s.filePath);a&&r.set(s.name,a)}return r}const m0=20;function kd(e,t,r=m0){const s={};if(t.length===0||e.size===0)return s;const a=new Map;for(const p of t)a.set(p.name,p);const o=p0(t),i=h0(e,t);for(const[p,u]of i)s[p]={status:u};const l=new Map;for(const[p]of i)l.set(p,new Set([p]));const c=[];for(const[p]of i)c.push({name:p,depth:0});for(;c.length>0;){const{name:p,depth:u}=c.shift();if(u>=r)continue;const h=l.get(p)||new Set,m=o.get(p);if(m)for(const f of m){if(!a.has(f))continue;l.has(f)||l.set(f,new Set);const g=l.get(f);let y=!1;for(const x of h)g.has(x)||(g.add(x),y=!0);y&&c.push({name:f,depth:u+1})}}for(const[p,u]of l){if(i.has(p))continue;const h=[];for(const m of u){const f=a.get(m),g=i.get(m);f&&g&&h.push({name:m,filePath:f.filePath,changeType:g})}h.sort((m,f)=>m.name.localeCompare(f.name)),s[p]={status:"impacted",impactedBy:h.length>0?h:void 0}}return s}function la(e){if(Array.isArray(e))return e;if(e&&typeof e=="object"){const t=e;for(const s of["components","entries","functions","glossary"]){const a=t[s];if(Array.isArray(a))return a}for(const s of Object.values(t))if(Array.isArray(s))return s;const r=Object.entries(t);if(r.length>0&&r.every(([,s])=>s&&typeof s=="object"&&!Array.isArray(s)))return r.map(([s,a])=>({...a,filePath:s}))}return[]}function f0(e){return la(e).filter(r=>r.testFile&&r.returnType!=="JSX.Element"&&r.returnType!=="React.ReactNode").map(r=>({name:r.name,filePath:r.filePath,description:r.description||"",testFile:r.testFile,feature:r.feature}))}function xl(e,t){var r,s,a,o,i;return t?!!((r=e.metadata)!=null&&r.executionResult):!!((a=(s=e.metadata)==null?void 0:s.screenshotPaths)!=null&&a[0])&&!((o=e.metadata)!=null&&o.noScreenshotSaved)&&!((i=e.metadata)!=null&&i.sameAsDefault)}function g0(e,t){return e.filter(r=>r.analyses&&r.analyses.length>0).map(r=>{var h;const s=r.analyses[0],a=s.scenarios||[],o=!((h=s.status)!=null&&h.finishedAt),i=r.entityType||"visual",l=i==="library"||i==="functionCall",c=a.filter(m=>xl(m,l)),p=a.filter(m=>!xl(m,l)),u=t.find(m=>m.filePath===(r.filePath||""));return{sha:r.sha,name:r.name,entityType:i,filePath:r.filePath||"",analysisId:s.id,isAnalyzing:o,scenarioCount:a.length,scenarios:c.map(m=>{var f,g;return{id:m.id,name:m.name,description:m.description||"",screenshotPath:((g=(f=m.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0])||null}}),pendingScenarios:p.map(m=>m.name),testFile:u==null?void 0:u.testFile}})}function y0(e,t){var s;const r={};for(const a of e){const i=(((s=a.metadata)==null?void 0:s.importedExports)||[]).map(l=>l.name).filter(l=>t.has(l));i.length>0&&(r[a.name]=i)}return r}function x0(e,t,r){const s={...e},a=new Map;for(const o of r)o.filePath&&a.set(o.filePath,o.name);for(const[o,i]of Object.entries(t)){if(s[o])continue;const l=a.get(i);l&&s[l]&&(s[o]=s[l])}return s}function Ct(e,t){const r=new Map;for(const s of e)r.set(t(s),s);return[...r.values()]}function Tt(e){return e.replace(/[^a-zA-Z0-9_]+/g,"_")}function _d(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function zr(e){return e.replace("T"," ").replace(/\.\d{3}Z$/,"")}function qo(e,t){return!!(e.created_at&&e.created_at>=t||e.updated_at&&e.updated_at>=t)}const b0=["defaultScreenSize","screenSizes","projectTitle","projectDescription","appFormats"];function yk(e){try{const t=JSON.parse(ge.readFileSync(e,"utf8")),r={};for(const s of b0)t[s]!==void 0&&(r[s]=t[s]);return r}catch{return{}}}function w0(e){const t=se.join(e,".codeyam","editor-step.json");try{ge.unlinkSync(t)}catch{}}function Qo(e,t,r){const s=e&&e.startsWith("/");return s&&t?`${t}${e}`:e&&!s?e:t||r||null}function v0(e){var t,r;try{const s=se.join(e,".codeyam","config.json"),a=JSON.parse(ge.readFileSync(s,"utf8"));if((t=a.defaultScreenSize)!=null&&t.width&&((r=a.defaultScreenSize)!=null&&r.height))return{width:a.defaultScreenSize.width,height:a.defaultScreenSize.height}}catch{}return null}function Zo(e){try{const t=se.join(e,".codeyam","config.json"),r=JSON.parse(ge.readFileSync(t,"utf8"));if(r.screenSizes&&typeof r.screenSizes=="object"&&!Array.isArray(r.screenSizes))return r.screenSizes}catch{}return{}}function N0(e){var t,r;return{width:e.bodyWidth||((t=e.projectDefault)==null?void 0:t.width)||1280,height:e.bodyHeight||((r=e.projectDefault)==null?void 0:r.height)||720}}function ca(e){let t=null;if(e.dimension){const a=Zo(e.codeyamRoot)[e.dimension];a!=null&&a.width&&(a!=null&&a.height)&&(t={width:a.width,height:a.height})}const r=t||v0(e.codeyamRoot);return N0({bodyWidth:e.bodyWidth,bodyHeight:e.bodyHeight,projectDefault:r})}async function S0(e,t){const r=t.dimensions?JSON.stringify(t.dimensions):null,s=t.screenshotPaths?JSON.stringify(t.screenshotPaths):null,a=await e.selectFrom("editor_scenarios").selectAll().where("name","=",t.name).where("project_id","=",t.projectId).orderBy("created_at","desc").execute();if(a.length>0){const c=a[0].id,p={description:t.description,component_name:t.componentName,component_path:t.componentPath,url:t.url,type:t.type,viewport_width:t.viewportWidth,viewport_height:t.viewportHeight,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")};t.dimensions!==void 0&&(p.dimensions=r,p.screenshot_paths=s),t.pageFilePath!==void 0&&(p.page_file_path=t.pageFilePath),t.entitySha!==void 0&&(p.entity_sha=t.entitySha),t.displayName!==void 0&&(p.display_name=t.displayName),await e.updateTable("editor_scenarios").set(p).where("id","=",c).execute();const u=a.slice(1).map(h=>h.id);return u.length>0&&await e.deleteFrom("editor_scenarios").where("id","in",u).execute(),{scenarioId:c,isNew:!1,cleanedUpIds:u}}const o=globalThis.crypto.randomUUID(),i={id:o,project_id:t.projectId,name:t.name,description:t.description,component_name:t.componentName,component_path:t.componentPath,url:t.url,type:t.type,viewport_width:t.viewportWidth,viewport_height:t.viewportHeight};return t.dimensions!==void 0&&(i.dimensions=r,i.screenshot_paths=s),t.pageFilePath!==void 0&&(i.page_file_path=t.pageFilePath),t.entitySha!==void 0&&(i.entity_sha=t.entitySha),t.displayName!==void 0&&(i.display_name=t.displayName),await e.insertInto("editor_scenarios").values(i).execute(),{scenarioId:o,isNew:!0,cleanedUpIds:[]}}function C0(e,t){const r=se.join(e,".codeyam","editor-scenarios"),s=se.join(r,"screenshots");for(const a of t){for(const o of[`${a}.json`,`${a}.seed.json`,se.join("screenshots",`${a}.png`)])try{ge.unlinkSync(se.join(r,o))}catch{}try{const o=ge.readdirSync(s);for(const i of o)if(i.startsWith(`${a}--`)&&i.endsWith(".png"))try{ge.unlinkSync(se.join(s,i))}catch{}}catch{}}}function k0(e){const{lookupFilePath:t,scenarioType:r,projectRoot:s}=e;if(r!=="application"&&r!=="user")return{valid:!0};if(!t)return{valid:!0};const a=se.join(s,".codeyam","glossary.json");let o=[];try{const l=JSON.parse(ge.readFileSync(a,"utf8"));o=la(l)}catch{}if(!o.some(l=>l.filePath===t)){const l=o.length===0?` glossary.json is empty or could not be parsed. It must be a JSON array: [{"name": "...", "filePath": "${t}", ...}]`:` Found ${o.length} entries but none with filePath "${t}".`;return{valid:!1,error:`No glossary entry found for '${t}'.${l} Add this file to .codeyam/glossary.json before registering app scenarios.`}}return{valid:!0,needsAnalysis:!0}}function _0(e){const{componentName:t,url:r}=e;return!t||!r?{valid:!0}:ia(r)?{valid:!0}:{valid:!1,error:`Scenario has componentName "${t}" but URL "${r}" is not an isolation route. Component scenarios must use an isolation URL like /isolated-components/${t}?s=ScenarioName or /codeyam-isolate/${t}?s=ScenarioName. Either change the URL to an isolation route, or remove componentName to register as an application scenario.`}}const E0=Ed;async function Ed(e,t){const r=new Map,s=new Map;for(const i of t)if(i.filePath){r.set(`${i.name}::${i.filePath}`,i);const l=s.get(i.filePath);(!l||!l.isDefaultExport||i.isDefaultExport)&&s.set(i.filePath,i)}const a=await e.selectFrom("editor_scenarios").selectAll().where(i=>i.or([i("component_path","is not",null),i("page_file_path","is not",null)])).execute();if(a.length===0)return{updated:0};let o=0;for(const i of a){const l=i,c=l.component_path||l.page_file_path;if(!c)continue;const p=l.component_name&&r.get(`${l.component_name}::${c}`)||s.get(c);if(!p||l.entity_sha===p.sha)continue;let u=null;l.component_name?u=l.component_name:l.page_file_path&&l.page_file_path.startsWith("app/")?u=Ft(_t(l.page_file_path)):l.url&&(u=mt(l.url)),await e.updateTable("editor_scenarios").set({entity_sha:p.sha,...u?{display_name:u}:{}}).where("id","=",l.id).execute(),o++}return{updated:o}}async function bl(e,t,r){const s=se.join(e,".codeyam","editor-scenarios"),a=i=>{const l=se.join(s,`${i}.seed.json`);if(ge.existsSync(l))try{return JSON.parse(ge.readFileSync(l,"utf-8"))}catch{return null}const c=se.join(s,`${i}.json`);if(ge.existsSync(c))try{return JSON.parse(ge.readFileSync(c,"utf-8")).seed||null}catch{return null}return null},o=a(r);if(o)return o;try{const i=await t.selectFrom("editor_scenarios").select("id").where("name","=",r).orderBy("created_at","desc").limit(1).executeTakeFirst();if(i)return a(i.id)}catch{}return null}function A0(e){const{activeAnalyzedScenario:t,analyzedPreviewUrl:r,activeScenarioId:s,scenarios:a,proxyUrl:o,devServerUrl:i,zoomComponent:l}=e;if(t&&r)return r;if(t&&!r)return null;if(s){const p=a.find(u=>u.id===s);if(p!=null&&p.url){const u=o||i;return u?p.url.startsWith("/")?`${u}${p.url}`:p.url:null}}const c=o||i;if(!c)return null;if(l&&s){const p=a.find(h=>h.id===s),u=p?Tt(p.name):"Default";return`${c}/__codeyam__/${l}/${u}`}return c}function Ad(e,t){if(!e||!t)return e;try{const r=new URL(e),s=t.indexOf("?");return s>=0?(r.pathname=t.slice(0,s),r.search=t.slice(s)):(r.pathname=t,r.search=""),r.href}catch{return e}}function P0(e,t){return e?e!==t:!1}function ps(e){if(e.length!==0)return e.find(t=>t.url==="/")||e.find(t=>t.type==="application")||e[0]}function Ha(e,t,r){if(!e.viewportWidth||!e.viewportHeight)return r??null;const s=t.find(a=>a.width===e.viewportWidth&&a.height===e.viewportHeight);return{name:(s==null?void 0:s.name)||"Custom",width:e.viewportWidth,height:e.viewportHeight}}function wl(e,t){const r=t.width,s=t.height??900,a=e.width,o=e.height;return r<=a&&s<=o?1:Math.min(a/r,o/s)}async function j0({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw re("Invalid parameters",{status:400});const s=await _n(t);if(!s)throw re("Entity not found",{status:404});const a=await Xs(s),o=((l=a==null?void 0:a.scenarios)==null?void 0:l.find(c=>c.id===r))||null;if(!o)throw re("Scenario not found",{status:404});const i=await Ye();return re({entity:s,scenario:o,analysis:a,projectSlug:i})}const Va=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],T0=et(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=st(),o=Rt(),i=fe(null),l=fe(null),[c,p]=P(null),[u,h]=P(1440),[m,f]=P({name:"Desktop",width:1440,height:900}),[g,y]=P(!1),[x,b]=P(null),[w,v]=P("chat"),[N,S]=P(0),[C,A]=P(null),_=ce(ue=>{A(ue||null),S(me=>me+1)},[]),{customSizes:E,addCustomSize:R}=oa(a),D=ie(()=>[...Va,...E],[E]),{interactiveServerUrl:T,isStarting:$,isLoading:L,showIframe:B,iframeKey:H,onIframeLoad:q}=jn({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0,refreshTrigger:N}),O=ie(()=>Ad(T,C),[T,C]),{lastLine:W}=Jt(a,$||L),I=()=>{o(`/entity/${t.sha}`)},j=(ue,me)=>{h(ue);const Se=D.find($e=>$e.width===ue&&$e.height===me);p(Se||null),f({name:(Se==null?void 0:Se.name)||"Custom",width:ue,height:me})},k=ue=>{p(ue),h(ue.width),f({name:ue.name,width:ue.width,height:ue.height})},Y=ue=>{R(ue,m.width,m.height??900),y(!1),f(me=>({...me,name:ue}))},G=()=>{var me;v("chat"),(me=l.current)==null||me.sendInput("Create a new scenario for this entity based on the work we've just done. Create a name and description that reflects what the live preview is showing. Use the scenario data you've changed to create a new scenario in the database. If the data structure was fixed in any way you need to update that in the database as well and backfill all existing scenarios, then save to the database and capture a screenshot. Remember the database is at `.codeyam/db.sqlite3`, the scenarios table has all scenarios and the analyses table contains the scenariosDataStructure is its metadata.")},Q=((s==null?void 0:s.scenarios)||[]).filter(ue=>{var me;return!((me=ue.metadata)!=null&&me.sameAsDefault)}),K=Q.findIndex(ue=>ue.id===(r==null?void 0:r.id)),F=K+1,M=Q.length,z=K>0,J=K<Q.length-1,te=()=>{if(z){const ue=Q[K-1];o(`/entity/${t.sha}/scenarios/${ue.id}/dev`)}},oe=()=>{if(J){const ue=Q[K+1];o(`/entity/${t.sha}/scenarios/${ue.id}/dev`)}},de=$||L||!B;return d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[d("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:Ks,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),d("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:te,disabled:!z,className:`${z?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),d("span",{className:"text-gray-400 text-sm",children:[F,"/",M]}),n("button",{onClick:oe,disabled:!J,className:`${J?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),d("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&d("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]}),n("span",{className:"bg-[#005c75] text-white text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wider ml-2",children:"Dev Mode"})]}),n("button",{onClick:I,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close dev mode",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),d("div",{className:"flex-1 flex min-h-0",children:[d("div",{className:"flex-1 flex flex-col min-w-0",children:[d("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Va[Va.length-1].width}px`,width:"100%"},children:n(Go,{currentViewportWidth:u,currentPresetName:m.name,onDevicePresetClick:k,devicePresets:D,hideLabel:!0,onHoverChange:b,lightMode:!0})})}),d("div",{className:"relative z-10 flex items-center gap-2",children:[d("div",{className:"relative w-28 h-5",children:[d("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(x==null?void 0:x.name)||m.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),d("select",{value:m.name,onChange:ue=>{const me=D.find(Se=>Se.name===ue.target.value);me&&k(me)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[D.map(ue=>n("option",{value:ue.name,children:ue.name},ue.name)),m.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:m.width,onChange:ue=>{const me=parseInt(ue.target.value,10);!isNaN(me)&&me>0&&j(me,m.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"x"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:m.height??900}),m.name==="Custom"&&n("button",{onClick:()=>y(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
135
+ linear-gradient(45deg, #ebebeb 25%, transparent 25%),
136
+ linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
137
+ linear-gradient(45deg, transparent 75%, #ebebeb 75%),
138
+ linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
139
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:T?d("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${m.width}px`,maxHeight:`${m.height}px`},children:[de&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Wt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the dev server to be ready"}),W&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Kn,{}),W]})]})]})}),n("iframe",{ref:i,src:O||T,className:"w-full h-full border-none",title:`Dev mode preview: ${r==null?void 0:r.name}`,onLoad:q,style:{opacity:B?1:0}},H)]}):d("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Wt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Dev Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment with live preview"}),W&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Kn,{}),W]})]})]})})]}),d("aside",{className:"w-[50%] min-w-[400px] max-w-[800px] bg-[#1e1e1e] border-l border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden",children:[d("div",{className:"border-b border-[#3d3d3d] px-4 shrink-0 flex items-center justify-between",children:[d("div",{className:"flex items-center gap-0",children:[d("button",{onClick:()=>v("chat"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${w==="chat"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Chat",w==="chat"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),d("button",{onClick:()=>v("scenarios"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${w==="scenarios"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Scenarios",w==="scenarios"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]})]}),w==="chat"&&n("button",{onClick:G,disabled:!T,className:"px-3 py-1 text-[11px] font-medium rounded bg-[#005c75] text-white hover:bg-[#004a5c] transition-colors disabled:bg-gray-600 disabled:text-gray-400 disabled:cursor-not-allowed cursor-pointer",children:"Save Scenario"})]}),n("div",{style:{display:w==="chat"?"flex":"none"},className:"flex-1 overflow-hidden flex-col",children:n(vd,{ref:l,entityName:t.name,entityType:t.entityType,entitySha:t.sha,entityFilePath:t.filePath||t.localFilePath,scenarioName:r==null?void 0:r.name,scenarioDescription:r==null?void 0:r.description,analysisId:s==null?void 0:s.id,projectSlug:a,onRefreshPreview:_})}),w==="scenarios"&&n(l0,{scenarios:Q,currentScenarioId:r==null?void 0:r.id,entitySha:t.sha,cacheBuster:0})]})]}),n(wd,{serverUrl:T,isStarting:$,projectSlug:a}),g&&n(Ko,{width:m.width,height:m.height??900,onSave:Y,onCancel:()=>y(!1)})]})}),M0=Object.freeze(Object.defineProperty({__proto__:null,default:T0,loader:j0},Symbol.toStringTag,{value:"Module"})),Pd=3e4,$0="seed-session.json";function I0(e){const t={};try{const r=V.readFileSync(e,"utf-8");for(const s of r.split(`
140
+ `)){const a=s.trim();if(!a||a.startsWith("#"))continue;const o=a.indexOf("=");if(o===-1)continue;const i=a.slice(0,o).trim();let l=a.slice(o+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),i&&(t[i]=l)}}catch{}return t}function jd(e){const t=[".env",".env.local",".env.development",".env.development.local"];let r={};for(const s of t){const a=I0(U.join(e,s));r={...r,...a}}return r}function Td(e){const t={};try{const r=U.join(e,".codeyam","config.json"),s=JSON.parse(V.readFileSync(r,"utf-8"));for(const a of s.environmentVariables||[]){const o=a.key||a.name;o&&a.value!==void 0&&(t[o]=a.value)}}catch{}return t}function R0(e){const t=U.join(e,".codeyam","tmp",$0);try{if(!V.existsSync(t))return;const r=V.readFileSync(t,"utf-8"),s=JSON.parse(r);return V.unlinkSync(t),s.cookies&&Array.isArray(s.cookies)?s.cookies:void 0}catch{return}}function Xo(e,t,r){const s=Pd,a=U.basename(U.dirname(e))===".codeyam"?U.dirname(U.dirname(e)):U.dirname(e);return new Promise(o=>{const i=Date.now(),l=e.endsWith(".ts");let c,p;if(l){const b=F0(a);b?(c=b,p=[e,t]):(c="npx",p=["tsx",e,t])}else c=e,p=[t];const u=jd(a),h=Td(a),m=ft(c,p,{cwd:a,env:{...u,...h,...process.env}});let f="",g="",y=!1;const x=setTimeout(()=>{y=!0,m.kill("SIGTERM")},s);m.stdout.on("data",b=>{f+=b.toString()}),m.stderr.on("data",b=>{g+=b.toString()}),m.on("close",b=>{clearTimeout(x);const w=Date.now()-i;if(y)o({success:!1,output:f,error:`Seed adapter timeout after ${s}ms`,durationMs:w});else if(b===0){const v=R0(a);o({success:!0,output:f,durationMs:w,sessionCookies:v})}else o({success:!1,output:f,error:g||`Seed adapter exited with code ${b}`,durationMs:w})}),m.on("error",b=>{clearTimeout(x),o({success:!1,output:"",error:b.message,durationMs:Date.now()-i})})})}function D0(e,t,r){const s=Pd,a=U.basename(U.dirname(e))===".codeyam"?U.dirname(U.dirname(e)):U.dirname(e);return new Promise(o=>{const i=Date.now(),l=e.endsWith(".ts"),c=l?"npx":e,p=l?["tsx",e,"--export",t]:["--export",t],u=jd(a),h=Td(a),m=ft(c,p,{cwd:a,env:{...u,...h,...process.env}});let f="",g="",y=!1;const x=setTimeout(()=>{y=!0,m.kill("SIGTERM")},s);m.stdout.on("data",b=>{f+=b.toString()}),m.stderr.on("data",b=>{g+=b.toString()}),m.on("close",b=>{clearTimeout(x);const w=Date.now()-i;o(y?{success:!1,output:f,error:`Seed adapter export timeout after ${s}ms`,durationMs:w}:b===0?{success:!0,output:f,durationMs:w}:{success:!1,output:f,error:g||`Seed adapter export exited with code ${b}`,durationMs:w})}),m.on("error",b=>{clearTimeout(x),o({success:!1,output:"",error:b.message,durationMs:Date.now()-i})})})}function Mr(e){const t=["seed-adapter.ts","seed-adapter.js"];for(const r of t){const s=U.join(e,".codeyam",r);try{return V.accessSync(s),s}catch{}}return null}function F0(e){const t=[U.join(e,"node_modules",".bin","tsx"),U.join(e,"..","node_modules",".bin","tsx")];for(const r of t)try{return V.accessSync(r,V.constants.X_OK),r}catch{}return null}function vl(e,t){const r={};for(const[s,a]of Object.entries(e))r[s]=JSON.parse(JSON.stringify(a));for(const[s,a]of Object.entries(t))r[s]=JSON.parse(JSON.stringify(a));return r}let fn=null;async function da(e){const{scenarioId:t,projectRoot:r}=e,s=se.join(r,".codeyam"),a=se.join(s,"editor-scenarios");let o=e.scenarioSlug||null;if(!o)try{const h=se.join(a,`${t}.json`);ge.existsSync(h)?o=JSON.parse(ge.readFileSync(h,"utf-8")).name||t:o=t}catch{o=t}let i=e.scenarioType||null;if(!i)try{const h=se.join(a,`${t}.json`);ge.existsSync(h)&&(i=JSON.parse(ge.readFileSync(h,"utf-8")).type||null)}catch{}const l=se.join(s,"active-scenario.json");ge.mkdirSync(s,{recursive:!0}),ge.writeFileSync(l,JSON.stringify({scenarioSlug:o,scenarioName:e.scenarioName||o,scenarioId:t,type:i,dataFile:`.codeyam/editor-scenarios/${t}.json`,switchedAt:new Date().toISOString()},null,2));let c=null,p;const u=i==="application"||i==="user";if(u)if(fn&&fn.scenarioId===t)c=await fn.promise;else{const h=Mr(r),m=se.join(a,`${t}.seed.json`);if(h&&ge.existsSync(m)){const f=Xo(h,m).then(g=>({success:g.success,error:g.error,sessionCookies:g.sessionCookies}));fn={scenarioId:t,promise:f};try{const g=await f;c={success:g.success,error:g.error},p=g.sessionCookies}finally{fn&&fn.scenarioId===t&&(fn=null)}if(c!=null&&c.success&&p&&p.length>0)try{const g=se.join(a,`${t}.json`),y=JSON.parse(ge.readFileSync(g,"utf-8"));y.sessionCookies=p,ge.writeFileSync(g,JSON.stringify(y,null,2))}catch{}}else h||(c={success:!1,error:"No seed adapter found"})}return{success:!0,scenarioSlug:o,scenarioId:t,type:i,seeded:u,...c?{seedResult:c}:{},...p&&p.length>0?{sessionCookies:p}:{}}}function O0(e){return er.createHash("sha256").update(JSON.stringify(e)).digest("hex")}function L0(e){const t=e.match(/^(GET|POST|PUT|DELETE|PATCH)\s+(\/\S+)$/);return t?{method:t[1],pathPattern:t[2]}:{method:null,pathPattern:e}}function B0(e){const t=[],r=e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(s,a)=>(t.push(a),"([^/]+)"));return{regex:new RegExp(`^${r}$`),paramNames:t}}function z0(e,t){if(t.includes(e))return e;const r=e.lastIndexOf("/");if(r>0){const s=e.substring(0,r);if(t.includes(s))return s}return null}function Y0(){let e=[],t={},r=null,s=null,a=!1,o=null;function i(p){const u=[],h=p.routes;if(h&&typeof h=="object")for(const[m,f]of Object.entries(h)){const{method:g,pathPattern:y}=L0(m),{regex:x,paramNames:b}=B0(y),w=typeof f=="object"&&f!==null?f:{body:f};u.push({method:g,pathPattern:y,pathRegex:x,paramNames:b,response:{body:w.body,status:typeof w.status=="number"?w.status:200}})}return u}function l(p){const u=p.state;if(u&&typeof u=="object"){a=!0,t={};for(const[h,m]of Object.entries(u))t[h]=Array.isArray(m)?JSON.parse(JSON.stringify(m)):[];r=JSON.stringify(u)}else a=!1,t={},r=null}return{loadScenario(p){const u=O0(p);s&&u===s||(s=u,o=p,e=i(p),l(p))},matchRequest(p,u,h){if(!o&&e.length===0&&!a)return null;const m=Object.keys(t);if(a){const g=z0(u,m);if(g&&p==="GET"&&g===u)return{body:t[g],status:200};if(g){const y=c(p,u);if(p==="POST"&&g===u&&y){const x=t[g],b=typeof h=="object"&&h!==null?{...h}:{};if(!("id"in b)){const w=x.reduce((v,N)=>{const S=typeof N.id=="number"?N.id:0;return Math.max(v,S)},0);b.id=w+1}return x.push(b),{body:b,status:y.response.status}}if(p==="DELETE"&&y&&y.params){const x=y.params.id,b=t[g],w=b.findIndex(v=>String(v.id)===String(x));return w===-1?{body:{error:"Not found"},status:404}:(b.splice(w,1),{body:null,status:y.response.status})}if(p==="PUT"&&y&&y.params){const x=y.params.id,b=t[g],w=b.findIndex(N=>String(N.id)===String(x));if(w===-1)return{body:{error:"Not found"},status:404};const v=typeof h=="object"&&h!==null?{...h}:b[w];return b[w]=v,{body:v,status:y.response.status}}}}const f=c(p,u);if(f)return{body:f.response.body??null,status:f.response.status,params:f.params};if(o&&p==="GET"){const g=u.match(/^\/api\/(.+)$/);if(g){const y=g[1];if(y in o&&y!=="routes"&&y!=="state")return{body:o[y],status:200}}}return null},resetState(){if(r){const p=JSON.parse(r);t={};for(const[u,h]of Object.entries(p))t[u]=Array.isArray(h)?JSON.parse(JSON.stringify(h)):[]}},getState(){return{...t}}};function c(p,u){for(const h of e)if(h.method!==null&&h.method===p&&h.paramNames.length===0&&h.pathRegex.exec(u))return{response:h.response};if(p==="GET"){for(const h of e)if(h.method===null&&h.paramNames.length===0&&h.pathRegex.exec(u))return{response:h.response}}for(const h of e)if(h.paramNames.length>0){if((h.method??"GET")!==p)continue;const f=h.pathRegex.exec(u);if(f){const g={};for(let y=0;y<h.paramNames.length;y++)g[h.paramNames[y]]=f[y+1];return{response:h.response,params:g}}}return null}}function W0(e){var a,o;const t=se.join(e,"package.json");if(!ge.existsSync(t))return{error:"No package.json found."};let r="npm",s=["run","dev"];try{const i=JSON.parse(ge.readFileSync(t,"utf8"));if(ge.existsSync(se.join(e,"pnpm-lock.yaml"))?r="pnpm":ge.existsSync(se.join(e,"yarn.lock"))?r="yarn":ge.existsSync(se.join(e,"bun.lockb"))&&(r="bun"),!((a=i.scripts)!=null&&a.dev))if((o=i.scripts)!=null&&o.start)s=["run","start"];else return{error:'No "dev" or "start" script found in package.json.'}}catch{}return{command:r,args:s}}function U0(e,t){const r=t.toString(),s={PORT:r},a=se.join(e,".codeyam","config.json");if(ge.existsSync(a))try{const c=(JSON.parse(ge.readFileSync(a,"utf8")).webapps||[])[0];if(c!=null&&c.startCommand){const{command:p,args:u,env:h}=c.startCommand,m=(u||[]).map(f=>f.includes("$PORT")?f.replace(/\$PORT/g,r):f);if(h)for(const[f,g]of Object.entries(h))typeof g=="string"&&g.includes("$PORT")?s[f]=g.replace(/\$PORT/g,r):typeof g=="string"&&(s[f]=g);return{command:p,args:m,env:s}}}catch{}const o=W0(e);return"error"in o?o:{command:o.command,args:o.args,env:s}}function Md(e){return{proxyPort:e+1,devServerPort:e+2}}const J0=[/Local:\s+(https?:\/\/[^\s]+)/,/Ready on\s+(https?:\/\/[^\s]+)/i,/started at\s+(https?:\/\/[^\s]+)/i,/listening on\s+(https?:\/\/[^\s]+)/i,/waiting on\s+(https?:\/\/[^\s]+)/i,/http:\/\/localhost:\d+/];function H0(e){for(const t of J0){const r=e.match(t);if(r){const s=r[1]||r[0];return V0(s).trim()}}return null}function V0(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function ei(){const e=globalThis.__codeyam_editor_dev_server__;return e&&e.status==="running"&&e.url?e.url:null}async function G0(e,t={}){const{intervalMs:r=2e3,maxAttempts:s=15}=t,a=`http://localhost:${e}`;for(let o=0;o<s;o++){try{const i=await fetch(a,{method:"HEAD",signal:AbortSignal.timeout(2e3)});if(i.ok||i.status===304)return a}catch{}o<s-1&&await new Promise(i=>setTimeout(i,r))}return null}function K0(e){const{exitCode:t,uptime:r,retryCount:s,wasRunning:a}=e,o=r<1e4;return t!==0&&t!==null&&o&&s===0?{action:"retry"}:t!==0&&t!==null?{action:"error"}:a===!1?{action:"error"}:{action:"stopped"}}class q0 extends Fr{emitDataMutationForwarded(t,r){this.emit("event",{type:"data-mutation-forwarded",method:t,pathname:r,timestamp:Date.now()})}}const ho="__codeyam_mock_state_event_emitter__";if(!globalThis[ho]){const e=new q0;e.setMaxListeners(20),globalThis[ho]=e}const Q0=globalThis[ho];function Z0(e){try{return new URL(e).toString().replace(/\/$/,"")}catch{return e}}async function X0(e){const t=["127.0.0.1","::1"];for(const r of t)try{if(await new Promise(a=>{const o=new Lc.Socket;o.setTimeout(1e3),o.once("connect",()=>{o.destroy(),a(!0)}),o.once("error",()=>{o.destroy(),a(!1)}),o.once("timeout",()=>{o.destroy(),a(!1)}),o.connect(e,r)}))return r}catch{}return null}const $d="__codeyam_editor_proxy__",Id="__codeyam_preview_health__";function Rd(){return globalThis[Id]??null}function Dd(e){globalThis[Id]=e}function Nl(){return Rd()}function Fd(){Dd(null)}const ey=`<script data-codeyam-health>
141
+ (function() {
142
+ var errors = [];
143
+ var reported = false;
144
+ function report(type, msg, stack) {
145
+ errors.push({ type: type, message: msg, stack: stack, timestamp: Date.now() });
146
+ if (!reported) {
147
+ reported = true;
148
+ setTimeout(function() { flush(); }, 500);
149
+ }
150
+ }
151
+ function flush() {
152
+ fetch('/__codeyam__/preview-health', {
153
+ method: 'POST',
154
+ headers: { 'Content-Type': 'application/json' },
155
+ body: JSON.stringify({ errors: errors, url: location.href })
156
+ }).catch(function(){});
157
+ reported = false;
158
+ errors = [];
159
+ }
160
+ window.addEventListener('error', function(e) {
161
+ report('error', e.message, e.error && e.error.stack);
162
+ });
163
+ window.addEventListener('unhandledrejection', function(e) {
164
+ report('unhandledrejection', String(e.reason), e.reason && e.reason.stack);
165
+ });
166
+ var origError = console.error;
167
+ console.error = function() {
168
+ report('console.error', Array.prototype.join.call(arguments, ' '));
169
+ origError.apply(console, arguments);
170
+ };
171
+ window.addEventListener('load', function() {
172
+ setTimeout(function() {
173
+ var hasContent = document.body && document.body.innerText.trim().length > 0;
174
+ fetch('/__codeyam__/preview-health', {
175
+ method: 'POST',
176
+ headers: { 'Content-Type': 'application/json' },
177
+ body: JSON.stringify({
178
+ loaded: true,
179
+ hasContent: hasContent,
180
+ url: location.href,
181
+ errorCount: errors.length
182
+ })
183
+ }).catch(function(){});
184
+ }, 1000);
185
+ });
186
+
187
+ // Network-idle detection: notify the parent editor when all initial
188
+ // fetch requests have completed, so it can show the preview after
189
+ // client-side data (API calls) has arrived — not just when the DOM loads.
190
+ var inflight = 0;
191
+ var settled = false;
192
+ var settleTimer = null;
193
+ var origFetch = window.fetch;
194
+ window.fetch = function() {
195
+ if (!settled) inflight++;
196
+ return origFetch.apply(this, arguments).then(function(resp) {
197
+ if (!settled) { inflight--; checkSettle(); }
198
+ return resp;
199
+ }, function(err) {
200
+ if (!settled) { inflight--; checkSettle(); }
201
+ throw err;
202
+ });
203
+ };
204
+ function checkSettle() {
205
+ if (inflight <= 0 && !settled) {
206
+ clearTimeout(settleTimer);
207
+ // Small delay to allow React to re-render with the fetched data
208
+ settleTimer = setTimeout(function() {
209
+ if (inflight <= 0) {
210
+ settled = true;
211
+ try {
212
+ window.parent.postMessage({ type: 'codeyam-preview-ready' }, '*');
213
+ } catch(e) {}
214
+ }
215
+ }, 100);
216
+ }
217
+ }
218
+ // Fallback: if no fetches happen (static page), settle after load
219
+ window.addEventListener('load', function() {
220
+ setTimeout(function() { checkSettle(); }, 200);
221
+ });
222
+ })();
223
+ <\/script>`,ty=500;let Yt={data:null,timestamp:0},bn,_r,ua=null,pa=null,ha=null,mo=null;const Sl=10*1024*1024;function ma(){return globalThis[$d]??null}function Od(e){globalThis[$d]=e}function Ld(){const e="__codeyam_mock_state__";return globalThis[e]||(globalThis[e]=Y0()),globalThis[e]}function Bd(){const e=ma();return e?`http://localhost:${e.port}`:null}function ny(){const e=Date.now();if(Yt.data!==null&&e-Yt.timestamp<ty)return Yt.data;const t=Ne()||process.env.CODEYAM_ROOT_PATH||process.cwd(),r=se.join(t,".codeyam","active-scenario.json");try{if(!ge.existsSync(r))return Yt={data:null,timestamp:e},null;const s=JSON.parse(ge.readFileSync(r,"utf-8")),a=s.scenarioId;if(!a)return ha=s.prototypeId||null,Yt={data:null,timestamp:e},null;const o=se.join(t,".codeyam","editor-scenarios",`${a}.json`);if(!ge.existsSync(o))return console.log(`[editorProxy] Scenario data file not found: ${o}`),Yt={data:null,timestamp:e},null;const i=JSON.parse(ge.readFileSync(o,"utf-8"));bn=i.session||null,_r=i.sessionCookies||void 0,ua=i.localStorage||null,pa=a;const l=s.type||i.type||null;mo=l;let c;return(l==="application"||l==="user")&&i.seed?i.externalApis&&typeof i.externalApis=="object"?c={routes:i.externalApis}:c={}:c=i,Yt={data:c,timestamp:e},Ld().loadScenario(c),c}catch(s){return console.warn("[editorProxy] Error reading scenario data:",s),Yt={data:null,timestamp:e},null}}function ry(e){return new Promise(t=>{const r=[];let s=0;e.on("data",a=>{s+=a.length,s>Sl?(t(null),e.resume()):r.push(a)}),e.on("end",()=>{s>Sl||t(Buffer.concat(r))}),e.on("error",()=>{t(null)})})}function ti(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function Cl(e,t,r,s){const a=new URL(r),o=ti(a.hostname),i={...e.headers,host:`${a.hostname}:${a.port}`};delete i["accept-encoding"],s&&(i["content-length"]=String(s.length));const l={hostname:o,port:a.port,path:e.url,method:e.method,headers:i},c=Io.request(l,p=>{const u=p.statusCode||200;u>=400&&console.warn(`[editorProxy] Target returned ${u} for ${e.method} ${e.url}`);const h={...p.headers};if(zd(h),(p.headers["content-type"]||"").includes("text/html")){Fd();const f=[];p.on("data",g=>f.push(g)),p.on("end",()=>{const g=Buffer.concat(f).toString("utf-8"),y=Yd(ua,pa||"",ha),x=Wd(g,y);delete h["content-length"],delete h["content-encoding"],h["cache-control"]="no-store, must-revalidate",t.writeHead(u,h),t.end(x)});return}t.writeHead(u,h),p.pipe(t,{end:!0})});c.on("error",p=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${p.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),s&&s.length>0?c.end(s):c.end()}function sy(e,t,r){const s=new URL(r),a=ti(s.hostname),{"accept-encoding":o,...i}=e.headers,l={hostname:a,port:s.port,path:e.url,method:e.method,headers:{...i,host:`${s.hostname}:${s.port}`}},c=Io.request(l,p=>{const u=p.statusCode||200;u>=400&&console.warn(`[editorProxy] Target returned ${u} for ${e.method} ${e.url}`);const h={...p.headers};if(zd(h),(p.headers["content-type"]||"").includes("text/html")){Fd();const f=[];p.on("data",g=>f.push(g)),p.on("end",()=>{const g=Buffer.concat(f).toString("utf-8"),y=Yd(ua,pa||"",ha),x=Wd(g,y);delete h["content-length"],delete h["content-encoding"],h["cache-control"]="no-store, must-revalidate",t.writeHead(u,h),t.end(x)});return}t.writeHead(u,h),p.pipe(t,{end:!0})});c.on("error",p=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${p.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),e.pipe(c,{end:!0})}function zd(e){const t=[];if(bn!==void 0&&(bn!=null&&bn.cookieValue?t.push(`session-token=${bn.cookieValue}; Path=/; SameSite=Lax`):t.push("session-token=; Path=/; Max-Age=0")),_r&&_r.length>0)for(const s of _r){const a=s.path||"/",o=s.sameSite||"Lax";t.push(`${s.name}=${s.value}; Path=${a}; SameSite=${o}`)}if(t.length===0)return;const r=e["set-cookie"];r?e["set-cookie"]=[...Array.isArray(r)?r:[r],...t]:e["set-cookie"]=t}function ay(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)|0;return(t>>>0).toString(36)}function Yd(e,t,r){if(!e||typeof e!="object"){const c=t?`clear:${t}`:"";return r?`<script data-codeyam-ls>
224
+ (function() {
225
+ if (localStorage.getItem('__codeyam_proto__') === ${JSON.stringify(r)}) return;
226
+ localStorage.clear();
227
+ localStorage.setItem('__codeyam_proto__', ${JSON.stringify(r)});
228
+ })();
229
+ <\/script>`:t?`<script data-codeyam-ls>
230
+ (function() {
231
+ if (localStorage.getItem('__codeyam_ls_sid__') === ${JSON.stringify(c)}) return;
232
+ var prev = JSON.parse(localStorage.getItem('__codeyam_ls_keys__') || '[]');
233
+ for (var i = 0; i < prev.length; i++) localStorage.removeItem(prev[i]);
234
+ localStorage.removeItem('__codeyam_ls_keys__');
235
+ localStorage.setItem('__codeyam_ls_sid__', ${JSON.stringify(c)});
236
+ })();
237
+ <\/script>`:""}const s=Object.entries(e),a=s.map(([c])=>c),o=s.map(([c,p])=>{const u=typeof p=="string"?p:JSON.stringify(p);return`localStorage.setItem(${JSON.stringify(c)}, ${JSON.stringify(u)});`}).join(`
238
+ `),i=ay(JSON.stringify(e)),l=`${t}:${i}`;return`<script data-codeyam-ls>
239
+ (function() {
240
+ if (localStorage.getItem('__codeyam_ls_sid__') === ${JSON.stringify(l)}) return;
241
+ var prev = JSON.parse(localStorage.getItem('__codeyam_ls_keys__') || '[]');
242
+ for (var i = 0; i < prev.length; i++) localStorage.removeItem(prev[i]);
243
+ ${o}
244
+ localStorage.setItem('__codeyam_ls_keys__', ${JSON.stringify(JSON.stringify(a))});
245
+ localStorage.setItem('__codeyam_ls_sid__', ${JSON.stringify(l)});
246
+ })();
247
+ <\/script>`+oy()}function oy(){return`<script data-codeyam-ls-watcher>
248
+ (function() {
249
+ if (window.__codeyam_ls_watcher_installed__) return;
250
+ window.__codeyam_ls_watcher_installed__ = true;
251
+
252
+ var origSet = localStorage.setItem.bind(localStorage);
253
+ var origRemove = localStorage.removeItem.bind(localStorage);
254
+ var origClear = localStorage.clear.bind(localStorage);
255
+ window.__codeyam_orig_setItem__ = origSet;
256
+ window.__codeyam_orig_removeItem__ = origRemove;
257
+ window.__codeyam_orig_clear__ = origClear;
258
+
259
+ function isInternal(key) {
260
+ return typeof key === 'string' && key.indexOf('__codeyam_') === 0;
261
+ }
262
+
263
+ localStorage.setItem = function(key, value) {
264
+ origSet(key, value);
265
+ if (!isInternal(key) && window.parent !== window) {
266
+ window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'set', key: key }, '*');
267
+ }
268
+ };
269
+
270
+ localStorage.removeItem = function(key) {
271
+ origRemove(key);
272
+ if (!isInternal(key) && window.parent !== window) {
273
+ window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'remove', key: key }, '*');
274
+ }
275
+ };
276
+
277
+ localStorage.clear = function() {
278
+ origClear();
279
+ if (window.parent !== window) {
280
+ window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'clear' }, '*');
281
+ }
282
+ };
283
+
284
+ window.addEventListener('message', function(event) {
285
+ if (event.data && event.data.type === 'codeyam-get-localstorage') {
286
+ var data = {};
287
+ for (var i = 0; i < localStorage.length; i++) {
288
+ var k = localStorage.key(i);
289
+ if (k && !isInternal(k)) {
290
+ data[k] = localStorage.getItem(k);
291
+ }
292
+ }
293
+ event.source.postMessage({ type: 'codeyam-localstorage-state', data: data }, '*');
294
+ }
295
+ });
296
+ })();
297
+ <\/script>`}function Wd(e,t){const r=(t||"")+ey;return e.includes("</head>")?e.replace("</head>",r+"</head>"):e.includes("</body>")?e.replace("</body>",r+"</body>"):e+r}function iy(e,t){const r=[];e.on("data",s=>r.push(s)),e.on("end",()=>{try{const s=JSON.parse(Buffer.concat(r).toString("utf-8")),a=Rd()||{errors:[],loaded:!1,hasContent:!1,url:"",lastUpdated:0};s.errors&&Array.isArray(s.errors)&&(a.errors=a.errors.concat(s.errors)),s.loaded!==void 0&&(a.loaded=s.loaded),s.hasContent!==void 0&&(a.hasContent=s.hasContent),s.url&&(a.url=s.url),a.lastUpdated=Date.now(),Dd(a)}catch{}t.writeHead(204),t.end()})}function ly(e,t,r,s){const a=new URL(s),o=ti(a.hostname),i=parseInt(a.port,10)||80;console.log(`[editorProxy] WebSocket upgrade: ${e.url} → ${o}:${i}`);const l=Lc.connect(i,o,()=>{const c=`${e.method} ${e.url} HTTP/${e.httpVersion}\r
298
+ `,p=Object.entries(e.headers).filter(([,u])=>u!=null).map(([u,h])=>`${u}: ${Array.isArray(h)?h.join(", "):h}`).join(`\r
299
+ `);l.write(c+p+`\r
300
+ \r
301
+ `),r.length>0&&l.write(r),l.pipe(t,{end:!0}),t.pipe(l,{end:!0})});l.on("error",c=>{console.warn(`[editorProxy] WebSocket proxy error: ${c.message}`),t.destroy()}),t.on("error",()=>{l.destroy()})}function cy(e,t){const r=Ne()||process.env.CODEYAM_ROOT_PATH||process.cwd(),s=se.join(r,".codeyam","proxy-config.json");try{ge.mkdirSync(se.dirname(s),{recursive:!0}),ge.writeFileSync(s,JSON.stringify({proxyUrl:`http://localhost:${e}`,devServerUrl:t}),"utf-8"),console.log(`[editorProxy] Wrote proxy config to ${s}`)}catch(a){console.warn("[editorProxy] Failed to write proxy-config.json:",a)}}function dy(){const e=Ne()||process.env.CODEYAM_ROOT_PATH||process.cwd(),t=se.join(e,".codeyam","proxy-config.json");try{ge.existsSync(t)&&ge.unlinkSync(t)}catch{}}async function fo(e){const t=ma();if(t)return console.log(`[editorProxy] Proxy already running on port ${t.port} → ${t.targetUrl}`),{port:t.port};await Ud();let r=Z0(e.targetUrl),s=e.port;try{const l=new URL(r);if(l.hostname==="localhost"){const c=parseInt(l.port||"80",10),p=await X0(c);p&&(l.hostname=p,r=l.toString().replace(/\/$/,""),console.log(`[editorProxy] Resolved localhost to ${p} for port ${c}`))}}catch{}console.log(`[editorProxy] Starting proxy (requested port ${s}, target ${r})`);const a=Ld(),o=Io.createServer((l,c)=>{(async()=>{const u=new URL(l.url||"/",`http://localhost:${s}`).pathname,h=l.method||"GET";if(h==="OPTIONS"){c.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Max-Age":"86400"}),c.end();return}if(h==="POST"&&u==="/__codeyam__/preview-health"){iy(l,c);return}if(ny(),h==="POST"||h==="PUT"||h==="DELETE"||h==="PATCH"){const g=await ry(l);if(g===null){Cl(l,c,r,null);return}let y;if(g.length>0)try{y=JSON.parse(g.toString("utf-8"))}catch{}const x=a.matchRequest(h,u,y);if(x){console.log(`[editorProxy] Intercepted ${h} ${u} → mock response (status ${x.status})`),c.writeHead(x.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data","Cache-Control":"no-store"}),c.end(x.body!=null?JSON.stringify(x.body):"");return}(mo==="application"||mo==="user")&&u.startsWith("/api/")&&Q0.emitDataMutationForwarded(h,u),Cl(l,c,r,g);return}const f=a.matchRequest(h,u);if(f){console.log(`[editorProxy] Intercepted ${h} ${u} → mock response (status ${f.status})`),c.writeHead(f.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data","Cache-Control":"no-store"}),c.end(f.body!=null?JSON.stringify(f.body):"");return}sy(l,c,r)})()});o.on("upgrade",(l,c,p)=>{ly(l,c,p,r)});const i=10;for(let l=0;l<i;l++){const c=s+l;try{await new Promise((h,m)=>{o.once("error",m),o.listen(c,"0.0.0.0",()=>{o.removeListener("error",m),h()})});const p=o.address();return s=typeof p=="object"&&p!==null?p.port:c,Od({server:o,port:s,targetUrl:r}),cy(s,r),console.log(`[editorProxy] Proxy started on port ${s}, forwarding to ${r}`),{port:s}}catch(p){if((p==null?void 0:p.code)==="EADDRINUSE"&&l<i-1){console.log(`[editorProxy] Port ${c} in use, trying ${c+1}`);continue}return console.error("[editorProxy] Failed to start proxy:",p),null}}return null}async function Ud(){const e=ma();if(e)return console.log(`[editorProxy] Stopping proxy on port ${e.port}`),dy(),new Promise(t=>{e.server.close(()=>{console.log("[editorProxy] Proxy stopped"),t()}),Od(null),setTimeout(t,2e3)})}function En(){Yt={data:null,timestamp:0},bn=void 0,_r=void 0,ua=null,pa=null,ha=null}async function kl(){const e=ma();if(!e)return console.warn("[editorProxy] Cannot verify — proxy is not running"),!1;try{const t=await fetch(`http://127.0.0.1:${e.port}/`,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return t.status===502?(console.warn("[editorProxy] Verification failed — proxy returned 502 (target unreachable)"),!1):(console.log(`[editorProxy] Verification passed — proxy forwarding to ${e.targetUrl} (status ${t.status})`),!0)}catch{return console.warn(`[editorProxy] Verification failed — could not reach proxy on port ${e.port}`),!1}}async function ni(){const e=Bd();if(e)return console.log(`[editorProxy] Proxy already running at ${e}`),e;const t=globalThis.__codeyam_editor_dev_server__;if(!t||t.status!=="running"||!t.url)return console.log("[editorProxy] Cannot start proxy — dev server not running"),null;const r=parseInt(process.env.CODEYAM_PORT||"3111",10),{proxyPort:s}=Md(r);console.log(`[editorProxy] Proxy not running, starting on-demand (port ${s}, target ${t.url})`);const a=await fo({port:s,targetUrl:t.url});if(a){const o=`http://localhost:${a.port}`;return console.log(`[editorProxy] On-demand proxy started at ${o}`),o}return console.error("[editorProxy] Failed to start on-demand proxy"),null}async function uy({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioId:r,scenarioName:s,scenarioSlug:a}=t;if(!r||typeof r!="string")return Response.json({error:"scenarioId is required"},{status:400});const o=Ne()||process.cwd(),i=await da({scenarioId:r,scenarioName:s,scenarioSlug:a,projectRoot:o});return En(),Response.json({success:i.success,seeded:i.seeded,seedResult:i.seedResult})}catch(t){const r=t instanceof Error?t.message:String(t);return Response.json({error:r},{status:500})}}const py=Object.freeze(Object.defineProperty({__proto__:null,action:uy},Symbol.toStringTag,{value:"Module"}));async function hy({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{url:r,filename:s,viewportWidth:a,viewportHeight:o}=t;if(!r||!s)return new Response(JSON.stringify({error:"url and filename are required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=process.env.CODEYAM_ROOT_PATH||process.cwd(),l=U.join(i,".codeyam","journal","screenshots");await _e.mkdir(l,{recursive:!0});const c=s.replace(/[^a-zA-Z0-9_\-T]/g,"_"),p=U.join(l,`${c}.png`),u=U.dirname(new URL(import.meta.url).pathname);let h=u;for(let w=0;w<5;w++){const v=U.dirname(h);if(U.basename(v)==="webserver"||U.basename(h)==="webserver"){h=U.basename(h)==="webserver"?h:v;break}h=v}const m=[U.join(h,"scripts","journalCapture.ts"),U.join(h,"app","lib","journalCapture.ts"),U.join(i,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),U.resolve(u,"..","lib","journalCapture.ts")];let f="";for(const w of m)try{await _e.access(w),f=w;break}catch{}f||(console.warn(`[editor-journal-screenshot] journalCapture.ts not found in any of: ${m.join(", ")}`),f=m[0]);const g=ca({bodyWidth:a,bodyHeight:o,codeyamRoot:i}),y=JSON.stringify({url:r,outputPath:p,viewportWidth:g.width,viewportHeight:g.height}),x=await new Promise(w=>{const v=ft("npx",["tsx",f,y],{cwd:i,env:{...process.env}});let N="",S="";v.stdout.on("data",C=>{N+=C.toString()}),v.stderr.on("data",C=>{S+=C.toString()}),v.on("close",C=>{w(C===0?{success:!0,output:N}:{success:!1,output:N,error:S||`Process exited with code ${C}`})}),v.on("error",C=>{w({success:!1,output:"",error:C.message})})});if(!x.success)return new Response(JSON.stringify({error:"Failed to capture screenshot",details:x.error}),{status:500,headers:{"Content-Type":"application/json"}});const b=`screenshots/${c}.png`;return new Response(JSON.stringify({success:!0,path:b}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-screenshot] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const my=Object.freeze(Object.defineProperty({__proto__:null,action:hy},Symbol.toStringTag,{value:"Module"}));async function fy({request:e}){const t={"Content-Type":"application/json"};try{const r=Ne()||process.cwd(),s=await e.json(),{scenarioId:a,table:o,rowIndex:i,column:l,value:c}=s;if(!a||!o||i==null||!l)return new Response(JSON.stringify({success:!1,error:"Missing required fields"}),{headers:t,status:400});const p=U.join(r,".codeyam","editor-scenarios",`${a}.json`);if(!V.existsSync(p))return new Response(JSON.stringify({success:!1,error:"Scenario file not found"}),{headers:t,status:404});const u=JSON.parse(V.readFileSync(p,"utf-8"));if(Array.isArray(u[o])&&i<u[o].length)return u[o][i][l]=c,V.writeFileSync(p,JSON.stringify(u,null,2)),new Response(JSON.stringify({success:!0}),{headers:t});if(u.seed&&typeof u.seed=="object"){const h=o.charAt(0).toLowerCase()+o.slice(1);for(const m of[o,h,`${h}s`])if(Array.isArray(u.seed[m])&&i<u.seed[m].length){u.seed[m][i][l]=c,V.writeFileSync(p,JSON.stringify(u,null,2));const f=p.replace(/\.json$/,".seed.json");if(V.existsSync(f))try{const g=JSON.parse(V.readFileSync(f,"utf-8"));Array.isArray(g[m])&&(g[m][i][l]=c,V.writeFileSync(f,JSON.stringify(g,null,2)))}catch{}return new Response(JSON.stringify({success:!0}),{headers:t})}}if(u.localStorage&&typeof u.localStorage=="object"){for(const[h,m]of Object.entries(u.localStorage))if(typeof m=="string")try{let f=JSON.parse(m);const g=!Array.isArray(f)&&typeof f=="object"&&f!==null;if(g&&(f=[f]),!Array.isArray(f))continue;const y=o.charAt(0).toLowerCase()+o.slice(1),x=()=>{f[i][l]=c;const b=g?f[0]:f;u.localStorage[h]=JSON.stringify(b),V.writeFileSync(p,JSON.stringify(u,null,2))};if((h===o||h===y||h===`${y}s`||h===`${o}s`)&&i<f.length)return x(),new Response(JSON.stringify({success:!0}),{headers:t});if(f.length>0&&l in f[0]&&i<f.length)return x(),new Response(JSON.stringify({success:!0}),{headers:t})}catch{}}return new Response(JSON.stringify({success:!1,error:"Table not found in scenario"}),{headers:t,status:404})}catch(r){return new Response(JSON.stringify({success:!1,error:r instanceof Error?r.message:"Unknown error"}),{headers:t,status:500})}}const gy=Object.freeze(Object.defineProperty({__proto__:null,action:fy},Symbol.toStringTag,{value:"Module"})),Jd=Eo({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),ri=()=>{const e=Js(Jd);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},fa=({children:e})=>{const[t,r]=P({height:720,width:1200}),[s,a]=P(1),[o,i]=P(1200),l=fe(null),c=ce(({height:h,width:m})=>{r(f=>({height:h??f.height,width:m??f.width}))},[]),p=ce(h=>{a(h)},[]),u=ce(h=>{i(h)},[]);return n(Jd.Provider,{value:{dimensions:t,updateDimensions:c,iframeRef:l,scale:s,updateScale:p,maxWidth:o,updateMaxWidth:u},children:e})},yy=typeof window<"u";function xy(){const[e,t]=P(null);return ae(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const by=1200,wy=720,_l=30,vy=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:s=1440,defaultHeight:a=900,onDataOverride:o,onIframeLoad:i,onScaleChange:l,onDimensionChange:c})=>{const p=xy(),[u,h]=P(!1),[m,f]=P(!1),[g,y]=P(by),[x,b]=P(wy),[w,v]=P(null),[N,S]=P(null),{dimensions:C,updateDimensions:A,iframeRef:_,updateScale:E,updateMaxWidth:R}=ri(),D=ie(()=>Math.min(1,g/C.width),[g,C.width]),T=N!==null?N:D;ae(()=>{u||(E(T),l==null||l(T))},[T,E,l,u]),ae(()=>{R(g)},[g,R]);const $=ce(()=>{h(!0),S(D)},[D]),L=ce(()=>{h(!1),S(null)},[]),B=ce((I,j)=>{const k=N!==null?N:1,Y=Math.round(j.size.width/k);A({width:Y}),c==null||c(Y,C.height)},[A,N,c,C.height]),H=ce(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);ae(()=>{const I=j=>{if(j.data.type==="codeyam-resize"){if(t&&j.data.name!==t||C.height===j.data.height||j.data.height===0)return;A({height:j.data.height})}};return window.addEventListener("message",I),()=>{window.removeEventListener("message",I)}},[_,t,s,C,A]),ae(()=>{m&&o&&o(_.current)},[m,o,_]),ae(()=>{if(!t)return;const I=setInterval(()=>{var j,k;(k=(j=_==null?void 0:_.current)==null?void 0:j.contentWindow)==null||k.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(I)},[t,_]),ae(()=>{const I=()=>{const j=document.getElementById("scenario-container");if(!j)return;const k=j.getBoundingClientRect(),Y=j.clientWidth-_l*2,G=window.innerHeight-k.top-_l*2,Q=Math.max(G,400),K=window.innerHeight-k.top;y(Y),b(Q),v(K)};return I(),window.addEventListener("resize",I),()=>window.removeEventListener("resize",I)},[]),ae(()=>{A({width:s,height:a})},[s,a,A]);const q=ie(()=>C.width*T,[C.width,T]),O=ie(()=>{const I=C.height,j=I*T;return I&&I!==720&&I!==900&&j<x?j:x},[C.height,x,T]),W=ce(()=>{window.history.back()},[]);return!yy||!p?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):d("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:w?{height:`${w}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
302
+ .react-resizable-handle-e {
303
+ display: flex !important;
304
+ align-items: center !important;
305
+ justify-content: center !important;
306
+ width: 6px !important;
307
+ height: 48px !important;
308
+ right: -8px !important;
309
+ top: 50% !important;
310
+ transform: translateY(-50%) !important;
311
+ cursor: ew-resize !important;
312
+ background: #d1d5db !important;
313
+ border-radius: 3px !important;
314
+ opacity: 0 !important;
315
+ transition: all 0.2s ease !important;
316
+ }
317
+ .react-resizable-handle-e:hover {
318
+ opacity: 0.8 !important;
319
+ background: #9ca3af !important;
320
+ }
321
+ .react-resizable:hover .react-resizable-handle-e {
322
+ opacity: 0.4 !important;
323
+ }
324
+ `}),n(p,{width:q,height:O,minConstraints:[300,200],maxConstraints:[g,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:$,onResizeStop:L,onResize:B,children:n("div",{className:"overflow-auto",style:{width:`${q}px`,height:`${O}px`},children:n("div",{style:{width:`${C.width}px`,height:`${C.height}px`,transform:`scale(${T})`,transformOrigin:"top left"},children:r?n("iframe",{ref:_,className:"w-full h-full rounded-lg",src:r,onLoad:H,sandbox:"allow-scripts allow-same-origin"}):d("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[n("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),n("span",{className:"text-blue-600 cursor-pointer",onClick:W,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function Ny({presets:e,customSizes:t,currentWidth:r,currentHeight:s,scale:a,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:l,className:c=""}){const[p,u]=P(!1),[h,m]=P(String(r)),[f,g]=P(String(s)),[y,x]=P(!1),[b,w]=P(!1),v=fe(null);ae(()=>{y||m(String(r))},[r,y]),ae(()=>{b||g(String(s))},[s,b]),ae(()=>{const T=$=>{v.current&&!v.current.contains($.target)&&u(!1)};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[]);const N=ie(()=>{const T=e.find(L=>L.width===r&&L.height===s);if(T)return T.name;const $=t.find(L=>L.width===r&&L.height===s);return $?$.name:"Custom"},[e,t,r,s]),S=N==="Custom",C=T=>{o(T.width,T.height),u(!1)},A=T=>{const $=T.target.value;m($);const L=parseInt($,10);!isNaN(L)&&L>0&&o(L,s)},_=T=>{const $=T.target.value;g($);const L=parseInt($,10);!isNaN(L)&&L>0&&o(r,L)},E=()=>{x(!1);const T=parseInt(h,10);(isNaN(T)||T<=0)&&m(String(r))},R=()=>{w(!1);const T=parseInt(f,10);(isNaN(T)||T<=0)&&g(String(s))},D=T=>{(T.key==="Enter"||T.key==="Escape")&&T.target.blur()};return d("div",{className:`flex items-center gap-3 ${c}`,children:[d("div",{className:"relative",ref:v,children:[d("button",{onClick:()=>u(!p),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:N}),n("svg",{className:`w-4 h-4 transition-transform ${p?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),p&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:d("div",{className:"py-1",children:[e.length>0&&d(we,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(T=>d("button",{onClick:()=>C(T),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${N===T.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:T.name}),d("span",{className:"text-xs text-gray-500",children:[T.width," x ",T.height]})]},T.name))]}),t.length>0&&d(we,{children:[n("div",{className:"border-t border-gray-100 my-1"}),n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Custom"}),[...t].sort((T,$)=>T.width-$.width).map(T=>d("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${N===T.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[d("button",{onClick:()=>C(T),className:"flex-1 text-left px-3 py-2 text-sm flex justify-between items-center gap-4 whitespace-nowrap cursor-pointer",children:[n("span",{children:T.name}),d("span",{className:"text-xs text-gray-500",children:[T.width," x ",T.height]})]}),l&&n("button",{onClick:$=>{$.stopPropagation(),N===T.name&&e.length>0&&o(e[0].width,e[0].height),l(T.name)},className:"p-1.5 mr-1 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded cursor-pointer transition-colors",title:"Remove custom size",children:n("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},T.name))]})]})})]}),d("div",{className:"flex items-center gap-1 text-sm",children:[d("div",{className:"flex items-center",children:[n("input",{type:"text",value:h,onChange:A,onFocus:()=>x(!0),onBlur:E,onKeyDown:D,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),d("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:_,onFocus:()=>w(!0),onBlur:R,onKeyDown:D,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),a!==void 0&&a<1&&d("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(a*100),"%)"]})]}),S&&n("button",{onClick:i,className:"px-3 py-1.5 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors",children:"Save Custom Size"})]})}function Ga(e,t,r){if(Array.isArray(e)){if(!isNaN(parseInt(t)))return e[parseInt(t)];for(const s of e)if(s.name===t||s.title===t||s.id===t)return s}return e[t]}function go(e){return e&&(typeof e=="object"||Array.isArray(e))}function Sy(e){return Array.isArray(e)?e.length:void 0}function Cy(e){const{data:t,structure:r}=e;if(!(!t&&!r)){if(Array.isArray(r))return Array.isArray(t)?t.map((s,a)=>a.toString()):[];if(typeof r=="object")return[...new Set([...Object.keys(t),...Object.keys(r)])].sort((a,o)=>{const i=go(t[a]),l=go(t[o]);return i&&!l?1:!i&&l?-1:a.localeCompare(o)});if(typeof t=="object")return Object.keys(t).sort((a,o)=>a.localeCompare(o))}}function ky({scenarioFormData:e,handleInputChange:t}){return d("div",{className:"p-3 flex flex-col gap-3",children:[d("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),n("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),d("div",{className:"grid w-full gap-1.5 pt-2",children:[n("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),n("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[100px]"})]}),n("button",{type:"submit",className:"mt-3 w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium",children:"Save Name & Description"})]})}function _y({path:e,namedPath:t,isArray:r,count:s,onClick:a}){const o=ce(()=>{a&&a(e)},[a,e]);return d("div",{className:"bg-blue-50 p-3 rounded-lg flex items-center justify-between cursor-pointer group hover:bg-blue-100 transition-colors border border-blue-200",onClick:o,children:[d("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),d("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],s!==void 0&&` (${s})`]})]}),d("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var Hd=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Hd||{});const Ey=({name:e,value:t,options:r,onChange:s})=>{const a=ce(o=>{s({target:{name:e,value:o.target.value}})},[e,s]);return n("select",{name:e,value:t,onChange:a,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",children:r.map((o,i)=>n("option",{value:o.trim(),children:o.trim()},i))})},Ay=({name:e,value:t,onChange:r})=>{const s=ce(a=>{const o=a.target.checked;r({target:{name:e,value:o}})},[e,r]);return n("label",{className:"flex items-center gap-2 cursor-pointer",children:n("input",{type:"checkbox",name:e,checked:t,onChange:s,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
325
+ bg-gray-300 checked:bg-blue-600
326
+ after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
327
+ after:bg-white after:rounded-full after:transition-transform
328
+ checked:after:translate-x-4`})})};function Py({dataType:e,path:t,value:r,onChange:s}){const a=ie(()=>t[t.length-1],[t]),o=ie(()=>t.join("-"),[t]),i=ce(c=>{s(t,c.target.value)},[s,t]),l=ce(c=>{s(t,c.target.value)},[s,t]);return d("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:o,className:"capitalize text-sm font-medium text-gray-700",children:a==="~~codeyam-code~~"?"Dynamic Field":a}),e.includes("|")?n(Ey,{name:o,value:r,options:e.split("|"),onChange:i}):e===Hd.BOOLEAN?n(Ay,{name:o,value:r??!1,onChange:l}):n("input",{id:o,name:o,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${o}`)]})}function jy({analysis:e,scenarioName:t,dataItem:r,onResult:s,onGenerateData:a}){const[o,i]=P(!1),[l,c]=P(""),p=ce(async()=>{if(!a){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const h=e.scenarios.find(x=>x.name===t);if(!h)throw new Error("Scenario not found");const m=e.scenarios.find(x=>x.name===Qs),f=await a(l,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const g=(x,b)=>{const w=Object.assign({},x);return y(x)&&y(b)&&Object.keys(b).forEach(v=>{y(b[v])?v in x?w[v]=g(x[v],b[v]):Object.assign(w,{[v]:b[v]}):Object.assign(w,{[v]:b[v]})}),w},y=x=>x&&typeof x=="object"&&!Array.isArray(x);h.metadata.data=g(g((m==null?void 0:m.metadata.data)||{},h.metadata.data),f.data||{}),s(h),i(!1),c("")}catch(h){console.error("Error generating AI data:",h),i(!1)}},[e,l,r,t,s,a]),u=ce(h=>{c(h.target.value)},[]);return d("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:l}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${l.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void p(),children:o?d(we,{children:[d("svg",{className:"animate-spin h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Please wait"]}):"Generate Data"})]})}function Ty({namedPath:e,path:t,last:r,onClick:s}){const a=ce(()=>s(r?t.slice(0,-1):t),[r,t,s]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:a,children:e[e.length-1]})}function My({dataItem:e,onClick:t}){const r=ce(()=>t([]),[t]),s=ie(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return d("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&d("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(s).map((a,o)=>d("div",{className:"flex items-center gap-1",children:[n(Ty,{namedPath:e.namedPath.slice(0,o+s+1),path:e.path.slice(0,o+s+1),last:o+s===e.namedPath.length-1,onClick:t}),o+s<e.namedPath.length-1&&n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},`path-${a}-${o+s}`))]})}function El({analysis:e,scenarioName:t,dataItem:r,onClick:s,onChange:a,onAIResult:o,onGenerateData:i,saveFeedback:l}){const c=ie(()=>r.data,[r]),p=ie(()=>Cy(r),[r]);return d("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(My,{dataItem:r,onClick:s}),d("div",{className:"flex flex-col gap-3",children:[n(jy,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),p==null?void 0:p.map((u,h)=>{var f;if(go(c[u])){let g=u;isNaN(Number(u))||(g=c[u].name??c[u].title??c[u].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const y=[...r.path,u],x=[...r.namedPath,g];return n(_y,{path:y,namedPath:x,isArray:Array.isArray(c),count:Sy(c[u]),onClick:s},`data-${u}-${h}`)}if(u==="id")return null;const m=[...r.path,u];return n(Py,{dataType:((f=r.structure)==null?void 0:f[u])??"string",path:m,value:c[u],onChange:a},`InputField-${m.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),d("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:l!=null&&l.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save & Recapture"})]}),(l==null?void 0:l.message)&&!(l!=null&&l.isSaving)&&n("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${l.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:l.message})]})}function Al({title:e,children:t,defaultOpen:r=!1,borderT:s=!1,borderB:a=!1}){const[o,i]=P(r),l=[];return s&&l.push("border-t"),a&&l.push("border-b"),d("div",{className:`${l.join(" ")} border-gray-300`,children:[d("button",{type:"button",onClick:()=>i(!o),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${o?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),o&&n("div",{className:"px-4 py-3",children:t})]})}const $y=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:s,shouldCreateNewScenario:a,onSave:o,onNavigate:i,iframeRef:l,onGenerateData:c,saveFeedback:p})=>{const u=ce((A,_)=>{const E=Object.assign({},A),R=D=>D&&typeof D=="object"&&!Array.isArray(D);return R(A)&&R(_)&&Object.keys(_).forEach(D=>{R(_[D])?D in A?E[D]=u(A[D],_[D]):Object.assign(E,{[D]:_[D]}):Object.assign(E,{[D]:_[D]})}),E},[]),[h,m]=P({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,g]=P(null),y=ie(()=>({...h.data}),[h]),x=ie(()=>({...y.mockData?{"Retrieved Data":y.mockData}:{},...y.argumentsData?{"Function Arguments":y.argumentsData}:{}}),[y]),b=ie(()=>{const A={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(A).reduce((_,E)=>{if(E.includes(".")){const[R,D]=E.split(".");_[R]||(_[R]={}),_[R][D]=A[E]}else _[E]=A[E];return _},{})},[r]),w=ce(async A=>{A.preventDefault();const _=A.target.querySelector('input[name="recapture"]'),E=(_==null?void 0:_.value)==="true",R={mockData:h.data.mockData??{},argumentsData:h.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:h.name,shouldRecapture:E,dataToSave:R,rawFormData:h.data,iframePayload:{arguments:y.argumentsData??[],...y.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(R,null,2).substring(0,1e3));const D=s==null?void 0:s.scenarios.map(T=>!a&&T.name===e.name?{...T,name:h.name,description:h.description,metadata:{...T.metadata,data:R}}:T);a&&D.push({name:h.name,description:h.description,metadata:{data:R,interactiveExamplePath:s==null?void 0:s.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",D),o&&await o(D,{recapture:E}),i&&i(h.name)},[s,e.name,h,y,a,o,i]),v=ce(A=>{m(_=>({..._,[A.target.name]:A.target.value}))},[]),N=ce(A=>{g(_=>{if(!_)return null;for(const E of[{arguments:A.metadata.data.argumentsData},A.metadata.data.mockData]){let R=E;for(const D of _.path)if(R=Ga(R,D),!R)break;R&&(_.data=R)}return{..._}}),m({name:A.name,description:A.description,data:A.metadata.data})},[]),S=ce((A,_)=>{m(E=>{for(const R of[{"Function Arguments":E.data.argumentsData},{"Retrieved Data":E.data.mockData}]){let D=R;for(const T of A.slice(0,-1))if(D=Ga(D,T),!D)break;if(D){const T=D[A[A.length-1]];g($=>$?($.namedPath[$.namedPath.length-1]===T&&($.namedPath[$.namedPath.length-1]=_.toString()),$.data[A[A.length-1]]=_,{...$}):null),D[A[A.length-1]]=_}}return{...E}})},[]),C=ce(A=>{var D,T,$;if(A.length===0){g(null);return}let _=x;const E=[];let R=b;for(const L of A){if(E.push(isNaN(parseInt(L))?L:((D=_[L])==null?void 0:D.name)??((T=_[L])==null?void 0:T.title)??(($=_[L])==null?void 0:$.id)??L),_=Ga(_,L),!_){console.log("Data not found",_,L),g(null);return}Array.isArray(R)?R=R[0]:R=R[L]}g({path:A,namedPath:E,data:_,structure:R})},[x,b]);return ae(()=>{const A=_=>{var E;_.data.type==="codeyam-log"&&((E=_.data.data)!=null&&E.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",_.data.data)};return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},[]),ae(()=>{var A;if((A=l==null?void 0:l.current)!=null&&A.contentWindow){const _={arguments:y.argumentsData??[],...y.mockData??{}},E={type:"codeyam-override-data",name:e.name,data:JSON.stringify(_)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:E.type,name:E.name,dataPreview:JSON.stringify(_).substring(0,200)+"...",fullData:_}),l.current.contentWindow.postMessage(E,"*")}},[y,e,l]),n("form",{method:"post",onSubmit:A=>void w(A),children:f?n(El,{analysis:s,scenarioName:h.name,dataItem:f,onClick:C,onChange:S,onAIResult:N,onGenerateData:c,saveFeedback:p}):d(we,{children:[n(Al,{title:"Edit Name and Description",borderT:!0,children:n(ky,{scenarioFormData:h,handleInputChange:v})}),e.metadata.data&&n(Al,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(El,{analysis:s,scenarioName:h.name,dataItem:{path:[],namedPath:[],data:x,structure:b},onClick:C,onChange:S,onAIResult:N,onGenerateData:c,saveFeedback:p})})]})})};function ga({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:s,isLoading:a,showIframe:o,iframeKey:i,onIframeLoad:l,onScaleChange:c,onDimensionChange:p,projectSlug:u,defaultWidth:h=1440,defaultHeight:m=900,retryCount:f=0}){const{lastLine:g}=Jt(u??null,s||a);return r?d("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:o?1:0,background:"transparent"},children:n(vy,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:h,defaultHeight:m,onIframeLoad:l,onScaleChange:c,onDimensionChange:p},i)}),!o&&(s||a)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Wt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),g&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Kn,{}),g]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center",children:d("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Wt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),g&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Kn,{}),g]})]})]})})}const Iy=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Ry({params:e}){var c,p;const{sha:t,scenarioId:r}=e;if(!t)throw new Response("Entity SHA is required",{status:400});if(!r)throw new Response("Scenario ID is required",{status:400});const s=await Zs(t,!0),a=s&&s.length>0?s[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const o=(c=a.scenarios)==null?void 0:c.find(u=>u.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=(p=a.scenarios)==null?void 0:p.find(u=>u.name===Qs),l=await Ye();return re({analysis:a,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:l})}function Dy(){var L,B,H;const e=st(),t=e.analysis,r=e.scenario,s=e.defaultScenario,a=e.entitySha,o=e.projectSlug,i=Rt(),{iframeRef:l}=ri(),[c,p]=P(!1),[u,h]=P(null),[m,f]=P(null),[g,y]=P(!1),[x,b]=P(!1),[w,v]=P(null),{interactiveServerUrl:N,isStarting:S,isLoading:C,showIframe:A,iframeKey:_,onIframeLoad:E}=jn({analysisId:t==null?void 0:t.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0}),R=ce(async(q,O)=>{p(!0),h(null),f(null),console.log("[EditScenario] Starting save with options:",O),console.log("[EditScenario] Scenarios to save:",q);try{const W={analysis:t,scenarios:q};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:q.length,scenarioNames:q.map(k=>k.name)});const I=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(W)}),j=await I.json();if(console.log("[EditScenario] API response:",j),!I.ok||!j.success)throw new Error(j.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),O!=null&&O.recapture&&r.id&&N){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:N}),h("Changes saved. Capturing screenshot...");const k={serverUrl:N,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",k);const Y=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});console.log("[EditScenario] Capture response status:",Y.status);const G=await Y.json();if(console.log("[EditScenario] Capture response body:",G),!Y.ok||!G.success)throw console.error("[EditScenario] Capture failed:",G),new Error(G.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",G),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),h("Recapture successful")}else if(O!=null&&O.recapture&&!N){console.log("[EditScenario] No running server, using queued recapture");const k=new FormData;k.append("analysisId",t.id||""),k.append("scenarioId",r.id||"");const Y=await fetch("/api/recapture-scenario",{method:"POST",body:k}),G=await Y.json();if(!Y.ok||!G.success)throw new Error(G.error||"Failed to trigger recapture");console.log("Recapture queued:",G),f(G.jobId),h("Changes saved. Screenshot recapture queued.")}else h("Changes saved successfully.")}catch(W){console.error("Error saving scenarios:",W),h(`Error: ${W instanceof Error?W.message:String(W)}`)}finally{p(!1)}},[t,r.id,N]),D=ce(q=>{},[]),T=ce(async(q,O)=>{var j;const W=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:q,existingScenarios:t.scenarios,scenariosDataStructure:(j=t.metadata)==null?void 0:j.scenariosDataStructure,editingMockName:r.name,editingMockData:O==null?void 0:O.data})}),I=await W.json();if(!W.ok||!I.success)throw new Error(I.error||"Failed to generate scenario data");return I.data},[t,r.name]),$=ce(async()=>{var q;if(!r.id){v("Cannot delete scenario without ID");return}y(!0),v(null);try{const O=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((q=r.metadata)==null?void 0:q.screenshotPaths)||[]})}),W=await O.json();if(!O.ok||!W.success)throw new Error(W.error||"Failed to delete scenario");i(`/entity/${a}`)}catch(O){console.error("[EditScenario] Error deleting scenario:",O),v(O instanceof Error?O.message:"Failed to delete scenario"),b(!1)}finally{y(!1)}},[r.id,(L=r.metadata)==null?void 0:L.screenshotPaths,a,i]);return d("div",{className:"h-screen bg-gray-50 flex flex-col",children:[d("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:d(Ce,{to:`/entity/${a}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(B=t.entity)==null?void 0:B.name]})}),d("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",r.name]}),r.description&&n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:r.description})]}),d("div",{className:"flex flex-1 gap-0 min-h-0",children:[d("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n($y,{currentScenario:r,defaultScenario:s,dataStructure:((H=t.metadata)==null?void 0:H.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:R,onNavigate:D,iframeRef:l,onGenerateData:T,saveFeedback:{isSaving:c,message:u,isError:(u==null?void 0:u.startsWith("Error"))??!1}}),u==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(Ce,{to:`/entity/${a}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),d("div",{className:"border-t border-gray-200 p-4 mt-4",children:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),x?d("div",{className:"space-y-3",children:[d("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),d("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void $(),disabled:g,className:"flex-1 px-4 py-2 bg-red-600 text-white rounded-md text-sm font-medium hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors",children:g?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>b(!1),disabled:g,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md text-sm font-medium hover:bg-gray-200 disabled:opacity-50 transition-colors",children:"Cancel"})]})]}):n("button",{onClick:()=>b(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),w&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:w})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(ga,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:N,isStarting:S,isLoading:C,showIframe:A,iframeKey:_,onIframeLoad:E,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const Fy=et(function(){return n(fa,{children:n(Dy,{})})}),Oy=Object.freeze(Object.defineProperty({__proto__:null,default:Fy,loader:Ry,meta:Iy},Symbol.toStringTag,{value:"Module"})),Ly=["/api/health","/__codeyam__/preview-health"];function Vd(e){const t=[];for(const r of e.split(`
329
+ `))if(r.includes("[JournalCapture] HTTP error:"))t.push(r.replace(/.*\[JournalCapture\] /,""));else if(r.includes("[JournalCapture] API response error:"))t.push(r.replace(/.*\[JournalCapture\] /,""));else if(r.includes("[JournalCapture] Page console.error:"))t.push(r.replace(/.*\[JournalCapture\] Page console\.error:\s*/,""));else if(r.includes("[JournalCapture] Network failed:")){if(Ly.some(s=>r.includes(s)))continue;t.push(r.replace(/.*\[JournalCapture\] /,""))}return t}function By(e){for(const t of e.split(`
330
+ `))if(t.includes("[JournalCapture] Visible text: "))return t.replace(/.*\[JournalCapture\] Visible text: /,"");return null}async function Gd(e,t,r,s){const a=U.join(e,".codeyam","editor-scenarios","client-errors.json");let o={};try{const i=await _e.readFile(a,"utf8");o=JSON.parse(i)}catch{}for(const[i,l]of Object.entries(o))i!==t&&l.scenarioName===r&&delete o[i];o[t]={scenarioName:r,capturedAt:new Date().toISOString(),errors:s},await _e.mkdir(U.dirname(a),{recursive:!0}),await _e.writeFile(a,JSON.stringify(o,null,2),"utf8")}async function Kd(e){const t=U.join(e,".codeyam","editor-scenarios","client-errors.json");try{const r=await _e.readFile(t,"utf8");return JSON.parse(r)}catch{return{}}}function si(e){let r=U.dirname(new URL(e).pathname);for(let s=0;s<5;s++){const a=U.dirname(r);if(U.basename(a)==="webserver"||U.basename(r)==="webserver")return U.basename(r)==="webserver"?r:a;r=a}return r}async function ai(e,t){const r=[U.join(e,"scripts","journalCapture.ts"),U.join(e,"app","lib","journalCapture.ts"),U.join(t,"codeyam-cli","src","webserver","app","lib","journalCapture.ts")];for(const s of r)try{return await _e.access(s),s}catch{}return r[0]}function oi(e,t,r){return new Promise(s=>{const a=e.endsWith(".ts"),l=ft(a?"npx":e,a?["tsx",e,t]:[t],{cwd:r,env:{...process.env}});let c="",p="";l.stdout.on("data",u=>{c+=u.toString()}),l.stderr.on("data",u=>{p+=u.toString()}),l.on("close",u=>{s(u===0?{success:!0,output:c}:{success:!1,output:c,error:p||`Process exited with code ${u}`})}),l.on("error",u=>{s({success:!1,output:"",error:u.message})})})}function zy(e){const t=U.join(e,".codeyam","editor-scenarios");let r;try{r=V.readdirSync(t)}catch{return[]}const s=[];for(const a of r){if(!a.endsWith(".json")||a.endsWith(".seed.json")||a==="client-errors.json")continue;const o=U.join(t,a);try{if(!V.statSync(o).isFile())continue;const l=JSON.parse(V.readFileSync(o,"utf8"));if(l._metadata){const c=a.replace(/\.json$/,"");s.push({id:c,metadata:l._metadata})}}catch{}}return s}function qd(e,t,r){const s=U.join(e,".codeyam","editor-scenarios",`${t}.json`);let a={};try{a=JSON.parse(V.readFileSync(s,"utf8"))}catch{return}a._metadata=r,V.writeFileSync(s,JSON.stringify(a,null,2),"utf8")}function Yy(e,t,r){const s=U.join(e,".codeyam","editor-scenarios",`${t}.json`);let a={};try{a=JSON.parse(V.readFileSync(s,"utf8"))}catch{return}a._metadata&&typeof a._metadata=="object"&&(a._metadata.screenshotPath=r,a._metadata.updatedAt=new Date().toISOString(),V.writeFileSync(s,JSON.stringify(a,null,2),"utf8"))}function Wy(e,t,r,s={}){const a=U.join(e,".codeyam","editor-scenarios");V.mkdirSync(a,{recursive:!0});const o=U.join(a,`${t}.json`);let i={};try{i=JSON.parse(V.readFileSync(o,"utf8"))}catch{}const l={...i,_metadata:r,...s};V.writeFileSync(o,JSON.stringify(l,null,2),"utf8")}function Uy(e,t){const r=U.join(e,".codeyam","editor-scenarios");for(const s of[".json",".seed.json"]){const a=U.join(r,`${t}${s}`);try{V.unlinkSync(a)}catch{}}}const ii=globalThis.__codeyamTerminalSessions??(globalThis.__codeyamTerminalSessions=new Set);globalThis.__codeyamDetachedPtys??(globalThis.__codeyamDetachedPtys=new Map);function li(e,t){const r=JSON.stringify({type:"refresh-preview",...e&&{path:e},...t&&{scenarioId:t}});let s=0;for(const a of ii)try{a.ws.readyState===Ro.OPEN&&(a.ws.send(r),s++)}catch{}return s}function Jy(){const e=JSON.stringify({type:"hide-results"});let t=0;for(const r of ii)try{r.ws.readyState===Ro.OPEN&&(r.ws.send(e),t++)}catch{}return t}function ci(e){const t=JSON.stringify({type:"set-viewport",...e});let r=0;for(const s of ii)try{s.ws.readyState===Ro.OPEN&&(s.ws.send(t),r++)}catch{}return r}const Hy=Object.freeze(Object.defineProperty({__proto__:null,broadcastHideResults:Jy,broadcastPreviewRefresh:li,broadcastSetViewport:ci},Symbol.toStringTag,{value:"Module"}));function Vy(e){if(e.dimension)try{ci({name:e.dimension,width:e.viewport.width,height:e.viewport.height})}catch{}li(e.refreshPath,e.scenarioId)}function Gy(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=Ie("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return Ky(r)}catch{return[]}}function Ky(e){const t=e.trim().split(`
331
+ `).filter(s=>s.length>0),r=[];for(const s of t){const a=s[0],o=s[1];let i=s.slice(2).replace(/^[ \t]+/,""),l,c=!1,p;if(a==="A"||o==="A")l="added",c=a==="A";else if(a==="M"||o==="M")l="modified",c=a==="M";else if(a==="D"||o==="D")l="deleted",c=a==="D";else if(a==="R"||o==="R"){l="renamed",c=a==="R";const u=i.indexOf(" -> ");u!==-1&&(p=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(l="untracked",c=!1):(l="modified",c=a!==" "&&a!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=se.join(u,i);try{const m=(g,y)=>{const x=ge.readdirSync(g,{withFileTypes:!0}),b=[];for(const w of x){const v=se.join(g,w.name),N=se.relative(u,v);w.isDirectory()?b.push(...m(v,y)):w.isFile()&&b.push(N)}return b},f=m(h,u);for(const g of f)r.push({path:g,status:l,staged:c,...p&&{oldPath:p}})}catch(m){console.error(`Failed to expand directory ${i}:`,m)}}else r.push({path:i,status:l,staged:c,...p&&{oldPath:p}})}return r}function qy(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ie("git branch --show-current",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch(r){return console.error("Failed to get current branch:",r),null}}function Qy(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const s=Ie('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().match(/refs\/remotes\/origin\/(.+)/);if(s)return s[1];try{return Ie("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return Ie("git show-ref --verify --quiet refs/heads/master",{cwd:t,stdio:["pipe","pipe","ignore"]}),"master"}catch{return"main"}}}catch(r){return console.error("Failed to get default branch:",r),"main"}}function Zy(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ie('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
332
+ `).filter(s=>s.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function or(){const e=Ne();return e?Gy(e):[]}function Xy(){const e=Ne();return e?qy(e):null}function ex(){const e=Ne();return e?Qy(e):"main"}function tx(){const e=Ne();return e?Zy(e):[]}function Qd(e,t){const r=Ne();return r?nx(e,t,r):[]}function nx(e,t,r){const s=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ie(`git diff --name-status ${e}...${t}`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
333
+ `).filter(i=>i.length>0).map(i=>{const l=i.split(" "),c=l[0];let p=l[1],u,h;return c==="A"?h="added":c==="M"?h="modified":c==="D"?h="deleted":c.startsWith("R")?(h="renamed",u=l[1],p=l[2]):h="modified",{path:p,status:h,...u&&{oldPath:u}}})}catch(a){return console.error("Failed to get branch diff:",a),[]}}function Zd(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=Ie(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let a="";try{a=ge.readFileSync(se.join(r,e),"utf8")}catch(o){console.error(`Failed to read current file ${e}:`,o),a=""}return{oldContent:s,newContent:a,fileName:e}}catch(s){return console.error(`Failed to get diff for ${e}:`,s),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function rx(e){const t=Ne();return t?Zd(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function sx(e,t,r,s){const a=s||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=Ie(`git show ${t}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=Ie(`git show ${r}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:o,newContent:i,fileName:e}}catch(o){return console.error(`Failed to get branch diff for ${e}:`,o),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Cs(e,t,r){const s=Ne();return s?sx(e,t,r,s):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}async function ax(e,t,r){const s=U.join(e,".codeyam","journal"),a=U.join(s,"index.json");U.join(s,"screenshots");let o;try{const l=await _e.readFile(a,"utf8");o=JSON.parse(l)}catch{return}let i=!1;for(const l of o.entries)if(!l.commitSha&&l.scenarioScreenshots)for(let c=0;c<l.scenarioScreenshots.length;c++){const p=l.scenarioScreenshots[c];if(p.name!==t)continue;const u=U.join(s,p.path);try{await _e.copyFile(r,u),i=!0,console.log(`[editor-register-scenario] Updated journal screenshot for "${t}" in entry "${l.title}"`)}catch(h){console.warn(`[editor-register-scenario] Failed to update journal screenshot: ${h instanceof Error?h.message:h}`)}}i&&Nt.notifyChange("journal")}const Pl=ei;async function ox({request:e}){var t,r;if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const s=await e.json();s.url=s.url||s.path||void 0;const a=_0({componentName:s.componentName,url:s.url,type:s.type});if(!a.valid)return new Response(JSON.stringify({error:a.error}),{status:400,headers:{"Content-Type":"application/json"}});const{name:o,description:i,componentName:l,componentPath:c}=s;if(!o)return new Response(JSON.stringify({error:"name is required"}),{status:400,headers:{"Content-Type":"application/json"}});if(l&&!c)return new Response(JSON.stringify({error:`componentPath is required when componentName is provided. Add "componentPath": "app/components/${l}.tsx" (or the actual file path) to the registration JSON.`}),{status:400,headers:{"Content-Type":"application/json"}});const p=await Ye();if(!p)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:u}=await De(p),h=Pe(),m=process.env.CODEYAM_ROOT_PATH||process.cwd();let f,g,y;if(!s.viewportWidth&&!s.viewportHeight&&!s.dimension&&!s.dimensions){const K=await h.selectFrom("editor_scenarios").selectAll().where("name","=",o).where("project_id","=",u.id).orderBy("created_at","desc").executeTakeFirst();if(K){f=K.viewport_width||void 0,g=K.viewport_height||void 0;try{const F=K.dimensions?JSON.parse(K.dimensions):void 0;Array.isArray(F)&&(y=F)}catch{}}}let x=null;s.dimensions&&s.dimensions.length>0?x=s.dimensions:s.dimension?x=[s.dimension]:y&&y.length>0&&(x=y);const b=(x==null?void 0:x[0])||void 0,w=ca({bodyWidth:s.viewportWidth||f,bodyHeight:s.viewportHeight||g,dimension:b,codeyamRoot:m});let v=null;if(!l){if(s.pageFilePath)v=s.pageFilePath;else if(s.url){const{scanPageFilePaths:K}=await Promise.resolve().then(()=>lx),F=Ne()||process.cwd(),{allFiles:M}=K(F);if(v=Nd(s.url,M),!v){const z=await import("fs"),J=await import("path"),te=["src/App.tsx","src/App.jsx","src/app/App.tsx","src/popup/App.tsx","src/pages/index.tsx","src/pages/index.jsx","src/routes/index.tsx","app/root.tsx"];for(const oe of te)if(z.existsSync(J.join(F,oe))){v=oe;break}}}}let N=null,S=null;const C=c||v;if(C)try{await Je();const F=(await Xe({})||[]).filter(J=>J.filePath===C),z=F.find(J=>{var te,oe;return((te=J.metadata)==null?void 0:te.notExported)===!1&&((oe=J.metadata)==null?void 0:oe.namedExport)===!1})||F[0];z&&(N=z.sha)}catch{}const A=s.type==="application"||s.type==="user";if(!N&&A&&C){const K=Ne()||process.cwd(),F=k0({lookupFilePath:C,scenarioType:s.type||null,projectRoot:K});if(!F.valid)return Response.json({error:F.error},{status:400});if(F.needsAnalysis)try{const{runAnalysisForEntities:M}=await import("./analysisRunner-B6HnVI5u.js");await M({projectRoot:K,filePaths:[C],onlyDataStructure:!0});try{const J=(await Xe({})||[]).filter(de=>de.filePath===C),oe=J.find(de=>{var ue,me;return((ue=de.metadata)==null?void 0:ue.notExported)===!1&&((me=de.metadata)==null?void 0:me.namedExport)===!1})||J[0];oe&&(N=oe.sha)}catch{}if(N)try{const z=await Xe({});await E0(h,(z||[]).map(J=>{var te,oe;return{sha:J.sha,name:J.name,filePath:J.filePath||"",isDefaultExport:((te=J.metadata)==null?void 0:te.notExported)===!1&&((oe=J.metadata)==null?void 0:oe.namedExport)===!1}}))}catch{}}catch(M){console.warn(`[editor-register-scenario] Auto analyze-imports failed for ${C}: ${M.message}`)}}l?S=l:v&&v.startsWith("app/")?S=Ft(_t(v)):s.url&&(S=mt(s.url));const _=await S0(h,{projectId:u.id,name:o,description:i||null,componentName:l||null,componentPath:c||null,url:s.url||null,type:s.type||null,viewportWidth:w.width,viewportHeight:w.height,dimensions:x,screenshotPaths:null,pageFilePath:v,entitySha:N,displayName:S}),E=_.scenarioId;if(_.cleanedUpIds.length>0&&(C0(m,_.cleanedUpIds),console.log(`[editor-register-scenario] Cleaned up ${_.cleanedUpIds.length} duplicate(s) for "${o}"`)),s.seedFrom&&!s.seed){const K=await bl(m,h,s.seedFrom);K?(s.seed=K,s.type||(s.type="application"),console.log(`[editor-register-scenario] Resolved seed data from "${s.seedFrom}"`)):console.warn(`[editor-register-scenario] seedFrom "${s.seedFrom}" not found — no seed data will be used`)}else if(s.seedFrom&&s.seed){const K=await bl(m,h,s.seedFrom);K&&(s.seed=vl(K,s.seed),console.log(`[editor-register-scenario] Merged seed data: base from "${s.seedFrom}", overlay from registration`))}const R=s.type==="application"||s.type==="user",D=new Date().toISOString(),T={name:o,description:i||null,componentName:l||null,componentPath:c||null,url:s.url||null,type:s.type||(R?null:"component"),screenshotPath:null,viewportWidth:w.width,viewportHeight:w.height,dimensions:x,screenshotPaths:null,pageFilePath:v,entitySha:N,displayName:S,createdAt:D,updatedAt:D},$={};if(R&&s.seed){let K=s.seed;if(s.type==="user"&&s.baseScenario)try{const M=U.join(m,".codeyam","editor-scenarios",`${s.baseScenario}.json`),z=await _e.readFile(M,"utf-8"),J=JSON.parse(z);J.seed&&(K=vl(J.seed,s.seed),console.log(`[editor-register-scenario] Merged seed data from base scenario ${s.baseScenario}`))}catch(M){console.warn(`[editor-register-scenario] Could not read base scenario ${s.baseScenario}: ${M instanceof Error?M.message:M}`)}$.type=s.type,$.seed=K,s.externalApis&&($.externalApis=s.externalApis),s.session&&($.session=s.session),s.auth&&($.auth=s.auth),s.localStorage&&($.localStorage=s.localStorage);const F=U.join(m,".codeyam","editor-scenarios");await _e.mkdir(F,{recursive:!0}),await _e.writeFile(U.join(F,`${E}.seed.json`),JSON.stringify(K,null,2))}else(s.mockData||s.localStorage)&&(s.mockData&&Object.assign($,s.mockData),s.localStorage&&($.localStorage=s.localStorage));let L=null;if(R&&!s.seed&&Mr(m)){const F=U.join(m,".codeyam","editor-scenarios",`${E}.json`);let M=!1;try{M=!!JSON.parse(await _e.readFile(F,"utf-8")).seed}catch{}M||(L='WARNING: This application scenario has no seed data. A seed adapter exists — include "seed":{...} in registration so the page has database rows to render. Without seed data, the page will likely be empty.',console.warn(`[editor-register-scenario] ${L}`))}Wy(m,E,T,$);let B=null;if(R&&s.seed){const K=Mr(m);if(K){const F=U.join(m,".codeyam","editor-scenarios",`${E}.seed.json`);console.log(`[editor-register-scenario] Running seed adapter: ${K}`);const M=await Xo(K,F);if(B={success:M.success,error:M.error},M.success){if(console.log(`[editor-register-scenario] Seed adapter completed in ${M.durationMs}ms`),M.sessionCookies&&M.sessionCookies.length>0)try{const z=U.join(m,".codeyam","editor-scenarios",`${E}.json`),J=JSON.parse(await _e.readFile(z,"utf-8"));J.sessionCookies=M.sessionCookies,await _e.writeFile(z,JSON.stringify(J,null,2)),console.log(`[editor-register-scenario] Saved ${M.sessionCookies.length} session cookie(s) to scenario data`)}catch(z){console.warn(`[editor-register-scenario] Failed to save session cookies: ${z}`)}}else console.warn(`[editor-register-scenario] Seed adapter failed: ${M.error}`)}else console.warn(`[editor-register-scenario] No seed adapter found at ${m}/.codeyam/seed-adapter.ts`),B={success:!1,error:"No seed adapter found. Create .codeyam/seed-adapter.ts to use seed-based scenarios."}}Nt.notifyChange("scenario"),console.log(`[editor-register-scenario] Starting auto-capture for scenario "${o}" (id: ${E})`);const H=s.url&&s.url.startsWith("/"),q=!s.url||H?await ni():null,O=Pl(),W=Qo(s.url||null,q,O);console.log(`[editor-register-scenario] Capture URL resolution: explicit=${s.url||"none"}, isPath=${H}, proxy=${q||"none"}, devServer=${O||"none"} → using ${W||"none"}`);let I=null,j=null,k=[],Y=null,G=null,Q={};if(W){const K=Tt(o),F=await da({scenarioId:E,scenarioSlug:K,scenarioType:s.type||void 0,projectRoot:m});En(),!B&&F.seedResult&&(B=F.seedResult),console.log(`[editor-register-scenario] Active scenario set to "${K}" (${E}), type=${F.type}, seeded=${F.seeded}, seedResult=${JSON.stringify(F.seedResult??null)}, cache invalidated`),await new Promise(me=>setTimeout(me,300));const M=(t=s.url)!=null&&t.startsWith("/")?`${Pl()||"http://localhost:3113"}${s.url}`:W;for(let me=0;me<5;me++){try{const Se=await fetch(M,{method:"GET",signal:AbortSignal.timeout(3e3)});if(Se.status<500)break;console.log(`[editor-register-scenario] Route returned ${Se.status}, waiting for HMR (attempt ${me+1}/5)...`)}catch{console.log(`[editor-register-scenario] Route not reachable, waiting for HMR (attempt ${me+1}/5)...`)}await new Promise(Se=>setTimeout(Se,2e3))}const z=U.join(m,".codeyam","editor-scenarios","screenshots");await _e.mkdir(z,{recursive:!0});const J=si(import.meta.url),te=await ai(J,m);console.log(`[editor-register-scenario] Capture script: ${te}`);const oe=Zo(m),de=x&&x.length>0?x:[null];Q={};let ue=null;for(let me=0;me<de.length;me++){const Se=de[me];let Te=w;if(Se){const he=oe[Se];he!=null&&he.width&&(he!=null&&he.height)&&(Te={width:he.width,height:he.height})}const $e=Se?_d(Se):null,Re=$e&&de.length>1?`${E}--${$e}.png`:`${E}.png`,X=U.join(z,Re),ye=`screenshots/${Re}`;me===0&&(G=Te,ue=X);const ee=JSON.stringify({url:W,outputPath:X,viewportWidth:Te.width,viewportHeight:Te.height,...l?{selector:"#codeyam-capture"}:{}});console.log(`[editor-register-scenario] Capture ${Se||"default"}: ${Te.width}×${Te.height} → ${Re}`);const ne=Date.now(),xe=await oi(te,ee,m),Me=Date.now()-ne;console.log(`[editor-register-scenario] Capture ${Se||"default"} ${xe.success?"succeeded":"FAILED"} in ${Me}ms`),xe.success||(console.warn(`[editor-register-scenario] Capture stdout: ${xe.output.slice(0,500)}`),console.warn(`[editor-register-scenario] Capture stderr: ${(xe.error||"").slice(0,500)}`)),me===0&&(k=Vd(xe.output),Y=By(xe.output),await Gd(m,E,o,k),k.length>0&&console.warn(`[editor-register-scenario] ${k.length} client-side error(s) detected:`,k)),xe.success?(Se&&(Q[Se]=ye),me===0&&(I=ye)):me===0&&(j=xe.error||"Unknown capture error",console.warn(`[editor-register-scenario] Screenshot capture failed (non-blocking): ${j}`))}if(I){try{await h.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}const me={screenshot_path:I,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")};Object.keys(Q).length>0&&(me.screenshot_paths=JSON.stringify(Q)),await h.updateTable("editor_scenarios").set(me).where("id","=",E).execute(),Nt.notifyChange("scenario"),ue&&await ax(m,o,ue)}}else console.log("[editor-register-scenario] Skipping screenshot — no capture URL available (dev server not running?)");if(console.log(`[editor-register-scenario] Done: scenario="${o}", screenshot=${I?"captured":"skipped"}`),W&&I)try{const K=Ne()||process.cwd(),F=U.join(K,".codeyam","editor-step.json");let M=null;try{const z=V.readFileSync(F,"utf8");M=JSON.parse(z).featureStartedAt||null}catch{}if(M){const z=zr(M),J=await h.selectFrom("editor_scenarios").selectAll().where("project_id","=",u.id).orderBy("created_at","asc").execute(),te=Ct(J,de=>`${de.name}::${de.url||"/"}`),oe=or();if(oe.length>0){let de=!1;try{const{execSync:ne}=await import("child_process"),xe=ne("git rev-list --count HEAD",{cwd:K,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();de=parseInt(xe,10)<=1}catch{de=!0}const ue=Sd(oe,de),me={},Se=U.join(K,"app");if(V.existsSync(Se)){const ne=(xe,Me)=>{for(const he of V.readdirSync(xe,{withFileTypes:!0}))if(he.name!=="isolated-components"){if(he.isDirectory())ne(U.join(xe,he.name),Me?`${Me}/${he.name}`:he.name);else if(he.name==="page.tsx"||he.name==="page.js"){const He=mt(Me?`/${Me}`:"/");me[He]=Me?`app/${Me}/${he.name}`:`app/${he.name}`}}};ne(Se,"")}let Te=[];try{await Je(),Te=await Xe({})||[]}catch{}const $e=te.map(ne=>({componentName:ne.component_name||null,componentPath:ne.component_path||null,pageFilePath:ne.page_file_path??null,url:ne.url??null,displayName:ne.display_name??null})),Re=Cd($e,me,Te),X=kd(ue,Re),ye=te.filter(ne=>ne.created_at<z),ee=new Map;for(const ne of ye){const xe=Kt({componentName:ne.component_name,pageFilePath:ne.page_file_path,url:ne.url});((r=X[xe])==null?void 0:r.status)==="impacted"&&ee.set(xe,ne)}if(ee.size>0){console.log(`[editor-register-scenario] Recapturing ${ee.size} impacted older scenario(s): ${[...ee.keys()].join(", ")}`);const{recaptureScenarios:ne}=await Promise.resolve().then(()=>Fx),xe=[...ee.values()].map(he=>({id:he.id,name:he.name,url:he.url,component_name:he.component_name,dimensions:he.dimensions,viewport_width:he.viewport_width,viewport_height:he.viewport_height}));await ne({scenarios:xe,codeyamRoot:m,proxyUrl:q,devUrl:O,db:h,importMetaUrl:import.meta.url});const Me=U.join(m,".codeyam","active-scenario.json");await _e.writeFile(Me,JSON.stringify({scenarioId:E,scenarioSlug:Tt(o),type:s.type||null,timestamp:new Date().toISOString()})),En(),Nt.notifyChange("scenario")}}}}catch(K){console.warn(`[editor-register-scenario] Recapture of impacted scenarios failed (non-blocking): ${K instanceof Error?K.message:K}`)}try{const K=new Date().toISOString(),F=Object.keys(Q).length>0?Q:null;qd(m,E,{name:o,description:i||null,componentName:l||null,componentPath:c||null,url:s.url||null,type:s.type||null,screenshotPath:I||null,viewportWidth:w.width,viewportHeight:w.height,dimensions:x,screenshotPaths:F,pageFilePath:v,createdAt:K,updatedAt:K})}catch(K){console.warn(`[editor-register-scenario] Failed to update scenario metadata (non-blocking): ${K instanceof Error?K.message:K}`)}try{Vy({dimension:b,viewport:w,refreshPath:s.url||void 0,scenarioId:E})}catch{}return new Response(JSON.stringify({success:!0,scenario:{id:E,name:o,description:i,componentName:l||null,componentPath:c||null,screenshotPath:I,url:s.url||null,type:s.type||null,viewportWidth:w.width,viewportHeight:w.height,dimensions:x,screenshotPaths:Object.keys(Q).length>0?Q:null},updated:!_.isNew,screenshotCaptured:I!==null,capturedViewport:G,captureError:j,clientErrors:k,...Y?{visibleText:Y}:{},...B?{seedResult:B}:{},...L?{missingSeedWarning:L}:{}}),{headers:{"Content-Type":"application/json"}})}catch(s){const a=s instanceof Error?s.message:String(s);return console.error("[editor-register-scenario] Error:",s),new Response(JSON.stringify({error:a}),{status:500,headers:{"Content-Type":"application/json"}})}}const ix=Object.freeze(Object.defineProperty({__proto__:null,action:ox},Symbol.toStringTag,{value:"Module"}));function di(e){const t={},r=[],s=U.join(e,"app");if(!V.existsSync(s))return{map:t,allFiles:r};const a=c=>c.split("/").filter(p=>!p.startsWith("(")).join("/"),o=new Set(["_layout.tsx","_layout.ts","_layout.js","layout.tsx","layout.ts","layout.js"]),i=new Set([".tsx",".ts",".jsx",".js"]),l=(c,p)=>{for(const u of V.readdirSync(c,{withFileTypes:!0}))if(u.name!=="isolated-components")if(u.isDirectory())l(U.join(c,u.name),p?`${p}/${u.name}`:u.name);else if(u.name==="page.tsx"||u.name==="page.js"){const h=p?`app/${p}/${u.name}`:`app/${u.name}`;r.push(h);const m=a(p);t[mt(m?`/${m}`:"/")]=h}else{if(o.has(u.name))continue;{const h=U.extname(u.name);if(!i.has(h))continue;const m=U.basename(u.name,h),f=p?`app/${p}/${u.name}`:`app/${u.name}`,g=a(p);let y;m==="index"?y=g?`/${g}`:"/":y=g?`/${g}/${m}`:`/${m}`,r.push(f);const x=mt(y);t[x]||(t[x]=f)}}};return l(s,""),{map:t,allFiles:r}}function Xd(e){try{const t=Ie("git rev-list --count HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();return parseInt(t,10)<=1}catch{return!0}}function eu(e){try{const t=U.join(e,".codeyam","editor-step.json"),r=V.readFileSync(t,"utf8");return JSON.parse(r).featureStartedAt||null}catch{return null}}function ui(e){try{const t=U.join(e,".codeyam","editor-step.json"),r=V.readFileSync(t,"utf8");return JSON.parse(r).feature||null}catch{return null}}function tu(e){try{const t=U.join(e,".codeyam","editor-step.json"),r=V.readFileSync(t,"utf8"),s=JSON.parse(r);return typeof s.step=="number"&&s.label?{step:s.step,label:s.label}:null}catch{return null}}function nu(e){try{const t=U.join(e,".codeyam","editor-step.json"),r=V.readFileSync(t,"utf8"),s=JSON.parse(r);return Array.isArray(s.appFormats)?s.appFormats:null}catch{return null}}function ru(e){try{const t=U.join(e,".codeyam","claude-session-id.txt");return V.readFileSync(t,"utf8").trim()||null}catch{return null}}function pi(e){try{const t=U.join(e,".codeyam","editor-user-prompt.txt");return V.readFileSync(t,"utf8").trim()||null}catch{return null}}function su(e){const t=U.join(e,".codeyam","active-scenario.json");try{return V.existsSync(t)&&JSON.parse(V.readFileSync(t,"utf-8")).scenarioId||null}catch{return null}}const lx=Object.freeze(Object.defineProperty({__proto__:null,detectFirstFeature:Xd,readEditorAppFormats:nu,readEditorFeature:ui,readEditorSessionId:ru,readEditorStep:tu,readEditorUserPrompt:pi,readFeatureStartedAt:eu,readSavedActiveScenarioId:su,scanPageFilePaths:di},Symbol.toStringTag,{value:"Module"}));async function ir(e){const{projectRoot:t,scenarioInputs:r,glossaryInputs:s}=e,o=(e.precomputedPageFilePaths??di(t)).map,i=new Set(Object.keys(o)),l=e.precomputedGitFiles??or();if(l.length===0)return{entityChangeStatus:{},pageEntityNames:i};const c=Xd(t),p=Sd(l,c);let u=[];if(e.precomputedEntities)u=e.precomputedEntities;else try{await Je(),u=await Xe({})||[]}catch{}const h=Cd(r,o,u);let m=h;if(s&&s.length>0){const g=new Set(h.map(x=>x.name)),y=c0(s,g);m=[...h,...y]}return{entityChangeStatus:kd(p,m),pageEntityNames:i}}function cx(e,t,r,s){const a=s?s.replace("T"," ").replace(/\.\d{3}Z$/,""):null,o=[],i=[],l=new Set;for(const u of e){const h=Kt({componentName:u.component_name,pageFilePath:u.page_file_path,url:u.url});if(!h)continue;const m=t[h];if(!m||u.component_name)continue;const f=u.created_at||"",g=u.updated_at||"";(a?f>=a||g>=a:!0)?(i.push({name:u.name,url:u.url,entityName:h}),l.add(h)):o.push({name:u.name,url:u.url,entityName:h,changeStatus:m.status,lastCaptured:f})}const c=[];for(const[u,h]of Object.entries(t)){if(!r.has(u)||l.has(u))continue;o.some(f=>f.entityName===u)||c.push({entityName:u,changeStatus:h.status})}const p=o.length===0&&c.length===0;return{staleScenarios:o,freshScenarios:i,uncoveredPages:c,pass:p}}async function dx(){const e=Ne()||process.cwd(),t=await Ye();if(!t)return Response.json({error:"No project configured"},{status:400});const r=U.join(e,".codeyam","editor-step.json");let s=null;try{const f=V.readFileSync(r,"utf8");s=JSON.parse(f).featureStartedAt||null}catch{}const{project:a}=await De(t),i=await Pe().selectFrom("editor_scenarios").select(["id","name","component_name","component_path","page_file_path","url","type","created_at","updated_at","display_name"]).where("project_id","=",a.id).orderBy("created_at","asc").execute(),l=Ct(i,f=>`${f.name}::${f.url||"/"}`),c=l.map(f=>({componentName:f.component_name||null,componentPath:f.component_path||null,pageFilePath:f.page_file_path??null,url:f.url??null,displayName:f.display_name??null}));let p={},u=new Set;try{const f=await ir({projectRoot:e,scenarioInputs:c});p=f.entityChangeStatus,u=f.pageEntityNames}catch{}if(Object.keys(p).length===0)return Response.json({staleScenarios:[],uncoveredPages:[],freshScenarios:[],pass:!0,note:"No entity change data available — cannot determine coverage."});const h=l.map(f=>({name:f.name,component_name:f.component_name,page_file_path:f.page_file_path??null,url:f.url??null,created_at:f.created_at||"",updated_at:f.updated_at||null})),m=cx(h,p,u,s);return Response.json(m)}const ux=Object.freeze(Object.defineProperty({__proto__:null,loader:dx},Symbol.toStringTag,{value:"Module"}));function px({executionFlows:e,selections:t,onChange:r,disabled:s=!1}){const a=ce(i=>t.some(l=>l.flowId===i),[t]),o=ce(i=>{a(i.id)?r(t.filter(l=>l.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,a]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const l=a(i.id),c=i.usedInScenarios.length>0;return d("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[d("label",{className:"flex items-start gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:l,onChange:()=>o(i),disabled:s,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!c&&n("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&n("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&n("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),l&&i.requiredValues.length>0&&d("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[n("span",{className:"text-gray-700 font-medium",children:"Required values:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((p,u)=>d("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:p.attributePath})," ",n("span",{className:"text-gray-400",children:p.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:p.value})]},u))})]})]},i.id)})})}function hi(e,t){const r=(e||[]).map(c=>({...c,usedInScenarios:[]})),s=new Map;r.forEach(c=>{s.set(c.id,c)});const a=[];t.forEach(c=>{var u;const p=((u=c.metadata)==null?void 0:u.coveredFlows)||[];p.forEach(h=>{const m=s.get(h);m&&m.usedInScenarios.push({id:c.id||"",name:c.name})}),a.push({scenario:c,coveredFlowIds:p})});const o=r.length,i=r.filter(c=>c.usedInScenarios.length>0).length,l=o>0?i/o*100:0;return{executionFlows:r,totalFlows:o,coveredFlows:i,coveragePercentage:l,scenariosWithFlows:a}}function hx(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const mx=({data:e})=>[{title:e!=null&&e.entity?`Create Scenario - ${e.entity.name} - CodeYam`:"Create Scenario - CodeYam"},{name:"description",content:"Create a new scenario"}];async function fx({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await Zs(t,!0),s=r&&r.length>0?r[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const a=(i=s.scenarios)==null?void 0:i.find(l=>l.name===Qs);if(!a)throw new Response("Default scenario not found",{status:404});const o=await Ye();return re({analysis:s,defaultScenario:a,entity:s.entity,entitySha:t,projectSlug:o})}function gx(){var W;const{analysis:e,defaultScenario:t,entity:r,entitySha:s,projectSlug:a}=st(),o=Rt(),{iframeRef:i}=ri(),[l,c]=P(""),[p,u]=P(400),[h,m]=P(!1),[f,g]=P(!1),[y,x]=P(!1),[b,w]=P(null),[v,N]=P(null),[S,C]=P([]),A=ie(()=>{var j;return!((j=e==null?void 0:e.metadata)!=null&&j.executionFlows)||!(e!=null&&e.scenarios)?[]:hi(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:_,isStarting:E,isLoading:R,showIframe:D,iframeKey:T,onIframeLoad:$}=jn({analysisId:e==null?void 0:e.id,scenarioId:t==null?void 0:t.id,scenarioName:t==null?void 0:t.name,projectSlug:a,enabled:!0}),L=ce(async()=>{var I,j,k,Y;if(!l.trim()&&S.length===0){w("Please describe how you want to change the scenario or select execution flows");return}g(!0),w(null),N("Generating scenario with AI...");try{const G=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,existingScenarios:e.scenarios,scenariosDataStructure:(I=e.metadata)==null?void 0:I.scenariosDataStructure,flowSelections:S.length>0?S:void 0})}),Q=await G.json();if(!G.ok||!Q.success)throw new Error(Q.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",Q.data);const K=Q.data;if(!K.name||!K.data)throw new Error("AI response missing required fields (name or data)");N("Saving new scenario..."),x(!0);const F={name:K.name,description:K.description||l,metadata:{data:K.data,interactiveExamplePath:(j=t.metadata)==null?void 0:j.interactiveExamplePath}},M=[...e.scenarios||[],F],z=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:M})}),J=await z.json();if(!z.ok||!J.success)throw new Error(J.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",J);const te=(Y=(k=J.analysis)==null?void 0:k.scenarios)==null?void 0:Y.find(oe=>oe.name===K.name);if(!(te!=null&&te.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),N("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${s}`),1e3);return}if(_){N("Capturing screenshot...");const oe=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:_,scenarioId:te.id,projectId:e.projectId,viewportWidth:1440})}),de=await oe.json();!oe.ok||!de.success?(console.error("[CreateScenario] Capture failed:",de),N("Scenario created! (Screenshot capture failed)")):N("Scenario created and captured!")}else N("Scenario created!");setTimeout(()=>{o(`/entity/${s}/scenarios/${te.id}`)},1e3)}catch(G){console.error("[CreateScenario] Error:",G),w(G instanceof Error?G.message:String(G)),N(null)}finally{g(!1),x(!1)}},[l,S,e,t,s,_,o]),B=f||y,H=ce(()=>{m(!0)},[]),q=ce(I=>{if(!h)return;const j=I.clientX;j>=250&&j<=600&&u(j)},[h]),O=ce(()=>{m(!1)},[]);return ae(()=>(h?(document.addEventListener("mousemove",q),document.addEventListener("mouseup",O)):(document.removeEventListener("mousemove",q),document.removeEventListener("mouseup",O)),()=>{document.removeEventListener("mousemove",q),document.removeEventListener("mouseup",O)}),[h,q,O]),d("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:d("div",{className:"flex items-end h-full px-6 gap-6",children:[d("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:()=>void o(`/entity/${s}`),className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:r==null?void 0:r.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:r==null?void 0:r.filePath,children:r==null?void 0:r.filePath})]}),d("div",{className:"flex items-end gap-8 shrink-0",children:[n(Ce,{to:`/entity/${s}/scenarios`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-medium border-b-2",style:{color:"#005C75",borderColor:"#005C75"},children:d("span",{className:"flex items-center gap-2",children:["Scenarios",n("span",{className:"inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full bg-[#cbf3fa] text-[#005c75]",children:((W=e==null?void 0:e.scenarios)==null?void 0:W.length)||0})]})}),n(Ce,{to:`/entity/${s}/related`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Related Entities"}),n(Ce,{to:`/entity/${s}/code`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Code"}),n(Ce,{to:`/entity/${s}/data`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Data Structure"}),n(Ce,{to:`/entity/${s}/history`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"History"})]})]})}),d("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[d("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${p}px`},children:[d("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select execution flows and/or describe how you'd like to change it."})]}),A.length>0&&d("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[d("summary",{className:"px-3 py-2 text-sm font-medium text-gray-700 cursor-pointer hover:bg-gray-50 rounded-lg",children:["Select Execution Flows"," ",S.length>0&&d("span",{className:"text-blue-600",children:["(",S.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(px,{executionFlows:A,selections:S,onChange:C,disabled:B})})]}),d("div",{className:"mb-4",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"Describe your scenario"}),n("textarea",{id:"prompt",value:l,onChange:I=>c(I.target.value),placeholder:"e.g., Show an empty state with no items...",className:"w-full h-32 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm resize-none",disabled:B})]}),d("div",{className:"space-y-2",children:[n("button",{onClick:()=>void L(),disabled:B||!l.trim()&&S.length===0,className:"w-full px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium cursor-pointer transition-colors hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed",children:B?"Creating...":"Create Scenario"}),v&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:v}),b&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:b})]})]}),d("div",{onMouseDown:H,style:{width:"20px",position:"absolute",top:0,left:`${p-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[n("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:h?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),n("div",{style:{position:"absolute",top:"50%",left:"10px",transform:"translate(-50%, -50%)",width:"8px",height:"40px",background:"#fff",border:"1px solid rgba(0,0,0,0.15)",borderRadius:"4px",cursor:"col-resize"}})]}),n("main",{className:"flex-1 overflow-auto flex items-center justify-center min-w-0",style:{backgroundImage:`
334
+ linear-gradient(45deg, #ebebeb 25%, transparent 25%),
335
+ linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
336
+ linear-gradient(45deg, transparent 75%, #ebebeb 75%),
337
+ linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
338
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:n(ga,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:_,isStarting:E,isLoading:R,showIframe:D,iframeKey:T,onIframeLoad:$,projectSlug:a,defaultWidth:1440,defaultHeight:900})})]})]})}const yx=et(function(){return n(fa,{children:n(gx,{})})}),xx=Object.freeze(Object.defineProperty({__proto__:null,default:yx,loader:fx,meta:mx},Symbol.toStringTag,{value:"Module"})),bx=ei;async function wx({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioId:r,url:s,viewportWidth:a,viewportHeight:o}=t;if(!r)return new Response(JSON.stringify({error:"scenarioId is required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=await Ye();if(!i)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:l}=await De(i),c=Pe(),p=await c.selectFrom("editor_scenarios").selectAll().where("id","=",r).where("project_id","=",l.id).executeTakeFirst();if(!p)return new Response(JSON.stringify({error:"Scenario not found"}),{status:404,headers:{"Content-Type":"application/json"}});const u=s??p.url??null,h=u&&u.startsWith("/"),m=!u||h?await ni():null,f=bx(),g=Qo(u,m,f);if(console.log(`[editor-capture-scenario] URL resolution: explicit=${s||"none"}, db=${p.url||"none"}, proxy=${m||"none"}, devServer=${f||"none"} → captureUrl=${g||"none"}`),!g)return new Response(JSON.stringify({error:"Cannot determine capture URL — no proxy or dev server running"}),{status:400,headers:{"Content-Type":"application/json"}});console.log(`[editor-capture-scenario] Starting capture for scenario "${p.name}" (id: ${r}), url: ${g}`);const y=process.env.CODEYAM_ROOT_PATH||process.cwd(),x=Tt(p.name);await da({scenarioId:r,scenarioSlug:x,scenarioType:p.type||void 0,projectRoot:y}),En(),console.log(`[editor-capture-scenario] Active scenario set to "${x}", cache invalidated`),await new Promise(D=>setTimeout(D,300));const b=U.join(y,".codeyam","editor-scenarios","screenshots");await _e.mkdir(b,{recursive:!0});const w=si(import.meta.url),v=await ai(w,y);console.log(`[editor-capture-scenario] Capture script: ${v}`);let N;const S=p;if(t.dimensions&&t.dimensions.length>0)N=t.dimensions;else if(S.dimensions)try{const D=typeof S.dimensions=="string"?JSON.parse(S.dimensions):S.dimensions;N=Array.isArray(D)&&D.length>0?D:[null]}catch{N=[null]}else N=[null];const C=Zo(y);let A=null;const _={};let E=[],R=null;for(let D=0;D<N.length;D++){const T=N[D];let $;T&&C[T]?$=C[T]:$=ca({bodyWidth:a||S.viewport_width||void 0,bodyHeight:o||S.viewport_height||void 0,dimension:T||void 0,codeyamRoot:y});const L=T?_d(T):null,B=L&&N.length>1?`${r}--${L}.png`:`${r}.png`,H=U.join(b,B),q=`screenshots/${B}`,O=JSON.stringify({url:g,outputPath:H,viewportWidth:$.width,viewportHeight:$.height,...p.component_name?{selector:"#codeyam-capture"}:{}});console.log(`[editor-capture-scenario] Capture ${T||"default"}: ${$.width}×${$.height} → ${B}`);const W=Date.now(),I=await oi(v,O,y),j=Date.now()-W;if(console.log(`[editor-capture-scenario] Capture ${T||"default"} ${I.success?"succeeded":"FAILED"} in ${j}ms`),!I.success){console.warn(`[editor-capture-scenario] Capture stdout: ${I.output.slice(0,500)}`),console.warn(`[editor-capture-scenario] Capture stderr: ${(I.error||"").slice(0,500)}`),D===0&&(R=I.error||"Unknown capture error");continue}if(D===0){A=q;const k=Vd(I.output);E=k,await Gd(y,r,p.name,k)}T&&(_[T]=q)}if(!A&&R)return new Response(JSON.stringify({error:"Failed to capture screenshot",details:R}),{status:500,headers:{"Content-Type":"application/json"}});if(A){try{await c.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}const D={screenshot_path:A,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")};Object.keys(_).length>0&&(D.screenshot_paths=JSON.stringify(_)),await c.updateTable("editor_scenarios").set(D).where("id","=",r).execute()}return E.length>0&&console.warn(`[editor-capture-scenario] ${E.length} client-side error(s) detected:`,E),Nt.notifyChange("scenario"),new Response(JSON.stringify({success:!0,screenshotPath:A,screenshotPaths:Object.keys(_).length>0?_:null,clientErrors:E}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-capture-scenario] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const vx=Object.freeze(Object.defineProperty({__proto__:null,action:wx},Symbol.toStringTag,{value:"Module"}));async function Nx({request:e,params:t}){const r=t["*"];if(!r)return new Response("Image path is required",{status:400});const s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=se.join(s,".codeyam","editor-scenarios","screenshots",r),o=se.resolve(a),i=se.resolve(se.join(s,".codeyam","editor-scenarios","screenshots"));if(!o.startsWith(i))return new Response("Invalid path",{status:403});try{const l=await Ee.stat(a),c=`"${l.mtimeMs}-${l.size}"`;if(e.headers.get("If-None-Match")===c)return new Response(null,{status:304,headers:{ETag:c,"Cache-Control":"public, max-age=300"}});const u=await Ee.readFile(a),h=se.extname(a).toLowerCase(),m=h===".png"?"image/png":h===".jpg"||h===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(u,{status:200,headers:{"Content-Type":m,"Cache-Control":"public, max-age=300",ETag:c}})}catch{return new Response("Image not found",{status:404})}}const Sx=Object.freeze(Object.defineProperty({__proto__:null,loader:Nx},Symbol.toStringTag,{value:"Module"}));async function Cx({params:e}){const t=e["*"];if(!t)return new Response("Image path is required",{status:400});const r=process.env.CODEYAM_ROOT_PATH||process.cwd(),s=se.join(r,".codeyam","journal","screenshots",t),a=se.resolve(s),o=se.resolve(se.join(r,".codeyam","journal","screenshots"));if(!a.startsWith(o))return new Response("Invalid path",{status:403});try{const i=await Ee.readFile(s),l=se.extname(s).toLowerCase(),c=l===".png"?"image/png":l===".jpg"||l===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(i,{status:200,headers:{"Content-Type":c,"Cache-Control":"no-store"}})}catch{return new Response("Image not found",{status:404})}}const kx=Object.freeze(Object.defineProperty({__proto__:null,loader:Cx},Symbol.toStringTag,{value:"Module"})),_x=["JSX","React","Element","ReactNode"],Ex=new Set(["page.tsx","page.ts","index.tsx","index.ts"]);function Ax(e){if(e.returnType&&_x.some(t=>e.returnType.includes(t)))return!0;if(e.filePath){const t=e.filePath.split("/").pop()||"";if(Ex.has(t))return!0}return!1}function Px(e){const t=[],r=[];for(const s of e)Ax(s)?t.push(s):r.push(s);return{components:t,functions:r}}function Ka({components:e,functions:t,scenarioCounts:r,testFileExistence:s,testResults:a,clientErrors:o,totalScenarioCounts:i,entityChangeStatus:l,analysisFailedEntities:c}){const p=e.map(S=>{const C=r[S.name]||0,A=(i==null?void 0:i[S.name])||0,_=l==null?void 0:l[S.name],E=o==null?void 0:o[S.name],R=C>0&&E&&E.length>0;let D;c!=null&&c.has(S.name)?D="analysis_failed":C===0?_&&A>0?D="needs_recapture":D="missing":R?D="has_errors":D="ok";let T;if(D==="missing"){const $=S.filePath.split("/").pop()||"";$==="layout.tsx"||$==="layout.ts"?T=`This is a layout file — register an app-level scenario with pageFilePath instead of componentName: codeyam editor register '{"name":"${S.name} - Default","pageFilePath":"${S.filePath}","url":"/<route>","dimensions":["Desktop"]}'`:$==="page.tsx"||$==="page.ts"?T=`This is a page file — register an app-level scenario with pageFilePath: codeyam editor register '{"name":"${S.name} - Default","pageFilePath":"${S.filePath}","url":"/<route>","dimensions":["Desktop"]}'`:T=`Register a component scenario via an isolation route: codeyam editor isolate ${S.name} then codeyam editor register '{"name":"${S.name} - Default","componentName":"${S.name}","url":"/isolated-components/${S.name}?s=Default","dimensions":["Desktop"]}'`}else D==="needs_recapture"?T=`This component's code or dependencies changed — recapture existing scenarios to update screenshots: codeyam editor recapture ${S.name}`:D==="analysis_failed"&&(T="Analysis failed for this component (likely timed out due to complex dependencies). The component has partial data but may be missing some dependency schemas. Try re-analyzing: codeyam editor analyze-imports");return{name:S.name,filePath:S.filePath,scenarioCount:D==="needs_recapture"?A:C,status:D,...R?{clientErrors:E}:{},...T?{hint:T}:{}}}),u=t.map(S=>{if(!(S.testFile?s[S.testFile]??!1:!1)){const R=S.testFile?void 0:S.filePath.replace(/\.tsx?$/,".test.ts");return{name:S.name,filePath:S.filePath,testFile:S.testFile,testFileExists:!1,status:"missing",...R?{suggestedTestFile:R}:{}}}const A=S.testFile&&a?a[S.testFile]:void 0;if(!A)return{name:S.name,filePath:S.filePath,testFile:S.testFile,testFileExists:!0,status:"ok"};let _;!A.passing&&A.errorMessage?_="runner_error":A.passing?A.hasEntityNameDescribe?_="ok":_="name_mismatch":_="failing";let E;return _==="name_mismatch"?E=`Tests pass but won't show in the CodeYam UI. Add a top-level describe("${S.name}", ...) block in ${S.testFile}`:_==="runner_error"&&A.errorMessage&&(E=`Test runner crashed (not a test failure): ${A.errorMessage}`),{name:S.name,filePath:S.filePath,testFile:S.testFile,testFileExists:!0,testsPassing:A.passing,testsVisibleInUi:A.hasEntityNameDescribe,status:_,...A.errorMessage?{errorMessage:A.errorMessage}:{},...E?{hint:E}:{}}}),h=p.filter(S=>S.status==="ok").length,m=p.filter(S=>S.status==="has_errors").length,f=p.filter(S=>S.status==="missing").length,g=p.filter(S=>S.status==="needs_recapture").length,y=p.filter(S=>S.status==="analysis_failed").length,x=u.filter(S=>S.status==="ok").length,b=u.filter(S=>S.status==="failing").length,w=u.filter(S=>S.status==="runner_error").length,v=u.filter(S=>S.status==="name_mismatch").length,N=u.filter(S=>S.status==="missing").length;return{components:p,functions:u,summary:{totalComponents:p.length,componentsOk:h,componentsMissing:f,componentsWithErrors:m,componentsNeedingRecapture:g,componentsAnalysisFailed:y,totalFunctions:u.length,functionsOk:x,functionsMissing:N,functionsFailing:b,functionsRunnerError:w,functionsNameMismatch:v,allPassing:f===0&&m===0&&y===0&&b===0&&w===0&&v===0&&N===0}}}function jx({featureStartedAt:e,entityChangeStatus:t}){return t&&Object.keys(t).length>0?{featureStartedAt:e,entityChangeStatus:t}:{featureStartedAt:null,entityChangeStatus:t}}function Tx(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>!!(t[r.name]||t[r.filePath]))}async function Mx(e,t,r){const a=await e.selectFrom("editor_scenarios").select(["entity_sha"]).select(e.fn.count("id").as("count")).where("project_id","=",t).where("entity_sha","is not",null).groupBy("entity_sha").execute();if(a.length===0)return[];const o=a.map(N=>N.entity_sha),i=await e.selectFrom("analyses").select("entity_sha").where("entity_sha","in",o).groupBy("entity_sha").execute(),l=new Set(i.map(N=>N.entity_sha)),c=a.filter(N=>!l.has(N.entity_sha));if(c.length===0)return[];const p=c.map(N=>N.entity_sha),u=await e.selectFrom("entities").select(["sha","name","file_path"]).where("sha","in",p).execute(),h=new Map(u.map(N=>[N.sha,N.name])),m=new Map(u.map(N=>[N.sha,N.file_path])),f=[...new Set(u.map(N=>`${N.name}::${N.file_path}`).filter(N=>!N.startsWith("::")&&!N.endsWith("::")))];let g=new Set;if(f.length>0){const N=[...new Set(u.map(C=>C.name).filter(Boolean))],S=await e.selectFrom("entities").innerJoin("analyses","analyses.entity_sha","entities.sha").select(["entities.name","entities.file_path"]).where("entities.name","in",N).groupBy(["entities.name","entities.file_path"]).execute();g=new Set(S.map(C=>`${C.name}::${C.file_path}`))}const y=c.filter(N=>{const S=N.entity_sha,C=h.get(S),A=m.get(S);if(!C)return!1;const _=`${C}::${A}`;return!g.has(_)});if(y.length===0)return[];const x=y.map(N=>N.entity_sha),b=await e.selectFrom("editor_scenarios").select(["entity_sha","component_name"]).where("project_id","=",t).where("entity_sha","in",x).where("component_name","is not",null).groupBy("entity_sha").execute(),w=new Map(b.map(N=>[N.entity_sha,N.component_name]));let v=new Set;if(r){const N=r.replace("T"," ").replace(/\.\d{3}Z$/,""),S=await e.selectFrom("editor_scenarios").select("entity_sha").where("project_id","=",t).where("entity_sha","in",x).where(C=>C.or([C("created_at",">=",N),C("updated_at",">=",N)])).groupBy("entity_sha").execute();v=new Set(S.map(C=>C.entity_sha))}return y.map(N=>{const S=N.entity_sha;return{entitySha:S,name:h.get(S)||w.get(S)||"Unknown",scenarioCount:Number(N.count),preExisting:r?!v.has(S):!1}})}async function $x(e,t,r){let s=e.selectFrom("editor_scenarios").select(["component_name","name","url"]).where("project_id","=",t).where("component_name","is not",null).where("url","is not",null);if(r){const l=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(c=>c.or([c("created_at",">=",l),c("updated_at",">=",l)]))}const o=(await s.execute()).filter(l=>l.url&&!ia(l.url));if(o.length===0)return[];const i=new Map;for(const l of o){const c=`${l.component_name}::${l.url}`,p=i.get(c);p?p.scenarioNames.push(l.name):i.set(c,{componentName:l.component_name,scenarioNames:[l.name],url:l.url})}return[...i.values()]}async function jl(e,t,r){let s=e.selectFrom("editor_scenarios").select(["component_name"]).select(e.fn.count("id").as("count")).where("project_id","=",t).where("component_name","is not",null).groupBy("component_name");if(r){const i=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(l=>l.or([l("created_at",">=",i),l("updated_at",">=",i)]))}const a=await s.execute(),o={};for(const i of a)i.component_name&&(o[i.component_name]=Number(i.count));return o}async function Tl(e,t,r){let s=e.selectFrom("editor_scenarios").select(["page_file_path"]).select(e.fn.count("id").as("count")).where("project_id","=",t).where("component_name","is",null).where("page_file_path","is not",null).groupBy("page_file_path");if(r){const i=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(l=>l.or([l("created_at",">=",i),l("updated_at",">=",i)]))}const a=await s.execute(),o={};for(const i of a)i.page_file_path&&(o[i.page_file_path]=Number(i.count));return o}async function Ix(e,t,r){var i;let s=e.selectFrom("editor_scenarios").select(["component_name","component_path","page_file_path","name"]).where("project_id","=",t).where("entity_sha","is",null).where(l=>l.or([l("component_path","is not",null),l("page_file_path","is not",null)]));if(r){const l=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(c=>c.or([c("created_at",">=",l),c("updated_at",">=",l)]))}const a=await s.execute();if(a.length===0)return[];const o=new Map;for(const l of a){const c=l,p=c.component_path||c.page_file_path,u=o.get(p);if(u)u.scenarioNames.push(c.name);else{const h=c.component_name||((i=p.split("/").pop())==null?void 0:i.replace(/\.\w+$/,""))||p;o.set(p,{name:h,filePath:p,scenarioNames:[c.name]})}}return[...o.values()].map(l=>({name:l.name,filePath:l.filePath,scenarioCount:l.scenarioNames.length,scenarioNames:l.scenarioNames}))}function Rx(e){const t=new Map;for(const r of e){const s=t.get(r.name);s?s.push(r):t.set(r.name,[r])}for(const[r,s]of t)s.length<=1&&t.delete(r);return t}function au(e){const{scenarios:t,entityChangeStatus:r}=e;if(!r||Object.keys(r).length===0)return[];const s=[];for(const a of t){if(a.updatedInSession||!a.entityName)continue;const o=r[a.entityName];o&&o.status!=="new"&&s.push({scenarioName:a.name,entityName:a.entityName,status:o})}return s}function Dx(e,t){const r={},s=new Map;for(const a of t){const o=Kt({componentName:a.componentName,pageFilePath:a.pageFilePath,url:a.url});o&&s.set(a.name,o)}for(const[,a]of Object.entries(e)){if(a.errors.length===0)continue;let o=s.get(a.scenarioName);if(!o){const i=a.scenarioName.indexOf(" - ");o=i>=0?a.scenarioName.slice(0,i):a.scenarioName}o&&(r[o]||(r[o]=[]),r[o].push(...a.errors))}return r}async function ou(e){const{scenarios:t,codeyamRoot:r,proxyUrl:s,devUrl:a,db:o,importMetaUrl:i,onProgress:l}=e,c={recaptured:[],failed:[]};if(t.length===0)return c;const p=si(i),u=await ai(p,r),h=U.join(r,".codeyam","editor-scenarios","screenshots");for(const m of t)try{const f=Tt(m.name);await da({scenarioId:m.id,scenarioSlug:f,projectRoot:r}),En(),await new Promise(N=>setTimeout(N,300));const g=Qo(m.url||null,s,a);if(!g){c.failed.push({name:m.name,error:"No capture URL available"});continue}const y=U.join(h,`${m.id}.png`);let x;try{const N=m.dimensions?JSON.parse(m.dimensions):null;Array.isArray(N)&&N.length>0&&(x=N[0])}catch{}const b=ca({bodyWidth:m.viewport_width||void 0,bodyHeight:m.viewport_height||void 0,dimension:x,codeyamRoot:r}),w=JSON.stringify({url:g,outputPath:y,viewportWidth:b.width,viewportHeight:b.height,...m.component_name?{selector:"#codeyam-capture"}:{}});l==null||l(`Capturing "${m.name}"...`),console.log(`[recapture] Capturing "${m.name}" at ${b.width}x${b.height}`);const v=await oi(u,w,r);if(v.success)await o.updateTable("editor_scenarios").set({screenshot_path:`screenshots/${m.id}.png`,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")}).where("id","=",m.id).execute(),c.recaptured.push(m.name),l==null||l(`Recaptured "${m.name}"`),console.log(`[recapture] Succeeded: "${m.name}"`);else{const N=v.error||"Unknown capture error";c.failed.push({name:m.name,error:N}),l==null||l(`Failed: "${m.name}" — ${N}`),console.warn(`[recapture] Failed: "${m.name}": ${N}`)}}catch(f){const g=f instanceof Error?f.message:String(f);c.failed.push({name:m.name,error:g}),console.warn(`[recapture] Error for "${m.name}": ${g}`)}return c}const Fx=Object.freeze(Object.defineProperty({__proto__:null,recaptureScenarios:ou},Symbol.toStringTag,{value:"Module"}));async function Ox({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ne()||process.cwd(),r=await Ye();if(!r)return Response.json({error:"No project configured"},{status:400});const{project:s}=await De(r),a=Pe(),o=process.env.CODEYAM_ROOT_PATH||process.cwd(),i=U.join(t,".codeyam","editor-step.json");let l=null;try{const S=V.readFileSync(i,"utf8");l=JSON.parse(S).featureStartedAt||null}catch{}try{await Je();const S=await Xe({})||[];await Ed(a,S.map(C=>{var A,_;return{sha:C.sha,name:C.name,filePath:C.filePath||"",isDefaultExport:((A=C.metadata)==null?void 0:A.notExported)===!1&&((_=C.metadata)==null?void 0:_.namedExport)===!1}}))}catch{}const c=await a.selectFrom("editor_scenarios").select(["id","name","component_name","component_path","page_file_path","url","display_name","dimensions","viewport_width","viewport_height","created_at","updated_at"]).where("project_id","=",s.id).orderBy("created_at","asc").execute(),p=Ct(c,S=>`${S.name}::${S.url||"/"}`),u=p.map(S=>({componentName:S.component_name||null,componentPath:S.component_path||null,pageFilePath:S.page_file_path??null,url:S.url??null,displayName:S.display_name??null})),{entityChangeStatus:h}=await ir({projectRoot:t,scenarioInputs:u});if(Object.keys(h).length===0)return Response.json({type:"done",recaptured:[],failed:[],total:0,note:"No entity changes detected."});const m=l?zr(l):null,f=p.map(S=>({name:S.name,entityName:Kt({componentName:S.component_name,pageFilePath:S.page_file_path,url:S.url}),updatedInSession:m?qo({created_at:S.created_at,updated_at:S.updated_at},m):!1})),g=au({scenarios:f,entityChangeStatus:h});if(g.length===0)return Response.json({type:"done",recaptured:[],failed:[],total:0,note:"All scenarios are up to date."});const y=new Set(g.map(S=>S.scenarioName)),x=p.filter(S=>y.has(S.name)).map(S=>({id:S.id,name:S.name,url:S.url,component_name:S.component_name,dimensions:S.dimensions,viewport_width:S.viewport_width,viewport_height:S.viewport_height})),b=await ni(),w=ei(),v=new Map(p.map(S=>[S.name,S])),N=new ReadableStream({async start(S){const C=_=>{S.enqueue(new TextEncoder().encode(JSON.stringify(_)+`
339
+ `))};C({type:"start",total:g.length});const A=await ou({scenarios:x,codeyamRoot:o,proxyUrl:b,devUrl:w,db:a,importMetaUrl:import.meta.url,onProgress:_=>{if(_.startsWith('Recaptured "')){const E=_.slice(12,-1);C({type:"success",name:E});const R=v.get(E);if(R)try{Yy(o,R.id,`screenshots/${R.id}.png`)}catch{}}else if(_.startsWith('Failed: "')){const E=_.match(/^Failed: "(.+?)" — (.+)$/);E&&C({type:"failure",name:E[1],error:E[2]})}else if(_.startsWith('Capturing "')){const E=_.slice(11,_.indexOf('"',11));C({type:"capturing",name:E})}}});C({type:"done",recaptured:A.recaptured,failed:A.failed,total:g.length}),S.close()}});return new Response(N,{headers:{"Content-Type":"application/x-ndjson","Transfer-Encoding":"chunked"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-recapture-stale] Error:",t),Response.json({error:r},{status:500})}}const Lx=Object.freeze(Object.defineProperty({__proto__:null,action:Ox},Symbol.toStringTag,{value:"Module"}));async function Bx({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,name:s}=t;if(!r||!(s!=null&&s.trim()))return Response.json({error:"Missing required fields: scenarioId, name"},{status:400});const a=s.trim();await Pe().updateTable("editor_scenarios").set({name:a,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")}).where("id","=",r).execute();const l=Ne()||process.cwd(),p=zy(l).find(u=>u.id===r);return p&&qd(l,r,{...p.metadata,name:a,updatedAt:new Date().toISOString()}),Response.json({success:!0,name:a})}catch(t){return console.error("[API] Error renaming scenario:",t),Response.json({error:"Failed to rename scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const zx=Object.freeze(Object.defineProperty({__proto__:null,action:Bx},Symbol.toStringTag,{value:"Module"}));async function Yx({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=t.mode||"overwrite",s=t.localStorage,a=Ne()||process.cwd(),o=se.join(a,".codeyam"),i=se.join(o,"active-scenario.json");if(!ge.existsSync(i))return new Response(JSON.stringify({error:"No active scenario"}),{status:400,headers:{"Content-Type":"application/json"}});const c=JSON.parse(ge.readFileSync(i,"utf-8")).scenarioId;if(!c)return new Response(JSON.stringify({error:"No active scenario ID"}),{status:400,headers:{"Content-Type":"application/json"}});const p=se.join(o,"editor-scenarios"),u=Mr(a);let h=null;if(u){const f=se.join(o,"tmp",`export-${Date.now()}.json`);ge.mkdirSync(se.dirname(f),{recursive:!0});const g=await D0(u,f);if(!g.success)return new Response(JSON.stringify({error:`Export failed: ${g.error}`}),{status:500,headers:{"Content-Type":"application/json"}});try{h=JSON.parse(ge.readFileSync(f,"utf-8"))}finally{try{ge.unlinkSync(f)}catch{}}}if(!h&&!s)return new Response(JSON.stringify({error:"No data to save: no seed adapter found and no localStorage provided"}),{status:400,headers:{"Content-Type":"application/json"}});let m=c;if(r==="new"){m=er.randomUUID();const f=se.join(p,`${c}.json`);let g={_metadata:{type:"application"}};ge.existsSync(f)&&(g=JSON.parse(ge.readFileSync(f,"utf-8"))),h&&(g.seed=h),s&&(g.localStorage=s),ge.writeFileSync(se.join(p,`${m}.json`),JSON.stringify(g,null,2)),h&&ge.writeFileSync(se.join(p,`${m}.seed.json`),JSON.stringify(h,null,2))}else{const f=se.join(p,`${c}.json`);if(ge.existsSync(f)){const g=JSON.parse(ge.readFileSync(f,"utf-8"));h&&(g.seed=h),s&&(g.localStorage=s),ge.writeFileSync(f,JSON.stringify(g,null,2))}h&&ge.writeFileSync(se.join(p,`${c}.seed.json`),JSON.stringify(h,null,2))}return En(),new Response(JSON.stringify({success:!0,mode:r,scenarioId:m}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Wx=Object.freeze(Object.defineProperty({__proto__:null,action:Yx},Symbol.toStringTag,{value:"Module"}));async function Ux({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});const t=await e.json(),{prompt:r}=t;if(!r)return Response.json({error:"Missing prompt"},{status:400});const s=Ne()||process.cwd(),a=U.join(s,".codeyam","tmp");V.mkdirSync(a,{recursive:!0});const o=jo.randomUUID().slice(0,8),i=U.join(a,`scenario-prompt-${o}.md`);return V.writeFileSync(i,r,"utf8"),Response.json({promptFile:i})}const Jx=Object.freeze(Object.defineProperty({__proto__:null,action:Ux},Symbol.toStringTag,{value:"Module"}));let gn=null;async function Hx({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioSlug:r,scenarioId:s,scenarioName:a,scenarioType:o,skipBroadcast:i}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({error:"scenarioSlug is required"}),{status:400,headers:{"Content-Type":"application/json"}});const l=Ne()||process.cwd(),c=se.join(l,".codeyam"),p=se.join(c,"active-scenario.json");let u=o||null;if(!u&&s){const x=se.join(c,"editor-scenarios",`${s}.json`);try{ge.existsSync(x)&&(u=JSON.parse(ge.readFileSync(x,"utf-8")).type||null)}catch{}}let h=null;try{ge.existsSync(p)&&(h=JSON.parse(ge.readFileSync(p,"utf-8")).scenarioId||null)}catch{}const m=h===s&&s!==null;ge.mkdirSync(c,{recursive:!0}),ge.writeFileSync(p,JSON.stringify({scenarioSlug:r,scenarioName:a||null,scenarioId:s||null,type:u,dataFile:s?`.codeyam/editor-scenarios/${s}.json`:null,switchedAt:new Date().toISOString()},null,2));let f=null;const g=u==="application"||u==="user";if(g&&s&&m)console.log(`[editor-switch-scenario] Same scenario "${r}" already active — skipping seed`),f={success:!0};else if(g&&s)if(gn&&gn.scenarioId===s)console.log(`[editor-switch-scenario] Seed already in progress for "${s}" — reusing`),f=await gn.promise;else{const x=Mr(l),b=se.join(c,"editor-scenarios",`${s}.seed.json`);if(x&&ge.existsSync(b)){console.log(`[editor-switch-scenario] Running seed adapter for ${u} scenario "${a||r}"`);const w=Xo(x,b).then(v=>{const N={success:v.success,error:v.error};if(v.success){if(console.log(`[editor-switch-scenario] Seed adapter completed in ${v.durationMs}ms`),v.sessionCookies&&v.sessionCookies.length>0)try{const S=se.join(c,"editor-scenarios",`${s}.json`);if(ge.existsSync(S)){const C=JSON.parse(ge.readFileSync(S,"utf-8"));C.sessionCookies=v.sessionCookies,ge.writeFileSync(S,JSON.stringify(C,null,2))}}catch{}}else console.warn(`[editor-switch-scenario] Seed adapter failed: ${v.error}`);return N});gn={scenarioId:s,promise:w};try{f=await w}finally{gn&&gn.scenarioId===s&&(gn=null)}}else x||(console.warn("[editor-switch-scenario] No seed adapter found — skipping database seeding"),f={success:!1,error:"No seed adapter found"})}En();const y=i?0:li();return new Response(JSON.stringify({success:!0,scenarioSlug:r,refreshedClients:y,seeded:g,...f?{seedResult:f}:{}}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Vx=Object.freeze(Object.defineProperty({__proto__:null,action:Hx},Symbol.toStringTag,{value:"Module"}));var ke;(e=>{(t=>{t.OPENAI_GPT5_1="openai/gpt-5.1",t.OPENAI_GPT5="openai/gpt-5",t.OPENAI_GPT5_MINI="openai/gpt-5-mini",t.OPENAI_GPT5_NANO="openai/gpt-5-nano",t.OPENAI_GPT4_1="openai/gpt-4.1",t.OPENAI_GPT4_1_MINI="openai/gpt-4.1-mini",t.OPENAI_GPT4_O="openai/gpt-4o",t.OPENAI_GPT4_O_MINI="openai/gpt-4o-mini",t.OPENAI_GPT_OSS_120B_GROQ="openai/gpt-oss-120b-groq",t.OPENAI_GPT_OSS_120B_DEEPINFRA="openai/gpt-oss-120b-deepinfra",t.QWEN3_235B_INSTRUCT_DEEPINFRA="qwen/qwen3-235b-instruct-deepinfra",t.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA="qwen/qwen3-coder-480b-instruct-deepinfra",t.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA="google/gemini-2.5-pro-deepinfra",t.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA="google/gemini-2.5-flash-deepinfra",t.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER="google/gemini-2.5-flash-lite-openrouter",t.META_LLAMA_4_MAVERICK_OPENROUTER="meta-llama/llama-4-maverick-openrouter",t.DEEPSEEK_V3_1_TERMINUS_OPENROUTER="deepseek/v3.1-terminus-openrouter",t.ANTHROPIC_CLAUDE_4_5_HAIKU="anthropic/claude-4.5-haiku",t.ANTHROPIC_CLAUDE_4_5_SONNET="anthropic/claude-4.5-sonnet",t.ANTHROPIC_CLAUDE_4_5_OPUS="anthropic/claude-4.5-opus",t.PHIND_CODELLAMA="phind/codellama",t.GOOGLE_GEMINI_PRO="google/gemini-pro",t.GOOGLE_PALM_2_CODE_CHAT_32K="google/palm-2-code-chat-32k",t.META_CODELLAMA_34B_INSTRUCT="meta-llama/codellama-34b-instruct",t.OPENAI_GPT4_PREVIEW="openai/gpt-4-preview"})(e.Model||(e.Model={}))})(ke||(ke={}));function iu(e,t){return e?Object.values(ke.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const lu=iu(process.env.DEFAULT_SMALLER_MODEL,ke.Model.OPENAI_GPT4_1_MINI),Gx=iu(process.env.DEFAULT_LARGER_MODEL,ke.Model.OPENAI_GPT4_1),jt={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},qa={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},Kx={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},Qa={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},en={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},qx={[ke.Model.OPENAI_GPT5_1]:{id:ke.Model.OPENAI_GPT5_1,provider:jt,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[ke.Model.OPENAI_GPT5]:{id:ke.Model.OPENAI_GPT5,provider:jt,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[ke.Model.OPENAI_GPT5_MINI]:{id:ke.Model.OPENAI_GPT5_MINI,provider:jt,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[ke.Model.OPENAI_GPT5_NANO]:{id:ke.Model.OPENAI_GPT5_NANO,provider:jt,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[ke.Model.OPENAI_GPT4_1]:{id:ke.Model.OPENAI_GPT4_1,provider:jt,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[ke.Model.OPENAI_GPT4_1_MINI]:{id:ke.Model.OPENAI_GPT4_1_MINI,provider:jt,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ke.Model.OPENAI_GPT4_O]:{id:ke.Model.OPENAI_GPT4_O,provider:jt,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[ke.Model.OPENAI_GPT4_O_MINI]:{id:ke.Model.OPENAI_GPT4_O_MINI,provider:jt,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[ke.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:ke.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:qa,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[ke.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:ke.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:qa,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[ke.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:ke.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:qa,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[ke.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:ke.Model.OPENAI_GPT_OSS_120B_GROQ,provider:Kx,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[ke.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:ke.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:en,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[ke.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:ke.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:en,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[ke.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:ke.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:en,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ke.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:ke.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:en,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[ke.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:ke.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:en,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[ke.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:ke.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:Qa,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[ke.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:ke.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:Qa,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[ke.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:ke.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:Qa,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[ke.Model.PHIND_CODELLAMA]:{id:ke.Model.PHIND_CODELLAMA,provider:jt,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ke.Model.GOOGLE_GEMINI_PRO]:{id:ke.Model.GOOGLE_GEMINI_PRO,provider:en,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ke.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:ke.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:en,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ke.Model.META_CODELLAMA_34B_INSTRUCT]:{id:ke.Model.META_CODELLAMA_34B_INSTRUCT,provider:en,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ke.Model.OPENAI_GPT4_PREVIEW]:{id:ke.Model.OPENAI_GPT4_PREVIEW,provider:jt,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function ya(e){const t=qx[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function Qx(e){return ya(e).maxCompletionTokens}function Zx(e){return ya(e).pricing}const Ml=1e6;function Xx({model:e,usage:t}){const r=Zx(e);return r?t.prompt_tokens*(r.input/Ml)+t.completion_tokens*(r.output/Ml):null}function eb({chatRequest:e,chatCompletion:t,model:r}){if("error"in t&&t.error)return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),error:JSON.stringify(t.error)};const s=t.usage||{prompt_tokens:0,completion_tokens:0},a=Xx({model:r,usage:s});return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,cost:a?Math.round(a*1e5)/1e5:void 0}}function tb({messages:{system:e,prompt:t},model:r,responseType:s,jsonSchema:a}){const o=r??lu,i=ya(o);Qx(o);const l=[];return e&&l.push({role:"system",content:e}),l.push({role:"user",content:[{type:"text",text:t}]}),{messages:l,model:i.apiModelName,response_format:s==="json_schema"&&a?{type:"json_schema",json_schema:{name:a.name,schema:a.schema,strict:a.strict!==!1}}:{type:s&&s=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}let Er=null;function nb(e){if(typeof process>"u"||!process.versions||!process.versions.node)return!1;try{const t=jr(e,".codeyam","secrets.json");if(vt(t)){const s=JSON.parse(rl(t,"utf-8"));if(s.anthropicApiKey||s.ANTHROPIC_API_KEY||s.openAiApiKey||s.OPENAI_API_KEY||s.groqApiKey||s.GROQ_API_KEY)return!0}const r=jr(fh(),".codeyam","secrets.json");if(vt(r)){const s=JSON.parse(rl(r,"utf-8"));if(s.anthropicApiKey||s.ANTHROPIC_API_KEY||s.openAiApiKey||s.OPENAI_API_KEY||s.groqApiKey||s.GROQ_API_KEY)return!0}return!!(process.env.OPENAI_API_KEY||process.env.ANTHROPIC_API_KEY||process.env.GROQ_API_KEY)}catch{return!1}}function rb(e){if(typeof process>"u"||!process.versions||!process.versions.node)return!1;const t=jr(e,".claude");return vt(t)}function xk(e){if(nb(e))return Er={mode:"direct-api",projectRoot:e},"direct-api";if(rb(e))return Er={mode:"claude-cli",projectRoot:e},"claude-cli";throw new Error(`No AI service configured. Please either:
340
+ 1. Add an API key to ~/.codeyam/secrets.json (shared across projects) or .codeyam/secrets.json (project-specific), or
341
+ 2. Use Claude Code CLI (detected by .claude folder)`)}function sb(){return(Er==null?void 0:Er.mode)==="claude-cli"}const yo="/tmp/codeyam-e2e-tracking";let Za,Xa;function ab(){return Za===void 0&&(Za=process.env.CODEYAM_E2E_TRACK_DATA==="true"),Za}function ob(){return Xa===void 0&&(Xa=!process.env.CODEYAM_LLM_FIXTURES_DIR),Xa}function ib(){V.existsSync(yo)||V.mkdirSync(yo,{recursive:!0})}function lb(e){const t=JSON.stringify(e,null,0);return jo.createHash("md5").update(t).digest("hex")}function cb(e,t,r){return[e].join("_")+".json"}function cu(e,t,r,s){if(!ab())return;ib();const a=cb(e),o=U.join(yo,a),i=lb(t);if(ob()){const l={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:s,dataHash:i,data:t};V.writeFileSync(o,JSON.stringify(l,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(V.existsSync(o)){const l=JSON.parse(V.readFileSync(o,"utf-8")),c={matches:i===l.dataHash,firstRunHash:l.dataHash};if(c.matches)console.log(`[E2E Tracking] Match at ${e} hash=${i.substring(0,8)}`);else{c.differences=xo(l.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${l.dataHash}`),console.log(` Second run hash: ${i}`);const p=o.replace(".json","_DIFF.json");V.writeFileSync(p,JSON.stringify({checkpoint:e,entityName:r,scenarioName:s,firstRun:l.data,secondRun:t,differences:c.differences},null,2)),console.log(` Diff saved to: ${p}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function xo(e,t,r=""){const s=[];if(typeof e!=typeof t)return s.push(`${r||"root"}: type mismatch (${typeof e} vs ${typeof t})`),s;if(e===null||t===null)return e!==t&&s.push(`${r||"root"}: ${JSON.stringify(e)} vs ${JSON.stringify(t)}`),s;if(Array.isArray(e)&&Array.isArray(t)){e.length!==t.length&&s.push(`${r||"root"}: array length ${e.length} vs ${t.length}`);const a=Math.max(e.length,t.length);for(let o=0;o<a;o++)s.push(...xo(e[o],t[o],`${r}[${o}]`));return s}if(typeof e=="object"&&typeof t=="object"){const a=Object.keys(e),o=Object.keys(t),i=Array.from(new Set([...a,...o]));for(const l of i){const c=e[l],p=t[l];l in e?l in t?s.push(...xo(c,p,`${r?r+".":""}${l}`)):s.push(`${r?r+".":""}${l}: missing in second run`):s.push(`${r?r+".":""}${l}: missing in first run`)}return s}if(e!==t){const a=JSON.stringify(e),o=JSON.stringify(t);a.length<100&&o.length<100?s.push(`${r||"root"}: ${a} vs ${o}`):s.push(`${r||"root"}: values differ (${a.length} chars vs ${o.length} chars)`)}return s}const $l=$o(Mo),Il=2;function db(e){try{return JSON.parse(e),{valid:!0}}catch(t){return{valid:!1,error:t.message}}}function ub(e){const t=e.trim(),r=(t.match(/\{/g)||[]).length,s=(t.match(/\}/g)||[]).length,a=(t.match(/\[/g)||[]).length,o=(t.match(/\]/g)||[]).length,i=(t.match(new RegExp('(?<!\\\\)"',"g"))||[]).length;return r>s||a>o||i%2!==0||!t.endsWith("}")&&!t.endsWith("]")}async function du(e,t,r,s=0){try{const a=`${e}
342
+
343
+ ${t}${r?`
344
+
345
+ Respond with valid JSON only.`:""}`;let o="claude";try{const{stdout:c}=await $l("which claude",{timeout:1e3});o=c.trim()}catch{const c=["/usr/local/bin/claude",`${process.env.HOME}/.nvm/versions/node/v20.16.0/bin/claude`,`${process.env.HOME}/.npm-global/bin/claude`];for(const p of c)try{await $l(`test -x "${p}"`,{timeout:1e3}),o=p;break}catch{}}const{stdout:i,stderr:l}=await new Promise((c,p)=>{var y,x,b;const h=ft(o,["-p",a,"--output-format","json","--max-turns","1"],{env:{...process.env}});(y=h.stdin)==null||y.end();let m="",f="";(x=h.stdout)==null||x.on("data",w=>{const v=w.toString();m+=v}),(b=h.stderr)==null||b.on("data",w=>{f+=w.toString()}),h.on("error",w=>{p(w)}),h.on("close",(w,v)=>{if(w===0)c({stdout:m,stderr:f});else{const N=new Error(`Command failed with exit code ${w}. stderr: ${f.substring(0,500)}`);N.code=w,N.stdout=m,N.stderr=f,p(N)}});const g=setTimeout(()=>{h.kill("SIGTERM"),setTimeout(()=>{h.killed||h.kill("SIGKILL")},5e3),p(new Error("Claude CLI command timed out after 60 seconds"))},6e4);h.on("close",()=>clearTimeout(g))});try{const c=JSON.parse(i);let p=c.result||c.response||c.text||c.content;if(!p)throw new Error("No response content from Claude CLI");const u=p.match(/^```(?:json)?\s*\n([\s\S]*?)\n```\s*$/);if(u&&(p=u[1]),r){const h=db(p);if(h.valid)console.log("✅ Claude CLI: JSON validation passed");else{console.log(`⚠️ Claude CLI: Invalid JSON response (attempt ${s+1}/${Il+1})`),console.log(`⚠️ Claude CLI: JSON error: ${h.error}`),console.log(`⚠️ Claude CLI: Response length: ${p.length} bytes`);const m=ub(p);if(console.log(`⚠️ Claude CLI: Appears truncated: ${m}`),m&&s<Il){console.log(`🔄 Claude CLI: Attempting to recover truncated JSON (retry ${s+1})`);const f=`The previous response was truncated and incomplete. Here's what was received:
346
+
347
+ \`\`\`json
348
+ ${p}
349
+ \`\`\`
350
+
351
+ Please complete this JSON response. Make sure it's valid, complete JSON that properly closes all braces, brackets, and quotes. Return ONLY the complete, valid JSON.`;try{return await du(e,f,r,s+1)}catch(g){console.log(`⚠️ Claude CLI: Recovery attempt failed: ${g}`)}}console.log(`⚠️ Claude CLI: Returning invalid JSON response after ${s+1} attempts`),console.log(`⚠️ Claude CLI: Downstream parsing will likely fail. First 500 chars: ${p.substring(0,500)}`)}}return p}catch(c){if(i.trim())return i.trim();throw new Error(`Failed to parse Claude CLI response: ${c}`)}}catch(a){const o=a.message;throw o.includes("command not found")||o.includes("ENOENT")?new Error("Claude Code CLI not found. Please ensure Claude Code is installed."):o.includes("not authenticated")||o.includes("subscription")?new Error("Claude Code CLI not authenticated. Please run `claude` to authenticate."):a}}const hs=new Nh({concurrency:100,timeout:1200*1e3,autoStart:!0}),Rl={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},tn={};async function bo({type:e,systemMessage:t,prompt:r,jsonResponse:s=!0,jsonSchema:a,model:o=lu,attempts:i=0}){var A,_,E,R,D,T,$;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await pb(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${hs.size}, running=${hs.pending}]`);const l=Date.now();let c,p=0;if(sb()){console.log("Using Claude CLI mode for AI request");const L=await du(t,r,s);return{finishReason:"stop",completion:L,stats:{model:"claude-sonnet-4-5",prompt_type:e,system_message:t,prompt_text:r,response:L,input_tokens:0,output_tokens:0,cost:0}}}const u=ya(o),h=process.env[u.provider.apiKeyEnvVar];if(!h)throw new Error(`API key not found for provider ${u.provider.name}. Please set ${u.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${u.provider.name} for AI request`);const m=new vh({apiKey:h,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:a?"json_schema":s?"json_object":"text",jsonSchema:a},g=tb(f),y=await hs.add(()=>(c=Date.now(),sl(async()=>{const L=Date.now(),B=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],H=setInterval(()=>{const q=Math.floor((Date.now()-L)/1e3),O=Math.floor(q/10)%B.length;ol(1,`${B[O]} [type=${e}, model=${o}, elapsed=${q}s]`)},1e4);try{return await m.chat.completions.create(g,{timeout:300*1e3})}finally{clearInterval(H)}},{...Rl,onFailedAttempt:L=>{p++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:L,prompt:r,systemMessage:t,attempts:i,retryCount:p})}})));if(!y)throw new Error("Completion call returned no result");const x=y,b=Date.now(),w=eb({chatRequest:f,chatCompletion:x,model:o});if(!w)throw new Error("Failed to get LLM call stats");w.retries=p,w.wait_ms=c-l,w.duration_ms=b-l;const v=(A=x.choices)==null?void 0:A[0];let N=null;if(v){if(!v.finish_reason)throw console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({chatCompletion:x,chatRequest:f},null,2)),new Error("completionCall(): missing finish_reason in LLM response");N=(_=v.message)==null?void 0:_.content}let S=N;N&&(S=N.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const C=s?S&&(((E=S.match(/\{[\s\S]*\}/))==null?void 0:E[0])??S):S;if(!C){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:C,rawCompletion:N,chatCompletion:x,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await bo({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(C.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:N,prompt:r,systemMessage:t}),new Error("Empty completion");if(s)try{JSON.parse(C)}catch(L){if(console.log("CodeYam Error: Invalid JSON in completion",{error:L.message,model:o,completion:C.substring(0,500),rawCompletion:N==null?void 0:N.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:L.message});const B=`Your previous response contained invalid JSON with the following error:
352
+
353
+ ${L.message}
354
+
355
+ Here was your previous response:
356
+ \`\`\`
357
+ ${C}
358
+ \`\`\`
359
+
360
+ Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,H=await hs.add(()=>sl(async()=>{const j=Date.now(),k=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],Y=setInterval(()=>{const G=Math.floor((Date.now()-j)/1e3),Q=Math.floor(G/10)%k.length;ol(1,`${k[Q]} [type=${e}, model=${o}, elapsed=${G}s]`)},1e4);try{return await m.chat.completions.create({...g,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:C},{role:"user",content:B}]},{timeout:300*1e3})}finally{clearInterval(Y)}},{...Rl,onFailedAttempt:j=>{console.log("CodeYam Error: Correction call failed",{error:j,attempts:i})}}));if(!H)throw new Error("Correction call returned no result");const q=H,O=(T=(D=(R=q.choices)==null?void 0:R[0])==null?void 0:D.message)==null?void 0:T.content;let W=O;O&&(W=O.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const I=W&&((($=W.match(/\{[\s\S]*\}/))==null?void 0:$[0])??W);if(!I)throw new Error("Correction attempt returned empty completion");try{JSON.parse(I),console.log("CodeYam: JSON correction successful");const j=Date.now();return w.duration_ms=j-l,{finishReason:q.choices[0].finish_reason,completion:I,stats:w}}catch(j){return console.log("CodeYam Error: Corrected JSON still invalid",{error:j.message,correctedCompletion:I.substring(0,500)}),await bo({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${L.message}`)}return cu(`completionCall_${e}`,{completion:C,finishReason:x.choices[0].finish_reason}),{finishReason:x.choices[0].finish_reason,completion:C,stats:w}}async function pb(e,t,r){var o,i,l,c,p;const s=await import("fs"),a=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!s.existsSync(t))throw console.log(`CodeYam Test: Fixtures directory does not exist yet: ${t}`),new Error(`No LLM fixture files found - directory does not exist: ${t}`);const u=s.readdirSync(t).filter(w=>w.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${t}`);const h={};for(const w of u)try{const v=s.readFileSync(a.join(t,w),"utf-8"),N=JSON.parse(v);h[N.prompt_type]||(h[N.prompt_type]=[]),h[N.prompt_type].push(N)}catch(v){console.warn(`Failed to parse LLM fixture file ${w}:`,v)}for(const w of Object.keys(h))h[w].sort((v,N)=>{const S=v.created_at??0,C=N.created_at??0;return S-C});const m=h[e];if(!m||m.length===0){const w=Object.keys(h).join(", ");return console.warn(`CodeYam Test: No captured LLM call found for type '${e}'. Available types: ${w}`),{finishReason:"stop",completion:"{}",stats:{model:"fixture-fallback",prompt_type:e,system_message:"",prompt_text:"",response:"{}",input_tokens:0,output_tokens:0,cost:0}}}let f;if(["generateEntityScenarioData","generateChunkMockData","generateMissingMockData"].includes(e)&&r){const w=r.match(/Scenario name must match exactly: "([^"]+)"/),v=w==null?void 0:w[1];if(v){const N={};for(const C of m)try{const _=((o=JSON.parse(C.props||"{}").scenario)==null?void 0:o.name)||"__NO_SCENARIO__";N[_]||(N[_]=[]),N[_].push(C)}catch{}const S=N[v];if(S&&S.length>0){const C=`${t}::${e}::${v}`;tn[C]===void 0&&(tn[C]=0);const A=tn[C];tn[C]=(A+1)%S.length,f=S[A],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${v}' [${A+1}/${S.length}]`)}else{const C=Object.keys(N).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${v}'. Available: [${C}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const w=`${t}::${e}`;tn[w]===void 0&&(tn[w]=0);const v=tn[w];tn[w]=(v+1)%m.length,f=m[v],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${v+1}/${m.length}]`)}let y;try{y=((c=(l=(i=JSON.parse(f.response).choices)==null?void 0:i[0])==null?void 0:l.message)==null?void 0:c.content)||f.response}catch{y=f.response}let x=y;y&&(x=y.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const b=x&&(((p=x.match(/\{[\s\S]*\}/))==null?void 0:p[0])??x);return cu(`completionCall_${e}`,{completion:b||"",finishReason:"stop"}),{finishReason:"stop",completion:b||"",stats:{model:f.model??"fixture",prompt_type:e,system_message:f.system_message??"",prompt_text:f.prompt_text??"",response:f.response??"",input_tokens:f.input_tokens??0,output_tokens:f.output_tokens??0,cost:f.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(u){throw console.error("CodeYam Test Error: Failed to replay LLM call:",u),u}}function Dl(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function hb(e){const{propsJson:t,...r}=e,s=JSON.stringify(t,null,2),a=To(),o=Date.now(),i={...r,id:a,created_at:o,props:s};let l;const c=`${i.object_id}_${a}.json`;if(process.env.DYNAMODB_PATH?l=U.join(process.env.DYNAMODB_PATH,c):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(l=U.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",c)),l)try{const u=U.dirname(l);return await _e.mkdir(u,{recursive:!0}),await _e.writeFile(l,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${l}`),{id:a}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const p=Dl();if(!p)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,h]of Object.entries(i))typeof h>"u"&&console.log(`CodeYam Warning: LLM call ${a} property ${u} with explicit value 'undefined'`);try{return await new Gs().send(new Sh({TableName:Dl(),Item:kh(i,{removeUndefinedValues:!0})})),{id:a}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${p}`,u),{id:"-1"}}}new Gs({});new Gs({});new Gs({});const mb=3,fb=2,mi=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+mb*String(t).length*(1+fb)});new Do(mi());new Do(mi());new Do(mi());class gb{constructor(){this.byMethodName=new Map,this.byClassAndMethod=new Map}register(t,r,s){this.byMethodName.has(t)||this.byMethodName.set(t,[]),this.byMethodName.get(t).push(r),s&&(this.byClassAndMethod.has(s)||this.byClassAndMethod.set(s,new Map),this.byClassAndMethod.get(s).set(t,r))}getByMethodName(t){return this.byMethodName.get(t)}getByClassAndMethod(t,r){var s;return(s=this.byClassAndMethod.get(t))==null?void 0:s.get(r)}}class yb{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class xb{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class bb{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class wb{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class vb{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];if(s.addType(o,"function"),s.addEquivalence(o.withParameter(1),r.withElement("*")),a.args.length>1){const i=a.args[1];s.addEquivalence(o.withParameter(0),i)}}}isComplete(){return!0}}class Nb{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.getLastFunctionCallSegment();a&&a.args.forEach(o=>{s.addEquivalence(t,o)}),s.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class Sb{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.withReturnValues();s.addType(a,"unknown")}isComplete(){return!0}}class Cb{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>2)for(let o=2;o<a.args.length;o++){const i=a.args[o];s.addEquivalence(r.withElement("*"),i)}}isComplete(){return!0}}class kb{getReturnType(){return"number"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0)for(let o=0;o<a.args.length;o++)s.addEquivalence(r.withElement("*"),t.withParameter(o))}isComplete(){return!0}}class _b{getReturnType(){return"string"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}class Eb{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Ab{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Pb{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown"),s.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class jb{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Tb{getReturnType(){return"object"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"array")}}isComplete(){return!0}}class Mb{getReturnType(){return"string[]"}addEquivalences(t,r,s){s.addType(r,"string"),s.addType(t,"string[]"),s.addEquivalence(t.withReturnValues().withElement("*"),r)}isComplete(){return!0}}class $b{getReturnType(){return"unknown"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r),s.addEquivalence(t.withProperty("functionCallReturnValue"),o.withProperty("returnValue"))}}isComplete(){return!0}}class Ib{getReturnType(){return"unknown"}addEquivalences(t,r,s){t.getLastFunctionCallSegment()}isComplete(){return!0}}class Rb{getReturnType(){return"array"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(s.addType(t.withParameter(1),"function"),a&&a.args.length>0){const o=a.args[0];s.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}class Db{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(t,"boolean")}isComplete(){return!0}}class Fb{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(t,"boolean")}isComplete(){return!0}}function Ob(){const e=new gb;return e.register("filter",new yb,"Array"),e.register("map",new Eb,"Array"),e.register("flatMap",new Ab,"Array"),e.register("join",new _b,"Array"),e.register("find",new wb,"Array"),e.register("findLast",new jb,"Array"),e.register("at",new Pb,"Array"),e.register("reduce",new vb,"Array"),e.register("concat",new Nb,"Array"),e.register("slice",new Sb,"Array"),e.register("splice",new Cb,"Array"),e.register("push",new kb,"Array"),e.register("some",new xb,"Array"),e.register("every",new bb,"Array"),e.register("fromEntries",new Tb,"Object"),e.register("split",new Mb,"String"),e.register("then",new $b,"Promise"),e.register("useState",new Rb,"React"),e.register("useMemo",new Ib,"React"),e.register("has",new Db),e.register("delete",new Fb),e}Ob();new Set(Object.getOwnPropertyNames(Array.prototype).filter(e=>typeof Array.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(String.prototype).filter(e=>typeof String.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Number.prototype).filter(e=>typeof Number.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Boolean.prototype).filter(e=>typeof Boolean.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Date.prototype).filter(e=>typeof Date.prototype[e]=="function"));const Lb=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),Bb=new Set(["find","findLast","at","pop","shift"]),zb=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),Yb=new Set([...Lb,...Bb,...zb]),Wb=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Ub=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Jb=new Set([...Wb,...Ub]);[...Yb,...Jb];class Hb{constructor(t){this.depth=0,this.traceCount=0,this.defaultOutput=(r,s)=>{const a=" ".repeat(this.depth),o=this.timestamps?`[${Date.now()}] `:"";s?console.info(`${o}${a}${r}`,JSON.stringify(s)):console.info(`${o}${a}${r}`)},this.enabled=t.enabled,this.pathPatterns=t.pathPatterns??[],this.scopePatterns=t.scopePatterns??[],this.maxDepth=t.maxDepth??50,this.output=t.output??this.defaultOutput,this.timestamps=t.timestamps??!1}shouldTrace(t){return!this.enabled||this.depth>=this.maxDepth?!1:!!(this.pathPatterns.length===0&&this.scopePatterns.length===0||t.path&&this.pathPatterns.length>0&&this.pathPatterns.some(r=>r.test(t.path))||t.scope&&this.scopePatterns.length>0&&this.scopePatterns.some(r=>r.test(t.scope)))}trace(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[TRACE] ${t}`,r))}traceEnter(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[ENTER] ${t}`,r),this.depth++)}traceExit(t,r={}){this.depth>0&&this.depth--,this.shouldTrace(r)&&this.output(`[EXIT] ${t}`,r)}traceWarn(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[WARN] ${t}`,r))}enable(){this.enabled=!0}disable(){this.enabled=!1}resetDepth(){this.depth=0}getStats(){return{traceCount:this.traceCount,currentDepth:this.depth,enabled:this.enabled}}reset(){this.depth=0,this.traceCount=0}}new Hb({enabled:!1});function yn(e,t){const r={added:{},removed:{},changed:{}},s=new Set(Object.keys(e??{})),a=new Set(Object.keys(t??{}));for(const o of a)s.has(o)||(r.added[o]=t[o]);for(const o of s)a.has(o)||(r.removed[o]=e[o]);for(const o of s)a.has(o)&&e[o]!==t[o]&&(r.changed[o]={from:e[o],to:t[o]});return r}function Vb(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function ms(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let Gb=0;class fi{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++Gb,this.enabled=(t==null?void 0:t.enabled)??!1,this.outputPath=(t==null?void 0:t.outputPath)??"/tmp/codeyam/transform-trace.json",this.enabled&&console.log(`[Tracer] Initialized (id=${this.tracerId}, output=${this.outputPath})`)}log(t){this.isEnabled()&&console.log(`[Tracer] ${t}`)}isEnabled(){const t=process.env.CODEYAM_TRACE_TRANSFORMS;return t==="1"||t==="true"?!0:this.enabled}enable(){this.enabled=!0}disable(){this.enabled=!1}setOutputPath(t){this.outputPath=t}setProjectSlug(t){this.projectSlug=t}startEntity(t){if(!this.isEnabled())return;this.currentEntity=t.name;const r=this.traces.get(t.name);if(r){this.log(`startEntity: ${t.name} already exists, preserving ${r.stages.length} stages`);return}this.log(`startEntity: ${t.name}`),this.traces.set(t.name,{entityName:t.name,entityType:t.entityType,filePath:t.filePath,stages:[],operations:[]})}snapshot(t,r,s){var c,p,u,h;if(!this.isEnabled())return;const a=this.traces.get(t);if(!a)return this.log(`snapshot: no trace for ${t}, creating one`),this.startEntity({name:t,entityType:"unknown",filePath:"unknown"}),this.snapshot(t,r,s);this.log(`snapshot: ${t} → ${r}`),this.currentStage=r;const o=JSON.parse(JSON.stringify(s)),i={stage:r,timestamp:Date.now(),data:o},l=a.stages[a.stages.length-1];if(l&&(i.diffFromPrevious={signatureSchema:yn(l.data.signatureSchema,o.signatureSchema),returnValueSchema:yn(l.data.returnValueSchema,o.returnValueSchema)},o.dependencySchemas||l.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const m=new Set([...Object.keys(o.dependencySchemas??{}),...Object.keys(l.data.dependencySchemas??{})]);for(const f of m){const g=(c=l.data.dependencySchemas)==null?void 0:c[f],y=(p=o.dependencySchemas)==null?void 0:p[f];for(const x of new Set([...Object.keys(g??{}),...Object.keys(y??{})])){const b=`${f}::${x}`,w=(u=g==null?void 0:g[x])==null?void 0:u.returnValueSchema,v=(h=y==null?void 0:y[x])==null?void 0:h.returnValueSchema,N=yn(w,v);Vb(N)&&(i.diffFromPrevious.dependencySchemas[b]=N)}}}a.stages.push(i)}operation(t,r){if(!this.isEnabled())return;const s=this.traces.get(t);s&&s.operations.push({...r,stage:r.stage??this.currentStage??void 0,timestamp:Date.now()})}computeFlushSummary(){var a;const t={},r=new Map;for(const[o,i]of this.traces){let l=0;for(const c of i.stages){if(!c.diffFromPrevious)continue;const u=`${((a=i.stages[i.stages.indexOf(c)-1])==null?void 0:a.stage)??"start"}→${c.stage}`;if(t[u]||(t[u]={added:0,removed:0,changed:0}),c.diffFromPrevious.signatureSchema){const h=c.diffFromPrevious.signatureSchema;t[u].added+=Object.keys(h.added).length,t[u].removed+=Object.keys(h.removed).length,t[u].changed+=Object.keys(h.changed).length,l+=ms(h)}if(c.diffFromPrevious.returnValueSchema){const h=c.diffFromPrevious.returnValueSchema;t[u].added+=Object.keys(h.added).length,t[u].removed+=Object.keys(h.removed).length,t[u].changed+=Object.keys(h.changed).length,l+=ms(h)}}r.set(o,l)}const s=[...r.entries()].sort((o,i)=>i[1]-o[1]).slice(0,10).map(([o])=>o);return{stageChangeCounts:t,entitiesWithMostChanges:s}}flush(){if(!this.isEnabled())return;if(this.traces.size===0){this.log("flush: no traces to write");return}const t=Array.from(this.traces.keys()),r=t.map(p=>`${p}(${this.traces.get(p).stages.length})`).join(", ");this.log(`flush: writing ${t.length} entities: ${r}`);const{stageChangeCounts:s,entitiesWithMostChanges:a}=this.computeFlushSummary(),o={timestamp:new Date().toISOString(),projectSlug:this.projectSlug,entityCount:this.traces.size},i={stageChangeCounts:s,entitiesWithMostChanges:a},l=U.dirname(this.outputPath);V.existsSync(l)||V.mkdirSync(l,{recursive:!0});const c=V.openSync(this.outputPath,"w");try{V.writeSync(c,`{
361
+ "meta": `),V.writeSync(c,JSON.stringify(o,null,2)),V.writeSync(c,`,
362
+ "summary": `),V.writeSync(c,JSON.stringify(i,null,2)),V.writeSync(c,`,
363
+ "entities": {`);let p=!0;for(const[u,h]of this.traces)p||V.writeSync(c,","),V.writeSync(c,`
364
+ ${JSON.stringify(u)}: `),V.writeSync(c,JSON.stringify(h,null,2)),p=!1;V.writeSync(c,`
365
+ }
366
+ }
367
+ `),this.log(`flush: wrote trace to ${this.outputPath}`)}finally{V.closeSync(c)}}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=V.readFileSync(t,"utf-8"),s=JSON.parse(r),a=new fi({enabled:!1});a.projectSlug=s.meta.projectSlug;for(const[o,i]of Object.entries(s.entities))a.traces.set(o,i);return a}getSummary(){var a,o,i;const t={},r=new Map;for(const[l,c]of this.traces){let p=0;for(let u=1;u<c.stages.length;u++){const h=c.stages[u],f=`${((a=c.stages[u-1])==null?void 0:a.stage)??"start"}→${h.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(o=h.diffFromPrevious)!=null&&o.signatureSchema){const g=h.diffFromPrevious.signatureSchema;t[f].added+=Object.keys(g.added).length,t[f].removed+=Object.keys(g.removed).length,t[f].changed+=Object.keys(g.changed).length,p+=ms(g)}if((i=h.diffFromPrevious)!=null&&i.returnValueSchema){const g=h.diffFromPrevious.returnValueSchema;t[f].added+=Object.keys(g.added).length,t[f].removed+=Object.keys(g.removed).length,t[f].changed+=Object.keys(g.changed).length,p+=ms(g)}}r.set(l,p)}const s=[...r.entries()].sort((l,c)=>c[1]-l[1]).slice(0,10).map(([l,c])=>({name:l,totalChanges:c}));return{entityCount:this.traces.size,stageChangeCounts:t,entitiesWithMostChanges:s}}getEntitySummary(t){const r=this.traces.get(t);return r?{entityName:t,stages:r.stages.map(s=>({stage:s.stage,diffFromPrevious:s.diffFromPrevious?{signatureSchema:s.diffFromPrevious.signatureSchema,returnValueSchema:s.diffFromPrevious.returnValueSchema}:void 0}))}:null}getOperations(t,r){const s=this.traces.get(t);return s?r?s.operations.filter(a=>a.path&&r.test(a.path)):s.operations:[]}tracePath(t,r){var o,i;const s=this.traces.get(t),a=[];if(!s)return{entityName:t,path:r,history:a};for(const l of s.stages){const c=(o=l.data.signatureSchema)==null?void 0:o[r],p=(i=l.data.returnValueSchema)==null?void 0:i[r],u=c??p;u!==void 0&&a.push({stage:l.stage,value:u})}for(const l of s.operations)l.path===r&&a.push({operation:l.operation,stage:l.stage,value:l.after??l.before,context:l.context});return{entityName:t,path:r,history:a}}getEntityTrace(t){return this.traces.get(t)}getEntityNames(){return[...this.traces.keys()]}findProperty(t,r){const s=this.traces.get(t);if(!s)return[];const a=[],o=new RegExp(`(^|\\.)${r}(\\.|\\[|$)`);for(const i of s.stages){for(const[l,c]of Object.entries(i.data.signatureSchema??{}))o.test(l)&&a.push({stage:i.stage,path:l,type:c,schemaType:"signature"});for(const[l,c]of Object.entries(i.data.returnValueSchema??{}))o.test(l)&&a.push({stage:i.stage,path:l,type:c,schemaType:"returnValue"});for(const[l,c]of Object.entries(i.data.dependencySchemas??{}))for(const[p,u]of Object.entries(c))for(const[h,m]of Object.entries(u.returnValueSchema??{}))o.test(h)&&a.push({stage:i.stage,path:`${l}/${p}::${h}`,type:m,schemaType:"dependency"})}return a}findTypeInconsistencies(t){const r=this.traces.get(t);if(!r)return[];let s=r.stages[r.stages.length-1];for(let c=r.stages.length-1;c>=0;c--)if(Object.keys(r.stages[c].data.dependencySchemas??{}).length>0){s=r.stages[c];break}if(!s)return[];const a=new Set(["length","toString","valueOf","constructor"]),o=new Map,i=(c,p)=>{const u=c.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!u)return;const h=u[1],m=u[2]==="[]";if(a.has(h))return;const f=h+(m?"[]":"");o.has(f)||o.set(f,[]),o.get(f).push({path:c,type:p})};for(const[,c]of Object.entries(s.data.dependencySchemas??{}))for(const[,p]of Object.entries(c))for(const[u,h]of Object.entries(p.returnValueSchema??{}))i(u,h);const l=[];for(const[c,p]of o)new Set(p.map(h=>h.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&l.push({propertyName:c,paths:p.map(h=>({...h,stage:s.stage}))});return l.sort((c,p)=>{const u=new Set(c.paths.map(m=>m.type)).size;return new Set(p.paths.map(m=>m.type)).size-u}),l}getStageDiffSummary(t,r,s){const a=this.traces.get(t);if(!a)return null;const o=a.stages.find(m=>m.stage===r),i=a.stages.find(m=>m.stage===s);if(!o||!i)return null;const l={added:[],removed:[],typeChanged:[]},c=o.data.returnValueSchema??{},p=i.data.returnValueSchema??{},u=new Set(Object.keys(c)),h=new Set(Object.keys(p));for(const m of h)u.has(m)?c[m]!==p[m]&&l.typeChanged.push({path:m,from:c[m],to:p[m]}):l.added.push(`${m}: ${p[m]}`);for(const m of u)h.has(m)||l.removed.push(`${m}: ${c[m]}`);return l}traceSchemaTransform(t,r,s,a,o){if(!this.enabled)return a(s),s;const i={...s};a(s);const l=yn(i,s);for(const[c,p]of Object.entries(l.added))this.operation(t,{operation:r,path:c,before:void 0,after:p,context:{...o,changeType:"added"}});for(const[c,p]of Object.entries(l.removed))this.operation(t,{operation:r,path:c,before:p,after:void 0,context:{...o,changeType:"removed"}});for(const[c,{from:p,to:u}]of Object.entries(l.changed))this.operation(t,{operation:r,path:c,before:p,after:u,context:{...o,changeType:"changed"}});return s}traceSchemaTransformResult(t,r,s,a,o){if(!this.enabled)return;const i=yn(s,a);for(const[l,c]of Object.entries(i.added))this.operation(t,{operation:r,path:l,before:void 0,after:c,context:{...o,changeType:"added"}});for(const[l,c]of Object.entries(i.removed))this.operation(t,{operation:r,path:l,before:c,after:void 0,context:{...o,changeType:"removed"}});for(const[l,{from:c,to:p}]of Object.entries(i.changed))this.operation(t,{operation:r,path:l,before:c,after:p,context:{...o,changeType:"changed"}})}traceDependencySchemaTransform(t,r,s,a,o="both"){if(!this.enabled){for(const i in s)for(const l in s[i]){const c=s[i][l];(o==="signature"||o==="both")&&c.signatureSchema&&a(c.signatureSchema),(o==="returnValue"||o==="both")&&c.returnValueSchema&&a(c.returnValueSchema)}return}for(const i in s)for(const l in s[i]){const c=s[i][l],p={filePath:i,dependencyName:l};(o==="signature"||o==="both")&&c.signatureSchema&&this.traceSchemaTransform(t,r,c.signatureSchema,a,{...p,schemaType:"signature"}),(o==="returnValue"||o==="both")&&c.returnValueSchema&&this.traceSchemaTransform(t,r,c.returnValueSchema,a,{...p,schemaType:"returnValue"})}}traceDependencySchemaChanges(t,r,s,a){var i;if(!this.enabled){a();return}const o={};for(const l in s){o[l]={};for(const c in s[l]){const p=s[l][c];o[l][c]={sig:{...p.signatureSchema||{}},rv:{...p.returnValueSchema||{}}}}}a();for(const l in s)for(const c in s[l]){const p=s[l][c],u=(i=o[l])==null?void 0:i[c],h={filePath:l,dependencyName:c};if(p.signatureSchema){const m=(u==null?void 0:u.sig)||{},f=yn(m,p.signatureSchema);for(const[g,y]of Object.entries(f.added))this.operation(t,{operation:r,path:g,before:void 0,after:y,context:{...h,schemaType:"signature",changeType:"added"}});for(const[g,{from:y,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:g,before:y,after:x,context:{...h,schemaType:"signature",changeType:"changed"}})}if(p.returnValueSchema){const m=(u==null?void 0:u.rv)||{},f=yn(m,p.returnValueSchema);for(const[g,y]of Object.entries(f.added))this.operation(t,{operation:r,path:g,before:void 0,after:y,context:{...h,schemaType:"returnValue",changeType:"added"}});for(const[g,{from:y,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:g,before:y,after:x,context:{...h,schemaType:"returnValue",changeType:"changed"}})}}}}function Kb(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const Fl=new fi({enabled:Kb(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{Fl.isEnabled()&&Fl.flush()});function uu(e){if(e==null)return null;const t=e.match(/```json\s*([\s\S]*?)\s*```/);t&&(e=t[1]),e=e.replace(/"[^"]+"\s*:\s*undefined\s*,?\s*/g,""),e=e.replace(/,(\s*[}\]])/g,"$1");try{return Ch.parse(e)}catch(r){const a=r.message.match(/invalid character .* at (\d+):(\d+)/);if(a){const o=parseInt(a[2],10);if(e.substring(o-2,o-1)==='"')return e=e.substring(0,o-2)+"\\"+e.substring(o-2),uu(e)}return null}}function qb({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:s}){let a="";return s&&s.length>0&&(a=`
368
+ User-selected Execution Flow Values:
369
+ The user has specifically requested these values be used in the scenario:
370
+ ${s.map(o=>` - ${o.path}: ${o.value}${o.isCustom?" (custom value)":""}`).join(`
371
+ `)}
372
+
373
+ IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
374
+ `),`Mock Scenario Data Structure:
375
+ \`\`\`
376
+ ${JSON.stringify(r,null,2)}
377
+ \`\`\`
378
+ Existing Mock Scenario Data:
379
+ \`\`\`
380
+ ${JSON.stringify(t,null,2)}
381
+ \`\`\`
382
+ ${a}
383
+ New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
384
+ `}function Qb({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}){const o=s.find(i=>i.name===Qs);return`Mock Scenario Data Structure:
385
+ \`\`\`
386
+ ${JSON.stringify({props:a.arguments,dataVariables:a.dataForMocks},null,2)}
387
+ \`\`\`
388
+
389
+ Existing Mock Scenario Data:
390
+ \`\`\`
391
+ ${JSON.stringify(s.map(i=>({name:i.name,data:Sr(o.metadata.data,i.metadata.data)})),null,2)}
392
+ \`\`\`
393
+
394
+ Mock Scenario that should be edited: "${t}"
395
+ ${r?`The portion of the data that should be edited:
396
+ \`\`\`
397
+ ${JSON.stringify(r,null,2)}
398
+ \`\`\``:""}
399
+
400
+ How this data should be changed: "${e}"
401
+ `}async function Zb({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,flowSelections:o,model:i}){const l=t?Qb({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}):qb({description:e,existingScenarios:s,scenariosDataStructure:a,flowSelections:o}),c=await bo({type:"guessScenarioDataFromDescription",systemMessage:t?ew(r):Xb,prompt:l,model:i??Gx});await hb({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,model:i},...c.stats});const{completion:p}=c;return p?uu(p):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const Xb=`
402
+ You will be provided with a list of data secnarios for a component and the overall structure for the data. Additionally you'll receive a description for a new scenario written by the user.
403
+
404
+ Your goal is to add one scenario to the list of existing scenarios by generating an english name, proper description, and a JSON data structure that describes the data that would be used in a scenario for the code.
405
+
406
+ The data for the scenario will be merged with the "Default Scenario" data, so you don't need to replicate any data in the default scenario but must overwrite any data that should be different.
407
+
408
+ You must respond with valid JSON following this format of this TS type definition:
409
+ \`\`\`
410
+ export type ScenarioData = {
411
+ name: string;
412
+ description: string;
413
+ data: {
414
+ mockData: { [key: string]: unknown };
415
+ argumentsData: { [key: string]: unknown };
416
+ };
417
+ };
418
+
419
+ \`\`\`
420
+ `,ew=e=>`
421
+ You will be provided with a list of data secnarios for a component and the overall structure for the data. Additionally you'll receive a description for a new scenario written by the user.
422
+
423
+ Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
424
+ ${e?`
425
+ We only want to edit a specific portion of the data, which is provided in the "The portion of the data that should be edited" section. You should only change the data that is provided in this section.`:""}
426
+
427
+ Always return the complete data structure for the scenario, with both mockData and argumentsData, even if you only changed a small portion of the data.
428
+
429
+ You must respond with valid JSON following this type definition:
430
+ \`\`\`
431
+ {
432
+ data: {
433
+ mockData: { [key: string]: unknown };
434
+ argumentsData: { [key: string]: unknown };
435
+ }
436
+ }
437
+ \`\`\`
438
+ `;async function tw({request:e}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:s,scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:l}=t;if(!r&&(!l||l.length===0))return re({error:"Missing required field: description or flowSelections"},{status:400});const c=await Zb({description:r||"",existingScenarios:s??[],scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:l}),p=(c==null?void 0:c.data)||c;return re({success:!0,data:p})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),re({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const nw=Object.freeze(Object.defineProperty({__proto__:null,action:tw},Symbol.toStringTag,{value:"Module"}));function rw(e,t,r=new Date){const s={"1d":1,"3d":3,"7d":7,"30d":30}[t],a=new Date(r);a.setDate(a.getDate()-s);const o=a.toISOString().split("T")[0],i=e.filter(h=>h.date>=o),l=new Set(i.map(h=>h.commitSha).filter(Boolean)),c=new Map;for(const h of i)if(h.scenarioScreenshots)for(const m of h.scenarioScreenshots){c.has(m.name)||c.set(m.name,[]);const f=c.get(m.name);f.some(g=>g.path===m.path)||f.push({path:m.path,time:h.time})}for(const h of c.values())h.sort((m,f)=>m.time.localeCompare(f.time));const p=[],u=new Map;for(const[h,m]of c){const f=h.indexOf(" - ");if(f!==-1){const g=h.slice(0,f);u.has(g)||u.set(g,[]),u.get(g).push({name:h,screenshots:m})}else p.push({name:h,screenshots:m})}return{commitCount:l.size,entryCount:i.length,appScenarios:p,componentGroups:u,totalScenarios:c.size}}function sw(e){const t=new Map;for(const r of[...e].reverse()){const s=t.get(r.date)||[];s.push(r),t.set(r.date,s)}return t}function aw(e){const t=new Map;for(const r of e){let s;if("componentName"in r&&r.componentName)s=r.componentName;else if("componentName"in r&&r.componentName===null)s="App";else{const o=r.name.indexOf(" - ");s=o!==-1?r.name.slice(0,o):"App"}const a=t.get(s)||[];a.push(r),t.set(s,a)}return[...t.entries()].sort(([r],[s])=>r==="App"?-1:s==="App"?1:r.localeCompare(s))}function ow(e,t){const r=e.replace(/[^a-zA-Z0-9_\-]/g,"_");return`${t.toISOString().replace(/:/g,"-").replace(/\.\d+Z$/,"")}_${r}.png`}function iw(e){const{title:t,timeStr:r,type:s,description:a,allScenarioNames:o,screenshot:i,scenarioScreenshots:l,commitSha:c,commitMessage:p,featureName:u,userPrompt:h}=e,m=["","---","",`### ${t}`,`**Time:** ${r}`,`**Type:** ${s}`];if(u&&m.push(`**Feature:** ${u}`),h&&m.push(`**Prompt:** ${h}`),o.length>0&&m.push(`**Scenarios:** ${o.join(", ")}`),m.push(""),m.push(a),i&&(m.push(""),m.push(`![${t}](${i})`)),l.length>0){m.push(""),m.push("**Scenario Screenshots:**");for(const f of l)m.push(""),m.push(`![${f.name}](${f.path})`)}return c&&p&&(m.push(""),m.push(`**Commit:** \`${c}\` — ${p}`)),m.push(""),m.join(`
439
+ `)}function lw(e,t){return e.findIndex(r=>r.time===t)}function cw(e){return!!e.commitSha}function dw(e,t){return t.commitSha!==void 0&&(e.commitSha=t.commitSha),t.commitMessage!==void 0&&(e.commitMessage=t.commitMessage),t.description!==void 0&&(e.description=t.description),t.scenarios!==void 0&&(e.scenarios=t.scenarios),t.scenarioScreenshots!==void 0&&(e.scenarioScreenshots=t.scenarioScreenshots),e}function uw(e,t,r,s){const a=`
440
+ **Commit:** \`${r}\` — ${s||"no message"}
441
+ `,o=`### ${t}`,i=e.lastIndexOf(o);if(i===-1)return null;const l=e.indexOf(`
442
+ ---
443
+ `,i+1),c=l!==-1?l:e.length;return e.slice(0,c)+a+e.slice(c)}async function pw(e){console.log(`[editorScenarioLookup] Looking up screenshots for ${e.length} scenarios: ${e.join(", ")}`);try{const t=await Ye();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up scenarios"),[];const{project:r}=await De(t),a=await Pe().selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","page_file_path","url"]).where("project_id","=",r.id).where("name","in",e).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] DB query returned ${a.length} matching scenarios:`,a.map(c=>({name:c.name,screenshot_path:c.screenshot_path,id:c.id})));const o=a.filter(c=>!c.screenshot_path);o.length>0&&console.warn(`[editorScenarioLookup] ${o.length} scenarios have no screenshot_path:`,o.map(c=>c.name));const i=a.filter(c=>c.screenshot_path),l=Ct(i,c=>c.name).map(c=>({name:c.name,screenshotPath:c.screenshot_path,scenarioId:c.id,componentName:c.component_name||null,pageFilePath:c.page_file_path||null,url:c.url||null}));return console.log(`[editorScenarioLookup] Found ${l.length} scenarios with screenshots`),l}catch(t){return console.error("[editorScenarioLookup] Failed to look up scenario screenshots:",t),[]}}async function hw(e){console.log(`[editorScenarioLookup] Looking up screenshots by entity names: ${e.join(", ")}`);try{const t=await Ye();if(!t)return[];const{project:r}=await De(t),a=await Pe().selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","page_file_path","url"]).where("project_id","=",r.id).orderBy("created_at","asc").execute(),o=new Set(e),l=a.filter(p=>{const u=Kt({componentName:p.component_name,pageFilePath:p.page_file_path,url:p.url});return o.has(u)}).filter(p=>p.screenshot_path),c=Ct(l,p=>p.name).map(p=>({name:p.name,screenshotPath:p.screenshot_path,scenarioId:p.id,componentName:p.component_name||null,pageFilePath:p.page_file_path||null,url:p.url||null}));return console.log(`[editorScenarioLookup] Found ${c.length} scenarios for ${e.length} entities`),c}catch(t){return console.error("[editorScenarioLookup] Failed to look up entity screenshots:",t),[]}}async function pu(e){console.log("[editorScenarioLookup] Looking up session scenario screenshots",e?`(after ${e})`:"(all session)");try{const t=await Ye();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up session scenarios"),[];const{project:r}=await De(t),s=Pe(),a=Ne()||process.cwd();let o=null;const i=U.join(a,".codeyam","editor-step.json");try{const m=V.readFileSync(i,"utf8");o=JSON.parse(m).featureStartedAt||null}catch{return console.warn("[editorScenarioLookup] No editor-step.json found — cannot determine session start"),[]}if(!o)return console.warn("[editorScenarioLookup] No featureStartedAt found in editor-step.json"),[];const l=e&&e>o?e:o,c=zr(l),p=await s.selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","page_file_path","url"]).where("project_id","=",r.id).where("created_at",">=",c).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] Query returned ${p.length} scenarios since ${l}`);const u=p.filter(m=>m.screenshot_path),h=Ct(u,m=>m.name).map(m=>({name:m.name,screenshotPath:m.screenshot_path,scenarioId:m.id,componentName:m.component_name||null,pageFilePath:m.page_file_path||null,url:m.url||null}));return console.log(`[editorScenarioLookup] Found ${h.length} session scenarios with screenshots`),h}catch(t){return console.error("[editorScenarioLookup] Failed to look up session scenario screenshots:",t),[]}}async function wo(e,t,r){const s=U.join(t,".codeyam","journal","screenshots");await _e.mkdir(s,{recursive:!0});const a=[];for(const o of e){const i=U.join(t,".codeyam","editor-scenarios",o.screenshotPath),l=ow(o.name,r),c=U.join(s,l);console.log(`[editorScenarioLookup] Copying scenario screenshot: "${o.name}" from ${i} → ${c}`);try{await _e.access(i),await _e.copyFile(i,c),a.push({name:o.name,path:`screenshots/${l}`,componentName:o.componentName,url:o.url}),console.log(`[editorScenarioLookup] Successfully copied screenshot for "${o.name}"`)}catch(p){console.warn(`[editorScenarioLookup] Scenario screenshot not found: ${i}`,p instanceof Error?p.message:p)}}return console.log(`[editorScenarioLookup] Scenario screenshot summary: ${a.length} scenarios have screenshots embedded`),a}async function mw({request:e}){if(e.method!=="PATCH")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{time:r,commitSha:s,commitMessage:a,description:o,includeSessionScenarios:i}=t;if(!r)return new Response(JSON.stringify({error:"time is required to identify the entry"}),{status:400,headers:{"Content-Type":"application/json"}});const l=process.env.CODEYAM_ROOT_PATH||process.cwd(),c=U.join(l,".codeyam","journal"),p=U.join(c,"index.json");console.log(`[editor-journal-update] Updating entry with time="${r}"`);let u={entries:[]};try{const y=await _e.readFile(p,"utf8");u=JSON.parse(y)}catch{return new Response(JSON.stringify({error:"No journal index found"}),{status:404,headers:{"Content-Type":"application/json"}})}const h=lw(u.entries,r);if(h===-1)return new Response(JSON.stringify({error:`No journal entry found with time "${r}"`}),{status:404,headers:{"Content-Type":"application/json"}});const m=u.entries[h];if(cw(m))return console.log(`[editor-journal-update] Rejected: entry "${m.title}" already committed (${m.commitSha}). Create a new entry instead.`),new Response(JSON.stringify({error:`Journal entry already committed (${m.commitSha}). Create a new entry via POST /api/editor-journal-entry instead of updating.`}),{status:409,headers:{"Content-Type":"application/json"}});let f,g;if(i){const y=await pu();y.length>0&&(f=y.map(x=>x.name),g=await wo(y,l,new Date))}if(dw(m,{commitSha:s,commitMessage:a,description:o,scenarios:f,scenarioScreenshots:g}),u.entries[h]=m,await _e.writeFile(p,JSON.stringify(u,null,2),"utf8"),console.log("[editor-journal-update] Updated index.json"),s)try{const y=m.date,x=U.join(c,`${y}.md`);let b="";try{b=await _e.readFile(x,"utf8")}catch{}if(b){const w=uw(b,m.title,s,a||null);w&&(await _e.writeFile(x,w,"utf8"),console.log(`[editor-journal-update] Appended commit line to ${x}`))}}catch(y){console.warn("[editor-journal-update] Failed to update markdown:",y)}return Nt.notifyChange("journal"),console.log(`[editor-journal-update] Done: updated entry "${m.title}"`),new Response(JSON.stringify({success:!0,entry:m}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-update] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const fw=Object.freeze(Object.defineProperty({__proto__:null,action:mw},Symbol.toStringTag,{value:"Module"}));async function gw({request:e}){var t;try{const r=process.env.CODEYAM_ROOT_PATH||process.cwd(),s=await Kd(r);let a=0;const o={};for(const[c,p]of Object.entries(s))p.errors.length>0&&(o[c]=p,a+=p.errors.length);let i=Nl();if(!i)for(let c=0;c<20&&(await new Promise(p=>setTimeout(p,500)),i=Nl(),!i);c++);const l=((t=i==null?void 0:i.errors)==null?void 0:t.length)??0;return new Response(JSON.stringify({hasErrors:a>0||l>0,totalErrors:a+l,scenarios:o,livePreview:i?{loaded:i.loaded,hasContent:i.hasContent,errors:i.errors,url:i.url,lastUpdated:i.lastUpdated}:null}),{headers:{"Content-Type":"application/json"}})}catch(r){const s=r instanceof Error?r.message:String(r);return console.error("[editor-client-errors] Error:",r),new Response(JSON.stringify({error:s}),{status:500,headers:{"Content-Type":"application/json"}})}}const yw=Object.freeze(Object.defineProperty({__proto__:null,loader:gw},Symbol.toStringTag,{value:"Module"}));async function xw({request:e}){try{const r=(await Pn()||[]).filter(i=>i.analyses&&i.analyses.length>0).map(i=>{var g;const l=i.analyses[0],c=l.scenarios||[],p=!((g=l.status)!=null&&g.finishedAt),u=i.entityType||"visual",m=u==="library"||u==="functionCall"?c.some(y=>{var x;return!!((x=y.metadata)!=null&&x.executionResult)}):c.some(y=>{var x,b,w,v;return((b=(x=y.metadata)==null?void 0:x.screenshotPaths)==null?void 0:b[0])&&!((w=y.metadata)!=null&&w.noScreenshotSaved)&&!((v=y.metadata)!=null&&v.sameAsDefault)}),f=c.length;return{name:i.name,entityType:u,filePath:i.filePath||"",hasScreenshot:m,isAnalyzing:p,scenarioCount:f}}),s=r.filter(i=>i.hasScreenshot),a=r.filter(i=>!i.hasScreenshot&&!i.isAnalyzing).map(i=>i.name),o=r.filter(i=>i.isAnalyzing).length;return new Response(JSON.stringify({entities:r,summary:{total:r.length,withScreenshots:s.length,missingScreenshots:a,analyzing:o}}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-entity-status] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const bw=Object.freeze(Object.defineProperty({__proto__:null,loader:xw},Symbol.toStringTag,{value:"Module"}));async function ww({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{title:r,type:s,description:a,scenarios:o,includeSessionScenarios:i,screenshot:l,commitSha:c,commitMessage:p}=t;if(console.log(`[editor-journal-entry] Creating journal entry: title="${r}", type="${s}", scenarios=${JSON.stringify(o||[])}, includeSessionScenarios=${!!i}, screenshot=${l||"none"}`),!r||!s||!a)return console.warn("[editor-journal-entry] Missing required fields:",{title:!!r,type:!!s,description:!!a}),new Response(JSON.stringify({error:"title, type, and description are required"}),{status:400,headers:{"Content-Type":"application/json"}});const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=U.join(u,".codeyam","journal");await _e.mkdir(h,{recursive:!0});const m=new Date,f=m.toISOString().split("T")[0],g=m.toISOString();let y=o||[];const x=U.join(h,"index.json");let b={entries:[]};try{const B=await _e.readFile(x,"utf8");b=JSON.parse(B)}catch{}let w;i&&b.entries.length>0&&(w=b.entries[b.entries.length-1].time);const v=i?await pu(w):o&&o.length>0?await pw(o):[];i&&v.length>0&&(y=v.map(B=>B.name));const N=await wo(v,u,m);let S;try{const B=Ne()||process.cwd(),H=await Ye();if(H){const{project:q}=await De(H),W=await Pe().selectFrom("editor_scenarios").select(["name","component_name","component_path","page_file_path","url","display_name"]).where("project_id","=",q.id).orderBy("created_at","asc").execute(),j=Ct(W,Y=>`${Y.name}::${Y.url||"/"}`).map(Y=>({componentName:Y.component_name||null,componentPath:Y.component_path||null,pageFilePath:Y.page_file_path??null,url:Y.url??null,displayName:Y.display_name??null})),k=await ir({projectRoot:B,scenarioInputs:j});Object.keys(k.entityChangeStatus).length>0&&(S=k.entityChangeStatus)}}catch{}if(S&&Object.keys(S).length>0){const B=new Set(v.map(q=>q.name)),H=Object.entries(S).filter(([,q])=>q.status==="impacted").map(([q])=>q);if(H.length>0){const q=[],O=new Set(v.map(W=>Kt(W)));for(const W of H)O.has(W)||q.push(W);if(q.length>0)try{const W=await hw(q);if(W.length>0){const I=await wo(W.filter(j=>!B.has(j.name)),u,m);N.push(...I),y.push(...I.map(j=>j.name))}}catch{}}}let C=N,A=y;if(!i&&S&&Object.keys(S).length>0){C=u0(N,S);const B=new Set(C.map(H=>H.name));A=y.filter(H=>B.has(H))}const _=ui(u),E=pi(u);let R;try{const B=or();B.length>0&&(R=B.filter(H=>H.status!=="deleted").map(H=>({path:H.path,status:H.status})))}catch{}const D=U.join(h,`${f}.md`);let T="";try{T=await _e.readFile(D,"utf8")}catch{T=`# Development Journal — ${f}
444
+ `}const $=iw({title:r,timeStr:g,type:s,description:a,allScenarioNames:A,screenshot:l||null,scenarioScreenshots:C,commitSha:c||null,commitMessage:p||null,featureName:_,userPrompt:E});await _e.writeFile(D,T+$,"utf8"),console.log(`[editor-journal-entry] Written daily markdown: ${D}`);const L={date:f,time:g,title:r,type:s,description:a,scenarios:A,screenshot:l||null,scenarioScreenshots:C,commitSha:c||null,commitMessage:p||null,entityChangeStatus:S,featureName:_,userPrompt:E,modifiedFiles:R};b.entries.push(L),await _e.writeFile(x,JSON.stringify(b,null,2),"utf8"),console.log(`[editor-journal-entry] Updated index.json (now ${b.entries.length} entries)`);try{await _e.unlink(U.join(u,"editor-user-prompt.txt"))}catch{}return Nt.notifyChange("journal"),console.log(`[editor-journal-entry] Done: title="${r}", scenarioScreenshotsEmbedded=${C.length}`),new Response(JSON.stringify({success:!0,entry:L,scenarioScreenshotsFound:C.length}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-entry] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const vw=Object.freeze(Object.defineProperty({__proto__:null,action:ww},Symbol.toStringTag,{value:"Module"}));function Nw({request:e}){const t={"Content-Type":"application/json","Access-Control-Allow-Origin":"*"};try{const r=Ne()||process.cwd();let o=new URL(e.url).searchParams.get("scenarioId");if(!o){const c=U.join(r,".codeyam","active-scenario.json");if(!V.existsSync(c))return new Response(JSON.stringify({}),{headers:t});o=JSON.parse(V.readFileSync(c,"utf-8")).scenarioId||null}if(!o)return new Response(JSON.stringify({}),{headers:t});const i=U.join(r,".codeyam","editor-scenarios",`${o}.json`);if(!V.existsSync(i))return new Response(JSON.stringify({}),{headers:t});const l=V.readFileSync(i,"utf-8");return new Response(l,{headers:t})}catch{return new Response(JSON.stringify({}),{headers:t})}}const Sw=Object.freeze(Object.defineProperty({__proto__:null,loader:Nw},Symbol.toStringTag,{value:"Module"}));async function Cw({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=Array.isArray(t.paths)?t.paths:[],s=Array.isArray(t.apiRoutes)?t.apiRoutes:[];if(r.length===0&&s.length===0)return new Response(JSON.stringify({error:'At least one entry in "paths" or "apiRoutes" is required.'}),{status:400,headers:{"Content-Type":"application/json"}});const a=globalThis.__codeyam_editor_dev_server__;if(!a||!a.url||a.status!=="running")return new Response(JSON.stringify({error:`Dev server is not running. Start it with: codeyam editor dev-server '{"action":"start"}'`}),{status:503,headers:{"Content-Type":"application/json"}});const o=a.url,i=1e4,l={},c={};let p=!0;for(const f of r)try{const g=await fetch(`${o}${f}`,{signal:AbortSignal.timeout(i)}),y=g.ok;y||(p=!1),l[f]={status:g.status,ok:y}}catch(g){p=!1,l[f]={status:0,ok:!1,error:g.message}}for(const f of s)try{const g=await fetch(`${o}${f}`,{signal:AbortSignal.timeout(i)}),y=g.ok;y||(p=!1);let x=!1,b;try{const w=await g.text();JSON.parse(w),x=!0,b=w.length>200?w.slice(0,200)+"…":w}catch{}c[f]={status:g.status,ok:y,isJSON:x,preview:b}}catch(g){p=!1,c[f]={status:0,ok:!1,isJSON:!1,error:g.message}}const u=r.length+s.length,h=Object.values(l).filter(f=>f.ok).length+Object.values(c).filter(f=>f.ok).length,m=p?`All ${u} routes OK`:`${h}/${u} routes passed`;return new Response(JSON.stringify({ok:p,routes:l,apiRoutes:c,summary:m}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-verify-routes] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const kw=Object.freeze(Object.defineProperty({__proto__:null,action:Cw},Symbol.toStringTag,{value:"Module"}));async function _w(e,t){const r=Ne();if(!r)return{entityCalls:[],analysisCalls:[]};const s=U.join(r,".codeyam","llm-calls");try{await _e.access(s)}catch{return{entityCalls:[],analysisCalls:[]}}const a=[],o=[];try{const l=(await _e.readdir(s)).filter(b=>b.endsWith(".json")),c=`${e}_`,p=t?`${t}_`:null,u=[],h=[];for(const b of l)b.startsWith(c)||p&&b.startsWith(p)?u.push(b):h.push(b);const m=u.map(async b=>{try{const w=U.join(s,b),v=await _e.readFile(w,"utf-8");return JSON.parse(v)}catch{return null}}),f=h.map(async b=>{try{const w=U.join(s,b),v=await _e.readFile(w,"utf-8"),N=JSON.parse(v);return N.object_id===e||t&&N.object_id===t?N:null}catch{return null}}),[g,y]=await Promise.all([Promise.all(m),Promise.all(f)]),x=[...g,...y].filter(b=>b!==null);for(const b of x)b.object_id===e?a.push(b):t&&b.object_id===t&&o.push(b);a.sort((b,w)=>w.created_at-b.created_at),o.sort((b,w)=>w.created_at-b.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:a,analysisCalls:o}}async function Ew({params:e,request:t}){const{entitySha:r}=e;if(!r)return re({error:"Entity SHA is required"},{status:400});const a=new URL(t.url).searchParams.get("analysisId")||void 0,o=await _w(r,a);return re(o)}const Aw=Object.freeze(Object.defineProperty({__proto__:null,loader:Ew},Symbol.toStringTag,{value:"Module"}));function Pw(){try{const e=Ne()||process.cwd(),t=se.join(e,".codeyam","config.json");if(!ge.existsSync(t))return Response.json({projectTitle:null,projectDescription:null,defaultScreenSize:null,screenSizes:null,appFormats:null});const r=JSON.parse(ge.readFileSync(t,"utf8"));return Response.json({projectTitle:r.projectTitle||null,projectDescription:r.projectDescription||null,defaultScreenSize:r.defaultScreenSize||null,screenSizes:r.screenSizes||null,appFormats:r.appFormats||null})}catch{return Response.json({projectTitle:null,projectDescription:null,defaultScreenSize:null,screenSizes:null,appFormats:null})}}async function jw({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ne()||process.cwd(),r=se.join(t,".codeyam","config.json");if(!ge.existsSync(r))return new Response(JSON.stringify({error:"No config.json found"}),{status:404,headers:{"Content-Type":"application/json"}});const s=await e.json(),a=JSON.parse(ge.readFileSync(r,"utf8"));return s.projectTitle!==void 0&&(a.projectTitle=s.projectTitle),s.projectDescription!==void 0&&(a.projectDescription=s.projectDescription),s.defaultScreenSize!==void 0&&(a.defaultScreenSize=s.defaultScreenSize),s.screenSizes!==void 0&&(a.screenSizes=s.screenSizes),s.appFormats!==void 0&&(a.appFormats=s.appFormats),ge.writeFileSync(r,JSON.stringify(a,null,2)),s.defaultScreenSize&&!s.skipBroadcast&&ci(s.defaultScreenSize),Nt.notifyChange("unknown"),new Response(JSON.stringify({success:!0,projectTitle:a.projectTitle||null,projectDescription:a.projectDescription||null,defaultScreenSize:a.defaultScreenSize||null,screenSizes:a.screenSizes||null,appFormats:a.appFormats||null}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Tw=Object.freeze(Object.defineProperty({__proto__:null,action:jw,loader:Pw},Symbol.toStringTag,{value:"Module"}));function hu(e){try{const t=U.join(e,"package.json"),r=JSON.parse(V.readFileSync(t,"utf8")),s={...r.dependencies,...r.devDependencies};return s.vitest?"vitest":s.jest?"jest":null}catch{return null}}function Mw(e,t){var i;const s=JSON.parse(t).testResults||[],a=[];for(const l of s)for(const c of l.assertionResults||[]){const p=c.ancestorTitles||[],u=c.title||c.fullName||"unknown",h=p.length>0?`${p.join(" > ")} > ${u}`:u;a.push({title:u,fullName:h,status:c.status==="passed"?"passed":c.status==="failed"?"failed":"skipped",duration:c.duration,failureMessages:(i=c.failureMessages)!=null&&i.length?c.failureMessages:void 0})}const o=a.some(l=>l.status==="failed");return{testFilePath:e,status:o?"failed":"passed",testCases:a}}function $w(e,t,r){var l;const a=JSON.parse(r).testResults||[],o=new Map;for(const c of a){const p=c.name||"",u=o.get(p);u?u.push(c):o.set(p,[c])}const i={};e.endsWith("/")||e+"";for(const c of t){const p=U.isAbsolute(c)?c:U.join(e,c),u=o.get(p);if(!u||u.length===0){i[c]={testFilePath:c,status:"error",testCases:[],errorMessage:`File not found in test output: ${c}`};continue}const h=[];for(const f of u)for(const g of f.assertionResults||[]){const y=g.ancestorTitles||[],x=g.title||g.fullName||"unknown",b=y.length>0?`${y.join(" > ")} > ${x}`:x;h.push({title:x,fullName:b,status:g.status==="passed"?"passed":g.status==="failed"?"failed":"skipped",duration:g.duration,failureMessages:(l=g.failureMessages)!=null&&l.length?g.failureMessages:void 0})}const m=h.some(f=>f.status==="failed");i[c]={testFilePath:c,status:m?"failed":"passed",testCases:h}}return i}function Iw(e,t,r){return e==="vitest"?{cmd:"node",args:["./node_modules/.bin/vitest","run","--reporter=json","--outputFile",t,...r]}:{cmd:"./node_modules/.bin/jest",args:["--json","--outputFile",t,...r]}}async function Rw(e,t){if(t.length===0)return{};const r=hu(e);if(!r){const c={};for(const p of t)c[p]={testFilePath:p,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};return c}const s=[],a={};for(const c of t){const p=U.isAbsolute(c)?c:U.join(e,c);V.existsSync(p)?s.push(c):a[c]={testFilePath:c,status:"error",testCases:[],errorMessage:"Test file not found"}}if(s.length===0)return a;const o=U.join(Hs.tmpdir(),`codeyam-test-result-${Date.now()}.json`),{cmd:i,args:l}=Iw(r,o,s);return new Promise(c=>{var m;const p=ft(i,l,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let u="";(m=p.stderr)==null||m.on("data",f=>{u+=f.toString()});const h=setTimeout(()=>{p.kill("SIGTERM");for(const f of s)a[f]={testFilePath:f,status:"error",testCases:[],errorMessage:"Test timed out after 60 seconds"};c(a)},6e4);p.on("close",()=>{clearTimeout(h);try{const f=V.readFileSync(o,"utf8");V.unlinkSync(o);const g=$w(e,s,f);Object.assign(a,g)}catch{for(const f of s)a[f]={testFilePath:f,status:"error",testCases:[],errorMessage:u.trim().slice(0,500)||"Test runner failed to produce output"}}c(a)}),p.on("error",f=>{clearTimeout(h);for(const g of s)a[g]={testFilePath:g,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${f.message}`};c(a)})})}async function Dw(e,t){const r=hu(e);if(!r)return{testFilePath:t,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};const s=U.isAbsolute(t)?t:U.join(e,t);if(!V.existsSync(s))return{testFilePath:t,status:"error",testCases:[],errorMessage:"Test file not found"};const a=U.join(Hs.tmpdir(),`codeyam-test-result-${Date.now()}.json`);return new Promise(o=>{var h;let i,l;r==="vitest"?(l="node",i=["./node_modules/.bin/vitest","run","--reporter=json","--outputFile",a,t]):(l="./node_modules/.bin/jest",i=["--json","--outputFile",a,"--testPathPatterns",t]);const c=ft(l,i,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let p="";(h=c.stderr)==null||h.on("data",m=>{p+=m.toString()});const u=setTimeout(()=>{c.kill("SIGTERM"),o({testFilePath:t,status:"error",testCases:[],errorMessage:"Test timed out after 30 seconds"})},3e4);c.on("close",()=>{clearTimeout(u);try{const m=V.readFileSync(a,"utf8");V.unlinkSync(a),o(Mw(t,m))}catch{o({testFilePath:t,status:"error",testCases:[],errorMessage:p.trim().slice(0,500)||"Test runner failed to produce output"})}}),c.on("error",m=>{clearTimeout(u),o({testFilePath:t,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${m.message}`})})})}function Ol(){return{version:1,results:{}}}function mu(e,t,r){return e.sourceHash!==t||e.testHash!==r}function Fw(e,t,r){return{testFilePath:e.testFilePath,status:e.status,testCases:e.testCases,...e.errorMessage?{errorMessage:e.errorMessage}:{},sourceHash:t,testHash:r,timestamp:new Date().toISOString()}}function Ow(e,t){return{version:1,results:{...e.results,...t}}}const fu="test-results.json";function gi(e){const t=U.join(e,".codeyam",fu);try{const r=V.readFileSync(t,"utf8"),s=JSON.parse(r);return s&&s.version===1&&s.results?s:Ol()}catch{return Ol()}}function Lw(e,t){const r=U.join(e,".codeyam");V.mkdirSync(r,{recursive:!0});const s=U.join(r,fu);V.writeFileSync(s,JSON.stringify(t,null,2)+`
445
+ `)}function Ll(e){try{const t=V.readFileSync(e);return jo.createHash("sha256").update(t).digest("hex")}catch{return""}}function yi(e,t){const r={};for(const s of t){const a=U.join(e,s.filePath),o=U.join(e,s.testFile);r[s.testFile]={sourceHash:Ll(a),testHash:Ll(o)}}return r}function gu(e,t,r){const s=gi(e),a=yi(e,r),o={};for(const[l,c]of Object.entries(t)){const p=a[l];p&&(o[l]=Fw(c,p.sourceHash,p.testHash))}const i=Ow(s,o);Lw(e,i)}async function Bw({request:e}){const r=new URL(e.url).searchParams.get("testFile");if(!r)return new Response(JSON.stringify({status:"error",errorMessage:"Missing testFile parameter",testCases:[],testFilePath:""}),{headers:{"Content-Type":"application/json"}});const s=Ne()||process.cwd();try{const a=await Dw(s,r);try{const o=U.join(s,".codeyam","glossary.json"),i=V.readFileSync(o,"utf8"),c=la(JSON.parse(i)).find(p=>p.testFile===r);c&&gu(s,{[r]:a},[{filePath:c.filePath,testFile:r}])}catch{}return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}catch(a){const o=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({testFilePath:r,status:"error",testCases:[],errorMessage:o}),{status:500,headers:{"Content-Type":"application/json"}})}}const zw=Object.freeze(Object.defineProperty({__proto__:null,loader:Bw},Symbol.toStringTag,{value:"Module"}));function Bl(e,t){var r,s;try{return((s=(r=Ie(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:r.toString())==null?void 0:s.trim())??null}catch(a){return console.error(`Failed to get commit SHA for ${e}:`,a),""}}function Yw(e,t,r,s){const a=er.createHash("sha256");return a.update(`${e}:${t}:${r}:${s}`),a.digest("hex").substring(0,16)}function yu(){const e=Ne();if(!e)throw new Error("No project root found");const t=se.join(e,".codeyam","cache","branch-entity-diff");return ge.existsSync(t)||ge.mkdirSync(t,{recursive:!0}),t}function Ww(e){try{const t=yu(),r=se.join(t,`${e}.json`);if(!ge.existsSync(r))return null;const s=ge.readFileSync(r,"utf8");return JSON.parse(s)}catch(t){return console.error("Failed to read cache:",t),null}}function Uw(e,t){try{const r=yu(),s=se.join(r,`${e}.json`);ge.writeFileSync(s,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function Jw(e,t,r){const s=Rs(t,e),a=Rs(r,e),o=new Map(s.map(u=>[u.name,u])),i=new Map(a.map(u=>[u.name,u])),l=[],c=[],p=[];for(const[u,h]of i){const m=o.get(u);m?m.sha!==h.sha&&c.push({name:u,baseSha:m.sha,compareSha:h.sha,entityType:h.entityType}):l.push(h)}for(const[u,h]of o)i.has(u)||p.push(h);return{filePath:e,newEntities:l,modifiedEntities:c,deletedEntities:p}}function Hw(e,t){const r=Ne();if(!r)throw new Error("No project root found");const s=Bl(e,r),a=Bl(t,r);if(!s||!a)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=Yw(e,t,s,a),i=Ww(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const l=Qd(e,t),c=[];for(const u of l)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const h=Cs(u.path,e,t),m=Rs(h.oldContent,u.path);c.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:m})}else if(u.status==="added"){const h=Cs(u.path,e,t),m=Rs(h.newContent,u.path);c.push({filePath:u.path,newEntities:m,modifiedEntities:[],deletedEntities:[]})}else{const h=Cs(u.path,e,t),m=Jw(u.path,h.oldContent,h.newContent);(m.newEntities.length>0||m.modifiedEntities.length>0||m.deletedEntities.length>0)&&c.push(m)}const p={baseBranch:e,compareBranch:t,baseCommitSha:s,compareCommitSha:a,fileComparisons:c,cacheKey:o,computedAt:new Date().toISOString()};return Uw(o,p),p}function Vw({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),s=t.searchParams.get("compare");if(!r||!s)return re({error:"Missing required parameters: base and compare"},{status:400});const a=Hw(r,s);return re(a)}catch(t){return console.error("Failed to compute branch entity diff:",t),re({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const Gw=Object.freeze(Object.defineProperty({__proto__:null,loader:Vw},Symbol.toStringTag,{value:"Module"}));async function Kw({request:e}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:s,projectId:a,viewportWidth:o=1440}=t;if(!r||!s||!a)return re({error:"Missing required fields: serverUrl, scenarioId, and projectId"},{status:400});console.log(`[Capture] URL to capture: ${r}`),console.log(`[Capture] Scenario ID from request: ${s}`);const i=Ne();if(!i)return re({error:"Project root not found"},{status:500});const l=U.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),c=JSON.stringify({url:r,scenarioId:s,projectId:a,projectRoot:i,viewportWidth:o}),p=await new Promise(m=>{const f=U.join(i,".codeyam","db.sqlite3"),g=ft("npx",["tsx",l,c],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let y="",x="";g.stdout.on("data",b=>{const w=b.toString();y+=w;const v=w.trim().split(`
446
+ `);for(const N of v)N.includes("[Capture]")&&console.log(N)}),g.stderr.on("data",b=>{const w=b.toString();x+=w,console.error("[Capture:Error]",w.trim())}),g.on("close",b=>{m(b===0?{success:!0,output:y}:{success:!1,output:y,error:x||`Process exited with code ${b}`})}),g.on("error",b=>{console.error("[Capture] Failed to spawn child process:",b),m({success:!1,output:"",error:b.message})})});if(!p.success)return re({error:"Failed to capture screenshot",details:p.error},{status:500});const u=p.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return re({error:"Failed to parse capture result"},{status:500});const h=JSON.parse(u[1]);return re(h)}catch(t){return console.error("[Capture] Error:",t),re({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const qw=Object.freeze(Object.defineProperty({__proto__:null,action:Kw},Symbol.toStringTag,{value:"Module"}));function Qw(e){const t=e||process.cwd();try{return Ie("git rev-parse HEAD",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch(r){throw new Error(`Failed to get HEAD SHA: ${r}`)}}function Zw(e){const t=e||process.cwd();try{return Ie("git rev-parse --git-dir",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),!0}catch{return!1}}function Xw(e){if(Zw(e))return!1;Ie("git init",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]});try{Ie('git config user.email "codeyam@local"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Ie('git config user.name "CodeYam"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}catch{}return!0}function ev(e){Ie("git add -A",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}function tv(e,t){return Ie(`git commit -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Qw(e)}function nv(e){return/^[0-9a-f]{7,40}$/i.test(e)}function rv(e,t){try{return Ie(`git cat-file -t ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"}),!0}catch{return!1}}function sv(e,t){try{return{stashed:!Ie(`git stash push -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:"pipe"}).includes("No local changes")}}catch{return{stashed:!1}}}function av(e,t){Ie(`git checkout ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"})}async function ov({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{commitSha:r}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({success:!1,error:"commitSha is required"}),{status:400,headers:{"Content-Type":"application/json"}});if(!nv(r))return new Response(JSON.stringify({success:!1,error:"Invalid commit SHA format"}),{status:400,headers:{"Content-Type":"application/json"}});const s=process.env.CODEYAM_ROOT_PATH||process.cwd();if(console.log(`[editor-load-commit] Loading commit ${r} in ${s}`),!rv(s,r))return new Response(JSON.stringify({success:!1,error:`Commit ${r} not found`}),{status:400,headers:{"Content-Type":"application/json"}});const{stashed:a}=sv(s,"codeyam: auto-stash before time travel");a&&console.log("[editor-load-commit] Stashed uncommitted changes");try{av(s,r),console.log(`[editor-load-commit] Checked out ${r}`)}catch(o){const i=o instanceof Error?o.message:String(o);return console.error("[editor-load-commit] Checkout failed:",i),new Response(JSON.stringify({success:!1,error:`Checkout failed: ${i}`}),{status:500,headers:{"Content-Type":"application/json"}})}try{const i=await(await fetch(`http://localhost:${process.env.CODEYAM_PORT||"3111"}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})})).json();console.log("[editor-load-commit] Dev server restart:",i)}catch(o){console.warn("[editor-load-commit] Dev server restart warning:",o)}return new Response(JSON.stringify({success:!0,stashed:a}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-load-commit] Error:",t),new Response(JSON.stringify({success:!1,error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const iv=Object.freeze(Object.defineProperty({__proto__:null,action:ov},Symbol.toStringTag,{value:"Module"}));async function lv(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await Je();const s=await Vt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const a=Pe(),o=s.entitySha,i=await a.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let l={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?l=JSON.parse(i.metadata):l=i.metadata),l.defaultWidth=t,await a.updateTable("entities").set({metadata:JSON.stringify(l)}).where("sha","=",o).execute(),console.log(`[recapture] Updated defaultWidth for entity ${o} to ${t}`),!s.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=s.scenarios)==null?void 0:f.length)||0} scenarios`),await nr(e,g=>{if(g){if(g.readyToBeCaptured=!0,g.scenarios)for(const y of g.scenarios)delete y.finishedAt,delete y.startedAt,delete y.screenshotStartedAt,delete y.screenshotFinishedAt,delete y.interactiveStartedAt,delete y.interactiveFinishedAt,delete y.error,delete y.errorStack;delete g.finishedAt}}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const c=Ne();if(!c)throw new Error("Project root not found");const p=U.join(c,".codeyam","config.json"),u=JSON.parse(V.readFileSync(p,"utf8")),{projectSlug:h}=u;if(!h)throw new Error("Project slug not found in config");const{jobId:m}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:h,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${m}`),{jobId:m}}async function cv(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await Je();const s=await Vt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const a=(u=s.scenarios)==null?void 0:u.find(h=>h.id===t);if(!a)throw console.log(`[recapture] Scenario ${t} not found in analysis ${e}`),new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${a.name}`),await nr(e,h=>{if(h&&(h.readyToBeCaptured=!0,delete h.finishedAt,h.scenarios)){const m=h.scenarios.find(f=>f.name===a.name);m&&(delete m.finishedAt,delete m.startedAt,delete m.error,delete m.errorStack,delete m.screenshotStartedAt,delete m.screenshotFinishedAt,delete m.interactiveStartedAt,delete m.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${a.name} for recapture`);const o=Ne();if(!o)throw new Error("Project root not found");const i=U.join(o,".codeyam","config.json"),l=JSON.parse(V.readFileSync(i,"utf8")),{projectSlug:c}=l;if(!c)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:c,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${p}`),{jobId:p}}async function dv({request:e,context:t}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Gt()),!r)return re({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a||!o)return re({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${a}, scenario ${o}`);const i=await cv(a,o,r);return console.log("[API] Scenario recapture queued",i),re({success:!0,message:"Scenario recapture queued",...i})}catch(s){return console.log("[API] Error during scenario recapture:",s),re({error:"Failed to recapture scenario",details:s instanceof Error?s.message:String(s)},{status:500})}}const uv=Object.freeze(Object.defineProperty({__proto__:null,action:dv},Symbol.toStringTag,{value:"Module"}));async function vo(e){try{return await Ee.stat(e),!0}catch{return!1}}async function xu(){try{const e=Ne();if(!e)return null;const t=se.join(e,".codeyam","config.json");return JSON.parse(await Ee.readFile(t,"utf-8")).projectSlug||null}catch{return null}}function pv(){return`/private/tmp/claude-501/-${(Ne()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const ks="/tmp/claude-rule-markers",hv=/<system-reminder>[\s\S]*?<\/system-reminder>/g,zl=2e3;function mv(e,t){if(e==="Read"||e==="Write"||e==="Edit")return String(t.file_path||"");if(e==="Glob")return String(t.pattern||"");if(e==="Grep"){const r=String(t.pattern||""),s=String(t.path||"");return s?`"${r}" in ${s}`:`"${r}"`}if(e==="Bash"){const r=String(t.command||"");return r.length>100?r.slice(0,100)+"...":r}if(e==="Task")return String(t.description||String(t.prompt||"").slice(0,80));for(const r of Object.values(t))if(typeof r=="string"&&r)return r.slice(0,80);return""}const fv=["no,","no ","that's not","thats not","that is not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","dont do","shouldn't","should not","try again","let me clarify","to clarify","that broke","that failed","error","bug"];function gv(e){const t=[],r=new Set;for(const s of e)if(!(s.type!=="tool_call"||!s.name||!s.input)){if(s.name==="Write"||s.name==="Edit"){const a=String(s.input.file_path||"");if(a.includes(".claude/rules/")){const o=a.replace(/^.*?(\.claude\/rules\/)/,"$1"),i=`${s.name}:${o}`;r.has(i)||(r.add(i),s.name==="Write"?t.push({action:"created",filePath:o,content:String(s.input.content||"")}):t.push({action:"modified",filePath:o,oldString:String(s.input.old_string||""),newString:String(s.input.new_string||"")}))}}else if(s.name==="Bash"){const a=String(s.input.command||"");if(a.includes("codeyam memory touch")){const o=`touch:${a}`;r.has(o)||(r.add(o),t.push({action:"touched",filePath:a}))}}}return t}function yv(e){if(!e)return;const t="### Session transcript",r=e.indexOf(t);if(r===-1)return;let s=e.slice(r+t.length).trim();const a=s.indexOf(`
447
+ ###`);return a!==-1&&(s=s.slice(0,a).trim()),s||void 0}function xv(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const s of fv)if(r.includes(s))return!0}return!1}function bv(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type==="assistant"){const a=(s.message||{}).model;if(typeof a=="string"&&a)return a}}catch{continue}}}function wv(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type!=="result")continue;const a={subtype:String(s.subtype||"unknown"),is_error:!!s.is_error};if(typeof s.duration_ms=="number"&&(a.duration_ms=s.duration_ms),typeof s.duration_api_ms=="number"&&(a.duration_api_ms=s.duration_api_ms),typeof s.num_turns=="number"&&(a.num_turns=s.num_turns),typeof s.total_cost_usd=="number"&&(a.total_cost_usd=s.total_cost_usd),s.usage&&typeof s.usage=="object"){a.usage={};for(const o of["input_tokens","output_tokens","cache_read_input_tokens","cache_creation_input_tokens"])typeof s.usage[o]=="number"&&(a.usage[o]=s.usage[o])}return Array.isArray(s.errors)&&s.errors.length>0&&(a.errors=s.errors.map(String)),a}catch{continue}}}function vv(e){const t=[],r={};for(const s of e){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}const i=o.type;if(i==="progress"||i==="system"||i==="result")continue;const c=(o.message||{}).content,p=o.timestamp||"";if(i==="user"){if(typeof c=="string")t.push({type:"user_prompt",text:c,timestamp:p,agent_id:String(o.agentId||o.session_id||"unknown"),slug:String(o.slug||"")});else if(Array.isArray(c)){for(const u of c)if(typeof u=="object"&&u!==null&&u.type==="tool_result"){const h=u,m=String(h.tool_use_id||"");let f=h.content;const g=!!h.is_error;typeof f=="string"&&(f=f.replace(hv,"").trim()),t.push({type:"tool_result",tool_use_id:m,tool_name:r[m]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:g,timestamp:p})}}}else if(i==="assistant"&&Array.isArray(c))for(const u of c){if(typeof u!="object"||u===null)continue;const h=u;if(h.type==="text"){const m=String(h.text||"").trim();m&&t.push({type:"assistant_text",text:m,timestamp:p})}else if(h.type==="tool_use"){const m=String(h.id||""),f=String(h.name||"unknown"),g=h.input||{};r[m]=f,t.push({type:"tool_call",tool_use_id:m,name:f,input:g,timestamp:p})}}}return t}function Nv(e,t){return e.type==="user_prompt"||e.type==="assistant_text"?(e.text||"").toLowerCase().includes(t):e.type==="tool_call"?(e.name||"").toLowerCase().includes(t)?!0:JSON.stringify(e.input||{}).toLowerCase().includes(t):e.type==="tool_result"?(e.content||"").toLowerCase().includes(t):!1}const Yn=20;async function Yl(e){const r=(await Ee.readFile(e.filePath,"utf-8")).split(`
448
+ `),s=vv(r);if(s.length===0)return null;const a=s.find(v=>v.type==="user_prompt"),o=e.stem,i=bv(r);let l=(a==null?void 0:a.slug)||"",c=(a==null?void 0:a.timestamp)||"";c||(c=new Date(e.mtime).toISOString());let p;if(e.filePath.endsWith(".log")){e.stem.endsWith("-stale")?l=l||"rule-reflection/stale":e.stem.endsWith("-conversation")?l=l||"rule-reflection/conversation":e.stem.endsWith("-interruption")?l=l||"rule-reflection/interruption":l=l||"rule-reflection";const v=e.filePath.replace(/\.log$/,".context");if(await vo(v))try{p=await Ee.readFile(v,"utf-8")}catch{}}const u=s.filter(v=>v.type==="tool_call").length,h=s.filter(v=>v.type==="assistant_text").length,m=s.filter(v=>v.type==="tool_result"&&v.is_error&&v.content!=="Sibling tool call errored"),f=m.length,g=m.map(v=>{const N=v.content||"Unknown error";return N.length>150?N.slice(0,150)+"...":N});for(const v of s)v.type==="tool_call"&&v.name&&v.input&&(v.summary=mv(v.name,v.input));for(const v of s)v.type==="tool_result"&&v.content&&v.content.length>zl&&(v.truncated=!0,v.fullLength=v.content.length,v.content=v.content.slice(0,zl));const y=gv(s),x=xv(s),b=yv(p),w=wv(r);return{id:o,slug:l,timestamp:c,model:i,sourceFile:e.filePath,stats:{toolCalls:u,textBlocks:h,errors:f,errorMessages:g},entries:s,context:p,conversationSnippet:b,ruleChanges:y,hasConfusion:x,sessionResult:w}}async function Sv(){const e=pv(),t=ks,r=[];if(await vo(e)){const i=await Ee.readdir(e);for(const l of i)if(l.endsWith(".output")){const c=se.join(e,l),p=await Ee.stat(c);r.push({filePath:c,stem:l.replace(".output",""),mtime:p.mtimeMs})}}const s=new Set,a=await xu(),o=[];a&&o.push(se.join(t,a)),o.push(t);for(const i of o){if(!await vo(i))continue;const l=await Ee.readdir(i);for(const c of l){if(!c.endsWith(".log")||s.has(c))continue;s.add(c);const p=se.join(i,c),u=await Ee.stat(p);r.push({filePath:p,stem:c.replace(".log",""),mtime:u.mtimeMs})}}return r.sort((i,l)=>l.mtime-i.mtime),r}async function Cv({request:e}){var t;try{const r=new URL(e.url),s=((t=r.searchParams.get("search"))==null?void 0:t.toLowerCase())||"",a=Math.max(1,parseInt(r.searchParams.get("page")||"1",10)),o=await Sv();if(!s){const u=o.length,h=(a-1)*Yn,m=o.slice(h,h+Yn),f=[];for(const g of m){const y=await Yl(g);y&&f.push(y)}return Response.json({agents:f,total:u,page:a,pageSize:Yn})}const i=[];for(const u of o){const h=await Yl(u);if(!h)continue;(h.id.toLowerCase().includes(s)||h.slug.toLowerCase().includes(s)||h.entries.some(f=>Nv(f,s)))&&i.push(h)}const l=i.length,c=(a-1)*Yn,p=i.slice(c,c+Yn);return Response.json({agents:p,total:l,page:a,pageSize:Yn})}catch(r){return console.error("[api.agent-transcripts] Error:",r),Response.json({error:"Failed to load agent transcripts",details:r instanceof Error?r.message:String(r)},{status:500})}}const kv=Object.freeze(Object.defineProperty({__proto__:null,loader:Cv},Symbol.toStringTag,{value:"Module"})),bu="__codeyam_editor_dev_server__",Wl=30;function xi(){return globalThis[bu]??null}function wu(e){globalThis[bu]=e}function fs(e,t){const r=[se.join(e,".next","dev","lock"),se.join(e,"node_modules",".vite","deps","_lock")];for(const s of r)try{ge.existsSync(s)&&(ge.unlinkSync(s),console.log(`[editor-dev-server] Removed stale lock file: ${s}`))}catch(a){console.warn(`[editor-dev-server] Failed to remove lock file ${s}:`,a)}if(t)try{const s=Ie(`lsof -ti:${t}`,{encoding:"utf8"}).trim();if(s){const a=process.pid,o=s.split(`
449
+ `).filter(i=>i&&parseInt(i,10)!==a);if(o.length>0){for(const i of o)try{Ie(`kill ${i}`)}catch{}console.log(`[editor-dev-server] Killed orphaned process(es) on port ${t}: ${o.join(", ")}`)}}}catch{}}function _v({request:e}){const t=xi();return t?new Response(JSON.stringify({status:t.status,url:t.url,proxyUrl:Bd(),pid:t.pid,errorMessage:t.status==="error"?t.errorMessage:null}),{headers:{"Content-Type":"application/json"}}):new Response(JSON.stringify({status:"stopped",url:null,proxyUrl:null}),{headers:{"Content-Type":"application/json"}})}async function Ev({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{action:r}=t;return r==="start"?No():r==="stop"?Ul():r==="restart"?(Ul(),await new Promise(s=>setTimeout(s,1e3)),No()):new Response(JSON.stringify({error:'Invalid action. Use "start", "stop", or "restart".'}),{status:400,headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}function Av(){let t=se.dirname(new URL(import.meta.url).pathname);for(let s=0;s<5;s++){const a=se.dirname(t);if(se.basename(a)==="webserver"||se.basename(t)==="webserver"){t=se.basename(t)==="webserver"?t:a;break}t=a}const r=[se.join(t,"scripts","codeyam-preload.mjs"),se.join(t,"scripts","codeyam-preload.mjs")];for(const s of r)if(ge.existsSync(s))return s;return console.warn("[editor-dev-server] codeyam-preload.mjs not found, SSR fetch interception disabled"),null}function No(e=!1){var C,A;const t=xi();if(t&&t.status!=="stopped"&&t.status!=="error")return new Response(JSON.stringify({status:t.status,url:t.url,message:"Dev server is already running"}),{headers:{"Content-Type":"application/json"}});const r=Ne()||process.cwd(),s=parseInt(process.env.CODEYAM_PORT||"3111",10),{proxyPort:a,devServerPort:o}=Md(s),i=U0(r,o);if("error"in i)return new Response(JSON.stringify({error:i.error}),{status:400,headers:{"Content-Type":"application/json"}});const{command:l,args:c,env:p}=i;fs(r,o),fs(r,3e3),fs(r,3001),fs(r,5173),console.log(`[editor-dev-server] Starting: ${l} ${c.join(" ")} in ${r}`);const u=Av(),h=u?`--import ${u}`:"",{NODE_OPTIONS:m,PORT:f,CODEYAM_PORT:g,...y}=process.env,x={};try{const _=se.join(r,".codeyam","config.json"),E=JSON.parse(ge.readFileSync(_,"utf-8"));for(const R of E.environmentVariables||[])R.key&&R.value!==void 0&&(x[R.key]=R.value)}catch{}const b=ft(l,c,{cwd:r,stdio:["ignore","pipe","pipe"],env:{...y,...x,FORCE_COLOR:"1",BROWSER:"none",...h?{NODE_OPTIONS:h}:{},CODEYAM_PROXY_URL:`http://localhost:${a}`,...p},detached:!0});b.unref();const w=e?((t==null?void 0:t.retryCount)??0)+1:0,v={process:b,url:null,status:"starting",errorMessage:null,stderrBuffer:[],pid:b.pid||0,startedAt:Date.now(),retryCount:w};wu(v);const N=(_,E)=>{const R=_.toString(),D=R.split(`
450
+ `).filter(T=>T.trim());if(D.length>0&&(v.stderrBuffer.push(...D),v.stderrBuffer.length>Wl&&(v.stderrBuffer=v.stderrBuffer.slice(-Wl))),v.status==="starting"){const T=H0(R);T&&(v.url=T,v.status="running",console.log(`[editor-dev-server] URL detected: ${v.url}`),fo({port:a,targetUrl:v.url}).then(()=>kl()))}};(C=b.stdout)==null||C.on("data",_=>N(_)),(A=b.stderr)==null||A.on("data",_=>N(_));const S=parseInt(p.PORT||"0",10);return S>0&&(async()=>{if(await new Promise(E=>setTimeout(E,1e4)),v.status!=="starting")return;console.log(`[editor-dev-server] Stdout detection timed out, polling port ${S}...`);const _=await G0(S,{intervalMs:2e3,maxAttempts:15});_&&v.status==="starting"&&(v.url=_,v.status="running",console.log(`[editor-dev-server] URL detected via polling: ${v.url}`),fo({port:a,targetUrl:v.url}).then(()=>kl()))})(),b.on("exit",_=>{console.log(`[editor-dev-server] Process exited with code ${_}`);const E=Date.now()-v.startedAt,R=v.status==="running",D=K0({exitCode:_??null,uptime:E,retryCount:v.retryCount,wasRunning:R});if(D.action==="retry")console.log(`[editor-dev-server] Quick failure (${E}ms), auto-retrying...`),v.status="stopped",No(!0);else if(D.action==="error"){v.status="error";const T=v.stderrBuffer.length>0?v.stderrBuffer.join(`
451
+ `):"",$=R?`Dev server exited with code ${_}`:`Dev server exited (code ${_}) before it started serving`;v.errorMessage=T?`${$}
452
+
453
+ ${T}`:$,console.error(`[editor-dev-server] Server failed: ${v.errorMessage}`)}else v.status="stopped"}),b.on("error",_=>{console.error("[editor-dev-server] Process error:",_),v.status="error",v.errorMessage=_.message}),new Response(JSON.stringify({status:"starting",pid:b.pid,message:`Starting ${l} ${c.join(" ")}`}),{headers:{"Content-Type":"application/json"}})}function Ul(){const e=xi();if(!e||e.status==="stopped")return new Response(JSON.stringify({status:"stopped",message:"No server to stop"}),{headers:{"Content-Type":"application/json"}});Ud();try{e.process.pid&&process.kill(-e.process.pid,"SIGTERM")}catch{try{e.process.kill("SIGTERM")}catch{}}return e.status="stopped",wu(null),new Response(JSON.stringify({status:"stopped",message:"Dev server stopped"}),{headers:{"Content-Type":"application/json"}})}const Pv=Object.freeze(Object.defineProperty({__proto__:null,action:Ev,loader:_v},Symbol.toStringTag,{value:"Module"}));async function jv({params:e,request:t}){const{projectSlug:r}=e;if(!r)return new Response("Project slug is required",{status:400});if(t.method!=="DELETE")return new Response("Method not allowed",{status:405});const s=Lr(r);try{return await Nr(s,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(a){console.error("[api.logs] Error clearing log file:",a);const o=a instanceof Error?a.message:String(a);return new Response(`Error clearing log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function Tv({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=Lr(t);try{if(!vt(r))return new Response("No logs available yet. Analysis may not have started.",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});const s=await oo(r,"utf-8");return!s||s.trim().length===0?new Response("Log file is empty. Waiting for analysis to start...",{headers:{"Content-Type":"text/plain; charset=utf-8"}}):new Response(s,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(s){console.error("[api.logs] Error reading log file:",s);const a=s instanceof Error?s.message:String(s);return new Response(`Error reading log file: ${a}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const Mv=Object.freeze(Object.defineProperty({__proto__:null,action:jv,loader:Tv},Symbol.toStringTag,{value:"Module"}));function $v({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return Response.json({error:"Missing path parameter"},{status:400});const s=Ne()||process.cwd(),a=U.resolve(s,r);if(!a.startsWith(s+U.sep)&&a!==s)return Response.json({error:"Path outside project root"},{status:403});const o=Zd(r,s);return Response.json(o)}const Iv=Object.freeze(Object.defineProperty({__proto__:null,loader:$v},Symbol.toStringTag,{value:"Module"}));async function Rv(){const e=await Ye();if(!e)return Response.json({error:"No project configured"},{status:400});const{project:t}=await De(e),r=Pe(),s=process.env.CODEYAM_PORT||"3111",a=Ne()||process.cwd(),o=await r.selectFrom("editor_scenarios").select(["id","name","component_name","component_path","url","type","screenshot_path","page_file_path","display_name"]).where("project_id","=",t.id).orderBy("created_at","asc").execute(),i=Ct(o,p=>`${p.name}::${p.url||"/"}`);let l={};try{const p=i.map(h=>({componentName:h.component_name||null,componentPath:h.component_path||null,pageFilePath:h.page_file_path??null,url:h.url??null,displayName:h.display_name??null}));l=(await ir({projectRoot:a,scenarioInputs:p})).entityChangeStatus}catch{}const c=i.map(p=>{const u=p,h=Kt({componentName:p.component_name,pageFilePath:u.page_file_path,url:u.url}),m=h?l[h]:void 0;return{id:p.id,name:p.name,componentName:p.component_name||null,type:p.type||null,changeStatus:(m==null?void 0:m.status)||null,screenshotPath:p.screenshot_path||null,link:`http://localhost:${s}/editor?scenario=${p.id}&ref=link`}});return Response.json({scenarios:c})}const Dv=Object.freeze(Object.defineProperty({__proto__:null,loader:Rv},Symbol.toStringTag,{value:"Module"}));async function Fv(e,t){var o,i,l,c,p,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await Je();const r=await Vt({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const s=(o=r.scenarios)==null?void 0:o.find(h=>h.id===t);if(!s)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${s.name}`);const a={returnValue:{status:"success",data:((c=(l=(i=s.metadata)==null?void 0:i.data)==null?void 0:l.argumentsData)==null?void 0:c[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(p=s.metadata)==null?void 0:p.data)==null?void 0:u.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),a}async function Ov({request:e}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),s=t.get("scenarioId");if(!r||!s)return re({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${s}`);const a=await Fv(r,s);return console.log("[API] Function execution completed successfully"),re({success:!0,result:a})}catch(t){return console.log("[API] Error during function execution:",t),re({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const Lv=Object.freeze(Object.defineProperty({__proto__:null,action:Ov},Symbol.toStringTag,{value:"Module"}));function Bv({request:e}){return re({status:"ok"})}async function zv({request:e,context:t}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Gt()),!r)return console.error("[Interactive Mode API] Queue not initialized"),re({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("action"),o=s.get("analysisId"),i=s.get("scenarioId");if(!a||!o)return re({error:"Missing required fields: action and analysisId"},{status:400});if(a!=="start"&&a!=="stop")return re({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await Ye();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return re({error:"Project not initialized"},{status:500});if(a==="start"){const c=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:l});return re({success:!0,action:"start",message:"Interactive mode starting...",jobId:c})}else{const c=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:l});return re({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:c})}}catch(s){console.error("[Interactive Mode API] Error:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Interactive Mode API] Error stack:",o),re({error:"Failed to control interactive mode",details:a},{status:500})}}const Yv=Object.freeze(Object.defineProperty({__proto__:null,action:zv,loader:Bv},Symbol.toStringTag,{value:"Module"}));async function Wv({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,screenshotPaths:s}=t;if(!r)return Response.json({error:"Missing required field: scenarioId"},{status:400});if(console.log(`[API] Deleting scenario ${r}`),s&&s.length>0){const a=Ne();if(a)for(const o of s){const i=se.join(a,".codeyam","captures","screenshots",o);try{await Ee.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(l){console.log(`[API] Could not delete screenshot ${i}:`,l instanceof Error?l.message:l)}}}await Xm({ids:[r]});try{await Pe().deleteFrom("editor_scenarios").where("id","=",r).execute()}catch{}try{const a=Ne()||process.cwd();Uy(a,r)}catch{}return console.log(`[API] Scenario ${r} deleted successfully`),Response.json({success:!0,message:"Scenario deleted successfully"})}catch(t){return console.error("[API] Error deleting scenario:",t),Response.json({error:"Failed to delete scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const Uv=Object.freeze(Object.defineProperty({__proto__:null,action:Wv},Symbol.toStringTag,{value:"Module"}));class Jv extends Fr{emitFileSynced(t,r){this.emit("event",{type:"file-synced",fileName:t,filePath:r,timestamp:Date.now()})}emitError(t,r){this.emit("event",{type:"sync-error",fileName:t,filePath:r,timestamp:Date.now()})}emitRefreshPreview(){this.emit("event",{type:"refresh-preview",timestamp:Date.now()})}}const So="__codeyam_dev_mode_event_emitter__";if(!globalThis[So]){const e=new Jv;e.setMaxListeners(20),globalThis[So]=e}const Jl=globalThis[So];function Hv({request:e}){const t=new ReadableStream({start(r){const s=new TextEncoder;r.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
454
+
455
+ `));let a=!1;const o=()=>{if(!a){a=!0,Jl.off("event",i),clearInterval(l);try{r.close()}catch{}}},i=c=>{try{r.enqueue(s.encode(`data: ${JSON.stringify(c)}
456
+
457
+ `))}catch{o()}};Jl.on("event",i);const l=setInterval(()=>{try{r.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
458
+
459
+ `))}catch{o()}},3e4);e.signal.addEventListener("abort",o)}});return new Response(t,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const Vv=Object.freeze(Object.defineProperty({__proto__:null,loader:Hv},Symbol.toStringTag,{value:"Module"})),$r="/tmp/codeyam",Co=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",vu=500,Gv=vu*1024*1024;function wn(e,t){try{return Ie(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function _s(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Nu(e){return wn("config user.email",e)}function Kv(e){const t=U.join(e,".codeyam","debug-report.md");if(!V.existsSync(t))return null;try{return V.readFileSync(t,"utf8")}catch{return null}}function qv(e,t=20){const r=U.join($r,"local-dev",e,"codeyam","log.txt");if(!V.existsSync(r))return[];try{return V.readFileSync(r,"utf8").split(`
460
+ `).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function Qv(e){try{const t=await fetch(`${Co}/api/reports/check-base`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseSha:e})});if(!t.ok)return!1;const{hasBase:r}=await t.json();return r}catch{return!1}}function Zv(e,t){try{Ie(`git archive HEAD | gzip > "${t}"`,{cwd:e,stdio:"pipe",shell:"/bin/bash"})}catch(r){throw new Error(`Failed to create base archive: ${r.message}`)}}function Xv(e){const{projectRoot:t,projectSlug:r,outputPath:s,metadata:a,screenshot:o,onProgress:i}=e,l=i||(()=>{}),c=Date.now(),p=U.join($r,`delta-staging-${c}`),u=U.join(p,"delta");V.mkdirSync(u,{recursive:!0});try{const h=wn("diff --binary HEAD",t)||"";V.writeFileSync(U.join(u,"tracked.patch"),h?h+`
461
+ `:"");const m=wn("ls-files --others --exclude-standard",t);if(m){const x=U.join(u,"untracked");V.mkdirSync(x,{recursive:!0});for(const b of m.split(`
462
+ `).filter(Boolean)){const w=U.join(t,b),v=U.join(x,b);if(V.existsSync(w)){const N=U.dirname(v);V.mkdirSync(N,{recursive:!0}),V.statSync(w).isFile()&&V.copyFileSync(w,v)}}}const f=U.join(t,".codeyam");if(V.existsSync(f)){const x=U.join(u,"codeyam");V.cpSync(f,x,{recursive:!0})}V.writeFileSync(U.join(u,"meta.json"),JSON.stringify(a,null,2));const g=U.join($r,"local-dev",r,"codeyam","log.txt");V.existsSync(g)?V.copyFileSync(g,U.join(u,"codeyam-log.txt")):V.writeFileSync(U.join(u,"codeyam-log.txt"),`# Log file not found
463
+ `);const y=U.join(t,".codeyam","debug-report.md");V.existsSync(y)&&(V.copyFileSync(y,U.join(u,"debug-report.md")),l("Debug report included")),o&&o.length>0&&(V.writeFileSync(U.join(u,"screenshot.jpg"),o),l(`Screenshot included (${_s(o.length)})`));try{Ie(`tar -czf "${s}" -C "${p}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{V.rmSync(p,{recursive:!0,force:!0})}}async function eN(e){const{projectRoot:t,projectSlug:r,feedback:s,screenshot:a,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const l=wn("rev-parse HEAD",t);if(!l)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const c=wn("rev-parse --abbrev-ref HEAD",t)||"unknown",p=wn("status --porcelain",t),u=wn("remote get-url origin",t),h=p!==null&&p.length>0,m=fd(r),f=Kv(t);let g=s;f&&(g={...s||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /codeyam-diagnose workflow"));const y={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:l,branch:c,isDirty:h,remoteUrl:u},versions:{cli:m.cliVersion,webserver:m.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:g},x=Date.now(),b=U.join($r,`base-${l}-${x}.tar.gz`),w=U.join($r,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const v=await Qv(l);let N=null;v?i("Server already has base, skipping..."):(i("Generating base archive..."),Zv(t,b),N=V.statSync(b).size,i(`Base archive: ${_s(N)}`)),i("Generating delta archive..."),Xv({projectRoot:t,projectSlug:r,outputPath:w,metadata:y,screenshot:a,onProgress:o});const C=V.statSync(w).size;i(`Delta archive: ${_s(C)}`);const A=(N||0)+C;if(A>Gv)throw V.existsSync(b)&&V.unlinkSync(b),V.unlinkSync(w),new Error(`Bundle too large: ${_s(A)} (max: ${vu} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:v?null:b,deltaPath:w,metadata:y,baseSha:l,baseSize:N,deltaSize:C}}async function tN(e){const{basePath:t,deltaPath:r,projectSlug:s,metadata:a,baseSha:o,deltaSize:i,onProgress:l}=e,c=l||(()=>{}),p=V.statSync(r),u=t?V.statSync(t):null,h=p.size+((u==null?void 0:u.size)||0);c("Requesting upload URLs...");const m=await fetch(`${Co}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:s,fileSizeBytes:h,baseSha:o,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:a.timestamp,git:a.git,versions:a.versions,system:a.system,feedback:a.feedback}})});if(!m.ok){const v=await m.json();throw new Error(v.error||`Server returned ${m.status}`)}const{reportId:f,deltaUploadUrl:g,baseUploadUrl:y}=await m.json(),x=[];if(t&&y){c("Uploading base...");const v=V.readFileSync(t);x.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:v}).then(N=>{if(!N.ok)throw new Error(`Base upload failed: ${N.status}`)}))}c("Uploading delta...");const b=V.readFileSync(r);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:b}).then(v=>{if(!v.ok)throw new Error(`Delta upload failed: ${v.status}`)})),await Promise.all(x),c("Confirming upload...");const w=await fetch(`${Co}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!w.ok){const v=await w.json();throw new Error(v.error||`Confirm failed: ${w.status}`)}return t&&V.existsSync(t)&&V.unlinkSync(t),V.unlinkSync(r),{bundleId:f}}async function nN({request:e}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),s=t.get("description"),a=t.get("email"),o=t.get("source"),i=t.get("entitySha"),l=t.get("scenarioId"),c=t.get("analysisId"),p=t.get("currentUrl"),u=t.get("entityName"),h=t.get("entityType"),m=t.get("scenarioName"),f=t.get("errorMessage"),g=t.get("screenshot");let y=s||void 0;!y&&u&&(m?y=`Issue on ${u} scenario "${m}"`:y=`Issue on ${u}`);let x;if(g&&g.size>0){const A=await g.arrayBuffer();x=Buffer.from(A),console.log(`[Bundle] Screenshot received: ${g.size} bytes`)}const b=Ne();if(!b)return re({error:"Project root not found"},{status:500});const w=await Ye();if(!w)return re({error:"Project slug not found"},{status:500});const v={issueType:r||"other",description:y,email:a||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:l||void 0,analysisId:c||void 0,currentUrl:p||void 0,recentActivity:qv(w,20),entityName:u||void 0,entityType:h||void 0,scenarioName:m||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${w}...`),console.log(`[Bundle] Context: ${v.source}, issue: ${v.issueType}`);const N=await eN({projectRoot:b,projectSlug:w,feedback:v,screenshot:x,onProgress:A=>{console.log(`[Bundle] ${A}`)}}),S=(N.baseSize||0)+N.deltaSize;console.log(`[Bundle] Archives created: delta=${N.deltaSize} bytes${N.basePath?`, base=${N.baseSize} bytes`:" (base reused)"}`);const C=await tN({basePath:N.basePath,deltaPath:N.deltaPath,projectSlug:w,metadata:N.metadata,baseSha:N.baseSha,deltaSize:N.deltaSize,onProgress:A=>{console.log(`[Bundle] ${A}`)}});return console.log(`[Bundle] Upload complete: ${C.bundleId}`),re({success:!0,reportId:C.bundleId,size:S})}catch(t){return console.error("[Bundle] Error:",t),re({error:t.message||"Failed to generate bundle"},{status:500})}}function rN(){const e=Ne(),t=e?Nu(e):null;return re({defaultEmail:t})}const sN=Object.freeze(Object.defineProperty({__proto__:null,action:nN,loader:rN},Symbol.toStringTag,{value:"Module"}));async function aN({request:e}){try{const r=new URL(e.url).searchParams.get("date"),s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=U.join(s,".codeyam","journal","index.json");let o={entries:[]};try{const l=await _e.readFile(a,"utf8");o=JSON.parse(l)}catch{}let i=o.entries;return r&&(i=i.filter(l=>l.date===r)),new Response(JSON.stringify({entries:i}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const oN=Object.freeze(Object.defineProperty({__proto__:null,loader:aN},Symbol.toStringTag,{value:"Module"}));function Su(e){if(!V.existsSync(e))return nt.Unknown;try{const t=JSON.parse(V.readFileSync(e,"utf8")),r={...t.dependencies,...t.devDependencies};return r.next?nt.Next:r["@remix-run/node"]||r["@remix-run/react"]||r["react-router"]?nt.Remix:r["react-scripts"]?nt.CRA:r.expo?nt.Expo:r.vite?nt.Vite:nt.Unknown}catch{return nt.Unknown}}function iN(e,t){let r=e;const s=U.resolve(t);for(;;){const a=U.resolve(r);if(V.existsSync(U.join(a,"pnpm-lock.yaml")))return"pnpm";if(V.existsSync(U.join(a,"yarn.lock")))return"yarn";if(V.existsSync(U.join(a,"package-lock.json")))return"npm";if(a===s)break;const o=U.dirname(a);if(o===a)break;r=o}throw new Error(`Could not detect package manager in ${e} or any parent directory up to ${t}`)}function lN(e){const t=/cd\s+([^\s;&|]+)\s*(?:&&|;)/,r=e.match(t);return r?r[1]:null}function cN(e){const t=U.join(e,"package.json");if(!V.existsSync(t))return{isWebApp:!1};if(Su(t)===nt.Unknown)return{isWebApp:!1};try{const a=JSON.parse(V.readFileSync(t,"utf8")).scripts||{},o=["remix","react-router","next dev","vite","react-scripts","webpack-dev-server","parcel","expo"],l=Object.keys(a).filter(c=>["dev","start","serve","build"].some(p=>c.includes(p))).filter(c=>o.some(p=>a[c].includes(p)));if(l.length===0)return{isWebApp:!1};for(const c of l){const p=a[c],u=lN(p);if(u){const h=U.join(e,u);if(V.existsSync(h)&&V.statSync(h).isDirectory())return{isWebApp:!0,actualPath:h}}}return{isWebApp:!0}}catch{return{isWebApp:!1}}}function Cu(e,t=e,r=0,s=3){if(r>s)return[];const a=[],o=cN(t);if(o.isWebApp){const l=o.actualPath||t,c=U.relative(e,l);return a.push(c||"."),a}const i=["node_modules",".git",".next","dist","build",".cache","coverage",".codeyam"];try{const l=V.readdirSync(t,{withFileTypes:!0});for(const c of l)if(c.isDirectory()&&!i.includes(c.name)){const p=U.join(t,c.name);a.push(...Cu(e,p,r+1,s))}}catch{}return a}function dN(e){const t=Cu(e);return t.length===0?[]:t.map(s=>{const a=U.join(e,s),o=U.join(a,"package.json"),i=Su(o),l=iN(a,e);let c;if(i===nt.Remix||i===nt.Next||i===nt.Expo){const m=U.join(a,"app");V.existsSync(m)&&V.statSync(m).isDirectory()&&(c="app")}const p=uN(s,e),h=p?{command:"sh",args:["-c",`${l} run ${p} -- --port $PORT`]}:void 0;return{path:s,framework:i,packageManager:l,appDirectory:c,startCommand:h}})}function uN(e,t){const r=U.join(t,e),s=U.join(r,"package.json");if(!V.existsSync(s))return null;try{const o=JSON.parse(V.readFileSync(s,"utf8")).scripts||{},i=["dev","start","serve"];for(const l of i)if(o[l])return l;return null}catch{return null}}function pN(e,t){const r=new Set(e.map(a=>a.path)),s=[...e];for(const a of t)r.has(a.path)||s.push(a);return s}async function hN({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ne()||process.cwd(),r=se.join(t,".codeyam","config.json");let s=[];try{s=dN(t)}catch{}if(ge.existsSync(r)){const i=JSON.parse(ge.readFileSync(r,"utf8")),l=i.webapps||[];i.webapps=pN(s,l),s=i.webapps,ge.writeFileSync(r,JSON.stringify(i,null,2))}const a=await Ye();if(a)try{await Gn({projectSlug:a,metadataUpdate:{webapps:s}})}catch{}let o=!1;if(s.length>0)try{const i=process.env.CODEYAM_PORT||"3111",c=await(await fetch(`http://localhost:${i}/api/editor-dev-server`)).json();(c.status==="stopped"||c.status===void 0)&&(await fetch(`http://localhost:${i}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}),o=!0)}catch{}return new Response(JSON.stringify({success:!0,webapps:s,devServerStarted:o,message:`Detected ${s.length} webapp(s)`}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const mN=Object.freeze(Object.defineProperty({__proto__:null,action:hN},Symbol.toStringTag,{value:"Module"}));async function fN({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=Ne()||process.cwd();if(t.action==="clear"){w0(r);try{V.unlinkSync(U.join(r,".codeyam","claude-session-id.txt"))}catch{}return new Response(JSON.stringify({success:!0,message:"Editor state cleared"}),{headers:{"Content-Type":"application/json"}})}return new Response(JSON.stringify({error:"Unknown action"}),{status:400,headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const gN=Object.freeze(Object.defineProperty({__proto__:null,action:fN},Symbol.toStringTag,{value:"Module"}));function Nn(){const e=process.memoryUsage(),t=_h.getHeapStatistics();return{process:{rss:Math.round(e.rss/1024/1024),heapTotal:Math.round(e.heapTotal/1024/1024),heapUsed:Math.round(e.heapUsed/1024/1024),external:Math.round(e.external/1024/1024),arrayBuffers:Math.round(e.arrayBuffers/1024/1024)},heap:{totalHeapSize:Math.round(t.total_heap_size/1024/1024),totalHeapSizeExecutable:Math.round(t.total_heap_size_executable/1024/1024),totalPhysicalSize:Math.round(t.total_physical_size/1024/1024),totalAvailableSize:Math.round(t.total_available_size/1024/1024),usedHeapSize:Math.round(t.used_heap_size/1024/1024),heapSizeLimit:Math.round(t.heap_size_limit/1024/1024),mallocedMemory:Math.round(t.malloced_memory/1024/1024),peakMallocedMemory:Math.round(t.peak_malloced_memory/1024/1024)},system:{totalMemory:Math.round(io.totalmem()/1024/1024),freeMemory:Math.round(io.freemem()/1024/1024)}}}function yN(){const e=Nn();console.log(`
464
+ [Memory Profiler] Detailed Statistics:`),console.log(" Process Memory:"),console.log(` RSS: ${e.process.rss} MB (total memory used by process)`),console.log(` Heap Used: ${e.process.heapUsed} MB / ${e.process.heapTotal} MB`),console.log(` External: ${e.process.external} MB (C++ objects)`),console.log(` ArrayBuffers: ${e.process.arrayBuffers} MB`),console.log(" V8 Heap:"),console.log(` Used: ${e.heap.usedHeapSize} MB / ${e.heap.totalHeapSize} MB`),console.log(` Physical: ${e.heap.totalPhysicalSize} MB`),console.log(` Limit: ${e.heap.heapSizeLimit} MB`),console.log(` Malloced: ${e.heap.mallocedMemory} MB (peak: ${e.heap.peakMallocedMemory} MB)`),console.log(" System:"),console.log(` Total: ${e.system.totalMemory} MB`),console.log(` Free: ${e.system.freeMemory} MB`);const t=(e.heap.usedHeapSize/e.heap.heapSizeLimit*100).toFixed(1);return console.log(` Heap Usage: ${t}% of limit`),e}function xN(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=Nn();global.gc();const t=Nn(),r=e.process.heapUsed-t.process.heapUsed;return console.log(`[Memory Profiler] GC freed ${r} MB`),console.log(`[Memory Profiler] Heap: ${t.process.heapUsed} MB (was ${e.process.heapUsed} MB)`),!0}else return console.log("[Memory Profiler] GC not available. Start Node with --expose-gc to enable."),!1}function bN(){const e=Nn(),t=e.heap.usedHeapSize/e.heap.heapSizeLimit*100,r={highHeapUsage:t>80,highExternalMemory:e.process.external>200,highArrayBuffers:e.process.arrayBuffers>100,nearHeapLimit:e.heap.totalAvailableSize<100},s=[];return r.highHeapUsage&&s.push(`High heap usage: ${t.toFixed(1)}% of limit`),r.highExternalMemory&&s.push(`High external memory: ${e.process.external} MB`),r.highArrayBuffers&&s.push(`High ArrayBuffer usage: ${e.process.arrayBuffers} MB`),r.nearHeapLimit&&s.push(`Near heap limit: only ${e.heap.totalAvailableSize} MB available`),{indicators:r,warnings:s,hasIssues:s.length>0}}function wN({request:e}){const r=new URL(e.url).searchParams.get("action");try{switch(r){case"snapshot":return Response.json({success:!1,error:"Heap snapshots are disabled because they block the server for several minutes. Use action=leaks instead."},{status:400});case"gc":{const s=xN(),a=Nn();return Response.json({success:s,message:s?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:a})}case"detailed":{const s=yN();return Response.json({success:!0,stats:s})}case"leaks":{const s=bN(),a=Nn();return Response.json({success:!0,leakCheck:s,stats:a})}default:{const s=Nn();return Response.json({success:!0,stats:s,actions:{gc:"/api/memory-profile?action=gc - Force garbage collection (requires --expose-gc)",detailed:"/api/memory-profile?action=detailed - Log detailed stats to console",leaks:"/api/memory-profile?action=leaks - Check for memory leak indicators"}})}}}catch(s){return console.error("[Memory API] Error:",s),Response.json({success:!1,error:s.message},{status:500})}}const vN=Object.freeze(Object.defineProperty({__proto__:null,loader:wN},Symbol.toStringTag,{value:"Module"})),gs=$o(Mo);async function NN({request:e}){const r=new URL(e.url).searchParams.get("pids");if(!r)return Response.json({error:"Missing pids parameter"},{status:400});const s=r.split(",").map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o));if(s.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const a=await Promise.all(s.map(async o=>{const i=SN(o),l=i?await CN(o):null;return{pid:o,isRunning:i,processName:l}}));return Response.json({processes:a})}function SN(e){try{return process.kill(e,0),!0}catch{return!1}}async function CN(e){if(process.platform==="win32")try{const{stdout:r}=await gs(`tasklist /FI "PID eq ${e}" /FO CSV /NH`),s=r.match(/"([^"]+)"/);if(!s)return null;const a=s[1];if(a.toLowerCase()==="node.exe")try{const{stdout:o}=await gs(`wmic process where "ProcessId=${e}" get CommandLine /FORMAT:LIST`),i=o.match(/codeyam-(\w+)/);if(i)return`codeyam-${i[1]}`}catch{}return a}catch{return null}try{const{stdout:r}=await gs(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:s}=await gs(`ps -p ${e} -o args=`),a=s.trim(),o=a.match(/codeyam-(\w+)/);return o?`codeyam-${o[1]}`:a.split(" ")[0]||null}catch{return null}}}const kN=Object.freeze(Object.defineProperty({__proto__:null,loader:NN},Symbol.toStringTag,{value:"Module"})),_N=Vs(import.meta.url),EN=U.dirname(_N);function AN({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=aa(),r=Ne()||(t==null?void 0:t.projectRoot);if(!r)throw new Error("Could not determine project root");const s=(t==null?void 0:t.port)||3111,a=U.join(EN,"..","..","..","..","webserver","bootstrap.js"),o=U.join(r,".codeyam","logs");V.existsSync(o)||V.mkdirSync(o,{recursive:!0});const i=V.openSync(U.join(o,"background-server.log"),"a"),l=V.openSync(U.join(o,"background-server-error.log"),"a"),c=new Date().toISOString();V.appendFileSync(U.join(o,"background-server.log"),`
465
+ [${c}] Server restart requested via dashboard
466
+ `),Vo();const p=ft("node",[a],{detached:!0,stdio:["ignore",i,l],env:{...process.env,CODEYAM_PORT:s.toString(),CODEYAM_ROOT_PATH:r,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});p.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${p.pid})`);const u=new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}});return setTimeout(()=>{console.log("[api.restart-server] Exiting old server process"),process.exit(0)},100),u}catch(t){return console.error("[api.restart-server] Error restarting server:",t),new Response(JSON.stringify({success:!1,error:t instanceof Error?t.message:"Unknown error"}),{status:500,headers:{"Content-Type":"application/json"}})}}const PN=Object.freeze(Object.defineProperty({__proto__:null,action:AN},Symbol.toStringTag,{value:"Module"}));async function jN({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:s}=t;if(!r||!s)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${r.id}`),console.log(`[API] Received ${s.length} scenarios to save`),s.forEach((l,c)=>{var h,m,f,g,y;const p=(m=(h=l.metadata)==null?void 0:h.data)==null?void 0:m.argumentsData,u=Array.isArray(p)&&p.length>0?JSON.stringify(p[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${c}: ${l.name}`,{id:l.id,projectId:l.projectId,analysisId:l.analysisId,hasMetadata:!!l.metadata,hasData:!!((f=l.metadata)!=null&&f.data),mockDataKeys:(y=(g=l.metadata)==null?void 0:g.data)!=null&&y.mockData?Object.keys(l.metadata.data.mockData):[],argumentsDataLength:Array.isArray(p)?p.length:"not-array",argumentsDataPreview:u})});const a=s.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),o=await gf(a);if(!o||o.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${o.length} scenarios to database`),o.forEach((l,c)=>{var u,h;const p=(h=(u=l.metadata)==null?void 0:u.data)==null?void 0:h.argumentsData;console.log(`[API] Saved scenario ${c}: ${l.name}`,{id:l.id,argumentsDataLength:Array.isArray(p)?p.length:"not-array"})});const i={...r,scenarios:o};return Response.json({success:!0,analysis:i})}catch(t){return console.error("[API] Error saving scenarios:",t),Response.json({error:"Failed to save scenarios",details:t instanceof Error?t.message:String(t)},{status:500})}}const TN=Object.freeze(Object.defineProperty({__proto__:null,action:jN},Symbol.toStringTag,{value:"Module"})),MN=()=>[{title:"Agent Transcripts - CodeYam"},{name:"description",content:"View background agent transcripts and tool call history"}];async function $N({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("search")||"",s=t.searchParams.get("page")||"1",a=new URLSearchParams;r&&a.set("search",r),s!=="1"&&a.set("page",s);const o=a.toString(),i=new URL(`/api/agent-transcripts${o?`?${o}`:""}`,e.url),c=await(await fetch(i.toString())).json();if(c.error)return re({agents:[],error:c.error,search:r,page:1,totalPages:1});const p=c.total??(c.agents||[]).length,u=c.pageSize??20;return re({agents:c.agents||[],error:null,search:r,page:c.page??parseInt(s,10),totalPages:Math.max(1,Math.ceil(p/u))})}catch(t){return console.error("Failed to load agent transcripts:",t),re({agents:[],error:"Failed to load agent transcripts",search:"",page:1,totalPages:1})}}function IN(e){if(!e)return"";try{return new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}catch{return e}}function RN(e){if(!e)return"";try{return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}catch{return e}}function DN(e){return e.includes("opus")?"Opus":e.includes("sonnet")?"Sonnet":e.includes("haiku")?"Haiku":e}function Es({type:e,toolName:t}){const r={user_prompt:"bg-[#00b4d8] text-black",assistant_text:"bg-[#a8dadc] text-black",tool_call:"bg-[#f4a261] text-black",tool_result:"bg-[#2a9d8f] text-black",context:"bg-[#7c3aed] text-white"},s={user_prompt:"USER",assistant_text:"ASSISTANT",tool_call:t||"TOOL",tool_result:"RESULT",context:"CONTEXT"};return n("span",{className:`inline-block px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wide ${r[e]||"bg-gray-300 text-black"}`,children:s[e]||e})}function FN({input:e}){return n("div",{className:"text-xs font-mono space-y-1",children:Object.entries(e).map(([t,r])=>{let s=typeof r=="string"?r:JSON.stringify(r);return s.length>500&&(s=s.slice(0,500)+"..."),d("div",{children:[d("span",{className:"text-[#f4a261] font-bold",children:[t,":"]})," ",n("span",{className:"text-gray-700",children:s})]},t)})})}function ON({content:e,truncated:t,fullLength:r}){const[s,a]=P(!1);return d("div",{children:[d("pre",{className:"whitespace-pre-wrap break-words text-xs max-h-96 overflow-y-auto text-gray-700",children:[e,t&&!s&&"..."]}),t&&n("button",{onClick:()=>a(!s),className:"text-[11px] text-gray-500 hover:text-gray-700 mt-1 font-mono cursor-pointer",children:s?"Show less":`Show more (${(r||0)-e.length} more chars)`})]})}function LN({entry:e,pairedResult:t}){const[r,s]=P(!1),a=IN(e.timestamp||"");return e.type==="user_prompt"?d("div",{className:"my-2",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(Es,{type:"user_prompt"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:a})]}),n("pre",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#00b4d8] max-h-72 overflow-y-auto text-gray-800",children:e.text})]}):e.type==="assistant_text"?d("div",{className:"my-2",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(Es,{type:"assistant_text"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:a})]}),n("div",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-sm border-l-[3px] border-l-[#a8dadc] text-gray-800",children:e.text})]}):e.type==="tool_call"?d("div",{className:"my-2",children:[d("button",{onClick:()=>s(!r),className:"flex items-center gap-2 w-full text-left bg-white border border-gray-200 rounded-md px-3 py-2 hover:bg-gray-50 cursor-pointer",children:[r?n(St,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n(on,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n(Es,{type:"tool_call",toolName:e.name}),n("span",{className:"text-xs text-gray-500 font-mono truncate flex-1",children:e.summary||""}),n("span",{className:"text-[11px] text-gray-400 font-mono flex-shrink-0",children:a})]}),r&&d("div",{className:"bg-white border border-t-0 border-gray-200 rounded-b-md px-3 py-2 border-l-[3px] border-l-[#f4a261]",children:[n(FN,{input:e.input||{}}),t&&d("div",{className:"mt-3 pt-3 border-t border-gray-200",children:[d("div",{className:"text-[11px] font-bold uppercase tracking-wide text-[#2a9d8f] mb-1",children:["Result",t.is_error?" (Error)":"",":"]}),n(ON,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function BN({context:e}){const[t,r]=P(!1);return d("div",{className:"my-2",children:[d("button",{onClick:()=>r(!t),className:"flex items-center gap-2 mb-1 cursor-pointer hover:opacity-80",children:[t?n(St,{className:"w-3 h-3 text-gray-400"}):n(on,{className:"w-3 h-3 text-gray-400"}),n(Es,{type:"context"}),n("span",{className:"text-xs text-gray-500",children:"Full prompt context"})]}),t&&n("pre",{className:"bg-gray-50 border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#7c3aed] max-h-96 overflow-y-auto text-gray-700",children:e})]})}function zN({snippet:e}){const[t,r]=P(!1),s=e.split(`
467
+ `).filter(l=>l.trim()),a=s.slice(0,4),o=s.length>4,i=t?s:a;return d("div",{className:"my-2 bg-blue-50 border border-blue-200 rounded-md p-3",children:[d("div",{className:"flex items-center gap-2 mb-2",children:[n(Hp,{className:"w-3.5 h-3.5 text-blue-600"}),n("span",{className:"text-xs font-bold text-blue-800",children:"Source Conversation"}),d("span",{className:"text-[10px] text-blue-500",children:[s.length," message",s.length!==1?"s":""]})]}),n("div",{className:"space-y-1",children:i.map((l,c)=>{const p=l.match(/^\[(\w+)\]:\s*(.*)/);if(!p)return null;const[,u,h]=p,m=u==="user";return d("div",{className:"text-xs",children:[d("span",{className:`font-bold ${m?"text-blue-700":"text-gray-500"}`,children:[m?"User":"Assistant",":"]})," ",n("span",{className:"text-gray-700",children:h.length>200?h.slice(0,200)+"...":h})]},c)})}),o&&n("button",{onClick:()=>r(!t),className:"text-[11px] text-blue-600 hover:text-blue-800 mt-2 font-mono cursor-pointer",children:t?"Show less":`Show all ${s.length} messages`})]})}function YN({change:e}){const[t,r]=P(!1),s=e.action==="created"?!!e.content:e.action==="modified"?!!(e.oldString||e.newString):!1;return d("li",{children:[n("button",{onClick:()=>s&&r(!t),className:`text-left w-full ${s?"hover:text-green-900 cursor-pointer":""}`,children:d("span",{className:"inline-flex items-center gap-1",children:[s&&(t?n(St,{className:"w-3 h-3 inline flex-shrink-0"}):n(on,{className:"w-3 h-3 inline flex-shrink-0"})),e.action==="created"?"Created":"Modified"," ",e.filePath]})}),t&&e.action==="created"&&e.content&&n("pre",{className:"mt-1 mb-2 ml-4 p-2 bg-white border border-green-200 rounded text-[11px] text-gray-700 whitespace-pre-wrap break-words max-h-64 overflow-y-auto",children:e.content}),t&&e.action==="modified"&&d("div",{className:"mt-1 mb-2 ml-4 space-y-1",children:[e.oldString&&d("pre",{className:"p-2 bg-red-50 border border-red-200 rounded text-[11px] text-red-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["- ",e.oldString]}),e.newString&&d("pre",{className:"p-2 bg-green-50 border border-green-300 rounded text-[11px] text-green-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["+ ",e.newString]})]})]})}function WN({changes:e}){const t=e.filter(i=>i.action==="touched"),r=e.filter(i=>i.action!=="touched"),s=r.some(i=>i.action==="created"),a=r.some(i=>i.action==="modified");return d("div",{className:`my-2 border rounded-md p-3 ${s?"bg-green-50 border-green-200 text-green-800 [&_ul]:text-green-700":a?"bg-amber-50 border-amber-200 text-amber-800 [&_ul]:text-amber-700":"bg-gray-50 border-gray-200 text-gray-600 [&_ul]:text-gray-500"}`,children:[n("div",{className:"text-xs font-bold mb-1",children:"Rule Changes:"}),d("ul",{className:"text-xs space-y-0.5 font-mono",children:[r.map((i,l)=>n(YN,{change:i},l)),t.length>0&&d("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function UN({result:e}){const t=e.is_error,r=t?"bg-red-50 border-red-200":"bg-green-50 border-green-200",s=t?"text-red-800":"text-green-800",a=t?"text-red-700":"text-green-700",o=e.subtype.replace(/^error_/,"").replace(/_/g," "),i=c=>c>=6e4?`${(c/6e4).toFixed(1)}m`:`${(c/1e3).toFixed(1)}s`,l=c=>c>=1e3?`${(c/1e3).toFixed(1)}k`:String(c);return d("div",{className:`my-2 border rounded-md p-3 ${r}`,children:[d("div",{className:`text-xs font-bold mb-1 ${s}`,children:["Session Result: ",o]}),d("div",{className:`text-xs ${a} font-mono space-y-0.5`,children:[d("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5",children:[e.duration_ms!=null&&d("span",{children:["Duration: ",i(e.duration_ms)]}),e.duration_api_ms!=null&&d("span",{children:["API time: ",i(e.duration_api_ms)]}),e.num_turns!=null&&d("span",{children:["Turns: ",e.num_turns]}),e.total_cost_usd!=null&&d("span",{children:["Cost: $",e.total_cost_usd.toFixed(4)]})]}),e.usage&&d("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5 mt-1",children:[e.usage.input_tokens!=null&&d("span",{children:["Input: ",l(e.usage.input_tokens)]}),e.usage.output_tokens!=null&&d("span",{children:["Output: ",l(e.usage.output_tokens)]}),e.usage.cache_read_input_tokens!=null&&d("span",{children:["Cache read: ",l(e.usage.cache_read_input_tokens)]}),e.usage.cache_creation_input_tokens!=null&&d("span",{children:["Cache write:"," ",l(e.usage.cache_creation_input_tokens)]})]}),e.errors&&e.errors.length>0&&n("div",{className:"mt-1",children:e.errors.map((c,p)=>n("div",{className:"text-red-700 break-words",children:c},p))})]})]})}function JN({agent:e,defaultOpen:t,isAdmin:r}){var S,C,A;const[s,a]=P(t),[o,i]=P(!1),[l,c]=P(null),[p,u]=P(!1),h=ie(()=>{const _={};for(const E of e.entries)E.type==="tool_result"&&E.tool_use_id&&(_[E.tool_use_id]=E);return _},[e.entries]),m=ie(()=>{const _=new Set;for(const E of e.entries)E.type==="tool_call"&&E.tool_use_id&&h[E.tool_use_id]&&_.add(E.tool_use_id);return _},[e.entries,h]),f=_=>{_.stopPropagation(),i(!0),c(null),fetch("/api/save-fixture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e.id})}).then(E=>E.json()).then(E=>{E.success?c(`Saved to ${E.fixturePath}`):c(`Error: ${E.error}`)}).catch(E=>{c(`Error: ${E instanceof Error?E.message:String(E)}`)}).finally(()=>{i(!1)})},g=(e.ruleChanges||[]).filter(_=>_.action!=="touched"),y=g.filter(_=>_.action==="created"),x=g.filter(_=>_.action==="modified"),b=(e.ruleChanges||[]).filter(_=>_.action==="touched"),w=g.length>0,v=b.length>0,N=w||v;return d("div",{className:`bg-white border rounded-lg overflow-hidden mb-4 ${e.stats.errors>0?"border-red-300":y.length>0?"border-green-300":x.length>0?"border-amber-300":"border-gray-200"}`,children:[d("button",{onClick:()=>a(!s),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:[s?n(St,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n(on,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm font-bold text-[#005C75] font-mono",children:e.id.slice(0,8)}),e.slug&&n("span",{className:"text-xs text-gray-500",children:e.slug}),e.model&&n("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold bg-purple-100 text-purple-700",title:e.model,children:DN(e.model)}),y.length>0&&d("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-green-100 text-green-800",children:[n(js,{className:"w-3 h-3"}),y.length," rule",y.length!==1?"s":""," ","created"]}),x.length>0&&d("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-100 text-amber-800",children:[n(js,{className:"w-3 h-3"}),x.length," rule",x.length!==1?"s":""," ","modified"]}),!w&&v&&d("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-gray-100 text-gray-500",children:[b.length," timestamp",b.length!==1?"s":""," ","touched"]}),e.stats.errors>0&&d("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-red-100 text-red-800",children:[n(Ps,{className:"w-3 h-3 flex-shrink-0"}),e.stats.errors," ",e.stats.errors===1?"Error":"Errors"]}),d("span",{className:"text-[11px] text-gray-400 font-mono",children:[e.stats.toolCalls," tool calls, ",e.stats.textBlocks," text blocks",((S=e.sessionResult)==null?void 0:S.duration_ms)!=null&&d(we,{children:[" · ",e.sessionResult.duration_ms>=6e4?`${(e.sessionResult.duration_ms/6e4).toFixed(1)}m`:`${(e.sessionResult.duration_ms/1e3).toFixed(1)}s`]}),((C=e.sessionResult)==null?void 0:C.total_cost_usd)!=null&&d(we,{children:[" · ","$",e.sessionResult.total_cost_usd.toFixed(2)]})]}),d("span",{className:"text-[11px] text-gray-400 font-mono ml-auto flex items-center gap-2",children:[RN(e.timestamp),r&&w&&d("button",{onClick:f,disabled:o,className:"inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] font-bold bg-gray-100 text-gray-600 hover:bg-gray-200 disabled:opacity-50 cursor-pointer",title:"Save as test fixture",children:[n(Jp,{className:"w-3 h-3"}),o?"Saving...":"Save Fixture"]})]})]}),l&&n("div",{className:`px-4 py-2 text-xs font-mono ${l.startsWith("Error")?"bg-red-50 text-red-700":"bg-green-50 text-green-700"}`,children:l}),s&&d("div",{className:"px-4 pb-4 border-t border-gray-100",children:[e.sourceFile&&d("div",{className:"flex items-center gap-2 py-2 text-xs text-gray-500 font-mono",children:[n("span",{className:"text-gray-400",children:"FILE:"}),n("span",{className:"truncate",children:e.sourceFile}),n("button",{onClick:_=>{_.stopPropagation(),navigator.clipboard.writeText(e.sourceFile),u(!0),setTimeout(()=>u(!1),2e3)},className:"p-0.5 rounded text-gray-400 hover:text-gray-600 cursor-pointer transition-colors flex-shrink-0",title:"Copy file path",children:p?n(kt,{className:"w-3.5 h-3.5 text-green-500"}):n($t,{className:"w-3.5 h-3.5"})})]}),e.sessionResult&&n(UN,{result:e.sessionResult}),e.stats.errors>0&&((A=e.stats.errorMessages)==null?void 0:A.length)>0&&d("div",{className:"my-2 bg-red-50 border border-red-200 rounded-md p-3",children:[d("div",{className:"text-xs font-bold text-red-800 mb-1",children:[e.stats.errors," Error",e.stats.errors!==1?"s":"",":"]}),n("ul",{className:"text-xs text-red-700 space-y-1 font-mono",children:e.stats.errorMessages.map((_,E)=>n("li",{className:"break-words",children:_},E))})]}),e.conversationSnippet&&n(zN,{snippet:e.conversationSnippet}),N&&n(WN,{changes:e.ruleChanges}),e.context&&n(BN,{context:e.context}),e.entries.map((_,E)=>{if(_.type==="tool_result"&&_.tool_use_id&&m.has(_.tool_use_id))return null;const R=_.type==="tool_call"&&_.tool_use_id?h[_.tool_use_id]:void 0;return n(LN,{entry:_,pairedResult:R},`${e.id}-${E}`)})]})]})}function eo(e,t){const r=new URLSearchParams;t&&r.set("search",t),e>1&&r.set("page",String(e));const s=r.toString();return`/agent-transcripts${s?`?${s}`:""}`}const HN=et(function(){const{agents:t,error:r,search:s,page:a,totalPages:o}=st(),i=Rt(),l=jc("root"),c=(l==null?void 0:l.isAdmin)??!1,[p,u]=P(s),[h,m]=P(!1),[f,g]=P(0);Dt({source:"agent-transcripts-page"});const y=b=>{b.preventDefault(),window.location.href=eo(1,p)},x=()=>{m(!h),g(b=>b+1)};return r?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:r})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-20 py-12 font-sans",children:[d("div",{className:"mb-8",children:[d("div",{className:"flex items-center gap-3 mb-1",children:[n("button",{onClick:()=>{i("/memory")},className:"text-gray-600 hover:text-[#005C75] transition-colors cursor-pointer",title:"Back to Memory","aria-label":"Back to Memory",children:n(Wp,{className:"w-5 h-5"})}),n(Ts,{className:"w-6 h-6 text-[#232323]"}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Agent Transcripts"})]}),n("p",{className:"text-[15px] text-gray-500 ml-14",children:"View background agent transcripts and tool call history"})]}),d("div",{className:"flex items-center gap-4 mb-6",children:[d("form",{onSubmit:y,className:"relative flex-1 max-w-md",children:[n(Dr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:p,onChange:b=>u(b.target.value),placeholder:"Search transcripts...",className:"w-full pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),n("button",{onClick:x,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:h?"Collapse All":"Expand All"})]}),d("div",{className:"text-sm text-gray-500 mb-4",children:["Page ",a," of ",o,s&&d("span",{children:[" ","matching “",s,"”",n(Ce,{to:"/agent-transcripts",className:"text-[#005C75] hover:underline ml-2",children:"Clear"})]})]}),t.length===0?d("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(Ts,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Agent Transcripts Found"}),n("p",{className:"text-gray-500",children:"Background agent output files will appear here when available."})]}):n("div",{children:t.map(b=>n(JN,{agent:b,defaultOpen:h,isAdmin:c},b.id))},f),o>1&&d("div",{className:"flex items-center justify-center gap-3 mt-8",children:[d("a",{href:a>1?eo(a-1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${a>1?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:[n(Up,{className:"w-4 h-4"}),"Prev"]}),d("span",{className:"text-sm text-gray-500 font-mono",children:[a," / ",o]}),d("a",{href:a<o?eo(a+1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${a<o?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:["Next",n(on,{className:"w-4 h-4"})]})]})]})})}),VN=Object.freeze(Object.defineProperty({__proto__:null,default:HN,loader:$N,meta:MN},Symbol.toStringTag,{value:"Module"}));async function GN({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{message:r}=t;if(!r)return new Response(JSON.stringify({error:"message is required"}),{status:400,headers:{"Content-Type":"application/json"}});const s=process.env.CODEYAM_ROOT_PATH||process.cwd();console.log(`[editor-commit] Committing with message: "${r}" in ${s}`);const a=Xw(s);a&&console.log("[editor-commit] Initialized new git repository"),ev(s),console.log("[editor-commit] Staged all changes");const o=tv(s,r);console.log(`[editor-commit] Created commit: ${o}`);try{const{broadcastHideResults:i}=await Promise.resolve().then(()=>Hy);i()}catch{}return new Response(JSON.stringify({success:!0,commitSha:o,initialized:a}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-commit] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const KN=Object.freeze(Object.defineProperty({__proto__:null,action:GN},Symbol.toStringTag,{value:"Module"}));function qN(){const e={"Content-Type":"application/json","Access-Control-Allow-Origin":"*"};try{const t=Ne()||process.cwd(),r=U.join(t,".codeyam","data-structure.json");if(V.existsSync(r))try{const o=JSON.parse(V.readFileSync(r,"utf-8")),i=Array.isArray(o)?o:[];return i.sort((l,c)=>(l.order??99)-(c.order??99)),new Response(JSON.stringify({dataStructures:i,source:"explicit"}),{headers:e})}catch{}const s=U.join(t,"prisma","schema.prisma");if(V.existsSync(s)){const o=V.readFileSync(s,"utf-8"),i=QN(o);return new Response(JSON.stringify({models:i,source:"prisma"}),{headers:e})}const a=ZN(t);return a.length>0?new Response(JSON.stringify({models:a,source:"typescript"}),{headers:e}):new Response(JSON.stringify({models:[],source:null}),{headers:e})}catch{return new Response(JSON.stringify({models:[],source:null}),{headers:e})}}function QN(e){const t=[],r=/model\s+(\w+)\s*\{([^}]+)\}/g,s=new Set;let a;const o=/model\s+(\w+)\s*\{/g;for(;(a=o.exec(e))!==null;)s.add(a[1]);let i;for(;(i=r.exec(e))!==null;){const l=i[1],c=i[2],p=[];for(const u of c.split(`
468
+ `)){const h=u.trim();if(!h||h.startsWith("//")||h.startsWith("@@"))continue;const m=h.match(/^(\w+)\s+([\w[\]?]+)\??(\s+.*)?$/);if(!m)continue;const f=m[1];let g=m[2];const y=m[3]||"",x=g.endsWith("[]"),b=g.endsWith("?")||h.includes("?");g=g.replace(/[[\]?]/g,"");const w=s.has(g),v=y.includes("@id");p.push({name:f,type:g,isRelation:w,isOptional:b,isList:x,isId:v,...w?{relatedModel:g}:{}})}t.push({name:l,fields:p})}return t}function ZN(e){const t=U.join(e,"src");if(!V.existsSync(t))return[];const r=[],s=new Set,a=[],o=["src","src/lib","src/types","src/utils","src/models"];for(const i of o){const l=U.join(e,i);if(V.existsSync(l))try{for(const c of V.readdirSync(l))c.endsWith(".ts")&&!c.endsWith(".test.ts")&&!c.endsWith(".spec.ts")&&a.push(U.join(l,c))}catch{}}for(const i of a){const l=V.readFileSync(i,"utf-8"),c=/export\s+interface\s+(\w+)/g;let p;for(;(p=c.exec(l))!==null;)s.add(p[1])}for(const i of a){const l=V.readFileSync(i,"utf-8"),c=/export\s+interface\s+(\w+)\s*\{([^}]+)\}/g;let p;for(;(p=c.exec(l))!==null;){const u=p[1],h=p[2],m=[];for(const f of h.split(`
469
+ `)){const g=f.trim();if(!g||g.startsWith("//"))continue;const y=g.match(/^(\w+)(\?)?:\s*([^;/]+)/);if(!y)continue;const x=y[1],b=!!y[2];let w=y[3].trim();const v=w.endsWith("[]");w=w.replace(/\[\]$/,"");const N=s.has(w);m.push({name:x,type:w,isRelation:N,isOptional:b,isList:v,isId:x==="id",...N?{relatedModel:w}:{}})}r.push({name:u,fields:m})}}return r}const XN=Object.freeze(Object.defineProperty({__proto__:null,loader:qN},Symbol.toStringTag,{value:"Module"}));async function eS({request:e}){const r=new URL(e.url).searchParams.get("skipTests")==="true",s=Ne()||process.cwd(),a=U.join(s,".codeyam","glossary.json");let o;try{const $=V.readFileSync(a,"utf8");o=la(JSON.parse($))}catch{return Response.json(Ka({components:[],functions:[],scenarioCounts:{},testFileExistence:{}}))}if(o.length===0)return Response.json(Ka({components:[],functions:[],scenarioCounts:{},testFileExistence:{}}));const i=U.join(s,".codeyam","editor-step.json");let l=null;try{const $=V.readFileSync(i,"utf8");l=JSON.parse($).featureStartedAt||null}catch{}let c,p=[];const u=await Ye();if(u)try{const{project:$}=await De(u),B=await Pe().selectFrom("editor_scenarios").select(["name","component_name","component_path","page_file_path","url","display_name"]).where("project_id","=",$.id).orderBy("created_at","asc").execute(),H=Ct(B,W=>`${W.name}::${W.url||"/"}`),q=H.map(W=>({componentName:W.component_name||null,componentPath:W.component_path||null,pageFilePath:W.page_file_path??null,url:W.url??null,displayName:W.display_name??null}));p=H.map(W=>({name:W.name,componentName:W.component_name||null,pageFilePath:W.page_file_path??null,url:W.url??null}));const O=await ir({projectRoot:s,scenarioInputs:q});Object.keys(O.entityChangeStatus).length>0&&(c=O.entityChangeStatus)}catch{}const h=jx({featureStartedAt:l,entityChangeStatus:c});l=h.featureStartedAt,c=h.entityChangeStatus;const m=Tx(o,c),{components:f,functions:g}=Px(m);let y={},x={};if(u)try{const{project:$}=await De(u),L=Pe();y=await jl(L,$.id,l);const B=await Tl(L,$.id,l);for(const[H,q]of Object.entries(B)){const O=m.find(W=>W.filePath===H);O&&(y[O.name]=(y[O.name]||0)+q)}if(l&&c){const H=await jl(L,$.id,null),q=await Tl(L,$.id,null);x={...H};for(const[O,W]of Object.entries(q)){const I=m.find(j=>j.filePath===O);I&&(x[I.name]=(x[I.name]||0)+W)}}}catch{}let b={};try{const $=process.env.CODEYAM_ROOT_PATH||process.cwd(),L=await Kd($);b=Dx(L,p)}catch{}const w={};for(const $ of g)$.testFile&&(w[$.testFile]=V.existsSync(U.join(s,$.testFile)));const v={};if(!r){const $=g.filter(B=>B.testFile&&w[B.testFile]).map(B=>B.testFile),L=[...new Set($)];if(L.length>0){const B=gi(s),H=g.filter(j=>!!j.testFile&&w[j.testFile]).map(j=>({filePath:j.filePath,testFile:j.testFile})),q=yi(s,H),O=new Set(c?Object.entries(c).filter(([,j])=>j.status==="impacted").map(([j])=>j):[]),W=[],I={};for(const j of L){const k=B.results[j],Y=q[j],G=g.some(Q=>Q.testFile===j&&O.has(Q.name));k&&Y&&!mu(k,Y.sourceHash,Y.testHash)&&!G?I[j]={testFilePath:k.testFilePath,status:k.status,testCases:k.testCases,...k.errorMessage?{errorMessage:k.errorMessage}:{}}:W.push(j)}try{const j=W.length>0?await Rw(s,W):{},k={...I,...j};try{gu(s,j,H)}catch{}for(const Y of g){if(!Y.testFile||!w[Y.testFile])continue;const G=k[Y.testFile];if(!G)continue;const Q=G.status==="passed",K=G.testCases.some(F=>F.fullName.startsWith(Y.name));v[Y.testFile]={passing:Q,hasEntityNameDescribe:K,...G.status==="error"&&G.errorMessage?{errorMessage:G.errorMessage}:{}}}}catch(j){for(const k of L)v[k]={passing:!1,hasEntityNameDescribe:!1,errorMessage:j.message||"Unknown test runner error"}}}}const N=new Set(o.map($=>$.filePath)),S=[];if(u)try{const{project:$}=await De(u),B=await Pe().selectFrom("editor_scenarios").select(["component_name","component_path","page_file_path"]).where("project_id","=",$.id).execute(),H=new Map;for(const q of B){const O=q,W=O.component_path||O.page_file_path;if(!W)continue;const I=H.get(W);I?I.count++:H.set(W,{name:O.component_name||U.basename(W,U.extname(W)),count:1})}for(const[q,O]of H)N.has(q)||S.push({name:O.name,filePath:q,scenarioCount:O.count})}catch{}const C=Ka({components:f,functions:g,scenarioCounts:y,testFileExistence:w,testResults:v,clientErrors:b,totalScenarioCounts:x,entityChangeStatus:c});C.missingFromGlossary=S,S.length>0&&(C.summary.allPassing=!1,C.summary.missingFromGlossary=S.length);let A=[];if(u)try{const{project:$}=await De(u),L=Pe();A=await Mx(L,$.id,l)}catch{}if(C.incompleteEntities=A,A.length>0){C.summary.allPassing=!1,C.summary.incompleteEntities=A.length;const $=A.filter(L=>L.preExisting).length;$>0&&(C.summary.preExistingIncompleteEntities=$)}let _=[];if(u)try{const{project:$}=await De(u),L=Pe();_=await $x(L,$.id,l)}catch{}C.miscategorizedScenarios=_,_.length>0&&(C.summary.allPassing=!1,C.summary.miscategorizedScenarios=_.length);let E=[];if(u)try{const{project:$}=await De(u),L=Pe();E=await Ix(L,$.id,l)}catch{}C.unassociatedScenarios=E,E.length>0&&(C.summary.allPassing=!1,C.summary.unassociatedScenarios=E.length);let R=[];if(u&&c&&Object.keys(c).length>0)try{const{project:$}=await De(u),B=await Pe().selectFrom("editor_scenarios").select(["editor_scenarios.name","editor_scenarios.component_name","editor_scenarios.page_file_path","editor_scenarios.url","editor_scenarios.created_at","editor_scenarios.updated_at"]).where("editor_scenarios.project_id","=",$.id).execute(),H=l?zr(l):null,q=B.map(O=>({name:O.name,entityName:Kt({componentName:O.component_name,pageFilePath:O.page_file_path,url:O.url}),updatedInSession:H?qo({created_at:O.created_at,updated_at:O.updated_at},H):!1}));R=au({scenarios:q,entityChangeStatus:c})}catch{}C.scenariosNeedingRecapture=R,R.length>0&&(C.summary.allPassing=!1,C.summary.scenariosNeedingRecapture=R.length);const D=[],T=Rx(o);for(const[$,L]of T)D.push({name:$,filePaths:L.map(B=>B.filePath)});return C.duplicateNames=D,Response.json(C)}const tS=Object.freeze(Object.defineProperty({__proto__:null,loader:eS},Symbol.toStringTag,{value:"Module"}));async function nS({request:e}){try{const t=await e.json(),{pid:r,signal:s="SIGTERM",commitSha:a}=t;if(!r||typeof r!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!Hl(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,s)}catch(u){return Response.json({error:"Failed to kill process",pid:r,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,l=500,c=Date.now();let p=!0;for(;p&&Date.now()-c<i;)await new Promise(u=>setTimeout(u,l)),p=Hl(r);if(p){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${r}:`,u)}}if(a)try{await nn({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(u){console.error("Failed to update database after killing process:",u)}return Response.json({success:!0,pid:r,signal:s,message:`Process ${r} killed successfully`,waitedMs:Date.now()-c})}catch(t){return console.error("Error in kill-process API:",t),Response.json({error:"Internal server error",details:t instanceof Error?t.message:String(t)},{status:500})}}function Hl(e){try{return process.kill(e,0),!0}catch{return!1}}const rS=Object.freeze(Object.defineProperty({__proto__:null,action:nS},Symbol.toStringTag,{value:"Module"})),sS=Vs(import.meta.url),aS=se.dirname(sS),oS=se.resolve(aS,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function iS(e){const t=[],r=new Set;for(const s of e.split(`
470
+ `)){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}if(o.type!=="assistant")continue;const i=o.message;if(!(!i||!Array.isArray(i.content)))for(const l of i.content){if(typeof l!="object"||l===null)continue;const c=l;if(c.type!=="tool_use")continue;const p=String(c.name||""),u=c.input||{};if(p==="Write"||p==="Edit"){const h=String(u.file_path||"");if(h.includes(".claude/rules/")){const m=h.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${p}:${m}`;r.has(f)||(r.add(f),t.push({action:p==="Write"?"created":"modified",filePath:m}))}}else if(p==="Bash"){const h=String(u.command||"");if(h.includes("codeyam memory touch")){const m=`touch:${h}`;r.has(m)||(r.add(m),t.push({action:"touched",filePath:h}))}}}}return t}async function lS({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{sessionId:r}=t;if(!r)return Response.json({error:"Missing required field: sessionId"},{status:400});const s=await xu(),a=s?se.join(ks,s):null;let o=a?se.join(a,`${r}.log`):"";if((!o||!vt(o))&&(o=se.join(ks,`${r}.log`)),!vt(o))return Response.json({error:`Log file not found: ${r}.log`},{status:404});const i=await oo(o,"utf-8");let l=a?se.join(a,`${r}.context`):"";(!l||!vt(l))&&(l=se.join(ks,`${r}.context`));let c=null;if(vt(l))try{c=await oo(l,"utf-8")}catch{}const p=iS(i),h=c?["no,","no ","that's not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","shouldn't","try again","that broke","that failed","error","bug"].some(x=>c.toLowerCase().includes(x)):!1,m=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":r.endsWith("-interruption")?"-int":"",f=r.slice(0,8)+m,g=se.join(oS,f);await mh(g,{recursive:!0}),await Nr(se.join(g,"agent-log.jsonl"),i),c&&await Nr(se.join(g,"context.md"),c),await Nr(se.join(g,"rule-changes.json"),JSON.stringify(p,null,2)),await Nr(se.join(g,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:h,ruleChangeCount:p.length},null,2));const y=se.relative(process.cwd(),g);return console.log(`[api.save-fixture] Saved fixture to ${y}`),Response.json({success:!0,fixturePath:y})}catch(t){return console.error("[api.save-fixture] Error:",t),Response.json({error:"Failed to save fixture",details:t instanceof Error?t.message:String(t)},{status:500})}}const cS=Object.freeze(Object.defineProperty({__proto__:null,action:lS},Symbol.toStringTag,{value:"Module"}));async function dS({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=Ne();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const s=se.join(r,".codeyam","captures","screenshots",t);try{await Ee.access(s);const a=await Ee.readFile(s),o=se.extname(s).toLowerCase(),i=o===".png"?"image/png":o===".jpg"||o===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(a,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const uS=Object.freeze(Object.defineProperty({__proto__:null,loader:dS},Symbol.toStringTag,{value:"Module"})),Vl={visual:{label:"VISUAL",bgColor:"#f9f9f9",textColor:"#9040f5"},library:{label:"LIBRARY",bgColor:"#f9f9f9",textColor:"#06b6d5"},type:{label:"TYPE",bgColor:"#ffe1e1",textColor:"#db2627"},other:{label:"OTHER",bgColor:"#f9f9f9",textColor:"#646464"}};function bi({type:e,className:t=""}){const r=Vl[e]||Vl.other;return n("div",{className:`inline-flex items-center justify-center px-[4px] rounded-[4px] ${t}`,style:{backgroundColor:r.bgColor,color:r.textColor,height:"15px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-semibold leading-[15px] uppercase",children:r.label})})}const pS={analyzer:{bgColor:"#e1e1e1",textColor:"#3e3e3e",borderColor:"#e1e1e1"},capture:{bgColor:"#e1e1e1",textColor:"#3e3e3e",borderColor:"#e1e1e1"},running:{bgColor:"#e8ffe6",textColor:"#00925d",borderColor:"#c3f3bf"},error:{bgColor:"#fee2e2",textColor:"#991b1b",borderColor:"#fecaca"}};function ys({variant:e,pid:t,label:r,className:s=""}){const a=pS[e],o=r||(e==="analyzer"&&t?`Analyzer: ${t}`:e==="capture"&&t?`Capture: ${t}`:e==="running"?"Running":e==="error"?"Error":"");return n("div",{className:`inline-flex items-center justify-center px-[8px] rounded-[4px] ${s}`,style:{backgroundColor:a.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:a.borderColor,height:"20px"},children:n("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:a.textColor},children:o})})}let Gl=!1;function hS(){if(Gl)return;const e=document.createElement("style");e.textContent=`
471
+ @keyframes strongPulse {
472
+ 0%, 100% { opacity: 0.2; }
473
+ 50% { opacity: 1; }
474
+ }
475
+ `,document.head.appendChild(e),Gl=!0}function wi({size:e="medium",className:t=""}){typeof document<"u"&&hS();const r={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:s,centerDotSize:a,gap:o}=r[e];return d("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${o}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}const mS=()=>[{title:"Activity - CodeYam"},{name:"description",content:"View analysis activity and queue status"}];async function fS({request:e,context:t,params:r}){var W,I,j,k,Y,G,Q,K;let s=t.analysisQueue;s||(s=await Gt());const a=new URL(e.url),o=parseInt(a.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!s)return re({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:l,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const c=s.getState(),p=await Ye();let u=null;if(p&&((W=c==null?void 0:c.currentlyExecuting)!=null&&W.commitSha)){const{project:F,branch:M}=await De(p),z=await Ds({projectId:F.id,branchId:M.id,shas:[c.currentlyExecuting.commitSha]});u=z&&z.length>0?z[0]:null}else u=await rr();const h=async F=>{const M=await _n(F);if(!M)return null;const{getAnalysesForEntity:z}=await Promise.resolve().then(()=>Of),J=await z(F,!1);return{...M,analyses:J||[]}},m=await Promise.all(((c==null?void 0:c.jobs)||[]).map(async F=>{const M=[];if(F.entityShas&&F.entityShas.length>0){const z=F.entityShas.map(te=>h(te)),J=await Promise.all(z);M.push(...J.filter(te=>te!==null))}return{...F,entities:M}}));let f=null;if(c!=null&&c.currentlyExecuting){const F=c.currentlyExecuting,M=[];if(F.entityShas&&F.entityShas.length>0){const z=F.entityShas.map(te=>h(te)),J=await Promise.all(z);M.push(...J.filter(te=>te!==null))}f={...F,entities:M}}const g=f?m.filter(F=>F.id!==f.id):m,y=((j=(I=u==null?void 0:u.metadata)==null?void 0:I.currentRun)==null?void 0:j.currentEntityShas)||[],b=(await Promise.all(y.map(F=>h(F)))).filter(F=>F!==null),w=[];if(p)try{const{project:F,branch:M}=await De(p),z=await Ds({projectId:F.id,branchId:M.id,limit:100});for(const J of z){const te=((k=J.metadata)==null?void 0:k.historicalRuns)||[];w.push(...te)}}catch(F){console.error("[activity.tsx] Failed to load historical runs from commits:",F)}const v=[...w].sort((F,M)=>{const z=F.lastCaptureAt||F.analysisCompletedAt||F.archivedAt||F.createdAt||"";return(M.lastCaptureAt||M.analysisCompletedAt||M.archivedAt||M.createdAt||"").localeCompare(z)}),N=(o-1)*i,S=N+i,C=v.slice(N,S),A=Math.ceil(v.length/i),_=await Promise.all(C.map(async F=>{const M=F.currentEntityShas||[];if(M.length===0)return{...F,entities:[]};const z=await Promise.all(M.map(J=>h(J)));return{...F,entities:z.filter(J=>J!==null)}})),E=!!f,R=g.length,D=v.filter(F=>{const M=!!F.failedAt,z=F.readyToBeCaptured,J=F.capturesCompleted??0,te=z===void 0?!0:z===0||J>=z;return!M&&!!F.analysisCompletedAt&&te}),T=new Set(((Y=f==null?void 0:f.entities)==null?void 0:Y.map(F=>F.sha))||[]),$=D.filter(F=>!(F.currentEntityShas||[]).some(z=>T.has(z))),B=(await Promise.all($.slice(0,3).map(async F=>{const M=F.currentEntityShas||[];if(M.length===0)return{run:F,entities:[]};const z=await Promise.all(M.map(J=>h(J)));return{run:F,entities:z.filter(J=>J!==null)}}))).flatMap(({run:F,entities:M})=>M.map(z=>({...z,runId:F.id,completedAt:F.lastCaptureAt||F.analysisCompletedAt||F.archivedAt||F.createdAt})));let H=[],q=null,O=null;if((Q=(G=u==null?void 0:u.metadata)==null?void 0:G.currentRun)!=null&&Q.analysisCompletedAt&&b.length>0){const F=b[0].sha;q=b[0];const M=await Zs(F);M&&M.length>0&&M[0].scenarios&&(H=M[0].scenarios,O=M[0].status)}return re({state:{...c,jobs:g,currentlyExecuting:f},currentRun:(K=u==null?void 0:u.metadata)==null?void 0:K.currentRun,historicalRuns:_,totalHistoricalRuns:v.length,currentPage:o,totalPages:A,projectSlug:p,commitSha:u==null?void 0:u.sha,queueJobs:g,currentlyExecuting:f,currentEntities:b,tab:l,hasCurrentActivity:E,queuedCount:R,recentCompletedEntities:B,hasMoreCompletedRuns:$.length>3,currentEntityScenarios:H,currentEntityForScenarios:q,currentAnalysisStatus:O})}function gS({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:s}){const a=[{id:"current",label:"Current Activity",hasContent:t,count:t?1:null},{id:"queued",label:"Queued Activity",hasContent:r>0,count:r},{id:"historic",label:"Historic Activity",hasContent:s>0,count:s}];return n("div",{className:"border-b border-gray-200 mb-6",children:n("nav",{className:"flex gap-8",children:a.map(o=>{const i=e===o.id;return n(Ce,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
476
+ relative pb-4 px-2 text-sm transition-colors cursor-pointer
477
+ ${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
478
+ `,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:d("span",{className:"flex items-center gap-2",children:[o.label,o.count!==null&&o.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
479
+ inline-block w-2 h-2 rounded-full
480
+ ${i?"":"bg-gray-400"}
481
+ `,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function yS({currentlyExecuting:e,currentRun:t,state:r,projectSlug:s,commitSha:a,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:l,currentEntityScenarios:c,currentEntityForScenarios:p,currentAnalysisStatus:u}){var L,B,H,q;const[h,m]=P({}),[f,g]=P({isKilling:!1,current:0,total:0}),y=Ut(),x=!!e,b=(e==null?void 0:e.entities)||[],w=!!(t!=null&&t.analysisCompletedAt),v=w&&!!(t!=null&&t.capturePid),N=!w,S=x,C=c||[],{lastLine:A}=Jt(s,S);ae(()=>{if(!t)return;const O=[t.analyzerPid,t.capturePid].filter(k=>!!k);if(O.length===0)return;let W=!0;const I=async()=>{try{const Y=await(await fetch(`/api/process-status?pids=${O.join(",")}`)).json();if(Y.processes&&W){const G={};Y.processes.forEach(Q=>{G[Q.pid]={isRunning:Q.isRunning,processName:Q.processName}}),m(G)}}catch(k){W&&console.error("Failed to fetch process statuses:",k)}};I();const j=setInterval(()=>void I(),5e3);return()=>{W=!1,clearInterval(j)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[_,E]=P(!1),[R,D]=P(!1);ae(()=>{b.length<=3&&_&&E(!1)},[b.length,_]),ae(()=>{i.length<=3&&R&&D(!1)},[i.length,R]);const T=_?b:b.slice(0,3),$=b.length>3;return d("div",{className:"flex flex-col gap-[45px]",children:[S?d("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"1px solid #e0e9ec"},children:[d("div",{className:"flex items-center gap-2 mb-[15px]",children:[n(Mt,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:v?"Capturing...":"Analyzing..."})]}),T.map(O=>d("div",{className:"bg-white border border-[#e1e1e1] rounded-[4px] mb-[15px]",style:{height:"60px",padding:"0 15px",display:"flex",alignItems:"center",justifyContent:"space-between",boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1)"},children:[d("div",{className:"flex items-center gap-3",children:[n("div",{children:n(ht,{type:O.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col gap-[1px]",children:[d("div",{className:"flex items-center gap-[14px]",children:[n(Ce,{to:`/entity/${O.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:O.name}),O.entityType&&n(bi,{type:O.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:O.filePath,children:O.filePath})]})]}),n("button",{onClick:o,className:"px-[10px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},children:"View Logs"})]},O.sha)),$&&!_&&d("button",{onClick:()=>E(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",b.length-3," more"," ",b.length-3===1?"entity":"entities"]}),_&&$&&n("button",{onClick:()=>E(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"}),v&&C&&C.length>0&&p&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:C.map(O=>{var Q,K,F,M;if(!O.id)return null;const W=(K=(Q=O.metadata)==null?void 0:Q.screenshotPaths)==null?void 0:K[0],I=(F=O.metadata)==null?void 0:F.noScreenshotSaved,j=W&&!I,k=(M=u==null?void 0:u.scenarios)==null?void 0:M.find(z=>z.name===O.name),G=k&&k.screenshotStartedAt&&!k.screenshotFinishedAt||!j&&!I;return n(Ce,{to:`/entity/${p.sha}/scenarios/${O.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:G?"#f9f9f9":void 0,borderColor:G?"#efefef":"#ccc"},children:j?n(lt,{screenshotPath:W,alt:O.name,className:"w-full h-full object-contain bg-gray-100"}):G?n("div",{className:"w-full h-full flex items-center justify-center",children:n(wi,{size:"medium"})}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},O.id)})}),A&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:A}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.capturePid))&&d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center gap-2",children:[d("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(t==null?void 0:t.analyzerPid)&&n(ys,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(N||((L=h[t.analyzerPid])==null?void 0:L.isRunning))&&n(ys,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(ys,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(v||((B=h[t.capturePid])==null?void 0:B.isRunning))&&n(ys,{variant:"running"})]}),(((H=h[t==null?void 0:t.analyzerPid])==null?void 0:H.isRunning)||((q=h[t==null?void 0:t.capturePid])==null?void 0:q.isRunning))&&n("button",{onClick:()=>{const O=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(j=>{var k;return!!j&&((k=h[j])==null?void 0:k.isRunning)});if(O.length===0)return;const W=O.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${W})?`))return;g({isKilling:!0,current:1,total:O.length}),(async()=>{for(let j=0;j<O.length;j++){const k=O[j];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:k,commitSha:a||""})})}catch(Y){console.error(`Failed to kill process ${k}:`,Y)}j<O.length-1&&g({isKilling:!0,current:j+2,total:O.length})}g({isKilling:!1,current:0,total:0}),y.revalidate()})()},disabled:f.isKilling,className:"px-[8px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:"#991b1b",color:"white",fontSize:"12px",lineHeight:"15px",fontWeight:500,height:"27px",width:"114px"},children:f.isKilling?"Killing...":"Kill All Processes"})]})]}):d("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[d("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Ic,{size:24,style:{color:"#005C75"}})}),d("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Current Activity"}),d("p",{className:"text-sm",style:{color:"#8e8e8e"},children:["There are no analyses running. Trigger one from"," ",n(Ce,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(Ce,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),d(Ce,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]}),i&&i.length>0&&d("div",{children:[n("h3",{className:"font-mono uppercase",style:{fontSize:"12px",lineHeight:"18px",color:"#8e8e8e",marginBottom:"16px",fontWeight:500,letterSpacing:"0.05em"},children:"Recently Completed Analyses"}),d("div",{className:"flex flex-col gap-4",children:[(R?i:i.slice(0,3)).map(O=>{var j;const W=(j=O.analyses)==null?void 0:j[0],I=(W==null?void 0:W.scenarios)||[];return W==null||W.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:d("div",{className:"flex flex-col gap-[15px]",children:[d("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",children:n(ht,{type:O.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[d("div",{className:"flex items-center gap-[5px]",children:[n(Ce,{to:`/entity/${O.sha}`,className:"hover:underline cursor-pointer",title:O.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:O.name}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:"#e8ffe6",color:"#00925d",fontSize:"12px",lineHeight:"16px",fontWeight:400},children:O.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:O.filePath,children:O.filePath})]}),n("div",{className:"flex-1"}),n("div",{className:"flex-shrink-0",children:n("button",{onClick:o,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:k=>{k.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:k=>{k.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),I.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:I.map(k=>{var K,F,M;if(!k.id)return null;const Y=(F=(K=k.metadata)==null?void 0:K.screenshotPaths)==null?void 0:F[0],G=(M=k.metadata)==null?void 0:M.noScreenshotSaved,Q=Y&&!G;return d("div",{className:"shrink-0 flex flex-col gap-2",children:[n(Ce,{to:`/entity/${O.sha}/scenarios/${k.id}`,className:"block cursor-pointer",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{backgroundColor:Q?"#f3f4f6":"#FAFAFA",borderColor:Q?"#d1d5db":"#BCCDD3",borderStyle:Q?"solid":"dashed"},onMouseEnter:z=>{Q&&(z.currentTarget.style.borderColor="#005C75",z.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:z=>{z.currentTarget.style.borderColor=Q?"#d1d5db":"#BCCDD3",z.currentTarget.style.boxShadow="none"},children:Q?n(lt,{screenshotPath:Y,alt:k.name,className:"max-w-full max-h-full object-contain"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})})}),n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k.name})]},k.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},O.sha)}),i.length>3&&!R&&d("button",{onClick:()=>D(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",i.length-3," more"," ",i.length-3===1?"entity":"entities"]}),R&&i.length>3&&n("button",{onClick:()=>D(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})]})}function xS({queueJobs:e,state:t,currentRun:r}){if(!e||e.length===0)return d("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[d("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Vp,{size:24,style:{color:"#005C75"}})}),d("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Queued Jobs"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Analysis jobs will appear here when they are queued but not yet started."})]})]}),d(Ce,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[s,a]=P(null),[o,i]=P(null),[l,c]=P(null),[p,u]=P(!1),[h,m]=P(!1),[f,g]=P(new Set),y=Ut();ae(()=>{e.length<=3&&h&&m(!1)},[e.length,h]);const x=C=>{a(C)},b=(C,A)=>{C.preventDefault(),i(A)},w=async(C,A)=>{if(C.preventDefault(),!s){i(null);return}const _=e.findIndex(D=>D.id===s);if(_===-1){a(null),i(null);return}if(_===A){a(null),i(null);return}const E=_<A?"down":"up",R=Math.abs(A-_);u(!0);try{for(let D=0;D<R;D++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:s,direction:E})});y.revalidate()}catch(D){console.error("Failed to reorder job:",D)}finally{u(!1),a(null),i(null)}},v=()=>{p||(a(null),i(null))},N=async C=>{if(confirm("Are you sure you want to cancel this job?"))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"remove",jobId:C})}),window.location.reload()}catch(A){console.error("Failed to cancel job:",A)}},S=async()=>{if(confirm(`Are you sure you want to cancel all ${e.length} queued jobs?`))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}),window.location.reload()}catch(C){console.error("Failed to cancel jobs:",C)}};return d("div",{children:[d("div",{className:"flex items-center justify-between mb-4",children:[d("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:[e.length," Queued Job",e.length!==1?"s":""]}),e.length>0&&n("button",{onClick:()=>void S(),className:"px-[10px] py-0 rounded transition-colors cursor-pointer hover:bg-red-300",style:{backgroundColor:"#ffdcd9",color:"#ef4444",fontSize:"12px",fontWeight:500,height:"29px"},children:"Cancel All"})]}),d("div",{className:"flex flex-col gap-3",children:[(h?e:e.slice(0,3)).map(C=>{var $,L,B,H;const A=e.findIndex(q=>q.id===C.id),_=l===A,E=s===C.id,R=o===A,D=f.has(C.id),T=(($=C.entities)==null?void 0:$.length)>0?D?C.entities:C.entities.slice(0,3):[];return d("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:E||p?.5:1,transform:R&&s!==null&&!E?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:p?"not-allowed":E?"grabbing":"grab"},onMouseEnter:()=>c(A),onMouseLeave:()=>c(null),draggable:!p,onDragStart:q=>{x(C.id),q.dataTransfer.effectAllowed="move"},onDragOver:q=>b(q,A),onDrop:q=>void w(q,A),onDragEnd:v,children:[d("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(Gp,{size:16,style:{color:"#005C75"}}),d("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",A+1]})]}),d("div",{className:"flex flex-col gap-2 mt-8",children:[T.length>0?d(we,{children:[T.map(q=>n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(ht,{type:q.entityType||"other",size:"large"})}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(Ce,{to:`/entity/${q.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:q.name}),q.entityType&&n(bi,{type:q.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:q.filePath})]})]})})},q.sha)),((L=C.entities)==null?void 0:L.length)>3&&n("button",{onClick:()=>{g(q=>{const O=new Set(q);return O.has(C.id)?O.delete(C.id):O.add(C.id),O})},className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"40px",fontSize:"12px",color:"#646464",fontWeight:500},children:D?"Show less":`+${C.entities.length-3} more ${C.entities.length-3===1?"entity":"entities"}`})]}):n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(Ms,{size:18,style:{color:"#8e8e8e"}})}),d("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((B=C.entityNames)==null?void 0:B[0])||(C.type==="analysis"?"Analysis Job":C.type==="recapture"?"Recapture Job":C.type==="debug-setup"?"Debug Setup":C.type.charAt(0).toUpperCase()+C.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((H=C.filePaths)==null?void 0:H[0])||(C.filePaths&&C.filePaths.length>1?`${C.filePaths.length} files`:C.entityShas&&C.entityShas.length>0?`${C.entityShas.length} ${C.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),d("div",{className:"flex items-center justify-end gap-2 mt-1",children:[_&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(Kp,{size:20})}),n("button",{onClick:()=>void N(C.id),className:"transition-colors cursor-pointer hover:bg-red-100 rounded flex items-center justify-center",style:{fontSize:"10px",fontWeight:600,lineHeight:"22px",color:"#ef4444",backgroundColor:"#fef6f6",padding:"0 10px",height:"22px"},children:"Cancel"})]})]})]},C.id)}),e.length>3&&!h&&d("button",{onClick:()=>m(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",e.length-3," more"," ",e.length-3===1?"job":"jobs"]}),h&&e.length>3&&n("button",{onClick:()=>m(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})}function bS({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:s,tab:a,onShowLogs:o}){if(t===0)return d("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[d("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(qp,{size:24,style:{color:"#005C75"}})}),d("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Historic Activity"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Completed analyses will appear here for historical reference."})]})]}),d(Ce,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[i,l]=P(!1),c=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(h=>{c.push({...h,runCreatedAt:u.createdAt})})});const p=i?c:c.slice(0,3);return d("div",{className:"flex flex-col gap-4",children:[p.map(u=>{var g;const h=(g=u.analyses)==null?void 0:g[0],m=(h==null?void 0:h.scenarios)||[],f=!u.isUncommitted;return d("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[d("div",{className:"flex items-start justify-between mb-3",children:[d("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{children:n(ht,{type:u.entityType||"other",size:"large"})}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(Ce,{to:`/entity/${u.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:u.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:f?"#e8ffe6":"#fef3cd",color:f?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:f?"Up to date":"Out of date"})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},title:u.filePath,children:u.filePath})]})]}),n("button",{onClick:o,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),m.length>0&&d("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[m.slice(0,8).map(y=>{var v,N,S;if(!y.id)return null;const x=(N=(v=y.metadata)==null?void 0:v.screenshotPaths)==null?void 0:N[0],b=(S=y.metadata)==null?void 0:S.noScreenshotSaved,w=x&&!b;return n(Ce,{to:`/entity/${u.sha}/scenarios/${y.id}`,className:"border rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px",borderColor:w?"#ccc":"#BCCDD3",borderStyle:w?"solid":"dashed"},children:w?n(lt,{screenshotPath:x,alt:y.name,className:"w-full h-full object-cover bg-gray-100"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},y.id)}),m.length>8&&d("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",m.length-8," more"]})]})]},`${u.sha}-${u.runCreatedAt}`)}),c.length>3&&!i&&d("button",{onClick:()=>l(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",c.length-3," more"," ",c.length-3===1?"entity":"entities"]}),i&&c.length>3&&n("button",{onClick:()=>l(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})}const wS=et(function(){const t=st(),r=Tc(),[s,a]=P(!1);Dt({source:"activity-page"});const o=r.tab||"current";return t?d("div",{className:"px-20 py-12",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-[15px] text-gray-500",children:"View queued, current, and historical analysis activity."})]}),n(gS,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(yS,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>a(!0),recentCompletedEntities:t.recentCompletedEntities||[],hasMoreCompletedRuns:t.hasMoreCompletedRuns||!1,currentEntityScenarios:t.currentEntityScenarios||[],currentEntityForScenarios:t.currentEntityForScenarios,currentAnalysisStatus:t.currentAnalysisStatus}),o==="queued"&&n(xS,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(bS,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>a(!0)}),s&&t.projectSlug&&n(rn,{projectSlug:t.projectSlug,onClose:()=>a(!1)})]}):n("div",{className:"px-20 py-12",children:n("div",{className:"text-center",children:n("p",{className:"text-gray-600",children:"Loading..."})})})}),vS=Object.freeze(Object.defineProperty({__proto__:null,default:wS,loader:fS,meta:mS},Symbol.toStringTag,{value:"Module"}));async function ku(e,t,r){var N,S;await Je();const s=await Vt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const a=Ne();if(!a)throw new Error("Project root not found");const o=U.join(a,".codeyam","config.json"),i=JSON.parse(V.readFileSync(o,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const c=Lr(l);try{V.writeFileSync(c,"","utf8")}catch{}const{project:p}=await De(l),u=((N=p.metadata)==null?void 0:N.packageManager)||"npm",h=3112,m=It(l),f=((S=p.metadata)==null?void 0:S.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const g=i.environmentVariables||[],y=qm({filePath:s.filePath,webapps:f,environmentVariables:g,port:h,packageManager:u});await nr(e,C=>{if(C&&(C.readyToBeCaptured=!0,C.scenarios))for(const A of C.scenarios)(!t||A.name===t)&&(delete A.screenshotStartedAt,delete A.screenshotFinishedAt,delete A.interactiveStartedAt,delete A.interactiveFinishedAt,delete A.error,delete A.errorStack)});const{jobId:x}=r.enqueue({type:"debug-setup",commitSha:s.commit.sha,projectSlug:l,analysisId:e,scenarioId:t,prepOnly:!0}),b=y.startCommand,w={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:m}]},{heading:"What's Happening",items:[{content:"1. Preparing analyzer and dependencies"},{content:"2. Syncing project files"},{content:"3. Setting up mock environment"}]},{heading:"Next Steps (Once Complete)",items:[{label:"1. Open the project directory",content:`code ${m}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:b,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${h}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:m,projectSlug:l,port:h,packageManager:u,framework:y.framework,instructions:w}}async function NS({request:e,context:t}){const r=new URL(e.url),s=r.searchParams.get("analysisId"),a=r.searchParams.get("scenarioId")||void 0;if(!s)return re({error:"Missing analysisId parameter",usage:"GET /api/debug-setup?analysisId=<uuid>&scenarioId=<uuid>",example:'curl "http://localhost:3111/api/debug-setup?analysisId=f35509cb-b8f1-4d86-998e-fc24201ae2c7"'},{status:400});let o=t.analysisQueue;if(o||(o=await Gt()),!o)return re({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:s,scenarioId:a});try{const i=await ku(s,a,o);return re({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),re({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function SS({request:e,context:t}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Gt()),!r)return re({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a)return re({error:"Missing required field: analysisId"},{status:400});const i=await ku(a,o,r);return re({...i,success:!0,message:"Debug setup queued"})}catch(s){console.error("[Debug Setup API] Error during debug setup:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Debug Setup API] Error stack:",o),re({error:"Failed to setup debug environment",details:a},{status:500})}}const CS=Object.freeze(Object.defineProperty({__proto__:null,action:SS,loader:NS},Symbol.toStringTag,{value:"Module"}));function kS({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return new Response("Missing path parameter",{status:400});const s=Ne()||process.cwd(),a=U.resolve(s,r);if(!a.startsWith(s+U.sep)&&a!==s)return new Response("Path outside project root",{status:403});try{const o=V.readFileSync(a,"utf8");return new Response(o,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch{return new Response("File not found",{status:404})}}const _S=Object.freeze(Object.defineProperty({__proto__:null,loader:kS},Symbol.toStringTag,{value:"Module"})),ES=process.env.LABS_UNLOCK_SALT||"codeyam-labs-default-salt";function _u(e){const t=yh("sha256",ES);return t.update(e),`CY-${t.digest("hex").slice(0,16)}`}function AS(e,t){return t===_u(e)}async function PS({request:e}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});try{const r=(await e.formData()).get("unlockCode");if(!r)return re({success:!1,error:"Unlock code is required"},{status:400});const s=await Ye();return s?AS(s,r)?(await Gn({projectSlug:s,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),re({success:!0})):re({success:!1,error:"Invalid unlock code"},{status:400}):re({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("[Labs Unlock] Error:",t),re({success:!1,error:"Failed to validate unlock code. Please try again."},{status:500})}}const jS=Object.freeze(Object.defineProperty({__proto__:null,action:PS},Symbol.toStringTag,{value:"Module"}));async function TS({request:e,context:t}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Gt()),!r)return re({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("defaultWidth");if(!a||!o)return re({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return re({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${a} with width ${i}`);const l=await lv(a,i,r);return console.log("[API] Recapture queued",l),re({success:!0,message:"Recapture queued",...l})}catch(s){return console.log("[API] Error during recapture:",s),re({error:"Failed to recapture screenshots",details:s instanceof Error?s.message:String(s)},{status:500})}}const MS=Object.freeze(Object.defineProperty({__proto__:null,action:TS},Symbol.toStringTag,{value:"Module"}));function $S(e){if(e.length===0)throw new Error("paths array must not be empty");return e.map(IS).map(a=>a===""?[]:a.split("/")).reduce((a,o)=>{const i=[];for(let l=0;l<Math.min(a.length,o.length)&&a[l]===o[l];l++)i.push(a[l]);return i}).join("/")}function IS(e){const r=e.replace(/\/+$/,"").split("/");for(;r.length>0;){const s=r[r.length-1];if(RS(s))r.pop();else break}return r.join("/")}function RS(e){return!!(e.includes("*")||/\.\w+$/.test(e))}function DS({request:e}){const r=new URL(e.url).searchParams.getAll("paths");if(r.length===0)return Response.json({error:"Missing required query parameter: paths"},{status:400});const s=$S(r),a=s?`.claude/rules/${s}/`:".claude/rules/";return Response.json({result:a})}const FS=Object.freeze(Object.defineProperty({__proto__:null,loader:DS},Symbol.toStringTag,{value:"Module"}));function OS(e,t){var i,l,c,p,u;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,s=e.analyses&&e.analyses.length>0&&e.analyses.some(h=>h.scenarios&&h.scenarios.length>0);if(!r){const h=!!((l=e.metadata)!=null&&l.previousVersionWithAnalyses),m=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return h||m?s?{state:"committed_no_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Committed - Simulations Outdated",color:"text-orange-700",bgColor:"bg-orange-50",borderColor:"border-orange-300",icon:"⚠"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Yet Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}:s?{state:"committed_with_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up to date",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"✓"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}const a=!!((c=e.metadata)!=null&&c.previousCommittedSha);if(!!((p=e.metadata)!=null&&p.previousVersionWithAnalyses)||a){const h=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return s&&!h?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:s?{state:"uncommitted_outdated_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Edited - Simulations Outdated",color:"text-amber-700",bgColor:"bg-amber-50",borderColor:"border-amber-300",icon:"⚠"}}:{state:"uncommitted_outdated_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}else return s?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:{state:"uncommitted_no_previous_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"New",color:"text-purple-700",bgColor:"bg-purple-50",borderColor:"border-purple-200",icon:"+"}}}function LS(e){return OS(e).hasOutdatedSimulations}function xa(e,t,r,s,a){var q,O,W,I,j,k,Y,G;const o=(q=t==null?void 0:t.scenarios)==null?void 0:q.find(Q=>Q.name===e.name),i=!!(o!=null&&o.startedAt),l=!!(o!=null&&o.screenshotStartedAt),c=!!(o!=null&&o.screenshotFinishedAt),p=!!(o!=null&&o.finishedAt),u=1800*1e3,h=l&&!c&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,m=!!((W=(O=e.metadata)==null?void 0:O.screenshotPaths)!=null&&W[0])||!!((I=e.metadata)!=null&&I.executionResult),f=l&&!c,g=o==null?void 0:o.error,y=(k=(j=e.metadata)==null?void 0:j.executionResult)==null?void 0:k.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const Q of t.errors)x.push({source:`${Q.phase} phase`,message:Q.message});if(t!=null&&t.steps)for(const Q of t.steps)Q.error&&x.push({source:Q.name,message:Q.error});const b=!m&&!g&&!y&&x.length>0,w=!!(g||y||h||b),v=h?"Capture timed out after 30 minutes":(typeof g=="string"?g:null)||(y==null?void 0:y.message)||(b?`Analysis error: ${x[0].message}`:null),N=h?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(o==null?void 0:o.errorStack)||(y==null?void 0:y.stack)||null,C=(s&&a?a.jobs.some(Q=>{var K;return((K=Q.entityShas)==null?void 0:K.includes(s))||Q.type==="analysis"&&Q.entityShas&&Q.entityShas.length===0})||((G=(Y=a.currentlyExecuting)==null?void 0:Y.entityShas)==null?void 0:G.includes(s)):!1)&&!i&&!w||!!(o!=null&&o.analyzing)&&!i&&!w,A=i&&!l&&!p&&!w,_=(C||A||f)&&!w,E=(C||A)&&r===!1&&!m;let R;E?R="crashed":w?R="error":m||p?R="completed":f?R="capturing":A?R="starting":C?R="queued":R="pending";let D="📷",T="pending",$=!1,L=`Not captured: ${e.name}`;const B="border-gray-300",H=w||E?"bg-red-50":"bg-white";return w||E?(D="⚠️",T="error",L=`Error: ${E?"Analysis process crashed":v||"Unknown error"}`):C?(D="⋯",T="queued",L=`Queued: ${e.name}`):A?(D="⋯",T="starting",$=!0,L=`Starting server for ${e.name}...`):f&&!w?(D="⋯",T="capturing",$=!0,L=`Capturing ${e.name}...`):m&&(D="✓",T="completed",L=e.name),{hasError:w||E,errorMessage:E?"Analysis process crashed":v,errorStack:E?"Process terminated unexpectedly before completing analysis":N,isCapturing:f,isCaptured:m,hasCrashed:E,isAnalyzing:_,isQueued:C,isServerStarting:A,status:R,icon:D,iconType:T,shouldSpin:$,title:L,borderColor:B,bgColor:H}}function Eu({scenario:e,entitySha:t,size:r="medium",showBorder:s=!0,isOutdated:a=!1}){var N,S,C,A,_,E;const o=xa(e,void 0,void 0,t,void 0),i=(N=e.metadata)==null?void 0:N.executionResult,l=!!i,p=(((C=(S=e.metadata)==null?void 0:S.data)==null?void 0:C.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,h=((_=(A=i==null?void 0:i.sideEffects)==null?void 0:A.consoleOutput)==null?void 0:_.length)||0,m=((E=i==null?void 0:i.timing)==null?void 0:E.duration)||0;let f=0;p>0&&f++,p>2&&f++,u&&f++,h>0&&f++,f=Math.min(3,f);const g=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},x=o.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:l?a?{border:"border-amber-500",bg:"bg-amber-50",icon:"text-amber-700",badge:"bg-amber-100 text-amber-700"}:{border:"border-blue-400",bg:"bg-blue-50",icon:"text-blue-600",badge:"bg-blue-100 text-blue-700"}:{border:"border-gray-300 border-dashed",bg:"bg-gray-50",icon:"text-gray-400",badge:"bg-gray-100 text-gray-600"},b=s?`border-2 ${x.border}`:"",w=Array.from({length:3},(R,D)=>n("div",{className:`w-1 h-1 rounded-full ${D<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},D)),v=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:l?`${e.name}
482
+ ${p} args → ${u?"value":"void"}${h>0?` (${h} logs)`:""}
483
+ ${m}ms`:`Not executed: ${e.name}`;return d(Ce,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${g.width} ${g.height} ${b} rounded ${x.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:v,onClick:R=>R.stopPropagation(),children:[n("div",{className:`${x.icon} ${g.iconSize} font-mono font-bold`,children:o.hasError?"⚠":l?"ƒ":"○"}),l&&!o.hasError&&d("div",{className:`flex items-center gap-0.5 ${g.textSize} ${x.badge} px-1 rounded`,children:[n("span",{children:p}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),l&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:w}),l&&!o.hasError&&m>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${g.textSize} ${x.badge} px-1 rounded`,children:m>1e3?`${Math.round(m/1e3)}s`:`${m}ms`}),l&&!o.hasError&&h>0&&r==="medium"&&d("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",h]})]})}function ko({size:e=24,className:t=""}){return d("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:[n("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),n("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),n("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function Kl({scenario:e,entity:t,analysisStatus:r,queueState:s,processIsRunning:a,size:o="medium",cacheBuster:i,className:l="",viewMode:c}){var y,x;if(t.entityType==="library")return n(Eu,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=xa(e,r,a,t.sha,s),h=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},m=`relative ${h.containerClass} ${l}`,f=()=>{const b=`/entity/${t.sha}/scenarios/${e.id}`;return c?`${b}/${c}`:b};if(u.isCaptured){const b=(x=(y=e.metadata)==null?void 0:y.screenshotPaths)==null?void 0:x[0];return n(Ce,{to:f(),className:`${m} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(lt,{screenshotPath:b,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const g=()=>{const b={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},w=n(wi,{size:o});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return w;switch(u.iconType){case"starting":case"capturing":return w;case"error":return d("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(ko,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(Qp,{...b});default:return w}};return n(Ce,{to:f(),className:`${m} ${u.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:u.title,children:n("div",{className:h.iconSize,children:g()})})}const Wn=70;function BS({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:s,entitySha:a,cacheBuster:o,activeTab:i,entityType:l,entity:c,queueState:p,processIsRunning:u,isEntityAnalyzing:h,areScenariosStale:m,viewMode:f,setViewMode:g,isBreakdownView:y,onCreateScenario:x}){var L,B,H,q,O,W;const b=fe(null),[w,v]=P(new Set),[N,S]=P(!1);ae(()=>{b.current&&i==="scenarios"&&b.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[s==null?void 0:s.id,i]);const C=I=>`/entity/${a}/scenarios/${I}`,A=I=>{v(j=>{const k=new Set(j);return k.has(I)?k.delete(I):k.add(I),k})},_=(I,j=2)=>{const Y=I.split(`
484
+ `).slice(0,j).join(" ").trim();return Y.length>Wn?Y.substring(0,Wn-3):(I.split(`
485
+ `).length>j||I.length>Y.length,Y)},E=ie(()=>{var j;if(!((j=r==null?void 0:r.metadata)!=null&&j.executionFlows)||!(r!=null&&r.scenarios))return null;const I=r.scenarios.filter(k=>{var Y;return!((Y=k.metadata)!=null&&Y.sameAsDefault)});return hi(r.metadata.executionFlows,I)},[r]),R=(E==null?void 0:E.totalFlows)||0,D=(E==null?void 0:E.coveredFlows)||0,T=(E==null?void 0:E.coveragePercentage)||0;(L=c==null?void 0:c.metadata)!=null&&L.defaultWidth||(B=r==null?void 0:r.metadata)!=null&&B.defaultWidth;const $=(H=r==null?void 0:r.status)!=null&&H.finishedAt?new Date(r.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return d("aside",{className:"w-[250px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-4",children:[r&&e.length>0&&d("div",{className:"flex flex-col gap-2",children:[n("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),d("div",{className:"grid grid-cols-2 gap-2",children:[d(Ce,{to:y?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((q=e[0])==null?void 0:q.id)}`:`/entity/${a}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[d("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(T),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),d(Ce,{to:y?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((O=e[0])==null?void 0:O.id)}`:`/entity/${a}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[d("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[D,"/",R]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),d(Ce,{to:y?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((W=e[0])==null?void 0:W.id)}`:`/entity/${a}/scenarios/breakdown`,className:`border rounded px-3 py-2 no-underline hover:shadow-sm transition-shadow flex items-center justify-between ${y?"bg-[#CBF3FA] border-[#CBF3FA]":"bg-[#F6F9FC] border-[#E0E9EC]"}`,children:[n("div",{className:"text-[11px] text-[#005c75] font-normal uppercase font-mono underline",children:"EXECUTION FLOWS"}),y?n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M3 3L9 9M9 3L3 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),c&&c.filePath&&n("div",{children:n("button",{onClick:x,className:"w-full px-3 py-2 bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[11px] font-medium font-mono cursor-pointer transition-colors hover:bg-[#004a5e] flex items-center justify-center gap-1",children:"+ Create New Scenario"})}),e.length>0&&d("div",{className:"py-3 flex items-center justify-between",children:[d("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),$&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:$})]}),h&&(m||e.length===0)?d("div",{className:"",children:[d("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[d("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}),n("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):e.length===0?n("div",{className:"",children:n("p",{className:"text-[#8e8e8e] text-xs font-medium m-0 text-left leading-5",children:"No Scenarios"})}):n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"flex flex-col gap-[11.6px]",children:e.map((I,j)=>{const k=!y&&(s==null?void 0:s.id)===I.id,Y=w.has(I.id||"");return I.id?d(Ce,{to:C(I.id),ref:k?b:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${k?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[n("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:n(Kl,{scenario:I,entity:{sha:a,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:p,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),d("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${Y?"":"line-clamp-1"}`,children:I.name}),I.description&&n("div",{className:"mt-2",children:d("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[Y?I.description:_(I.description),!Y&&I.description.length>Wn&&d(we,{children:["...",n("button",{onClick:G=>{G.preventDefault(),G.stopPropagation(),A(I.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),Y&&I.description.length>Wn&&n("button",{onClick:G=>{G.preventDefault(),G.stopPropagation(),A(I.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},j):null})})}),t.length>0&&!(h&&m)&&d("div",{className:"border-t border-[#e1e1e1] pt-3",children:[d("button",{onClick:()=>S(!N),className:"flex items-center gap-1 text-[10px] text-[#626262] font-medium cursor-pointer bg-transparent border-none p-0 hover:text-[#005c75] transition-colors w-full",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`transition-transform ${N?"rotate-90":""}`,children:n("path",{d:"M3.5 2L6.5 5L3.5 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"Hidden Scenarios (",t.length,")"]}),N&&d("div",{className:"mt-2",children:[n("p",{className:"text-[10px] text-[#8e8e8e] leading-[14px] mb-3",children:"These scenarios were hidden because the screenshots did not differ from the Default Scenario."}),n("div",{className:"flex flex-col gap-[11.6px]",children:t.map((I,j)=>{const k=!y&&(s==null?void 0:s.id)===I.id,Y=w.has(I.id||"");return I.id?d(Ce,{to:`/entity/${a}/scenarios/${I.id}`,ref:k?b:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${k?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[n("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:n(Kl,{scenario:I,entity:{sha:a,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:p,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),d("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${Y?"":"line-clamp-1"}`,children:I.name}),I.description&&n("div",{className:"mt-2",children:d("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[Y?I.description:_(I.description),!Y&&I.description.length>Wn&&d(we,{children:["...",n("button",{onClick:G=>{G.preventDefault(),G.stopPropagation(),A(I.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),Y&&I.description.length>Wn&&n("button",{onClick:G=>{G.preventDefault(),G.stopPropagation(),A(I.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},j):null})})]})]})]})}function zS({scenario:e,entitySha:t,onApply:r,onSave:s,onEditMockData:a,onDelete:o,isApplying:i=!1,isSaving:l=!1,saveMessage:c=null,showDeleteConfirm:p=!1,onShowDeleteConfirm:u,isDeleting:h=!1,deleteError:m=null}){const[f,g]=P(""),y=async()=>{await r(f)},x=async b=>{await s(f,b),b||g("")};return d("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[d("div",{className:"border-b border-[#e1e1e1] pb-3",children:[d("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(Ce,{to:`/entity/${t}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),n("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),d("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[d("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange:b=>g(b.target.value),placeholder:"e.g. change amount of data to zero",className:"w-full px-[7px] py-[6px] border border-[#c7c7c7] rounded-[4px] text-xs focus:outline-none focus:ring-1 focus:ring-[#005c75] focus:border-[#005c75] resize-none",rows:4}),d("button",{onClick:()=>void y(),disabled:i||!f.trim(),className:"w-full mt-1 h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center gap-1",children:[i&&d("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),i?"Applying...":"Apply"]})]}),n("div",{className:"border-t border-[#e1e1e1] my-1"}),d("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick:a,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),c&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${c.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:c}),c==="Recapture successful"&&n("div",{children:n(Ce,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),d("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[n("button",{onClick:()=>void x(!1),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center",children:l?"Saving...":"Save Scenario Data"}),n("button",{onClick:()=>void x(!0),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:"Save As New"}),o&&d(we,{children:[p?d("div",{className:"flex flex-col gap-1",children:[d("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),d("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void o(),disabled:h,className:"flex-1 h-[22px] bg-red-600 text-white rounded text-[10px] font-normal hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors flex items-center justify-center cursor-pointer",children:h?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>u==null?void 0:u(!1),disabled:h,className:"flex-1 h-[22px] bg-gray-100 text-gray-700 border border-gray-300 rounded text-[10px] font-normal hover:bg-gray-200 disabled:opacity-50 transition-colors flex items-center justify-center cursor-pointer",children:"Cancel"})]})]}):n("button",{onClick:()=>u==null?void 0:u(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),m&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:m})]})]})]})}function YS({scenario:e,analysis:t,entity:r}){var i,l,c;const s=((i=e.metadata)==null?void 0:i.executionResult)||null,a=((c=(l=e.metadata)==null?void 0:l.data)==null?void 0:c.argumentsData)||[],o=p=>{var g,y,x;if(!p)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const u=[],h=((g=p.sideEffects)==null?void 0:g.consoleOutput)||[];h.length>0&&(u.push(`Console Output: ${h.length} log ${h.length===1?"entry":"entries"} captured`),h.forEach(b=>{u.push(` [${b.level.toUpperCase()}] ${b.args.join(" ")}`)}));const m=((y=p.sideEffects)==null?void 0:y.fileWrites)||[];m.length>0&&(u.push(`
486
+ File System Operations: ${m.length} ${m.length===1?"operation":"operations"} detected`),m.forEach(b=>{u.push(` ${b.operation}: ${b.path}${b.size?` (${b.size} bytes)`:""}`)}));const f=((x=p.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(u.push(`
487
+ API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(b=>{u.push(` ${b.method} ${b.url}${b.status?` → ${b.status}`:""}${b.duration?` (${b.duration}ms)`:""}`)})),p.error&&u.push(`
488
+ Error: ${p.error.name||"Error"}: ${p.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
489
+ `)};return d("div",{className:"flex w-full h-full gap-0",children:[d("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(a,null,2)})})]}),d("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:s?n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:s.returnValue!==void 0?JSON.stringify(s.returnValue,null,2):"undefined"}):n("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),d("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:o(s)})})]})]})}const xn={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function xs({scenarioId:e,analysisId:t}){const[r,s]=P(!1),[a,o]=P(!1),[i,l]=P(null),[c,p]=P(!1),u=e||t;if(!u)return null;const h=`/codeyam-diagnose ${u}`,m=async()=>{o(!0);try{const{default:g}=await import("html2canvas-pro"),x=(await g(document.body,{scale:.5})).toDataURL("image/jpeg",.8);l(x),s(!0)}catch(g){console.error("Screenshot capture failed:",g),s(!0)}finally{o(!1)}},f=()=>{s(!1),l(null)};return d(we,{children:[d("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[n("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:xn.heading},children:"Claude can help debug this error."}),n("p",{className:"m-0 mb-4 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"18px",color:xn.subtext},children:"Simply run this command in Claude Code:"}),d("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:xn.commandBoxBg,borderColor:xn.commandBoxBorder,maxWidth:"505px",height:"35px",paddingLeft:"13px",paddingRight:"13px",paddingTop:"6px",paddingBottom:"6px"},children:[n("code",{className:"font-mono font-['IBM_Plex_Mono'] flex-1 text-left",style:{fontSize:"12px",lineHeight:"20px",color:xn.commandBoxText},children:h}),n("button",{onClick:g=>{g.stopPropagation(),navigator.clipboard.writeText(h),p(!0),setTimeout(()=>p(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:c?"#22c55e":xn.commandBoxText},title:c?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:c?n(kt,{size:14}):n($t,{size:14})})]}),d("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",n("button",{onClick:()=>void m(),disabled:a,className:"underline cursor-pointer bg-transparent border-none p-0 font-normal hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:xn.link},children:a?"capturing...":"please do so here"}),"."]})]}),n(zc,{isOpen:r,onClose:f,context:{source:e?"scenario-page":"entity-page",entitySha:void 0,scenarioId:e,analysisId:t,currentUrl:typeof window<"u"?window.location.pathname:"/"},screenshotDataUrl:i??void 0})]})}const ql=1440,bs=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],zt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function Au({selectedScenario:e,analysis:t,entity:r,viewMode:s,cacheBuster:a,hasScenarios:o,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:c=!0,processIsRunning:p,queueState:u}){var J,te,oe,de,ue,me,Se,Te,$e,Re,X;const h=Ke(),[m,f]=P(!1),[g,y]=P(!1),[x,b]=P({name:"Desktop",width:ql,height:900}),[w,v]=P(ql),[N,S]=P(1),{customSizes:C,addCustomSize:A,removeCustomSize:_}=oa(l),E=ie(()=>[...bs,...C],[C]),R=(ye,ee)=>{v(ye);const ne=E.find(xe=>xe.width===ye&&xe.height===ee);b({name:(ne==null?void 0:ne.name)||"Custom",width:ye,height:ee})},D=ye=>{v(ye.width),b({name:ye.name,width:ye.width,height:ye.height})},T=ye=>{A(ye,x.width,x.height??900),y(!1),b(ee=>({...ee,name:ye}))},$=(ye,ee)=>{v(ye);const ne=E.find(xe=>xe.width===ye&&xe.height===ee);b(xe=>({name:(ne==null?void 0:ne.name)||"Custom",width:ye,height:xe.height}))},L=(te=(J=e==null?void 0:e.metadata)==null?void 0:J.screenshotPaths)==null?void 0:te[0],B=ie(()=>e?xa(e,t==null?void 0:t.status,p,r==null?void 0:r.sha,u):null,[e,t==null?void 0:t.status,p,r==null?void 0:r.sha,u]),H=ie(()=>{var ee,ne;const ye=[];if((ee=t==null?void 0:t.status)!=null&&ee.errors&&t.status.errors.length>0)for(const xe of t.status.errors)ye.push({source:`${xe.phase} phase`,message:xe.message,stack:xe.stack});if((ne=t==null?void 0:t.status)!=null&&ne.steps)for(const xe of t.status.steps)xe.error&&ye.push({source:xe.name,message:xe.error,stack:xe.errorStack});return ye},[(oe=t==null?void 0:t.status)==null?void 0:oe.errors,(de=t==null?void 0:t.status)==null?void 0:de.steps]),q=(B==null?void 0:B.errorMessage)||null,O=(B==null?void 0:B.errorStack)||null,{interactiveServerUrl:W,isStarting:I,isLoading:j,showIframe:k,iframeKey:Y,onIframeLoad:G}=jn({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:l,enabled:s==="interactive"}),Q=ie(()=>W||null,[W]),K=!i&&o&&e&&!((me=(ue=e.metadata)==null?void 0:ue.screenshotPaths)!=null&&me[0])&&((Te=(Se=t==null?void 0:t.status)==null?void 0:Se.scenarios)==null?void 0:Te.some(ye=>ye.name===e.name&&ye.screenshotStartedAt&&!ye.screenshotFinishedAt)),{lastLine:F}=Jt(l,i||s==="interactive"||K||!1);if(!e){if(i&&r)return d(we,{children:[n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:d("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:K?"Capturing screenshots...":"Analyzing..."}),n("p",{className:"text-xs text-[#8e8e8e] text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:"This may take a few minutes."}),F&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:F}),l&&n("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})}),m&&l&&n(rn,{projectSlug:l,onClose:()=>f(!1)})]});if(!o&&r&&!i){if(H.length>0){const ye=H.length===1?(($e=H[0])==null?void 0:$e.message)||"An error occurred during analysis.":`${H.length} errors occurred during analysis.`;return d(we,{children:[n("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:d("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded",style:{backgroundColor:zt.background,border:`2px solid ${zt.border}`},role:"alert",children:d("div",{className:"flex items-center gap-3",children:[n(ko,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:d("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:zt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",ye," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:zt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(xs,{analysisId:t==null?void 0:t.id})})]})}),m&&l&&n(rn,{projectSlug:l,onClose:()=>f(!1)})]})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:d("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{h.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:h.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:h.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return d(we,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
490
+ linear-gradient(45deg, #ebebeb 25%, transparent 25%),
491
+ linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
492
+ linear-gradient(45deg, transparent 75%, #ebebeb 75%),
493
+ linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
494
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||K&&!L)&&!q&&s==="screenshot"?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-linear-to-br from-blue-50 to-indigo-50",children:d("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[d("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:K?`Capturing ${r==null?void 0:r.name}`:`Analyzing ${r==null?void 0:r.name}`}),n("p",{className:"text-base text-gray-600 leading-relaxed m-0 mb-2",children:K?`Taking screenshots for ${((Re=t==null?void 0:t.scenarios)==null?void 0:Re.length)||0} scenario${((X=t==null?void 0:t.scenarios)==null?void 0:X.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&d("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),F&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:d("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),d("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:F,children:F})]})]})}),l&&n("button",{onClick:()=>f(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),n("p",{className:"text-xs text-gray-500 mt-8 m-0",children:"Screenshots will appear here as they are captured. This may take a few minutes."})]})}):s==="screenshot"&&(L||q)||s==="interactive"&&(Q||I)||s==="data"?d(we,{children:[q&&!L&&n("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:d("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:zt.background,border:`2px solid ${zt.border}`,maxHeight:"50vh"},role:"alert",children:d("div",{className:"flex flex-col gap-3",children:[d("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:zt.text},children:[n(ko,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),d("div",{className:"text-center",children:[n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:zt.link},children:"See logs"})," ","for details."]}),n("div",{className:"flex-1 min-w-0",children:n("div",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:zt.text},children:q})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(xs,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),s==="interactive"?d("div",{className:"flex-1 flex flex-col min-h-0",children:[Q&&d("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center items-center gap-4",children:[n(Ny,{presets:[...bs],customSizes:C,currentWidth:x.width,currentHeight:x.height??900,scale:N,onSizeChange:R,onSaveCustomSize:()=>y(!0),onRemoveCustomSize:_}),e&&r&&d(Ce,{to:`/entity/${r.sha}/scenarios/${e.id}/fullscreen?from=${encodeURIComponent(`/entity/${r.sha}/scenarios/${e.id}/interactive`)}`,className:"flex items-center gap-2 px-4 py-2 bg-[#005c75] text-white rounded hover:bg-[#004a5c] transition-colors text-sm font-medium no-underline",title:"Open in fullscreen",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:n("path",{d:"M2 5V2H5M11 2H14V5M14 11V14H11M5 14H2V11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Fullscreen"]})]}),Q&&n("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${bs[bs.length-1].width}px`,width:"100%"},children:n(Go,{currentViewportWidth:w,currentPresetName:x.name,onDevicePresetClick:D,devicePresets:E})})}),n(ga,{scenarioId:e.id,scenarioName:e.name,iframeUrl:Q,isStarting:I,isLoading:j,showIframe:k,iframeKey:Y,onIframeLoad:G,onScaleChange:S,onDimensionChange:$,projectSlug:l,defaultWidth:x.width,defaultHeight:x.height})]}):s==="data"?n("div",{className:"flex-1 min-h-0",children:n(YS,{scenario:e,analysis:t,entity:r})}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 p-6 flex items-center justify-center",children:n("div",{className:"transition-all duration-300",style:{maxWidth:`${w}px`},children:(L||!q)&&n(lt,{screenshotPath:L,cacheBuster:a,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!L?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),d("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),d("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),F&&d("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:F})]}),l&&n("button",{onClick:()=>f(!0),className:"mt-4 px-4 py-2 bg-[#005c75] text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-[#004a5e]",children:"📋 View Full Logs"})]})]})})}):q?d("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!c&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:d("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[d("div",{className:"flex items-start gap-4",children:[n("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),d("div",{className:"bg-white border border-blue-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-blue-900 m-0 mb-2 uppercase tracking-wide",children:"CodeYam requires an AI API key for reliable analysis."}),d("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[n("li",{children:"You can use API keys for a variety of models"}),n("li",{children:"Faster analysis processing"}),n("li",{children:"Better handling of complex code structures"}),n("li",{children:"Improved scenario generation quality"})]})]}),n(Ce,{to:"/settings",className:"inline-block px-4 py-2 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700",children:"🔐 Configure API Keys"})]})}),n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),d("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),d("div",{className:"bg-white border border-red-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),n("div",{className:"max-h-[300px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:q})})]}),O&&d("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:O})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(xs,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):H.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),d("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:H,title:"Analysis Error",description:H.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${H.length} errors occurred during analysis. Screenshot capture was not completed.`}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(xs,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):d("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),m&&l&&n(rn,{projectSlug:l,onClose:()=>f(!1)}),g&&n(Ko,{width:x.width,height:x.height??900,onSave:T,onCancel:()=>y(!1)})]})}function WS({analysis:e,entitySha:t,onCreateScenario:r}){Ut();const[s,a]=P(e);ae(()=>{a(e)},[e]);const[o,i]=P(null),l=ie(()=>{var m;if(!((m=s==null?void 0:s.metadata)!=null&&m.executionFlows)||!(s!=null&&s.scenarios))return null;const h=s.scenarios.filter(f=>{var g;return!((g=f.metadata)!=null&&g.sameAsDefault)});return hi(s.metadata.executionFlows,h)},[s]),c=ie(()=>l?hx(l):[],[l]),p=ie(()=>s!=null&&s.scenarios?s.scenarios.filter(h=>{var m;return!((m=h.metadata)!=null&&m.sameAsDefault)}):[],[s]),u=h=>{var f;const m=((f=h.metadata)==null?void 0:f.coveredFlows)||[];return l?l.executionFlows.filter(g=>m.includes(g.id)):[]};return s?!l||l.executionFlows.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:d("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:d("div",{className:"p-6 space-y-6",children:[d("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),d("div",{className:"grid grid-cols-4 gap-4 text-center",children:[d("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:p.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:l.executionFlows.length}),n("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[d("div",{className:"text-2xl font-bold text-gray-900",children:[l.coveredFlows,"/",l.totalFlows]}),n("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[d("div",{className:`text-2xl font-bold ${l.coveragePercentage===100?"text-green-600":l.coveragePercentage>=50?"text-amber-600":"text-red-600"}`,children:[l.coveragePercentage.toFixed(0),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),d("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:d("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",p.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:p.length===0?d("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",n("button",{onClick:r,className:"text-blue-600 hover:underline bg-transparent border-none cursor-pointer p-0 text-sm",children:"Create one"})]}):p.map(h=>{var g,y,x;const m=(y=(g=h.metadata)==null?void 0:g.screenshotPaths)==null?void 0:y[0],f=u(h);return d("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(lt,{screenshotPath:m,alt:h.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),d("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:d("div",{children:[n(Ce,{to:`/entity/${t}/scenarios/${h.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:h.name}),((x=h.metadata)==null?void 0:x.error)&&n("span",{className:"ml-2 text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"Error"})]})}),n("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:h.description}),f.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:f.map(b=>n("span",{className:`text-xs px-1.5 py-0.5 rounded ${b.isError?"bg-red-50 text-red-700":b.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:b.name},b.id))})]})]},h.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:d("button",{onClick:r,className:"w-full px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 flex items-center justify-center gap-2 border-none cursor-pointer",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),c.length>0&&d("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[d("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[c.length," uncovered execution flow",c.length>1?"s":""," — consider adding scenarios to cover these"]}),d("div",{className:"flex flex-wrap gap-1",children:[c.slice(0,10).map(h=>d("span",{className:`text-xs px-2 py-0.5 rounded ${h.impact==="high"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[h.name,h.impact==="high"&&" (high impact)"]},h.id)),c.length>10&&d("span",{className:"text-xs text-amber-600",children:["+",c.length-10," more"]})]})]}),d("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:d("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",l.executionFlows.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:l.executionFlows.map(h=>{const m=o===h.id,f=h.usedInScenarios.length>0;return d("div",{children:[n("button",{onClick:()=>i(m?null:h.id),className:"w-full px-4 py-3 flex items-start justify-between text-left bg-transparent border-none cursor-pointer hover:bg-gray-50",children:d("div",{className:"flex items-start gap-3 flex-1",children:[n("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:m?"▼":"▶"}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-medium text-sm text-gray-900",children:h.name}),f?n("span",{className:"text-xs px-2 py-0.5 rounded bg-green-100 text-green-700",children:"Covered"}):n("span",{className:"text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700",children:"Uncovered"}),h.blocksOtherFlows&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),h.impact==="high"&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),h.isError&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),h.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:h.description})]})]})}),m&&d("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[h.requiredValues.length>0&&d("div",{className:"mb-4",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),n("div",{className:"space-y-1",children:h.requiredValues.map((g,y)=>d("div",{className:"flex items-center gap-2 text-xs",children:[n("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children:g.attributePath}),n("span",{className:"text-gray-400",children:g.comparison}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:g.value})]},y))})]}),f&&d("div",{children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),n("div",{className:"flex flex-wrap gap-1",children:h.usedInScenarios.map(g=>n("span",{className:"text-xs px-1.5 py-0.5 bg-green-50 text-green-700 rounded",children:g.name},g.id))})]}),h.codeSnippet&&d("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:h.codeSnippet})})]})]})]},h.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:d("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function Ql({hasIndirectBadge:e,onAnalyze:t}){return d(we,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:d("div",{className:"flex items-center justify-end gap-2",children:[e&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:"0 scenarios"})]})}),d("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[n("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),n("button",{className:"px-[15px] py-0 h-[23px] bg-[#005c75] text-white rounded text-xs font-medium leading-5 border-none cursor-pointer hover:bg-[#004a5e] transition-colors flex items-center justify-center",onClick:t,children:"Analyze"})]})]})}function US({entity:e,history:t}){const[r,s]=P("entity"),[a,o]=P(new Set),i=t.filter(u=>u.analyses.length>0).length,l=ie(()=>{const u=new Map;return t.forEach(h=>{h.analyses.forEach(m=>{(m.scenarios??[]).filter(g=>{var y;return!((y=g.metadata)!=null&&y.sameAsDefault)}).forEach(g=>{u.has(g.name)||u.set(g.name,[]),u.get(g.name).push({version:h,analysis:m,scenario:g})})})}),Array.from(u.entries()).map(([h,m])=>{var f;return{name:h,description:((f=m[0])==null?void 0:f.scenario.description)||"",versions:m.sort((g,y)=>{const x=new Date(g.analysis.createdAt||0).getTime();return new Date(y.analysis.createdAt||0).getTime()-x})}})},[t]),c=l.length,p=u=>{o(h=>{const m=new Set(h);return m.has(u)?m.delete(u):m.add(u),m})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:d("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:d("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[d("button",{onClick:()=>s("entity"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="entity"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-semibold leading-6",children:"Entity History"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="entity"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:i})]}),d("button",{onClick:()=>s("scenarios"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="scenarios"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-normal leading-6",children:"Scenario Changes"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="scenarios"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:c})]})]})}),t.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):r==="entity"?d("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((u,h)=>d("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center gap-3",children:[u.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),d(Ce,{to:`/entity/${u.sha}/scenarios`,className:"text-xs font-mono text-[#646464] leading-5 hover:text-[#005c75] transition-colors",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:u.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:u.createdAt&&new Date(u.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),u.analyses.length>0?n("div",{children:u.analyses.map((m,f)=>{var y;const g=(m.scenarios??[]).filter(x=>{var b;return!((b=x.metadata)!=null&&b.sameAsDefault)});return n("div",{children:g.length===0?n(Ql,{hasIndirectBadge:m.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):d(we,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:d("div",{className:"flex items-center justify-end gap-2",children:[m.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),d("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[g.length," scenario",g.length!==1?"s":""]})]})}),((y=m.metadata)==null?void 0:y.scenarioChangesOverview)&&n("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:d("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[d("span",{className:"font-medium",children:["What Changed:"," "]}),m.metadata.scenarioChangesOverview]})}),g.length>0&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:g.map((x,b)=>{var N,S;const w=(S=(N=x.metadata)==null?void 0:N.screenshotPaths)==null?void 0:S[0],v=`${x.name}-${b}`;return d(Ce,{to:`/entity/${u.sha}/scenarios/${x.id}`,className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden hover:border-[#005c75] hover:shadow-sm transition-all",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:w?n(lt,{screenshotPath:w,alt:x.name,className:"max-w-full max-h-full object-contain rounded-sm"}):d("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:x.name})})]},v)})})})]})},m.id||f)})}):n(Ql,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:l.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):l.map((u,h)=>{const m=a.has(u.name),f=m?u.versions:u.versions.slice(0,1),g=u.versions.length-1,y=u.versions[0];return y==null||y.version.sha,e==null||e.sha,d("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),d("div",{className:"p-5 bg-white",children:[f.map((x,b)=>{var A,_;const{version:w,analysis:v,scenario:N}=x,S=(_=(A=N.metadata)==null?void 0:A.screenshotPaths)==null?void 0:_[0],C=b===0;return d("div",{className:`flex gap-5 items-start ${C?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(Ce,{to:`/entity/${w.sha}/scenarios/${N.id}`,className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0 hover:border-[#005c75] hover:shadow-sm transition-all",children:S?n(lt,{screenshotPath:S,alt:N.name,className:"max-w-full max-h-full object-contain rounded-sm"}):d("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),d("div",{className:"flex-1 flex flex-col gap-2",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[w.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),C&&u.versions.length>1&&d("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[u.versions.length," versions"]})]}),d(Ce,{to:`/entity/${w.sha}/scenarios`,className:"text-xs font-mono text-[#646464] m-0 leading-5 hover:text-[#005c75] transition-colors w-fit",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:w.sha.substring(0,8)})]}),v.createdAt&&d("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(v.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),v.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${w.sha}-${b}`)}),g>0&&d("button",{onClick:()=>p(u.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${m?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),m?"Hide":`${g} previous version${g!==1?"s":""}`]})]})]})]},u.name)})})]})})}function Zl({entity:e,analysisInfo:t,from:r}){const s=Ke(),a=s.state!=="idle",o=e.entityType==="visual"||e.entityType==="library",i=l=>{l.preventDefault(),l.stopPropagation(),o&&s.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(Ce,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:d("div",{className:"flex gap-0 border border-gray-200 rounded-lg overflow-hidden transition-all hover:border-[#005c75] hover:shadow-md bg-white h-[100px]",children:[e.screenshotPath?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(lt,{screenshotPath:e.screenshotPath,alt:e.name,className:"max-w-full max-h-full object-contain"})}):n("div",{className:"w-[125px] h-full bg-[#efefef] flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n("span",{className:"text-[40px]",children:n(ht,{type:e.entityType})})}),d("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(ht,{type:e.entityType}),n("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),n("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),t.hasScenarios&&d("div",{className:"flex items-center gap-2 mt-2",children:[d("span",{className:"px-[5px] py-0 bg-[#efefef] text-[#3e3e3e] rounded text-[10px] font-medium",children:[t.scenarioCount," scenarios"]}),n("span",{className:"text-xs text-[#8e8e8e]",children:t.timestamp})]})]}),n("div",{className:"shrink-0 ml-4",children:t.status==="not_analyzed"?d(we,{children:[d("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:a,children:a?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?d("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):d(we,{children:[d("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:a,children:a?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const Xl=e=>{var a,o,i;const t=((a=e.analysisStatus)==null?void 0:a.status)||"not_analyzed",r=((o=e.analysisStatus)==null?void 0:o.scenarioCount)||0,s=(i=e.analysisStatus)==null?void 0:i.timestamp;return t==="not_analyzed"?{status:"not_analyzed",label:"Not analyzed",color:"gray"}:t==="up_to_date"?{status:"up_to_date",label:"Up to date",color:"green",hasScenarios:r>0,scenarioCount:r,timestamp:s}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:r>0,scenarioCount:r,timestamp:s}};function JS({importedEntities:e,importingEntities:t}){const[r]=Zn(),s=r.get("from"),a=Ke(),o=a.state!=="idle",i=e.length>0,l=t.length>0,c=m=>m.filter(f=>f.entityType==="visual"||f.entityType==="library"),p=m=>{const f=c(m);f.length!==0&&a.submit({entityShas:f.map(g=>g.sha).join(",")},{method:"post",action:"/api/analyze"})},u=c(e).length>0,h=c(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-6 py-4 flex items-start justify-between",children:[d("div",{children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&n("button",{onClick:()=>p(e),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(m=>n(Zl,{entity:m,analysisInfo:Xl(m),from:s},m.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-6 py-4 flex items-start justify-between",children:[d("div",{children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),h&&n("button",{onClick:()=>p(t),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),l?n("div",{className:"p-6 space-y-4",children:t.map(m=>n(Zl,{entity:m,analysisInfo:Xl(m),from:s},m.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px] text-center",children:"Not imported by any entity."})})]})]})})}function HS({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(JS,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function VS({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(Ir,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function Ir({data:e,depth:t,defaultExpanded:r,maxDepth:s,objectKey:a,showInlineToggle:o=!1}){const[i,l]=P(r||t<2);if(ae(()=>{l(r||t<2)},[r,t]),e===null)return n("span",{className:"text-gray-500",children:"null"});if(e===void 0)return n("span",{className:"text-gray-500",children:"undefined"});const c=typeof e;if(c==="string")return d("span",{className:"text-green-600",children:['"',e,'"']});if(c==="number")return n("span",{className:"text-blue-600",children:e});if(c==="boolean")return n("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?n("span",{className:"text-gray-600",children:"[]"}):d("span",{children:[d("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[d("span",{children:[i?"▼":"▶"," ","["]}),!i&&d("span",{children:[e.length,"]"]})]}),i?d(we,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((p,u)=>n("div",{className:"py-0.5",children:n(Ir,{data:p,depth:t+1,defaultExpanded:r,maxDepth:s})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(c==="object"){const p=Object.keys(e);if(p.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=m=>m!==null&&typeof m=="object"&&!Array.isArray(m)&&Object.keys(m).length>0,h=m=>Array.isArray(m)&&m.length>0;return d("span",{children:[d("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[d("span",{children:[i?"▼":"▶"," ","{"]}),!i&&d("span",{children:[p.length,"}"]})]}),i?d(we,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:p.map(m=>{const f=e[m],g=u(f),y=h(f);return n("div",{className:"py-0.5",children:g?n(vi,{propertyKey:m,value:f,depth:t,defaultExpanded:r,maxDepth:s}):y?n(Ni,{propertyKey:m,value:f,depth:t,defaultExpanded:r,maxDepth:s}):d(we,{children:[d("span",{className:"text-orange-600",children:[m,": "]}),n(Ir,{data:f,depth:t+1,defaultExpanded:r,maxDepth:s})]})},m)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function vi({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=P(s||r<2),l=Object.keys(t);return ae(()=>{i(s||r<2)},[s,r]),d(we,{children:[d("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),d("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&d("span",{className:"text-gray-600",children:[l.length,"}"]})]}),o&&d(we,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:l.map(c=>{const p=t[c],u=p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,h=Array.isArray(p)&&p.length>0;return n("div",{className:"py-0.5",children:u?n(vi,{propertyKey:c,value:p,depth:r+1,defaultExpanded:s,maxDepth:a}):h?n(Ni,{propertyKey:c,value:p,depth:r+1,defaultExpanded:s,maxDepth:a}):d(we,{children:[d("span",{className:"text-orange-600",children:[c,": "]}),n(Ir,{data:p,depth:r+2,defaultExpanded:s,maxDepth:a})]})},c)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function Ni({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=P(s||r<2);return ae(()=>{i(s||r<2)},[s,r]),d(we,{children:[d("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),d("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&d("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&d(we,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((l,c)=>{const p=l!==null&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,u=Array.isArray(l)&&l.length>0;return n("div",{className:"py-0.5",children:p?n(vi,{propertyKey:c.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:a}):u?n(Ni,{propertyKey:c.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:a}):n(Ir,{data:l,depth:r+2,defaultExpanded:s,maxDepth:a})},c)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function to({label:e,count:t,isActive:r,onClick:s,badgeColorActive:a,badgeTextActive:o}){return d("button",{onClick:s,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${a} ${o}`:"bg-gray-200 text-gray-700"}`,children:t}),r&&n("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function ec({label:e,isActive:t,onClick:r,disabled:s=!1}){return n("button",{onClick:r,className:`w-full text-left px-3 py-2.5 rounded-md transition-all text-sm cursor-pointer ${t?"bg-[#f6f9fc] text-[#005c75] font-medium border-l-2 border-[#005c75] pl-[10px]":"text-[#3e3e3e] hover:bg-gray-50"}`,disabled:s,children:e})}function tc({call:e,scenarioName:t}){const[r,s]=P(!1),[a,o]=P("system"),i=m=>new Date(m).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),l=m=>m?`$${m.toFixed(4)}`:null,c=(m,f)=>{if(!m&&!f)return null;const g=[];return m&&g.push(`${m.toLocaleString()} in`),f&&g.push(`${f.toLocaleString()} out`),g.join(" / ")},p=ie(()=>{var m,f,g,y,x;try{const b=JSON.parse(e.response);return(g=(f=(m=b.choices)==null?void 0:m[0])==null?void 0:f.message)!=null&&g.content?b.choices[0].message.content:(x=(y=b.content)==null?void 0:y[0])!=null&&x.text?b.content[0].text:e.response}catch{return e.response}},[e.response]),u=ie(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),h=ie(()=>{var m;if(t)return t;try{const f=JSON.parse(e.props);return((m=f==null?void 0:f.scenario)==null?void 0:m.name)||null}catch{return null}},[e.props,t]);return d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>s(!r),children:d("div",{className:"flex items-start justify-between gap-4",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),h&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:h}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),d("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),c(e.input_tokens,e.output_tokens)&&n("span",{children:c(e.input_tokens,e.output_tokens)}),l(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:l(e.cost)})]}),d("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.object_id,"_",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&d("div",{className:"border-t border-[#e1e1e1]",children:[d("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>o("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>o("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>o("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),a&&d("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[a==="system"&&n("div",{children:e.system_message?n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.system_message}):n("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),a==="prompt"&&n("div",{children:n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.prompt_text})}),a==="response"&&d("div",{children:[e.error&&d("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:p})]}),a==="props"&&n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),e.error&&!a&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:d("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const nc=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function GS({entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a}){var v,N,S,C,A,_,E,R,D;const[o,i]=P("entity"),[l,c]=P("analysis"),[p,u]=P(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[h,m]=P("entity"),{entityLlmCalls:f,scenarioLlmCalls:g,totalLlmCalls:y}=ie(()=>{if(!a)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const T=[...a.entityCalls,...a.analysisCalls],$=T.filter(B=>B.object_type==="entity"||nc.includes(B.prompt_type)),L=T.filter(B=>B.object_type!=="entity"&&!nc.includes(B.prompt_type));return $.sort((B,H)=>H.created_at-B.created_at),L.sort((B,H)=>H.created_at-B.created_at),{entityLlmCalls:$,scenarioLlmCalls:L,totalLlmCalls:T.length}},[a]),x=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(v=e==null?void 0:e.metadata)==null?void 0:v.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(N=t==null?void 0:t.metadata)==null?void 0:N.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(C=(S=e==null?void 0:e.metadata)==null?void 0:S.isolatedDataStructure)==null?void 0:C.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(A=t==null?void 0:t.metadata)==null?void 0:A.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(_=e==null?void 0:e.metadata)==null?void 0:_.importedExports,"External Dependencies":(E=e==null?void 0:e.metadata)==null?void 0:E.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(R=t==null?void 0:t.metadata)==null?void 0:R.scenariosDataStructure,description:"Structure template used across all scenarios"}],b=x.filter(T=>T.data!==void 0&&T.data!==null).length;let w=null;if(o==="entity"){const T=x.find($=>$.id===l);T&&T.data!==void 0&&T.data!==null&&(w={title:T.title,description:T.description,data:T.data})}else if(o==="scenarios"&&p){const T=r.find($=>($.id||$.name)===p.scenarioId);T&&(w={title:T.name,description:T.description||"Scenario data and configuration",data:T.metadata})}return d("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:d("div",{className:"flex border-b border-gray-200 relative",children:[n(to,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(to,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(to,{label:"LLM Calls",count:y,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((D=t==null?void 0:t.metadata)==null?void 0:D.analyzerVersion)&&d("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?d("div",{className:"flex-1 min-h-0",children:[d("div",{className:"flex gap-4 mb-4",children:[d("button",{onClick:()=>m("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${h==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),d("button",{onClick:()=>m("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${h==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",g.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:h==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(T=>n(tc,{call:T},T.id)):g.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No scenario-level LLM calls found"})}):g.map(T=>n(tc,{call:T},T.id))})]}):d("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:o==="entity"?d(we,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),b===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:x.map(T=>{const $=T.data!==void 0&&T.data!==null;return n(ec,{label:T.title,isActive:l===T.id,onClick:()=>c(T.id),disabled:!$},T.id)})})]}):d(we,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"SCENARIOS"}),r.length===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No scenarios available."}):n("nav",{className:"space-y-1",children:r.map(T=>{const $=T.id||T.name,L=(p==null?void 0:p.scenarioId)===$;return n(ec,{label:T.name,isActive:L,onClick:()=>u({scenarioId:$})},$)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:w?n(KS,{title:w.title,description:w.description,data:w.data}):o==="scenarios"&&r.length===0?n(rc,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:s}):o==="entity"?n(rc,{title:"No Entity Data Yet",description:"Entity data structures will appear here after analysis is complete.",onAnalyze:s}):n("div",{className:"p-6 text-center py-12 text-gray-500",children:"Select a section to view data"})})]})]})}function rc({title:e,description:t,onAnalyze:r}){return d("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[n("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),n("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:t}),r&&n("button",{onClick:r,className:"h-[54px] w-[183px] bg-[#005c75] text-white text-base font-medium rounded-lg border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]})}function KS({title:e,description:t,data:r}){const[s,a]=P(!0);return d(we,{children:[d("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[n("h3",{className:"text-base font-semibold text-black m-0",children:e}),n("p",{className:"text-sm text-[#646464] mt-1 m-0",children:t})]}),d("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[d("div",{className:"flex gap-2",children:[n("button",{onClick:()=>a(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),n("button",{onClick:()=>a(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),n(ct,{content:JSON.stringify(r,null,2),label:"Copy JSON",copiedLabel:"Copied!",className:"px-4 h-8 bg-[#343434] hover:bg-[#232323] text-white text-sm font-medium rounded border-none transition-colors whitespace-nowrap"})]}),n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"p-6",children:r?n("div",{className:"bg-gray-50 rounded-lg p-3 overflow-x-auto",children:n(VS,{data:r,defaultExpanded:s,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function qS({entity:e,analysis:t,scenarios:r,onAnalyze:s}){const a=Ke();return ae(()=>{if(e!=null&&e.sha&&a.state==="idle"&&!a.data){const o=t!=null&&t.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;a.load(o)}},[e==null?void 0:e.sha,t==null?void 0:t.id,a.state,a.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(GS,{entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a.data})})}const QS={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},ZS={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},XS=2e3,eC=e=>{var r;if(!e)return"typescript";switch((r=e.split(".").pop())==null?void 0:r.toLowerCase()){case"ts":case"tsx":return"typescript";case"js":case"jsx":return"javascript";case"json":return"json";case"css":return"css";default:return"typescript"}};function tC({entity:e,entityCode:t}){const r=Rr(),s=fe(null);return ae(()=>{const a=r.hash;if(!a||!s.current)return;const o=a.match(/^#L(\d+)$/);if(!o)return;const i=parseInt(o[1],10);setTimeout(()=>{if(!s.current)return;const l=s.current.querySelector(`[data-line-number="${i}"]`);if(l&&l instanceof HTMLElement){l.scrollIntoView({behavior:"smooth",block:"center"});const c=l.style.backgroundColor;l.style.backgroundColor="rgba(255, 255, 0, 0.2)",setTimeout(()=>{l.style.backgroundColor=c},2e3)}},300)},[r.hash,t]),n("div",{ref:s,className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:d("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[d("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),n("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e==null?void 0:e.filePath})]}),t&&n(ct,{content:t,label:"Copy Code",duration:XS,className:"px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] disabled:opacity-75 disabled:cursor-not-allowed"})]}),n("div",{className:"p-0",children:t?n("div",{className:"relative",children:n(Eh,{language:eC(e==null?void 0:e.filePath),style:Ah,showLineNumbers:!0,customStyle:QS,lineNumberStyle:ZS,wrapLines:!0,lineProps:a=>({"data-line-number":a,style:{display:"block"}}),children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}function qn({prompt:e,height:t=300,onClose:r,hideHeader:s}){const a=fe(null),o=fe(null),i=fe(null),l=fe(!1),c=fe(e);ae(()=>{const u=a.current;if(!u)return;let h=!1,m=null;async function f(){const[g,y]=await Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit")]);if(h)return;{let E=document.getElementById("xterm-css");E||(E=document.createElement("style"),E.id="xterm-css",document.head.appendChild(E)),E.textContent=`
495
+ .xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
496
+ .xterm.focus, .xterm:focus { outline: none; }
497
+ .xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
498
+ .xterm .xterm-helper-textarea { padding: 0; border: 0; margin: 0; position: absolute; opacity: 0; left: -9999em; top: 0; width: 0; height: 0; z-index: -5; white-space: nowrap; overflow: hidden; resize: none; caret-color: transparent !important; clip-path: inset(100%) !important; }
499
+ .xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
500
+ .xterm .composition-view.active { display: block; }
501
+ .xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
502
+ .xterm .xterm-screen { position: relative; }
503
+ .xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
504
+ .xterm .xterm-scroll-area { visibility: hidden; }
505
+ .xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
506
+ .xterm.enable-mouse-events { cursor: default; }
507
+ .xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
508
+ .xterm.column-select.focus { cursor: crosshair; }
509
+ .xterm .xterm-accessibility:not(.debug), .xterm .xterm-message { position: absolute; left: 0; top: 0; bottom: 0; right: 0; z-index: 10; color: transparent; pointer-events: none; }
510
+ .xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
511
+ .xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
512
+ .xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
513
+ .xterm-dim { opacity: 1 !important; }
514
+ .xterm-underline-1 { text-decoration: underline; }
515
+ .xterm-underline-2 { text-decoration: double underline; }
516
+ .xterm-underline-3 { text-decoration: wavy underline; }
517
+ .xterm-underline-4 { text-decoration: dotted underline; }
518
+ .xterm-underline-5 { text-decoration: dashed underline; }
519
+ .xterm-overline { text-decoration: overline; }
520
+ .xterm-strikethrough { text-decoration: line-through; }
521
+ .xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
522
+ .xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
523
+ .xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
524
+ .xterm-decoration-top { z-index: 2; position: relative; }
525
+ `}const x=new g.Terminal({theme:{background:"#1a1a1a",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78"},fontSize:12,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",cursorBlink:!0,scrollback:5e3,allowProposedApi:!0}),b=new y.FitAddon;x.loadAddon(b),x.open(u),requestAnimationFrame(()=>{try{b.fit()}catch{}}),i.current=x;let w=null;try{const E=await fetch("/api/editor-scenario-prompt",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:c.current})});E.ok&&(w=(await E.json()).promptFile)}catch{}if(h)return;const v=window.location.protocol==="https:"?"wss:":"ws:",N=window.location.host,S=new URLSearchParams;S.set("entityName","inline-claude");const C=`${v}//${N}/ws/terminal?${S.toString()}`,A=new WebSocket(C);o.current=A,A.onopen=()=>{A.send(JSON.stringify({type:"resize",cols:x.cols,rows:x.rows}))};let _=!1;A.onmessage=E=>{try{const R=JSON.parse(E.data);if(R.type==="session-id"&&!_){_=!0,setTimeout(()=>{const D=w?`claude "Read the file at '${w.replace(/'/g,"'\\''")}' for your instructions."`:"claude";A.send(JSON.stringify({type:"input",data:D+"\r"}))},300);return}if(R.type==="output"&&R.data){x.write(R.data);return}}catch{x.write(E.data)}},A.onclose=()=>{l.current||x.write(`\r
526
+ \x1B[90m--- Session ended ---\x1B[0m\r
527
+ `)},A.onerror=()=>{x.write(`\r
528
+ \x1B[31mConnection error\x1B[0m\r
529
+ `)},x.onData(E=>{A.readyState===WebSocket.OPEN&&A.send(JSON.stringify({type:"input",data:E}))}),m=new ResizeObserver(()=>{try{b.fit(),A.readyState===WebSocket.OPEN&&A.send(JSON.stringify({type:"resize",cols:x.cols,rows:x.rows}))}catch{}}),m.observe(u)}return f(),()=>{var g,y;h=!0,l.current=!0,m==null||m.disconnect(),((g=o.current)==null?void 0:g.readyState)===WebSocket.OPEN&&o.current.close(),(y=i.current)==null||y.dispose()}},[]);const p=t==="100%";return d("div",{className:s?"":"border-t border-[#2d2d2d]",style:p?{height:"100%",display:"flex",flexDirection:"column"}:void 0,children:[!s&&d("div",{className:"flex items-center justify-between px-3 py-1.5 bg-[#1e1e1e]",children:[n("span",{className:"text-[10px] font-medium text-[#00a0c4]",children:"Claude"}),r&&n("button",{onClick:r,className:"text-gray-500 hover:text-gray-300 text-[10px] bg-transparent border-none cursor-pointer",children:"Close"})]}),n("div",{ref:a,style:{height:p?void 0:t,flex:p?1:void 0,background:"#1a1a1a",padding:"4px 0",position:"relative",overflow:"hidden"}})]})}const nC=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function rC({currentParams:e,nextParams:t,currentUrl:r,nextUrl:s,formMethod:a,defaultShouldRevalidate:o}){return r.pathname===s.pathname&&r.search===s.search?o:!!(e.sha!==t.sha||a)}async function sC({params:e,request:t,context:r}){const{sha:s}=e;if(!s)throw new Response("Entity SHA is required",{status:400});const o=new URL(t.url).searchParams.get("from"),l=(e["*"]||"").split("/").filter(Boolean),c=l[0]||"scenarios",p=l[1]||null,u=l[2]||null,h=r.analysisQueue,m=h?h.getState():{paused:!1,jobs:[]},[f,g,y,x]=await Promise.all([_n(s),Ye(),rr(),Bf(Ne()||process.cwd())]),b=f?await Xs(f):null,w=f?await nd(f.sha):null;let v={importedEntities:[],importingEntities:[]},N=null,S=[];f&&(v=await rd(f),N=await sd(f),S=await od(f));const C=!!(f&&S.length>0&&S[0].sha!==f.sha),A=S.length>0?S[0].sha:null,_=!!(S.length>0&&S[0].analyses&&S[0].analyses.length>0),E=f?await ad(f):!1;return re({entity:f??void 0,analysis:b??void 0,currentEntityAnalysis:w??void 0,projectSlug:g,from:o,relatedEntities:v,entityCode:N??void 0,hasNewerVersion:C,newestEntitySha:A,newestVersionHasAnalysis:_,fileModifiedSinceEntity:E,history:S,tab:c,scenarioId:p,viewModeFromUrl:u,currentCommit:y,hasAnApiKey:x,queueState:m})}const aC=et(function(){var Kr,xt,qr,$n,Qr,pr,hr,mr,Pt,In,Zr,Xr,es,fr,ts;const t=st(),a=(Tc()["*"]||"").split("/").filter(Boolean),o=a[0]||"scenarios",i=a[1]||null,l=a[2]||null,c=t.entity,p=t.analysis,u=t.currentEntityAnalysis,h=u||p,m=t.projectSlug;t.from;const f=t.relatedEntities,g=t.entityCode,y=t.hasNewerVersion,x=t.newestEntitySha,b=t.newestVersionHasAnalysis,w=t.fileModifiedSinceEntity,v=t.history,N=t.currentCommit,S=t.hasAnApiKey,C=t.queueState;(Kr=h==null?void 0:h.status)==null||Kr.errors;const A=(h==null?void 0:h.scenarios)||[],_=A.filter(pe=>{var je;return!((je=pe.metadata)!=null&&je.sameAsDefault)}),E=A.filter(pe=>{var je;return(je=pe.metadata)==null?void 0:je.sameAsDefault}),R=Rt(),D=fe(null);ae(()=>{D.current===null&&(D.current=window.history.length)},[]);const T=()=>{if(typeof window>"u")return;const pe=window.history.state;if(pe===null||(pe==null?void 0:pe.idx)===void 0||(pe==null?void 0:pe.idx)===0)R("/");else{const je=window.history.length,tt=D.current;if(tt!==null&&je>tt){const Be=je-tt+1;R(-Be)}else R(-1)}},$=!!C.currentlyExecuting,L=o,B=(xt=N==null?void 0:N.metadata)==null?void 0:xt.currentRun,H=!!(B!=null&&B.createdAt)&&!(B!=null&&B.analysisCompletedAt),q=!!(c!=null&&c.sha&&((qr=B==null?void 0:B.currentEntityShas)!=null&&qr.includes(c.sha))),O=!!(c!=null&&c.sha&&((Qr=($n=C.currentlyExecuting)==null?void 0:$n.entityShas)!=null&&Qr.includes(c.sha))),W=!!(c!=null&&c.sha&&((pr=C.jobs)!=null&&pr.some(pe=>{var je;return(je=pe.entityShas)==null?void 0:je.includes(c.sha)}))),I=q||O||W,j=I&&((hr=h==null?void 0:h.status)==null?void 0:hr.finishedAt)!=null&&_.length>0&&h.entitySha!==(c==null?void 0:c.sha),k=ie(()=>{if(L!=="scenarios")return null;if(i){const pe=_.find(je=>je.id===i);if(pe)return pe}return _.length>0&&!I?_[0]:null},[L,i,_,I]),Y=((In=(Pt=(mr=k==null?void 0:k.metadata)==null?void 0:mr.executionResult)==null?void 0:Pt.error)==null?void 0:In.message)||((es=(Xr=(Zr=h==null?void 0:h.status)==null?void 0:Zr.errors)==null?void 0:Xr[0])==null?void 0:es.message);Dt({source:k?"scenario-page":"entity-page",entitySha:c==null?void 0:c.sha,scenarioId:k==null?void 0:k.id,analysisId:h==null?void 0:h.id,entityName:c==null?void 0:c.name,entityType:c==null?void 0:c.entityType,scenarioName:k==null?void 0:k.name,errorMessage:Y});const[G,Q]=P(()=>l&&l!=="edit"?l:(c==null?void 0:c.entityType)==="library"?"data":"screenshot");ae(()=>{l&&l!==G&&l!=="edit"&&Q(l)},[l]);const K=l==="edit",[F,M]=P(!1),[z,J]=P(!1),[te,oe]=P(null),[de,ue]=P(!1),[me,Se]=P(!1),[Te,$e]=P(null),[Re,X]=P(null),[ye,ee]=P(0),{interactiveServerUrl:ne,isStarting:xe,isLoading:Me,showIframe:he,iframeKey:He,onIframeLoad:Ve}=jn({analysisId:h==null?void 0:h.id,scenarioId:k==null?void 0:k.id,scenarioName:k==null?void 0:k.name,projectSlug:m,enabled:K&&!!k,refreshTrigger:ye}),[Oe,lr]=P(!1),[dn,$i]=P(""),[Tn,Ot]=P(!1),[We,Et]=P(Date.now()),[Wr,Mn]=P(!1),[at,cr]=P(!1),yt=Ke(),At=Ke(),ot=Ke(),Le=Ut(),dt=C.jobs.some(pe=>{var je;return(c==null?void 0:c.sha)&&((je=pe.entityShas)==null?void 0:je.includes(c.sha))||pe.type==="analysis"&&pe.commitSha===(N==null?void 0:N.sha)&&pe.entityShas&&pe.entityShas.length===0}),un=I,Ur=((fr=c==null?void 0:c.metadata)==null?void 0:fr.defaultWidth)||((ts=h==null?void 0:h.metadata)==null?void 0:ts.defaultWidth)||1440,va=Math.round(Ur*(900/1440));yt.state==="submitting"||yt.state,ie(()=>{var pe;return!!((pe=k==null?void 0:k.metadata)!=null&&pe.interactiveExamplePath)},[k]);const{isCompleted:Lt}=Jt(m,Tn);ae(()=>{yt.state==="idle"&&yt.data&&(yt.data.success?setTimeout(()=>{Et(Date.now()),Le.revalidate(),Ot(!1)},1500):yt.data.error&&(Ot(!1),alert(`Recapture failed: ${yt.data.error}`)))},[yt.state,yt.data,Le]),ae(()=>{Tn&&Lt&&setTimeout(()=>{Et(Date.now()),Le.revalidate(),Ot(!1)},1500)},[Tn,Lt,Le]),ae(()=>{At.state==="idle"&&At.data&&(At.data.success?setTimeout(()=>{Et(Date.now()),Le.revalidate(),Ot(!1)},1500):At.data.error&&(Ot(!1),alert(`Recapture failed: ${At.data.error}`)))},[At.state,At.data,Le]);const Na=ie(()=>{var tt;if(!c)return"";const pe=[];if(pe.push(`# Create a New Scenario for "${c.name}"`),pe.push(""),pe.push(`**Entity**: ${c.name}`),pe.push(`**Type**: ${c.entityType}`),c.filePath&&pe.push(`**File**: ${c.filePath}`),pe.push(""),_.length>0){pe.push("## Existing Scenarios");for(const Be of _)pe.push(`- **${Be.name}**${Be.description?`: ${Be.description}`:""}`);pe.push("")}const je=(tt=h==null?void 0:h.metadata)==null?void 0:tt.executionFlows;if(je&&je.length>0){pe.push("## Execution Flows");const Be=new Set(_.flatMap(Ge=>{var rt;return((rt=Ge.metadata)==null?void 0:rt.coveredFlows)||[]})),it=je.filter(Ge=>!Be.has(Ge.id)),bt=je.filter(Ge=>Be.has(Ge.id));if(bt.length>0){pe.push(`### Covered (${bt.length})`);for(const Ge of bt)pe.push(`- ${Ge.name}${Ge.description?`: ${Ge.description}`:""}`);pe.push("")}if(it.length>0){pe.push(`### Uncovered (${it.length}) — gaps to consider`);for(const Ge of it)pe.push(`- ${Ge.name}${Ge.description?`: ${Ge.description}`:""}${Ge.impact==="high"?" **(high impact)**":""}`);pe.push("")}}return pe.push("## Your Task"),pe.push("Ask the user what scenario they would like to create. Offer two options:"),pe.push("1. **Describe a scenario** — the user tells you what they want and you create it"),pe.push("2. **Analyze gaps** — you review the existing scenarios and execution flows to suggest scenarios that would improve coverage"),pe.push(""),pe.push("Once you know what scenario to create, use the `codeyam editor register` CLI command to register it. Write the scenario JSON to `.codeyam/tmp/scenario.json` first, then run `codeyam editor register @.codeyam/tmp/scenario.json`."),pe.join(`
530
+ `)},[c,_,h]),pn=()=>{cr(!0)},Jr=()=>{c&&(y&&x&&x!==c.sha?(R(`/entity/${x}/scenarios`),setTimeout(()=>{ot.submit({entitySha:x,filePath:c.filePath||""},{method:"post",action:"/api/analyze"})},100)):ot.submit({entitySha:c.sha,filePath:c.filePath||""},{method:"post",action:"/api/analyze"}))};ae(()=>{ot.state==="idle"&&ot.data&&(ot.data.success?Le.revalidate():ot.data.error&&alert(`Analysis failed: ${ot.data.error}`))},[ot.state,ot.data,c==null?void 0:c.sha,Le]),ae(()=>{const pe=setTimeout(()=>{Le.revalidate()},500);return()=>clearTimeout(pe)},[]),ae(()=>{if(H||un){const pe=setInterval(()=>{Le.revalidate()},3e3);return()=>clearInterval(pe)}},[H,un,Le]);const Hr=(pe,je)=>pe==="scenarios"?`/entity/${c==null?void 0:c.sha}/scenarios`:`/entity/${c==null?void 0:c.sha}/${pe}`,Sa=(pe,je)=>`/entity/${c==null?void 0:c.sha}/scenarios/${pe}/${je}`,dr=pe=>{Q(pe),k!=null&&k.id&&(pe==="interactive"?R(`/entity/${c==null?void 0:c.sha}/scenarios/${k.id}/fullscreen`,{replace:!0}):R(Sa(k.id,pe),{replace:!0}))},ur=async pe=>{var je,tt;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:pe,hasSelectedScenario:!!k,hasAnalysis:!!h}),!k||!h){const Be="Error: No scenario or analysis available";console.error("[EntityDetail]",Be),oe(Be);return}M(!0),oe(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:pe,scenarioId:k.id,scenarioName:k.name,currentData:k.data});try{const Be=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:pe,existingScenarios:h.scenarios,scenariosDataStructure:(je=h.metadata)==null?void 0:je.scenariosDataStructure,editingMockName:k.name,editingMockData:Re||((tt=k.metadata)==null?void 0:tt.data)})}),it=await Be.json();if(!Be.ok||!it.success)throw new Error(it.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",it.data),X(it.data);const bt=(h.scenarios||[]).map(qe=>qe.id===k.id?{...qe,metadata:{...qe.metadata,data:it.data}}:qe),Ge=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:h,scenarios:bt})}),rt=await Ge.json();if(!Ge.ok||!rt.success)throw console.error("[EntityDetail] Temp save failed:",rt),new Error(rt.error||"Failed to apply preview");if(oe("Generating preview. Capturing screenshot..."),ne){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:ne});const qe=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:ne,scenarioId:k.id,projectId:h.projectId,viewportWidth:1440})}),hn=await qe.json();!qe.ok||!hn.success?(console.error("[EntityDetail] Direct capture failed:",hn),oe("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),oe('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const qe=new FormData;qe.append("analysisId",h.id||""),qe.append("scenarioId",k.id||"");const hn=await fetch("/api/recapture-scenario",{method:"POST",body:qe}),Bt=await hn.json();!hn.ok||!Bt.success?(console.warn("[EntityDetail] Recapture failed:",Bt.error),oe("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",Bt.jobId),oe('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}ee(qe=>qe+1),Le.revalidate()}catch(Be){console.error("Error applying changes:",Be),oe(`Error: ${Be instanceof Error?Be.message:String(Be)}`)}finally{M(!1)}},Ca=async(pe,je)=>{var tt;if(!k||!h){oe("Error: No scenario or analysis available");return}J(!0),oe(null),console.log("[EntityDetail] Saving scenario to database",{description:pe,saveAsNew:je});try{const Be=Re||((tt=k.metadata)==null?void 0:tt.data);let it;if(je){const rt={...k,id:`${k.name}-${Date.now()}`,name:`${k.name} (Copy)`,metadata:{...k.metadata,data:Be},description:pe||k.description};it=[...h.scenarios||[],rt]}else it=(h.scenarios||[]).map(rt=>rt.id===k.id?{...rt,metadata:{...rt.metadata,data:Be},description:pe||rt.description}:rt);const bt=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:h,scenarios:it})}),Ge=await bt.json();if(!bt.ok||!Ge.success)throw new Error(Ge.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),oe(je?"New scenario created successfully":"Scenario saved successfully"),X(null),Le.revalidate()}catch(Be){console.error("Error saving scenario:",Be),oe(`Error: ${Be instanceof Error?Be.message:String(Be)}`)}finally{J(!1)}},Vr=()=>{k!=null&&k.id&&(c!=null&&c.sha)&&R(`/entity/${c.sha}/scenarios/${k.id}/dev`)},Gr=async()=>{var pe;if(!(k!=null&&k.id)){$e("Cannot delete scenario without ID");return}ue(!0),$e(null);try{const je=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:k.id,screenshotPaths:((pe=k.metadata)==null?void 0:pe.screenshotPaths)||[]})}),tt=await je.json();if(!je.ok||!tt.success)throw new Error(tt.error||"Failed to delete scenario");R(`/entity/${c==null?void 0:c.sha}/scenarios`)}catch(je){console.error("[EntityDetail] Error deleting scenario:",je),$e(je instanceof Error?je.message:"Failed to delete scenario"),Se(!1)}finally{ue(!1)}},qt=h&&c&&h.entitySha!==c.sha,ka=c?LS(c):!1;return n(fa,{children:d("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:d("div",{className:"flex items-end h-full px-6 gap-6",children:[d("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:T,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:c==null?void 0:c.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:c==null?void 0:c.filePath,children:c==null?void 0:c.filePath})]}),n("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:_.length},{id:"related",label:"Related Entities",count:f.importedEntities.length+f.importingEntities.length},{id:"code",label:"Code"},{id:"data",label:"Data Structure"},{id:"history",label:"History"}].map(pe=>n(Ce,{to:Hr(pe.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${L===pe.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:L===pe.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:d("span",{className:"flex items-center gap-2",children:[pe.label,pe.count!==void 0&&pe.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${L===pe.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:pe.count})]})},pe.id))})]})}),(y||qt&&!u||w&&ka)&&!I&&!dt&&n("div",{className:"border-b border-[#FEE585] px-6 py-3 flex items-center justify-center shrink-0",style:{backgroundColor:"#FEE585"},children:d("div",{className:"flex items-center gap-3",children:[n("svg",{className:"w-4 h-4",style:{color:"#714A25"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),n("span",{className:"text-sm font-semibold",style:{color:"#714A25"},children:qt&&!y?"This entity version has not been analyzed yet.":"This entity has been recently changed."}),n("span",{className:"text-sm",style:{color:"#714A25"},children:y?"You are viewing an older version. A newer version is available.":qt?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),y&&x&&b?n(Ce,{to:`/entity/${x}/scenarios`,className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono cursor-pointer transition-colors no-underline",style:{backgroundColor:"#C69538"},onMouseEnter:pe=>{pe.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:pe=>{pe.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:Jr,disabled:ot.state!=="idle",className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#C69538"},onMouseEnter:pe=>{ot.state==="idle"&&(pe.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:pe=>{ot.state==="idle"&&(pe.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),d("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[L==="scenarios"&&d(we,{children:[K&&k?n(zS,{scenario:k,entitySha:(c==null?void 0:c.sha)||"",onApply:ur,onSave:Ca,onEditMockData:Vr,onDelete:Gr,isApplying:F,isSaving:z,saveMessage:te,showDeleteConfirm:me,onShowDeleteConfirm:Se,isDeleting:de,deleteError:Te}):n(BS,{scenarios:_,hiddenScenarios:E,analysis:h,selectedScenario:k,entitySha:(c==null?void 0:c.sha)||"",cacheBuster:We,activeTab:L,entityType:c==null?void 0:c.entityType,entity:c,queueState:C,processIsRunning:$,isEntityAnalyzing:I,areScenariosStale:j,viewMode:G,setViewMode:dr,isBreakdownView:i==="breakdown",onCreateScenario:pn}),at?d("div",{className:"flex flex-col flex-1 min-h-0",children:[d("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:"Create New Scenario"}),n("button",{onClick:()=>cr(!1),className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors",children:"Close"})]}),n("div",{className:"flex-1 min-h-0",children:n(qn,{prompt:Na,height:"100%",hideHeader:!0})})]}):i==="breakdown"?n(WS,{analysis:h??null,entitySha:(c==null?void 0:c.sha)||"",onCreateScenario:pn}):K&&k?n(ga,{scenarioId:k.id||k.name,scenarioName:k.name,iframeUrl:ne,isStarting:xe,isLoading:Me,showIframe:he,iframeKey:He,onIframeLoad:Ve,projectSlug:m,defaultWidth:1440,defaultHeight:900}):d("div",{className:"flex flex-col flex-1 min-h-0",children:[k&&d("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:k.name}),d("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[Ur," × ",va]})]}),d("div",{className:"flex items-center gap-2",children:[n(Ce,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${k.id}/edit`,className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors no-underline flex items-center",title:"Edit Scenario Data",children:"Edit Scenario"}),d("button",{className:"px-3 py-1.5 bg-[#022A35] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#011a21] transition-colors flex items-center gap-1.5",onClick:()=>{alert("Download functionality coming soon")},title:"Download",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"})}),"Download"]}),d(Ce,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${k.id}/dev`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Dev Mode - Live preview with data editor and code sync",children:[d("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n("polyline",{points:"16 18 22 12 16 6"}),n("polyline",{points:"8 6 2 12 8 18"})]}),"Dev Mode"]}),d(Ce,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${k.id}/fullscreen`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Interactive Mode",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:n("path",{d:"M8 5v14l11-7z"})}),"Interactive Mode"]})]})]}),n(Au,{selectedScenario:k,analysis:h,entity:c,viewMode:G,cacheBuster:We,hasScenarios:_.length>0,isAnalyzing:un,projectSlug:m,hasAnApiKey:S,processIsRunning:$,queueState:C})]})]}),L==="related"&&n(HS,{relatedEntities:f}),L==="data"&&n(qS,{entity:c,analysis:h,scenarios:_,onAnalyze:Jr}),L==="code"&&n(tC,{entity:c,entityCode:g}),L==="history"&&n(US,{entity:c,history:v})]}),Wr&&m&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>Mn(!1),children:d("div",{className:"bg-white rounded-xl max-w-[1200px] w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:pe=>pe.stopPropagation(),children:[d("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>Mn(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(rn,{projectSlug:m,onClose:()=>Mn(!1)})})]})})]})})}),oC=Object.freeze(Object.defineProperty({__proto__:null,default:aC,loader:sC,meta:nC,shouldRevalidate:rC},Symbol.toStringTag,{value:"Module"}));async function iC(e){const{entityShas:t,filePaths:r,context:s,scenarioCount:a,queue:o}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await Je();const i=Ne();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=se.join(i,".codeyam","config.json"),c=JSON.parse(await Ee.readFile(l,"utf8")),{projectSlug:p,branchId:u}=c;if(!p||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${p}, Branch: ${u}`);const h=Lr(p);try{await Ee.writeFile(h,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:m,branch:f}=await De(p);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const g=await Xe({shas:t});if(!g||g.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);let y=r;if((!y||y.length===0)&&(y=[...new Set(g.map(w=>w.filePath).filter(w=>!!w))],console.log(`[analyzeEntities] Found ${y.length} unique files`)),!y||y.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${y.length} files...`);const x=await Rf(m,f,y);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await nn({commitSha:x.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:w=>{if(!w)return;const v=w.currentRun;if(v&&v.id&&v.archivedAt)return;v&&(v.analysesCompleted&&v.analysesCompleted>0||v.capturesCompleted&&v.capturesCompleted>0)&&Gf(w)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:b}=o.enqueue({type:"analysis",commitSha:x.sha,projectSlug:p,filePaths:y,entityShas:t,entityNames:g.map(w=>w.name),...s?{context:s}:{},...a?{scenarioCount:a}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${b} for ${t.length} entities`),{jobId:b}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function lC({request:e,context:t}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Gt()),!r)return re({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("entitySha"),o=s.get("entityShas"),i=s.get("filePath"),l=s.get("context"),c=s.get("scenarioCount");let p;if(o)p=o.split(",").filter(Boolean);else if(a)p=[a];else return re({error:"Missing required field: entitySha or entityShas"},{status:400});if(p.length===0)return re({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${p.length} entity(ies)`);const u=await Xe({shas:p}),m=[...new Set(u.map(g=>g.filePath).filter(g=>!!g))].length,{jobId:f}=await iC({entityShas:p,filePaths:i?[i]:void 0,context:l||void 0,scenarioCount:c?parseInt(c,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),re({success:!0,message:`Analysis queued for ${p.length} entity(ies)`,entityCount:p.length,fileCount:m,jobId:f})}catch(s){return console.error("[API] Error starting analysis:",s),re({error:"Failed to start analysis",details:s.message},{status:500})}}const cC=Object.freeze(Object.defineProperty({__proto__:null,action:lC},Symbol.toStringTag,{value:"Module"}));function dC(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:d("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function Pu(e){if(!e)return"Never";const t=new Date(e),r=new Date;if(t.getDate()===r.getDate()&&t.getMonth()===r.getMonth()&&t.getFullYear()===r.getFullYear()){const a=t.getHours(),o=t.getMinutes(),i=a>=12?"pm":"am",l=a%12||12,c=o.toString().padStart(2,"0");return`Today, ${l}:${c} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function wt(e,t=[],r=!1){var u,h;if(t.some(m=>{var f,g;return!!((f=m.entityShas)!=null&&f.includes(e.sha)||(g=m.entities)!=null&&g.some(y=>y.sha===e.sha))}))return r?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const a=e.analyses[0];if(!(((u=a.status)==null?void 0:u.scenarios)&&a.status.scenarios.length>0&&a.status.scenarios.some(m=>m.screenshotFinishedAt||m.finishedAt))||a.entitySha!==e.sha)return"not-analyzed";const i=a.createdAt?new Date(a.createdAt).getTime():0,l=(h=e.metadata)!=null&&h.editedAt?new Date(e.metadata.editedAt).getTime():0,c=a.scenarios||[],p=c.some(m=>{var f,g,y;return((g=(f=m.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0])||((y=m.metadata)==null?void 0:y.executionResult)});return i>=l?c.length>0&&p?c.every(f=>{var g,y,x;return((y=(g=f.metadata)==null?void 0:g.screenshotPaths)==null?void 0:y[0])||((x=f.metadata)==null?void 0:x.executionResult)})?"up-to-date":"incomplete":c.length>0?"incomplete":"not-analyzed":"out-of-date"}const uC=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function pC({request:e,context:t}){try{const r=t.analysisQueue,s=r?r.getState():{paused:!1,jobs:[]},a=await Pn();return re({entities:a||[],queueState:s})}catch(r){return console.error("Failed to load simulations:",r),re({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const hC=et(function(){const t=st(),r=t.entities,s=t.queueState;Dt({source:"simulations-page"});const[a,o]=P(""),[i,l]=P("visual"),c=ie(()=>{const y=[];return r.forEach(x=>{var w;const b=(w=x.analyses)==null?void 0:w[0];if(b!=null&&b.scenarios){const v=b.scenarios.filter(N=>{var S;return!((S=N.metadata)!=null&&S.sameAsDefault)}).map(N=>{var D,T,$,L,B;const S=(T=(D=N.metadata)==null?void 0:D.screenshotPaths)==null?void 0:T[0],C=($=N.metadata)==null?void 0:$.noScreenshotSaved,A=S&&!C,_=(B=(L=b.status)==null?void 0:L.scenarios)==null?void 0:B.find(H=>H.name===N.name),E=_&&_.screenshotStartedAt&&!_.screenshotFinishedAt;let R;return A?R="completed":E?R="capturing":R="error",{scenarioName:N.name,scenarioDescription:N.description||"",screenshotPath:S||"",scenarioId:N.id,state:R}}).filter(N=>N.state==="completed"||N.state==="capturing");v.length>0&&y.push({entity:x,screenshots:v,createdAt:b.createdAt||""})}}),y.sort((x,b)=>new Date(b.createdAt).getTime()-new Date(x.createdAt).getTime()),y},[r]),p=ie(()=>r.filter(y=>{var w,v;const x=(w=y.analyses)==null?void 0:w[0];return!((v=x==null?void 0:x.scenarios)==null?void 0:v.some(N=>{var S,C;return(C=(S=N.metadata)==null?void 0:S.screenshotPaths)==null?void 0:C[0]}))}),[r]),u=ie(()=>c.filter(({entity:y})=>{const x=!a||y.name.toLowerCase().includes(a.toLowerCase()),b=i==="all"||y.entityType===i;return x&&b}),[c,a,i]),h=ie(()=>p.filter(y=>{const x=!a||y.name.toLowerCase().includes(a.toLowerCase()),b=i==="all"||y.entityType===i;return x&&b}),[p,a,i]),m=ce(y=>{o(y.target.value)},[]),f=ce(y=>{l(y.target.value)},[]),g=c.length>0;return n("div",{className:"bg-[#F8F7F6] min-h-screen overflow-y-auto",children:d("div",{className:"px-20 py-12",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!g&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:d("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",n("strong",{children:"Start by analyzing your first component below."})]})}),d("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),d("div",{className:"flex gap-3",children:[d("div",{className:"relative",children:[d("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 pr-8 text-[13px] h-[39px] cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:i,onChange:f,children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(St,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"flex-1 relative",children:[n(Dr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-3 text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:a,onChange:m})]})]})]}),g&&u.length>0&&n("div",{className:"mb-2",children:d("div",{className:"flex items-center py-3",children:[d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:u.length})," ",u.length===1?"entity":"entities"]}),d("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:d("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:u.reduce((y,{screenshots:x})=>y+x.length,0)})," ","scenarios"]})]})}),d("div",{className:"flex flex-col gap-3",children:[g&&(u.length===0?n("div",{className:"bg-white border border-gray-200 rounded-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):n(we,{children:u.map(({entity:y,screenshots:x})=>n(mC,{entity:y,screenshots:x,queueJobs:(s==null?void 0:s.jobs)||[]},y.sha))})),!g&&(h.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No components found matching your filters."}):h.map(y=>n(fC,{entity:y},y.sha)))]})]})})});function mC({entity:e,screenshots:t,queueJobs:r}){var f,g,y;const s=Rt(),a=Ke(),[o,i]=P(!1),l=t.length||(((y=(g=(f=e.analyses)==null?void 0:f[0])==null?void 0:g.scenarios)==null?void 0:y.length)??0),c=x=>{s(`/entity/${e.sha}/scenarios/${x}?from=simulations`)},p=()=>{i(!0),a.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};ae(()=>{a.state==="idle"&&o&&i(!1)},[a.state,o]);const u=wt(e,r),h=dC(u),m=u==="out-of-date";return n("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:d("div",{className:"flex flex-col",children:[d("div",{className:"flex items-center px-[15px] py-[15px]",children:[n("div",{className:"flex-shrink-0",children:n(ht,{type:e.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[d("div",{className:"flex items-center gap-[5px]",children:[d(Ce,{to:`/entity/${e.sha}`,className:"hover:underline cursor-pointer",title:e.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:[e.name," (",l,")"]}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:h.bgColor,color:h.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:h.text})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),d("div",{className:"flex-shrink-0 flex items-center gap-2",children:[m&&n(we,{children:o||a.state!=="idle"?d("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[n(Mt,{size:14,className:"animate-spin",style:{color:"#be185d"}}),n("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):n("button",{onClick:p,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#005c75",color:"#ffffff",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#004d5e"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#005c75"},children:"Re-analyze"})}),n("button",{onClick:()=>void s(`/entity/${e.sha}/logs`),className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})]})]}),n("div",{className:"border-t border-gray-200"}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:t.length>0?t.map(x=>d("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>c(x.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:x.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:x.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:b=>{x.state==="completed"&&(b.currentTarget.style.borderColor="#005C75",b.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:b=>{b.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",b.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(lt,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(wi,{size:"medium"}):null})}),d("div",{className:"relative group",children:[n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.scenarioName}),n("div",{className:"fixed hidden group-hover:block pointer-events-none",style:{zIndex:1e4,transform:"translateY(8px)"},children:d("div",{className:"bg-gray-100 text-gray-800 text-xs rounded-lg px-3 py-2 shadow-lg max-w-xs border border-gray-200",children:[x.scenarioName,x.scenarioDescription&&d(we,{children:[": ",x.scenarioDescription]}),n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-100 border-l border-t border-gray-200 transform rotate-45"})]})})]})]},x.scenarioId)):n("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function fC({entity:e}){const t=Ke(),[r,s]=P(!1),a=()=>{s(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return ae(()=>{t.state==="idle"&&r&&s(!1)},[t.state,r]),n("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:a,children:d("div",{className:"px-5 py-4 flex items-center",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(ht,{type:e.entityType}),d("div",{className:"min-w-0",children:[d("div",{className:"flex items-center gap-3 mb-0.5",children:[n(Ce,{to:`/entity/${e.sha}`,className:"text-sm font-medium text-gray-900 no-underline",children:e.name}),n("span",{className:"text-[10px] font-semibold px-1 py-0.5 rounded",style:{color:e.entityType==="visual"?"#7c3aed":e.entityType==="library"?"#0DBFE9":e.entityType==="type"?"#dc2626":e.entityType==="data"?"#2563eb":e.entityType==="index"?"#ea580c":e.entityType==="functionCall"?"#7c3aed":e.entityType==="class"?"#059669":e.entityType==="method"?"#0891b2":"#6b7280",backgroundColor:e.entityType==="visual"?"#f3e8ff":e.entityType==="library"?"#cffafe":e.entityType==="type"?"#fee2e2":e.entityType==="data"?"#dbeafe":e.entityType==="index"?"#ffedd5":e.entityType==="functionCall"?"#f3e8ff":e.entityType==="class"?"#d1fae5":e.entityType==="method"?"#cffafe":"#f3f4f6"},children:e.entityType?e.entityType.toUpperCase():"UNKNOWN"})]}),n("div",{className:"text-xs text-gray-400 truncate",children:e.filePath})]})]}),n("div",{className:"w-32 flex justify-center",children:n("span",{className:"text-[10px] text-gray-500 bg-gray-100 px-2 py-1 rounded",children:"Not analyzed"})}),n("div",{className:"w-32 text-center text-[10px] text-gray-500",children:Pu(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?d("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(Mt,{size:14,className:"animate-spin"}),"Analyzing..."]}):n("button",{onClick:a,className:"bg-[#e0e9ec] text-[#005c75] px-4 py-1.5 rounded text-xs font-medium hover:bg-[#d0dde1] transition-colors cursor-pointer",children:"Analyze"})})]})})}const gC=Object.freeze(Object.defineProperty({__proto__:null,default:hC,loader:pC,meta:uC},Symbol.toStringTag,{value:"Module"}));function yC({request:e,context:t}){const r=t.dbNotifier||Nt;if(!r)return console.error("[SSE] ERROR: dbNotifier not found in context or global!"),new Response("Server configuration error",{status:500});r.start().catch(()=>{});const s=new ReadableStream({start(a){const o=new TextEncoder;a.enqueue(o.encode(`data: ${JSON.stringify({type:"connected"})}
531
+
532
+ `)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",c),clearInterval(p);try{a.close()}catch{}}},c=u=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
533
+
534
+ `))}catch{l()}};r.on("change",c);const p=setInterval(()=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
535
+
536
+ `))}catch{l()}},3e4);e.signal.addEventListener("abort",l)}});return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const xC=Object.freeze(Object.defineProperty({__proto__:null,loader:yC},Symbol.toStringTag,{value:"Module"}));function bC(){return new Response(JSON.stringify({status:"ok",version:Uo,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const wC=Object.freeze(Object.defineProperty({__proto__:null,loader:bC},Symbol.toStringTag,{value:"Module"}));function Si(e){const t=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,r=e.match(t);if(!r)return{frontmatter:{},body:e};const s=r[1],a=r[2],o={},i=s.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/),l=s.match(/paths:\s*\[([^\]]*)\]/);i&&i[1].trim()?o.paths=i[1].split(`
537
+ `).filter(p=>p.trim().startsWith("-")).map(p=>p.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean):l&&(o.paths=l[1].split(",").map(p=>p.replace(/['"]/g,"").trim()).filter(Boolean));const c=s.match(/^category:\s*(.+)$/m);return c&&(o.category=c[1].replace(/['"]/g,"").trim()),{frontmatter:o,body:a}}async function ba(e,t=""){const r=[];try{const s=await Ee.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){const i=await ba(se.join(e,a.name),o);r.push(...i)}else a.isFile()&&a.name.endsWith(".md")&&r.push(o)}}catch{}return r}async function Yr(e){const t=await ba(e),r=[];for(const s of t){const a=se.join(e,s);try{const o=await Ee.readFile(a,"utf-8"),{frontmatter:i,body:l}=Si(o);r.push({filePath:s,absolutePath:a,frontmatter:i,body:l})}catch{}}return r}function ju(e){const t=se.posix.dirname(e.filePath);return!t||t==="."?null:`${t}/**`}function Tu(e,t){if(t.frontmatter.paths&&t.frontmatter.paths.length>0)return t.frontmatter.paths.some(s=>lo(e,s,{matchBase:!0}));const r=ju(t);return r?lo(e,r,{matchBase:!0}):!1}function vC(e,t){return(!e.frontmatter.paths||e.frontmatter.paths.length===0)&&!ju(e)?[]:t.filter(r=>Tu(r,e))}const NC=new Set(["node_modules",".git","dist",".codeyam",".claude","build","coverage"]);async function Ci(e){const t=[];async function r(s,a){try{const o=await _e.readdir(s,{withFileTypes:!0});for(const i of o){const l=U.join(s,i.name),c=a?`${a}/${i.name}`:i.name;i.isDirectory()&&NC.has(i.name)||(i.isDirectory()?await r(l,c):i.isFile()&&t.push(c))}}catch{}}return await r(e,""),t}const SC="codeyam-rule-state.json",no=1;function Mu(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return er.createHash("sha256").update(t).digest("hex")}function $u(e){return se.join(e,".claude",SC)}async function Iu(e){const t=$u(e);try{const r=await Ee.readFile(t,"utf-8"),s=JSON.parse(r);return s.version!==no?(console.warn(`[ruleState] Unknown version ${s.version}, using empty state`),{version:no,rules:{}}):s}catch{return{version:no,rules:{}}}}async function Ru(e,t){const r=$u(e),s=se.dirname(r);await Ee.mkdir(s,{recursive:!0}),await Ee.writeFile(r,JSON.stringify(t,null,2)+`
538
+ `,"utf-8")}async function ki(e,t){const r=await Iu(e),s=new Set(t.map(a=>a.filePath));for(const a of Object.keys(r.rules))s.has(a)||delete r.rules[a];for(const a of t){const o=await Ee.readFile(a.absolutePath,"utf-8"),i=Mu(o),l=r.rules[a.filePath];l?l.contentHash!==i&&(r.rules[a.filePath]={...l,contentHash:i,reviewed:!1}):r.rules[a.filePath]={contentHash:i,reviewed:!1}}return await Ru(e,r),r}async function sc(e,t,r,s){const a=await Iu(e);if(r){const o=se.join(e,".claude","rules"),i=se.join(o,t),l=await Ee.readFile(i,"utf-8"),c=Mu(l);a.rules[t]?(a.rules[t].reviewed=!0,a.rules[t].contentHash=c):a.rules[t]={contentHash:c,reviewed:!0}}else a.rules[t]&&(a.rules[t].reviewed=!1);await Ru(e,a)}function _i(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function Du(e,t=""){const r=[],s=await Ee.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;a.isDirectory()?r.push(...await Du(se.join(e,a.name),o)):a.name.endsWith(".md")&&r.push(o)}return r}function zs(e){if(!e||e==="(diff not available)")return!1;const t=e.split(`
539
+ `).filter(s=>!(!s.startsWith("+")&&!s.startsWith("-")||s.startsWith("+++")||s.startsWith("---"))).map(s=>s.substring(1).trim());if(t.length===0)return!1;const r=/^(category:\s*\w+)$/;return t.every(s=>r.test(s))}async function CC({request:e}){const t=Ne();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=new URL(e.url),s=r.searchParams.get("action"),a=se.join(t,".claude","rules");if(s==="recent-changes")return _C(t,a);if(s==="reviewed-status")return AC(t,a);if(s==="audit")return PC(t,a);if(s==="source-files")return jC(t);if(s==="rule-coverage")return TC(t,a);if(s==="rule-diff"){const o=r.searchParams.get("filePath");return o?EC(t,o):Response.json({error:"Missing required parameter: filePath"},{status:400})}if(s==="rules-for-path"){const o=r.searchParams.get("path");return o?MC(a,o):Response.json({error:"Missing required parameter: path"},{status:400})}try{const o=await ba(a),i=[];for(const u of o){const h=se.join(a,u);try{const m=await Ee.readFile(h,"utf-8"),f=await Ee.stat(h),{frontmatter:g,body:y}=Si(m);i.push({filePath:u,content:m,frontmatter:g,body:y,lastModified:f.mtime.toISOString()})}catch{}}i.sort((u,h)=>new Date(h.lastModified).getTime()-new Date(u.lastModified).getTime());let l=i.length>0;if(!l)try{await Ee.access(se.join(t,".claude","codeyam-rule-state.json")),l=!0}catch{}const c=await Yr(a),p={};if(c.length>0){const u=await ki(t,c);for(const h of c)p[h.filePath]=_i(u,h.filePath)}return Response.json({memories:i,memoryInitialized:l,reviewedStatus:p})}catch(o){return console.error("[API] Error loading memories:",o),Response.json({error:"Failed to load memories",details:o instanceof Error?o.message:String(o),memoryInitialized:!1},{status:500})}}async function kC(e,t){const r=[];try{const s=t("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const a of s.split(`
540
+ `).filter(Boolean)){const o=a.substring(0,2);let i=a.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const l=o[0],c=o[1];let p=[i];if(i.endsWith("/")&&l==="?"){const u=se.join(e,i);try{p=(await Du(u)).map(m=>i+m)}catch{continue}}for(const u of p){if(u.endsWith("/"))continue;const h=u.replace(".claude/rules/","");let m="modified";l==="A"||l==="?"?m="added":l==="D"||c==="D"?m="deleted":(l==="M"||c==="M")&&(m="modified");let f="";try{if(m==="deleted")f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(m==="added"&&l==="?"){const g=`${e}/${u}`;try{const y=await Ee.readFile(g,"utf-8");f=`diff --git a/${u} b/${u}
541
+ new file mode 100644
542
+ --- /dev/null
543
+ +++ b/${u}
544
+ @@ -0,0 +1,${y.split(`
545
+ `).length} @@
546
+ ${y.split(`
547
+ `).map(x=>"+"+x).join(`
548
+ `)}`}catch{f="(content not available)"}}else f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});f.length>5e3&&(f=f.substring(0,5e3)+`
549
+ ... (truncated)`)}catch{f="(diff not available)"}m==="modified"&&zs(f)||r.push({filePath:h,changeType:m,diff:f})}}}catch{}return r}async function _C(e,t){try{const{execSync:r}=await import("child_process"),s=[],a=await Yr(t),o={};if(a.length>0){const u=await ki(e,a);for(const h of a)o[h.filePath]=_i(u,h.filePath)}const l=(await kC(e,r)).filter(u=>!o[u.filePath]);l.length>0&&s.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:l});const p=r('git log --format="%H|%aI|%s" --since="60 days ago" -- .claude/rules/ 2>/dev/null || true',{cwd:e,encoding:"utf-8",maxBuffer:10*1024*1024}).split(`
550
+ `).filter(Boolean).slice(0,20);for(const u of p){const[h,m,...f]=u.split("|"),g=f.join("|");if(!h||!m)continue;const y=r(`git diff-tree --no-commit-id --name-status -r ${h} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),x=[];for(const b of y.split(`
551
+ `).filter(Boolean)){const[w,v]=b.split(" ");if(!v||!v.startsWith(".claude/rules/"))continue;const N=v.replace(".claude/rules/","");let S="modified";if(w==="A"?S="added":w==="D"&&(S="deleted"),o[N])continue;let C="";try{C=r(`git show ${h} --format="" -- "${v}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),C.length>5e3&&(C=C.substring(0,5e3)+`
552
+ ... (truncated)`)}catch{C="(diff not available)"}S==="modified"&&zs(C)||x.push({filePath:N,changeType:S,diff:C})}x.length>0&&s.push({commitHash:h.substring(0,8),date:m,message:g,files:x})}return Response.json({changes:s,reviewedStatus:o})}catch(r){return console.error("[API] Error getting recent changes:",r),Response.json({changes:[],reviewedStatus:{}})}}async function EC(e,t){try{const{execSync:r}=await import("child_process"),s=`.claude/rules/${t}`,a=r(`git rev-list --count HEAD -- "${s}" 2>/dev/null || echo 0`,{cwd:e,encoding:"utf-8"}),o=parseInt(a.trim(),10)||0,i=r(`git diff HEAD -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});if(i.trim()){if(zs(i))return Response.json({diff:null});const y=i.length>5e3?i.substring(0,5e3)+`
553
+ ... (truncated)`:i;return Response.json({diff:{diff:y,commitMessage:"Uncommitted changes",date:new Date().toISOString(),isUncommitted:!0,commitCount:o}})}if(r(`git status --porcelain -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim().startsWith("?")){const y=se.join(e,s);try{const x=await Ee.readFile(y,"utf-8"),b=`diff --git a/${s} b/${s}
554
+ new file mode 100644
555
+ --- /dev/null
556
+ +++ b/${s}
557
+ @@ -0,0 +1,${x.split(`
558
+ `).length} @@
559
+ ${x.split(`
560
+ `).map(w=>"+"+w).join(`
561
+ `)}`;return Response.json({diff:{diff:b.length>5e3?b.substring(0,5e3)+`
562
+ ... (truncated)`:b,commitMessage:"New file (untracked)",date:new Date().toISOString(),isUncommitted:!0,commitCount:0}})}catch{}}const p=r(`git log -1 --format="%H|%aI|%s" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim();if(!p)return Response.json({diff:null});const[u,h,...m]=p.split("|"),f=m.join("|");if(!u||!h)return Response.json({diff:null});let g=r(`git show ${u} --format="" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});return g.trim()?zs(g)?Response.json({diff:null}):(g.length>5e3&&(g=g.substring(0,5e3)+`
563
+ ... (truncated)`),Response.json({diff:{diff:g,commitMessage:f,date:h,isUncommitted:!1,commitCount:o}})):Response.json({diff:null})}catch(r){return console.error("[API] Error getting rule diff:",r),Response.json({diff:null})}}async function AC(e,t){try{const r=await Yr(t),s={};if(r.length>0){const a=await ki(e,r);for(const o of r)s[o.filePath]=_i(a,o.filePath)}return Response.json({reviewedStatus:s})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function PC(e,t){try{const r=await Yr(t),s=await Ci(e),a=[];for(const o of s){const i=r.filter(l=>Tu(o,l));if(i.length>0){const l=i.reduce((c,p)=>c+p.body.length,0);a.push({filePath:o,matchingRules:i.map(c=>({filePath:c.filePath,patterns:c.frontmatter.paths||[],bodyLength:c.body.length})),totalTextLength:l})}}return a.sort((o,i)=>i.totalTextLength-o.totalTextLength),Response.json({topPaths:a,totalFilesWithCoverage:a.length,allSourceFiles:s})}catch(r){return console.error("[API] Error getting audit data:",r),Response.json({error:"Failed to get audit data",details:r instanceof Error?r.message:String(r)},{status:500})}}async function jC(e){try{const t=await Ci(e);return Response.json({files:t})}catch(t){return console.error("[API] Error getting source files:",t),Response.json({error:"Failed to get source files",details:t instanceof Error?t.message:String(t)},{status:500})}}async function TC(e,t){try{const[r,s]=await Promise.all([Yr(t),Ci(e)]),a={};for(const o of r)a[o.filePath]=vC(o,s).length;return Response.json({coverage:a})}catch(r){return console.error("[API] Error getting rule coverage:",r),Response.json({error:"Failed to get rule coverage",details:r instanceof Error?r.message:String(r)},{status:500})}}async function MC(e,t){try{const r=await ba(e),s=[];for(const o of r){const i=se.join(e,o);try{const l=await Ee.readFile(i,"utf-8"),c=await Ee.stat(i),{frontmatter:p,body:u}=Si(l);p.paths&&p.paths.some(h=>lo(t,h,{matchBase:!0}))&&s.push({filePath:o,content:l,frontmatter:p,body:u,lastModified:c.mtime.toISOString()})}catch{}}const a=s.reduce((o,i)=>o+i.body.length,0);return Response.json({rules:s,totalTextLength:a})}catch(r){return console.error("[API] Error getting rules for path:",r),Response.json({error:"Failed to get rules for path",details:r instanceof Error?r.message:String(r)},{status:500})}}async function $C({request:e}){const t=Ne();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=se.join(t,".claude","rules");try{const s=await e.json(),{action:a,filePath:o,content:i,lastModified:l}=s;if(!o)return Response.json({error:"Missing required field: filePath"},{status:400});if(a==="mark-reviewed")return await sc(t,o,!0),console.log(`[API] Rule marked as reviewed: ${o}`),Response.json({success:!0,message:"Rule marked as reviewed",filePath:o});if(a==="mark-unreviewed")return await sc(t,o,!1),console.log(`[API] Rule marked as unreviewed: ${o}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:o});const c=se.normalize(o);if(c.includes("..")||se.isAbsolute(c))return Response.json({error:"Invalid file path"},{status:400});const p=se.join(r,c);switch(a){case"create":case"update":return i?(await Ee.mkdir(se.dirname(p),{recursive:!0}),await Ee.writeFile(p,i,"utf-8"),console.log(`[API] Memory ${a}d: ${o}`),Response.json({success:!0,message:`Memory ${a}d successfully`,filePath:o})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await Ee.unlink(p),console.log(`[API] Memory deleted: ${o}`);const u=se.dirname(p);try{(await Ee.readdir(u)).length===0&&u!==r&&await Ee.rmdir(u)}catch{}return Response.json({success:!0,message:"Memory deleted successfully"})}catch(u){if(u.code==="ENOENT")return Response.json({error:"Memory not found"},{status:404});throw u}default:return Response.json({error:"Invalid action. Must be create, update, or delete"},{status:400})}}catch(s){return console.error("[API] Error managing memory:",s),Response.json({error:"Failed to manage memory",details:s instanceof Error?s.message:String(s)},{status:500})}}const IC=Object.freeze(Object.defineProperty({__proto__:null,action:$C,loader:CC},Symbol.toStringTag,{value:"Module"}));async function RC({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await Gt()),!r)return re({error:"Queue not initialized"},{status:500});const s=new URL(e.url),a=s.searchParams.get("queryType");if(!a)return re({error:"Missing queryType parameter for GET request"},{status:400});if(a==="job"){const i=s.searchParams.get("jobId");if(!i)return re({error:"Missing jobId parameter for job query"},{status:400});const l=r.getState();if(((o=l.currentlyExecuting)==null?void 0:o.id)===i)return re({jobId:i,status:"running",job:l.currentlyExecuting});const c=l.jobs.find(u=>u.id===i);if(c){const u=l.jobs.indexOf(c);return re({jobId:i,status:"queued",position:u,job:c})}const p=r.getJobResult(i);return p?re({jobId:i,status:p.status==="error"?"failed":"completed",error:p.error}):re({jobId:i,status:"completed"})}if(a==="full"){const i=r.getState(),l=await Promise.all(i.jobs.map(async p=>{const u=[];if(p.entityShas&&p.entityShas.length>0){const h=p.entityShas.map(f=>_n(f)),m=await Promise.all(h);u.push(...m.filter(f=>f!==null))}return{id:p.id,type:p.type,commitSha:p.commitSha,projectSlug:p.projectSlug,queuedAt:p.queuedAt,entities:u,filePaths:p.filePaths}}));let c;if(i.currentlyExecuting){const p=i.currentlyExecuting,u=[];if(p.entityShas&&p.entityShas.length>0){const h=p.entityShas.map(f=>_n(f)),m=await Promise.all(h);u.push(...m.filter(f=>f!==null))}c={id:p.id,type:p.type,commitSha:p.commitSha,projectSlug:p.projectSlug,queuedAt:p.queuedAt,entities:u,filePaths:p.filePaths}}return re({state:{...i,jobsWithEntities:l,currentlyExecutingWithEntities:c}})}return re({error:"Unknown queryType"},{status:400})}async function DC({request:e,context:t}){console.log("[Queue API] Received request"),console.log("[Queue API] Context keys:",Object.keys(t||{})),console.log("[Queue API] analysisQueue exists:",!!(t!=null&&t.analysisQueue));let r=t.analysisQueue;if(r||(r=await Gt(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),re({error:"Queue not initialized"},{status:500});const s=await e.json(),{action:a,...o}=s;if(console.log("[Queue API] Action:",a,"Params:",Object.keys(o)),a==="enqueue"){const{jobId:i,completion:l}=r.enqueue(o);return l.catch(c=>{console.error(`[Queue API] Job ${i} failed:`,c)}),re({jobId:i,status:"queued"})}if(a==="resume")return r.resume(),re({status:"resumed"});if(a==="pause")return r.pause(),re({status:"paused"});if(a==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?re({status:"removed",jobId:i}):re({error:"Job not found in queue"},{status:404}):re({error:"Missing jobId parameter"},{status:400})}if(a==="clear"){const i=r.clearQueue();return re({status:"cleared",count:i})}if(a==="reorder"){const{jobId:i,direction:l}=o;return!i||!l?re({error:"Missing jobId or direction parameter"},{status:400}):l!=="up"&&l!=="down"?re({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,l)?re({status:"reordered",jobId:i,direction:l}):re({error:"Could not reorder job (not found or at boundary)"},{status:400})}return re({error:"Unknown action"},{status:400})}const FC=Object.freeze(Object.defineProperty({__proto__:null,action:DC,loader:RC},Symbol.toStringTag,{value:"Module"})),OC=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],LC=et(function(){return Ke(),n(fa,{children:d("div",{className:"h-screen bg-[#F8F7F6] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:d("div",{className:"flex items-center h-full px-6 gap-6",children:[d("div",{className:"flex items-center gap-3 min-w-0",children:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[d("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),d("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:d("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[d("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded bg-[#343434] text-[#efefef] font-semibold h-8",children:["Scenarios",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),d("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),d("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(Au,{selectedScenario:null,analysis:void 0,entity:{sha:"mock-sha",name:"Dashboard",filePath:"codeyam-cli/src/webserver/app/routes/_index.tsx",entityType:"visual"},viewMode:"screenshot",cacheBuster:Date.now(),hasScenarios:!1,isAnalyzing:!1,projectSlug:null,hasAnApiKey:!0})]})]})})}),BC=Object.freeze(Object.defineProperty({__proto__:null,default:LC,meta:OC},Symbol.toStringTag,{value:"Module"})),zC=()=>[{title:"Settings - CodeYam"},{name:"description",content:"Configure project settings"}];async function YC({request:e}){var t,r;try{const s=await ea();if(!s)return re({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Project configuration not found"});let a=!1;try{const c=await Ye();if(c){const{project:p}=await De(c);a=((r=(t=p.metadata)==null?void 0:t.labs)==null?void 0:r.simulations)===!0}}catch{}const o=Ne()||process.cwd(),i=await ta(o),l=fd(s.projectSlug);return re({config:s,secrets:{GROQ_API_KEY:i.GROQ_API_KEY||"",ANTHROPIC_API_KEY:i.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:i.OPENAI_API_KEY||""},versionInfo:l,simulationsEnabled:a,error:null})}catch(s){return console.error("Failed to load config:",s),re({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Failed to load configuration"})}}function WC(e){if(!e||!e.trim())return;const t=e.trim().split(/\s+/);if(t.length===0)return;const r=t[0],s=t.length>1?t.slice(1):void 0;return{command:r,args:s}}async function UC({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),s=t.get("startCommands"),a=t.get("groqApiKey"),o=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),l=t.get("pathsToIgnore"),c=t.get("memorySettings");let p;if(r)try{p=JSON.parse(r)}catch{return re({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let u;if(s)try{u=JSON.parse(s)}catch{return re({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let h;l&&(h=l.split(",").map(x=>x.trim()).map(x=>x.startsWith('"')&&x.endsWith('"')||x.startsWith("'")&&x.endsWith("'")?x.slice(1,-1):x).filter(x=>x.length>0));let m;if(c)try{m=JSON.parse(c)}catch{return re({success:!1,error:"Invalid memorySettings JSON format",requiresRestart:!1},{status:400})}let f;if(u){const x=await ea();x!=null&&x.webapps&&(f=x.webapps.map((b,w)=>{if(u[w]!==void 0){const v=WC(u[w]);return{...b,startCommand:v}}return b}))}if(!await id({universalMocks:p,pathsToIgnore:h,webapps:f,memory:m}))return re({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let y=!1;if(a!==void 0||o!==void 0||i!==void 0){const x=Ne()||process.cwd(),b=await ta(x);y=a!==void 0&&a!==(b.GROQ_API_KEY||"")||o!==void 0&&o!==(b.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(b.OPENAI_API_KEY||""),await Lf(x,{...b,GROQ_API_KEY:a||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return re({success:!0,error:null,requiresRestart:y})}catch(t){return console.log("[Settings Action] Failed to save config:",t),re({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function ac(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function oc({mock:e,onSave:t,onCancel:r}){const[s,a]=P(e.entityName),[o,i]=P(e.filePath),[l,c]=P(e.content);return d("div",{className:"space-y-3",children:[d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:s,onChange:u=>a(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., determineDatabaseType"})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:o,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:l,onChange:u=>c(u.target.value),rows:6,className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., function determineDatabaseType() { return 'postgresql' }"})]}),d("div",{className:"flex gap-2 justify-end",children:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!s.trim()||!o.trim()||!l.trim()){alert("All fields are required");return}t({entityName:s,filePath:o,content:l})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function JC(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const HC=et(function(){var Te,$e,Re,X,ye;const{config:t,secrets:r,versionInfo:s,simulationsEnabled:a,error:o}=st(),i=Sp(),l=Ke(),c=Ut(),[p,u]=P(a?"project-metadata":"memory");Dt({source:"settings-page"});const[h,m]=P((t==null?void 0:t.universalMocks)||[]),[f,g]=P(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[y,x]=P(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[b,w]=P((r==null?void 0:r.GROQ_API_KEY)||""),[v,N]=P((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[S,C]=P((r==null?void 0:r.OPENAI_API_KEY)||""),[A,_]=P(!1),[E,R]=P(!1),[D,T]=P(!1),[$,L]=P(!1),[B,H]=P(!1),[q,O]=P(!1),[W,I]=P(null),[j,k]=P(!1),[Y,G]=P({}),[Q,K]=P(((Te=t==null?void 0:t.memory)==null?void 0:Te.conversationReflection)??!0),[F,M]=P((($e=t==null?void 0:t.memory)==null?void 0:$e.ruleMaintenance)??!0),[z,J]=P(((Re=t==null?void 0:t.memory)==null?void 0:Re.promptModel)??"haiku");ae(()=>{var ee,ne,xe,Me;if(t){m(t.universalMocks||[]);const he=(t.pathsToIgnore||[]).join(", ");g(he),x(he);const He={};(ee=t.webapps)==null||ee.forEach((Ve,Oe)=>{Ve.startCommand&&(He[Oe]=ac(Ve.startCommand))}),G(He),K(((ne=t.memory)==null?void 0:ne.conversationReflection)??!0),M(((xe=t.memory)==null?void 0:xe.ruleMaintenance)??!0),J(((Me=t.memory)==null?void 0:Me.promptModel)??"haiku")}r&&(w(r.GROQ_API_KEY||""),N(r.ANTHROPIC_API_KEY||""),C(r.OPENAI_API_KEY||""))},[t,r]),ae(()=>{if(i!=null&&i.success){L(!0);const ee=setTimeout(()=>L(!1),3e3);return()=>clearTimeout(ee)}},[i]),ae(()=>{if(l.state==="idle"&&l.data&&!q){console.log("[Settings] Fetcher data:",l.data);const ee=l.data;if(ee.success){console.log("[Settings] Save successful, revalidating..."),L(!0),O(!0),(f!==y||ee.requiresRestart)&&H(!0),c.revalidate();const ne=setTimeout(()=>{L(!1),O(!1)},3e3);return()=>clearTimeout(ne)}}},[l.state,l.data,q,c,f,y]);const te=ee=>{ee.preventDefault();const ne=new FormData(ee.currentTarget);ne.set("universalMocks",JSON.stringify(h)),ne.set("startCommands",JSON.stringify(Y)),ne.set("memorySettings",JSON.stringify({conversationReflection:Q,ruleMaintenance:F,promptModel:z})),console.log("[Settings] Submitting form data:",{universalMocks:ne.get("universalMocks"),startCommands:ne.get("startCommands"),openAiApiKey:ne.get("openAiApiKey")?"***":"(empty)"}),l.submit(ne,{method:"post"})},oe=ee=>{m([...h,ee]),k(!1)},de=(ee,ne)=>{const xe=[...h];xe[ee]=ne,m(xe),I(null)},ue=ee=>{m(h.filter((ne,xe)=>xe!==ee))};if(o)return d("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:o})})]});const me=[{id:"project-metadata",label:"Project Metadata"},{id:"ai-provider",label:"AI Provider Configuration"},{id:"commands",label:"Commands"},{id:"paths-to-ignore",label:"Paths To Ignore"},{id:"universal-mocks",label:"Universal Mocks"},{id:"memory",label:"Memory"},{id:"current-configuration",label:"Current Configuration"}],Se=a?me:me.filter(ee=>ee.id==="memory");return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-6 sm:px-12 lg:px-20 pt-8 pb-12 font-sans",children:[d("div",{className:"mb-8 flex justify-between items-start",children:[d("div",{children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Settings"}),n("p",{className:"text-[15px] text-gray-500",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:l.state==="submitting",className:"px-6 py-2 bg-[#005C75] text-white border-none rounded text-sm font-medium cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 hover:bg-[#004a5d] whitespace-nowrap",children:l.state==="submitting"?"Saving...":"Save Settings"})]}),($||B||(i==null?void 0:i.error)||l.data&&typeof l.data=="object"&&"error"in l.data)&&d("div",{className:"mb-4 space-y-3",children:[$&&n("div",{className:"text-emerald-600 text-sm font-medium bg-emerald-50 border border-emerald-200 rounded px-4 py-2",children:"Settings saved successfully!"}),B&&d("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[n("div",{children:"Settings changed. Please restart CodeYam for changes to take effect:"}),d("div",{className:"flex items-center gap-2 mt-1",children:[n("code",{className:"bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"}),n(ct,{content:"codeyam stop && codeyam",className:"px-2 py-1 text-xs bg-amber-200 hover:bg-amber-300 text-amber-800 rounded border-none transition-colors"})]})]}),(i==null?void 0:i.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:i.error}),(()=>{if(l.data&&typeof l.data=="object"&&"error"in l.data){const ee=l.data;return typeof ee.error=="string"?n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:ee.error}):null}return null})()]}),d("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8 items-start",children:[n("nav",{className:"w-full lg:w-64 flex-shrink-0",children:n("ul",{className:"flex lg:flex-col overflow-x-auto gap-1",children:Se.map(ee=>n("li",{children:n("button",{type:"button",onClick:()=>u(ee.id),className:`w-full text-left px-3 lg:px-0 py-2.5 text-sm transition-colors cursor-pointer whitespace-nowrap ${p===ee.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:ee.label})},ee.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:d("form",{id:"settings-form",onSubmit:te,className:"space-y-6",children:[p==="project-metadata"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),d("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((ee,ne)=>{var xe;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:d("div",{className:"space-y-2 text-sm",children:[d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:ee.path==="."?"Root":ee.path})]}),ee.appDirectory&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:ee.appDirectory})]}),d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:ee.framework})]}),ee.startCommand&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",d("span",{className:"text-gray-900 font-mono text-xs",children:[ee.startCommand.command," ",(xe=ee.startCommand.args)==null?void 0:xe.join(" ")]})]})]})},ne)})}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"}),n("p",{className:"mt-2 text-sm text-gray-600",children:"Web applications are detected during initialization. To modify, edit `.codeyam/config.json` or re-run `codeyam init`."})]})]}),p==="ai-provider"&&d("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),d("div",{className:"space-y-6",children:[d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),d("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:A?"text":"password",id:"groqApiKey",name:"groqApiKey",value:b,onChange:ee=>w(ee.target.value),placeholder:"gsk_...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>_(!A),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:A?"Hide":"Show"})]})]})]}),d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),d("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:E?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:v,onChange:ee=>N(ee.target.value),placeholder:"sk-ant-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>R(!E),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:E?"Hide":"Show"})]})]})]}),d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),d("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:D?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:S,onChange:ee=>C(ee.target.value),placeholder:"sk-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>T(!D),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:D?"Hide":"Show"})]})]})]})]})]}),p==="commands"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((ee,ne)=>d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[d("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:ee.path==="."?"Root":ee.path}),n("div",{className:"text-sm text-gray-600",children:ee.framework})]}),d("div",{children:[n("label",{htmlFor:`startCommand-${ne}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${ne}`,name:`startCommand-${ne}`,value:Y[ne]||"",onChange:xe=>G({...Y,[ne]:xe.target.value}),placeholder:"e.g., pnpm dev --port $PORT",className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("p",{className:"mt-2 text-xs text-gray-500",children:"Use $PORT as a placeholder for the dynamic port number"})]})]},ne))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),p==="paths-to-ignore"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:f,onChange:ee=>g(ee.target.value),placeholder:"e.g., __tests__, \\.test\\.ts$, ^background (no quotes needed)",className:"w-full px-3 py-3 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-2 focus:ring-[#005C75]/10"}),d("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),p==="universal-mocks"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),h.length===0?d("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>k(!0),className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}):n("div",{className:"space-y-3",children:h.map((ee,ne)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:W===ne?n(oc,{mock:ee,onSave:xe=>de(ne,xe),onCancel:()=>I(null)}):n(we,{children:d("div",{className:"flex justify-between items-start mb-2",children:[d("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:ee.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:ee.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:ee.content})]}),d("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>I(ne),className:"px-3 py-1 bg-teal-600 text-white border-none rounded text-sm cursor-pointer hover:bg-teal-700",children:"Edit"}),n("button",{type:"button",onClick:()=>ue(ne),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},ne))}),h.length>0&&n("button",{type:"button",onClick:()=>k(!0),className:"mt-4 px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}),p==="memory"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Memory"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure how CodeYam reflects on conversations and maintains rules between sessions."}),d("div",{className:"space-y-6",children:[n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Conversation Reflection"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent reviews the session for architectural decisions, tribal knowledge, confusion, or corrections that future sessions would benefit from knowing. It creates or updates Claude Rules based on what it learns."})]}),n("button",{type:"button",role:"switch","aria-checked":Q,onClick:()=>K(!Q),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${Q?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${Q?"translate-x-5":"translate-x-0"}`})})]})}),n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Rule Maintenance"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent checks if any existing Claude Rules have become stale based on recent code changes. It reviews the rule content against file diffs and updates rules that are out of date."})]}),n("button",{type:"button",role:"switch","aria-checked":F,onClick:()=>M(!F),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${F?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${F?"translate-x-5":"translate-x-0"}`})})]})}),d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Memory Prompt Model"}),n("p",{className:"text-sm text-gray-600 mb-4",children:"Choose the Claude model used for conversation reflection and rule maintenance tasks."}),n("div",{className:"space-y-3",children:[{value:"haiku",label:"Haiku",badge:"Default, Recommended",description:"Fastest and cheapest. Good for routine reflection tasks."},{value:"sonnet",label:"Sonnet",badge:null,description:"Balanced speed and quality. Better at nuanced rule writing."},{value:"opus",label:"Opus",badge:null,description:"Highest quality. Best for complex architectural decisions. Costs significantly more."}].map(ee=>d("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${z===ee.value?"border-[#005C75] bg-[#005C75]/5":"border-gray-200 hover:border-gray-300"}`,children:[n("input",{type:"radio",name:"promptModel",value:ee.value,checked:z===ee.value,onChange:()=>J(ee.value),className:"mt-1 accent-[#005C75]"}),d("div",{children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-gray-900",children:ee.label}),ee.badge&&n("span",{className:"px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:ee.badge})]}),n("p",{className:"text-sm text-gray-600 mt-0.5",children:ee.description})]})]},ee.value))})]})]})]}),p==="current-configuration"&&d("div",{className:"space-y-6",children:[t&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:d("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&d("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((ee,ne)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:d("div",{className:"space-y-2 text-sm",children:[d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:ee.path==="."?"Root":ee.path})]}),ee.appDirectory&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:ee.appDirectory})]}),d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:ee.framework})]}),ee.startCommand&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:ac(ee.startCommand)})]})]})},ne))})]})]}),s&&d("div",{className:"mt-6",children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:d("div",{className:"space-y-2 text-sm",children:[s.webserverVersion&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",n("span",{className:"text-gray-900 font-mono",children:s.webserverVersion.version||"unknown"})]}),s.templateVersion&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",n("span",{className:"font-mono text-gray-900",children:s.templateVersion.version||((X=s.templateVersion.gitCommit)==null?void 0:X.slice(0,7))||"unknown"}),s.templateVersion.buildTimestamp&&d("span",{className:"text-gray-500 ml-2",children:["(built"," ",JC(s.templateVersion.buildTimestamp),")"]})]}),s.cachedAnalyzerVersion&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"font-mono text-gray-900",children:s.cachedAnalyzerVersion.version||((ye=s.cachedAnalyzerVersion.gitCommit)==null?void 0:ye.slice(0,7))||"unknown"}),s.isCacheStale?n("span",{className:"ml-2 px-2 py-0.5 bg-amber-100 text-amber-800 rounded text-xs",children:"Stale - will update on next analysis"}):n("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]}),!s.cachedAnalyzerVersion&&(t==null?void 0:t.projectSlug)&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),j&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:d("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[n("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),n(oc,{mock:{entityName:"",filePath:"",content:""},onSave:oe,onCancel:()=>k(!1)})]})})]})})}),VC=Object.freeze(Object.defineProperty({__proto__:null,action:UC,default:HC,loader:YC,meta:zC},Symbol.toStringTag,{value:"Module"}));async function GC({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=Ne();if(!r)return new Response("Project root not found",{status:500});const a=se.extname(t)!==""?t:`${t}.html`,o=se.join(r,".codeyam","captures","static",a);try{await Ee.access(o);let i=await Ee.readFile(o);const l=se.extname(o).toLowerCase();let c="application/octet-stream";if(l===".html"){c="text/html";let p=i.toString("utf-8");const u=p.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const m=u[1].match(/=\s*(\{[\s\S]*\})/);if(m){const f=JSON.parse(m[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const g=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;p=p.replace(u[0],g)}}catch(h){console.error("[Static] Failed to parse Remix context:",h)}i=Buffer.from(p,"utf-8")}else l===".js"||l===".mjs"?c="application/javascript":l===".css"?c="text/css":l===".json"?c="application/json":l===".png"?c="image/png":l===".jpg"||l===".jpeg"?c="image/jpeg":l===".svg"?c="image/svg+xml":l===".woff"?c="font/woff":l===".woff2"?c="font/woff2":l===".ttf"&&(c="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":c,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const KC=Object.freeze(Object.defineProperty({__proto__:null,loader:GC},Symbol.toStringTag,{value:"Module"}));function qC(e,t,r=10){var c;const s=new Map,a=p=>p.entityType==="visual"||p.entityType==="library";for(const p of e)a(p)&&s.set(p.sha,{entity:p,depth:0});const o=new Map;for(const p of t){const u=(c=p.metadata)==null?void 0:c.importedBy;if(u)for(const h of Object.keys(u))for(const m of Object.keys(u[h])){const{shas:f}=u[h][m];for(const g of f)o.has(p.sha)||o.set(p.sha,new Set),o.get(p.sha).add(g)}}const i=[],l=new Set;for(const p of e)i.push({sha:p.sha,depth:0}),l.add(p.sha);for(;i.length>0;){const{sha:p,depth:u}=i.shift();if(u>=r)continue;const h=o.get(p);if(h)for(const m of h){if(l.has(m))continue;l.add(m);const f=t.find(g=>g.sha===m);if(f){if(a(f)){const g=u+1,y=s.get(m);(!y||g<y.depth)&&s.set(m,{entity:f,depth:g})}i.push({sha:m,depth:u+1})}}}return Array.from(s.values()).sort((p,u)=>p.depth!==u.depth?p.depth-u.depth:p.entity.name.localeCompare(u.entity.name))}function Ys(e){const t=new Map;for(const s of e)t.has(s.name)||t.set(s.name,[]),t.get(s.name).push(s);const r=[];for(const s of t.values())if(s.length===1)r.push(s[0]);else{const a=s.sort((o,i)=>{var p,u;const l=((p=o.metadata)==null?void 0:p.editedAt)||o.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(l)});r.push(a[0])}return r}function Fu(e,t){const r=new Map,s=new Set(e.map(a=>a.path));for(const a of e)a.status==="renamed"&&a.oldPath&&s.add(a.oldPath);for(const a of e){const o=t.filter(c=>c.filePath===a.path||a.status==="renamed"&&a.oldPath&&c.filePath===a.oldPath),i=o.filter(c=>{var p,u;return s.has(c.filePath)&&((p=c.metadata)==null?void 0:p.isUncommitted)&&!((u=c.metadata)!=null&&u.isSuperseded)}),l=Ys(i);r.set(a.path,{status:a,entities:o,editedEntities:l})}return r}function QC(e,t,r){const s=new Map;if(!r){for(const o of e)if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const i=t.filter(c=>c.filePath===o.path||o.status==="renamed"&&o.oldPath&&c.filePath===o.oldPath),l=Ys(i);s.set(o.path,{status:o,entities:l})}return s}const a=new Map;for(const o of r.fileComparisons){const i=new Set;for(const l of o.newEntities)i.add(l.name);for(const l of o.modifiedEntities)i.add(l.name);for(const l of o.deletedEntities)i.add(l.name);i.size>0&&a.set(o.filePath,i)}for(const o of e){const i=a.get(o.path);if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const l=i?t.filter(p=>(p.filePath===o.path||o.status==="renamed"&&o.oldPath&&p.filePath===o.oldPath)&&i.has(p.name)):[],c=Ys(l);s.set(o.path,{status:o,entities:c})}}return s}function ZC(e,t){const r=new Map,s=Ou(e,t);for(const a of s){const i=qC([a],t).filter(({depth:l})=>l>0);r.set(a.sha,i)}return r}function Ou(e,t){const r=new Set(e.map(a=>a.path));for(const a of e)a.status==="renamed"&&a.oldPath&&r.add(a.oldPath);const s=t.filter(a=>{var o,i;return r.has(a.filePath)&&((o=a.metadata)==null?void 0:o.isUncommitted)&&!((i=a.metadata)!=null&&i.isSuperseded)});return Ys(s)}function XC({recentSimulations:e}){const t=ie(()=>{const r=new Map;return e.forEach(s=>{const a=s.entitySha,o=r.get(a);o?o.push(s):r.set(a,[s])}),Array.from(r.entries()).map(([s,a])=>({entitySha:s,entityName:a[0].entityName,scenarios:a}))},[e]);return d("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:d("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:e.length>0?`Latest ${e.length} captured screenshot${e.length!==1?"s":""}`:"No simulations captured yet"})]})}),e.length>0?d(we,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>d("div",{children:[d("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(Pr,{size:16,style:{color:"#8B5CF6"}})}),n(Ce,{to:`/entity/${r.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:r.entityName})]}),n("div",{className:"grid grid-cols-4 gap-3",children:r.scenarios.map((s,a)=>n(Ce,{to:s.scenarioId?`/entity/${s.entitySha}/scenarios/${s.scenarioId}`:`/entity/${s.entitySha}`,className:"aspect-4/3 border border-gray-200 rounded-lg overflow-hidden bg-gray-50 transition-all flex items-center justify-center hover:scale-105",onMouseEnter:o=>{o.currentTarget.style.borderColor="#005C75",o.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:o=>{o.currentTarget.style.borderColor="#E5E7EB",o.currentTarget.style.boxShadow="none"},title:s.scenarioName,children:n(lt,{screenshotPath:s.screenshotPath,alt:s.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},s.scenarioId||`${s.entitySha}-${a}`))})]},r.entitySha))}),n(Ce,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:r=>r.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:r=>r.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):d("div",{className:"py-12 px-6 text-center rounded-lg w-full flex flex-col items-center justify-center min-h-50 border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:n(Pr,{size:24,style:{color:"#7A9BA5"},strokeWidth:1.5})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No simulations captured yet."}),d("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",n(Ce,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(Ce,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const e1="/assets/codeyam-name-logo-CvKwUgHo.svg",t1=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function n1({request:e,context:t}){var r,s,a,o,i;try{const l=await Ye();if(l){const{project:$}=await De(l),L=((r=$.metadata)==null?void 0:r.editorMode)??!1;if(!(((a=(s=$.metadata)==null?void 0:s.labs)==null?void 0:a.simulations)??!1)||L)return Cp("/memory")}const c=t.analysisQueue,p=c?c.getState():{paused:!1,jobs:[]},[u,h]=await Promise.all([Pn(),rr()]),m=or(),f=u?Fu(m,u):new Map,g=Array.from(f.entries()).sort(($,L)=>$[0].localeCompare(L[0])),y=(u==null?void 0:u.length)||0,x=(u==null?void 0:u.filter($=>$.entityType==="visual").length)||0,b=(u==null?void 0:u.filter($=>$.entityType==="library").length)||0,w=u?Ou(m,u):[],v=w.length,N=(u==null?void 0:u.filter($=>($.analyses??[]).filter(L=>L.scenarios&&L.scenarios.length>0).length>0).length)||0,S=(u==null?void 0:u.reduce(($,L)=>{var H,q,O;const B=((O=(q=(H=L.analyses)==null?void 0:H[0])==null?void 0:q.scenarios)==null?void 0:O.length)||0;return $+B},0))||0,C=(u==null?void 0:u.reduce(($,L)=>{var q,O;const H=(((O=(q=L.analyses)==null?void 0:q[0])==null?void 0:O.scenarios)||[]).filter(W=>{var I,j;return(j=(I=W.metadata)==null?void 0:I.screenshotPaths)==null?void 0:j[0]}).length;return $+H},0))||0,A=[];u==null||u.forEach($=>{var B;const L=(B=$.analyses)==null?void 0:B[0];L!=null&&L.scenarios&&L.scenarios.filter(q=>{var O;return!((O=q.metadata)!=null&&O.sameAsDefault)}).forEach(q=>{var W,I;const O=(I=(W=q.metadata)==null?void 0:W.screenshotPaths)==null?void 0:I[0];O&&A.push({entitySha:$.sha,entityName:$.name,scenarioId:q.id,scenarioName:q.name,screenshotPath:O,createdAt:L.createdAt||""})})}),A.sort(($,L)=>new Date(L.createdAt).getTime()-new Date($.createdAt).getTime());const _=A.slice(0,16),E=(u==null?void 0:u.filter($=>$.entityType==="visual").filter($=>{var H,q;const L=(H=$.analyses)==null?void 0:H[0];return!((q=L==null?void 0:L.scenarios)==null?void 0:q.some(O=>{var W,I;return(I=(W=O.metadata)==null?void 0:W.screenshotPaths)==null?void 0:I[0]}))}).slice(0,8))||[],R=(o=h==null?void 0:h.metadata)==null?void 0:o.currentRun,D=((i=R==null?void 0:R.currentEntityShas)==null?void 0:i.length)||0,T=p.jobs.length||0;return re({stats:{totalEntities:y,visualEntities:x,libraryEntities:b,uncommittedEntities:v,entitiesWithAnalyses:N,totalScenarios:S,capturedScreenshots:C,currentlyAnalyzing:D,filesOnQueue:T},uncommittedFiles:g,uncommittedEntitiesList:w,recentSimulations:_,visualEntitiesForSimulation:E,projectSlug:l,queueState:p,currentCommit:h})}catch(l){return console.error("Failed to load dashboard data:",l),re({stats:{totalEntities:0,visualEntities:0,libraryEntities:0,uncommittedEntities:0,entitiesWithAnalyses:0,totalScenarios:0,capturedScreenshots:0,currentlyAnalyzing:0,filesOnQueue:0},uncommittedFiles:[],uncommittedEntitiesList:[],recentSimulations:[],visualEntitiesForSimulation:[],projectSlug:null,queueState:{paused:!1,jobs:[]},currentCommit:null,error:"Failed to load dashboard data"})}}const r1=et(function(){var W,I;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:s,recentSimulations:a,visualEntitiesForSimulation:o,projectSlug:i,queueState:l,currentCommit:c}=st(),p=Ke(),u=Ut(),{showToast:h}=Oo();Dt({source:"dashboard"});const[m,f]=P(new Set),[g,y]=P(null),[x,b]=P(!1),[w,v]=P(!1),{lastLine:N,isCompleted:S}=Jt(i,!!g),{simulatingEntity:C,scenarios:A,scenarioStatuses:_,allScenariosCaptured:E}=ie(()=>{var M,z;const j={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!g)return j;const k=o==null?void 0:o.find(J=>J.sha===g);if(!k)return j;const Y=(M=k.analyses)==null?void 0:M[0],G=(Y==null?void 0:Y.scenarios)||[],Q=((z=Y==null?void 0:Y.status)==null?void 0:z.scenarios)||[],K=Q.filter(J=>J.screenshotFinishedAt).length,F=G.length>0&&K===G.length;return{simulatingEntity:k,scenarios:G,scenarioStatuses:Q,allScenariosCaptured:F}},[g,o]);ae(()=>{(S||E)&&y(null)},[S,E]);const R=(W=c==null?void 0:c.metadata)==null?void 0:W.currentRun,D=new Set((R==null?void 0:R.currentEntityShas)||[]),T=new Set(l.jobs.flatMap(j=>j.entityShas||[])),$=new Set(((I=l.currentlyExecuting)==null?void 0:I.entityShas)||[]),L=s.filter(j=>j.entityType==="visual"||j.entityType==="library"),B=L.filter(j=>!D.has(j.sha)&&!T.has(j.sha)&&!$.has(j.sha)),H=()=>{if(B.length===0){h("All entities are already queued or analyzing","info",3e3);return}const j=B.map(k=>k.sha);v(!0),h(`Starting analysis for ${B.length} entities...`,"info",3e3),p.submit({entityShas:j.join(",")},{method:"post",action:"/api/analyze"})};ae(()=>{if(p.state==="idle"&&p.data){const j=p.data;j.success?(console.log("[Analyze All] Success:",j.message),h(`Analysis started for ${j.entityCount} entities in ${j.fileCount} files. Watch the logs for progress.`,"success",6e3),v(!1)):j.error&&(console.error("[Analyze All] Error:",j.error),h(`Error: ${j.error}`,"error",8e3),v(!1))}},[p.state,p.data,h]);const q=j=>{f(k=>{const Y=new Set(k);return Y.has(j)?Y.delete(j):Y.add(j),Y})},O=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#005C75",tooltip:"In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested."},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981",tooltip:"Entities that have been analyzed by CodeYam and have generated scenarios."},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6",tooltip:"React components and visual elements that can be rendered and captured as screenshots."},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9",tooltip:"Reusable functions and utilities that can be independently tested."}];return n("div",{className:"bg-cygray-10 min-h-screen",children:d("div",{className:"px-20 pt-8 pb-12",children:[d("header",{className:"mb-8 flex justify-between items-center",children:[d("div",{className:"flex items-center gap-4",children:[n("img",{src:e1,alt:"CodeYam",className:"h-3.5"}),n("span",{className:"text-gray-400 text-sm",children:"|"}),n("h1",{className:"text-sm font-mono font-normal text-gray-400 m-0",children:i?i.replace(/-/g," ").replace(/\b\w/g,j=>j.toUpperCase()):"Project"})]}),u.state==="loading"&&n("div",{className:"text-blue-600 text-sm font-medium animate-pulse",children:"🔄 Updating..."})]}),n("div",{className:"flex items-center justify-between gap-3",children:O.map((j,k)=>n(Ce,{to:j.link,className:"flex-1 bg-white rounded-xl border border-gray-200 overflow-hidden flex transition-all hover:shadow-lg no-underline cursor-pointer",style:{borderLeft:`4px solid ${j.color}`},children:d("div",{className:"px-6 py-6 flex flex-col gap-3 flex-1",children:[d("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[d("div",{className:"flex items-center gap-1.5 group relative",children:[n("span",{className:"text-xs text-gray-700 font-medium font-mono uppercase",children:j.label}),d("svg",{className:"w-3 h-3 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:d("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[j.tooltip,n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 sm:hidden md:flex",style:{color:j.color},children:"View All →"})]}),d("div",{className:"flex flex-col gap-2",children:[d("div",{className:"flex items-center gap-3",children:[d("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${j.color}15`},children:[j.iconType==="folder"&&n(Zp,{size:20,style:{color:j.color}}),j.iconType==="check"&&n(Ao,{size:20,style:{color:j.color}}),j.iconType==="image"&&n(Pr,{size:20,style:{color:j.color}}),j.iconType==="code-xml"&&n(Xp,{size:20,style:{color:j.color}})]}),n("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:j.value.toLocaleString("en-US")})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:j.color},children:"View All →"})]})]})},k))}),d("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[d("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[d("div",{className:"flex justify-between items-start mb-5",children:[d("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),n("p",{className:"text-sm text-gray-500 m-0",children:r.length>0?`${r.length} file${r.length!==1?"s":""} with ${s.length} uncommitted entit${s.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),L.length>0&&n("button",{onClick:H,disabled:p.state!=="idle"||w||B.length===0,className:"px-5 py-2.5 text-white border-none rounded-lg text-sm font-semibold cursor-pointer transition-all hover:-translate-y-px disabled:bg-gray-400 disabled:cursor-not-allowed disabled:translate-y-0",style:{backgroundColor:"#005C75"},onMouseEnter:j=>j.currentTarget.style.backgroundColor="#004560",onMouseLeave:j=>j.currentTarget.style.backgroundColor="#005C75",children:p.state!=="idle"||w?"Starting analysis...":B.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([j,k])=>{const Y=m.has(j),G=k.editedEntities||[];return d("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#005C75"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>q(j),role:"button",tabIndex:0,children:d("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:Y?"▼":"▶"}),d("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[d("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),d("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:j}),d("span",{className:"text-xs text-gray-500",children:[G.length," entit",G.length!==1?"ies":"y"]})]})]})}),Y&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:G.length>0?G.map(Q=>{const K=D.has(Q.sha),F=T.has(Q.sha)||$.has(Q.sha);return d(Ce,{to:`/entity/${Q.sha}`,className:"flex items-center gap-4 p-4 bg-white border border-gray-200 rounded-lg no-underline transition-all hover:shadow-md hover:-translate-y-0.5",style:{borderColor:"inherit"},onMouseEnter:M=>M.currentTarget.style.borderColor="#005C75",onMouseLeave:M=>M.currentTarget.style.borderColor="inherit",children:[d("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:Q.entityType==="visual"?"#8B5CF615":Q.entityType==="library"?"#6366F1":"#EC4899"},children:[Q.entityType==="visual"&&n(Pr,{size:16,style:{color:"#8B5CF6"}}),Q.entityType==="library"&&n($c,{size:16,className:"text-white"}),Q.entityType==="other"&&n(eh,{size:16,className:"text-white"})]}),d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:Q.name}),Q.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),Q.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),Q.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),Q.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:Q.description})]}),d("div",{className:"flex items-center gap-2 shrink-0",children:[K&&d("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(Mt,{size:14,className:"animate-spin"}),"Analyzing..."]}),!K&&F&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!K&&!F&&n("button",{onClick:M=>{M.preventDefault(),M.stopPropagation(),h(`Starting analysis for ${Q.name}...`,"info",3e3),p.submit({entityShas:Q.sha},{method:"post",action:"/api/analyze"})},disabled:p.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:M=>M.currentTarget.style.backgroundColor="#004560",onMouseLeave:M=>M.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},Q.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},j)})}):d("div",{className:"py-12 px-6 text-center flex flex-col items-center rounded-lg min-h-50 justify-center border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:d("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#7A9BA5",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n("polyline",{points:"14 2 14 8 20 8"}),n("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),n("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!g&&n(XC,{recentSimulations:a}),g&&d("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:d("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:a.length>0?`Latest ${a.length} captured screenshot${a.length!==1?"s":""}`:"No simulations captured yet"})]})}),g&&d("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[C&&n("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:d("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(ht,{type:"visual"})}),d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",C.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:C.filePath})]})]})}),E?d("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[n("span",{className:"text-lg",children:"✅"}),d("span",{children:["Complete (",A.length," scenario",A.length!==1?"s":"",")"]})]}):N?d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Mt,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:N,children:N}),i&&n("button",{onClick:()=>b(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):p.state!=="idle"?d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Mt,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Mt,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),A.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:A.slice(0,8).map((j,k)=>{var z,J,te;const Y=(z=C==null?void 0:C.analyses)==null?void 0:z[0],G=xa(j,Y==null?void 0:Y.status,void 0,g||void 0,void 0),Q=(te=(J=j.metadata)==null?void 0:J.screenshotPaths)==null?void 0:te[0],K=G.isCaptured,F=G.status==="capturing"||G.status==="starting",M=G.hasError;return K?n(Ce,{to:`/entity/${g}`,className:"w-20 h-15 border-2 border-gray-200 rounded overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center no-underline hover:border-blue-600 hover:scale-105 hover:shadow-md",children:n(lt,{screenshotPath:Q,alt:j.name,title:j.name,className:"max-w-full max-h-full object-contain object-center"})},k):M?n("div",{className:"w-20 h-15 border-2 border-solid border-red-300 rounded bg-red-50 flex flex-col items-center justify-center text-lg",title:G.errorMessage||"Capture error",children:n("span",{className:"text-red-500",children:"⚠️"})},k):n("div",{className:"w-20 h-15 border-2 border-dashed border-gray-300 rounded bg-gray-50 flex items-center justify-center text-2xl",title:`${F?"Capturing":"Pending"} ${j.name}...`,children:n("span",{className:F?"animate-pulse":"text-gray-400",children:F?"⋯":"⏹️"})},k)})})]})]})]}),x&&i&&n(rn,{projectSlug:i,onClose:()=>b(!1)})]})})}),s1=Object.freeze(Object.defineProperty({__proto__:null,default:r1,loader:n1,meta:t1},Symbol.toStringTag,{value:"Module"}));function Lu({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(jh,{remarkPlugins:[Th],components:{h1:({children:s})=>n("h1",{className:"text-lg font-bold text-gray-900 mb-3 mt-6 first:mt-0 pb-1 border-b border-gray-200",children:s}),h2:({children:s})=>n("h2",{className:"text-base font-semibold text-gray-900 mb-2 mt-5 first:mt-0",children:s}),h3:({children:s})=>n("h3",{className:"text-sm font-semibold text-gray-800 mb-2 mt-4 first:mt-0",children:s}),p:({children:s})=>n("p",{className:"text-sm text-gray-700 mb-3 leading-relaxed",children:s}),ul:({children:s})=>n("ul",{className:"list-disc ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:s}),ol:({children:s})=>n("ol",{className:"list-decimal ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:s}),li:({children:s})=>n("li",{className:"leading-relaxed",children:s}),code:({children:s,className:a})=>(a==null?void 0:a.includes("language-"))?n("pre",{className:"bg-gray-100 rounded p-3 text-xs font-mono overflow-x-auto mb-3",children:n("code",{children:s})}):n("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono text-gray-800",children:s}),pre:({children:s})=>n(we,{children:s}),strong:({children:s})=>n("strong",{className:"font-semibold text-gray-900",children:s}),blockquote:({children:s})=>n("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic text-gray-600 mb-3",children:s}),table:({children:s})=>n("div",{className:"overflow-x-auto mb-3",children:n("table",{className:"min-w-full text-sm border-collapse border border-gray-200",children:s})}),thead:({children:s})=>n("thead",{className:"bg-gray-50",children:s}),th:({children:s})=>n("th",{className:"border border-gray-200 px-3 py-2 text-left font-semibold text-gray-900",children:s}),td:({children:s})=>n("td",{className:"border border-gray-200 px-3 py-2 text-gray-700",children:s}),a:({children:s,href:a})=>n("a",{href:a,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:s})},children:r})}function Bu(e){const t={name:"root",path:"",memories:[],children:new Map};for(const r of e){const s=r.filePath.split("/");s.pop();let a=t,o="";for(const i of s)o=o?`${o}/${i}`:i,a.children.has(i)||a.children.set(i,{name:i,path:o,memories:[],children:new Map}),a=a.children.get(i);s.length===0?t.memories.push(r):a.memories.push(r)}return t}function zu(e){let t=e.memories.length;for(const r of e.children.values())t+=zu(r);return t}function wa(e,t){var s;const r=e.match(/^#+ (.+)$/m);return r?r[1]:((s=t.split("/").pop())==null?void 0:s.replace(".md",""))||t}function Ar(e){return Math.round(e/3.5)}function Hn(e){const t=new Date(e),r=new Date;if(t.toDateString()===r.toDateString()){const c=r.getTime()-t.getTime(),p=Math.floor(c/(1e3*60)),u=Math.floor(c/(1e3*60*60));return p<3?"Just now":p<60?`${p}min ago`:u===1?"1h ago":`${u}h ago`}const a=t.toLocaleDateString("en-US",{month:"short"}),o=t.getDate(),i=t.getFullYear(),l=r.getFullYear();return i===l?`${a} ${o}`:`${a} ${o}, ${i}`}function a1({rule:e,onEdit:t,onDelete:r,onView:s,isReviewed:a,onToggleReviewed:o,changeType:i,isUncommitted:l,changeDate:c,diff:p,isFadingOut:u,showLeftBorder:h}){const[m,f]=P(!1),[g,y]=P(!1),x=ie(()=>wa(e.body,e.filePath),[e.body,e.filePath]),b=Ar(e.body.length),w=m?"#3e3e3e":l?"#d97706":"#c7c7c7",v=`rounded-lg border overflow-hidden transition-all ease-in-out ${l?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,N={...u&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return d("div",{className:v,style:N,children:[n("div",{className:`p-4 cursor-pointer ${l?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>s?s(e):f(!m),children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:m?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:w})})}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:l?"#78350f":"#000"},children:x}),i&&n("span",{className:`px-2 py-0.5 rounded uppercase font-medium tracking-wider ${i==="deleted"?"bg-red-100 text-red-700":""}`,style:{fontSize:"10px",...i==="added"&&{backgroundColor:"#CBF3FA",color:"#005C75"},...i==="modified"&&{backgroundColor:"#FFE8C1",color:"#C67E06"}},children:i}),l&&n("span",{className:"px-2 py-0.5 bg-amber-200 text-amber-800 rounded font-medium uppercase tracking-wider",style:{fontSize:"10px"},children:"Uncommitted"}),d("span",{className:"text-xs text-gray-400",children:["~",b.toLocaleString()," tokens"]})]}),n("div",{className:"flex items-center gap-2 text-xs text-gray-500 flex-wrap",children:e.frontmatter.paths&&e.frontmatter.paths.length>0&&d(we,{children:[e.frontmatter.paths.slice(0,2).map((S,C)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:S},C)),e.frontmatter.paths.length>2&&d("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-2," more"]})]})})]})]}),d("div",{className:"flex items-center gap-3 flex-shrink-0",children:[c&&n("span",{className:"text-xs text-gray-400",children:Hn(c)}),o&&n("button",{onClick:S=>{S.stopPropagation(),o(e.filePath,e.lastModified,a??!1)},className:`w-5 h-5 rounded-full border-2 flex items-center justify-center cursor-pointer transition-colors ${a?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,title:a?"Mark as unreviewed":"Mark as reviewed",children:a&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}),m&&d("div",{className:`border-t ${l?"border-amber-200":"border-gray-100"}`,children:[d("div",{className:`px-4 py-3 flex items-center justify-between ${l?"bg-amber-50":"bg-white"}`,children:[n("div",{className:"flex items-center gap-2",children:i==="modified"&&p&&d("button",{onClick:S=>{S.stopPropagation(),y(!g)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${g?l?"bg-amber-200 text-amber-900":"bg-gray-200 text-gray-900":l?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(Ts,{className:"w-3 h-3"}),g?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&d("div",{className:"flex items-center gap-2",children:[d("button",{onClick:S=>{S.stopPropagation(),t(e)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${l?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(th,{className:"w-3 h-3"}),"Edit"]}),d("button",{onClick:S=>{S.stopPropagation(),r(e)},className:"flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer text-red-600 hover:text-red-800 hover:bg-red-100",children:[n(nh,{className:"w-3 h-3"}),"Delete"]})]})]}),g&&p&&n("pre",{className:"mx-4 mb-4 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:p.split(`
564
+ `).map((S,C)=>{let A="";return S.startsWith("+")&&!S.startsWith("+++")?A="text-green-400":S.startsWith("-")&&!S.startsWith("---")?A="text-red-400":S.startsWith("@@")&&(A="text-cyan-400"),n("div",{className:A,children:S},C)})}),d("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Edit with Claude:"}),d("div",{className:"flex items-center gap-2",children:[d("span",{className:"px-2 py-1 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:["Claude, can you help me edit this rule: `",e.filePath,"`"]}),n(ct,{content:`Claude, can you help me edit this rule: \`${e.filePath}\``,icon:!0,iconSize:14,className:"p-1 text-gray-400 hover:text-gray-600 rounded transition-colors"})]})]}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&d("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Applies to paths:"}),n("div",{className:"flex flex-wrap gap-1.5",children:e.frontmatter.paths.map((S,C)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:S},C))})]}),!g&&n("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[500px] overflow-auto bg-white border-gray-200",children:n(Lu,{content:e.body})})]})]})}function o1(){return new Date().toISOString().split(".")[0]+"",`---
565
+ paths:
566
+ - '**/*.ts'
567
+ ---
568
+
569
+ ## Title
570
+
571
+ Description here.
572
+ `}function i1({rule:e,onSave:t,onCancel:r}){const[s,a]=P(e?`.claude/rules/${e.filePath}`:""),[o,i]=P((e==null?void 0:e.content)||o1()),[l,c]=P(!!e),[p,u]=P(!1),h=!e;return d("div",{className:"p-6",children:[d("div",{className:"flex items-center justify-between mb-4",children:[n("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),n("button",{onClick:r,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Xn,{className:"w-5 h-5"})})]}),h&&d("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:d("div",{className:"flex items-start gap-3",children:[n(Ts,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),d("div",{children:[n("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),n("p",{className:"text-sm text-[#0369a1] mb-2",children:"Run this command in Claude Code to create a properly formatted rule with the right file location and paths:"}),d("div",{className:"relative",children:[n("code",{className:"block bg-white px-3 py-2 pr-9 rounded border border-[#bae6fd] font-mono text-sm text-[#0c4a6e]",children:"/codeyam-new-rule"}),n("button",{onClick:()=>{navigator.clipboard.writeText("/codeyam-new-rule"),u(!0),setTimeout(()=>u(!1),2e3)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[#0284c7] hover:text-[#0c4a6e] cursor-pointer transition-colors",title:"Copy command",children:p?n(kt,{className:"w-4 h-4 text-green-500"}):n($t,{className:"w-4 h-4"})})]})]})]})}),d("button",{onClick:()=>c(!l),className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:l?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:l?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(l||!h)&&d("div",{className:"space-y-4",children:[d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),d("div",{className:"relative",children:[n("input",{type:"text",value:s,onChange:m=>a(m.target.value),placeholder:"e.g., src/webserver/architecture.md",className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm",disabled:!!e}),n("button",{onClick:()=>{navigator.clipboard.writeText(s)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy path",children:n($t,{className:"w-4 h-4"})})]})]}),e&&d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ask Claude for help editing:"}),d("div",{className:"relative",children:[n("input",{type:"text",value:`Claude, can you help me edit the rule: \`${s}\``,readOnly:!0,className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md bg-gray-50 font-mono text-sm text-gray-600"}),n("button",{onClick:()=>{navigator.clipboard.writeText(`Claude, can you help me edit the rule: \`${s}\``)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy prompt",children:n($t,{className:"w-4 h-4"})})]})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:o,onChange:m=>i(m.target.value),rows:20,className:"w-full px-3 py-2 border border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm bg-gray-900 text-gray-100 [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-track]:bg-gray-800 [&::-webkit-scrollbar-thumb]:bg-gray-600 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:hover:bg-gray-500 [&::-webkit-resizer]:bg-gray-700"})]}),d("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-[#001f3f] hover:text-[#001530] rounded-md cursor-pointer font-mono uppercase text-xs font-semibold",children:"Cancel"}),n("button",{onClick:()=>t(s.replace(/^\.claude\/rules\//,""),o),disabled:!s.trim()||!o.trim(),className:"px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer font-mono uppercase text-xs font-semibold",children:"Save"})]})]})]})}function l1({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:s,onToggleFolder:a}){const o=ie(()=>Bu(e),[e]),i=(p,u,h)=>{if(p.target.closest(".chevron-toggle")){h&&a(u||"root");return}const f=u||null;r(t===f?null:f),h&&!s.has(u||"root")&&a(u||"root")},l=p=>{r(t===p?null:p)},c=(p,u=0)=>{const h=s.has(p.path||"root"),m=zu(p),f=p.children.size>0,g=p.name==="root"?"(root)":p.name,y=p.memories.length>0||f,x=p.path||"",b=t===x||t===null&&x==="";return d("div",{children:[d("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${b?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${u*12+8}px`},onClick:w=>i(w,p.path,y),children:[y&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:w=>{w.stopPropagation(),a(p.path||"root")},children:n(on,{className:`w-3 h-3 text-gray-500 transition-transform ${h?"rotate-90":""}`})}),!y&&n("div",{className:"w-3"}),n(Rc,{className:"w-3.5 h-3.5 text-[#005C75]"}),n("span",{className:`text-xs font-mono font-semibold ${b?"text-[#005C75]":""}`,style:{color:"#005C75"},children:g}),d("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[m," rules"]})]}),h&&d("div",{className:"relative",children:[(p.memories.length>0||f)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${u*12+8+6}px`}}),p.memories.length>0&&n("div",{style:{paddingLeft:`${(u+1)*12+8}px`},children:p.memories.map(w=>{var N;const v=t===w.filePath;return n("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${v?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>l(w.filePath),children:n("span",{className:"text-xs",children:(N=w.filePath.split("/").pop())==null?void 0:N.replace(".md","")})},w.filePath)})}),f&&n("div",{children:Array.from(p.children.values()).sort((w,v)=>w.name.localeCompare(v.name)).map(w=>c(w,u+1))})]})]},p.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:c(o)})}function c1({memories:e,onEdit:t,onDelete:r,expandedFolders:s,onToggleFolder:a,reviewedStatus:o,onMarkReviewed:i,onMarkUnreviewed:l,onViewRule:c}){const[p,u]=P({});ae(()=>{u({})},[o]);const h=ie(()=>({...o,...p}),[o,p]),m=ie(()=>Bu(e),[e]),f=(y,x,b)=>{u(w=>({...w,[y]:!b})),b?l(y):i(y,x)},g=(y,x=0)=>{const b=s.has(y.path||"root"),w=y.children.size>0,v=y.name==="root"?"root":y.name,N=y.memories.length>0||w;return d("div",{children:[d("div",{className:"flex items-center gap-2 py-2 cursor-pointer hover:bg-gray-50 rounded px-2 mb-2",style:{backgroundColor:"rgba(224, 233, 236, 0.5)"},onClick:()=>N&&a(y.path||"root"),children:[N&&n(on,{className:`w-4 h-4 text-gray-500 transition-transform ${b?"rotate-90":""}`}),!N&&n("div",{className:"w-4"}),n(Rc,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:v})]}),b&&d("div",{className:"ml-10 space-y-4 relative",children:[(y.memories.length>0||w)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:"-24px"}}),y.memories.length>0&&n("div",{className:"space-y-2",children:y.memories.map(S=>n(a1,{rule:S,onEdit:t,onDelete:r,onView:c,isReviewed:h[S.filePath]??!1,onToggleReviewed:f},S.filePath))}),w&&n("div",{className:"space-y-4",children:Array.from(y.children.values()).sort((S,C)=>S.name.localeCompare(C.name)).map(S=>g(S,x+1))})]})]},y.path||"root")};return n("div",{children:g(m)})}function d1({memories:e,reviewedStatus:t,onViewRule:r,refreshKey:s}){const[a,o]=P("unreviewed"),[i,l]=P("by-date"),[c,p]=P(null),[u,h]=P(!0),[m,f]=P(new Map),g=fe(t),y=fe([]);ae(()=>()=>{y.current.forEach(clearTimeout)},[]),ae(()=>{(async()=>{h(!0);try{const C=await(await fetch("/api/memory?action=rule-coverage")).json();p(C.coverage??null)}catch{p(null)}finally{h(!1)}})()},[s]),ae(()=>{const N=g.current,S=[];for(const[C,A]of Object.entries(t))A&&!N[C]&&S.push(C);g.current=t,S.length!==0&&(f(C=>{const A=new Map(C);return S.forEach(_=>A.set(_,"approved")),A}),y.current.push(setTimeout(()=>{f(C=>{const A=new Map(C);return S.forEach(_=>A.set(_,"fading")),A})},1500)),y.current.push(setTimeout(()=>{f(C=>{const A=new Map(C);return S.forEach(_=>A.delete(_)),A})},2500)))},[t]);const x=ie(()=>{const N=[...e];return i==="by-impact"&&c!==null?N.sort((S,C)=>{const A=c[S.filePath]??0,_=c[C.filePath]??0;return _!==A?_-A:new Date(C.lastModified).getTime()-new Date(S.lastModified).getTime()}):N.sort((S,C)=>new Date(C.lastModified).getTime()-new Date(S.lastModified).getTime()),N},[e,i,c]),b=ie(()=>x.filter(N=>!t[N.filePath]).length,[x,t]),w=ie(()=>a==="unreviewed"?x.filter(N=>!t[N.filePath]||m.has(N.filePath)):x,[x,a,t,m]),v=!u&&c!==null;return d("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:[d("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Recently Changed Rules"})}),n("div",{className:"flex-1"}),d("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),d("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:["Unreviewed Rules (",b,")"]})]}),d("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),d("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:["All (",x.length,")"]})]})]}),d("div",{className:"grid grid-cols-[1fr_90px_80px_100px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Rule"}),d("button",{onClick:()=>v&&l("by-impact"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none p-0 ${v?"cursor-pointer hover:text-gray-600":"cursor-default"} ${i==="by-impact"?"text-[#005C75]":"text-gray-400"}`,children:["Src Files",i==="by-impact"&&n(St,{className:"w-3 h-3"})]}),d("button",{onClick:()=>l("by-date"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none cursor-pointer p-0 hover:text-gray-600 ${i==="by-date"?"text-[#005C75]":"text-gray-400"}`,children:["Changed At",i==="by-date"&&n(St,{className:"w-3 h-3"})]}),d("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center flex items-center justify-center gap-1 whitespace-nowrap",children:["✓ Reviewed",d("span",{className:"relative group",children:[n(ao,{className:"w-3 h-3 text-gray-300 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Showing which rules have been reviewed and approved. Click a rule to view it and approve it"})]})]})]}),n("div",{className:"flex-1 overflow-y-auto max-h-[400px]",children:w.map(N=>{const S=t[N.filePath]??!1,C=m.get(N.filePath),A=wa(N.body,N.filePath),_=(c==null?void 0:c[N.filePath])??0;return n("div",{className:`border-b border-gray-50 transition-all ${C==="fading"?"duration-1000":"duration-300"}`,style:{opacity:C==="fading"?0:1},children:d("div",{className:`grid grid-cols-[1fr_90px_80px_100px] px-5 py-2.5 items-center cursor-pointer transition-colors duration-300 ${C==="approved"?"bg-[#f0fdf4]":"hover:bg-gray-50"}`,onClick:()=>r(N),children:[n("div",{className:"flex items-center gap-2 min-w-0",children:n("span",{className:"text-sm text-gray-900 truncate",children:A})}),n("span",{className:"text-xs text-center",children:u?n("span",{className:"inline-block w-6 h-3 bg-gray-100 rounded animate-pulse"}):c!==null?n("span",{className:_>0?"text-gray-700 font-medium":"text-gray-300",children:_}):n("span",{className:"text-gray-300",children:"—"})}),n("span",{className:"text-xs text-gray-500 text-center",children:Hn(N.lastModified)}),n("div",{className:"flex justify-center",children:n("div",{className:`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors duration-300 ${S?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:S&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})})]})},N.filePath)})}),w.length===0&&a==="unreviewed"&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:"All rules have been reviewed"})]})}function u1(e,t){const r=t.map(s=>`- \`${s}\``).join(`
573
+ `);return`Please audit the following Claude Rules that apply to the file \`${e}\`:
574
+
575
+ ${r}
576
+
577
+ Please review these rules in conjunction with one another as they all apply to this file.
578
+
579
+ Review each rule with the other rules in mind:
580
+ - Necessary: Is this rule really necessary to avoid confusion in future work sessions?
581
+ - Efficiency: Are the rules concise and well-structured?
582
+ - Effectiveness: Does the rules provide clear, actionable guidance?
583
+ - Context window impact: Can the rules be shortened without losing important information?
584
+ - Overlap: Is there any redundant information across the rules that can be consolidated?
585
+ - Duplication: Are there any rules that are nearly identical that can be merged or removed?
586
+
587
+ Remember that documenting past confusion isn't helpul unless that confusion will likely happen again.
588
+
589
+ Note: Each rule may apply to multiple files, not just the file listed above. Consider this when suggesting changes — modifications should not negatively impact the rule's usefulness for other files it covers.`}function p1({filePath:e,rulePaths:t,onClose:r}){const[s,a]=P(!1),o=u1(e,t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:l=>l.stopPropagation(),children:[n("button",{onClick:r,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Xn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-1",children:"Audit Rules For File"}),n("p",{className:"font-mono text-sm text-gray-500 mb-4 truncate",title:e,children:e}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can audit these rules to try and make them as efficient and effective as possible, reducing the impact on the context window."}),n("textarea",{readOnly:!0,value:o,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-4",children:n("button",{onClick:()=>{navigator.clipboard.writeText(o),a(!0),setTimeout(()=>a(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:s?d(we,{children:[n(kt,{className:"w-4 h-4"}),"Copied!"]}):d(we,{children:[n($t,{className:"w-4 h-4"}),"Copy Prompt"]})})})]})})}function h1({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:s}){const[a,o]=P("unreviewed"),[i,l]=P(null),[c,p]=P(""),[u,h]=P(0),[m,f]=P(!1),[g,y]=P(null),[x,b]=P(null),w=fe(null),v=fe(null),[N,S]=P({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[C,A]=P(!0);ae(()=>{(async()=>{A(!0);try{const q=await(await fetch("/api/memory?action=audit")).json();S({topPaths:q.topPaths||[],totalFilesWithCoverage:q.totalFilesWithCoverage||0,allSourceFiles:q.allSourceFiles||[]})}catch(H){console.error("Failed to load audit data:",H)}finally{A(!1)}})()},[e]);const _=ie(()=>a==="all"?N.topPaths:N.topPaths.filter(B=>B.matchingRules.some(H=>!t[H.filePath])),[N.topPaths,a,t]);ie(()=>N.topPaths.filter(B=>B.matchingRules.some(H=>!t[H.filePath])).length,[N.topPaths,t]);const E=B=>B.split("/").pop()||B,R=ie(()=>{const B=new Map;for(const H of N.topPaths)B.set(H.filePath,H);return B},[N.topPaths]),D=ie(()=>{if(!c.trim())return[];const B=c.toLowerCase(),H=[],q=[];for(const O of N.allSourceFiles){const W=O.toLowerCase();if(!W.includes(B))continue;const I=R.get(O)||{filePath:O,matchingRules:[],totalTextLength:0};W.startsWith(B)?H.push(I):q.push(I)}return H.sort((O,W)=>O.filePath.localeCompare(W.filePath)),q.sort((O,W)=>O.filePath.localeCompare(W.filePath)),[...H,...q].slice(0,8)},[c,N.allSourceFiles,R]),T=ce(B=>{var H;y(B),l(B.filePath),p(B.filePath),f(!1),(H=w.current)==null||H.blur()},[]),$=ce(()=>{var B;p(""),y(null),l(null),(B=w.current)==null||B.focus()},[]),L=ce(B=>{var H;!m||D.length===0||(B.key==="ArrowDown"?(B.preventDefault(),h(q=>Math.min(q+1,D.length-1))):B.key==="ArrowUp"?(B.preventDefault(),h(q=>Math.max(q-1,0))):B.key==="Enter"?(B.preventDefault(),T(D[u])):B.key==="Escape"&&(f(!1),(H=w.current)==null||H.blur()))},[m,D,u,T]);return ae(()=>{h(0)},[D]),d("div",{className:"bg-white rounded-lg border border-gray-200 flex flex-col",children:[d("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Rule Audit"})}),d("div",{className:"relative flex-1 max-w-[300px]",children:[n(Dr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),n("input",{ref:w,type:"text",value:c,onChange:B=>{p(B.target.value),f(!0)},onFocus:()=>{c.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:L,placeholder:"Search files...",className:`w-full pl-8 ${c?"pr-7":"pr-3"} py-1 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-[#005C75] focus:border-[#005C75] bg-gray-50`}),c&&n("button",{type:"button",onMouseDown:B=>{B.preventDefault(),$()},className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center text-gray-400 hover:text-gray-600 cursor-pointer",children:n("svg",{viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"w-3 h-3",children:n("path",{d:"M1 1l12 12M13 1L1 13"})})}),m&&D.length>0&&n("div",{ref:v,className:"absolute left-0 top-full mt-0.5 bg-white border border-gray-200 rounded-md shadow-lg z-10 max-h-75 overflow-y-auto min-w-75 max-w-120",children:D.map((B,H)=>d("div",{onMouseDown:q=>{q.preventDefault(),T(B)},onMouseEnter:()=>h(H),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${H===u?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(Ms,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:B.filePath,children:(()=>{const q=B.filePath.toLowerCase().indexOf(c.toLowerCase());if(q===-1)return B.filePath;const O=B.filePath.slice(0,q),W=B.filePath.slice(q,q+c.length),I=B.filePath.slice(q+c.length);return d(we,{children:[O,n("span",{className:"font-semibold text-[#005C75]",children:W}),I]})})()}),d("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[B.matchingRules.length," rule",B.matchingRules.length!==1?"s":""]})]},B.filePath))})]}),n("div",{className:"flex-1"}),d("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:"Unreviewed Rules"})]}),d("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:"All"})]})]}),d("div",{className:"grid grid-cols-[1fr_140px_150px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Source file"}),d("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Rules",d("span",{className:"relative group",children:[n(ao,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-48 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Number of rules not yet reviewed for this file / Total number of rules that apply to this file"})]})]}),d("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Tokens",d("span",{className:"relative group",children:[n(ao,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Estimated tokens from unreviewed rules / Total number of tokens from all rules that apply to this file"})]})]})]}),C&&n("div",{className:"px-5 py-6",children:d("div",{className:"animate-pulse space-y-3",children:[n("div",{className:"h-4 bg-gray-200 rounded w-3/4"}),n("div",{className:"h-3 bg-gray-100 rounded w-1/2"}),n("div",{className:"h-4 bg-gray-200 rounded w-2/3 mt-4"})]})}),!C&&(_.length>0||g)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(g?[g,..._.filter(H=>H.filePath!==g.filePath)].slice(0,8):_.slice(0,8)).map((B,H)=>{const q=B.matchingRules.length,O=B.matchingRules.filter(G=>!t[G.filePath]),W=O.length,I=O.reduce((G,Q)=>G+Q.bodyLength,0),j=W>0,k=i===B.filePath,Y=(g==null?void 0:g.filePath)===B.filePath;return d("div",{children:[d("div",{onClick:()=>l(k?null:B.filePath),className:`grid grid-cols-[1fr_140px_150px] px-5 py-2.5 items-center border-b border-gray-50 cursor-pointer ${Y?"bg-[#f0f9ff] hover:bg-[#e0f2fe]":"hover:bg-gray-50"}`,children:[d("div",{className:"flex items-center gap-2 min-w-0",children:[k?n(St,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n(on,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(Ms,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:B.filePath,children:Y?B.filePath:E(B.filePath)})]}),d("span",{className:"text-sm text-center",children:[n("span",{className:j?"font-semibold text-[#1A5276]":"text-gray-400",children:W}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:q})]}),d("span",{className:"text-sm text-center",children:[n("span",{className:j?"font-semibold text-[#1A5276]":"text-gray-400",children:Ar(I).toLocaleString()}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:Ar(B.totalTextLength).toLocaleString()})]})]}),k&&d("div",{className:"bg-gray-50 border-b border-gray-100",children:[B.matchingRules.map(G=>{const Q=r.find(F=>F.filePath===G.filePath),K=t[G.filePath]??!1;return d("div",{onClick:F=>{F.stopPropagation(),Q&&s(Q)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(js,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-700 truncate flex-1",children:Q?wa(Q.body,Q.filePath):G.filePath}),d("span",{className:"text-xs text-gray-400 flex-shrink-0",children:[Ar(G.bodyLength).toLocaleString()," ","tokens"]}),n("div",{className:`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${K?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:K&&n("svg",{width:"8",height:"6",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]},G.filePath)}),d("div",{className:"flex items-center justify-center gap-3 px-5 py-2 border-t border-gray-200",children:[n("span",{className:"text-xs text-gray-400",children:"Have Claude audit these rules"}),n("button",{onClick:G=>{G.stopPropagation(),b({filePath:B.filePath,rulePaths:B.matchingRules.map(Q=>Q.filePath)})},className:"px-3 py-1 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer",children:"Prompt"})]})]})]},B.filePath)})}),!C&&_.length===0&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:a==="unreviewed"?"No files have unreviewed rules":"No files have rule coverage yet"}),x&&n(p1,{filePath:x.filePath,rulePaths:x.rulePaths,onClose:()=>b(null)})]})}function m1({rule:e,changeInfo:t,isReviewed:r,onApprove:s,onEdit:a,onDelete:o,onClose:i}){const l=wa(e.body,e.filePath),c=Ar(e.body.length),p=e.frontmatter.category,u=`.claude/rules/${e.filePath}`,[h,m]=P(null),f=(t==null?void 0:t.changeType)==="added"||h!=null&&h.commitCount!=null&&h.commitCount<=1&&!(h.commitCount===1&&h.isUncommitted);return ae(()=>{m(null),fetch(`/api/memory?action=rule-diff&filePath=${encodeURIComponent(e.filePath)}`).then(g=>g.json()).then(g=>{g.diff&&m(g.diff)}).catch(()=>{})},[e.filePath]),ae(()=>{const g=y=>{y.key==="Escape"&&i()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[i]),n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:i,children:d("div",{className:"rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",style:{backgroundColor:"#F8F7F6"},onClick:g=>g.stopPropagation(),children:[n("div",{className:"px-6 pt-5 pb-4",children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"min-w-0 flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[n("h2",{className:"text-[16px] font-bold text-gray-900",children:l}),t&&d(we,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:Hn(t.date)}),n("span",{className:`flex-shrink-0 text-[11px] uppercase font-semibold tracking-wider ${t.changeType==="added"?"text-green-600":t.changeType==="modified"?"text-orange-600":"text-red-600"}`,children:t.changeType})]})]}),p&&d("div",{className:"flex items-center gap-2 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"TYPE:"}),n("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase font-semibold tracking-wider bg-[#E0F2F1] text-[#00796B]",children:p})]}),d("div",{className:"flex items-center gap-1.5 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"FILE:"}),n("code",{className:"text-[11px] text-gray-600 font-mono",children:u}),n(ct,{content:u,icon:!0,iconSize:12,className:"p-0.5 rounded text-gray-400 hover:text-gray-600 transition-colors",ariaLabel:"Copy file path"})]}),d("div",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:["TOKENS: ~",c.toLocaleString()]})]}),d("div",{className:"flex items-center gap-2 flex-shrink-0 ml-4",children:[d("button",{onClick:s,className:`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer transition-colors ${r?"bg-green-600 text-white":"border border-green-600 text-green-700 hover:bg-green-50"}`,children:[n(kt,{className:"w-3.5 h-3.5"}),r?"Approved":"Approve"]}),n("button",{onClick:a,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors",children:"Edit"}),n("button",{onClick:o,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-red-300 text-red-600 hover:bg-red-50 transition-colors",children:"Delete"}),n("button",{onClick:i,className:"p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-200 cursor-pointer transition-colors ml-1",children:n(Xn,{className:"w-5 h-5"})})]})]})}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&d("div",{className:"px-6 pb-4",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Applies to paths:"}),n("div",{className:"bg-white rounded-lg p-4 space-y-2.5",style:{border:"1px solid #E6E6E6"},children:e.frontmatter.paths.map((g,y)=>{const x=g.split("/"),b=x.pop()||g,w=x.length>0?x.join("/")+"/":"";return d("div",{className:"flex items-center gap-2 text-[13px] font-mono",children:[n(Ms,{className:"w-4 h-4 text-[#005C75] flex-shrink-0"}),d("span",{children:[w&&n("span",{className:"text-gray-500",children:w}),n("span",{className:"font-bold text-gray-900",children:b})]})]},y)})})]}),f?n("div",{className:"px-6 pb-4",children:d("div",{className:"text-[13px] text-gray-500",children:["Created"," ",t!=null&&t.date?Hn(t.date):h!=null&&h.date?Hn(h.date):"recently"]})}):h&&n("div",{className:"px-6 pb-4",children:d("details",{children:[d("summary",{className:"text-[13px] text-gray-700 font-semibold cursor-pointer",children:["Recent change: ",h.commitMessage," —"," ",Hn(h.date)]}),n("pre",{className:"mt-2 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:h.diff.split(`
590
+ `).map((g,y)=>{let x="";return g.startsWith("+")&&!g.startsWith("+++")?x="text-green-400":g.startsWith("-")&&!g.startsWith("---")?x="text-red-400":g.startsWith("@@")&&(x="text-cyan-400"),n("div",{className:x,children:g},y)})})]})}),d("div",{className:"px-6 pb-6",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Rule Text:"}),n("div",{className:"bg-white rounded-lg p-6",style:{border:"1px solid #E6E6E6"},children:n(Lu,{content:e.body})})]})]})})}function f1(){return d("svg",{width:"24",height:"24",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#232323"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#232323"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#232323"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#232323"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#232323"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#232323"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#232323"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#232323"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#232323"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#232323"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#232323"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#232323"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#232323"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#232323"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#232323"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#232323"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#232323"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#232323"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#232323"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#232323"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#232323"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#232323"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#232323"})]})}function g1(){return d("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}function y1(){return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans max-w-3xl mx-auto",children:[d("div",{className:"text-center mb-10",children:[n("h1",{className:"text-[22px] font-semibold mb-4",style:{fontFamily:"Sora",color:"#232323"},children:"Get Started with CodeYam Memory"}),n("p",{className:"text-[15px] text-gray-500 leading-relaxed max-w-2xl mx-auto",children:"CodeYam Memory generates path-scoped Claude Rules that load automatically when Claude works on matching files. These rules capture any confusion, architectural decisions, and tribal knowledge from your as you work with Claude, ensuring sessions become more efficient and aligned with your codebase over time."})]}),d("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"Setup Steps"}),d("ol",{className:"space-y-5",children:[d("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"1"}),n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Open Claude Code in your project terminal"})]}),d("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"2"}),d("div",{children:[d("div",{className:"flex items-center gap-2 pt-0.5",children:[n("span",{className:"text-[14px] font-medium text-gray-900",children:"Run"}),n(ic,{value:"/codeyam-memory"}),n("span",{className:"text-[14px] font-medium text-gray-900",children:"in the Claude Code session"})]}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"This kicks off analysis of your git history to find confusion patterns."})]})]}),d("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"3"}),d("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Return to this dashboard page to review the new rules"}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"You can review, edit, and approve the rules Claude creates."})]})]})]})]}),d("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"What Gets Created"}),d("div",{className:"relative",children:[n("div",{className:"absolute left-[15px] top-8 bottom-4",style:{borderLeft:"2px dotted #B0BEC5"}}),d("div",{className:"space-y-6",children:[d("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),d("div",{children:[d("p",{className:"text-[14px] font-medium text-gray-900",children:[n("code",{className:"bg-gray-200/60 px-1.5 py-0.5 rounded text-[13px]",children:".claude/rules/*.md"}),n("span",{className:"text-gray-400 mx-1.5",children:"—"}),"path-scoped guidance files"]}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"Markdown files with frontmatter specifying which file paths they apply to."})]})]}),d("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),d("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Rules load automatically when Claude works on matching files"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"No manual steps needed — Claude picks up relevant rules based on the files it touches."})]})]}),d("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),d("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Pre-commit hook to keep rules fresh and capture new patterns"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"A git hook runs automatically to update rules when related code changes and looks for any new patterns of confusion in work sessions."})]})]})]})]})]}),d("div",{className:"rounded-lg px-8 py-5 flex items-center justify-center gap-3",style:{backgroundColor:"#1A2332"},children:[n("span",{className:"text-white text-[15px] font-medium",children:"Run"}),n(ic,{value:"/codeyam-memory"}),n("span",{className:"text-white text-[15px] font-medium",children:"in Claude Code to get started"})]})]})})}function ic({value:e}){const[t,r]=P(!1);return d("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[13px] font-mono cursor-pointer border-0",style:{backgroundColor:"#2C3E50",color:"#E0E0E0"},title:"Copy to clipboard",children:[e,t?n(kt,{className:"w-3.5 h-3.5 text-green-400"}):d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-400",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})}function ws({label:e,count:t,icon:r,bgColor:s,iconBgColor:a,textColor:o}){return n("div",{className:"rounded-lg p-4",style:{backgroundColor:s,border:"1px solid #EFEFEF"},children:d("div",{className:"flex items-start gap-3",children:[n("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:a},children:r}),d("div",{className:"flex-1",children:[n("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:o},children:t}),n("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:o},children:e})]})]})})}function x1({searchFilter:e,onSearchChange:t,onCreateNew:r,onLearnMore:s,reviewCounts:a}){return d("div",{className:"mb-8",children:[d("div",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[d("div",{children:[d("div",{className:"flex items-center gap-3 mb-2",children:[n(f1,{}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),d("p",{className:"text-[15px] text-gray-500",children:["Rules help Claude understand your codebase patterns and conventions."," ",n("button",{onClick:s,className:"text-[#005C75] underline cursor-pointer",children:"Learn more about rules."})]})]}),d("div",{className:"flex items-center gap-3",children:[d("div",{className:"relative",children:[n(Dr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:e,onChange:o=>t(o.target.value),placeholder:"Search rules...",className:"w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),d("button",{onClick:r,className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(Po,{className:"w-4 h-4"}),"New Rule"]})]})]}),d("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[n(ws,{label:"Total Rules",count:a.total,icon:n(g1,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(ws,{label:"Unreviewed",count:a.unreviewed,icon:n(rh,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(ws,{label:"Reviewed",count:a.reviewed,icon:n(kt,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(ws,{label:"Stale",count:a.stale,icon:n(Ic,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]})}function b1({onClose:e,onCreateNew:t}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:r=>r.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Xn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-4",children:"What are Claude Rules?"}),n("h3",{className:"mb-4 font-semibold",children:"And how does CodeYam Memory work with Claude Rules?"}),d("div",{className:"text-gray-600 text-[15px] space-y-3 mb-6",children:[d("p",{children:["Claude Rules are a component of"," ",n("a",{href:"https://code.claude.com/docs/en/memory#modular-rules-with-claude%2Frules%2F",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 underline",children:"Memory Management in Claude Code"}),'. The text of each rule is passed into the context window when working on the specific files described in the "paths" frontmatter field of the rule.']}),n("p",{children:"This allows you to provide context that is surgically specific to certain files in your codebase. They are a powerful tool but are harder to write and maintain than CLAUDE.md files."}),n("p",{children:"CodeYam Memory helps write and maintain Claude Rules. Hooks ensure that rules are reviewed and added during Claude Code working sessions. The CodeYam CLI Dashboard provides a page dedicated to Memory where you can view, edit, create, delete, and review Claude Rules."})]}),n("div",{className:"flex justify-center",children:d("button",{onClick:t,className:"flex items-center gap-2 px-5 py-2.5 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(Po,{className:"w-4 h-4"}),"New Rule"]})})]})})}function w1({rule:e,onConfirm:t,onCancel:r}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:d("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[n("h3",{className:"text-lg font-semibold mb-2",children:"Delete Memory?"}),d("p",{className:"text-gray-600 mb-4",children:["Are you sure you want to delete"," ",n("span",{className:"font-mono text-sm",children:e.filePath}),"? This cannot be undone."]}),d("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>t(e),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})}const lc="Can you help me perform an interactive rules audit? Please look at all of the rules in `.claude/rules`. Are they organized properly? Ideally they should be in a folder that is the best representation of the files they impact (e.g. if the rule impacts `folder1/folder2/file1` and `folder1/folder2/folder3/file2` then the rule should be in `.claude/rules/folder1/folder2`). Do they make sense? Are they oriented toward avoiding future confusion (vs documenting bug fixes or temporary workarounds, etc)? Please literally read each one to ensure you understand what it is saying and learn something useful from it. Are they concise and efficient in their communication? We want to be respectful of the context window so any information in a rule that does not make sense, is not particularly helpful, or is repetitive should be removed. All other information should be presented as directly as possible. Bullets and tables can help with this as opposed to paragraphs. Take into consideration how rules interact as any one file may have multiple rules applied to it. Please look at the impacted files as well to ensure that it is an appropriate rule for them and to ensure the rule is not just repeating information that can be ascertained from the code. We don't want Claude to have to read a large number of files (or a single very large file) to figure out how everything works, so architectural guidance can be quite valuable, but information that is specific to one file and can be ascertained by the code and comments in that file is unnecessary. Too often rules reflect past confusion that has been resolved and is unlikely to happen again. Content and rules like this should be removed. If you have any questions please ask!",cc="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function dc({text:e}){const[t,r]=P(!1);return n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:t?d(we,{children:[n(kt,{className:"w-4 h-4"}),"Copied!"]}):d(we,{children:[n($t,{className:"w-4 h-4"}),"Copy Prompt"]})})}function v1({onClose:e}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative max-h-[90vh] overflow-y-auto",onClick:t=>t.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Xn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-2",children:"Audit All Rules"}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can review all rules to look for information that is inconsistent, inappropriate, duplicative, inefficient, etc."}),n("textarea",{readOnly:!0,value:lc,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(dc,{text:lc})}),d("div",{className:"border-t border-gray-200 mt-6 pt-5",children:[n("p",{className:"text-gray-500 text-sm mb-3",children:"If you would like to avoid reviewing all of the changes Claude makes you can ask Claude to mark all rules as reviewed."}),n("textarea",{readOnly:!0,value:cc,className:"w-full h-16 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(dc,{text:cc})})]})]})})}function N1(){const[e,t]=P(!1);return d(we,{children:[d("div",{className:"border border-gray-200 rounded-lg px-5 py-4 flex items-center gap-3",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit All Rules"}),n("p",{className:"text-sm text-gray-500",children:"Ask Claude to review, audit, and improve all rules."}),n("button",{onClick:()=>t(!0),className:"px-4 py-2 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer flex-shrink-0",children:"Get Prompt"})]}),e&&n(v1,{onClose:()=>t(!1)})]})}function S1(e){return`Can you help me review my unreviewed rules? The following rules in \`.claude/rules\` have not been reviewed yet:
591
+
592
+ ${e.map(r=>`- \`.claude/rules/${r}\``).join(`
593
+ `)}
594
+
595
+ Are they organized properly? Ideally they should be in a folder that is the best representation of the files they impact (e.g. if the rule impacts \`folder1/folder2/file1\` and \`folder1/folder2/folder3/file2\` then the rule should be in \`.claude/rules/folder1/folder2\`). Do they make sense? Are they oriented toward avoiding future confusion (vs documenting bug fixes or temporary workarounds, etc)? Please literally read each one to ensure you understand what it is saying and learn something useful from it. Are they concise and efficient in their communication? We want to be respectful of the context window so any information in a rule that does not make sense, is not particularly helpful, or is repetitive should be removed. All other information should be presented as directly as possible. Bullets and tables can help with this as opposed to paragraphs. Take into consideration how rules interact as any one file may have multiple rules applied to it. Please look at the impacted files as well to ensure that it is an appropriate rule for them and to ensure the rule is not just repeating information that can be ascertained from the code. We don't want Claude to have to read a large number of files (or a single very large file) to figure out how everything works, so architectural guidance can be quite valuable, but information that is specific to one file and can be ascertained by the code and comments in that file is unnecessary. Too often rules reflect past confusion that has been resolved and is unlikely to happen again. Content and rules like this should be removed. If you have any questions please ask!`}const uc="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function pc({text:e}){const[t,r]=P(!1);return n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:t?d(we,{children:[n(kt,{className:"w-4 h-4"}),"Copied!"]}):d(we,{children:[n($t,{className:"w-4 h-4"}),"Copy Prompt"]})})}function C1({onClose:e,unreviewedRulePaths:t}){const r=S1(t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative max-h-[90vh] overflow-y-auto",onClick:s=>s.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Xn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-2",children:"Audit Unreviewed Rules"}),d("p",{className:"text-gray-600 text-sm mb-4",children:["Claude will review only the ",t.length," unreviewed"," ",t.length===1?"rule":"rules"," for quality, relevance, and organization."]}),n("textarea",{readOnly:!0,value:r,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(pc,{text:r})}),d("div",{className:"border-t border-gray-200 mt-6 pt-5",children:[n("p",{className:"text-gray-500 text-sm mb-3",children:"If you would like to avoid reviewing all of the changes Claude makes you can ask Claude to mark all rules as reviewed."}),n("textarea",{readOnly:!0,value:uc,className:"w-full h-16 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(pc,{text:uc})})]})]})})}function k1({unreviewedRulePaths:e}){const[t,r]=P(!1);return e.length===0?d("div",{className:"border border-gray-200 rounded-lg px-5 py-4 flex items-center gap-3 opacity-50",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit Unreviewed Rules"}),n("p",{className:"text-sm text-gray-500",children:"All rules have been reviewed."})]}):d(we,{children:[d("div",{className:"border border-gray-200 rounded-lg px-5 py-4 flex items-center gap-3",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit Unreviewed Rules"}),d("p",{className:"text-sm text-gray-500",children:["Ask Claude to review the ",e.length," unreviewed"," ",e.length===1?"rule":"rules","."]}),n("button",{onClick:()=>r(!0),className:"px-4 py-2 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer flex-shrink-0",children:"Get Prompt"})]}),t&&n(C1,{onClose:()=>r(!1),unreviewedRulePaths:e})]})}const _1=()=>[{title:"Memory - CodeYam"},{name:"description",content:"Manage Claude Memory documentation"}];async function E1({request:e}){try{const r=await(await fetch(new URL("/api/memory",e.url).toString())).json();return r.error?re({memories:[],reviewedStatus:{},memoryInitialized:r.memoryInitialized??!1,error:r.error}):r.memoryInitialized??!1?re({memories:r.memories||[],reviewedStatus:r.reviewedStatus||{},memoryInitialized:!0,error:null}):re({memories:[],reviewedStatus:{},memoryInitialized:!1,error:null})}catch(t){return console.error("Failed to load memories:",t),re({memories:[],reviewedStatus:{},memoryInitialized:!1,error:"Failed to load memories"})}}const A1=et(function(){const{memories:t,reviewedStatus:r,memoryInitialized:s,error:a}=st(),o=Ke(),i=Ut(),[l,c]=P(""),[p,u]=P(null),[h,m]=P(new Set(["root"])),[f,g]=P(null),[y,x]=P(!1),[b,w]=P(null),[v,N]=P(0),[S,C]=P(!1),[A,_]=P(null),[E,R]=P(null),[D,T]=P({}),$=F=>{m(M=>{const z=new Set(M);return z.has(F)?z.delete(F):z.add(F),z})};Dt({source:"memory-page"});const L=ie(()=>({...r,...D}),[r,D]),B=fe(o.state);ae(()=>{const F=B.current==="loading"||B.current==="submitting",M=o.state==="idle";F&&M&&o.data&&(i.revalidate(),g(null),x(!1),N(z=>z+1)),B.current=o.state},[o.state,o.data,i]),ae(()=>{T(F=>{const M={};for(const[z,J]of Object.entries(F))r[z]!==J&&(M[z]=J);return Object.keys(M).length===Object.keys(F).length?F:M})},[r]);const H=(F,M)=>{T(z=>({...z,[F]:!0})),o.submit({action:"mark-reviewed",filePath:F,lastModified:M},{method:"POST",action:"/api/memory",encType:"application/json"})},q=F=>{T(M=>({...M,[F]:!1})),o.submit({action:"mark-unreviewed",filePath:F},{method:"POST",action:"/api/memory",encType:"application/json"})},O=(F,M)=>{_(F),R(M??null)},W=ie(()=>{let F=t;if(l.trim()){const M=l.toLowerCase();F=F.filter(z=>{var te;return(((te=z.filePath.split("/").pop())==null?void 0:te.replace(".md",""))||"").toLowerCase().includes(M)||z.body.toLowerCase().includes(M)})}return F},[t,l]),I=ie(()=>p?W.some(M=>M.filePath===p)?W.filter(M=>M.filePath===p):W.filter(M=>M.filePath.startsWith(p+"/")||M.filePath===p):W,[W,p]),j=(F,M)=>{const z=f?"update":"create";o.submit({action:z,filePath:F,content:M},{method:"POST",action:"/api/memory",encType:"application/json"})},k=F=>{o.submit({action:"delete",filePath:F.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),w(null)},Y=ie(()=>{const F=t.filter(M=>L[M.filePath]).length;return{total:t.length,reviewed:F,unreviewed:t.length-F,stale:0}},[t,L]),G=ie(()=>{const F=new Set(["root"]);for(const M of W){const z=M.filePath.split("/");z.pop();let J="";for(const te of z)J=J?`${J}/${te}`:te,F.add(J)}return F},[W]),Q=G.size===h.size&&[...G].every(F=>h.has(F)),K=()=>{m(Q?new Set(["root"]):new Set(G))};return a?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:a})]})}):s?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans",children:[n(x1,{searchFilter:l,onSearchChange:c,onCreateNew:()=>x(!0),onLearnMore:()=>C(!0),reviewCounts:Y}),(y||f)&&n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:()=>{x(!1),g(null)},children:n("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:F=>F.stopPropagation(),children:n(i1,{rule:f,onSave:j,onCancel:()=>{x(!1),g(null)}})})}),d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(d1,{memories:W,reviewedStatus:L,onViewRule:O,refreshKey:v}),n(h1,{onEditRule:g,onDeleteRule:w,refreshKey:v,reviewedStatus:L,onMarkReviewed:H,onMarkUnreviewed:q,memories:t,onViewRule:O})]}),d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(k1,{unreviewedRulePaths:t.filter(F=>!L[F.filePath]).map(F=>F.filePath)}),n(N1,{})]}),d("div",{className:"flex items-center justify-between mb-4",children:[n("h2",{className:"text-xl leading-6 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"All Rules"}),n("div",{className:"flex items-center gap-4",children:G.size>1&&n("button",{onClick:K,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:Q?"Collapse All":"Expand All"})})]}),d("div",{className:"flex gap-6",children:[n("div",{className:"hidden lg:block w-80 flex-shrink-0",children:n(l1,{memories:W,selectedPath:p,onSelectPath:u,expandedFolders:h,onToggleFolder:$})}),n("div",{className:"flex-1 min-w-0",children:t.length===0?d("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(sh,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Rules Yet"}),d("p",{className:"text-gray-500 mb-4",children:["Run"," ",n("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam-memory"})," ","to generate initial memories for your codebase."]}),d("button",{onClick:()=>x(!0),className:"inline-flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer",children:[n(Po,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):d("div",{children:[p&&d("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:["Showing rules in"," ",n("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:p||"(root)"}),n("button",{onClick:()=>u(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(c1,{memories:I,onEdit:g,onDelete:w,expandedFolders:h,onToggleFolder:$,reviewedStatus:L,onMarkReviewed:H,onMarkUnreviewed:q,onViewRule:O})]})})]}),n("div",{className:"mt-8 mb-8",children:n(Ce,{to:"/agent-transcripts",className:"block bg-white border border-gray-200 rounded-lg p-5 hover:border-[#005C75] hover:shadow-sm transition-all group",children:d("div",{className:"flex items-center gap-3",children:[n("div",{className:"w-10 h-10 rounded-lg bg-[#EDF1F3] flex items-center justify-center",children:d("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#005C75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("polyline",{points:"4 17 10 11 4 5"}),n("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),d("div",{children:[n("h3",{className:"text-sm font-semibold text-[#232323] group-hover:text-[#005C75]",style:{fontFamily:"Sora"},children:"Agent Transcripts"}),n("p",{className:"text-xs text-gray-500",children:"View background agent transcripts and tool call history"})]})]})})}),A&&!f&&(()=>{const F=t.find(M=>M.filePath===A.filePath)??A;return n(m1,{rule:F,changeInfo:E??void 0,isReviewed:L[F.filePath]??!1,onApprove:()=>{L[F.filePath]??!1?q(F.filePath):H(F.filePath,F.lastModified),_(null)},onEdit:()=>{g(F)},onDelete:()=>{w(F),_(null)},onClose:()=>_(null)})})(),S&&n(b1,{onClose:()=>C(!1),onCreateNew:()=>{C(!1),x(!0)}}),b&&n(w1,{rule:b,onConfirm:k,onCancel:()=>w(null)})]})}):n(y1,{})}),P1=Object.freeze(Object.defineProperty({__proto__:null,default:A1,loader:E1,meta:_1},Symbol.toStringTag,{value:"Module"}));function ro(e){return`${e.filePath||""}::${e.name}`}function Yu(e,t){const r=Ke(),{showToast:s}=Oo(),[a,o]=P(new Map);ae(()=>{if(r.state==="idle"&&r.data){const m=r.data;m!=null&&m.error&&s(`Error: ${m.error}`,"error",6e3)}},[r.state,r.data,s]),ae(()=>{var f;if(a.size===0)return;const m=new Set;(f=t==null?void 0:t.jobs)==null||f.forEach(g=>{var y;(y=g.entityShas)==null||y.forEach(x=>{a.forEach((b,w)=>{b===x&&m.add(w)})})}),e==null||e.forEach(g=>{a.forEach((y,x)=>{y===g&&m.add(x)})}),m.size>0&&o(g=>{const y=new Map(g);return m.forEach(x=>y.delete(x)),y})},[t,e,a]);const i=ce(m=>{console.log("Generate analysis clicked for entity:",m.sha,m.name);const f=ro(m);o(y=>new Map(y).set(f,m.sha));const g=new FormData;g.append("entitySha",m.sha),g.append("filePath",m.filePath||""),r.submit(g,{method:"post",action:"/api/analyze"})},[r]),l=ce(m=>{const f=m.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(x=>{const b=new Map(x);return f.forEach(w=>b.set(ro(w),w.sha)),b});const g=f.map(x=>x.sha).join(","),y=new FormData;y.append("entityShas",g),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),c=ce(m=>(e==null?void 0:e.includes(m))??!1,[e]),p=ce(m=>{const f=ro(m);return a.has(f)},[a]),u=ce(m=>{var f;return((f=t==null?void 0:t.jobs)==null?void 0:f.some(g=>{var y;return(y=g.entityShas)==null?void 0:y.includes(m)}))??!1},[t]),h=ie(()=>Array.from(a.keys()),[a]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:l,isEntityBeingAnalyzed:c,isEntityPending:p,isEntityInQueue:u,pendingEntityKeys:h}}function Ei({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:s,analyzeAllDisabled:a=!1,analyzeAllText:o="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:d("div",{className:"flex justify-between items-center px-3 py-2",children:[d("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:n("span",{children:"STATE"})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:n("span",{children:"SIMULATIONS"})}),d("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),d("div",{className:"flex items-center justify-center gap-1 cursor-pointer hover:text-[#232323] transition-colors",style:{width:"116px"},onClick:r,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r==null||r())},children:[n("span",{children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:t==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&n("div",{className:"text-center",style:{width:"127px"},children:s&&n("button",{onClick:s,disabled:a,className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap px-3 py-1.5 normal-case",title:a?o:"Analyze all entities",children:o})})]})]})]})})}function j1({status:e,variant:t="compact"}){const r={modified:{label:"M",bgColor:"bg-[#f59e0c]"},added:{label:"A",bgColor:"bg-emerald-500"},deleted:{label:"D",bgColor:"bg-red-500",showWarning:!0},renamed:{label:"R",bgColor:"bg-indigo-500"},untracked:{label:"U",bgColor:"bg-purple-500"}},s={modified:{label:"MODIFIED",textColor:"#BB6BD9"},added:{label:"ADDED",textColor:"#F2994A"},deleted:{label:"DELETED",textColor:"#EF4444"},renamed:{label:"RENAMED",textColor:"#3B82F6"},untracked:{label:"UNTRACKED",textColor:"#6B7280"}};if(t==="full"){const o=s[e]||{label:"UNKNOWN",textColor:"#6B7280"};return n("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:o.textColor},children:o.label})})}const a=r[e]||{label:"?",bgColor:"bg-gray-500"};return d("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${a.bgColor}`,title:e,children:a.label}),a.showWarning&&n("span",{className:"inline-flex items-center justify-center w-3 h-3 text-[10px] text-amber-600",title:"Warning: File will be deleted",children:"⚠"})]})}function Ai({filePath:e,isExpanded:t,onToggle:r,fileStatus:s,simulationPreviews:a,entityCount:o,state:i,lastModified:l,actionButton:c,uncommittedCount:p,children:u,isNotAnalyzable:h=!1,isUncommitted:m=!1}){return d("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[d("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${h?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[d("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(Wc,{filePath:e}),s&&n(j1,{status:typeof s=="string"?s:s.status,variant:"full"}),m&&i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(m||i==="out-of-date")&&d("div",{className:"flex gap-1.5 items-center",children:[m&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&!m&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:a}),d("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:d("span",{className:"text-[13px] text-[#3e3e3e]",children:[o," ",o===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:Pu(l)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:c})]})]})]}),t&&u&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:u})]})}function Pi({entities:e,maxPreviews:t=3}){var s,a,o,i,l;const r=[];for(const c of e){if(r.length>=t)break;const p=((a=(s=c.analyses)==null?void 0:s[0])==null?void 0:a.scenarios)||[];if(c.entityType==="library"){const u=p.find(h=>{var m,f;return((m=h.metadata)==null?void 0:m.executionResult)||((f=h.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:c.sha})}else if(c.entityType==="visual"){const u=p.find(h=>{var m,f;return(f=(m=h.metadata)==null?void 0:m.screenshotPaths)==null?void 0:f[0]});if(u){const h=(i=(o=u.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],m=!!((l=u.metadata)!=null&&l.error);h&&r.push({type:"screenshot",screenshot:h,hasError:m,scenario:u,entitySha:c.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(we,{children:r.map((c,p)=>{if(c.type==="screenshot"&&c.screenshot){const u=c.hasError?"border-red-400":"border-gray-200";return d(Ce,{to:c.scenario?`/entity/${c.entitySha}/scenarios/${c.scenario.id}`:`/entity/${c.entitySha}`,className:`relative w-[50px] h-[38px] border ${u} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:h=>h.stopPropagation(),children:[n(lt,{screenshotPath:c.screenshot,alt:`Preview ${p+1}`,className:"max-w-full max-h-full object-contain object-center"}),c.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(Ps,{size:12,color:"white"})})]},`screenshot-${p}`)}return c.type==="library"&&c.scenario&&c.entitySha?n(Eu,{scenario:c.scenario,entitySha:c.entitySha,size:"small",showBorder:!0},`library-${p}`):null})})}function ji({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:s}){var u,h;const a=t||r?[{entityShas:[e.sha]}]:[],o=wt(e,a,t),i=e.entityType==="visual"||e.entityType==="library",l=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,p=(((h=(u=e.analyses)==null?void 0:u[0])==null?void 0:h.scenarios)||[]).filter(m=>{var f,g;return(g=(f=m.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0]});return d("div",{className:"bg-white rounded-lg",children:[d(Ce,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[d("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 shrink-0"}),e.entityType==="type"?n("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:n("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:n(ht,{type:"type"})})}):n(ht,{type:e.entityType||"other"}),n("span",{className:`font-['IBM_Plex_Sans'] text-[14px] leading-[18px] text-black ${i?"font-medium":"font-normal"}`,children:e.name}),n(bi,{type:e.entityType||"other"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),d("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?o==="queued"?d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):o==="analyzing"?d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):o==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):o==="out-of-date"?n("button",{onClick:m=>{m.preventDefault(),m.stopPropagation(),s(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):l&&n("button",{onClick:m=>{m.preventDefault(),m.stopPropagation(),s(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"})})]})]})]}),p.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:p.map((m,f)=>{var y,x;const g=(x=(y=m.metadata)==null?void 0:y.screenshotPaths)==null?void 0:x[0];return g?n(Ce,{to:`/entity/${e.sha}?scenario=${m.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:b=>b.stopPropagation(),children:n(lt,{screenshotPath:g,alt:m.name,className:"max-w-full max-h-full object-contain object-center"})},m.id):null})})]})}function T1({entities:e,page:t,itemsPerPage:r=50,currentRun:s,filter:a,entityType:o,queueState:i,isEntityPending:l,pendingEntityKeys:c,onGenerateSimulation:p,onGenerateAllSimulations:u,totalFilesCount:h,totalEntitiesCount:m,uncommittedFilesCount:f,showOnlyUncommitted:g,onToggleUncommitted:y}){const[x,b]=Zn(),[w,v]=P(new Set),[N,S]=P(""),[C,A]=P(!1),[_,E]=P("all"),[R,D]=P("desc"),T=o||"all",$=ie(()=>{let k=e;return T!=="all"&&(k=k.filter(Y=>Y.entityType===T)),a==="analyzed"&&(k=k.filter(Y=>Y.analyses&&Y.analyses.length>0)),k},[e,T,a]),L=ie(()=>{const k=new Map,Y=new Map,G=new Map;$.forEach(M=>{var te,oe;const z=`${M.filePath}::${M.name}`,J=Y.get(z);if(!J)Y.set(z,M),G.set(z,[]);else{const de=((te=J.metadata)==null?void 0:te.editedAt)||J.createdAt||"",ue=((oe=M.metadata)==null?void 0:oe.editedAt)||M.createdAt||"";let me=!1;if(ue>de)me=!0;else if(ue===de){const Se=J.createdAt||"";me=(M.createdAt||"")>Se}me?(G.get(z).push(J),Y.set(z,M)):G.get(z).push(M)}}),Y.forEach((M,z)=>{var te;if(!(M.analyses&&M.analyses.length>0)&&((te=M.metadata)!=null&&te.previousVersionWithAnalyses)){const de=(G.get(z)||[]).find(ue=>{var me;return ue.sha===((me=M.metadata)==null?void 0:me.previousVersionWithAnalyses)});de&&de.analyses&&de.analyses.length>0&&(M.analyses=de.analyses)}}),Array.from(Y.values()).sort((M,z)=>{var oe,de,ue,me;const J=!((oe=M.metadata)!=null&&oe.notExported)&&!((de=M.metadata)!=null&&de.namedExport),te=!((ue=z.metadata)!=null&&ue.notExported)&&!((me=z.metadata)!=null&&me.namedExport);return J&&!te?-1:!J&&te?1:0}).forEach(M=>{var de,ue,me,Se,Te;const z=M.filePath??"No File Path";k.has(z)||k.set(z,{filePath:z,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const J=k.get(z);J.entities.push(M),J.totalCount++,(de=M.metadata)!=null&&de.isUncommitted&&J.uncommittedCount++;const te=((Se=(me=(ue=M.analyses)==null?void 0:ue[0])==null?void 0:me.scenarios)==null?void 0:Se.length)||0;J.simulationCount+=te;const oe=((Te=M.metadata)==null?void 0:Te.editedAt)||M.updatedAt;oe&&(!J.lastUpdated||new Date(oe)>new Date(J.lastUpdated))&&(J.lastUpdated=oe)});const Q=(i==null?void 0:i.jobs)||[],K=M=>{const z=`${M.filePath||""}::${M.name}`;return(c==null?void 0:c.includes(z))||!1};k.forEach(M=>{const z=M.entities.map(J=>K(J)?"queued":wt(J,Q));z.includes("analyzing")||z.includes("queued")?M.state="analyzing":z.includes("incomplete")?M.state="incomplete":z.includes("out-of-date")?M.state="out-of-date":z.includes("not-analyzed")?M.state="not-analyzed":M.state="up-to-date"}),k.forEach(M=>{var z,J,te,oe,de;for(const ue of M.entities){if(M.previewScreenshots.length+M.previewLibraryScenarios.length>=3)break;const Se=((J=(z=ue.analyses)==null?void 0:z[0])==null?void 0:J.scenarios)||[];if(ue.entityType==="library"){const Te=Se.find($e=>{var Re,X;return((Re=$e.metadata)==null?void 0:Re.executionResult)||((X=$e.metadata)==null?void 0:X.error)});Te&&M.previewLibraryScenarios.push({scenario:Te,entitySha:ue.sha})}else{const Te=Se.find($e=>{var Re,X;return(X=(Re=$e.metadata)==null?void 0:Re.screenshotPaths)==null?void 0:X[0]});if(Te){const $e=(oe=(te=Te.metadata)==null?void 0:te.screenshotPaths)==null?void 0:oe[0],Re=!!((de=Te.metadata)!=null&&de.error);$e&&!M.previewScreenshots.includes($e)&&(M.previewScreenshots.push($e),M.previewScreenshotErrors.push(Re))}}}});const F=Array.from(k.values());return F.sort((M,z)=>{if(a==="analyzed"){const oe=Math.max(...M.entities.filter(ue=>{var me,Se;return(Se=(me=ue.analyses)==null?void 0:me[0])==null?void 0:Se.createdAt}).map(ue=>new Date(ue.analyses[0].createdAt).getTime()),0),de=Math.max(...z.entities.filter(ue=>{var me,Se;return(Se=(me=ue.analyses)==null?void 0:me[0])==null?void 0:Se.createdAt}).map(ue=>new Date(ue.analyses[0].createdAt).getTime()),0);return R==="desc"?de-oe:oe-de}if(M.uncommittedCount>0&&z.uncommittedCount===0)return-1;if(M.uncommittedCount===0&&z.uncommittedCount>0)return 1;const J=M.lastUpdated?new Date(M.lastUpdated).getTime():0,te=z.lastUpdated?new Date(z.lastUpdated).getTime():0;return R==="desc"?te-J:J-te}),F},[$,a,R,i,c]),B=ie(()=>{let k=L;if(_!=="all"&&(k=k.filter(Y=>Y.state===_)),N.trim()){const Y=N.toLowerCase();k=k.filter(G=>G.filePath.toLowerCase().includes(Y))}return k},[L,N,_]),H=(t-1)*r,q=H+r,O=B.slice(H,q),W=Math.ceil(B.length/r),I=k=>{v(Y=>{const G=new Set(Y);return G.has(k)?G.delete(k):G.add(k),G})},j=()=>{D(k=>k==="desc"?"asc":"desc")};return d("div",{children:[d("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),d("div",{className:"flex gap-3",children:[d("div",{className:"relative w-[130px]",children:[d("select",{value:T,onChange:k=>{const Y=k.target.value,G=new URLSearchParams(x);Y==="all"?G.delete("entityType"):G.set("entityType",Y),G.set("page","1"),b(G)},className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(St,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"relative w-[130px]",children:[d("select",{value:_,onChange:k=>E(k.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All States"}),n("option",{value:"analyzing",children:"Analyzing..."}),n("option",{value:"up-to-date",children:"Up to date"}),n("option",{value:"incomplete",children:"Incomplete"}),n("option",{value:"out-of-date",children:"Out of date"}),n("option",{value:"not-analyzed",children:"Not analyzed"})]}),n(St,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"flex-1 relative",children:[n(Dr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",value:N,onChange:k=>S(k.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),h!==void 0&&m!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center",children:[d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:B.length})," ",B.length===1?"file":"files"]}),d("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:d("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:B.reduce((k,Y)=>k+Y.totalCount,0)})," ",B.reduce((k,Y)=>k+Y.totalCount,0)===1?"entity":"entities"]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),g?d("button",{onClick:y,className:"flex items-center gap-2 text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase cursor-pointer",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[B.filter(k=>k.uncommittedCount>0).length," ","uncommitted"," ",B.filter(k=>k.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):d("button",{onClick:y,className:"text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[f," uncommitted"," ",f===1?"file":"files"]})]}),O.length>0&&d("div",{className:"flex gap-6",children:[d("button",{onClick:()=>{v(new Set(O.map(k=>k.filePath))),A(!0)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Dc,{className:"w-3.5 h-3.5"}),"Expand All"]}),d("button",{onClick:()=>{v(new Set),A(!1)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Fc,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(Ei,{showActions:!0,sortOrder:R,onSortChange:j}),n("div",{className:"flex flex-col gap-[3px]",children:O.map(k=>{const Y=w.has(k.filePath),Q=k.entities.filter(z=>(z.entityType==="visual"||z.entityType==="library")&&(wt(z,(i==null?void 0:i.jobs)||[])==="not-analyzed"||wt(z,(i==null?void 0:i.jobs)||[])==="out-of-date"||wt(z,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,K=z=>{var J;return((J=s==null?void 0:s.currentEntityShas)==null?void 0:J.includes(z))||!1},F=z=>{var J;return l!=null&&l(z)?!0:((J=i==null?void 0:i.jobs)==null?void 0:J.some(te=>{var oe;return(oe=te.entityShas)==null?void 0:oe.includes(z.sha)}))||!1},M=z=>{p==null||p(z)};return n(Ai,{filePath:k.filePath,isExpanded:Y,onToggle:()=>I(k.filePath),simulationPreviews:n(Pi,{entities:k.entities,maxPreviews:1}),entityCount:k.totalCount,state:k.state,lastModified:k.lastUpdated,uncommittedCount:k.uncommittedCount,isUncommitted:k.uncommittedCount>0,actionButton:Q?n("button",{onClick:z=>{z.stopPropagation();const J=k.entities.filter(te=>(te.entityType==="visual"||te.entityType==="library")&&(wt(te,(i==null?void 0:i.jobs)||[])==="not-analyzed"||wt(te,(i==null?void 0:i.jobs)||[])==="out-of-date"||wt(te,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(J)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:k.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:k.entities.sort((z,J)=>{var me,Se,Te,$e;const te=!((me=z.metadata)!=null&&me.notExported)&&!((Se=z.metadata)!=null&&Se.namedExport),oe=!((Te=J.metadata)!=null&&Te.notExported)&&!(($e=J.metadata)!=null&&$e.namedExport);if(te&&!oe)return-1;if(!te&&oe)return 1;const de=z.entityType==="visual"||z.entityType==="library",ue=J.entityType==="visual"||J.entityType==="library";return de&&!ue?-1:!de&&ue?1:z.name.localeCompare(J.name)}).map(z=>n(ji,{entity:z,isActivelyAnalyzing:K(z.sha),isQueued:F(z),onGenerateSimulation:M},z.sha))},k.filePath)})}),W>1&&d("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),d("span",{children:["Page ",t," of ",W]}),t<W&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const M1=()=>[{title:"Files & Entities - CodeYam"},{name:"description",content:"Browse your codebase files and entities"}];async function $1({request:e,context:t}){try{const r=new URL(e.url),s=parseInt(r.searchParams.get("page")||"1"),a=r.searchParams.get("filter")||null,o=r.searchParams.get("entityType"),i=t.analysisQueue,l=i?i.getState():{paused:!1,jobs:[]},[c,p]=await Promise.all([Pn(),rr()]);return re({entities:c,currentCommit:p,page:s,filter:a,entityType:o,queueState:l})}catch(r){return console.error("Failed to load entities:",r),re({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const I1=et(function(){var N,S,C;const{entities:t,currentCommit:r,page:s,filter:a,entityType:o,queueState:i,error:l}=st();Ut();const[c,p]=Zn(),[u,h]=P(!1);Dt({source:"files-page"});const{handleGenerateSimulation:m,handleGenerateAllSimulations:f,isEntityPending:g,pendingEntityKeys:y}=Yu((S=(N=r==null?void 0:r.metadata)==null?void 0:N.currentRun)==null?void 0:S.currentEntityShas,i),x=t||[],b=ie(()=>{const A=new Set([]);for(const _ of x)A.add(_.filePath??"No File Path");return Array.from(A)},[x]),w=ie(()=>{let A=x;return u&&(A=A.filter(_=>{var E;return(E=_.metadata)==null?void 0:E.isUncommitted})),A.sort((_,E)=>{var R,D,T,$,L,B;return(R=_.metadata)!=null&&R.isUncommitted&&!((D=E.metadata)!=null&&D.isUncommitted)?-1:!((T=_.metadata)!=null&&T.isUncommitted)&&(($=E.metadata)!=null&&$.isUncommitted)?1:new Date(((L=E.metadata)==null?void 0:L.editedAt)||0).getTime()-new Date(((B=_.metadata)==null?void 0:B.editedAt)||0).getTime()})},[x,u]),v=ie(()=>{var _;const A=new Set([]);for(const E of x)(_=E.metadata)!=null&&_.isUncommitted&&A.add(E.filePath??"No File Path");return Array.from(A)},[x]);return l?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:l})]})}):x.length===0?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-20 py-12 font-sans",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:d("div",{className:"max-w-md mx-auto",children:[n("h2",{className:"text-xl font-semibold text-gray-900 mb-3",children:"No entities found"}),d("p",{className:"text-[15px] text-gray-600 mb-6",children:["Your project hasn't been analyzed yet. Run"," ",n("code",{className:"px-2 py-1 bg-gray-100 rounded text-sm font-mono",children:"codeyam analyze"})," ","to extract entities from your codebase."]}),n("p",{className:"text-sm text-gray-500",children:"Entities include React components, functions, and other analyzable code elements."})]})})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-20 py-12 font-sans",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n(T1,{entities:w,page:s,itemsPerPage:50,currentRun:(C=r==null?void 0:r.metadata)==null?void 0:C.currentRun,filter:a,entityType:o,queueState:i,isEntityPending:g,pendingEntityKeys:y,onGenerateSimulation:m,onGenerateAllSimulations:f,totalFilesCount:b.length,totalEntitiesCount:x.length,uncommittedFilesCount:v.length,showOnlyUncommitted:u,onToggleUncommitted:()=>h(!u)})]})})}),R1=Object.freeze(Object.defineProperty({__proto__:null,default:I1,loader:$1,meta:M1},Symbol.toStringTag,{value:"Module"})),D1=()=>[{title:"Labs - CodeYam"},{name:"description",content:"Experimental features"}];async function F1({request:e}){var t;try{const r=await Ye();if(!r)return re({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Project not found"});const{project:s}=await De(r),a=Ne()||process.cwd(),o=Nu(a)||"";let i="";try{const c=await ea();if(c!=null&&c.webapps&&Array.isArray(c.webapps)){const p=c.webapps.map(u=>u.framework).filter(Boolean);p.length>0&&(i=p.join(", "))}}catch{}const l=_u(r);return re({labs:((t=s.metadata)==null?void 0:t.labs)??null,projectSlug:r,defaultEmail:o,detectedTechStack:i,unlockCode:l,error:null})}catch(r){return console.error("Failed to load labs config:",r),re({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Failed to load labs configuration"})}}async function O1({request:e}){try{const t=await e.formData(),r=t.get("feature"),s=t.get("enabled")==="true";if(!r)return re({success:!1,error:"Missing feature name"},{status:400});const a=await Ye();return a?(r==="clearAccess"?await Gn({projectSlug:a,metadataUpdate:{labs:{accessGranted:!1,simulations:!1}}}):await Gn({projectSlug:a,metadataUpdate:{labs:{[r]:s}}}),re({success:!0,error:null})):re({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),re({success:!1,error:"Failed to save labs configuration"},{status:500})}}const L1=[{id:"simulations",name:"Simulations",description:"Enable entity analysis, visual simulations, git impact analysis, file browsing, and activity monitoring. When disabled, only Memory, Labs, and Settings are accessible.",defaultEnabled:!0},{id:"enhancedClaudeTesting",name:"Enhanced Claude Testing",description:"Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!0},{id:"gitIntegration",name:"Git Integration Showing Impacted Files",description:"Lorem Ipsum Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!1}],hc="https://docs.google.com/forms/d/e/1FAIpQLSfopqQOQsjY9S4Ns0l3xDLzGl7iYNpKa2Wn2Xzmtxj8CR1sMA/viewform",B1=[{title:"CodeYam Simulations",status:"apply for early access",desc:"CodeYam Simulations are the core of the CodeYam development experience. They leverage static code analysis and AI to generate robust data scenarios that are used to hydrate code. This creates a whole new dimension to the software development experience"},{title:"The Full CodeYam Experience",status:"more to come",desc:"CodeYam is completely rethinking the software development experience in the AI era. Focused on navigating the challenges of iteration speed, complexity, and communication, CodeYam will provide a powerful software development experience."}];function z1({onClose:e}){const t=fe(null),r=fe(0);return ae(()=>{const s=t.current;if(!s)return;const a=100,o=2e3,i=500;let l=null,c=!1;const p=()=>{r.current=Date.now(),!l&&!c&&(l=setInterval(()=>{const u=Date.now()-r.current,h=s.scrollTop>a,m=u>o;h&&m&&(s.scrollTo({top:0,behavior:"smooth"}),c=!0,l&&(clearInterval(l),l=null))},i))};return s.addEventListener("scroll",p,{passive:!0}),()=>{s.removeEventListener("scroll",p),l&&clearInterval(l)}},[]),d("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:s=>{s.target===s.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),d("div",{className:"relative bg-white rounded-xl max-w-3xl w-full mx-4 max-h-[90vh] overflow-hidden",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none z-10",children:"×"}),d("div",{ref:t,className:"overflow-y-auto max-h-[90vh] p-4 md:p-6",children:[d("div",{className:"mb-4",children:[n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Request Early Access"}),n("p",{className:"text-sm text-gray-500",children:"Complete the form below to join the waitlist for CodeYam Labs."})]}),n("div",{className:"bg-white rounded-lg overflow-hidden",children:n("iframe",{src:`${hc}?embedded=true`,width:"100%",height:"1400",style:{border:0,minHeight:"1400px"},title:"Labs Waitlist Form",loading:"eager",children:n("div",{className:"flex items-center justify-center p-8 text-gray-600",children:d("div",{className:"text-center",children:[n("div",{className:"mb-4",children:"Loading form..."}),d("div",{className:"text-sm",children:["If this takes too long,"," ",n("a",{href:hc,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"open the form directly"})]})]})})})})]})]})]})}function Y1({onClose:e,unlockCodeInput:t,setUnlockCodeInput:r,unlockFetcher:s}){var i,l;const a=(i=s.data)==null?void 0:i.error,o=(l=s.data)==null?void 0:l.success;return d("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:c=>{c.target===c.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),d("div",{className:"relative bg-white rounded-xl p-8 max-w-md w-full mx-4",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none",children:"×"}),n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Have an unlock code?"}),n("p",{className:"text-sm text-cygray-50 mb-6",children:"If you've received an unlock code, paste it below to enable Simulations immediately."}),d(s.Form,{method:"post",action:"/api/labs-unlock",className:"space-y-4",children:[n("input",{type:"text",name:"unlockCode",value:t,onChange:c=>r(c.target.value),placeholder:"CY-...",className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-100 focus:border-transparent"}),n("button",{type:"submit",disabled:!t.trim()||s.state==="submitting",className:"w-full py-3 text-white border-none rounded-lg text-sm font-mono font-semibold uppercase tracking-wider cursor-pointer transition-all bg-primary-200 hover:bg-primary-100 disabled:bg-gray-400 disabled:cursor-not-allowed",children:s.state==="submitting"?"Validating...":"Unlock"}),a&&n("p",{className:"text-red-600 text-sm mt-2",children:a}),o&&n("p",{className:"text-emerald-600 text-sm mt-2",children:"Simulations enabled! Refresh the page to see all tabs."})]})]})]})}const W1=et(function(){const{labs:t,unlockCode:r,error:s}=st(),a=Ke(),o=Ke(),i=Ke(),[l,c]=P(""),[p,u]=P(!1),[h,m]=P(!1);Dt({source:"labs-page"});const f=(t==null?void 0:t.accessGranted)===!0||(t==null?void 0:t.simulations)===!0;return s?n("div",{className:"bg-cygray-10 min-h-screen",children:d("div",{className:"px-20 pt-8 pb-12 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Labs"}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 mt-4",children:n("p",{className:"text-red-700",children:s})})]})}):f?d("div",{className:"bg-cygray-10 min-h-screen font-sans flex flex-col",children:[n("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"})}),d("div",{className:"px-6 sm:px-12 pt-8 pb-10",children:[n("h2",{className:"font-serif italic text-[32px] sm:text-[48px] text-primary-100 mb-3 font-normal leading-tight",children:"Congrats!"}),n("p",{className:"font-serif text-[18px] sm:text-[24px] text-cyblack-100 font-normal leading-snug max-w-2xl",children:"You were granted early access to software simulation and other experimental features."})]}),n("div",{className:"px-6 sm:px-12 space-y-6 flex-1",children:L1.map(g=>{var b;const y=(t==null?void 0:t[g.id])??g.defaultEnabled,x=o.state==="submitting"&&((b=o.formData)==null?void 0:b.get("feature"))===g.id;return n("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:d("div",{className:"flex items-center justify-between gap-4",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-3 mb-3",children:[n("h3",{className:"text-lg font-semibold text-cyblack-100 m-0",children:g.name}),n("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${y?"bg-primary-100/15 text-primary-100":"bg-cygray-20 text-cygray-50"}`,children:y?"Enabled":"Disabled"})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed m-0",children:g.description})]}),d(o.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:g.id}),n("input",{type:"hidden",name:"enabled",value:String(!y)}),n("button",{type:"submit",disabled:x,className:`relative inline-flex h-8 w-14 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none disabled:opacity-60 disabled:cursor-not-allowed ${y?"bg-primary-100":"bg-gray-300"}`,children:n("span",{className:`pointer-events-none inline-block h-7 w-7 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${y?"translate-x-6":"translate-x-0"}`})})]})]})},g.id)})}),r&&n("div",{className:"px-6 sm:px-12 pt-12",children:d("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:[n("h3",{className:"text-base font-semibold text-cyblack-100 mb-1",children:"Unlock Code"}),n("p",{className:"text-sm text-cygray-50 mb-3",children:"This code was used to enable Labs access. Clear it to revoke access and return to the landing page."}),d("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[n("code",{className:"sm:flex-1 px-4 py-2.5 bg-cygray-10 border border-cygray-30 rounded-lg text-sm font-mono text-cyblack-100 overflow-x-auto",children:r}),d(i.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:"clearAccess"}),n("input",{type:"hidden",name:"enabled",value:"false"}),n("button",{type:"submit",disabled:i.state==="submitting",className:"px-4 py-2.5 bg-red-50 border border-red-200 rounded-lg text-sm font-medium text-red-700 cursor-pointer transition-colors hover:bg-red-100 disabled:opacity-60 disabled:cursor-not-allowed",children:i.state==="submitting"?"Clearing...":"Clear"})]})]})]})})]}):d("div",{className:"bg-cygray-10 min-h-screen font-sans",children:[p&&n(z1,{onClose:()=>u(!1)}),h&&n(Y1,{onClose:()=>m(!1),unlockCodeInput:l,setUnlockCodeInput:c,unlockFetcher:a}),d("div",{className:"flex flex-wrap justify-between items-center gap-3 px-6 sm:px-12 pt-8 pb-4",children:[n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"}),d("div",{className:"flex flex-wrap items-center gap-3",children:[n("button",{onClick:()=>m(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cygray-30 bg-transparent text-cygray-50 cursor-pointer transition-colors hover:border-cyblack-100 hover:text-cyblack-100",children:"Have a Code?"}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cyblack-100 bg-transparent text-cyblack-100 cursor-pointer transition-colors hover:bg-cyblack-100 hover:text-white",children:"Apply for Early Access"})]})]}),d("div",{className:"px-6 sm:px-12 pt-12 pb-8",children:[n("h2",{className:"font-serif text-[24px] sm:text-[32px] leading-snug text-cyblack-100 max-w-xl mb-4 font-normal",children:"Powerful tools for the AI coding era."}),d("p",{className:"text-base sm:text-lg text-cygray-50 leading-relaxed max-w-xl mb-8",children:["We're opening early access to"," ",n("strong",{className:"text-cyblack-100",children:"experimental features"})," to a small group of developers and teams."]}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded bg-primary-200 text-white border-none cursor-pointer transition-colors hover:bg-primary-100",children:"Apply for Early Access"})]}),n("div",{className:"px-6 sm:px-12 py-8",children:n("hr",{className:"border-t border-cygray-30 m-0"})}),d("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:[n("h3",{className:"font-serif text-[22px] sm:text-[28px] text-cyblack-100 mb-10 font-normal text-center",children:"In The Works"}),n("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5 max-w-4xl mx-auto",children:B1.map(g=>d("div",{className:"border border-cygray-30 bg-white p-5 sm:p-8 rounded-lg",children:[d("h4",{className:"text-base font-semibold text-cyblack-100 mb-1",children:[g.title," ",d("span",{className:"font-normal text-primary-100 font-serif italic",children:["(",g.status,")"]})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed mt-3 mb-0",children:g.desc})]},g.title))})]}),n("div",{className:"px-6 sm:px-12 py-16",children:d("div",{className:"rounded-lg p-6 sm:p-12 bg-primary-200",children:[n("h3",{className:"font-serif text-[20px] sm:text-[24px] text-white mb-4 font-semibold",children:"Request Early Access"}),n("p",{className:"text-sm text-white/80 leading-relaxed max-w-lg mb-10 font-mono",children:"We're onboarding a limited number of developers and teams. Tell us about how you build and we'll let you know when you can try simulations and other Labs features."}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded border border-white bg-white text-cyblack-100 cursor-pointer transition-colors hover:bg-white/90 mb-4",children:"Apply for Early Access"}),n("p",{className:"text-xs text-white/60 m-0",children:"Takes about 2 minutes. Your answers help us determine eligibility and prioritize access."})]})})]})}),U1=Object.freeze(Object.defineProperty({__proto__:null,action:O1,default:W1,loader:F1,meta:D1},Symbol.toStringTag,{value:"Module"}));function J1(e,t,r){const[s,a]=P(()=>new Set),[o,i]=P(()=>new Set),l=fe([]),c=fe([]);return ae(()=>{(t.length!==l.current.length||t.some((y,x)=>y!==l.current[x]))&&(l.current=t,a(y=>{const x=new Set;return t.forEach(b=>{y.has(b)&&x.add(b)}),x}))},[t]),ae(()=>{(r.length!==c.current.length||r.some((y,x)=>y!==c.current[x]))&&(c.current=r,i(y=>{const x=new Set;return r.forEach(b=>{y.has(b)&&x.add(b)}),x}))},[r]),{expandedUncommitted:s,expandedBranch:o,setExpandedUncommitted:a,setExpandedBranch:i,toggleFile:(g,y,x)=>{x(b=>{const w=new Set(b);return w.has(g)?w.delete(g):w.add(g),w})},expandAllUncommitted:()=>{a(new Set(t))},collapseAllUncommitted:()=>{a(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function H1(e,t,r){const[s,a]=P(null),[o,i]=P(null),l=Ke();ae(()=>{var h,m;((h=l.data)==null?void 0:h.oldContent)!==void 0&&((m=l.data)==null?void 0:m.newContent)!==void 0&&i({oldContent:l.data.oldContent,newContent:l.data.newContent,fileName:l.data.fileName})},[l.data]);const c=h=>{a({type:"file",path:h}),i(null);const m=new FormData;m.append("actionType","getDiff"),m.append("filePath",h),m.append("diffType","branch"),m.append("baseBranch",e),m.append("currentBranch",t||""),l.submit(m,{method:"post"})},p=(h,m)=>{a({type:"entity",path:h,entitySha:m}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",h),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",m),l.submit(f,{method:"post"})},u=()=>{a(null),i(null)};return{diffView:s,diffContent:o,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:c,handleShowEntityDiff:p,handleCloseDiff:u}}function V1({diffView:e,diffContent:t,isLoading:r,entities:s,onClose:a}){var p;const[o,i]=P(!1),[l,c]=P(!1);return ae(()=>{c(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:d("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[d("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[d("div",{children:[n("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),n("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&d("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((p=s.find(u=>u.sha===e.entitySha))==null?void 0:p.name)||e.entitySha]})]}),d("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick:a,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:l&&n(Mh,{oldValue:t.oldContent,newValue:t.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!o,extraLinesSurroundingDiff:4,styles:{variables:{light:{diffViewerBackground:"#fff",diffViewerColor:"#212529",addedBackground:"#e6ffed",addedColor:"#24292e",removedBackground:"#ffeef0",removedColor:"#24292e",wordAddedBackground:"#acf2bd",wordRemovedBackground:"#fdb8c0",addedGutterBackground:"#cdffd8",removedGutterBackground:"#ffdce0",gutterBackground:"#f6f8fa",gutterBackgroundDark:"#f3f4f6",highlightBackground:"#fffbdd",highlightGutterBackground:"#fff5b1"}},contentText:{fontSize:"12px",lineHeight:"1.5"},line:{padding:"2px 10px",fontSize:"12px","&:hover":{background:"#f8f9fa"}},splitView:{display:"flex",width:"100%"},diffContainer:{width:"50%",overflowX:"auto"}}})}):n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"No diff available"})})}),n("div",{className:"p-6 border-t border-[#e1e1e1] flex justify-end gap-3",children:n("button",{onClick:a,className:"px-4 py-2 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",children:"Close"})})]})})}function G1({files:e,currentBranch:t,defaultBranch:r,baseBranch:s,allBranches:a,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:l,sortOrder:c,onToggleFile:p,onBranchChange:u,onGenerateSimulation:h,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}){const x=e.flatMap(([v,{entities:N}])=>{const S=N.filter(C=>i(C.sha)||l(C)).map(C=>C.sha);return S.length>0?[{entityShas:S}]:[]}),b=v=>{const N=v.map(S=>wt(S,x));return N.includes("analyzing")||N.includes("queued")?"analyzing":N.includes("out-of-date")?"out-of-date":N.includes("not-analyzed")?"not-analyzed":"up-to-date"},w=ie(()=>[...e].sort((v,N)=>{const S=v[1].entities.reduce((E,R)=>{var T;const D=((T=R.metadata)==null?void 0:T.editedAt)||R.updatedAt;return D?E?new Date(D)>new Date(E)?D:E:D:E},null),C=N[1].entities.reduce((E,R)=>{var T;const D=((T=R.metadata)==null?void 0:T.editedAt)||R.updatedAt;return D?E?new Date(D)>new Date(E)?D:E:D:E},null);if(!S&&!C)return 0;if(!S)return 1;if(!C)return-1;const A=new Date(S).getTime(),_=new Date(C).getTime();return c==="desc"?_-A:A-_}),[e,c]);return n("div",{children:e.length>0?d("div",{children:[n(Ei,{showActions:!0,sortOrder:c,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}),n("div",{className:"flex flex-col gap-[3px]",children:w.map(([v,{status:N,entities:S,isUncommitted:C}])=>{const A=o.has(v),_=b(S),E=S.reduce(($,L)=>{var H;const B=((H=L.metadata)==null?void 0:H.editedAt)||L.updatedAt;return B?$?new Date(B)>new Date($)?B:$:B:$},null),D=S.filter($=>$.entityType==="visual"||$.entityType==="library").length===0;let T;return D?T=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):_==="analyzing"?T=d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):_==="up-to-date"?T=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):_==="out-of-date"?T=n("button",{onClick:$=>{$.stopPropagation(),S.filter(L=>(L.entityType==="visual"||L.entityType==="library")&&!i(L.sha)&&!l(L)).forEach(L=>h(L))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):_==="not-analyzed"&&(T=n("button",{onClick:$=>{$.stopPropagation(),S.filter(L=>(L.entityType==="visual"||L.entityType==="library")&&!i(L.sha)&&!l(L)).forEach(L=>h(L))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Ai,{filePath:v,isExpanded:A,onToggle:()=>p(v),fileStatus:N,isUncommitted:C,simulationPreviews:n(Pi,{entities:S,maxPreviews:1}),entityCount:S.length,state:_,lastModified:E,isNotAnalyzable:D,actionButton:T,children:S.sort(($,L)=>{const B=$.entityType==="visual"||$.entityType==="library",H=L.entityType==="visual"||L.entityType==="library";return B&&!H?-1:!B&&H?1:0}).map($=>n(ji,{entity:$,isActivelyAnalyzing:i($.sha),isQueued:l($),onGenerateSimulation:h},$.sha))},v)})})]}):d("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function K1({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:s,isEntityQueued:a,projectSlug:o,baseBranch:i,currentBranch:l,sortOrder:c,onToggleFile:p,onShowFileDiff:u,onGenerateSimulation:h,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}){const x=ie(()=>{const v=[];return e.forEach(([N,{editedEntities:S}])=>{const C=S.filter(A=>s(A.sha)||a(A)).map(A=>A.sha);C.length>0&&v.push({entityShas:C})}),v},[e,s,a]),b=ie(()=>{const v=new Map;return e.forEach(([N,{editedEntities:S}])=>{const C=S.map(R=>wt(R,x));let A;C.includes("analyzing")||C.includes("queued")?A="analyzing":C.includes("out-of-date")?A="out-of-date":C.includes("not-analyzed")?A="not-analyzed":A="up-to-date";const _=S.reduce((R,D)=>{var $;const T=(($=D.metadata)==null?void 0:$.editedAt)||D.updatedAt;return T&&(!R||new Date(T)>new Date(R))?T:R},null),E=S.filter(R=>R.entityType==="visual"||R.entityType==="library").length;v.set(N,{state:A,lastModified:_,analyzableCount:E})}),v},[e,x]),w=ie(()=>[...e].sort((v,N)=>{const S=b.get(v[0]),C=b.get(N[0]),A=S==null?void 0:S.lastModified,_=C==null?void 0:C.lastModified;if(!A&&!_)return 0;if(!A)return 1;if(!_)return-1;const E=new Date(A).getTime(),R=new Date(_).getTime();return c==="desc"?R-E:E-R}),[e,b,c]);return e.length===0?d("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"If you edit a file in your project, it will show up here."})]}):d("div",{children:[n(Ei,{showActions:!0,sortOrder:c,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}),n("div",{className:"flex flex-col gap-[3px]",children:w.map(([v,{status:N,editedEntities:S}])=>{const C=r.has(v),A=b.get(v),{state:_,lastModified:E,analyzableCount:R}=A,D=R===0;let T;return D?T=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):_==="analyzing"?T=d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):_==="up-to-date"?T=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):_==="out-of-date"?T=n("button",{onClick:$=>{$.stopPropagation(),S.filter(L=>(L.entityType==="visual"||L.entityType==="library")&&!s(L.sha)&&!a(L)).forEach(L=>h(L))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):_==="not-analyzed"&&(T=n("button",{onClick:$=>{$.stopPropagation(),S.filter(L=>(L.entityType==="visual"||L.entityType==="library")&&!s(L.sha)&&!a(L)).forEach(L=>h(L))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Ai,{filePath:v,isExpanded:C,onToggle:()=>p(v),fileStatus:N,simulationPreviews:n(Pi,{entities:S,maxPreviews:1}),entityCount:S.length,state:_,lastModified:E,isNotAnalyzable:D,isUncommitted:!0,actionButton:T,children:S.sort(($,L)=>{const B=$.entityType==="visual"||$.entityType==="library",H=L.entityType==="visual"||L.entityType==="library";return B&&!H?-1:!B&&H?1:0}).map($=>n(ji,{entity:$,isActivelyAnalyzing:s($.sha),isQueued:a($),onGenerateSimulation:h},$.sha))},v)})})]})}function q1({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:s}){return n("div",{className:"border-b border-gray-200",children:d("nav",{className:"flex gap-8 items-center",children:[d("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[d("span",{className:"flex items-center gap-2",children:["Branch Changes",s>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="branch"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:s})]}),e==="branch"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]}),d("button",{onClick:()=>t("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[d("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:r})]}),e==="uncommitted"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const Q1=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function Z1({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const s=t.get("filePath"),a=t.get("diffType"),o=t.get("baseBranch"),i=t.get("currentBranch"),l=t.get("entitySha");let c;return a==="branch"?c=Cs(s,o,i):c=rx(s),re({...c,entitySha:l})}return re({error:"Unknown action"},{status:400})}async function X1({request:e,context:t}){try{const r=new URL(e.url),s=r.searchParams.get("compare"),a=r.searchParams.get("viewBranch"),o=t.analysisQueue,i=o?o.getState():{paused:!1,jobs:[]},[l,c,p]=await Promise.all([Pn(),rr(),Ye()]),u=or(),h=Xy(),m=ex(),f=tx(),g=a||h,y=s||m;let x=[];return g&&g!==y&&(x=Qd(y,g)),re({entities:l||[],gitStatus:u,currentBranch:g,actualCurrentBranch:h,defaultBranch:m,allBranches:f,baseBranch:y,branchDiff:x,currentCommit:c,projectSlug:p,queueState:i})}catch(r){return console.error("Failed to load git data:",r),re({entities:[],gitStatus:[],currentBranch:null,actualCurrentBranch:null,defaultBranch:"main",allBranches:[],baseBranch:"main",branchDiff:[],currentCommit:null,projectSlug:null,queueState:{paused:!1,jobs:[]},error:"Failed to load git data"})}}const e2=et(function(){var xe,Me;const{entities:t,gitStatus:r,currentBranch:s,actualCurrentBranch:a,defaultBranch:o,allBranches:i,baseBranch:l,branchDiff:c,currentCommit:p,projectSlug:u,queueState:h}=st();Dt({source:"git-page"});const[m,f]=Zn(),[g,y]=P(null),[x,b]=P("desc"),[w,v]=P("branch"),N=m.get("expanded")==="true",S=()=>{b(he=>he==="desc"?"asc":"desc")},C=Ke(),A=C.data;ae(()=>{s&&l&&s!==l&&C.state==="idle"&&!A&&C.load(`/api/branch-entity-diff?base=${encodeURIComponent(l)}&compare=${encodeURIComponent(s)}`)},[s,l,C,A]);const _=ie(()=>{const he=Fu(r,t);return Array.from(he.entries()).sort((He,Ve)=>He[0].localeCompare(Ve[0]))},[r,t]),E=ie(()=>{const he=QC(c,t,A);return Array.from(he.entries()).sort((He,Ve)=>He[0].localeCompare(Ve[0]))},[c,t,A]),R=ie(()=>ZC(r,t),[r,t]),D=ie(()=>w==="uncommitted"?_:E,[w,_,E]),T=ie(()=>D.map(([he])=>he),[D]),{expandedUncommitted:$,setExpandedUncommitted:L,toggleFile:B,expandAllUncommitted:H,collapseAllUncommitted:q}=J1(N,T,[]),{diffView:O,diffContent:W,isLoading:I,handleShowFileDiff:j,handleCloseDiff:k}=H1(l,s),Y=(xe=p==null?void 0:p.metadata)==null?void 0:xe.currentRun,G=new Set((Y==null?void 0:Y.currentEntityShas)||[]),Q=new Set(h.jobs.flatMap(he=>he.entityShas||[])),K=new Set(((Me=h.currentlyExecuting)==null?void 0:Me.entityShas)||[]),{isAnalyzing:F,handleGenerateSimulation:M,handleGenerateAllSimulations:z,isEntityBeingAnalyzed:J,isEntityPending:te}=Yu(Y==null?void 0:Y.currentEntityShas,h),oe=he=>te(he)||Q.has(he.sha)||K.has(he.sha),de=he=>{he===(a||s)?m.delete("viewBranch"):m.set("viewBranch",he),f(m)},ue=he=>{he===o?m.delete("compare"):m.set("compare",he),f(m)},me=()=>{const He=D.flatMap(([Ve,Oe])=>Oe.editedEntities||Oe.entities||[]).filter(Ve=>!G.has(Ve.sha)&&!Q.has(Ve.sha)&&!K.has(Ve.sha)&&!te(Ve));z(He)},Se=_.length,Te=E.length,$e=D.flatMap(([he,He])=>He.editedEntities||He.entities||[]),Re=$e.filter(he=>he.entityType==="visual"||he.entityType==="library"),X=Re.length>0&&Re.every(he=>G.has(he.sha)),ye=Re.length>0&&!X&&Re.every(he=>Q.has(he.sha)||K.has(he.sha)),ee=F||X||ye,ne=X?"Analyzing...":ye?"Queued...":F?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-20 py-12",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Git Changes"}),d("p",{className:"text-[15px] text-gray-500",children:["This is a list of all the files that are affected by your local changes. ",n("strong",{children:"Analyze a file to get simulations."})]})]}),n("div",{className:"mb-6",children:n(q1,{activeTab:w,onTabChange:v,uncommittedCount:Se,branchCount:Te})}),s&&w==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:s===o?d("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:o}),"."]}):d("div",{className:"flex gap-6 items-center",children:[d("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?d("div",{className:"relative w-50",children:[n("select",{value:s,onChange:he=>de(he.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-2.5 pr-6 text-[13px] h-9.75 w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.map(he=>n("option",{value:he,children:he},he))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}):n("span",{className:"text-gray-900 font-medium text-[12px]",children:s})]}),d("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),d("div",{className:"relative w-[200px]",children:[n("select",{value:l,onChange:he=>ue(he.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.filter(he=>he!==s).map(he=>n("option",{value:he,children:he},he))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children:d("div",{className:"relative flex items-center",children:[n("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),n("div",{className:"mb-3",children:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center",children:[d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:D.length})," ","modified ",D.length===1?"file":"files"]}),d("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:d("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:$e.length})," ",$e.length===1?"entity":"entities"]})]}),D.length>0&&d("div",{className:"flex gap-6",children:[d("button",{onClick:H,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Dc,{className:"w-3.5 h-3.5"}),"Expand All"]}),d("button",{onClick:q,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Fc,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),d("div",{className:"overflow-hidden",children:[w==="branch"&&s&&n(G1,{files:E,currentBranch:s,defaultBranch:o,baseBranch:l,allBranches:i,expandedFiles:$,isEntityBeingAnalyzed:J,isEntityQueued:oe,sortOrder:x,onToggleFile:he=>B(he,$,L),onBranchChange:ue,onGenerateSimulation:M,onSortChange:S,onAnalyzeAll:me,analyzeAllDisabled:ee,analyzeAllText:ne}),w==="uncommitted"&&n(K1,{files:_,entityImpactMap:R,expandedFiles:$,isEntityBeingAnalyzed:J,isEntityQueued:oe,projectSlug:u,baseBranch:l,currentBranch:s,sortOrder:x,onToggleFile:he=>B(he,$,L),onShowFileDiff:j,onGenerateSimulation:M,onSortChange:S,onAnalyzeAll:me,analyzeAllDisabled:ee,analyzeAllText:ne})]}),O&&n(V1,{diffView:O,diffContent:W,isLoading:I,entities:t,onClose:k}),g&&u&&n(rn,{projectSlug:u,onClose:()=>y(null)})]})})}),t2=Object.freeze(Object.defineProperty({__proto__:null,action:Z1,default:e2,loader:X1,meta:Q1},Symbol.toStringTag,{value:"Module"})),mc=[{name:"Desktop",width:1440,height:900},{name:"Laptop",width:1024,height:768},{name:"Tablet",width:768,height:1024},{name:"Mobile",width:375,height:667}],n2=[{name:"iPhone 16",width:393,height:852},{name:"iPhone 16 Pro Max",width:430,height:932},{name:"iPhone SE",width:375,height:667},{name:"Pixel 8",width:412,height:915},{name:"iPad mini",width:744,height:1133}];function r2(e,t){if((t==null?void 0:t.includes("mobile-app"))??!1)return n2;const s=mc.map(i=>{const l=e==null?void 0:e[i.name];return l?{...i,...l}:i});if(!e)return s;const a=new Set(mc.map(i=>i.name)),o=Object.entries(e).filter(([i])=>!a.has(i)).map(([i,l])=>({name:i,width:l.width,height:l.height}));return[...s,...o]}const vs={width:24,height:76};function s2({width:e,height:t,enabled:r=!0,children:s}){if(!r)return n(we,{children:s});const a=12,o=48,i=28,l=e+a*2,c=t+o+i;return d("div",{style:{width:`${l}px`,height:`${c}px`,background:"#1a1a1a",borderRadius:"44px",padding:`${o}px ${a}px ${i}px`,position:"relative",boxShadow:"0 0 0 1px rgba(255,255,255,0.08), 0 8px 32px rgba(0,0,0,0.4)"},children:[n("div",{style:{position:"absolute",top:"14px",left:"50%",transform:"translateX(-50%)",width:"100px",height:"24px",background:"#000",borderRadius:"12px"}}),n("div",{style:{width:`${e}px`,height:`${t}px`,borderRadius:"6px",overflow:"hidden",position:"relative"},children:s}),n("div",{style:{position:"absolute",bottom:"10px",left:"50%",transform:"translateX(-50%)",width:"120px",height:"4px",background:"rgba(255,255,255,0.25)",borderRadius:"2px"}})]})}function a2({featureName:e,editorStep:t,editorStepLabel:r,onContinue:s}){const a=ce(o=>{o.key==="Enter"&&(o.preventDefault(),s())},[s]);return ae(()=>(window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)),[a]),n("div",{className:"flex items-center justify-center h-full bg-[#1e1e1e] text-[#d4d4d4]",children:d("div",{className:"max-w-md w-full mx-4 p-6 bg-[#252526] border border-[#3d3d3d] rounded-lg",children:[n("h2",{className:"text-lg font-semibold mb-3 text-white",children:"Resume Previous Session?"}),n("p",{className:"text-sm text-[#999] mb-4",children:"An editor session is still in progress:"}),d("div",{className:"bg-[#1e1e1e] rounded p-3 mb-5 text-sm",children:[e&&d("div",{className:"mb-1",children:[n("span",{className:"text-[#999]",children:"Feature:"})," ",n("span",{className:"text-white",children:e})]}),t!=null&&r&&d("div",{children:[n("span",{className:"text-[#999]",children:"Step:"})," ",d("span",{className:"text-white",children:[t," (",r,")"]})]})]}),n("button",{onClick:s,className:"w-full px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-[#005c75] text-white font-medium hover:bg-[#004d63] ring-2 ring-white/50",children:"Continue Session"})]})})}const o2={1:"Plan",2:"Prepare",3:"Prototype",4:"Verify Prototype",5:"Confirm",6:"Deconstruct",7:"Extract",8:"Glossary",9:"Analyze",10:"App Scenarios",11:"User Scenarios",12:"Verify",13:"Journal",14:"Review",15:"Present",16:"Commit",17:"Finalize",18:"Push"},i2={1:"Plan the feature and confirm the approach with the user before writing any code.",2:"Prepare the project environment and dependencies for prototyping.",3:"Build a working prototype quickly to validate the concept.",4:"Verify the prototype works correctly and fix any issues.",5:"Confirm the prototype looks right and get user approval to proceed.",6:"Read the code and plan all component and function extractions.",7:"Extract components and functions via TDD — components first, then functions.",8:"Record all extracted functions and components in the glossary.",9:"Analyze imports and verify all components are captured correctly.",10:"Create app-level scenarios that show full pages with realistic data.",11:"Create user-persona scenarios that exercise the app from different perspectives.",12:"Review all screenshots and check for visual errors or regressions.",13:"Create or update the journal entry documenting what was built.",14:"Final review of screenshots, audit for completeness.",15:"Present a summary of all work to the user for approval.",16:"Commit all changes to git.",17:"Update the journal with final details and amend the commit.",18:"Push the branch to the remote repository."},l2={1:"Survey",2:"App Scenarios",3:"Component Scenarios",4:"Preview",5:"Discuss",6:"Decompose",7:"Extract",8:"Recapture",9:"Journal",10:"Present"},c2={1:"Survey the existing codebase to understand pages, components, and dependencies.",2:"Create app-level scenarios showing full pages with realistic data.",3:"Create component-level scenarios for isolated component previews.",4:"Preview all captured scenarios and verify they look correct.",5:"Discuss the migration plan and prioritize which pages to decompose.",6:"Plan the decomposition of pages into clean, reusable components.",7:"Extract components and functions with tests via TDD.",8:"Recapture scenarios after extraction to verify nothing broke.",9:"Document the migration progress in a journal entry.",10:"Present the migration results for review and approval."},d2=18,u2=10;function p2({projectTitle:e,featureName:t,editorStep:r,editorStepLabel:s,migrationMode:a}){const[o,i]=P(!1),[l,c]=P(null),p=fe(null);ae(()=>{if(!o)return;const b=w=>{p.current&&!p.current.contains(w.target)&&i(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[o]);const u=t&&r!=null,h=a==="active",m=h?l2:o2,f=h?c2:i2,g=h?u2:d2,y=u?s||m[r]||"?":null;return d("div",{className:"h-8 shrink-0 flex items-center justify-between px-3 bg-[#2a2a2a] border-b border-[#333] text-xs select-none",children:[d("div",{className:"flex items-center gap-1.5 min-w-0",children:[n("span",{className:"text-[#888] truncate",children:e||"New Project"}),n("span",{className:"text-[#555]",children:">"}),n("span",{className:"text-[#ccc] font-medium truncate",children:t||"New Working Session"})]}),u&&d("div",{className:"relative",ref:p,children:[d("button",{onClick:()=>i(b=>!b),className:"flex items-center gap-1.5 text-[#ccc] hover:text-white transition-colors cursor-pointer",children:[n("span",{className:"text-[#555]",children:"::"}),d("span",{children:["Step ",r,d("span",{className:"text-[#888]",children:[" / ",g]}),":"," ",y]}),n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",className:`transition-transform ${o?"rotate-180":""}`,children:n("path",{d:"M2 4l3 3 3-3"})})]}),o&&n("div",{className:"absolute right-0 top-full mt-1 w-48 bg-[#2d2d2d] border border-[#444] rounded-lg shadow-lg z-30 py-1",children:Array.from({length:g},(b,w)=>w+1).map(b=>{const w=b===r,v=b<r,N=l===b,S=f[b];return d("div",{onClick:()=>c(N?null:b),className:"cursor-pointer",children:[d("div",{className:`w-full px-3 py-1 flex items-center gap-2 text-left transition-colors hover:bg-[#383838] ${w?"text-cygreen font-medium":v?"text-[#ccc]":"text-[#999]"}`,children:[d("span",{className:"w-5 text-right tabular-nums shrink-0",children:[b,"."]}),n("span",{className:"flex-1",children:m[b]||`Step ${b}`}),S&&n("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",className:`shrink-0 opacity-40 transition-transform ${N?"rotate-180":""}`,children:n("path",{d:"M2 4l3 3 3-3"})})]}),N&&S&&n("div",{className:"px-3 pb-1.5 pl-10",children:n("p",{className:"text-[10px] text-[#888] m-0 leading-relaxed",children:S})})]},b)})})]})]})}function Ti(e,t){const[r,s]=P(t??null),[a,o]=P(!1),[i,l]=P((t==null?void 0:t.stale)??!1),c=ce(()=>{e&&(o(!0),fetch(`/api/editor-test-results?testFile=${encodeURIComponent(e)}`).then(p=>p.json()).then(p=>{s(p),l(!1),o(!1)}).catch(()=>{s({testFilePath:e,status:"error",testCases:[],errorMessage:"Failed to fetch test results"}),l(!1),o(!1)}))},[e]);return{results:r,isRunning:a,runTests:c,stale:i}}function Qn({scenarioId:e,screenshotPath:t,updatedAt:r,alt:s,className:a="",imgClassName:o=""}){const[i,l]=P(!1),p=`/api/editor-scenario-image/${t?t.replace(/^screenshots\//,""):`${e}.png`}${r?`?v=${encodeURIComponent(r)}`:""}`;return ae(()=>{l(!1)},[e,t]),i?n("div",{className:`flex items-center justify-center ${a}`,children:n("span",{className:"text-[8px] text-gray-500",children:"No img"})}):n("div",{className:a,children:n("img",{src:p,alt:s,className:o,loading:"lazy",onError:()=>l(!0)})})}function sn(e){return e.flatMap(t=>{const r=t.screenshotPaths;return r&&Object.keys(r).length>1?Object.entries(r).map(([s,a])=>({scenario:t,dimensionLabel:s,screenshotPath:a,key:`${t.id}--${s}`})):[{scenario:t,dimensionLabel:null,screenshotPath:t.screenshotPath,key:t.id}]})}function wr({scenarioId:e,screenshotPath:t,updatedAt:r,hasScreenshot:s,imgSrc:a,name:o,dimensionLabel:i,isActive:l,onSelect:c}){const p=e&&s,u=!e&&a;return d("button",{onClick:c,className:"flex flex-col items-center gap-1 cursor-pointer group w-full",title:i?`${o} (${i})`:o,children:[d("div",{className:`w-full aspect-[16/10] rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] relative ${l?"border-[#D7FF63]/40 ring-1 ring-[#D7FF63]/20":"border-transparent hover:border-[#4d4d4d]"}`,children:[p?n(Qn,{scenarioId:e,screenshotPath:t,updatedAt:r,alt:i?`${o} (${i})`:o,className:"w-full h-full",imgClassName:"w-full h-full object-contain"}):u?n("img",{src:a,alt:o,className:"w-full h-full object-contain",loading:"lazy"}):n("div",{className:"w-full h-full bg-[#1a1a1a] flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})}),i&&n("span",{className:"absolute bottom-1 right-1 text-[8px] font-medium bg-black/60 text-white px-1 py-0.5 rounded",children:i})]}),n("span",{className:`text-[10px] leading-tight text-center truncate w-full ${l?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:i?`${o} (${i})`:o})]})}function so({testFile:e,entityName:t,cachedResult:r}){const{results:s,isRunning:a,runTests:o,stale:i}=Ti(e,r);if(a&&!s)return d("div",{className:"px-2 pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!s)return null;if(s.status==="error")return n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-red-400",children:s.errorMessage})});const l=t?s.testCases.filter(u=>u.fullName.startsWith(t)):s.testCases,c=l.length>0?l:s.testCases;if(c.length===0)return null;const p=t?`${t} > `:"";return d("div",{className:"px-2 pt-1 space-y-0.5",children:[c.map(u=>{var m;const h=p&&u.fullName.startsWith(p)?u.fullName.slice(p.length):u.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[u.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):u.status==="failed"?n("span",{className:"text-red-400 text-[10px]",children:"✗"}):n("span",{className:"text-gray-500 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${u.status==="passed"?"text-green-400":u.status==="failed"?"text-red-400":"text-gray-500"}`,children:h})]}),u.status==="failed"&&((m=u.failureMessages)==null?void 0:m.map((f,g)=>n("div",{className:"pl-4 text-[9px] text-red-300/70 truncate max-w-full",title:f,children:f.split(`
596
+ `)[0]},g)))]},u.fullName)}),d("div",{className:"flex items-center gap-2 mt-1",children:[n("button",{onClick:o,disabled:a,className:"text-[10px] text-[#00a0c4] hover:text-[#00c4ee] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:a?"Running...":i?"Re-run (stale)":"Re-run"}),i&&!a&&n("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0",title:"Source or test file changed since last run"})]})]})}function vr({filePath:e}){return e?d("div",{className:"flex items-center gap-1 px-2 mt-0.5",children:[d("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(ct,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function h2({scenarios:e,projectRoot:t,activeScenarioId:r,onScenarioSelect:s,zoomComponent:a,focusedEntity:o,onZoomChange:i,analyzedEntities:l=[],glossaryFunctions:c=[],cachedTestResults:p={},activeAnalyzedScenarioId:u,onAnalyzedScenarioSelect:h,entityImports:m,pageFilePaths:f={},onSwitchToBuild:g,entityShaMap:y,structureTab:x="application",onStructureTabChange:b}){const[w,v]=P(""),[N,S]=P(x),C=b?x:N,A=b||S,{pageGroups:_,componentGroups:E}=ie(()=>{var j;const O=new Map,W=new Map;for(const k of e)if(k.componentName){const Y=W.get(k.componentName)||[];Y.push(k),W.set(k.componentName,Y)}else if(ia(k.url)){const Y=(j=k.url)==null?void 0:j.match(/[?&]c=([^&]+)/),G=Y?decodeURIComponent(Y[1]):"Isolated",Q=W.get(G)||[];Q.push(k),W.set(G,Q)}else{const Y=k.pageFilePath?Ft(_t(k.pageFilePath)):mt(k.url),G=O.get(Y)||[];G.push(k),O.set(Y,G)}const I=new Map([...W.entries()].sort(([k],[Y])=>k.localeCompare(Y)));return{pageGroups:O,componentGroups:I}},[e]),R=ie(()=>{const O=new Set((l||[]).filter(I=>I.entityType==="visual").map(I=>I.name)),W=new Map;for(const[I,j]of E)O.has(I)||W.set(I,j);return W},[E,l]),{visualEntities:D,libraryEntities:T}=ie(()=>{const O=l.filter(I=>I.entityType==="visual").sort((I,j)=>I.name.localeCompare(j.name)),W=l.filter(I=>I.entityType==="library"||I.entityType==="functionCall").sort((I,j)=>I.name.localeCompare(j.name));return{visualEntities:O,libraryEntities:W}},[l]),$=ie(()=>{const O=new Set(T.map(W=>W.name));return c.filter(W=>!O.has(W.name)).sort((W,I)=>W.name.localeCompare(I.name))},[c,T]),L=l.some(O=>O.isAnalyzing),B=fe(null),H=fe(0),q=ce(()=>{B.current&&(H.current=B.current.scrollTop)},[]);if(ae(()=>{B.current&&H.current>0&&(B.current.scrollTop=H.current)}),e.length===0&&l.length===0&&$.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:d("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No scenarios yet"}),n("p",{className:"text-xs",children:"Scenarios will appear here as Claude creates them alongside your code. Each scenario represents a different state of your app's data."})]})});if(a&&o){const O=o.name,W=o.filePath,I=o.sha,j=e.filter(K=>K.componentName===O||K.componentPath===W||!K.componentName&&(K.pageFilePath===W||I&&K.entitySha===I)),k=new Set((m==null?void 0:m[O])||[]),Y=k.size>0,G=Y?D.filter(K=>k.has(K.name)):[],Q=Y?T.filter(K=>k.has(K.name)):[];return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-1",children:[d("button",{onClick:()=>i(void 0),className:"w-full flex items-center gap-2 px-3 py-1.5 text-xs text-gray-400 hover:text-white transition-colors cursor-pointer",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M7.5 9L4.5 6L7.5 3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"All scenarios"]}),n("div",{className:"px-3 py-1.5",children:n("span",{className:"text-xs font-semibold text-white uppercase tracking-wider",children:o.displayName})}),n("div",{className:"flex flex-wrap gap-2 px-2",children:j.length===0?n("div",{className:"px-3 py-2 text-xs text-gray-500",children:"No scenarios for this component"}):sn(j).map(({scenario:K,dimensionLabel:F,screenshotPath:M,key:z})=>n(wr,{scenarioId:K.id,screenshotPath:M,updatedAt:K.updatedAt,hasScreenshot:!!M,name:K.name,dimensionLabel:F,isActive:K.id===r,onSelect:()=>s(K,F??void 0)},z))}),G.length>0&&d("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),G.map(K=>d("div",{className:"mt-2",children:[n("div",{className:"flex items-center gap-2 px-2 py-1",children:n("button",{onClick:()=>i(K.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:K.name})}),n(vr,{filePath:K.filePath,projectRoot:t}),(K.scenarios.length>0||K.pendingScenarios.length>0)&&n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:K.scenarios.map(F=>n(wr,{imgSrc:F.screenshotPath?`/api/screenshot/${F.screenshotPath}`:null,name:F.name,isActive:F.id===u,onSelect:()=>h==null?void 0:h({analysisId:K.analysisId,scenarioId:F.id,scenarioName:F.name,entitySha:K.sha,entityName:K.name})},F.id))})]},K.sha))]}),Q.length>0&&d("div",{className:"pt-2 mt-1",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),Q.map(K=>d("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:K.name})}),n(vr,{filePath:K.filePath,projectRoot:t}),K.testFile&&n(so,{testFile:K.testFile,entityName:K.name,cachedResult:p[K.testFile]})]},K.sha))]})]})})}return n("div",{ref:B,onScroll:q,className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:d("div",{className:"p-4 space-y-4",children:[d("div",{className:"flex items-center gap-3 font-['IBM_Plex_Mono']",children:[n("button",{onClick:()=>A("application"),className:`text-xs font-bold uppercase tracking-wider shrink-0 bg-transparent border-none cursor-pointer p-0 transition-colors ${C==="application"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:"Application"}),n("button",{onClick:()=>A("components"),className:`text-xs font-bold uppercase tracking-wider shrink-0 bg-transparent border-none cursor-pointer p-0 transition-colors ${C==="components"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:"Components"}),n("div",{className:"flex-1"}),d("div",{className:"relative",style:{width:170},children:[d("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"11",cy:"11",r:"8"}),n("path",{d:"M21 21l-4.35-4.35"})]}),n("input",{type:"text",placeholder:"SEARCH...",value:w,onChange:O=>v(O.target.value),className:"w-full pl-9 pr-3 py-2 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded-md text-gray-300 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors tracking-wider"})]}),g&&d("button",{onClick:g,className:"flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer shrink-0 uppercase tracking-wider",children:[n("span",{children:"+"})," New Feature"]})]}),n("div",{className:"border-b border-[#2d2d2d]"}),C==="application"&&_.size>0&&n("div",{children:[..._.entries()].sort(([O],[W])=>O==="Home"?-1:W==="Home"?1:O.localeCompare(W)).filter(([O])=>w.trim()?O.toLowerCase().includes(w.trim().toLowerCase()):!0).map(([O,W])=>{const I=W.some(j=>j.id===r&&!u);return d("div",{className:"mt-3",children:[d("div",{className:"flex items-center gap-1.5 py-1",children:[d("button",{onClick:()=>i(O,y==null?void 0:y.get(O)),className:`flex items-center gap-1.5 text-sm font-normal cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0 ${I?"text-[#D7FF63]":"text-gray-300"}`,children:[O,d("span",{className:`text-xs ${I?"text-[#D7FF63]/60":"text-gray-500"}`,children:["(",W.length,")"]}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:I?"text-[#D7FF63]/60":"text-gray-500",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),I&&d("div",{className:"flex items-center gap-1 ml-auto",children:[n("button",{onClick:()=>i(O,y==null?void 0:y.get(O)),className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Edit scenarios",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),g&&n("button",{onClick:g,className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Add scenario",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]})]}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:sn(W).map(({scenario:j,dimensionLabel:k,screenshotPath:Y,key:G})=>n(wr,{scenarioId:j.id,screenshotPath:Y,updatedAt:j.updatedAt,hasScreenshot:!!Y,name:j.name,dimensionLabel:k,isActive:j.id===r&&!u,onSelect:()=>s(j,k??void 0)},G))})]},O)})}),C==="components"&&R.size>0&&n("div",{children:[...R.entries()].filter(([O])=>w.trim()?O.toLowerCase().includes(w.trim().toLowerCase()):!0).map(([O,W])=>{const I=W.some(j=>j.id===r&&!u);return d("div",{className:"mt-3",children:[d("div",{className:"flex items-center gap-1.5 py-1",children:[d("button",{onClick:()=>i(O,y==null?void 0:y.get(O)),className:`flex items-center gap-1.5 text-sm font-normal cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0 ${I?"text-[#D7FF63]":"text-gray-300"}`,children:[O,d("span",{className:`text-xs ${I?"text-[#D7FF63]/60":"text-gray-500"}`,children:["(",W.length,")"]}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:I?"text-[#D7FF63]/60":"text-gray-500",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),I&&d("div",{className:"flex items-center gap-1 ml-auto",children:[n("button",{onClick:()=>i(O,y==null?void 0:y.get(O)),className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Edit scenarios",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),g&&n("button",{onClick:g,className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Add scenario",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]})]}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:sn(W).map(({scenario:j,dimensionLabel:k,screenshotPath:Y,key:G})=>n(wr,{scenarioId:j.id,screenshotPath:Y,updatedAt:j.updatedAt,hasScreenshot:!!Y,name:j.name,dimensionLabel:k,isActive:j.id===r&&!u,onSelect:()=>s(j,k??void 0)},G))})]},O)})}),D.length>0&&d("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[d("div",{className:"px-2 py-1",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),L&&e.length===0&&l.every(O=>O.scenarioCount===0)&&n("span",{className:"ml-2 text-[10px] text-gray-500",children:"— Entities are being analyzed..."})]}),D.map(O=>d("div",{className:"mt-2",children:[d("div",{className:"flex items-center gap-2 px-2 py-1",children:[n("button",{onClick:()=>i(O.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:O.name}),O.isAnalyzing&&O.scenarioCount===0&&d("span",{className:"flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(vr,{filePath:O.filePath,projectRoot:t}),(O.scenarios.length>0||O.pendingScenarios.length>0)&&d("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:[O.scenarios.map(W=>n(wr,{imgSrc:W.screenshotPath?`/api/screenshot/${W.screenshotPath}`:null,name:W.name,isActive:W.id===u,onSelect:()=>h==null?void 0:h({analysisId:O.analysisId,scenarioId:W.id,scenarioName:W.name,entitySha:O.sha,entityName:O.name})},W.id)),O.pendingScenarios.map(W=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:W,children:W},W))]})]},O.sha))]}),(T.length>0||$.length>0)&&d("div",{className:`pt-2 mt-1 ${D.length>0?"":"border-t border-[#3d3d3d]"}`,children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),T.map(O=>d("div",{className:"mt-2",children:[d("div",{className:"px-2 py-1",children:[n("span",{className:"text-[11px] font-medium text-gray-300",children:O.name}),O.isAnalyzing&&O.scenarioCount===0&&d("span",{className:"ml-2 inline-flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(vr,{filePath:O.filePath,projectRoot:t}),O.testFile?n(so,{testFile:O.testFile,entityName:O.name,cachedResult:p[O.testFile]}):n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},O.sha)),$.map(O=>d("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:O.name})}),n(vr,{filePath:O.filePath,projectRoot:t}),n(so,{testFile:O.testFile,entityName:O.name,cachedResult:p[O.testFile]})]},O.name))]})]})})}function Wu(e){const t={};for(const[r,s]of Object.entries(e))if(typeof s=="string")try{const a=JSON.parse(s);Array.isArray(a)?t[r]=a:typeof a=="object"&&a!==null&&(t[r]=[a])}catch{}else Array.isArray(s)&&(t[r]=s);return t}function Uu(e,t){return e.length===0||t.length===0?!1:e.filter(s=>t.includes(s)).length>=Math.min(e.length,t.length)*.5}function m2(e,t){const{_metadata:r,...s}=t,a=s.localStorage&&typeof s.localStorage=="object"&&!Array.isArray(s.localStorage)?Wu(s.localStorage):{},o={};if(s.seed&&typeof s.seed=="object"&&!Array.isArray(s.seed))for(const[h,m]of Object.entries(s.seed))Array.isArray(m)&&(o[h]=m);const i={},l=[],c=new Set,p=new Set,u=new Set;for(const h of e){const m=h.fields.filter(b=>!b.isRelation),f=m.map(b=>b.name),g=h.name.charAt(0).toLowerCase()+h.name.slice(1);let y=null,x=[];for(const b of[h.name,g,`${g}s`])if(b in s&&Array.isArray(s[b])){y=b,x=s[b],p.add(b);break}if(!y){for(const b of[h.name,g,`${g}s`])if(b in o){y=b,x=o[b],u.add(b),b in a&&c.add(b);break}}if(!y){for(const b of[h.name,g,`${g}s`])if(b in a){y=g,x=a[b],c.add(b);break}}if(!y){for(const[b,w]of Object.entries(a))if(!c.has(b)&&w.length>0&&Uu(f,Object.keys(w[0]))){y=g,x=w,c.add(b);break}}y||(y=g),i[y]=x,l.push({label:h.name,dataKey:y,schemaFields:m.map(b=>({name:b.name,type:b.type,isId:b.isId}))})}for(const[h,m]of Object.entries(s))h==="_metadata"||h==="localStorage"||h==="seed"||h==="type"||p.has(h)||Array.isArray(m)&&(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(o))u.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(a))c.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));return{data:i,tabs:l}}function f2(e){return e==null?"null":typeof e=="number"?Number.isInteger(e)?"int4":"float":typeof e=="boolean"?"bool":typeof e=="object"?Array.isArray(e)?"array":"json":"text"}function g2(e,t){return e.length>0?Object.keys(e[0]):t?t.map(r=>r.name):[]}function y2(e,t,r){const s=new Map((r||[]).map(o=>[o.name,o.type])),a={};for(const o of e)a[o]=s.get(o)||(t.length>0?f2(t[0][o]):"text");return a}function x2(e,t){var r;return((r=t==null?void 0:t.find(s=>s.isId))==null?void 0:r.name)||e.find(s=>s==="id")||null}function b2(e,t){const{_metadata:r,...s}=t,a=s.localStorage&&typeof s.localStorage=="object"&&!Array.isArray(s.localStorage)?Wu(s.localStorage):{},o={};if(s.seed&&typeof s.seed=="object"&&!Array.isArray(s.seed))for(const[h,m]of Object.entries(s.seed))Array.isArray(m)&&(o[h]=m);const i={},l=[],c=new Set,p=new Set,u=new Set;for(const h of e){const m=h.name.charAt(0).toLowerCase()+h.name.slice(1),f=h.fields.map(x=>x.name);let g=null,y=[];for(const x of[h.name,m,`${m}s`])if(x in s&&Array.isArray(s[x])){g=x,y=s[x],p.add(x);break}if(!g){for(const x of[h.name,m,`${m}s`])if(x in o){g=x,y=o[x],u.add(x),x in a&&c.add(x);break}}if(!g){for(const x of[h.name,m,`${m}s`])if(x in a){g=m,y=a[x],c.add(x);break}}if(!g){for(const[x,b]of Object.entries(a))if(!c.has(x)&&b.length>0&&Uu(f,Object.keys(b[0]))){g=m,y=b,c.add(x);break}}g||(g=m),i[g]=y,l.push({label:h.name,dataKey:g,category:h.category,description:h.description,schemaFields:h.fields.map(x=>({name:x.name,type:x.type,isId:x.isId??!1}))})}for(const[h,m]of Object.entries(s))h==="_metadata"||h==="localStorage"||h==="seed"||h==="type"||p.has(h)||Array.isArray(m)&&(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(o))u.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(a))c.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));return{data:i,tabs:l}}function Mi(e){var a,o;const t=new Map,r=new Map;for(const i of e)if(i.componentName){const l=r.get(i.componentName)||[];l.push(i),r.set(i.componentName,l)}else if(ia(i.url)){const l=(a=i.url)==null?void 0:a.match(/[?&]c=([^&]+)/),c=l?decodeURIComponent(l[1]):"Isolated",p=r.get(c)||[];p.push(i),r.set(c,p)}else{const l=i.displayName||((o=i.pageFilePath)!=null&&o.startsWith("app/")?Ft(_t(i.pageFilePath)):mt(i.url)),c=t.get(l)||[];c.push(i),t.set(l,c)}const s=new Map([...r.entries()].sort(([i],[l])=>i.localeCompare(l)));return{pageGroups:t,componentGroups:s}}function Ju(e,t){var s,a;const r=new Map;for(const[o,i]of e){const l=(s=i.find(c=>c.entitySha))==null?void 0:s.entitySha;l&&r.set(o,l)}for(const[o,i]of t){const l=(a=i.find(c=>c.entitySha))==null?void 0:a.entitySha;l&&r.set(o,l)}return r}function w2(e){const t=new Set;for(const[r,s]of Object.entries(e)){t.add(r);for(const a of s)t.add(a)}return t}function v2(e,t,r,s){if(t.has(e))return!0;const a=r.find(o=>o.sha===e);return a?s.has(a.name):!1}function N2(e,t,r,s){const a=[];for(const[o,i]of e){const l=r.get(o);l?s(l)||a.push({name:o,scenarios:i,reason:"incomplete"}):a.push({name:o,scenarios:i,reason:"missing"})}for(const[o,i]of t){const l=r.get(o);l?s(l)||a.push({name:o,scenarios:i,reason:"incomplete"}):a.push({name:o,scenarios:i,reason:"missing"})}return a}function fc(e,t,r){if(!e)return null;const s=t.find(a=>a.sha===e);return s?{sha:e,name:s.name,filePath:s.filePath,entityType:s.entityType,displayName:s.name}:null}const gc=120;function Hu({text:e,theme:t}){const[r,s]=P(!1),a=e.length>gc,o=a&&!r?e.slice(0,gc)+"…":e,i=t==="light";return d("div",{className:`px-4 py-2 ${i?"border-b border-gray-200 bg-gray-50":"border-b border-[#3d3d3d] bg-[#252525]"}`,children:[n("span",{className:"text-[9px] font-semibold uppercase tracking-wider text-gray-500",children:"User Prompt"}),d("p",{className:`text-[11px] mt-0.5 mb-0 leading-relaxed ${i?"text-gray-600":"text-gray-400"}`,children:[o,a&&n("button",{onClick:()=>s(!r),className:`ml-1 text-[11px] font-medium bg-transparent border-none p-0 cursor-pointer ${i?"text-blue-500 hover:text-blue-700":"text-[#00a0c4] hover:text-[#00c0e8]"}`,children:r?"Show less":"Read more…"})]})]})}const yc={new:0,edited:1,impacted:2};function xc({status:e,onClick:t}){const r={new:{label:"New",bg:"bg-green-100",text:"text-green-700",border:"border-green-200"},edited:{label:"Edited",bg:"bg-blue-100",text:"text-blue-700",border:"border-blue-200"},impacted:{label:"Impacted",bg:"bg-amber-100",text:"text-amber-700",border:"border-amber-200"}}[e.status],s=t&&(e.status==="edited"||e.status==="impacted");return n("button",{onClick:s?t:void 0,className:`${r.bg} ${r.text} ${r.border} border text-[9px] font-bold px-1.5 py-0.5 rounded-full uppercase tracking-wider shrink-0 ${s?"cursor-pointer hover:opacity-80 transition-opacity":"cursor-default"}`,children:r.label})}function bc({filePath:e}){const[t,r]=P(null),[s,a]=P(!0),[o,i]=P(null);return ae(()=>{import("react-diff-viewer-continued").then(l=>{i(()=>l.default)})},[]),ae(()=>{a(!0),fetch(`/api/editor-file-diff?path=${encodeURIComponent(e)}`).then(l=>l.json()).then(l=>{r({oldContent:l.oldContent,newContent:l.newContent})}).catch(()=>{r(null)}).finally(()=>a(!1))},[e]),s?n("div",{className:"p-2 text-[10px] text-gray-400",children:"Loading diff..."}):!t||!o?n("div",{className:"p-2 text-[10px] text-gray-400",children:"Could not load diff"}):n("div",{className:"mt-2 border border-gray-200 rounded-lg overflow-hidden max-h-[300px] overflow-auto text-xs",children:n(o,{oldValue:t.oldContent,newValue:t.newContent,splitView:!1,useDarkTheme:!1,showDiffOnly:!0,styles:{contentText:{fontSize:"11px",lineHeight:"1.4"},line:{padding:"1px 8px",fontSize:"11px"}}})})}function wc({impactedBy:e,changedEntities:t}){return n("div",{className:"mt-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5",children:e&&e.length>0?d(we,{children:[n("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"Re-captured because these dependencies changed"}),n("ul",{className:"mt-1.5 space-y-1",children:e.map(r=>d("li",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold px-1 py-0 rounded-full uppercase tracking-wider border ${r.changeType==="new"?"bg-green-100 text-green-700 border-green-200":"bg-blue-100 text-blue-700 border-blue-200"}`,children:r.changeType==="new"?"New":"Edited"}),n("span",{className:"text-[11px] font-medium text-amber-800",children:r.name}),n("span",{className:"text-[9px] text-amber-500 truncate",children:r.filePath})]},r.filePath))})]}):t&&t.length>0?d(we,{children:[n("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"Unchanged — these entities were modified in this session"}),n("ul",{className:"mt-1.5 space-y-1",children:t.map(r=>d("li",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold px-1 py-0 rounded-full uppercase tracking-wider border ${r.status==="new"?"bg-green-100 text-green-700 border-green-200":"bg-blue-100 text-blue-700 border-blue-200"}`,children:r.status==="new"?"New":"Edited"}),n("span",{className:"text-[11px] font-medium text-amber-800",children:r.name})]},r.name))})]}):n("span",{className:"text-[10px] text-amber-600",children:"This component was re-captured because a dependency changed"})})}function vc({scenarioId:e,screenshotPath:t,name:r,dimensionLabel:s,isActive:a,onSelect:o,updatedAt:i}){const l=fe(null);return ae(()=>{a&&l.current&&l.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[a]),d("button",{ref:l,onClick:o,className:"flex flex-col items-center gap-1.5 cursor-pointer group",title:s?`${r} (${s})`:r,children:[d("div",{className:`w-32 h-32 rounded-lg overflow-hidden border-2 transition-all relative ${a?"border-[#0ea5e9] ring-2 ring-[#0ea5e9]/40 shadow-lg shadow-[#0ea5e9]/20":"border-gray-200 hover:border-gray-400 shadow-sm"}`,children:[n(Qn,{scenarioId:e,screenshotPath:t,updatedAt:i,alt:s?`${r} (${s})`:r,className:"w-full h-full bg-white",imgClassName:"w-full h-full object-contain bg-white"}),s&&n("span",{className:"absolute bottom-1 right-1 text-[9px] font-medium bg-black/60 text-white px-1.5 py-0.5 rounded",children:s})]}),n("span",{className:`text-[11px] leading-tight text-center truncate w-32 font-medium ${a?"text-gray-900":"text-gray-600 group-hover:text-gray-900"}`,children:s?`${r} (${s})`:r})]})}function S2({filePath:e}){return e?d("div",{className:"flex items-center gap-1 mt-0.5",children:[d("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-400 hover:text-gray-600 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(ct,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-400 hover:text-gray-600 transition-colors"})]}):null}function _o({testFile:e,entityName:t,cachedResult:r}){const{results:s,isRunning:a,runTests:o,stale:i}=Ti(e,r);if(a&&!s)return d("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#0ea5e9] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!s)return null;if(s.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-500",children:s.errorMessage})});const l=t?s.testCases.filter(u=>u.fullName.startsWith(t)):s.testCases,c=l.length>0?l:s.testCases;if(c.length===0)return null;const p=t?`${t} > `:"";return d("div",{className:"pt-1 space-y-0.5",children:[c.map(u=>{var m;const h=p&&u.fullName.startsWith(p)?u.fullName.slice(p.length):u.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[u.status==="passed"?n("span",{className:"text-green-600 text-[10px]",children:"✓"}):u.status==="failed"?n("span",{className:"text-red-500 text-[10px]",children:"✗"}):n("span",{className:"text-gray-400 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${u.status==="passed"?"text-green-600":u.status==="failed"?"text-red-500":"text-gray-400"}`,children:h})]}),u.status==="failed"&&((m=u.failureMessages)==null?void 0:m.map((f,g)=>n("div",{className:"pl-4 text-[9px] text-red-400 truncate max-w-full",title:f,children:f.split(`
597
+ `)[0]},g)))]},u.fullName)}),d("div",{className:"flex items-center gap-2 mt-1",children:[n("button",{onClick:o,disabled:a,className:"text-[10px] text-[#0ea5e9] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:a?"Running...":i?"Re-run (stale)":"Re-run"}),i&&!a&&n("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0",title:"Source or test file changed since last run"})]})]})}function Nc(e){const t=e.indexOf(" - ");return t!==-1?e.slice(t+3):e}function Sc(e,t){return!t||Object.keys(t).length===0?e:[...e].sort(([r],[s])=>{var l,c;const a=((l=t[r])==null?void 0:l.status)||"impacted",o=((c=t[s])==null?void 0:c.status)||"impacted",i=(yc[a]??2)-(yc[o]??2);return i!==0?i:r.localeCompare(s)})}function C2({scenarios:e,allScenarios:t=[],glossaryFunctions:r=[],cachedTestResults:s={},projectRoot:a,activeScenarioId:o,onScenarioSelect:i,onClose:l,entityChangeStatus:c={},modifiedFiles:p=[],featureName:u,userPrompt:h}){const m=ie(()=>{if(t.length===0||Object.keys(c).length===0)return e;const R=new Set(e.map(T=>T.id)),D=t.filter(T=>{var L,B;if(R.has(T.id))return!1;const $=T.componentName||T.displayName||((L=T.pageFilePath)!=null&&L.startsWith("app/")?Ft(_t(T.pageFilePath)):mt(T.url));return((B=c[$])==null?void 0:B.status)==="impacted"});return D.length===0?e:[...e,...D]},[e,t,c]),f=ie(()=>Object.entries(c).filter(([,R])=>R.status==="new"||R.status==="edited").map(([R,D])=>({name:R,status:D.status})),[c]),[g,y]=P(null),x=ce(R=>{y(D=>D===R?null:R)},[]),{pageGroups:b,componentGroups:w}=ie(()=>Mi(m),[m]),v=ie(()=>Sc([...b.entries()],c),[b,c]),N=ie(()=>Sc([...w.entries()],c),[w,c]),S=v,C=N,A=ie(()=>d0(r,c),[r,c]),_=ie(()=>{const R=[];for(const[,D]of S)R.push(...D);for(const[,D]of C)R.push(...D);return R},[S,C]),E=fe(!1);return ae(()=>{E.current||_.length!==0&&(E.current=!0,console.log("[ResultsPanel] Auto-selecting first scenario: %s",_[0].name),i(_[0]))},[_,i]),ae(()=>{if(_.length===0)return;const R=D=>{if(D.key!=="ArrowLeft"&&D.key!=="ArrowRight")return;const T=D.target,$=T==null?void 0:T.tagName;if($==="INPUT"||$==="SELECT"||$==="TEXTAREA"&&!T.classList.contains("xterm-helper-textarea"))return;D.preventDefault();const L=_.findIndex(H=>H.id===o);let B;D.key==="ArrowLeft"?B=L<=0?_.length-1:L-1:B=L>=_.length-1?0:L+1,i(_[B])};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[_,o,i]),m.length===0&&r.length===0?d("div",{className:"h-full bg-white flex items-center justify-center relative",children:[n("button",{onClick:l,className:"absolute top-2 right-3 text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none",title:"Close results",children:"×"}),n("span",{className:"text-sm text-gray-400",children:"No scenarios registered yet"})]}):d("div",{className:"h-full bg-white flex flex-col overflow-hidden",children:[d("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-gray-200 shrink-0",children:[d("div",{className:"min-w-0",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Working Session Results"}),u&&n("div",{className:"text-[11px] text-gray-400 truncate",title:u,children:u})]}),n("button",{onClick:l,className:"text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none shrink-0",title:"Close results",children:"×"})]}),h&&n(Hu,{text:h,theme:"light"}),n("div",{className:"flex-1 overflow-auto p-4",children:d("div",{className:"space-y-5",children:[S.length>0&&d("div",{children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"})}),n("div",{className:"space-y-3 pl-1",children:S.map(([R,D])=>{var B;const T=c[R],$=g===R,L=(B=D[0])==null?void 0:B.componentPath;return d("div",{children:[d("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:R}),T&&n(xc,{status:T,onClick:()=>x(R)})]}),$&&(T==null?void 0:T.status)==="edited"&&L&&n(bc,{filePath:L}),$&&(T==null?void 0:T.status)==="impacted"&&n(wc,{impactedBy:T.impactedBy,changedEntities:f}),n("div",{className:"flex flex-wrap gap-3",children:sn(D).map(({scenario:H,dimensionLabel:q,screenshotPath:O,key:W})=>n(vc,{scenarioId:H.id,screenshotPath:O,name:Nc(H.name),dimensionLabel:q,isActive:H.id===o,onSelect:()=>i(H,q??void 0),updatedAt:H.updatedAt},W))})]},R)})})]}),C.length>0&&d("div",{className:S.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),n("div",{className:"space-y-3 pl-1",children:C.map(([R,D])=>{var B;const T=c[R],$=g===R,L=(B=D[0])==null?void 0:B.componentPath;return d("div",{children:[d("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:R}),T&&n(xc,{status:T,onClick:()=>x(R)})]}),$&&(T==null?void 0:T.status)==="edited"&&L&&n(bc,{filePath:L}),$&&(T==null?void 0:T.status)==="impacted"&&n(wc,{impactedBy:T.impactedBy,changedEntities:f}),n("div",{className:"flex flex-wrap gap-3",children:sn(D).map(({scenario:H,dimensionLabel:q,screenshotPath:O,key:W})=>n(vc,{scenarioId:H.id,screenshotPath:O,name:Nc(H.name),dimensionLabel:q,isActive:H.id===o,onSelect:()=>i(H,q??void 0),updatedAt:H.updatedAt},W))})]},R)})})]}),A.length>0&&d("div",{className:S.length>0||C.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),n("div",{className:"space-y-2 pl-1",children:A.map(R=>d("div",{children:[n("div",{className:"flex items-center gap-2",children:n("span",{className:"text-[11px] font-medium text-gray-700",children:R.name})}),n(S2,{filePath:R.filePath,projectRoot:a}),R.testFile?n(_o,{testFile:R.testFile,entityName:R.name,cachedResult:s[R.testFile]}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-400",children:"No test file"})})]},R.name))})]}),p.length>0&&d("div",{className:S.length>0||C.length>0||A.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:d("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:["Modified Files (",p.length,")"]})}),n("div",{className:"space-y-0.5 pl-1 max-h-[200px] overflow-auto",children:p.map(R=>d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold uppercase w-[14px] text-center ${R.status==="added"||R.status==="untracked"?"text-green-600":R.status==="modified"?"text-blue-600":R.status==="renamed"?"text-purple-600":"text-gray-400"}`,children:R.status==="added"||R.status==="untracked"?"A":R.status==="modified"?"M":R.status==="renamed"?"R":"?"}),n("span",{className:"text-[10px] text-gray-500 truncate font-mono",children:R.path})]},R.path))})]})]})})]})}function Cc(e,t,r,s){var c;const a=s.length>0?s.map(p=>`- "${p.name}" (ID: ${p.id})${p.url?` — URL: ${p.url}`:""}`).join(`
598
+ `):"(no scenarios yet)",o=t.endsWith("/page.tsx")||t.endsWith("/page.js"),i=((c=s.find(p=>p.url))==null?void 0:c.url)||"/",l=[`You are helping edit scenarios for the "${e}" entity in a CodeYam project.`,"","## Entity",`- **Name:** ${e}`,`- **File:** ${t}`,`- **Type:** ${o?"Page (application scenario with seed data)":"Component (component scenario with mock props)"}`,"","## Existing Scenarios",a,""];return o?l.push("## How Seed Data Works","","Application scenarios use `seed` data to populate the database before the page is captured.","The seed is a JSON object where each key is a Prisma model name in camelCase singular (matching the Prisma client accessor name) and the value is an array of records.","","### Seed Key Naming Convention","The key must be the camelCase singular form of the Prisma model name:",'- `model User` → key `"user"`','- `model BlogPost` → key `"blogPost"`','- `model Feedback` → key `"feedback"`',"",'**WARNING:** Do NOT use plural forms like "users", "blogPosts", or "feedbacks" — the seed adapter will silently fail to match them.',"","To understand the data models, read the Prisma schema at `prisma/schema.prisma`.","To see examples of existing seed data, look at `.codeyam/editor-scenarios/*.seed.json` files.","",`Also read the source file at \`${t}\` to understand what data the page queries and renders.`,"","## Registering a Scenario","","For small seed data, pass it inline:","```",`codeyam editor register '{"name":"Scenario Name","type":"application","url":"${i}","dimensions":["Laptop"],"seed":{"user":[...],"feedback":[...]}}'`,"```","","For large seed data, write it to a temp file and use @file syntax:","```","# Write JSON to a temp file","cat > .codeyam/tmp/scenario.json << 'SCENARIO_EOF'",`{"name":"Scenario Name","type":"application","url":"${i}","dimensions":["Laptop"],"seed":{"user":[...],"feedback":[...]}}`,"SCENARIO_EOF","codeyam editor register @.codeyam/tmp/scenario.json","```"):l.push("## Registering a Scenario","",`Read the source file at \`${t}\` to understand what props the component expects.`,"","```",`codeyam editor register '{"name":"Scenario Name","type":"component","componentName":"${e}","componentPath":"${t}","dimensions":["Laptop"],"mockData":{"propName":"value"}}'`,"```"),l.push("","## Deleting a Scenario","","To delete a scenario, use its ID from the list above:","```","codeyam editor delete <scenarioId>","```","","## Validating Seed Data","","Before registering, you can validate seed data structure and check that keys match Prisma models:","```",`codeyam editor validate-seed '{"user":[...]}'`,"```"),l.push("","## Recapturing Scenarios After Code Changes","",`If the user asks you to modify the code for this ${o?"page":"component"} (CSS, layout, logic, etc.), you MUST re-register all existing scenarios after the code change so their screenshots are updated.`,"","Re-registering a scenario with the same name overwrites it and captures a fresh screenshot.","","To recapture, re-register each existing scenario using `codeyam editor register` with its current configuration. You can read the scenario JSON files in `.codeyam/editor-scenarios/` to get the exact registration data for each scenario."),l.push("","## Important","- DO NOT take any action until the user tells you what they want","- Start by briefly listing the existing scenarios",'- Then ask: "Would you like to modify an existing scenario or add a new one?"',"- Wait for the user's answer before proceeding",'- Keep scenario names descriptive: "Empty State", "With Comments", "Admin View", etc.',`- Each scenario should capture a distinct, meaningful state of the ${o?"page":"component"}`),l.join(`
599
+ `)}function Vu(e,t){var a;const r=t.some(o=>!o.componentName),s=t.map(o=>`'${o.id}'`).join(", ");if(r){const o=((a=t.find(l=>l.url))==null?void 0:a.url)||null,i=t.map(l=>`.codeyam/editor-scenarios/${l.id}.json`).join(", ");return[`### Page: "${e}" (${t.length} scenario(s))`,...o?["",`Scenario URL: \`${o}\``]:[],"",...o?["Step A: Find the source file that renders this page. In Next.js App Router, URLs map to page.tsx files:"," - `/` → `app/page.tsx`"," - `/about` → `app/about/page.tsx`"," - `/c/my-slug` → `app/c/[slug]/page.tsx` (dynamic segment)","",`Based on the URL \`${o}\`, find the corresponding page.tsx file. Confirm it exists with \`cat <filepath> | head -5\`.`]:["Step A: Find the source file that renders this page by running:",' find src app -name "App.tsx" -o -name "App.jsx" -o -name "page.tsx" -o -name "page.jsx" -o -name "index.tsx" 2>/dev/null',"","Pick the file that is the main app entry point or the page component for this route. Confirm it exists with `cat <filepath> | head -5`."],"","Step B: Set page_file_path on all scenarios for this page (replace PAGE_FILE_PATH with the path from Step A):",` sqlite3 .codeyam/db.sqlite3 "UPDATE editor_scenarios SET page_file_path = 'PAGE_FILE_PATH' WHERE id IN (${s});"`,"","Step C: Get the entity SHA (after running analyze-imports in the shared step above):",` sqlite3 .codeyam/db.sqlite3 "SELECT sha FROM entities WHERE file_path = 'PAGE_FILE_PATH' ORDER BY created_at DESC LIMIT 1;"`,"","If no rows appear, the path was wrong — go back to Step A.","","Step D: Set entity_sha and display_name on all scenarios (replace ENTITY_SHA with the SHA from Step C):",` sqlite3 .codeyam/db.sqlite3 "UPDATE editor_scenarios SET entity_sha = 'ENTITY_SHA', display_name = '${e}' WHERE id IN (${s});"`,"","Step E: Add pageFilePath to the scenario JSON files so this fix persists across clones.",`For each file (${i}), read it and add \`"pageFilePath": "PAGE_FILE_PATH"\` to the \`_metadata\` object (after the \`"type"\` field). Then commit the updated JSON files.`].join(`
600
+ `)}else return[`### Component: "${e}" (${t.length} scenario(s))`,"","Step A: Get the entity SHA (after running analyze-imports in the shared step above):",` sqlite3 .codeyam/db.sqlite3 "SELECT sha FROM entities WHERE name = '${e}' ORDER BY created_at DESC LIMIT 1;"`,"","If no rows appear, check that .codeyam/glossary.json contains an entry for this component.","","Step B: Set entity_sha and display_name on all scenarios (replace ENTITY_SHA with the SHA from Step A):",` sqlite3 .codeyam/db.sqlite3 "UPDATE editor_scenarios SET entity_sha = 'ENTITY_SHA', display_name = '${e}' WHERE id IN (${s});"`].join(`
601
+ `)}function As({scenarioId:e,screenshotPath:t,updatedAt:r,hasScreenshot:s,imgSrc:a,name:o,dimensionLabel:i,isActive:l,onSelect:c}){const p=e&&s,u=!e&&a;return d("button",{onClick:c,className:"flex flex-col items-center gap-1 cursor-pointer group w-full",title:i?`${o} (${i})`:o,children:[d("div",{className:`w-full aspect-[16/10] rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] relative ${l?"border-[#D7FF63]/40 ring-1 ring-[#D7FF63]/20":"border-transparent hover:border-[#4d4d4d]"}`,children:[p?n(Qn,{scenarioId:e,screenshotPath:t,updatedAt:r,alt:i?`${o} (${i})`:o,className:"w-full h-full",imgClassName:"w-full h-full object-contain"}):u?n("img",{src:a,alt:o,className:"w-full h-full object-contain",loading:"lazy"}):n("div",{className:"w-full h-full bg-[#1a1a1a] flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})}),i&&n("span",{className:"absolute bottom-1 right-1 text-[8px] font-medium bg-black/60 text-white px-1 py-0.5 rounded",children:i})]}),n("span",{className:`text-[10px] leading-tight text-center truncate w-full ${l?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:i?`${o} (${i})`:o})]})}function Ns({filePath:e}){return e?d("div",{className:"flex items-center gap-1.5 mt-0.5",children:[d("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1.5 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-sm truncate font-['IBM_Plex_Mono']",children:e}),n("svg",{className:"shrink-0",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(ct,{content:e,icon:!0,iconSize:12,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function Gu({name:e,scenarios:t,reason:r="missing"}){var o,i;const s=((o=t[0])==null?void 0:o.componentPath)||((i=t[0])==null?void 0:i.pageFilePath)||null,a=r==="incomplete"?[`The "${e}" entity exists but has not been fully analyzed — its components and functions cannot be displayed.`,"","Follow these steps:","",`Step 1: Check if "${e}" is in the glossary:`,` cat .codeyam/glossary.json | grep "${e}"`,"","If not found, add an entry to .codeyam/glossary.json:",` { "name": "${e}", "filePath": "${s||"FILL_IN_PATH"}", "description": "...", "returnType": "JSX.Element" }`,"","Step 2: Run: codeyam editor analyze-imports","","Step 3: Reload the editor page and verify components/functions appear."].join(`
602
+ `):[`The "${e}" ${t.some(l=>!l.componentName)?"page":"component"} is missing entity data in the CodeYam database. Its scenarios are hidden until this is fixed.`,"","IMPORTANT: Do NOT re-register scenarios — that would overwrite their screenshots. Instead, update the database and scenario JSON files directly.","","Follow these steps EXACTLY:","","Step 1: Run: codeyam editor analyze-imports","","Step 2: Fix this entity:","",Vu(e,t),"","Step 3: Reload the editor page in the browser and verify the scenarios appear."].join(`
603
+ `);return n(ct,{content:a,label:"Copy Fix Prompt",copiedLabel:"Copied!",className:"text-[10px] text-[#E0D400] hover:text-[#E0D400]/80 bg-transparent border border-[#E0D400]/30 rounded px-2 py-0.5 cursor-pointer transition-colors ml-2"})}function k2({brokenEntities:e}){const[t,r]=P(!1),s=ce(c=>{navigator.clipboard.writeText(c).then(()=>{r(!0),setTimeout(()=>r(!1),2e3)})},[]);if(e.length===0)return null;const a=e.reduce((c,p)=>c+p.scenarios.length,0),o=e.filter(c=>c.reason==="incomplete"),i=e.filter(c=>c.reason==="missing"),l=[`${e.length} entities are missing data in the CodeYam database. ${a} total scenario(s) are hidden until this is fixed.`,"","IMPORTANT: Do NOT re-register scenarios — that would overwrite their screenshots. Instead, update the database and scenario JSON files directly.","","Follow these steps EXACTLY:","",...o.length>0?["## Step 1: Add missing entries to the glossary","","Read `.codeyam/glossary.json` and check if these entities have entries. For each one that is missing, add an entry:","",...o.map(c=>{var u,h;const p=((u=c.scenarios[0])==null?void 0:u.componentPath)||((h=c.scenarios[0])==null?void 0:h.pageFilePath)||"FILL_IN_PATH";return`- "${c.name}" (filePath: "${p}")`}),"",'Each glossary entry needs: name, filePath, description, returnType (use "JSX.Element" for components/pages).',""]:["## Step 1: No glossary changes needed",""],"## Step 2: Run import analysis"," codeyam editor analyze-imports","",...i.length>0?["## Step 3: Fix missing entity associations","",...i.map(c=>Vu(c.name,c.scenarios)),""]:[],`## Step ${i.length>0?"4":"3"}: Reload the editor page in the browser and verify all scenarios appear. Then commit the updated scenario JSON files so the fix persists across clones.`].join(`
604
+ `);return n("div",{className:"p-4 rounded-lg border border-[#E0D400]/40 bg-[#E0D400]/8",children:d("div",{className:"flex items-center gap-3",children:[d("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#E0D400",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),d("p",{className:"flex-1 min-w-0 text-sm text-[#E0D400]/90 m-0 leading-snug font-['IBM_Plex_Sans']",children:[e.length," ",e.length===1?"entity is":"entities are"," missing data, resulting in ",a," hidden scenario",a!==1?"s":"","."," ",n("button",{type:"button",className:"font-bold underline bg-transparent border-none text-[#E0D400] cursor-pointer p-0 text-sm inline hover:text-[#E0D400]/70 transition-colors",onClick:()=>s(l),children:t?d("span",{className:"inline-flex items-center gap-1",children:["Copied",n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"inline",children:n("polyline",{points:"20 6 9 17 4 12"})})]}):"Copy this prompt"})," ","into Claude to fix them all at once."]}),n(ct,{content:l,label:d("span",{className:"flex items-center gap-2",children:["COPY PROMPT",d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]}),copiedLabel:d("span",{className:"flex items-center gap-2",children:[n("span",{className:"invisible",children:"COPY PROMPT"}),n("span",{className:"absolute inset-0 flex items-center justify-center",children:"COPIED!"}),n("span",{className:"invisible",children:n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",children:n("rect",{x:"9",y:"9",width:"13",height:"13"})})})]}),className:"relative text-xs font-semibold text-[#1e1e1e] bg-[#E0D400] hover:bg-[#E0D400]/80 border-none rounded px-4 py-2 cursor-pointer transition-colors shrink-0 tracking-wide font-['IBM_Plex_Mono']"})]})})}function Ku({focusedEntity:e,breadcrumbItems:t,onZoomChange:r,projectRoot:s,scenarios:a,analyzedEntities:o,activeScenarioId:i,onScenarioSelect:l,onAnalyzedScenarioSelect:c,onSwitchToBuild:p,entityImports:u,glossaryFunctions:h,cachedTestResults:m={},glossaryEntries:f,entityShaMap:g,componentGroups:y,visualEntities:x,isEntityComplete:b,onReseedPreview:w}){var Re;const v=e.filePath,N=e.name,[S,C]=P("scenarios"),[A,_]=P(null),[E,R]=P(""),[D,T]=P(!1),[$,L]=P(null),[B,H]=P(!1),[q,O]=P(!1),[W,I]=P(null);ae(()=>{C("scenarios"),_(null),H(!1),O(!1),I(null)},[e.sha]);const j=ie(()=>{const X=new Map;for(const ye of h)X.set(ye.name,ye);return X},[h]),k=o.some(X=>X.sha===e.sha||X.filePath===v),Y=!!((Re=u==null?void 0:u[N])!=null&&Re.length),G=ce(async X=>{if(!(!E.trim()||D)){T(!0);try{(await fetch("/api/editor-rename-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:X,name:E.trim()})})).ok&&_(null)}catch{}finally{T(!1)}}},[E,D]),Q=ce(async X=>{if(confirm(`Delete scenario "${X.name}"?`)){L(X.id);try{const ye=X.screenshotPaths?Object.values(X.screenshotPaths):X.screenshotPath?[X.screenshotPath]:[];await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:X.id,screenshotPaths:ye})})}catch{}finally{L(null)}}},[]);if(!k&&!Y){const X=a.filter(ee=>ee.entitySha===e.sha),ye=[`The "${e.displayName}" entity (${v}) exists in the database but has not been fully analyzed. Its components and functions cannot be shown until it has import metadata.`,"","Follow these steps:","",`Step 1: Add "${N}" to the glossary if it's not already there:`,` Check: cat .codeyam/glossary.json | grep "${N}"`,"",` If not found, add an entry with name "${N}" and filePath "${v}" to .codeyam/glossary.json`,"","Step 2: Run import analysis:"," codeyam editor analyze-imports","","Step 3: Reload the editor page and verify components/functions appear."].join(`
605
+ `);return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-4 space-y-3",children:[d("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>{if(t.length>1){const ee=t[t.length-2];r(ee.componentName,ee.entitySha)}else r()},className:"text-gray-400 hover:text-white transition-colors cursor-pointer bg-transparent border-none p-0 shrink-0 text-lg",title:"Go back",children:"←"}),n("h2",{className:"text-lg font-medium text-white m-0 font-['IBM_Plex_Sans']",children:e.displayName})]}),v&&n(Ns,{filePath:v,projectRoot:s}),d("div",{className:"py-2",children:[n("p",{className:"text-[11px] text-amber-400/80 m-0 leading-relaxed",children:"This entity has not been fully analyzed. Its components and functions cannot be displayed. Please copy and paste this prompt into Claude to fix the data."}),n("div",{className:"mt-2",children:n(ct,{content:ye,label:"Copy Fix Prompt",copiedLabel:"Copied!",className:"text-[10px] text-amber-400 hover:text-amber-300 bg-transparent border border-amber-400/30 rounded px-2 py-1 cursor-pointer transition-colors"})})]}),X.length>0&&n("div",{className:"grid grid-cols-3 gap-2",children:sn(X).map(({scenario:ee,dimensionLabel:ne,screenshotPath:xe,key:Me})=>n(As,{scenarioId:ee.id,screenshotPath:xe,updatedAt:ee.updatedAt,hasScreenshot:!!xe,name:ee.name,dimensionLabel:ne,isActive:ee.id===i,onSelect:()=>l(ee,ne??void 0)},Me))})]})})}const K=e.sha,F=a.filter(X=>!X.componentName&&(X.pageFilePath===v||K&&X.entitySha===K)),M=a.filter(X=>X.componentName===N||X.componentPath===v),z=x.find(X=>X.filePath===v||X.name===N),J=j.get(N)||h.find(X=>X.filePath===v),te=[...F,...M],oe=ie(()=>{const X=[];if(X.push(`# Create a New Scenario for "${e.displayName}"`),X.push(""),X.push(`**Entity**: ${e.displayName}`),X.push(`**Type**: ${e.entityType}`),X.push(`**File**: ${v}`),X.push(""),te.length>0){X.push("## Existing Scenarios");for(const ye of te)X.push(`- **${ye.name}**${ye.url?` — URL: ${ye.url}`:""}`);X.push("")}return X.push("## Your Task"),X.push("Ask the user what scenario they would like to create. Offer two options:"),X.push("1. **Describe a scenario** — the user tells you what they want and you create it"),X.push("2. **Analyze gaps** — you review the existing scenarios and source code to suggest scenarios that would improve coverage"),X.push(""),X.push("Once you know what scenario to create, use the `codeyam editor register` CLI command to register it. Write the scenario JSON to `.codeyam/tmp/scenario.json` first, then run `codeyam editor register @.codeyam/tmp/scenario.json`."),X.join(`
606
+ `)},[e.displayName,e.entityType,v,te]),de=new Set((u==null?void 0:u[N])||[]),ue=Y?[...y.entries()].filter(([X])=>de.has(X)):[],me=Y?x.filter(X=>de.has(X.name)&&!ue.some(([ye])=>ye===X.name)):[],Se=Y?f.filter(X=>de.has(X.name)&&X.returnType!=="JSX.Element"&&X.returnType!=="React.ReactNode").map(X=>({name:X.name,filePath:X.filePath,description:X.description||"",testFile:X.testFile,feature:X.feature})):[],Te=ue.length>0||me.length>0,$e=Se.length>0;return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-5",children:[d("div",{className:"mb-5",children:[d("div",{className:"flex items-center gap-2.5",children:[n("button",{onClick:()=>{if(t.length>1){const X=t[t.length-2];r(X.componentName,X.entitySha)}else r()},className:"text-gray-400 hover:text-white transition-colors cursor-pointer bg-transparent border-none p-0 shrink-0 text-xl",title:"Go back",children:"←"}),n("h2",{className:"text-xl font-medium text-white m-0 font-['IBM_Plex_Sans']",children:e.displayName})]}),e.filePath&&n("div",{className:"mt-1.5 ml-7",children:n(Ns,{filePath:e.filePath,projectRoot:s})})]}),n("div",{className:"-mx-5 px-5 border-t border-b border-[#3d3d3d] flex items-center gap-6",children:[["scenarios","Scenarios"],["components","Components"],["functions","Functions"],["data-structure","Data Structure"]].map(([X,ye])=>n("button",{onClick:()=>C(X),className:`text-xs font-normal uppercase tracking-wider transition-colors bg-transparent border-none cursor-pointer px-0 font-['IBM_Plex_Mono'] border-b-2 leading-none ${S===X?"text-[#D7FF63] border-b-[#D7FF63]":"text-gray-500 hover:text-gray-300 border-b-transparent"}`,style:{marginBottom:-1,paddingTop:16,paddingBottom:14},children:ye},X))}),S==="scenarios"&&d("div",{className:"space-y-3 mt-5",children:[te.map(X=>{const ye=X.id===i,ee=A===X.id;return d("div",{children:[d("div",{onClick:()=>{ee||l(X)},className:`flex items-center gap-4 p-3 rounded-lg cursor-pointer transition-colors ${ye?"bg-[#1a2e1a] border border-[#D7FF63]/40":"bg-[#252525] hover:bg-[#2a2a2a] border border-transparent"}`,style:{opacity:$===X.id?.4:1},children:[X.screenshotPaths&&Object.keys(X.screenshotPaths).length>1?n("div",{className:"flex gap-2 shrink-0",children:Object.entries(X.screenshotPaths).map(([ne,xe])=>d("div",{className:"relative",children:[n(Qn,{scenarioId:X.id,screenshotPath:xe,updatedAt:X.updatedAt,alt:ne,className:"rounded w-[120px] h-[75px] overflow-hidden border border-[#3d3d3d]",imgClassName:"w-full h-full object-cover"}),n("span",{className:"absolute bottom-1 right-1 text-[8px] font-medium bg-black/60 text-white px-1 py-0.5 rounded",children:ne})]},ne))}):X.screenshotPath?n(Qn,{scenarioId:X.id,screenshotPath:X.screenshotPath,updatedAt:X.updatedAt,alt:"",className:"rounded w-[160px] h-[100px] shrink-0 overflow-hidden border border-[#3d3d3d]",imgClassName:"w-full h-full object-cover"}):n("div",{className:"rounded bg-[#1a1a1a] w-[160px] h-[100px] shrink-0 flex items-center justify-center border border-[#3d3d3d]",children:n("span",{className:"text-[10px] text-gray-600",children:"No image"})}),n("div",{className:"flex-1 min-w-0",children:ee?d("form",{className:"flex items-center gap-1.5",onSubmit:ne=>{ne.preventDefault(),G(X.id)},onClick:ne=>ne.stopPropagation(),children:[n("input",{type:"text",value:E,onChange:ne=>R(ne.target.value),className:"flex-1 px-2 py-1 text-xs bg-[#1e1e1e] text-white border border-[#3d3d3d] rounded outline-none focus:border-[#005c75] min-w-0",autoFocus:!0,disabled:D}),n("button",{type:"submit",disabled:D||!E.trim(),className:"px-2 py-1 text-[10px] bg-[#005c75] text-white rounded hover:bg-[#004d63] disabled:opacity-40 cursor-pointer border-none",children:D?"...":"Save"}),n("button",{type:"button",onClick:()=>_(null),className:"px-2 py-1 text-[10px] text-gray-400 hover:text-white cursor-pointer bg-transparent border-none",children:"Cancel"})]}):d(we,{children:[n("span",{className:"text-xs text-gray-300 truncate block",children:X.name}),ye&&d("div",{className:"flex items-center gap-3 mt-1.5",children:[n("button",{onClick:ne=>{ne.stopPropagation(),I(W===X.id?null:X.id)},className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 cursor-pointer bg-transparent border-none p-0",children:"View Data"}),n("button",{onClick:ne=>{ne.stopPropagation(),O(!1),H(!0)},className:"text-[10px] text-gray-400 hover:text-white cursor-pointer bg-transparent border-none p-0",children:"Edit with Claude"}),n("button",{onClick:ne=>{ne.stopPropagation(),_(X.id),R(X.name)},className:"text-[10px] text-gray-400 hover:text-white cursor-pointer bg-transparent border-none p-0",children:"Rename"}),n("button",{onClick:ne=>{ne.stopPropagation(),Q(X)},disabled:$===X.id,className:"text-[10px] text-red-400/60 hover:text-red-400 cursor-pointer bg-transparent border-none p-0",children:"Delete"})]})]})})]}),W===X.id&&n(_2,{scenarioId:X.id,onClose:()=>I(null),editPrompt:Cc(e.displayName,e.filePath,e.entityType,te),onReseedPreview:w})]},X.id)}),z&&(z.scenarios.length>0||z.pendingScenarios.length>0)&&d("div",{className:"space-y-1 mt-2",children:[z.scenarios.map(X=>d("div",{onClick:()=>c({analysisId:z.analysisId,scenarioId:X.id,scenarioName:X.name,entitySha:z.sha,entityName:z.name}),className:"flex items-center gap-3 p-2 rounded cursor-pointer transition-colors hover:bg-[#252525] border border-transparent",children:[X.screenshotPath?n("img",{src:`/api/screenshot/${X.screenshotPath}`,alt:X.name,className:"rounded w-[48px] h-[48px] shrink-0 object-cover",loading:"lazy"}):n("div",{className:"rounded bg-[#1a1a1a] w-[48px] h-[48px] shrink-0 flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})}),n("span",{className:"text-xs text-gray-300 truncate",children:X.name})]},X.id)),z.pendingScenarios.map(X=>d("div",{className:"flex items-center gap-3 p-2",children:[n("div",{className:"rounded bg-[#1a1a1a] w-[48px] h-[48px] shrink-0 flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"..."})}),n("span",{className:"text-xs text-gray-500 truncate",children:X})]},X))]}),te.length===0&&!z&&!J&&n("div",{className:"text-xs text-gray-500 py-2",children:"No scenarios for this entity"}),d("button",{onClick:()=>{H(!1),O(!0)},className:"flex items-center gap-2.5 mt-4 text-xs text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none cursor-pointer p-0 font-normal uppercase tracking-wider font-['IBM_Plex_Mono'] transition-colors",children:[d("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("line",{x1:"12",y1:"8",x2:"12",y2:"16"}),n("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]}),"Create New Scenario"]}),q&&n("div",{className:"mt-2 border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(qn,{prompt:oe,height:500,onClose:()=>O(!1)})}),B&&te.length>0&&n("div",{className:"mt-2 border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(qn,{prompt:Cc(e.displayName,e.filePath,e.entityType,te),height:500,onClose:()=>H(!1)})})]}),S==="components"&&n("div",{className:"space-y-3",children:Te?d(we,{children:[ue.map(([X,ye])=>n("div",{children:g.has(X)?d(we,{children:[n("div",{className:"py-1",children:n("button",{onClick:()=>r(X,g.get(X)),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:X})}),ye.length>0&&n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:sn(ye).map(({scenario:ee,dimensionLabel:ne,screenshotPath:xe,key:Me})=>n(As,{scenarioId:ee.id,screenshotPath:xe,updatedAt:ee.updatedAt,hasScreenshot:!!xe,name:ee.name,dimensionLabel:ne,isActive:ee.id===i,onSelect:()=>l(ee,ne??void 0)},Me))})]}):d("div",{className:"py-2",children:[n("span",{className:"text-[11px] font-medium text-gray-500",children:X}),n("p",{className:"text-[10px] text-amber-400/80 m-0 mt-1.5 leading-relaxed",children:"There is data missing that is required to show the scenarios for this component. Please copy and paste this prompt into Claude to ask Claude to fix the data."}),n("div",{className:"mt-1.5",children:n(Gu,{name:X,scenarios:ye})})]})},X)),me.map(X=>d("div",{children:[n("div",{className:"py-1",children:n("button",{onClick:()=>r(X.name,X.sha),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:X.name})}),(X.scenarios.length>0||X.pendingScenarios.length>0)&&d("div",{className:"grid grid-cols-3 gap-2 pt-1",children:[X.scenarios.map(ye=>n(As,{imgSrc:ye.screenshotPath?`/api/screenshot/${ye.screenshotPath}`:null,name:ye.name,isActive:!1,onSelect:()=>c({analysisId:X.analysisId,scenarioId:ye.id,scenarioName:ye.name,entitySha:X.sha,entityName:X.name})},ye.id)),X.pendingScenarios.map(ye=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:ye,children:ye},ye))]})]},X.sha))]}):n("div",{className:"text-xs text-gray-500 py-2",children:"No component dependencies"})}),S==="functions"&&d("div",{className:"space-y-3",children:[J&&J.testFile&&d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] text-gray-500",children:"Tests:"}),n(Ns,{filePath:J.testFile,projectRoot:s})]}),n(_o,{testFile:J.testFile,entityName:N,cachedResult:m[J.testFile]})]}),$e?n("div",{children:Se.map(X=>d("div",{className:"mt-2",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>r(X.name,g.get(X.name)),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:X.name})}),n(Ns,{filePath:X.filePath,projectRoot:s}),X.testFile&&d("div",{className:"mt-0.5",children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[9px] text-gray-600",children:"test:"}),n("span",{className:"text-[9px] text-gray-500 truncate",children:X.testFile})]}),n(_o,{testFile:X.testFile,entityName:X.name,cachedResult:m[X.testFile]})]})]},X.name))}):J!=null&&J.testFile?null:n("div",{className:"text-xs text-gray-500 py-2",children:"No function dependencies"})]}),S==="data-structure"&&n(E2,{})]})})}function _2({scenarioId:e,onClose:t,editPrompt:r,onReseedPreview:s}){const[a,o]=P(null),[i,l]=P([]),[c,p]=P(!0),[u,h]=P(null),[m,f]=P(null),[g,y]=P(!1),[x,b]=P(null),[w,v]=P(""),[N,S]=P(""),[C,A]=P(0),[_,E]=P(!1),[R,D]=P(!1),T=fe(null);if(ae(()=>{p(!0),h(null),Promise.all([fetch("/api/editor-schema").then(I=>I.json()).catch(()=>({models:[]})),fetch(`/api/editor-scenario-data?scenarioId=${e}`).then(I=>I.json())]).then(([I,j])=>{const k=I.source==="explicit"?b2(I.dataStructures||[],j):m2(I.models||[],j);o(k.data),l(k.tabs),k.tabs.length>0&&!m&&f(k.tabs[0].dataKey)}).catch(()=>h("Failed to load scenario data")).finally(()=>p(!1))},[e,C]),c)return n("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg p-4 text-xs text-gray-400",children:"Loading mock data..."});if(u||!a)return n("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg p-4 text-xs text-red-400",children:u||"No data available"});if(i.length===0)return d("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg p-4 text-xs text-gray-500",children:["No mock data found for this scenario.",n("button",{onClick:t,className:"ml-2 text-gray-400 hover:text-white bg-transparent border-none cursor-pointer text-[10px]",children:"Dismiss"})]});const $=i.find(I=>I.dataKey===m)||i[0],L=m?a[m]||[]:[],B=g2(L,$.schemaFields),H=y2(B,L,$.schemaFields),q=x2(B,$.schemaFields);return d("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg overflow-hidden",children:[d("div",{className:"flex items-center gap-1.5 px-2 py-1.5 bg-[#252525] border-b border-[#3d3d3d] flex-wrap",children:[i.map(I=>{const j=m===I.dataKey,k=I.category==="datastore"?j?"text-[#D7FF63] bg-[#D7FF63]/15 border-[#D7FF63]/40":"text-[#D7FF63]/60 bg-transparent border-transparent hover:text-[#D7FF63]/80":I.category==="mock-api"?j?"text-blue-400 bg-blue-400/15 border-blue-400/40":"text-blue-400/60 bg-transparent border-transparent hover:text-blue-400/80":j?"text-white bg-[#3d3d3d] border-[#4d4d4d]":"text-gray-500 bg-transparent border-transparent hover:text-gray-300";return n("button",{onClick:()=>f(I.dataKey),className:`px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider rounded cursor-pointer border transition-colors ${k}`,children:I.label},I.dataKey)}),n("div",{className:"flex-1"}),n("button",{onClick:t,className:"w-5 h-5 flex items-center justify-center text-gray-500 hover:text-white bg-[#3d3d3d] hover:bg-[#4d4d4d] rounded-full border-none cursor-pointer text-xs transition-colors",title:"Close",children:"×"})]}),($.description||$.category)&&d("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-[#1e1e1e] border-b border-[#2d2d2d]",children:[$.category&&n("span",{className:`text-[9px] rounded px-1.5 py-0 border ${$.category==="datastore"?"text-[#D7FF63]/80 bg-[#D7FF63]/10 border-[#D7FF63]/30":$.category==="mock-api"?"text-blue-400/80 bg-blue-400/10 border-blue-400/30":"text-gray-400 bg-gray-700/30 border-gray-600/30"}`,children:$.category==="mock-api"?"API Mock":$.category}),$.description&&n("span",{className:"text-[10px] text-gray-500",children:$.description})]}),B.length===0?n("div",{className:"px-3 py-4 text-[10px] text-gray-500 text-center",children:"No columns defined for this table"}):n("div",{className:"overflow-x-auto max-h-[300px] overflow-y-auto",children:d("table",{className:"w-full text-[10px] border-collapse table-fixed",children:[n("thead",{children:d("tr",{className:"bg-[#1e1e1e] sticky top-0 z-10",children:[n("th",{className:"text-right text-gray-600 font-normal px-2 py-1.5 border-b border-[#3d3d3d] w-8",children:"#"}),B.map(I=>d("th",{className:"text-left px-2 py-1.5 border-b border-[#3d3d3d] whitespace-nowrap overflow-hidden",children:[I===q&&n("span",{className:"inline-block text-[8px] font-bold text-white bg-[#D7FF63] rounded px-1 py-0 mr-1.5 align-middle",children:"PK"}),n("span",{className:"text-gray-300 font-medium",children:I}),n("span",{className:"text-gray-600 font-normal ml-1",children:H[I]})]},I))]})}),n("tbody",{children:L.map((I,j)=>d("tr",{className:"border-b border-[#2d2d2d] hover:bg-[#252525] group/row",children:[n("td",{className:"text-right text-gray-600 px-2 py-1.5 w-8 select-none",children:j+1}),B.map(k=>d("td",{className:`px-2 py-1.5 overflow-hidden relative group/cell ${k===q?"text-[#D7FF63] font-medium":"text-gray-300"}`,title:String(I[k]??""),children:[n("span",{className:"truncate block whitespace-nowrap",children:I[k]===null?n("span",{className:"text-gray-600 italic",children:"null"}):typeof I[k]=="object"?n("span",{className:"text-gray-500",children:JSON.stringify(I[k])}):typeof I[k]=="number"?n("span",{className:"text-amber-400",children:String(I[k])}):String(I[k])}),n("button",{onClick:Y=>{Y.stopPropagation(),b({row:j,col:k});const G=I[k]===null?"":typeof I[k]=="object"?JSON.stringify(I[k]):String(I[k]);v(G),S(G)},className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover/cell:opacity-100 text-gray-500 hover:text-white bg-[#252525] border border-[#4d4d4d] rounded cursor-pointer p-0.5 transition-opacity",title:"Edit",children:d("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]},k))]},j))})]})}),x&&d("div",{className:"border-t border-[#3d3d3d] bg-[#1e1e1e] px-3 py-2",children:[n("div",{className:"flex items-center gap-2 mb-1.5",children:d("span",{className:"text-[10px] text-gray-400",children:["Editing"," ",n("strong",{className:"text-gray-200",children:x.col})," in row ",x.row+1]})}),n("textarea",{value:w,onChange:I=>{const j=I.target.value;v(j),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{W($.dataKey,x.row,x.col,j)},600)},className:"w-full px-2 py-1.5 text-[11px] bg-[#252525] text-white border border-[#4d4d4d] rounded outline-none focus:border-[#D7FF63]/50 resize-y min-h-[60px] max-h-[200px] font-mono",autoFocus:!0,rows:w.length>100?4:2,onKeyDown:I=>{I.key==="Escape"&&O(),I.key==="Enter"&&(I.metaKey||I.ctrlKey)&&(T.current&&clearTimeout(T.current),W($.dataKey,x.row,x.col,w),b(null))}}),d("div",{className:"flex items-center gap-2 mt-1.5",children:[n("button",{onClick:()=>{T.current&&clearTimeout(T.current),W($.dataKey,x.row,x.col,w),b(null)},className:"px-3 py-1 text-[10px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded cursor-pointer border-none hover:bg-[#D7FF63]/80 transition-colors",children:"Save"}),n("button",{onClick:()=>O(),className:"px-3 py-1 text-[10px] text-gray-400 hover:text-white bg-transparent border-none cursor-pointer",children:"Cancel"}),d("span",{className:"text-[9px] text-gray-600 ml-auto",children:["⌘","+Enter to save, Esc to cancel"]})]})]}),_&&!x&&d("div",{className:"border-t border-[#3d3d3d] bg-amber-500/5 px-3 py-2 flex items-center gap-2",children:[n("span",{className:"text-[10px] text-amber-400/80",children:"Data modified — recapture to update the screenshot"}),n("div",{className:"flex-1"}),n("button",{onClick:()=>{D(!0),Promise.resolve().then(()=>(s&&s(),new Promise(I=>setTimeout(I,2e3)))).then(()=>fetch("/api/editor-capture-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e})})).then(()=>E(!1)).catch(()=>{}).finally(()=>D(!1))},disabled:R,className:"px-3 py-1 text-[10px] font-medium text-white bg-amber-600 rounded cursor-pointer border-none hover:bg-amber-500 disabled:opacity-50 transition-colors",children:R?"Recapturing...":"Recapture Screenshot"})]}),r&&d("div",{className:"border-t border-[#3d3d3d]",children:[n("div",{className:"flex justify-center py-2",children:n("button",{onClick:()=>y(!g),className:"px-3 py-1 text-[10px] font-medium text-[#D7FF63] border border-[#D7FF63]/40 rounded cursor-pointer transition-colors hover:bg-[#D7FF63]/10 bg-transparent",children:g?"Hide Claude":"Edit with Claude"})}),g&&n("div",{className:"border-t border-[#3d3d3d]",children:n(qn,{prompt:r,height:400,onClose:()=>{y(!1),A(I=>I+1)}})})]})]});function O(){if(T.current&&clearTimeout(T.current),!!x){if(w!==N){if(a&&m){const I=a[m];if(I&&I[x.row]){let j=N;N===""?j="":N==="null"?j=null:N==="true"?j=!0:N==="false"?j=!1:isNaN(Number(N))||(j=Number(N));const k=[...I];k[x.row]={...k[x.row],[x.col]:j},o({...a,[m]:k})}}fetch("/api/editor-save-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e,table:$.dataKey,rowIndex:x.row,column:x.col,value:N})}).then(()=>{s&&s()}).catch(()=>{})}b(null),E(!1)}}async function W(I,j,k,Y){if(a&&m){const G=a[m];if(G&&G[j]){let Q=Y;Y==="null"?Q=null:Y==="true"?Q=!0:Y==="false"?Q=!1:Y!==""&&!isNaN(Number(Y))&&(Q=Number(Y));const K=[...G];K[j]={...K[j],[k]:Q},o({...a,[m]:K})}}E(!0);try{await fetch("/api/editor-save-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e,table:I,rowIndex:j,column:k,value:Y})}),s&&s()}catch{}}}function E2(){const[e,t]=P([]),[r,s]=P([]),[a,o]=P(!0),[i,l]=P(null),[c,p]=P(!1),[u,h]=P(null);if(ae(()=>{fetch("/api/editor-schema").then(y=>y.json()).then(y=>{var x,b;h(y.source||null),y.source==="explicit"?(s(y.dataStructures||[]),((x=y.dataStructures)==null?void 0:x.length)>0&&l(y.dataStructures[0].name)):(t(y.models||[]),((b=y.models)==null?void 0:b.length)>0&&l(y.models[0].name))}).catch(()=>{}).finally(()=>o(!1))},[]),a)return n("div",{className:"text-xs text-gray-400 py-4",children:"Loading schema..."});if(!(u==="explicit"?r.length>0:e.length>0))return n("div",{className:"text-xs text-gray-500 py-4",children:"No data structure found. Use the chat below to have Claude analyze your codebase and generate one."});const f=u==="explicit"?j2(r):P2(e,u);return u==="explicit"?d("div",{className:"space-y-2",children:[r.map(y=>{const x=i===y.name,b=y.category==="datastore"?"text-[#D7FF63]/80 bg-[#D7FF63]/10 border border-[#D7FF63]/30":y.category==="mock-api"?"text-blue-400/80 bg-blue-400/10 border border-blue-400/30":"text-gray-400 bg-gray-700/30 border border-gray-600/30";return d("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:[d("button",{onClick:()=>l(x?null:y.name),className:"w-full flex items-center gap-2 px-3 py-2 bg-[#252525] text-left cursor-pointer border-none transition-colors hover:bg-[#2a2a2a]",children:[n("svg",{className:`text-gray-500 transition-transform shrink-0 ${x?"rotate-90":""}`,width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M9 18l6-6-6-6"})}),n("span",{className:"text-xs font-semibold text-gray-200",children:y.name}),y.order===1&&n("span",{className:"text-[9px] text-amber-400/70",children:"Primary"}),n("span",{className:`text-[9px] rounded px-1.5 py-0 ${b}`,children:y.category==="mock-api"?"API Mock":y.category}),d("span",{className:"text-[10px] text-gray-500",children:[y.fields.length," fields"]})]}),x&&d("div",{className:"border-t border-[#3d3d3d]",children:[y.description&&n("div",{className:"px-3 py-1.5 text-[10px] text-gray-400 border-b border-[#2d2d2d]",children:y.description}),n("table",{className:"w-full text-[10px]",children:n("tbody",{children:y.fields.map(w=>d("tr",{className:"border-b border-[#2d2d2d] last:border-b-0",children:[d("td",{className:"px-3 py-1.5 text-gray-300 font-medium w-1/3",children:[w.isId&&n("span",{className:"text-amber-400 mr-1",title:"Primary key",children:"•"}),w.name]}),n("td",{className:"px-3 py-1.5 text-gray-500",children:w.type}),n("td",{className:"px-3 py-1.5 text-gray-600 w-16 text-right",children:w.required===!1?"optional":""})]},w.name))})})]})]},y.name)}),n("div",{className:"flex justify-center pt-2",children:n("button",{onClick:()=>p(!c),className:"px-4 py-1.5 text-[11px] font-medium text-[#D7FF63] border border-[#D7FF63]/40 rounded-lg cursor-pointer transition-colors hover:bg-[#D7FF63]/10 bg-transparent",children:c?"Hide Chat":"Chat with Claude about the Data Structure"})}),c&&n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(qn,{prompt:f,height:500,onClose:()=>p(!1)})})]}):d("div",{className:"space-y-2",children:[n(A2,{prompt:`Analyze this codebase and generate a .codeyam/data-structure.json file that describes the app's data structures.
607
+
608
+ The file should be a JSON array where each entry has:
609
+ - "name": display name for the data structure
610
+ - "description": what this data represents and how it's used
611
+ - "category": either "datastore" (persisted data like DB tables, localStorage) or "mock-api" (mocked external API responses)
612
+ - "order": integer for display order (1 = primary/most important)
613
+ - "fields": array of { "name", "type", "isId" (boolean), "required" (boolean) }
614
+
615
+ Look at:
616
+ - Database schemas (prisma/schema.prisma, SQLite, etc.)
617
+ - TypeScript interfaces/types used for stored data
618
+ - localStorage usage patterns
619
+ - API response types that need mocking
620
+ - Do NOT include types that are only used as component props
621
+
622
+ Write the file to .codeyam/data-structure.json.`}),e.map(y=>{const x=i===y.name,b=y.fields.filter(v=>v.isRelation),w=y.fields.filter(v=>!v.isRelation);return d("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:[d("button",{onClick:()=>l(x?null:y.name),className:"w-full flex items-center gap-2 px-3 py-2 bg-[#252525] text-left cursor-pointer border-none transition-colors hover:bg-[#2a2a2a]",children:[n("svg",{className:`text-gray-500 transition-transform ${x?"rotate-90":""}`,width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M9 18l6-6-6-6"})}),n("span",{className:"text-xs font-semibold text-gray-200",children:y.name}),d("span",{className:"text-[10px] text-gray-500",children:[w.length," fields"]}),b.length>0&&d("span",{className:"text-[10px] text-[#D7FF63]/70",children:[b.length," relation",b.length>1?"s":""]})]}),x&&n("div",{className:"border-t border-[#3d3d3d]",children:n("table",{className:"w-full text-[10px]",children:d("tbody",{children:[w.map(v=>d("tr",{className:"border-b border-[#2d2d2d] last:border-b-0",children:[d("td",{className:"px-3 py-1.5 text-gray-300 font-medium w-1/3",children:[v.isId&&n("span",{className:"text-amber-400 mr-1",title:"Primary key",children:"•"}),v.name]}),d("td",{className:"px-3 py-1.5 text-gray-500",children:[v.type,v.isOptional&&"?",v.isList&&"[]"]})]},v.name)),b.length>0&&n("tr",{children:d("td",{colSpan:2,className:"px-3 py-1.5 border-t border-[#3d3d3d]",children:[n("span",{className:"text-[9px] text-gray-500 uppercase tracking-wider",children:"Relations"}),n("div",{className:"mt-1 flex flex-wrap gap-1.5",children:b.map(v=>n("button",{onClick:()=>l(v.relatedModel??null),className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/80 bg-[#D7FF63]/10 border border-[#D7FF63]/30 rounded px-1.5 py-0.5 cursor-pointer transition-colors",children:v.isList?`${v.relatedModel}[]`:v.relatedModel},v.name))})]})})]})})})]},y.name)}),n("div",{className:"flex justify-center pt-2",children:n("button",{onClick:()=>p(!c),className:"px-4 py-1.5 text-[11px] font-medium text-[#D7FF63] border border-[#D7FF63]/40 rounded-lg cursor-pointer transition-colors hover:bg-[#D7FF63]/10 bg-transparent",children:c?"Hide Chat":"Chat with Claude about the Data Structure"})}),c&&n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(qn,{prompt:f,height:500,onClose:()=>p(!1)})})]})}function A2({prompt:e}){const[t,r]=P(!1),[s,a]=P(()=>typeof window>"u"?!1:localStorage.getItem("codeyam-ds-migration-dismissed")==="1");return s?null:d("div",{className:"relative border border-amber-500/30 bg-amber-500/5 rounded-lg p-3 pr-8",children:[n("button",{onClick:()=>{a(!0),localStorage.setItem("codeyam-ds-migration-dismissed","1")},className:"absolute top-2 right-2 text-gray-500 hover:text-white bg-transparent border-none cursor-pointer p-0.5",title:"Dismiss",children:n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M2 2l8 8M10 2l-8 8"})})}),n("p",{className:"text-[11px] text-amber-400/90 m-0 font-['IBM_Plex_Sans'] leading-relaxed",children:"This data structure was auto-detected. For better results, ask Claude to generate an explicit data structure config."}),n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"mt-2 px-3 py-1 text-[10px] font-medium text-amber-400 border border-amber-500/40 rounded cursor-pointer transition-colors hover:bg-amber-500/10 bg-transparent",children:t?"Copied!":"Copy prompt for Claude"})]})}function P2(e,t){const r=e.map(a=>{const o=a.fields.map(i=>{let l=` ${i.name}: ${i.type}`;return i.isList&&(l+="[]"),i.isOptional&&(l+=" (optional)"),i.isId&&(l+=" [PK]"),i.isRelation&&(l+=` → ${i.relatedModel}`),l}).join(`
623
+ `);return`${a.name}:
624
+ ${o}`}).join(`
625
+
626
+ `);return`You are helping the user understand and modify the data structure of their application.
627
+
628
+ ${t==="prisma"?"The data structure is defined in `prisma/schema.prisma`.":t==="typescript"?"The data structure is defined via TypeScript interfaces in the `src/` directory.":"The data structure was inferred from the project."}
629
+
630
+ Here is the current data structure:
631
+
632
+ ${r}
633
+
634
+ Wait for the user to tell you what they want to do. They might want to:
635
+ - Add new models/tables
636
+ - Add or modify fields on existing models
637
+ - Understand relationships between models
638
+ - Get advice on data modeling
639
+ - Generate or modify seed data for scenarios
640
+
641
+ When making changes:
642
+ ${t==="prisma"?"- Edit `prisma/schema.prisma` directly":"- Edit the TypeScript interface files in `src/`"}
643
+ - After schema changes, update any affected scenario seed data
644
+ - Explain the impact of changes on existing data
645
+
646
+ Do NOT start making changes until the user tells you what they want.`}function j2(e){return`You are helping the user understand and modify the data structure of their application.
647
+
648
+ The data structure is explicitly defined in \`.codeyam/data-structure.json\`.
649
+
650
+ Here is the current data structure:
651
+
652
+ ${e.map(r=>{const s=r.category==="datastore"?"[datastore]":r.category==="mock-api"?"[mock-api]":`[${r.category}]`,a=r.fields.map(i=>{let l=` ${i.name}: ${i.type}`;return i.isId&&(l+=" [PK]"),i.required===!1&&(l+=" (optional)"),l}).join(`
653
+ `),o=r.description?` ${r.description}`:"";return`${r.name} ${s}${o?`
654
+ ${o}`:""}
655
+ ${a}`}).join(`
656
+
657
+ `)}
658
+
659
+ Each data structure has:
660
+ - **name**: display name
661
+ - **description**: what this data represents
662
+ - **category**: "datastore" (persisted data) or "mock-api" (mocked external API)
663
+ - **order**: display order (1 = primary)
664
+ - **fields**: array of { name, type, isId, required }
665
+
666
+ Wait for the user to tell you what they want to do. They might want to:
667
+ - Add new data structures (tables, API mocks)
668
+ - Add or modify fields
669
+ - Change categories or descriptions
670
+ - Understand how data flows through the app
671
+
672
+ When making changes:
673
+ - Edit \`.codeyam/data-structure.json\` directly
674
+ - Keep the file as a JSON array sorted by order
675
+ - Update descriptions to reflect changes
676
+ - After data structure changes, update affected scenario seed data
677
+
678
+ Do NOT start making changes until the user tells you what they want.`}function kc({status:e}){const t={new:{label:"New",bg:"bg-green-900/40",text:"text-green-400",border:"border-green-700/50"},edited:{label:"Edited",bg:"bg-blue-900/40",text:"text-blue-400",border:"border-blue-700/50"},impacted:{label:"Impacted",bg:"bg-amber-900/40",text:"text-amber-400",border:"border-amber-700/50"}}[e.status];return n("span",{className:`${t.bg} ${t.text} ${t.border} border text-[8px] font-bold px-1 py-0 rounded-full uppercase tracking-wider`,children:t.label})}function T2({testFile:e,entityName:t,cachedResult:r}){const{results:s,isRunning:a,runTests:o,stale:i}=Ti(e,r);if(a&&!s)return d("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#00a0c4] animate-pulse"}),n("span",{className:"text-[10px] text-gray-500",children:"Running tests..."})]});if(!s)return null;if(s.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-400",children:s.errorMessage})});const l=t?s.testCases.filter(u=>u.fullName.startsWith(t)):s.testCases,c=l.length>0?l:s.testCases;if(c.length===0)return null;const p=t?`${t} > `:"";return d("div",{className:"pt-1 space-y-0.5",children:[c.map(u=>{var m;const h=p&&u.fullName.startsWith(p)?u.fullName.slice(p.length):u.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[u.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):u.status==="failed"?n("span",{className:"text-red-400 text-[10px]",children:"✗"}):n("span",{className:"text-gray-500 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${u.status==="passed"?"text-green-400":u.status==="failed"?"text-red-400":"text-gray-500"}`,children:h})]}),u.status==="failed"&&((m=u.failureMessages)==null?void 0:m.map((f,g)=>n("div",{className:"pl-4 text-[9px] text-red-400/70 truncate max-w-full",title:f,children:f.split(`
679
+ `)[0]},g)))]},u.fullName)}),d("div",{className:"flex items-center gap-2 mt-1",children:[n("button",{onClick:o,disabled:a,className:"text-[10px] text-[#00a0c4] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:a?"Running...":i?"Re-run (stale)":"Re-run"}),i&&!a&&n("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0",title:"Source or test file changed since last run"})]})]})}const M2={added:"text-green-400",untracked:"text-green-400",modified:"text-blue-400",renamed:"text-purple-400"};function $2({files:e}){return d("div",{className:"border-t border-[#3d3d3d] pt-2 mt-1",children:[d("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:["Modified Files (",e.length,")"]}),n("div",{className:"mt-1 space-y-0.5 max-h-[150px] overflow-auto",children:e.map(t=>d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold uppercase w-[14px] text-center ${M2[t.status]||"text-gray-500"}`,children:t.status==="added"||t.status==="untracked"?"A":t.status==="modified"?"M":t.status==="renamed"?"R":"?"}),n("span",{className:"text-[10px] text-gray-400 truncate font-mono",children:t.path})]},t.path))})]})}const I2={feature:{label:"Feature",color:"bg-[#005c75]"},fix:{label:"Fix",color:"bg-amber-700"},refactor:{label:"Refactor",color:"bg-purple-700"},scaffold:{label:"Scaffold",color:"bg-green-700"},data:{label:"Data",color:"bg-blue-700"},milestone:{label:"Milestone",color:"bg-yellow-600"}};function R2(e){try{return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function D2(e){try{return new Date(e+"T00:00:00").toLocaleDateString([],{weekday:"long",month:"long",day:"numeric"})}catch{return e}}const F2=[{value:"1d",label:"1 Day"},{value:"3d",label:"3 Days"},{value:"7d",label:"1 Week"},{value:"30d",label:"1 Month"}];function O2({entries:e,onScreenshotClick:t}){const[r,s]=P(!1),[a,o]=P("7d"),i=ie(()=>rw(e,a),[e,a]);return d("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[d("button",{onClick:()=>s(!r),className:"w-full flex items-center justify-between px-3 py-2.5 cursor-pointer bg-transparent border-none text-left hover:bg-[#333] transition-colors",children:[n("span",{className:"text-xs font-semibold text-gray-400 uppercase tracking-wider",children:"Timeframe Summary"}),n("span",{className:`text-gray-500 text-[10px] transition-transform ${r?"rotate-180":""}`,children:"▼"})]}),r&&d("div",{className:"px-3 pb-3 space-y-3 border-t border-[#3d3d3d]",children:[n("div",{className:"flex gap-1 pt-2.5",children:F2.map(l=>n("button",{onClick:()=>o(l.value),className:`px-2.5 py-1 text-[10px] font-medium rounded transition-colors cursor-pointer border ${a===l.value?"bg-[#005c75] text-white border-[#005c75]":"bg-transparent text-gray-400 border-[#4d4d4d] hover:text-white hover:border-[#005c75]"}`,children:l.label},l.value))}),d("div",{className:"flex items-center gap-3 text-[11px] text-gray-400",children:[d("span",{children:[n("span",{className:"text-white font-medium",children:i.commitCount})," ",i.commitCount===1?"commit":"commits"]}),n("span",{className:"text-[#3d3d3d]",children:"|"}),d("span",{children:[n("span",{className:"text-white font-medium",children:i.totalScenarios})," ",i.totalScenarios===1?"scenario changed":"scenarios changed"]}),n("span",{className:"text-[#3d3d3d]",children:"|"}),d("span",{children:[n("span",{className:"text-white font-medium",children:i.entryCount})," ",i.entryCount===1?"entry":"entries"]})]}),i.totalScenarios===0?n("p",{className:"text-[11px] text-gray-500 italic m-0",children:"No scenario changes in this period."}):d("div",{className:"space-y-3",children:[i.appScenarios.length>0&&d("div",{className:"space-y-2",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),i.appScenarios.map(l=>n(_c,{scenario:l,onScreenshotClick:t},l.name))]}),i.componentGroups.size>0&&d("div",{className:"space-y-2",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),[...i.componentGroups.entries()].sort(([l],[c])=>l.localeCompare(c)).map(([l,c])=>d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:l}),c.map(p=>n(_c,{scenario:p,onScreenshotClick:t},p.name))]},l))]})]})]})]})}function _c({scenario:e,onScreenshotClick:t}){const r=e.name.indexOf(" - "),s=r!==-1?e.name.slice(r+3):e.name;return d("div",{className:"pl-2",children:[n("span",{className:"text-[10px] text-gray-500 block mb-1",children:s}),n("div",{className:"flex items-center gap-1 overflow-x-auto",children:e.screenshots.map((a,o)=>d("div",{className:"flex items-center shrink-0",children:[o>0&&n("span",{className:"text-[8px] text-gray-600 mx-0.5",children:"→"}),n("button",{type:"button",className:"w-16 h-16 rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] shrink-0 flex items-center justify-center cursor-pointer transition-colors",title:`${e.name} (${new Date(a.time).toLocaleDateString()})`,onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${a.path.replace("screenshots/","")}`,commitSha:null,commitMessage:null,scenarioName:e.name}),children:n("img",{src:`/api/editor-journal-image/${a.path.replace("screenshots/","")}`,alt:e.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})})]},a.path))})]})}function L2({isActive:e,onScreenshotClick:t,glossaryFunctions:r=[],cachedTestResults:s={}}){const[a,o]=P([]),[i,l]=P(!0),[c,p]=P(new Set),u=ce(f=>{p(g=>{const y=new Set(g);return y.has(f)?y.delete(f):y.add(f),y})},[]),h=ce(async()=>{try{const f=await fetch("/api/editor-journal");if(f.ok){const g=await f.json();o(g.entries||[])}}catch{}finally{l(!1)}},[]);if(ae(()=>{h()},[h]),ae(()=>{e&&h()},[e,h]),ae(()=>{if(!e)return;const f=setInterval(()=>void h(),5e3);return()=>clearInterval(f)},[e,h]),i)return n("div",{className:"flex-1 flex items-center justify-center",children:n("span",{className:"text-gray-500 text-sm",children:"Loading journal..."})});if(a.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:d("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No journal entries yet"}),n("p",{className:"text-xs",children:"Journal entries will appear as you build. Claude records features, screenshots, and commits as the project evolves."})]})});const m=sw(a);return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-4",children:[n(O2,{entries:a,onScreenshotClick:t}),[...m.entries()].map(([f,g])=>d("div",{children:[n("div",{className:"px-3 py-1.5 sticky top-0 bg-[#1e1e1e] z-10",children:n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:D2(f)})}),n("div",{className:"space-y-2",children:g.map((y,x)=>{const b=I2[y.type]||{label:y.type,color:"bg-gray-600"},w=`${y.time}-${x}`,v=c.has(w);return d("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[d("div",{className:`p-3 space-y-2 ${v?"":"max-h-[300px] overflow-y-auto"}`,children:[n("div",{className:"flex items-start gap-2 cursor-pointer",onClick:()=>u(w),children:d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-white truncate",children:y.title}),n("span",{className:`${b.color} text-white text-[9px] font-bold px-1.5 py-0.5 rounded uppercase tracking-wider shrink-0`,children:b.label})]}),n("span",{className:"text-[10px] text-gray-500",children:R2(y.time)}),y.featureName&&n("span",{className:"text-[10px] text-gray-500 italic truncate",title:y.featureName,children:y.featureName})]})}),y.userPrompt&&n(Hu,{text:y.userPrompt,theme:"dark"}),n("p",{className:"text-xs text-gray-400 leading-relaxed",children:y.description}),y.screenshot&&n("button",{type:"button",className:"rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] flex items-center justify-center p-1 cursor-pointer transition-colors w-full",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${y.screenshot.replace("screenshots/","")}`,commitSha:y.commitSha,commitMessage:y.commitMessage,scenarioName:y.title}),children:n("img",{src:`/api/editor-journal-image/${y.screenshot.replace("screenshots/","")}`,alt:y.title,className:"max-w-full max-h-full object-contain",loading:"lazy"})}),y.scenarioScreenshots&&y.scenarioScreenshots.length>0&&(()=>{const N=aw(y.scenarioScreenshots),S=y.entityChangeStatus,C=N.filter(([D])=>D==="App").flatMap(([,D])=>D),A=N.filter(([D])=>D!=="App"),_=new Map;for(const D of C){const T=D,$=T.pageFilePath?Ft(_t(T.pageFilePath)):mt(T.url??null),L=_.get($)||[];L.push(D),_.set($,L)}const E=[..._.entries()],R=D=>n("button",{type:"button",className:"w-[4.5rem] h-[4.5rem] rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] shrink-0 flex items-center justify-center cursor-pointer transition-colors",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${D.path.replace("screenshots/","")}`,commitSha:y.commitSha,commitMessage:y.commitMessage,scenarioName:D.name}),children:n("img",{src:`/api/editor-journal-image/${D.path.replace("screenshots/","")}`,alt:D.name,title:D.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})},D.path);return d("div",{className:"space-y-2",children:[E.length>0&&d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),E.map(([D,T])=>d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:D}),(S==null?void 0:S[D])&&n(kc,{status:S[D]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:T.map(R)})]},D))]}),A.length>0&&d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),A.map(([D,T])=>d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:D}),(S==null?void 0:S[D])&&n(kc,{status:S[D]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:T.map(R)})]},D))]})]})})(),r.length>0&&d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"}),n("div",{className:"space-y-2",children:r.map(N=>d("div",{children:[n("span",{className:"text-[11px] font-medium text-gray-200",children:N.name}),n("span",{className:"text-[9px] text-gray-500 truncate block",children:N.filePath}),N.testFile?n(T2,{testFile:N.testFile,entityName:N.name,cachedResult:s[N.testFile]}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},N.name))})]}),y.commitSha&&d("div",{className:"flex items-center gap-1.5 text-[10px]",children:[n("span",{className:"font-mono text-[#00a0c4] bg-[#00a0c4]/10 px-1.5 py-0.5 rounded",children:y.commitSha.slice(0,7)}),n("span",{className:"text-gray-500 truncate",children:y.commitMessage})]}),v&&y.modifiedFiles&&y.modifiedFiles.length>0&&n($2,{files:y.modifiedFiles})]}),d("button",{onClick:()=>u(w),className:"w-full py-1.5 text-[10px] text-gray-500 hover:text-gray-300 border-t border-[#3d3d3d] transition-colors cursor-pointer",children:["——— ",v?"Collapse":"Expand"," ———"]})]},w)})})]},f))]})})}function B2({hasProject:e,scenarios:t,analyzedEntities:r,allEntities:s=[],glossaryFunctions:a=[],cachedTestResults:o={},glossaryEntries:i=[],projectRoot:l,activeScenarioId:c,onScenarioSelect:p,onAnalyzedScenarioSelect:u,onSwitchToBuild:h,zoomComponent:m,focusedEntity:f,onZoomChange:g,entityImports:y,pageFilePaths:x={},projectTitle:b,projectDescription:w,migrationMode:v="none",migrationState:N,onStartMigration:S,breadcrumbItems:C=[],onReseedPreview:A}){const{pageGroups:_,componentGroups:E}=ie(()=>Mi(t),[t]),R=ie(()=>Ju(_,E),[_,E]),D=ie(()=>new Set(r.map(F=>F.sha)),[r]),T=ie(()=>w2(y||{}),[y]),$=ce(F=>v2(F,D,s,T),[D,s,T]),L=ie(()=>{const F=new Map;for(const M of s)F.set(M.sha,M.name);return F},[s]),B=ie(()=>N2(_,E,R,$),[_,E,R,$]),H=ie(()=>r.filter(F=>F.entityType==="visual").sort((F,M)=>F.name.localeCompare(M.name)),[r]),[q,O]=P(()=>{try{return localStorage.getItem("codeyam-app-banner-dismissed")==="true"}catch{return!1}}),W=ce(()=>{O(!0);try{localStorage.setItem("codeyam-app-banner-dismissed","true")}catch{}},[]),[I,j]=P(""),k=fe(null),Y=fe(0),G=ce(()=>{k.current&&(Y.current=k.current.scrollTop)},[]);ae(()=>{k.current&&Y.current>0&&(k.current.scrollTop=Y.current)});const Q=(f==null?void 0:f.sha)??"overview";if(!e)return n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:d("div",{className:"flex flex-col items-center gap-4",children:[n("h2",{className:"text-lg font-medium text-white m-0",children:"Ready to build something?"}),n("button",{onClick:h,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Start Building"})]})});if(v==="candidate")return n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:d("div",{className:"flex flex-col items-center gap-5 px-8 text-center max-w-[420px]",children:[n("h2",{className:"text-lg font-medium text-white m-0",children:"Migrate Your Project"}),n("p",{className:"text-sm text-gray-400 m-0 leading-relaxed",children:"It looks like you have an existing project. Claude can survey your codebase and systematically migrate it — deconstructing pages into clean components, extracting functions with tests, and creating scenarios. One page per session."}),n("button",{onClick:S,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Get Started"}),n("button",{onClick:h,className:"text-xs text-gray-500 hover:text-gray-300 bg-transparent border-none p-0 cursor-pointer underline",children:"Skip — build a new feature instead"})]})});if(v==="active"&&N){const F=N.pages||[],M=F.filter(te=>te.status==="complete").length,z=F.length,J=z>0?Math.round(M/z*100):0;return d("div",{className:"flex-1 flex flex-col overflow-auto p-4 font-['IBM_Plex_Sans']",children:[n("h2",{className:"text-lg font-medium text-white m-0 mb-3",children:"Project Migration"}),d("div",{className:"mb-4",children:[n("div",{className:"flex items-center gap-2 mb-1",children:d("span",{className:"text-xs text-gray-400",children:[M,"/",z," pages (",J,"%)"]})}),n("div",{className:"w-full h-1.5 bg-[#2d2d2d] rounded-full overflow-hidden",children:n("div",{className:"h-full bg-[#005c75] rounded-full transition-all",style:{width:`${J}%`}})})]}),n("div",{className:"space-y-1.5",children:F.map((te,oe)=>{const de=te.status==="complete"?"✓":te.status==="in-progress"?"→":"○",ue=te.status==="complete"?"text-green-400":te.status==="in-progress"?"text-cyan-400":"text-gray-600";return d("div",{className:"flex items-center gap-2",children:[n("span",{className:`text-xs ${ue} w-3 text-center`,children:de}),n("span",{className:`text-xs ${te.status==="in-progress"?"text-white font-medium":te.status==="complete"?"text-gray-400":"text-gray-600"}`,children:te.name}),n("span",{className:"text-[10px] text-gray-600",children:te.route}),te.status==="complete"&&d("span",{className:"text-[10px] text-gray-600",children:[(te.extractedComponents||[]).length,"c"," ",(te.extractedFunctions||[]).length,"f"," ",te.scenarioCount||0,"s"]})]},oe)})}),(N.sharedComponents||[]).length>0&&d("div",{className:"mt-4",children:[n("h3",{className:"text-xs font-medium text-gray-400 mb-1.5",children:"Shared Components"}),(N.sharedComponents||[]).map((te,oe)=>d("div",{className:"text-[10px] text-gray-500 mb-0.5",children:[te.name," ",d("span",{className:"text-gray-600",children:["— used in: ",(te.usedInPages||[]).join(", ")]})]},oe))]}),n("div",{className:"mt-4",children:n("button",{onClick:h,className:"px-4 py-2 bg-[#005c75] text-white text-xs font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Continue in Chat"})})]})}return t.length>0||H.length>0?f?n(Ku,{focusedEntity:f,breadcrumbItems:C,onZoomChange:g,projectRoot:l,scenarios:t,analyzedEntities:r,activeScenarioId:c,onScenarioSelect:p,onAnalyzedScenarioSelect:u,onSwitchToBuild:h,entityImports:y,glossaryFunctions:a,cachedTestResults:o,glossaryEntries:i,entityShaMap:R,componentGroups:E,visualEntities:H,isEntityComplete:$,onReseedPreview:A}):n("div",{ref:k,onScroll:G,className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:d("div",{className:"p-4 space-y-4",children:[B.length>1&&n(k2,{brokenEntities:B}),!q&&d("div",{className:"relative border border-[#2e7d32]/40 bg-cybg rounded-lg p-4 pr-10",children:[n("button",{onClick:W,className:"absolute top-3 right-3 text-[#D7FF63] hover:text-white bg-transparent border-none cursor-pointer p-0.5",title:"Dismiss",children:n("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M2 2l8 8M10 2l-8 8"})})}),n("p",{className:"text-sm text-white font-medium m-0 leading-snug",children:"These are all the pages in your project."}),d("p",{className:"text-sm text-gray-400 m-0 leading-snug mt-0.5",children:["(1) Select a scenario below and switch to"," ",n("button",{type:"button",onClick:h,className:"underline text-[#D7FF63] bg-transparent border-none cursor-pointer p-0 text-sm inline hover:text-[#D7FF63]/70 transition-colors",children:"build"})," ","to change or enhance an existing page."]}),n("p",{className:"text-sm text-gray-400 m-0 leading-snug mt-0.5",children:"(2) Select a page to see all of its sub-components and edit scenarios."})]}),_.size>0&&d("div",{children:[d("div",{className:"flex items-center gap-3 font-['IBM_Plex_Mono']",children:[n("span",{className:"text-xs font-bold text-gray-400 uppercase tracking-wider shrink-0",children:"Pages"}),n("div",{className:"flex-1"}),d("div",{className:"relative",style:{width:170},children:[d("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"11",cy:"11",r:"8"}),n("path",{d:"M21 21l-4.35-4.35"})]}),n("input",{type:"text",placeholder:"SEARCH...",value:I,onChange:F=>j(F.target.value),className:"w-full pl-9 pr-3 py-2 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded-md text-gray-300 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors tracking-wider"})]}),d("button",{onClick:h,className:"flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer shrink-0 uppercase tracking-wider",children:[n("span",{children:"+"})," New Page"]})]}),n("div",{className:"border-b border-[#2d2d2d] mt-3"}),[..._.entries()].sort(([F],[M])=>F==="Home"?-1:M==="Home"?1:F.localeCompare(M)).filter(([F])=>{if(!I.trim())return!0;const M=R.get(F);return((M?L.get(M):void 0)||F).toLowerCase().includes(I.trim().toLowerCase())}).map(([F,M])=>{const z=M.some(J=>J.id===c);return n("div",{className:"mt-2",children:R.has(F)&&$(R.get(F))?d(we,{children:[n("div",{className:"flex items-center gap-1.5 py-1",children:d("button",{onClick:()=>g(F,R.get(F)),className:`flex items-center gap-1.5 text-sm font-normal cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0 ${z?"text-[#D7FF63]":"text-gray-300"}`,children:[(()=>{const J=R.get(F);return(J?L.get(J):void 0)||F})(),d("span",{className:`font-normal text-sm ${z?"text-[#D7FF63]/60":"text-gray-500"}`,children:["(",M.length,")"]}),n("svg",{className:z?"text-[#D7FF63]/60":"text-gray-500",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M9 18l6-6-6-6"})})]})}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:sn(M).map(({scenario:J,dimensionLabel:te,screenshotPath:oe,key:de})=>n(As,{scenarioId:J.id,screenshotPath:oe,updatedAt:J.updatedAt,hasScreenshot:!!oe,name:J.name,dimensionLabel:te,isActive:J.id===c,onSelect:()=>p(J,te??void 0)},de))})]}):d("div",{className:"py-2",children:[n("span",{className:"text-sm font-normal text-gray-500",children:(()=>{const J=R.get(F);return J&&L.get(J)||F})()}),d("div",{className:"flex items-center gap-2 mt-1.5",children:[d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#E0D400",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),n("p",{className:"text-xs text-[#E0D400]/80 m-0 leading-relaxed",children:"Data missing for this page."}),n(Gu,{name:F,scenarios:M,reason:R.has(F)?"incomplete":"missing"})]})]})},F)})]})]})},Q):n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:d("div",{className:"flex flex-col items-center gap-4 px-8 text-center",children:[b?d(we,{children:[n("h2",{className:"text-lg font-medium text-white m-0",children:b}),w&&n("p",{className:"text-sm text-gray-400 m-0 leading-relaxed",children:w})]}):n("h2",{className:"text-lg font-medium text-white m-0",children:"Your project is ready"}),n("p",{className:"text-sm text-gray-400 m-0 leading-relaxed",children:"Describe what you want to build in the Chat and your pages and components will appear here."}),n("button",{onClick:h,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Start Building"})]})})}const Ec=[{key:"app",label:"App"},{key:"build",label:"Build"},{key:"data",label:"Structure"},{key:"history",label:"History"}],z2=()=>n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"text-[#8E8E8E] shrink-0",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})});function Y2({activeTab:e,onTabChange:t,buildIdle:r,projectTitle:s,breadcrumbItems:a,onBreadcrumbNavigate:o}){const[i,l]=P(!1),c=fe(null);ae(()=>{if(!i)return;const u=h=>{c.current&&!c.current.contains(h.target)&&l(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[i]);const p=a&&a.length>0;return d("div",{className:"shrink-0 z-20 @container",children:[d("div",{className:"bg-black h-10 flex items-center px-4 gap-4",children:[d("div",{className:"flex items-center gap-3 min-w-0",children:[d("div",{className:"flex items-center gap-2 shrink-0",children:[n("img",{src:Ks,alt:"CodeYam",className:"h-5 shrink-0"}),n("span",{className:"text-sm font-medium text-white whitespace-nowrap hidden @min-[500px]:inline",children:"CodeYam Editor"})]}),n("span",{className:"text-[#8E8E8E] text-sm shrink-0",children:"/"}),n("div",{className:"hidden @min-[350px]:flex items-center gap-1",children:Ec.map(u=>d("button",{onClick:()=>t(u.key),className:`px-2.5 py-2.5 text-sm transition-colors cursor-pointer border-b ${e===u.key?"text-[#D7FF63] border-[#D7FF63] font-medium":"text-[#8E8E8E] border-transparent hover:text-white font-light"}`,children:[u.label,u.key==="build"&&r&&e!=="build"&&n("span",{className:"ml-1 inline-block w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"})]},u.key))})]}),n("div",{className:"flex-1"}),n("button",{onClick:()=>t("settings"),className:`hidden @min-[350px]:block p-1.5 rounded-md transition-colors cursor-pointer ${e==="settings"?"text-[#D7FF63]":"text-[#8E8E8E] hover:text-white"}`,title:"Settings",children:d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"3"}),n("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}),d("div",{className:"@min-[350px]:hidden relative",ref:c,children:[n("button",{onClick:()=>l(!i),className:"p-1.5 rounded-md transition-colors cursor-pointer text-[#8E8E8E] hover:text-white",title:"Menu",children:d("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[n("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),n("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),n("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),i&&d("div",{className:"absolute right-0 top-full mt-1 bg-[#2d2d2d] border border-[#3d3d3d] rounded-lg shadow-lg py-1 min-w-[140px] z-50",children:[Ec.map(u=>d("button",{onClick:()=>{t(u.key),l(!1)},className:`w-full text-left px-4 py-2 text-sm transition-colors cursor-pointer bg-transparent border-none ${e===u.key?"text-[#D7FF63]":"text-[#8E8E8E] hover:text-white hover:bg-[#3d3d3d]"}`,children:[u.label,u.key==="build"&&r&&e!=="build"&&n("span",{className:"ml-1 inline-block w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"})]},u.key)),n("div",{className:"border-t border-[#3d3d3d] my-1"}),n("button",{onClick:()=>{t("settings"),l(!1)},className:`w-full text-left px-4 py-2 text-sm transition-colors cursor-pointer bg-transparent border-none ${e==="settings"?"text-[#D7FF63]":"text-[#8E8E8E] hover:text-white hover:bg-[#3d3d3d]"}`,children:"Settings"})]})]})]}),n("div",{className:`bg-[#161616] h-8 flex items-center px-4 border-b border-[#2d2d2d]${e==="build"?" hidden":""}`,children:n("nav",{className:"flex items-center gap-2 text-sm min-w-0",children:p?d(we,{children:[n("button",{type:"button",onClick:()=>o==null?void 0:o(),className:"text-[#8E8E8E] hover:text-white transition-colors bg-transparent border-none p-0 cursor-pointer shrink-0",children:s||"Untitled Project"}),a.slice(1).map((u,h)=>{const m=h===a.length-2;return d("span",{className:"flex items-center gap-2 min-w-0",children:[n(z2,{}),m?n("span",{className:"text-white truncate",children:u.name}):n("button",{type:"button",onClick:()=>o==null?void 0:o(u.componentName,u.entitySha),className:"text-[#8E8E8E] hover:text-white transition-colors bg-transparent border-none p-0 cursor-pointer truncate",children:u.name})]},u.componentName||u.name)})]}):n("span",{className:"text-[#8E8E8E]",children:s||"Untitled Project"})})})]})}function W2({onMouseDown:e,onDoubleClick:t,isDragging:r}){return d("div",{className:"shrink-0 relative flex items-center justify-center cursor-col-resize group",style:{width:12},onMouseDown:e,onDoubleClick:t,children:[n("div",{className:"absolute inset-y-0 left-1/2 -translate-x-1/2",style:{width:r?3:1,backgroundColor:r?"#3b82f6":"#3d3d3d",transition:"width 100ms, background-color 100ms"}}),!r&&n("div",{className:"absolute inset-0 bg-blue-500/0 group-hover:bg-blue-500/20 transition-colors pointer-events-none"}),d("div",{className:"relative z-10 flex flex-col gap-[3px] opacity-0 group-hover:opacity-100 transition-opacity",style:r?{opacity:1}:void 0,children:[n("div",{className:"w-2 h-px bg-gray-400"}),n("div",{className:"w-2 h-px bg-gray-400"}),n("div",{className:"w-2 h-px bg-gray-400"})]})]})}const Ac=300,Ss=150;function U2(e){const[t,r]=P(null),[s,a]=P(!1),o=fe(0),i=fe(null);ae(()=>{e.current&&r(Math.round(e.current.offsetWidth*.5))},[e]);const l=ce(()=>{var x;return((x=e.current)==null?void 0:x.offsetWidth)??(typeof window<"u"?window.innerWidth:1024)},[e]),c=ce(x=>{x.preventDefault(),a(!0)},[]),p=ce(()=>{r(Math.round(l()*.5))},[l]),u=ce(()=>{r(x=>(x&&x>0&&(i.current=x),0))},[]),h=ce(()=>{const x=i.current;i.current=null,r(x&&x>=Ac?x:Math.round(l()*.5))},[l]),m=ce(()=>{r(Math.round(l()*.5))},[l]);ae(()=>{if(!s)return;document.body.style.cursor="col-resize",document.body.style.userSelect="none";const x=w=>{cancelAnimationFrame(o.current),o.current=requestAnimationFrame(()=>{var E;const v=(E=e.current)==null?void 0:E.getBoundingClientRect(),N=(v==null?void 0:v.left)??0,C=((v==null?void 0:v.width)??window.innerWidth)-Ss,A=w.clientX-N,_=Math.min(Math.max(A,Ac),C);r(_)})},b=w=>{var A;cancelAnimationFrame(o.current),a(!1);const v=(A=e.current)==null?void 0:A.getBoundingClientRect(),N=(v==null?void 0:v.left)??0,S=(v==null?void 0:v.width)??window.innerWidth,C=w.clientX-N;C<Ss?r(0):S-C<Ss&&r(S)};return document.addEventListener("mousemove",x),document.addEventListener("mouseup",b),()=>{cancelAnimationFrame(o.current),document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",b),document.body.style.cursor="",document.body.style.userSelect=""}},[s,e]),ae(()=>{const x=()=>{r(b=>{if(b===null||b===0)return b;const w=l();return b>=w?w:Math.min(b,w-Ss)})};if(!(typeof window>"u"))return window.addEventListener("resize",x),()=>window.removeEventListener("resize",x)},[l]);const f=l(),g=t===0,y=t!==null&&t>=f;return{editorWidth:t,isDragging:s,isEditorCollapsed:g,isPreviewCollapsed:y,handleMouseDown:c,handleDoubleClick:p,collapseEditor:u,expandEditor:h,expandPreview:m}}function J2({preview:e,viewportWidth:t,viewportHeight:r,scale:s,onDismiss:a,onLoadCommit:o}){const i=t*s,l=r*s;return d("div",{className:"flex flex-col items-center gap-4 w-full",style:{maxWidth:`${i}px`},children:[d("div",{className:"text-center shrink-0",children:[n("h2",{className:"text-lg font-semibold text-[#333] m-0 font-['IBM_Plex_Sans']",children:"Journal Screenshot"}),n("p",{className:"text-sm text-[#888] mt-1 m-0 font-['IBM_Plex_Sans']",children:"This is a snapshot from a previous version — not a live preview"})]}),n("div",{className:"rounded-lg border-2 border-[#ccc] shadow-md overflow-y-auto overflow-x-hidden shrink",style:{width:`${i}px`,maxHeight:`${l}px`},children:n("img",{src:e.screenshotUrl,alt:e.scenarioName,className:"block",style:{width:`${i}px`}})}),d("div",{className:"flex items-center gap-2 text-sm text-[#666] shrink-0",children:[e.commitSha&&n("span",{className:"font-mono text-xs text-[#00a0c4] bg-[#00a0c4]/15 px-2 py-0.5 rounded",children:e.commitSha.slice(0,7)}),d("span",{className:"truncate",children:[e.scenarioName,e.commitMessage&&` — ${e.commitMessage}`]})]}),n("div",{className:"flex items-center gap-3 shrink-0",children:e.commitSha&&o&&n(H2,{commitSha:e.commitSha,onLoadCommit:o})})]})}function H2({commitSha:e,onLoadCommit:t}){const[r,s]=P(!1),[a,o]=P(null);return d(we,{children:[n("button",{onClick:()=>{s(!0),o(null),t(e).then(i=>{i.success||o(i.error||"Failed to load commit")}).catch(i=>{o(i instanceof Error?i.message:"Network error")}).finally(()=>s(!1))},disabled:r,className:"bg-[#005c75] hover:bg-[#004d63] disabled:opacity-50 text-white text-sm font-medium px-4 py-1.5 rounded transition-colors cursor-pointer",children:r?"Reverting...":"Revert to this code and load this version"}),a&&n("div",{className:"bg-red-50 border border-red-200 rounded px-4 py-2 text-sm text-red-600 w-full text-center",children:a})]})}function V2({preview:e,viewportWidth:t,viewportHeight:r,scale:s,onDismiss:a}){const o=t*s,i=r*s;return d("div",{className:"flex flex-col items-center gap-4 w-full",style:{maxWidth:`${o}px`},children:[d("div",{className:"text-center shrink-0",children:[n("h2",{className:"text-lg font-semibold text-gray-200 m-0 font-['IBM_Plex_Sans']",children:e.scenarioName}),d("div",{className:"flex items-center justify-center gap-2 mt-2",children:[n("span",{className:"inline-block w-2 h-2 rounded-full bg-amber-400 animate-pulse"}),n("p",{className:"text-sm text-amber-400/90 m-0 font-['IBM_Plex_Sans']",children:"The app is being edited - you can control the live preview when building is paused or complete."})]})]}),e.hasScreenshot?n("div",{className:"rounded-lg border-2 border-[#4d4d4d] shadow-md overflow-y-auto overflow-x-hidden shrink",style:{width:`${o}px`,maxHeight:`${i}px`},children:n(Qn,{scenarioId:e.scenarioId,screenshotPath:e.screenshotPath,updatedAt:e.updatedAt,alt:e.scenarioName,imgClassName:"block w-full",className:""})}):n("div",{className:"rounded-lg border-2 border-[#4d4d4d] bg-[#1a1a1a] flex items-center justify-center w-[400px] h-[300px]",children:n("span",{className:"text-sm text-gray-500",children:"No screenshot available"})}),n("button",{onClick:a,className:"text-xs text-gray-500 hover:text-gray-300 bg-transparent border-none cursor-pointer transition-colors shrink-0",children:"Dismiss"})]})}function G2({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,onStateChange:o}){const{interactiveServerUrl:i,isStarting:l,isLoading:c}=jn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:!0});return ae(()=>{o(i,l||c)},[i,l,c,o]),null}function K2({onSaveToCurrent:e,onSaveAsNew:t,onDismiss:r,isSaving:s,scenarioName:a}){return d("div",{className:"flex items-center justify-between px-4 py-1.5 bg-emerald-900/60 border-b border-emerald-700/50 text-emerald-200 text-xs",children:[n("span",{className:"font-medium",children:a?d(we,{children:["Data modified in “",a,"”."]}):"Data modified."}),d("div",{className:"flex items-center gap-2",children:[n("button",{onClick:e,disabled:s,className:"px-2.5 py-0.5 bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white text-xs font-medium rounded transition-colors cursor-pointer disabled:cursor-not-allowed",children:s?"Saving...":"Save to Scenario"}),n("button",{onClick:t,disabled:s,className:"px-2.5 py-0.5 bg-emerald-800 hover:bg-emerald-700 disabled:opacity-50 text-emerald-200 text-xs font-medium rounded transition-colors cursor-pointer disabled:cursor-not-allowed",children:"Save as New"}),n("button",{onClick:r,disabled:s,className:"text-emerald-400 hover:text-emerald-200 disabled:opacity-50 transition-colors cursor-pointer disabled:cursor-not-allowed",title:"Dismiss",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})}function q2({latestVersion:e}){const[t,r]=P(!1);if(t)return null;const s=`npm install -g @codeyam/codeyam-cli@${e}`;return d("div",{className:"shrink-0 w-full bg-[#D7FF63] px-4 py-1.5 flex items-center text-xs text-black font-['IBM_Plex_Sans']",children:[d("div",{className:"flex-1 flex items-center justify-center gap-2",children:[n("span",{children:"An update to the codeyam editor is available."}),n("code",{className:"bg-[#2d2d2d] text-white font-mono text-xs px-3 py-0.5 rounded-full",children:s}),n(ct,{content:s,icon:!0,iconSize:12,className:"text-black hover:text-gray-700 transition-colors"})]}),n("button",{type:"button",onClick:()=>r(!0),className:"shrink-0 p-0.5 rounded text-black/60 hover:text-black hover:bg-black/10 transition-colors cursor-pointer bg-transparent border-none","aria-label":"Dismiss upgrade banner",children:n("svg",{className:"w-3.5 h-3.5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})}function Q2(e,t){return t.status==="error"?{url:null,proxyUrl:null,isStarting:!1,error:t.errorMessage||"Dev server crashed",canStartServer:e.canStartServer,autoStartAttempted:e.autoStartAttempted,shouldAutoStart:!1}:t.url?{url:t.url,proxyUrl:t.proxyUrl||null,isStarting:!1,error:null,canStartServer:!0,autoStartAttempted:e.autoStartAttempted,shouldAutoStart:!1}:t.status==="starting"?{...e,isStarting:!0,error:null,canStartServer:!0,shouldAutoStart:!1}:t.status==="stopped"?e.url?{...e,url:null,isStarting:!1,shouldAutoStart:!1}:e.autoStartAttempted?{...e,isStarting:!1,shouldAutoStart:!1}:{...e,autoStartAttempted:!0,shouldAutoStart:!0}:{...e,shouldAutoStart:!1}}function Z2(e){const[t,r]=P({url:null,proxyUrl:null,isStarting:!1,error:null,canStartServer:!0,autoStartAttempted:!1}),s=fe(t);s.current=t,ae(()=>{let i=!1,l=null;const c=async()=>{try{const p=await fetch("/api/editor-dev-server");if(i)return;const u=await p.json(),h=Q2(s.current,u),{shouldAutoStart:m,...f}=h;if(r(f),m&&!(e!=null&&e.skipAutoStart))try{const g=await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})});if(i)return;g.ok?r(y=>({...y,isStarting:!0})):r(y=>({...y,canStartServer:!1}))}catch{}}catch{}};return c(),l=setInterval(()=>void c(),2e3),()=>{i=!0,l&&clearInterval(l)}},[t.url]);const a=ce(()=>{r(i=>({...i,error:null,isStarting:!0})),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})}).catch(()=>{})},[]),o=ce(()=>{r(i=>({...i,error:null,isStarting:!0})),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}).catch(()=>{})},[]);return{devServerUrl:t.url,proxyUrl:t.proxyUrl,isStarting:t.isStarting,error:t.error,canStartServer:t.canStartServer,retryServer:a,startServer:o}}function X2(e){const t=fe(null),r=fe(null);ae(()=>{if(typeof document>"u")return;r.current||(r.current=document.createElement("canvas"),r.current.width=64,r.current.height=64);const s=document.querySelector('link[rel="icon"]');if(!s)return;if(t.current||(t.current=s.href),!e){s.href=t.current;return}const a=new Image;a.crossOrigin="anonymous",a.onload=()=>{const o=r.current,i=o.getContext("2d");i.clearRect(0,0,64,64);const l=56,c=(64-l)/2;i.drawImage(a,c,c,l,l);const p=12,u=64-p-1,h=p+1;i.beginPath(),i.arc(u,h,p,0,2*Math.PI),i.fillStyle="#ef4444",i.fill(),s.href=o.toDataURL("image/png")},a.src=t.current},[e]),ae(()=>()=>{if(typeof document>"u")return;const s=document.querySelector('link[rel="icon"]');s&&t.current&&(s.href=t.current)},[])}function e5(e){if(!e||typeof e!="object")return[];for(const t of Object.values(e))if(Array.isArray(t))return t;return[]}function t5(e){return U.join(e,".codeyam","migration-state.json")}function qu(e){const t=t5(e);try{const r=V.readFileSync(t,"utf8"),s=JSON.parse(r);return n5(s)}catch{return null}}function n5(e){const t=Array.isArray(e.pages)?e.pages:[],r=Array.isArray(e.sharedComponents)?e.sharedComponents:[];return{status:e.status||"surveyed",startedAt:e.startedAt||new Date().toISOString(),completedAt:e.completedAt??null,currentPageIndex:typeof e.currentPageIndex=="number"?e.currentPageIndex:0,pages:t.map(s=>({name:s.name||"Unknown",route:s.route||"/",filePath:s.filePath||"",status:s.status||"pending",startedAt:s.startedAt??null,completedAt:s.completedAt??null,extractedComponents:Array.isArray(s.extractedComponents)?s.extractedComponents:[],extractedFunctions:Array.isArray(s.extractedFunctions)?s.extractedFunctions:[],scenarioCount:typeof s.scenarioCount=="number"?s.scenarioCount:0})),sharedComponents:r.map(s=>({name:s.name||"",filePath:s.filePath||"",extractedFromPage:s.extractedFromPage||"",usedInPages:Array.isArray(s.usedInPages)?s.usedInPages:[]}))}}function r5(e,t){if(!V.existsSync(U.join(e,"package.json"))||t!=null&&t.hasEditorScenarios)return!1;const r=U.join(e,".codeyam","glossary.json");if(V.existsSync(r))try{const o=JSON.parse(V.readFileSync(r,"utf8"));if((Array.isArray(o)?o:e5(o)).length>0)return!1}catch{}const s=U.join(e,".codeyam","editor-step.json");if(V.existsSync(s))try{const o=JSON.parse(V.readFileSync(s,"utf8"));if(o.feature||o.scaffolded)return!1}catch{}const a=qu(e);return(a==null?void 0:a.status)!=="complete"}function s5(e){const t=U.join(e,".codeyam","editor-step.json");try{const r=V.readFileSync(t,"utf8");return!!JSON.parse(r).migration}catch{return!1}}function a5({currentUrl:e,nextUrl:t,formMethod:r,defaultShouldRevalidate:s}){return r||e.pathname===t.pathname?s:e.pathname.startsWith("/editor")&&t.pathname.startsWith("/editor")?!1:s}const o5=()=>[{title:"Editor - CodeYam"},{name:"description",content:"CodeYam Code + Data Editor"}];function i5(e){const t=new URL(e).pathname.match(/\/editor\/entity\/([^/]+)/);return t?t[1]:null}async function l5({request:e}){var I;const t=await Ye();let r=!1,s=[],a=[];const o=Ne()||process.cwd();let i={map:{},allFiles:[]};try{i=di(o)}catch{}let l=[];try{l=or()}catch{}if(t){const{project:j}=await De(t);r=((I=j.metadata)==null?void 0:I.editorMode)??!1;try{const k=Pe();try{const K=await k.selectFrom("editor_scenarios").select(["id","url"]).where("project_id","=",j.id).where("component_name","is",null).where("page_file_path","is",null).execute();if(K.length>0){const{allFiles:F}=i;for(const M of K){const z=M;if(!z.url)continue;const J=Nd(z.url,F);J&&await k.updateTable("editor_scenarios").set({page_file_path:J}).where("id","=",z.id).execute()}}}catch(K){console.warn("[editor] page_file_path backfill failed (non-fatal):",K instanceof Error?K.message:K)}const Y=await k.selectFrom("editor_scenarios").selectAll().where("project_id","=",j.id).orderBy("created_at","asc").execute(),G=K=>{const F=K;let M=null,z=null;try{F.dimensions&&(M=typeof F.dimensions=="string"?JSON.parse(F.dimensions):F.dimensions)}catch{}try{F.screenshot_paths&&(z=typeof F.screenshot_paths=="string"?JSON.parse(F.screenshot_paths):F.screenshot_paths)}catch{}return{id:K.id,name:K.name,description:K.description||"",componentName:K.component_name||null,componentPath:K.component_path||null,screenshotPath:K.screenshot_path||null,url:F.url||null,type:F.type||null,viewportWidth:F.viewport_width||null,viewportHeight:F.viewport_height||null,dimensions:M,screenshotPaths:z,pageFilePath:F.page_file_path||null,entitySha:F.entity_sha||null,displayName:F.display_name||null,updatedAt:F.updated_at||null}};a=Ct(Y,K=>`${K.name}::${K.url||"/"}`).map(G);const Q=eu(o);if(Q){const K=zr(Q),F=Y.filter(M=>qo(M,K));s=Ct(F,M=>`${M.name}::${M.url||"/"}`).map(G)}else s=a}catch{}}const c=[...new Set(a.map(j=>j.componentName).filter(j=>j!==null))];let p=[];try{const j=U.join(o,".codeyam","glossary.json");if(V.existsSync(j)){const k=V.readFileSync(j,"utf8");p=JSON.parse(k)}}catch{}const u=f0(p),h={};try{const j=gi(o),k=u.filter(Y=>Y.testFile).map(Y=>({filePath:Y.filePath,testFile:Y.testFile}));if(k.length>0){const Y=yi(o,k);for(const[G,Q]of Object.entries(j.results)){const K=Y[G];h[G]={...Q,stale:K?mu(Q,K.sourceHash,K.testHash):!0}}}}catch{}let m=[],f=[];try{const j=await Pn()||[];m=j.map(k=>({sha:k.sha,name:k.name,entityType:k.entityType||"visual",filePath:k.filePath||""})),f=g0(j,p)}catch{}let g=[];try{if(m.length>0){const j=m.map(k=>k.sha);await Je(),g=await Xe({shas:j})||[]}}catch{}let y={};try{if(g.length>0){const j=new Set([...f.map(k=>k.name),...m.map(k=>k.name),...c,...p.map(k=>k.name)]);y=y0(g,j)}}catch{}const x=i.map,b=i.allFiles;if(Object.keys(x).length>0&&g.length>0&&(y=x0(y,x,g)),b.length>0&&g.length>0){const j=new Map;for(const k of g)k.filePath&&j.set(k.filePath,k.name);for(const k of b){const Y=Ft(_t(k));if(y[Y])continue;const G=j.get(k);G&&y[G]&&(y[Y]=y[G])}}let w={};try{w=(await ir({projectRoot:o,scenarioInputs:a,glossaryInputs:u,precomputedPageFilePaths:i,precomputedGitFiles:l,precomputedEntities:g})).entityChangeStatus}catch{}const v=l.filter(j=>j.status!=="deleted").map(j=>({path:j.path,status:j.status})),N=ui(o),S=pi(o),C=tu(o),A=ru(o);let _=null,E=null,R=null,D=null,T=null;try{const j=U.join(o,".codeyam","config.json");if(V.existsSync(j)){const k=JSON.parse(V.readFileSync(j,"utf8"));_=k.projectTitle||null,E=k.projectDescription||null,R=k.defaultScreenSize||null,D=k.screenSizes||null,T=k.appFormats||null}}catch{}T||(T=nu(o));const $=i5(e.url);let L=null,B=null;if($&&t)try{await Je();const j=await Xe({}),k=j==null?void 0:j.find(Y=>Y.sha===$);if(k){const Y=k.name,G=k.filePath||"",Q=k.entityType||"visual";B={name:Y,filePath:G,entityType:Q,displayName:Y};const K=j==null?void 0:j.find(F=>F.name===k.name&&F.filePath===k.filePath&&F.sha!==$&&F.createdAt&&k.createdAt&&F.createdAt>k.createdAt);K&&(L=K.sha)}}catch{}const H=su(o),q=H&&a.some(j=>j.id===H)?H:null;let O="none",W=null;try{if(W=qu(projRoot),(W==null?void 0:W.status)==="complete")O="complete";else if((W==null?void 0:W.status)==="in-progress"||(W==null?void 0:W.status)==="surveyed")O="active";else if(s5(projRoot))O="active";else if(t){const j=a.length>0;r5(projRoot,{hasEditorScenarios:j})&&(O="candidate")}}catch{}return re({projectSlug:t,projectRoot:Ne(),hasProject:!!t,editorMode:r,scenarios:s,allScenarios:a,components:c,analyzedEntities:f,allEntities:m,glossaryFunctions:u,glossaryEntries:p,entityImports:y,pageFilePaths:x,entityChangeStatus:w,modifiedFiles:v,featureName:N,userPrompt:S,projectTitle:_,projectDescription:E,defaultScreenSize:R,screenSizes:D,appFormats:T,editorStep:(C==null?void 0:C.step)??null,editorStepLabel:(C==null?void 0:C.label)??null,claudeSessionId:A,focusedEntitySha:$,newerEntitySha:L,focusedEntity:B,savedActiveScenarioId:q,migrationMode:O,migrationState:W,cachedTestResults:h})}class c5 extends Pp{constructor(){super(...arguments);ut(this,"state",{error:null,errorInfo:null})}static getDerivedStateFromError(r){return{error:r,errorInfo:null}}componentDidCatch(r,s){console.error("[EditorErrorBoundary] Error:",r.message),console.error("[EditorErrorBoundary] Component stack:",s.componentStack),console.error("[EditorErrorBoundary] Loader snapshot:",JSON.stringify(this.props.loaderSnapshot,null,2)),this.setState({errorInfo:s})}render(){var r;return this.state.error?n("div",{className:"fixed inset-0 bg-[#1e1e1e] flex items-center justify-center p-8",children:d("div",{className:"max-w-[600px] w-full space-y-4",children:[n("h2",{className:"text-lg font-semibold text-red-400 font-['IBM_Plex_Sans'] m-0",children:"Something went wrong"}),n("pre",{className:"text-xs text-gray-300 bg-[#2d2d2d] p-3 rounded overflow-auto max-h-[120px]",children:this.state.error.message}),((r=this.state.errorInfo)==null?void 0:r.componentStack)&&d("details",{className:"text-xs text-gray-500",children:[n("summary",{className:"cursor-pointer hover:text-gray-300 transition-colors",children:"Component stack"}),n("pre",{className:"mt-2 bg-[#2d2d2d] p-3 rounded overflow-auto max-h-[200px] text-yellow-300",children:this.state.errorInfo.componentStack})]}),n("p",{className:"text-xs text-gray-500 m-0",children:"Full diagnostics are in the browser console."}),n("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 bg-[#005c75] text-white text-sm rounded hover:bg-[#004d63] transition-colors cursor-pointer",children:"Reload"})]})}):this.props.children}}const d5=et(function(){var Hi,Vi;const{projectSlug:t,projectRoot:r,hasProject:s,scenarios:a,allScenarios:o,analyzedEntities:i,allEntities:l,glossaryFunctions:c,glossaryEntries:p,entityImports:u,pageFilePaths:h,entityChangeStatus:m,modifiedFiles:f,featureName:g,userPrompt:y,projectTitle:x,projectDescription:b,defaultScreenSize:w,screenSizes:v,appFormats:N,editorStep:S,editorStepLabel:C,claudeSessionId:A,focusedEntitySha:_,newerEntitySha:E,focusedEntity:R,migrationMode:D,migrationState:T,cachedTestResults:$}=st(),L=jc("root"),B=(L==null?void 0:L.npmUpdate)??null,[H,q]=Zn(),O=Rt(),W=fe(null),I=fe(null),j=fe(null),k=fe(null),[Y,G]=P(_);ae(()=>{G(_)},[_]),ae(()=>{const Z=le=>{const ve=le.target;(ve.tagName==="BUTTON"||ve.closest("button"))&&(ve.closest("button")??ve).blur()};return document.addEventListener("mouseup",Z),()=>document.removeEventListener("mouseup",Z)},[]);const Q=ie(()=>fc(Y,l),[Y,l,o]),K=(Q==null?void 0:Q.displayName)??void 0,F=H.get("scenario")||((Hi=ps(o))==null?void 0:Hi.id)||void 0,[M,z]=P(()=>K?[K]:[]),J=fe(null),te=fe([]),oe=fe(null);ae(()=>{var Ue;const Z=F||((Ue=ps(o))==null?void 0:Ue.id);if(!P0(Z,J.current))return;const le=o.find(Qe=>Qe.id===Z);if(!le)return;J.current=Z;const ve=Ha(le,te.current,oe.current);ve&&Et(ve);const Ae=Tt(le.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Ae,scenarioId:le.id,scenarioName:le.name,scenarioType:le.type})}).catch(()=>{})},[F,o]),ae(()=>{const Z=new BroadcastChannel("codeyam-editor");return Z.onmessage=le=>{var ve;if(((ve=le.data)==null?void 0:ve.type)==="switch-scenario"&&le.data.scenarioId){const Ae=le.data.scenarioId,Ue=o.find(zn=>zn.id===Ae);if(!Ue)return;J.current=Ae;const Qe=new URLSearchParams(H);Qe.set("scenario",Ae),Qe.delete("zoom"),q(Qe),ne(null),Me(null),Oe(null),Zt(!0);const Xt=Tt(Ue.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Xt,scenarioId:Ae,scenarioType:Ue.type})}).then(()=>{ye(!1),Dn(zn=>zn+1)}).catch(()=>{Zt(!1)})}},()=>Z.close()},[H,q,o]),ae(()=>{if(H.get("ref")!=="link"||!F)return;const Z=new BroadcastChannel("codeyam-editor");Z.postMessage({type:"switch-scenario",scenarioId:F}),Z.close(),window.close()},[]);const{devServerUrl:de,proxyUrl:ue,isStarting:me,error:Se,canStartServer:Te,retryServer:$e,startServer:Re}=Z2({skipAutoStart:D==="candidate"||D==="active"}),[X,ye]=P(!1),[ee,ne]=P(null),[xe,Me]=P(null),[he,He]=P(!1),[Ve,Oe]=P(null),[lr,dn]=P(null),$i=ce(async Z=>{const ve=await(await fetch("/api/editor-load-commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commitSha:Z})})).json();return ve.success&&(Oe(null),ye(!1)),ve},[]),Tn=ce((Z,le)=>{Me(ve=>(Z&&Z!==ve&&ye(!1),Z)),!le&&Z&&ye(!0),He(le)},[]),Ot=ce(Z=>{Oe(null),ne(ve=>(ve&&ve.analysisId===Z.analysisId||(Me(null),Dn(Ue=>Ue+1)),Z)),He(!0),ye(!1);const le=new URLSearchParams(H);le.delete("scenario"),le.delete("zoom"),q(le)},[H,q]),[We,Et]=P(w?{name:w.name,width:w.width,height:w.height}:{name:"Desktop",width:1440,height:900}),[Wr,Mn]=P(!1),[at,cr]=P(!1),yt=(N==null?void 0:N.includes("mobile-app"))??!1,At=w?{name:w.name,width:w.width,height:w.height}:null;oe.current=At;const ot=Rr(),Le=ie(()=>{const Z=ot.pathname.split("/").filter(Boolean),le=Z[Z.length-1];return le==="build"||le==="history"||le==="settings"?le:le==="structure"?"data":"app"},[ot.pathname]),dt=ce(Z=>{G(null),z([]);const le=Z==="app"?"":`/${Z==="data"?"structure":Z}`,ve=H.get("scenario"),Ae=ve?`?scenario=${ve}`:"";O(`/editor${le}${Ae}`)},[O,H]),un=ce(()=>{dt("build"),Lt(!0)},[dt]),Ur=ce(()=>{dt("build"),Lt(!0),setTimeout(()=>{var Z;(Z=W.current)==null||Z.sendInput("codeyam editor migrate")},300)},[dt]),[va,Lt]=P(Le==="build"),Na=!!(g&&S),[pn,Jr]=P(Na?"pending":"no-session"),Hr=fe(!1);ae(()=>{pn==="pending"&&!Hr.current&&(Hr.current=!0,dt("build"),Lt(!0))},[pn,dt]);const Sa=ce(()=>{Jr("continue")},[]),[dr,ur]=P(!1),[Ca,Vr]=P(!1),Gr=fe(!1),qt=fe(0),ka=fe(!1),Kr=ce(Z=>{ur(Z),Z||(ka.current=!0),Z&&!Gr.current&&(Vr(!1),qt.current=Date.now()),Z||(qt.current=0),Gr.current=Z},[]),[xt,qr]=P(!1),$n=fe(!1),Qr=ce(Z=>{Z!==$n.current&&(console.log("[Editor] claudeBuilding: %s → %s",$n.current,Z),$n.current=Z,qr(Z))},[]);X2(dr);const pr=fe(xt);ae(()=>{var le;const Z=pr.current&&!xt;if(pr.current=xt,!xt)if(Z){const ve=H.get("scenario")||((le=ps(o))==null?void 0:le.id),Ae=o.find(Ue=>Ue.id===ve);if(Ae){console.log("[Editor] Building stopped, loading live preview for: %s",Ae.name),dn(null);const Ue=Tt(Ae.name);J.current=Ae.id,Zt(!0),Fn(!1),ye(!1),fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Ue,scenarioId:Ae.id,scenarioType:Ae.type,skipBroadcast:!0})}).then(()=>{Dn(Qe=>Qe+1)}).catch(()=>{Zt(!1),ye(!0)})}else dn(null)}else dn(null)},[xt,H,o]);const{editorWidth:hr,isDragging:mr,isEditorCollapsed:Pt,isPreviewCollapsed:In,handleMouseDown:Zr,handleDoubleClick:Xr,collapseEditor:es,expandEditor:fr,expandPreview:ts}=U2(k),[pe,je]=P(!1),tt=ce(()=>{je(!0),dt("build"),Lt(!0)},[dt]),Be=ce(()=>{je(!1)},[]),it=ce(Z=>{Et(Z),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:Z,skipBroadcast:!0})})},[]),[bt,Ge]=P(Jn);ae(()=>{const Z=t0();Ge(Z),Z.systemNotification&&typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()},[]);const rt=ce(Z=>{Ge(Z),n0(Z)},[]);ae(()=>{if(Le==="build"){ur(!1);const Z=setTimeout(()=>{var le,ve;(le=W.current)==null||le.scrollToBottom(),(ve=W.current)==null||ve.focus()},50);return()=>clearTimeout(Z)}},[Le]),ae(()=>{function Z(){!document.hidden&&Le==="build"&&ur(!1)}return document.addEventListener("visibilitychange",Z),()=>document.removeEventListener("visibilitychange",Z)},[Le]);const[qe,hn]=P(null);ae(()=>{const Z=j.current;if(!Z)return;const le=new ResizeObserver(ve=>{const Ae=ve[0];Ae&&hn({width:Ae.contentRect.width,height:Ae.contentRect.height})});return le.observe(Z),()=>le.disconnect()},[]);const Bt=yt&&!at&&(We.height??900)>We.width,Qt=ie(()=>qe?Bt?wl(qe,{width:We.width+vs.width,height:(We.height??900)+vs.height}):wl(qe,We):1,[qe,We,Bt]),[Rn,Dn]=P(0),[Ii,_a]=P(null),[ns,Zt]=P(!1),rs=fe(!1),[Qu,Fn]=P(!1),[Zu,Ri]=P(!1),Ea=fe(0);ae(()=>{Rn>0&&(Ea.current=Date.now()+3e3)},[Rn]);const Xu=ce(()=>{if(Date.now()<Ea.current)return;const Z=qt.current;Z===0||Date.now()-Z<5e3||Fn(!0)},[]);ae(()=>{const Z=le=>{var ve;if(((ve=le.data)==null?void 0:ve.type)==="codeyam-localstorage-changed"){if(Date.now()<Ea.current)return;const Ae=qt.current;if(Ae===0||Date.now()-Ae<5e3)return;Fn(!0)}};return window.addEventListener("message",Z),()=>window.removeEventListener("message",Z)},[]);const Di=ce(async Z=>{Ri(!0);try{let le;const ve=I.current;ve!=null&&ve.contentWindow&&(le=await new Promise(Qe=>{const Xt=setTimeout(()=>Qe(void 0),2e3),zn=Gi=>{var Ki;((Ki=Gi.data)==null?void 0:Ki.type)==="codeyam-localstorage-state"&&(clearTimeout(Xt),window.removeEventListener("message",zn),Qe(Gi.data.data))};window.addEventListener("message",zn),ve.contentWindow.postMessage({type:"codeyam-get-localstorage"},"*")}));const Ue=await(await fetch("/api/editor-save-seed-state",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:Z,localStorage:le})})).json();Ue.success?Fn(!1):console.error("[editor] Save seed state failed:",Ue.error)}catch(le){console.error("[editor] Save seed state error:",le)}finally{Ri(!1)}},[]),ep=ce((Z,le)=>{if(_a(Z||null),le){const ve=new URLSearchParams(H);ve.set("scenario",le),J.current=le,q(ve);const Ae=o.find(Ue=>Ue.id===le);if(Ae){const Ue=Ha(Ae,te.current,oe.current);Ue&&Et(Ue)}}Oe(null),ye(!1),Dn(ve=>ve+1)},[H,q,o]),{customSizes:Aa,addCustomSize:tp,removeCustomSize:np}=oa(t),gr=ie(()=>r2(v,N),[v,N]),ss=ie(()=>[...gr,...Aa],[gr,Aa]);te.current=ss;const as=ie(()=>{const Z=new Map;for(const le of l){Z.set(le.name,le.sha);const ve=Ft(_t(le.filePath));ve!==le.name&&Z.set(ve,le.sha)}return Z},[l]),Fi=ie(()=>{const Z=new Map;for(const le of l)Z.set(le.sha,le.name);return Z},[l]),Oi=ie(()=>{const Z=[{name:"App"}];for(const le of M){const ve=as.get(le),Ae=ve?Fi.get(ve):void 0;Z.push({name:Ae||le,componentName:le,entitySha:ve})}return Z},[M,as,Fi]),{pageGroups:Li,componentGroups:Pa}=ie(()=>Mi(o),[o]),os=ie(()=>Ju(Li,Pa),[Li,Pa]),[rp,sp]=P("application"),[On,ja]=P([]),[Ta,Bi]=P(null),zi=ie(()=>Ta?fc(Ta,l):null,[Ta,l,o]),Yi=ie(()=>{const Z=[{name:"App"}];for(const le of On)Z.push({name:le,componentName:le,entitySha:as.get(le)});return Z},[On,as]),Ma=ce((Z,le)=>{if(!Z){ja([]),Bi(null);return}const ve=le||os.get(Z);if(!ve)return;const Ae=On.indexOf(Z);Ae>=0?ja(On.slice(0,Ae+1)):ja([...On,Z]),Bi(ve)},[On,os]),Wi=ce((Z,le)=>{if(!Z){z([]),G(null);const Qe=H.get("scenario"),Xt=Qe?`?scenario=${Qe}`:"";O(`/editor${Xt}`);return}if(!le){console.error(`[editor] No entity SHA for "${Z}" — entity missing from database`);return}const ve=M.indexOf(Z);ve>=0?z(M.slice(0,ve+1)):z([...M,Z]);const Ae=o.find(Qe=>Qe.entitySha===le);G(le);const Ue=Ae?`?scenario=${Ae.id}`:"";O(`/editor/entity/${le}${Ue}`)},[O,o,M,H]),Ui=ce(Z=>{Zt(!0),rs.current=!0,Fn(!1),ye(!1);const le=Tt(Z.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:le,scenarioId:Z.id,scenarioType:Z.type,skipBroadcast:!0})}).then(()=>{rs.current=!1,Dn(ve=>ve+1)}).catch(()=>{rs.current=!1,Zt(!1),ye(!0)})},[]),Ln=ce((Z,le)=>{console.log("[Editor] Scenario selected: %s dimension=%s (claudeBuilding=%s)",Z.name,le??"default",xt),ne(null),Me(null),Oe(null),_a(null);let ve=null;if(le&&(v!=null&&v[le])){const Ue=v[le],Qe=ss.find(Xt=>Xt.width===Ue.width&&Xt.height===Ue.height);ve={name:(Qe==null?void 0:Qe.name)||le,...Ue}}ve||(ve=Ha(Z,ss,At)),ve&&Et(ve),J.current=Z.id;const Ae=new URLSearchParams(H);Ae.set("scenario",Z.id),q(Ae),xt?dn({scenarioId:Z.id,scenarioName:Z.name,updatedAt:Z.updatedAt,hasScreenshot:!!Z.screenshotPath,screenshotPath:Z.screenshotPath}):(dn(null),Ui(Z))},[H,q,ss,v,xt,Ui]),ap=ce(()=>{const Z=F;if(!Z)return;const le=o.find(Ae=>Ae.id===Z);if(!le)return;const ve=Tt(le.name);ye(!1),fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:ve,scenarioId:le.id,scenarioType:le.type})}).then(()=>{Dn(Ae=>Ae+1)})},[F,o]),op=ce(Z=>{if(!Z.commitSha){const le=o.find(ve=>ve.name===Z.scenarioName);if(le){Ln(le);return}}Oe(Z)},[o,Ln]),ip=Z=>{const le={name:Z.name,width:Z.width,height:Z.height};Et(le),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:le,skipBroadcast:!0})})},lp=(Z,le,ve)=>{tp(Z,le,ve)},cp=Z=>{Et(Z),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:Z,skipBroadcast:!0})})};ae(()=>{const Z=le=>{var ve;if(((ve=le.data)==null?void 0:ve.type)==="codeyam-preview-ready"&&!ee){if(rs.current)return;ye(!0),Zt(!1)}};return window.addEventListener("message",Z),()=>window.removeEventListener("message",Z)},[ee]);const Ji=()=>{ee||setTimeout(()=>{ye(Z=>(Z||Zt(!1),!0))},5e3)},Bn=ie(()=>A0({activeAnalyzedScenario:!!ee,analyzedPreviewUrl:xe,activeScenarioId:F||null,scenarios:o,proxyUrl:ue,devServerUrl:de,zoomComponent:K||null}),[ue,de,K,F,o,ee,xe]),$a=ie(()=>{const Z=Ad(Bn,Ii);if(!Z)return null;const le=Z.includes("?")?"&":"?";return`${Z}${le}__cb=${Rn}`},[Bn,Ii,Rn]),dp=ie(()=>({projectSlug:t,hasProject:s,scenarioCount:a==null?void 0:a.length,allScenarioCount:o==null?void 0:o.length,analyzedEntityCount:i==null?void 0:i.length,glossaryFunctionCount:c==null?void 0:c.length,entityChangeStatusKeys:m?Object.keys(m):[],featureName:g}),[t,s,a,o,i,c,m,g]);return d(we,{children:[n(c5,{loaderSnapshot:dp,children:d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[ee&&n(G2,{analysisId:ee.analysisId,scenarioId:ee.scenarioId,scenarioName:ee.scenarioName,entityName:ee.entityName,projectSlug:t,onStateChange:Tn},ee.analysisId),B&&n(q2,{latestVersion:B.latestVersion}),d("div",{ref:k,className:"flex-1 flex min-h-0",children:[Pt&&n("div",{className:"shrink-0 flex items-center justify-center cursor-pointer hover:bg-[#3d3d3d] transition-colors",style:{width:8,backgroundColor:"#2d2d2d"},onClick:fr,title:"Expand editor",children:n("svg",{width:"6",height:"10",viewBox:"0 0 6 10",fill:"none",stroke:"#888",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M1 1l4 4-4 4"})})}),d("aside",{className:"bg-[#1e1e1e] shrink-0 flex flex-col overflow-hidden",style:{...Pt?{display:"none"}:hr!==null?{width:`${hr}px`}:{width:"50%"}},children:[E&&Q&&d("div",{className:"px-3 py-2 text-xs flex items-center justify-between",style:{background:"#2a1f00",borderBottom:"1px solid #3d2e00",color:"#f0c040"},children:[d("span",{children:["Viewing an older version of"," ",n("strong",{children:Q.name}),". A newer version exists."]}),n("a",{href:`/editor/entity/${E}`,className:"px-2 py-0.5 rounded text-xs",style:{background:"#3d2e00",color:"#f0c040",textDecoration:"none"},children:"View latest"})]}),n(Y2,{activeTab:Le,onTabChange:Z=>{dt(Z),Z==="build"&&Lt(!0),fetch("/api/telemetry-page-view",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({route:`/editor/${Z}`})}).catch(()=>{})},buildIdle:dr,projectTitle:x,breadcrumbItems:Le==="data"?Yi:Oi,onBreadcrumbNavigate:Le==="data"?Ma:Wi}),d("div",{className:"flex-1 min-h-0 overflow-hidden relative",children:[dr&&Le!=="build"&&!Ca&&d("div",{className:"absolute top-3 left-1/2 -translate-x-1/2 z-50 animate-[slideDown_0.3s_ease-out]",children:[n("style",{children:`
680
+ @keyframes slideDown {
681
+ from { transform: translate(-50%, -100%); opacity: 0; }
682
+ to { transform: translate(-50%, 0); opacity: 1; }
683
+ }
684
+ `}),d("div",{className:"flex items-center gap-1 bg-amber-50 border-2 border-amber-300 rounded-lg shadow-lg",children:[d("button",{onClick:()=>{dt("build"),Lt(!0)},className:"flex items-center gap-2 px-4 py-2 cursor-pointer hover:bg-amber-100 transition-colors rounded-l-md",children:[n("span",{className:"inline-block w-2 h-2 rounded-full bg-amber-400 animate-pulse"}),n("span",{className:"text-sm font-medium text-amber-900",children:"Claude is waiting for you"}),n("span",{className:"text-xs text-amber-600 ml-1",children:"Go to Build"})]}),n("button",{onClick:Z=>{Z.stopPropagation(),Vr(!0)},className:"px-2 py-2 cursor-pointer hover:bg-amber-100 transition-colors rounded-r-md text-amber-400 hover:text-amber-600","aria-label":"Dismiss",children:n("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M3 3l8 8M11 3l-8 8"})})})]})]}),va&&d("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Le==="build"?"visible":"hidden"},children:[n(p2,{projectTitle:x,featureName:g,editorStep:S,editorStepLabel:C,migrationMode:D}),n("div",{className:"flex-1 min-h-0",style:pe?{flex:"1 1 50%"}:void 0,children:pn==="pending"?n(a2,{featureName:g,editorStep:S,editorStepLabel:C,onContinue:Sa}):n(vd,{ref:W,entityName:"Editor",projectSlug:t,entityFilePath:null,scenarioName:null,onRefreshPreview:ep,onShowResults:tt,onHideResults:Be,onSetViewport:it,onDataMutationForwarded:Xu,editorMode:!0,onIdleChange:Kr,onBuildingChange:Qr,notificationSettings:bt,buildTabActive:Le==="build",claudeStartMode:pn==="continue"?"resume":"fresh",claudeSessionId:A,editorStepLabel:C,resultsOpen:pe})}),pe&&n("div",{style:{flex:"1 1 50%"},className:"min-h-0 border-t-2 border-gray-300",children:n(C2,{scenarios:a,allScenarios:o,glossaryFunctions:c,cachedTestResults:$,projectRoot:r,activeScenarioId:F,onScenarioSelect:Ln,onClose:Be,entityChangeStatus:m,modifiedFiles:f,featureName:g,userPrompt:y})})]}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Le==="app"?"visible":"hidden"},children:n(B2,{hasProject:s,scenarios:o,analyzedEntities:i,allEntities:l,glossaryFunctions:c,cachedTestResults:$,glossaryEntries:p,projectRoot:r,activeScenarioId:F,onScenarioSelect:Ln,onAnalyzedScenarioSelect:Ot,onSwitchToBuild:un,zoomComponent:K,focusedEntity:Q,onZoomChange:Wi,entityImports:u,pageFilePaths:h,projectTitle:x,projectDescription:b,breadcrumbItems:Oi,migrationMode:D,migrationState:T,onStartMigration:Ur,onReseedPreview:ap})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Le==="data"?"visible":"hidden"},children:zi?n(Ku,{focusedEntity:zi,breadcrumbItems:Yi,onZoomChange:Ma,projectRoot:r,scenarios:o,analyzedEntities:[],activeScenarioId:F,onScenarioSelect:Ln,onAnalyzedScenarioSelect:Ot,onSwitchToBuild:un,entityImports:u,glossaryFunctions:c,cachedTestResults:$,glossaryEntries:p,entityShaMap:os,componentGroups:Pa,visualEntities:[],isEntityComplete:()=>!0}):n(h2,{scenarios:o,projectRoot:r,activeScenarioId:F,onScenarioSelect:Ln,zoomComponent:void 0,focusedEntity:null,onZoomChange:Ma,analyzedEntities:[],glossaryFunctions:c,cachedTestResults:$,activeAnalyzedScenarioId:ee==null?void 0:ee.scenarioId,onAnalyzedScenarioSelect:Ot,entityImports:u,pageFilePaths:h,onSwitchToBuild:un,entityShaMap:os,structureTab:rp,onStructureTabChange:sp})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Le==="history"?"visible":"hidden"},children:n(L2,{isActive:Le==="history",onScreenshotClick:op,glossaryFunctions:c,cachedTestResults:$})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Le==="settings"?"visible":"hidden"},children:d("div",{className:"flex-1 overflow-auto p-4",children:[n("h2",{className:"text-sm font-semibold text-white mb-4",children:"Settings"}),n("p",{className:"text-xs text-gray-400",children:"Settings panel coming soon."})]})})]}),n(wd,{serverUrl:de,isStarting:me,projectSlug:t,devServerError:Se,onStartServer:Te?Re:void 0,notificationSettings:bt,onChangeNotificationSettings:rt})]}),!Pt&&!In&&n(W2,{onMouseDown:Zr,onDoubleClick:Xr,isDragging:mr}),In&&n("div",{className:"shrink-0 flex items-center justify-center cursor-pointer hover:bg-[#3d3d3d] transition-colors",style:{width:8,backgroundColor:"#2d2d2d"},onClick:ts,title:"Expand preview",children:n("svg",{width:"6",height:"10",viewBox:"0 0 6 10",fill:"none",stroke:"#888",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M5 1l-4 4 4 4"})})}),d("div",{className:"flex-1 flex flex-col min-w-0",style:{...In?{display:"none"}:void 0,...mr?{pointerEvents:"none"}:void 0},children:[d("div",{className:"bg-[#2d2d2d] border-b border-[#3d3d3d] shrink-0 z-10 h-10 flex items-center pr-4 relative",children:[n("div",{className:"flex items-center gap-1 shrink-0 z-10",children:n("button",{onClick:()=>{Pt?(fr(),setTimeout(()=>{var Z;return(Z=W.current)==null?void 0:Z.focus()},50)):es()},className:`p-1.5 rounded transition-colors cursor-pointer ${Pt?"text-white bg-[#666] hover:bg-[#777]":"text-gray-500 hover:text-gray-300"}`,title:Pt?"Show chat":"Hide chat",children:n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:Pt?d(we,{children:[n("path",{d:"M13 17l5-5-5-5"}),n("path",{d:"M6 17l5-5-5-5"})]}):d(we,{children:[n("path",{d:"M11 17l-5-5 5-5"}),n("path",{d:"M18 17l-5-5 5-5"})]})})})}),n("div",{className:"absolute inset-0 flex items-center justify-center gap-1 pointer-events-none",children:d("div",{className:"flex items-center gap-1 pointer-events-auto",children:[gr.map(Z=>{const le=Z.height>Z.width,ve=le&&Z.width>=700,Ae=Z.name==="Desktop"||Z.name==="Laptop"||Z.name==="Tablet"||Z.name==="Mobile"?Z.name:ve?"Tablet":le?"Mobile":Z.width>1200?"Desktop":"Laptop";return d("button",{onClick:()=>{at&&cr(!1),ip(Z)},className:`p-1.5 rounded transition-colors cursor-pointer ${!at&&We.name===Z.name?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:`${Z.name} (${Z.width}×${Z.height})`,children:[Ae==="Desktop"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n("path",{d:"M8 21h8M12 17v4"})]}),Ae==="Laptop"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8H4V6z"}),n("path",{d:"M2 18h20"})]}),Ae==="Tablet"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]}),Ae==="Mobile"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"7",y:"2",width:"10",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]})]},Z.name)}),d("div",{className:"relative",children:[d("button",{onClick:()=>{at||Mn(Z=>!Z)},className:`flex items-center gap-1.5 px-2 py-1 rounded transition-colors ${at?"":"cursor-pointer"} ${at||Wr||!gr.some(Z=>Z.name===We.name)?"text-white bg-[#555]":"text-gray-400 hover:text-gray-200 hover:bg-[#444]"}`,title:"Custom dimensions",children:[n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),n("span",{className:"text-xs font-mono",children:at&&qe?`${Math.round(qe.width)} × ${Math.round(qe.height)}`:`${We.width} × ${We.height??900}`})]}),Wr&&n(Kg,{currentWidth:We.width,currentHeight:We.height??900,devicePresets:gr,customSizes:Aa,onApply:cp,onSave:lp,onRemove:np,onClose:()=>Mn(!1)})]}),n("button",{onClick:()=>{cr(Z=>!Z)},className:`p-1.5 rounded transition-colors cursor-pointer ${at?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:at?"Exit fullscreen":"Fill page with preview",children:n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:at?d(we,{children:[n("polyline",{points:"4 14 10 14 10 20"}),n("polyline",{points:"20 10 14 10 14 4"}),n("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),n("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):d(we,{children:[n("polyline",{points:"15 3 21 3 21 9"}),n("polyline",{points:"9 21 3 21 3 15"}),n("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),n("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})}),n("button",{onClick:()=>{const Z=$a||Bn;Z&&window.open(Z,"_blank")},className:"p-1.5 rounded text-gray-500 hover:text-gray-300 transition-colors cursor-pointer",title:"Open preview in new window",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),n("polyline",{points:"15 3 21 3 21 9"}),n("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})})]})})]}),Qu&&n(K2,{onSaveToCurrent:()=>void Di("overwrite"),onSaveAsNew:()=>void Di("new"),onDismiss:()=>Fn(!1),isSaving:Zu,scenarioName:(Vi=o.find(Z=>{var le;return Z.id===(F||((le=ps(o))==null?void 0:le.id))}))==null?void 0:Vi.name}),n("div",{ref:j,className:`flex-1 flex ${Ve||lr?"overflow-y-auto overflow-x-hidden":"overflow-hidden"} ${at?"":"items-center justify-center p-8"}`,style:at?{backgroundColor:"#fff"}:Ve?{backgroundColor:"#f5f0e8",backgroundImage:"repeating-linear-gradient(0deg, transparent, transparent 19px, #e8e0d0 19px, #e8e0d0 20px), repeating-linear-gradient(90deg, transparent, transparent 19px, #e8e0d0 19px, #e8e0d0 20px)"}:lr?{backgroundColor:"#1e1e1e"}:{backgroundImage:`
685
+ linear-gradient(45deg, #333 25%, transparent 25%),
686
+ linear-gradient(-45deg, #333 25%, transparent 25%),
687
+ linear-gradient(45deg, transparent 75%, #333 75%),
688
+ linear-gradient(-45deg, transparent 75%, #333 75%)
689
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#2d2d2d"},children:Ve?n(J2,{preview:Ve,viewportWidth:We.width,viewportHeight:We.height??900,scale:Qt,onDismiss:()=>Oe(null),onLoadCommit:$i}):lr?n(V2,{preview:lr,viewportWidth:We.width,viewportHeight:We.height??900,scale:Qt,onDismiss:()=>dn(null)}):Bn?at?d("div",{className:"relative w-full h-full bg-white",children:[!X&&!ns&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-[#2a2a2a] rounded-lg p-8 w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Wt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the app to render"})]})]})}),ns&&n("div",{className:"absolute inset-0 z-20 flex items-center justify-center",style:{backgroundColor:"rgba(0, 0, 0, 0.25)",backdropFilter:"blur(1px)",transition:"opacity 200ms ease-out"},children:d("div",{className:"flex flex-col items-center gap-3 animate-pulse",children:[n("svg",{className:"w-6 h-6 text-white/80 animate-spin",viewBox:"0 0 24 24",fill:"none",children:n("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"50 100"})}),n("span",{className:"text-white/70 text-xs font-['IBM_Plex_Sans']",children:"Switching scenario"})]})}),n("iframe",{ref:I,src:$a||Bn,className:"w-full h-full border-none",title:"Editor preview",onLoad:Ji,style:{opacity:X?1:0}},Rn)]}):n("div",{style:{width:`${(Bt?We.width+vs.width:We.width)*Qt}px`,height:`${(Bt?(We.height??900)+vs.height:We.height??900)*Qt}px`},children:n("div",{className:"origin-top-left",style:{transform:Qt<1?`scale(${Qt})`:void 0},children:n(s2,{width:We.width,height:We.height??900,enabled:Bt,children:d("div",{className:"relative bg-white",style:{width:`${We.width}px`,height:`${We.height??900}px`},children:[!X&&!ns&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-[#2a2a2a] rounded-lg p-8 w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Wt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the app to render"})]})]})}),ns&&n("div",{className:"absolute inset-0 z-20 flex items-center justify-center",style:{backgroundColor:"rgba(0, 0, 0, 0.25)",backdropFilter:"blur(1px)",transition:"opacity 200ms ease-out"},children:d("div",{className:"flex flex-col items-center gap-3 animate-pulse",children:[n("svg",{className:"w-6 h-6 text-white/80 animate-spin",viewBox:"0 0 24 24",fill:"none",children:n("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"50 100"})}),n("span",{className:"text-white/70 text-xs font-['IBM_Plex_Sans']",children:"Switching scenario"})]})}),n("iframe",{ref:I,src:$a||Bn,className:"w-full h-full border-none",title:"Editor preview",onLoad:Ji,style:{opacity:X?1:0}},Rn)]})})})}):n("div",{className:"bg-[#2a2a2a] rounded-lg flex flex-col items-center justify-center",style:{width:`${We.width*Qt}px`,height:`${(We.height??900)*Qt}px`},children:Se?d("div",{className:"flex flex-col gap-4 text-center px-8 max-w-[600px]",children:[n("h2",{className:"text-xl font-medium text-red-400 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Dev Server Failed"}),n("pre",{className:"text-xs text-left bg-[#1e1e1e] text-gray-300 p-4 rounded overflow-auto max-h-[300px] w-full font-mono whitespace-pre-wrap",children:Se}),n("button",{onClick:$e,className:"mx-auto px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded hover:bg-[#004d63] transition-colors cursor-pointer",children:"Retry"})]}):me||he?d(we,{children:[n("div",{className:"mb-4",children:n(Wt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:he?"Starting Interactive Mode":"Starting Dev Server"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:he?"Loading component preview...":"Your dev server is starting up..."})]})]}):d("div",{className:"flex flex-col gap-3 text-center px-8",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Live Preview"}),n("p",{className:"text-sm text-gray-500 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Describe what you want to build in the Build tab"})]})})})]})]})]})}),n(Pc,{})]})}),u5=Object.freeze(Object.defineProperty({__proto__:null,default:d5,loader:l5,meta:o5,shouldRevalidate:a5},Symbol.toStringTag,{value:"Module"})),p5=et(function(){return null}),Un=Object.freeze(Object.defineProperty({__proto__:null,default:p5},Symbol.toStringTag,{value:"Module"})),bk={entry:{module:"/assets/entry.client-SuW9syRS.js",imports:["/assets/jsx-runtime-D_zvdyIk.js","/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/index-CWV9XZiG.js"],css:[]},routes:{root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!0,module:"/assets/root-dKFRTYcy.js",imports:["/assets/jsx-runtime-D_zvdyIk.js","/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/index-CWV9XZiG.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/ReportIssueModal-C2PLkej3.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/loader-circle-De-7qQ2u.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/book-open-CL-lMgHh.js","/assets/useToast-5HR2j9ZE.js","/assets/useLastLogLine-D9QZKaLJ.js","/assets/LogViewer-CM5zg40N.js","/assets/EntityTypeIcon-CD7lGABo.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/chevron-down-GmAjGS9-.js","/assets/circle-check-DFcQkN5j.js","/assets/CopyButton-CLe80MMu.js","/assets/triangle-alert-DqJ0j69l.js","/assets/copy-C6iF61Xs.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.fullscreen-BrkN-40Y.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/Spinner-Bc8BG-Lw.js","/assets/useLastLogLine-D9QZKaLJ.js","/assets/ViewportInspectBar-BA_Ry-rs.js","/assets/useCustomSizes-DhXHbEjP.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/InlineSpinner-CgTNOhnu.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.dev":{id:"routes/entity.$sha.scenarios.$scenarioId.dev",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/dev",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.dev-wdiwx5-Z.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/Spinner-Bc8BG-Lw.js","/assets/useLastLogLine-D9QZKaLJ.js","/assets/ViewportInspectBar-BA_Ry-rs.js","/assets/useCustomSizes-DhXHbEjP.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/InlineSpinner-CgTNOhnu.js","/assets/editorPreview-CluPkvXJ.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/preload-helper-ckwbz45p.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-switch-scenario":{id:"routes/api.interactive-switch-scenario",parentId:"root",path:"api/interactive-switch-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-switch-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-screenshot":{id:"routes/api.editor-journal-screenshot",parentId:"root",path:"api/editor-journal-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-save-scenario-data":{id:"routes/api.editor-save-scenario-data",parentId:"root",path:"api/editor-save-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-save-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-CRXJWmpB.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/InteractivePreview-DtYTSPL2.js","/assets/Spinner-Bc8BG-Lw.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-D9QZKaLJ.js","/assets/InlineSpinner-CgTNOhnu.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-register-scenario":{id:"routes/api.editor-register-scenario",parentId:"root",path:"api/editor-register-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-register-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-coverage":{id:"routes/api.editor-scenario-coverage",parentId:"root",path:"api/editor-scenario-coverage",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-coverage-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha_.create-scenario-DxfhekTZ.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/InteractivePreview-DtYTSPL2.js","/assets/Spinner-Bc8BG-Lw.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-D9QZKaLJ.js","/assets/InlineSpinner-CgTNOhnu.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-capture-scenario":{id:"routes/api.editor-capture-scenario",parentId:"root",path:"api/editor-capture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-capture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-recapture-stale":{id:"routes/api.editor-recapture-stale",parentId:"root",path:"api/editor-recapture-stale",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-recapture-stale-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-rename-scenario":{id:"routes/api.editor-rename-scenario",parentId:"root",path:"api/editor-rename-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-rename-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-save-seed-state":{id:"routes/api.editor-save-seed-state",parentId:"root",path:"api/editor-save-seed-state",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-save-seed-state-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-prompt":{id:"routes/api.editor-scenario-prompt",parentId:"root",path:"api/editor-scenario-prompt",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-prompt-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-switch-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-update-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-client-errors-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-entity-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-entry-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-verify-routes":{id:"routes/api.editor-verify-routes",parentId:"root",path:"api/editor-verify-routes",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-verify-routes-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-project-info":{id:"routes/api.editor-project-info",parentId:"root",path:"api/editor-project-info",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-project-info-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-test-results-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-load-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.agent-transcripts-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-dev-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.logs._projectSlug-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-file-diff":{id:"routes/api.editor-file-diff",parentId:"root",path:"api/editor-file-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.execute-function-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-mode-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.delete-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.dev-mode-events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.generate-report-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-refresh-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-session":{id:"routes/api.editor-session",parentId:"root",path:"api/editor-session",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-session-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.memory-profile-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.restart-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/agent-transcripts-Bg3e7q4S.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/terminal-CrplD4b1.js","/assets/search-BdBb5aqc.js","/assets/chevron-down-GmAjGS9-.js","/assets/book-open-CL-lMgHh.js","/assets/triangle-alert-DqJ0j69l.js","/assets/copy-C6iF61Xs.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-schema":{id:"routes/api.editor-schema",parentId:"root",path:"api/editor-schema",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-schema-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-audit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.save-fixture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-yH46LLUz.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/LogViewer-CM5zg40N.js","/assets/useLastLogLine-D9QZKaLJ.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/EntityTypeIcon-CD7lGABo.js","/assets/EntityTypeBadge-CQgyEGV-.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/LoadingDots-By5zI316.js","/assets/loader-circle-De-7qQ2u.js","/assets/pause-CFxEKL1u.js","/assets/createLucideIcon-4ImjHTVC.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.debug-setup-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.labs-unlock-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.rule-path-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha._-DYJRGiDI.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useLastLogLine-D9QZKaLJ.js","/assets/Spinner-Bc8BG-Lw.js","/assets/InteractivePreview-DtYTSPL2.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/LibraryFunctionPreview-D3s1MFkb.js","/assets/LoadingDots-By5zI316.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-CefgqbCr.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-CD7lGABo.js","/assets/CopyButton-CLe80MMu.js","/assets/LogViewer-CM5zg40N.js","/assets/MiniClaudeChat-CQENLSrF.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/preload-helper-ckwbz45p.js","/assets/InlineSpinner-CgTNOhnu.js","/assets/ViewportInspectBar-BA_Ry-rs.js","/assets/useCustomSizes-DhXHbEjP.js","/assets/ReportIssueModal-C2PLkej3.js","/assets/circle-check-DFcQkN5j.js","/assets/triangle-alert-DqJ0j69l.js","/assets/copy-C6iF61Xs.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.analyze-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/simulations-DSCdE99u.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/LoadingDots-By5zI316.js","/assets/EntityTypeIcon-CD7lGABo.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/chevron-down-GmAjGS9-.js","/assets/search-BdBb5aqc.js","/assets/loader-circle-De-7qQ2u.js","/assets/createLucideIcon-4ImjHTVC.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.health-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.memory-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.queue-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/dev.empty-CRepiabR.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/ScenarioViewer-CefgqbCr.js","/assets/InteractivePreview-DtYTSPL2.js","/assets/ViewportInspectBar-BA_Ry-rs.js","/assets/useCustomSizes-DhXHbEjP.js","/assets/LogViewer-CM5zg40N.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/useLastLogLine-D9QZKaLJ.js","/assets/Spinner-Bc8BG-Lw.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-C2PLkej3.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/circle-check-DFcQkN5j.js","/assets/triangle-alert-DqJ0j69l.js","/assets/copy-C6iF61Xs.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/InlineSpinner-CgTNOhnu.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/settings-DdE-Untf.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/CopyButton-CLe80MMu.js","/assets/copy-C6iF61Xs.js","/assets/createLucideIcon-4ImjHTVC.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/static._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/_index-C1YkzTAV.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useLastLogLine-D9QZKaLJ.js","/assets/useToast-5HR2j9ZE.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/LogViewer-CM5zg40N.js","/assets/EntityTypeIcon-CD7lGABo.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/circle-check-DFcQkN5j.js","/assets/loader-circle-De-7qQ2u.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/memory-Cx2xEx7s.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/terminal-CrplD4b1.js","/assets/copy-C6iF61Xs.js","/assets/CopyButton-CLe80MMu.js","/assets/chevron-down-GmAjGS9-.js","/assets/search-BdBb5aqc.js","/assets/pause-CFxEKL1u.js","/assets/book-open-CL-lMgHh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/files-D-xGrg29.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/EntityItem-Crt_KN_U.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/chevron-down-GmAjGS9-.js","/assets/search-BdBb5aqc.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/useToast-5HR2j9ZE.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/LibraryFunctionPreview-D3s1MFkb.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-DqJ0j69l.js","/assets/EntityTypeIcon-CD7lGABo.js","/assets/EntityTypeBadge-CQgyEGV-.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/labs-B_IX45ih.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-Cy5Qg_UR.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/git-Bq_fbXP5.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/EntityItem-Crt_KN_U.js","/assets/LogViewer-CM5zg40N.js","/assets/index-DE3jI_dv.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/useToast-5HR2j9ZE.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/LibraryFunctionPreview-D3s1MFkb.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-DqJ0j69l.js","/assets/EntityTypeIcon-CD7lGABo.js","/assets/EntityTypeBadge-CQgyEGV-.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/editor.entity.($sha)":{id:"routes/editor.entity.($sha)",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor.entity.(_sha)-CRxPi2BB.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useCustomSizes-DhXHbEjP.js","/assets/editorPreview-CluPkvXJ.js","/assets/CopyButton-CLe80MMu.js","/assets/MiniClaudeChat-CQENLSrF.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/Spinner-Bc8BG-Lw.js","/assets/copy-C6iF61Xs.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/useLastLogLine-D9QZKaLJ.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-index":{id:"editor-tab-index",parentId:"routes/editor.entity.($sha)",path:void 0,index:!0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-Gbk_i5Js.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-build":{id:"editor-tab-build",parentId:"routes/editor.entity.($sha)",path:"build",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-Gbk_i5Js.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-structure":{id:"editor-tab-structure",parentId:"routes/editor.entity.($sha)",path:"structure",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-Gbk_i5Js.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-history":{id:"editor-tab-history",parentId:"routes/editor.entity.($sha)",path:"history",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-Gbk_i5Js.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-settings":{id:"editor-tab-settings",parentId:"routes/editor.entity.($sha)",path:"settings",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-Gbk_i5Js.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-entity":{id:"editor-tab-entity",parentId:"routes/editor.entity.($sha)",path:"entity/:sha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-Gbk_i5Js.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-9032538f.js",version:"9032538f",sri:void 0},wk="build/client",vk="/",Nk={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,unstable_previewServerPrerendering:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},Sk=!0,Ck=!1,kk=[],_k={mode:"lazy",manifestPath:"/__manifest"},Ek="/",Ak={module:Ih},Pk={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:Vg},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,module:Xg},"routes/entity.$sha.scenarios.$scenarioId.dev":{id:"routes/entity.$sha.scenarios.$scenarioId.dev",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/dev",index:void 0,caseSensitive:void 0,module:M0},"routes/api.interactive-switch-scenario":{id:"routes/api.interactive-switch-scenario",parentId:"root",path:"api/interactive-switch-scenario",index:void 0,caseSensitive:void 0,module:py},"routes/api.editor-journal-screenshot":{id:"routes/api.editor-journal-screenshot",parentId:"root",path:"api/editor-journal-screenshot",index:void 0,caseSensitive:void 0,module:my},"routes/api.editor-save-scenario-data":{id:"routes/api.editor-save-scenario-data",parentId:"root",path:"api/editor-save-scenario-data",index:void 0,caseSensitive:void 0,module:gy},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,module:Oy},"routes/api.editor-register-scenario":{id:"routes/api.editor-register-scenario",parentId:"root",path:"api/editor-register-scenario",index:void 0,caseSensitive:void 0,module:ix},"routes/api.editor-scenario-coverage":{id:"routes/api.editor-scenario-coverage",parentId:"root",path:"api/editor-scenario-coverage",index:void 0,caseSensitive:void 0,module:ux},"routes/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,module:xx},"routes/api.editor-capture-scenario":{id:"routes/api.editor-capture-scenario",parentId:"root",path:"api/editor-capture-scenario",index:void 0,caseSensitive:void 0,module:vx},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,module:Sx},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,module:kx},"routes/api.editor-recapture-stale":{id:"routes/api.editor-recapture-stale",parentId:"root",path:"api/editor-recapture-stale",index:void 0,caseSensitive:void 0,module:Lx},"routes/api.editor-rename-scenario":{id:"routes/api.editor-rename-scenario",parentId:"root",path:"api/editor-rename-scenario",index:void 0,caseSensitive:void 0,module:zx},"routes/api.editor-save-seed-state":{id:"routes/api.editor-save-seed-state",parentId:"root",path:"api/editor-save-seed-state",index:void 0,caseSensitive:void 0,module:Wx},"routes/api.editor-scenario-prompt":{id:"routes/api.editor-scenario-prompt",parentId:"root",path:"api/editor-scenario-prompt",index:void 0,caseSensitive:void 0,module:Jx},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,module:Vx},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,module:nw},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,module:fw},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,module:yw},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,module:bw},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,module:vw},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,module:Sw},"routes/api.editor-verify-routes":{id:"routes/api.editor-verify-routes",parentId:"root",path:"api/editor-verify-routes",index:void 0,caseSensitive:void 0,module:kw},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,module:Aw},"routes/api.editor-project-info":{id:"routes/api.editor-project-info",parentId:"root",path:"api/editor-project-info",index:void 0,caseSensitive:void 0,module:Tw},"routes/api.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,module:zw},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,module:Gw},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:qw},"routes/api.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,module:iv},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:uv},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:kv},"routes/api.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,module:Pv},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:Mv},"routes/api.editor-file-diff":{id:"routes/api.editor-file-diff",parentId:"root",path:"api/editor-file-diff",index:void 0,caseSensitive:void 0,module:Iv},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,module:Dv},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:Lv},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:Yv},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:Uv},"routes/api.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,module:Vv},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:sN},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,module:oN},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,module:mN},"routes/api.editor-session":{id:"routes/api.editor-session",parentId:"root",path:"api/editor-session",index:void 0,caseSensitive:void 0,module:gN},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:vN},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:kN},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:PN},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:TN},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:VN},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,module:KN},"routes/api.editor-schema":{id:"routes/api.editor-schema",parentId:"root",path:"api/editor-schema",index:void 0,caseSensitive:void 0,module:XN},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,module:tS},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:rS},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:cS},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:uS},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:vS},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:CS},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,module:_S},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,module:jS},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:MS},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,module:FS},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:oC},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:cC},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:gC},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:xC},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:wC},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:IC},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:FC},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:BC},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:VC},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:KC},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:s1},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:P1},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:R1},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:U1},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:t2},"routes/editor.entity.($sha)":{id:"routes/editor.entity.($sha)",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,module:u5},"editor-tab-index":{id:"editor-tab-index",parentId:"routes/editor.entity.($sha)",path:void 0,index:!0,caseSensitive:void 0,module:Un},"editor-tab-build":{id:"editor-tab-build",parentId:"routes/editor.entity.($sha)",path:"build",index:void 0,caseSensitive:void 0,module:Un},"editor-tab-structure":{id:"editor-tab-structure",parentId:"routes/editor.entity.($sha)",path:"structure",index:void 0,caseSensitive:void 0,module:Un},"editor-tab-history":{id:"editor-tab-history",parentId:"routes/editor.entity.($sha)",path:"history",index:void 0,caseSensitive:void 0,module:Un},"editor-tab-settings":{id:"editor-tab-settings",parentId:"routes/editor.entity.($sha)",path:"settings",index:void 0,caseSensitive:void 0,module:Un},"editor-tab-entity":{id:"editor-tab-entity",parentId:"routes/editor.entity.($sha)",path:"entity/:sha",index:void 0,caseSensitive:void 0,module:Un}},jk=!1;export{_m as $,Nf as A,bf as B,kf as C,gf as D,Pe as E,Lm as F,Bm as G,An as H,ik as I,sm as J,om as K,im as L,lm as M,Jc as N,dm as O,um as P,Hc as Q,hm as R,mm as S,Pm as T,Vc as U,xm as V,wm as W,vm as X,Nm as Y,Cm as Z,km as _,Qh as a,Em as a0,nm as a1,rm as a2,Am as a3,Is as a4,Tm as a5,Mm as a6,$m as a7,Im as a8,Dm as a9,Ck as aA,kk as aB,_k as aC,Ek as aD,Ak as aE,Pk as aF,jk as aG,bk as aH,Rm as aa,pk as ab,Uo as ac,hk as ad,fk as ae,mk as af,uk as ag,xk as ah,De as ai,Ff as aj,Rf as ak,Gf as al,Lr as am,lk as an,Xc as ao,jf as ap,Tf as aq,dN as ar,yk as as,cn as at,ck as au,dk as av,wk as aw,vk as ax,Nk as ay,Sk as az,Cn as b,Sn as c,Ht as d,Or as e,Lo as f,qs as g,Uc as h,Kh as i,Xm as j,ef as k,an as l,Vt as m,zo as n,cf as o,Ds as p,Xe as q,qc as r,Qc as s,Yo as t,nn as u,Zc as v,nr as w,Gn as x,Qm as y,ll as z};