@codeyam/codeyam-cli 0.1.0-staging.e38f7bd → 0.1.0-staging.eb21b2f
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.
- package/analyzer-template/.build-info.json +8 -8
- package/analyzer-template/common/execAsync.ts +1 -1
- package/analyzer-template/log.txt +3 -3
- package/analyzer-template/package.json +21 -17
- package/analyzer-template/packages/ai/index.ts +21 -5
- package/analyzer-template/packages/ai/package.json +4 -4
- package/analyzer-template/packages/ai/src/lib/__mocks__/completionCall.ts +122 -0
- package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +228 -24
- package/analyzer-template/packages/ai/src/lib/astScopes/arrayDerivationDetector.ts +199 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +205 -10
- package/analyzer-template/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.ts +644 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +181 -23
- package/analyzer-template/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.ts +10 -17
- package/analyzer-template/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.ts +18 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.ts +38 -1
- package/analyzer-template/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.ts +181 -1
- package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +1619 -125
- package/analyzer-template/packages/ai/src/lib/astScopes/sharedPatterns.ts +28 -0
- package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +324 -5
- package/analyzer-template/packages/ai/src/lib/checkAllAttributes.ts +29 -10
- package/analyzer-template/packages/ai/src/lib/completionCall.ts +216 -36
- package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +2543 -399
- package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +21 -4
- package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +976 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +243 -77
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +16 -3
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +6 -4
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +71 -2
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +161 -19
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.ts +70 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +163 -14
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.ts +98 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.ts +179 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.ts +40 -30
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +441 -82
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.ts +129 -0
- package/analyzer-template/packages/ai/src/lib/dataStructureChunking.ts +183 -0
- package/analyzer-template/packages/ai/src/lib/deepEqual.ts +30 -0
- package/analyzer-template/packages/ai/src/lib/e2eDataTracking.ts +334 -0
- package/analyzer-template/packages/ai/src/lib/extractCriticalDataKeys.ts +120 -0
- package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +74 -7
- package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +89 -112
- package/analyzer-template/packages/ai/src/lib/generateEntityDataStructure.ts +63 -2
- package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +1419 -101
- package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +216 -109
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +710 -0
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +528 -0
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +2484 -0
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.ts +239 -0
- package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +143 -31
- package/analyzer-template/packages/ai/src/lib/guessScenarioDataFromDescription.ts +8 -2
- package/analyzer-template/packages/ai/src/lib/isolateScopes.ts +328 -7
- package/analyzer-template/packages/ai/src/lib/mergeJsonTypeDefinitions.ts +5 -0
- package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +111 -87
- package/analyzer-template/packages/ai/src/lib/promptGenerators/collapseNullableObjects.ts +118 -0
- package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +17 -7
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.ts +1 -1
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +32 -102
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChunkPrompt.ts +82 -0
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateCriticalKeysPrompt.ts +103 -0
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +110 -6
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +14 -53
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.ts +58 -0
- package/analyzer-template/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.ts +28 -2
- package/analyzer-template/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.ts +391 -0
- package/analyzer-template/packages/ai/src/lib/resolvePathToControllable.ts +824 -0
- package/analyzer-template/packages/ai/src/lib/splitOutsideParentheses.ts +5 -1
- package/analyzer-template/packages/ai/src/lib/validateExecutionFlowPaths.ts +531 -0
- package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +127 -3
- package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +121 -2
- package/analyzer-template/packages/analyze/index.ts +2 -0
- package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +79 -59
- package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +113 -26
- package/analyzer-template/packages/analyze/src/lib/analysisContext.ts +44 -4
- package/analyzer-template/packages/analyze/src/lib/asts/nodes/index.ts +1 -0
- package/analyzer-template/packages/analyze/src/lib/asts/nodes/isAsyncFunction.ts +67 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.ts +19 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.ts +19 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllExports.ts +11 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.ts +8 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.ts +49 -1
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.ts +2 -1
- package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +570 -180
- package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +54 -1
- package/analyzer-template/packages/analyze/src/lib/files/analyze/dependencyResolver.ts +6 -0
- package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +3 -0
- package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +4 -2
- package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +33 -10
- package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +31 -15
- package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +11 -7
- package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +11 -12
- package/analyzer-template/packages/analyze/src/lib/files/analyzeRemixRoute.ts +4 -5
- package/analyzer-template/packages/analyze/src/lib/files/enums/steps.ts +1 -1
- package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +22 -13
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/TransformationTracer.ts +1315 -0
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +313 -0
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.ts +102 -0
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +711 -78
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.ts +1 -1
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.ts +28 -62
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +550 -137
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +264 -0
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +78 -83
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +4 -8
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +1067 -167
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.ts +56 -11
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/propagateArrayItemSchemas.ts +474 -0
- package/analyzer-template/packages/analyze/src/lib/files/setImportedExports.ts +2 -1
- package/analyzer-template/packages/analyze/src/lib/index.ts +1 -0
- package/analyzer-template/packages/analyze/src/lib/utils/getFileByPath.ts +19 -0
- package/analyzer-template/packages/aws/codebuild/index.ts +1 -0
- package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts +11 -1
- package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts.map +1 -1
- package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js +29 -18
- package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js.map +1 -1
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts +2 -2
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts.map +1 -1
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js +2 -2
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js.map +1 -1
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts +8 -18
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts.map +1 -1
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js +17 -61
- package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js.map +1 -1
- package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts +15 -0
- package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts.map +1 -0
- package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js +31 -0
- package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js.map +1 -0
- package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.d.ts.map +1 -1
- package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js +8 -1
- package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js.map +1 -1
- package/analyzer-template/packages/aws/package.json +3 -3
- package/analyzer-template/packages/aws/s3/index.ts +1 -0
- package/analyzer-template/packages/aws/src/lib/codebuild/waitForBuild.ts +43 -19
- package/analyzer-template/packages/aws/src/lib/ecs/ecsDefineContainer.ts +3 -3
- package/analyzer-template/packages/aws/src/lib/ecs/ecsTaskFactory.ts +17 -69
- package/analyzer-template/packages/aws/src/lib/s3/checkS3ObjectExists.ts +47 -0
- package/analyzer-template/packages/aws/src/lib/s3/uploadFileToS3.ts +8 -1
- package/analyzer-template/packages/database/package.json +1 -1
- package/analyzer-template/packages/database/src/lib/analysisBranchToDb.ts +1 -1
- package/analyzer-template/packages/database/src/lib/analysisToDb.ts +1 -1
- package/analyzer-template/packages/database/src/lib/branchToDb.ts +1 -1
- package/analyzer-template/packages/database/src/lib/commitBranchToDb.ts +1 -1
- package/analyzer-template/packages/database/src/lib/commitToDb.ts +1 -1
- package/analyzer-template/packages/database/src/lib/fileToDb.ts +1 -1
- package/analyzer-template/packages/database/src/lib/kysely/db.ts +18 -5
- package/analyzer-template/packages/database/src/lib/kysely/tableRelations.ts +2 -2
- package/analyzer-template/packages/database/src/lib/kysely/tables/commitsTable.ts +6 -0
- package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +36 -9
- package/analyzer-template/packages/database/src/lib/kysely/tables/labsRequestsTable.ts +52 -0
- package/analyzer-template/packages/database/src/lib/loadAnalyses.ts +58 -1
- package/analyzer-template/packages/database/src/lib/loadAnalysis.ts +13 -0
- package/analyzer-template/packages/database/src/lib/loadBranch.ts +16 -1
- package/analyzer-template/packages/database/src/lib/loadCommit.ts +11 -0
- package/analyzer-template/packages/database/src/lib/loadCommits.ts +28 -0
- package/analyzer-template/packages/database/src/lib/loadEntities.ts +26 -3
- package/analyzer-template/packages/database/src/lib/loadEntityBranches.ts +12 -0
- package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +30 -5
- package/analyzer-template/packages/database/src/lib/projectToDb.ts +1 -1
- package/analyzer-template/packages/database/src/lib/saveFiles.ts +1 -1
- package/analyzer-template/packages/database/src/lib/scenarioToDb.ts +1 -1
- package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +7 -14
- package/analyzer-template/packages/database/src/lib/userScenarioToDb.ts +1 -1
- package/analyzer-template/packages/generate/index.ts +3 -0
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.ts +17 -1
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +193 -0
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.ts +73 -0
- package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +9 -4
- package/analyzer-template/packages/generate/src/lib/deepMerge.ts +26 -1
- package/analyzer-template/packages/generate/src/lib/directExecutionScript.ts +17 -2
- package/analyzer-template/packages/generate/src/lib/getComponentScenarioPath.ts +8 -3
- package/analyzer-template/packages/generate/src/lib/scenarioComponentForServer.ts +114 -0
- package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +4 -2
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +13 -3
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelations.d.ts +2 -2
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts +1 -11
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js +3 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +30 -7
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts +23 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +2 -6
- package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts +2 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js +45 -2
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js +8 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js +11 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js +7 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts +3 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js +22 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts +3 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +23 -4
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js +9 -0
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +23 -5
- package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts +2 -2
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +5 -4
- package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/index.d.ts +3 -0
- package/analyzer-template/packages/github/dist/generate/index.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/index.js +3 -0
- package/analyzer-template/packages/github/dist/generate/index.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts +9 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts +20 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
- package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js +27 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.js +10 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.js +7 -3
- package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.js.map +1 -1
- package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts +8 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts.map +1 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js +89 -0
- package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js.map +1 -0
- package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js +10 -0
- package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js.map +1 -1
- package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js +3 -0
- package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js.map +1 -1
- package/analyzer-template/packages/github/dist/types/index.d.ts +2 -2
- package/analyzer-template/packages/github/dist/types/index.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/index.js.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts +87 -13
- package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts +2 -0
- package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts +2 -0
- package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts +7 -0
- package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +11 -6
- package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +199 -3
- package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
- package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts +2 -0
- package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.js +26 -2
- package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
- package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts +9 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js +29 -3
- package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js.map +1 -1
- package/analyzer-template/packages/github/package.json +1 -1
- package/analyzer-template/packages/github/src/lib/loadOrCreateCommit.ts +14 -0
- package/analyzer-template/packages/github/src/lib/syncPrimaryBranch.ts +2 -0
- package/analyzer-template/packages/process/index.ts +2 -0
- package/analyzer-template/packages/process/package.json +12 -0
- package/analyzer-template/packages/process/tsconfig.json +8 -0
- package/analyzer-template/packages/types/index.ts +5 -0
- package/analyzer-template/packages/types/src/types/Analysis.ts +104 -13
- package/analyzer-template/packages/types/src/types/Commit.ts +2 -0
- package/analyzer-template/packages/types/src/types/Entity.ts +2 -0
- package/analyzer-template/packages/types/src/types/ProjectMetadata.ts +7 -0
- package/analyzer-template/packages/types/src/types/Scenario.ts +11 -10
- package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +228 -3
- package/analyzer-template/packages/types/src/types/ScopeAnalysis.ts +6 -1
- package/analyzer-template/packages/types/src/types/StatementInfo.ts +2 -0
- package/analyzer-template/packages/ui-components/package.json +4 -4
- package/analyzer-template/packages/ui-components/src/components/ScenarioDetailInteractiveView.tsx +23 -7
- package/analyzer-template/packages/utils/dist/types/index.d.ts +2 -2
- package/analyzer-template/packages/utils/dist/types/index.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/index.js.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts +87 -13
- package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts +2 -0
- package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts +2 -0
- package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts +7 -0
- package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +11 -6
- package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +199 -3
- package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
- package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts +2 -0
- package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.js +26 -2
- package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js +93 -2
- package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
- package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts +9 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js +29 -3
- package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js.map +1 -1
- package/analyzer-template/packages/utils/src/lib/applyUniversalMocks.ts +28 -2
- package/analyzer-template/packages/utils/src/lib/fs/rsyncCopy.ts +108 -2
- package/analyzer-template/packages/utils/src/lib/lightweightEntityExtractor.ts +27 -0
- package/analyzer-template/packages/utils/src/lib/safeFileName.ts +48 -3
- package/analyzer-template/playwright/capture.ts +57 -26
- package/analyzer-template/playwright/captureStatic.ts +1 -1
- package/analyzer-template/playwright/getCodeYamInfo.ts +12 -7
- package/analyzer-template/playwright/takeElementScreenshot.ts +26 -11
- package/analyzer-template/playwright/takeScreenshot.ts +15 -9
- package/analyzer-template/playwright/waitForServer.ts +21 -6
- package/analyzer-template/project/TESTING.md +83 -0
- package/analyzer-template/project/analyzeBaselineCommit.ts +9 -0
- package/analyzer-template/project/analyzeBranchCommit.ts +4 -0
- package/analyzer-template/project/analyzeFileEntities.ts +4 -0
- package/analyzer-template/project/analyzeRegularCommit.ts +9 -0
- package/analyzer-template/project/captureLibraryFunctionDirect.ts +29 -26
- package/analyzer-template/project/constructMockCode.ts +1319 -158
- package/analyzer-template/project/controller/startController.ts +16 -1
- package/analyzer-template/project/createEntitiesAndSortFiles.ts +83 -0
- package/analyzer-template/project/executeLibraryFunctionDirect.ts +7 -3
- package/analyzer-template/project/loadReadyToBeCaptured.ts +82 -42
- package/analyzer-template/project/mocks/analyzeFileMock.ts +8 -7
- package/analyzer-template/project/orchestrateCapture/AwsCaptureTaskRunner.ts +12 -4
- package/analyzer-template/project/orchestrateCapture/KyselyAnalysisLoader.ts +13 -9
- package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +93 -42
- package/analyzer-template/project/orchestrateCapture/taskRunner.ts +4 -2
- package/analyzer-template/project/orchestrateCapture.ts +88 -12
- package/analyzer-template/project/reconcileMockDataKeys.ts +245 -2
- package/analyzer-template/project/runAnalysis.ts +11 -0
- package/analyzer-template/project/runMultiScenarioServer.ts +11 -10
- package/analyzer-template/project/serverOnlyModules.ts +413 -0
- package/analyzer-template/project/start.ts +72 -19
- package/analyzer-template/project/startScenarioCapture.ts +79 -41
- package/analyzer-template/project/writeMockDataTsx.ts +466 -73
- package/analyzer-template/project/writeScenarioClientWrapper.ts +21 -0
- package/analyzer-template/project/writeScenarioComponents.ts +1447 -214
- package/analyzer-template/project/writeScenarioFiles.ts +26 -0
- package/analyzer-template/project/writeSimpleRoot.ts +56 -22
- package/analyzer-template/project/writeUniversalMocks.ts +32 -11
- package/analyzer-template/scripts/comboWorkerLoop.cjs +99 -50
- package/analyzer-template/scripts/defaultCmd.sh +9 -0
- package/analyzer-template/tsconfig.json +2 -1
- package/background/src/lib/local/createLocalAnalyzer.js +2 -30
- package/background/src/lib/local/createLocalAnalyzer.js.map +1 -1
- package/background/src/lib/local/execAsync.js +1 -1
- package/background/src/lib/local/execAsync.js.map +1 -1
- package/background/src/lib/virtualized/common/execAsync.js +1 -1
- package/background/src/lib/virtualized/common/execAsync.js.map +1 -1
- package/background/src/lib/virtualized/project/analyzeBaselineCommit.js +7 -1
- package/background/src/lib/virtualized/project/analyzeBaselineCommit.js.map +1 -1
- package/background/src/lib/virtualized/project/analyzeBranchCommit.js +2 -1
- package/background/src/lib/virtualized/project/analyzeBranchCommit.js.map +1 -1
- package/background/src/lib/virtualized/project/analyzeFileEntities.js +2 -1
- package/background/src/lib/virtualized/project/analyzeFileEntities.js.map +1 -1
- package/background/src/lib/virtualized/project/analyzeRegularCommit.js +7 -1
- package/background/src/lib/virtualized/project/analyzeRegularCommit.js.map +1 -1
- package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js +3 -3
- package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js.map +1 -1
- package/background/src/lib/virtualized/project/constructMockCode.js +1171 -120
- package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
- package/background/src/lib/virtualized/project/controller/startController.js +11 -1
- package/background/src/lib/virtualized/project/controller/startController.js.map +1 -1
- package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js +73 -1
- package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js.map +1 -1
- package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js +6 -3
- package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js.map +1 -1
- package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js +34 -9
- package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js.map +1 -1
- package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js +7 -7
- package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js.map +1 -1
- package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js +2 -2
- package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js.map +1 -1
- package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js +12 -6
- package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js.map +1 -1
- package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js +73 -36
- package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
- package/background/src/lib/virtualized/project/orchestrateCapture.js +72 -13
- package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
- package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +204 -2
- package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
- package/background/src/lib/virtualized/project/runAnalysis.js +9 -0
- package/background/src/lib/virtualized/project/runAnalysis.js.map +1 -1
- package/background/src/lib/virtualized/project/runMultiScenarioServer.js +11 -9
- package/background/src/lib/virtualized/project/runMultiScenarioServer.js.map +1 -1
- package/background/src/lib/virtualized/project/serverOnlyModules.js +338 -0
- package/background/src/lib/virtualized/project/serverOnlyModules.js.map +1 -0
- package/background/src/lib/virtualized/project/start.js +62 -19
- package/background/src/lib/virtualized/project/start.js.map +1 -1
- package/background/src/lib/virtualized/project/startScenarioCapture.js +61 -31
- package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
- package/background/src/lib/virtualized/project/writeMockDataTsx.js +404 -62
- package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
- package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js +15 -0
- package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js.map +1 -0
- package/background/src/lib/virtualized/project/writeScenarioComponents.js +1066 -146
- package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
- package/background/src/lib/virtualized/project/writeScenarioFiles.js +19 -0
- package/background/src/lib/virtualized/project/writeScenarioFiles.js.map +1 -1
- package/background/src/lib/virtualized/project/writeSimpleRoot.js +57 -20
- package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
- package/background/src/lib/virtualized/project/writeUniversalMocks.js +27 -12
- package/background/src/lib/virtualized/project/writeUniversalMocks.js.map +1 -1
- package/codeyam-cli/scripts/apply-setup.js +180 -0
- package/codeyam-cli/scripts/apply-setup.js.map +1 -1
- package/codeyam-cli/src/cli.js +11 -1
- package/codeyam-cli/src/cli.js.map +1 -1
- package/codeyam-cli/src/codeyam-cli.js +18 -2
- package/codeyam-cli/src/codeyam-cli.js.map +1 -1
- package/codeyam-cli/src/commands/analyze.js +5 -3
- package/codeyam-cli/src/commands/analyze.js.map +1 -1
- package/codeyam-cli/src/commands/baseline.js +176 -0
- package/codeyam-cli/src/commands/baseline.js.map +1 -0
- package/codeyam-cli/src/commands/debug.js +44 -18
- package/codeyam-cli/src/commands/debug.js.map +1 -1
- package/codeyam-cli/src/commands/default.js +30 -34
- package/codeyam-cli/src/commands/default.js.map +1 -1
- package/codeyam-cli/src/commands/detect-universal-mocks.js +2 -0
- package/codeyam-cli/src/commands/detect-universal-mocks.js.map +1 -1
- package/codeyam-cli/src/commands/init.js +49 -257
- package/codeyam-cli/src/commands/init.js.map +1 -1
- package/codeyam-cli/src/commands/memory.js +307 -0
- package/codeyam-cli/src/commands/memory.js.map +1 -0
- package/codeyam-cli/src/commands/recapture.js +228 -0
- package/codeyam-cli/src/commands/recapture.js.map +1 -0
- package/codeyam-cli/src/commands/report.js +72 -24
- package/codeyam-cli/src/commands/report.js.map +1 -1
- package/codeyam-cli/src/commands/setup-sandbox.js +2 -0
- package/codeyam-cli/src/commands/setup-sandbox.js.map +1 -1
- package/codeyam-cli/src/commands/setup-simulations.js +284 -0
- package/codeyam-cli/src/commands/setup-simulations.js.map +1 -0
- package/codeyam-cli/src/commands/start.js +8 -12
- package/codeyam-cli/src/commands/start.js.map +1 -1
- package/codeyam-cli/src/commands/status.js +23 -1
- package/codeyam-cli/src/commands/status.js.map +1 -1
- package/codeyam-cli/src/commands/test-startup.js +3 -1
- package/codeyam-cli/src/commands/test-startup.js.map +1 -1
- package/codeyam-cli/src/commands/verify.js +14 -2
- package/codeyam-cli/src/commands/verify.js.map +1 -1
- package/codeyam-cli/src/commands/wipe.js +108 -0
- package/codeyam-cli/src/commands/wipe.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js +179 -0
- package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js +81 -0
- package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +128 -82
- package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
- package/codeyam-cli/src/utils/analysisRunner.js +29 -15
- package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
- package/codeyam-cli/src/utils/analyzer.js +7 -0
- package/codeyam-cli/src/utils/analyzer.js.map +1 -1
- package/codeyam-cli/src/utils/backgroundServer.js +104 -23
- package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
- package/codeyam-cli/src/utils/database.js +91 -5
- package/codeyam-cli/src/utils/database.js.map +1 -1
- package/codeyam-cli/src/utils/generateReport.js +253 -106
- package/codeyam-cli/src/utils/generateReport.js.map +1 -1
- package/codeyam-cli/src/utils/git.js +79 -0
- package/codeyam-cli/src/utils/git.js.map +1 -0
- package/codeyam-cli/src/utils/install-skills.js +76 -42
- package/codeyam-cli/src/utils/install-skills.js.map +1 -1
- package/codeyam-cli/src/utils/labsAutoCheck.js +19 -0
- package/codeyam-cli/src/utils/labsAutoCheck.js.map +1 -0
- package/codeyam-cli/src/utils/npmVersionCheck.js +76 -0
- package/codeyam-cli/src/utils/npmVersionCheck.js.map +1 -0
- package/codeyam-cli/src/utils/progress.js +7 -0
- package/codeyam-cli/src/utils/progress.js.map +1 -1
- package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +38 -0
- package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
- package/codeyam-cli/src/utils/queue/job.js +249 -16
- package/codeyam-cli/src/utils/queue/job.js.map +1 -1
- package/codeyam-cli/src/utils/queue/manager.js +103 -7
- package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
- package/codeyam-cli/src/utils/queue/persistence.js.map +1 -1
- package/codeyam-cli/src/utils/requireSimulations.js +10 -0
- package/codeyam-cli/src/utils/requireSimulations.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js +82 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js +230 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js +67 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js +105 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js +34 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js +162 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js +75 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js +378 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js +116 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js +127 -0
- package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js +50 -0
- package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js +116 -0
- package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/index.js +5 -0
- package/codeyam-cli/src/utils/ruleReflection/index.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js +44 -0
- package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js +85 -0
- package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js.map +1 -0
- package/codeyam-cli/src/utils/ruleReflection/types.js +5 -0
- package/codeyam-cli/src/utils/ruleReflection/types.js.map +1 -0
- package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js +293 -0
- package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js.map +1 -0
- package/codeyam-cli/src/utils/rules/index.js +6 -0
- package/codeyam-cli/src/utils/rules/index.js.map +1 -0
- package/codeyam-cli/src/utils/rules/parser.js +83 -0
- package/codeyam-cli/src/utils/rules/parser.js.map +1 -0
- package/codeyam-cli/src/utils/rules/pathMatcher.js +18 -0
- package/codeyam-cli/src/utils/rules/pathMatcher.js.map +1 -0
- package/codeyam-cli/src/utils/rules/ruleState.js +150 -0
- package/codeyam-cli/src/utils/rules/ruleState.js.map +1 -0
- package/codeyam-cli/src/utils/rules/staleness.js +137 -0
- package/codeyam-cli/src/utils/rules/staleness.js.map +1 -0
- package/codeyam-cli/src/utils/serverState.js +37 -10
- package/codeyam-cli/src/utils/serverState.js.map +1 -1
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +21 -42
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
- package/codeyam-cli/src/utils/versionInfo.js +46 -15
- package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
- package/codeyam-cli/src/utils/wipe.js +128 -0
- package/codeyam-cli/src/utils/wipe.js.map +1 -0
- package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js +66 -0
- package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js.map +1 -0
- package/codeyam-cli/src/webserver/app/lib/database.js +118 -6
- package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
- package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
- package/codeyam-cli/src/webserver/backgroundServer.js +55 -10
- package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
- package/codeyam-cli/src/webserver/bootstrap.js +60 -0
- package/codeyam-cli/src/webserver/bootstrap.js.map +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/CopyButton-jNYXRRNI.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/EntityItem-bwuHPyTa.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-kykTbcnD.js → EntityTypeBadge-CvzqMxcu.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-BH0XDim7.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-EhOseatT.js +34 -0
- package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-yjIHlOGa.js +25 -0
- package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-Cq5o8jL4.js +3 -0
- package/codeyam-cli/src/webserver/build/client/assets/LoadingDots-BvMu2i-g.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/LogViewer-kgBTLoJD.js +3 -0
- package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-BzPgx-xO.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-CwZrv-Ok.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-BX2Ny2Qj.js +10 -0
- package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-C06nsHKY.js → TruncatedFilePath-CDpEprKa.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/_index-BRx8ZGZo.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-4S4yPfFw.js +27 -0
- package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-DHKuQSmR.js +17 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.agent-transcripts-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.health-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.labs-unlock-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.memory-profile-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.restart-server-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.save-fixture-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/book-open-D4IPYH_y.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/chevron-down-CG65viiV.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/chunk-JZWAC4HX-DB3aFuEO.js +51 -0
- package/codeyam-cli/src/webserver/build/client/assets/circle-check-igfMr5DY.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/copy-Coc4o_8c.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-D1zB-pYc.js +21 -0
- package/codeyam-cli/src/webserver/build/client/assets/{cy-logo-cli-C1gnJVOL.svg → cy-logo-cli-CCKUIm0S.svg} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-DcX-ZS3p.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/dev.empty-JTAjQ54M.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-CYqBrC9s.js → entity._sha._-B0h9AqE6.js} +22 -15
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DjLxr2JB.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-CtYowLOt.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-PePWg17F.js +5 -0
- package/codeyam-cli/src/webserver/build/client/assets/entry.client-I-Wo99C_.js +29 -0
- package/codeyam-cli/src/webserver/build/client/assets/executionFlowCoverage-BWhdfn70.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-9sMMAiWJ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/files-Co65J0s3.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/git-BdHOxVfg.js +15 -0
- package/codeyam-cli/src/webserver/build/client/assets/globals-CCgBKWy4.css +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-fmIEn3Bc.js +9 -0
- package/codeyam-cli/src/webserver/build/client/assets/index-CUM5iXwc.js +9 -0
- package/codeyam-cli/src/webserver/build/client/assets/index-_417gcQW.js +3 -0
- package/codeyam-cli/src/webserver/build/client/assets/labs-BK0C1H1T.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/loader-circle-TzRHMVog.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/manifest-390cb8fa.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/memory-CzZySbBE.js +78 -0
- package/codeyam-cli/src/webserver/build/client/assets/pause-hjzB7t2z.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/preload-helper-ckwbz45p.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/root-DnbDhvTU.js +62 -0
- package/codeyam-cli/src/webserver/build/client/assets/scenarioStatus-B_8jpV3e.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/search-DcAwD_Ln.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/settings-CclxrcPK.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/simulations-DVNJVQgD.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/terminal-DbEAHMbA.js +11 -0
- package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-CAD5b1o_.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-BqgrAzs3.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-Blr5oZDE.js → useLastLogLine-DAFqfEDH.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/useReportContext-DZlYx2c4.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{useToast-Bbf4Hokd.js → useToast-ihdMtlf6.js} +1 -1
- package/codeyam-cli/src/webserver/build/server/assets/index-CXfuiwt3.js +1 -0
- package/codeyam-cli/src/webserver/build/server/assets/server-build-BSvme_Ao.js +259 -0
- package/codeyam-cli/src/webserver/build/server/index.js +1 -1
- package/codeyam-cli/src/webserver/build-info.json +5 -5
- package/codeyam-cli/src/webserver/devServer.js +1 -3
- package/codeyam-cli/src/webserver/devServer.js.map +1 -1
- package/codeyam-cli/src/webserver/server.js +35 -25
- package/codeyam-cli/src/webserver/server.js.map +1 -1
- package/codeyam-cli/templates/{codeyam-debug-skill.md → codeyam-debug.md} +48 -4
- package/codeyam-cli/templates/codeyam-diagnose.md +481 -0
- package/codeyam-cli/templates/codeyam-memory-hook.sh +199 -0
- package/codeyam-cli/templates/codeyam-memory.md +396 -0
- package/codeyam-cli/templates/codeyam-new-rule.md +13 -0
- package/codeyam-cli/templates/{codeyam-setup-skill.md → codeyam-setup.md} +151 -4
- package/codeyam-cli/templates/{codeyam-sim-skill.md → codeyam-sim.md} +1 -1
- package/codeyam-cli/templates/{codeyam-test-skill.md → codeyam-test.md} +1 -1
- package/codeyam-cli/templates/{codeyam-verify-skill.md → codeyam-verify.md} +1 -1
- package/codeyam-cli/templates/rule-notification-hook.py +56 -0
- package/codeyam-cli/templates/rule-reflection-hook.py +627 -0
- package/codeyam-cli/templates/rules-instructions.md +132 -0
- package/package.json +25 -22
- package/packages/ai/index.js +8 -6
- package/packages/ai/index.js.map +1 -1
- package/packages/ai/src/lib/analyzeScope.js +181 -13
- package/packages/ai/src/lib/analyzeScope.js.map +1 -1
- package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js +150 -0
- package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js.map +1 -0
- package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +154 -9
- package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
- package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js +435 -0
- package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js.map +1 -0
- package/packages/ai/src/lib/astScopes/methodSemantics.js +138 -23
- package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
- package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js +10 -14
- package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js.map +1 -1
- package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js +8 -0
- package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js.map +1 -1
- package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js +23 -0
- package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js.map +1 -1
- package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js +138 -1
- package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js.map +1 -1
- package/packages/ai/src/lib/astScopes/processExpression.js +1235 -104
- package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
- package/packages/ai/src/lib/astScopes/sharedPatterns.js +25 -0
- package/packages/ai/src/lib/astScopes/sharedPatterns.js.map +1 -1
- package/packages/ai/src/lib/checkAllAttributes.js +24 -9
- package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
- package/packages/ai/src/lib/completionCall.js +178 -31
- package/packages/ai/src/lib/completionCall.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +1961 -224
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +19 -4
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +661 -0
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +180 -56
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +13 -3
- package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +6 -4
- package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +66 -2
- package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +139 -13
- package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js +63 -0
- package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +142 -12
- package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js +86 -0
- package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js +173 -0
- package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js +37 -20
- package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +371 -73
- package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js +107 -0
- package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js.map +1 -0
- package/packages/ai/src/lib/dataStructureChunking.js +130 -0
- package/packages/ai/src/lib/dataStructureChunking.js.map +1 -0
- package/packages/ai/src/lib/deepEqual.js +32 -0
- package/packages/ai/src/lib/deepEqual.js.map +1 -0
- package/packages/ai/src/lib/e2eDataTracking.js +241 -0
- package/packages/ai/src/lib/e2eDataTracking.js.map +1 -0
- package/packages/ai/src/lib/extractCriticalDataKeys.js +96 -0
- package/packages/ai/src/lib/extractCriticalDataKeys.js.map +1 -0
- package/packages/ai/src/lib/generateChangesEntityScenarioData.js +62 -5
- package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
- package/packages/ai/src/lib/generateChangesEntityScenarios.js +81 -90
- package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
- package/packages/ai/src/lib/generateEntityDataStructure.js +50 -1
- package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
- package/packages/ai/src/lib/generateEntityScenarioData.js +1127 -91
- package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
- package/packages/ai/src/lib/generateEntityScenarios.js +193 -83
- package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
- package/packages/ai/src/lib/generateExecutionFlows.js +495 -0
- package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -0
- package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js +380 -0
- package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js.map +1 -0
- package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +1807 -0
- package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -0
- package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js +194 -0
- package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js.map +1 -0
- package/packages/ai/src/lib/getConditionalUsagesFromCode.js +84 -14
- package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
- package/packages/ai/src/lib/guessScenarioDataFromDescription.js +2 -1
- package/packages/ai/src/lib/guessScenarioDataFromDescription.js.map +1 -1
- package/packages/ai/src/lib/isolateScopes.js +270 -7
- package/packages/ai/src/lib/isolateScopes.js.map +1 -1
- package/packages/ai/src/lib/mergeJsonTypeDefinitions.js +5 -0
- package/packages/ai/src/lib/mergeJsonTypeDefinitions.js.map +1 -1
- package/packages/ai/src/lib/mergeStatements.js +88 -46
- package/packages/ai/src/lib/mergeStatements.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js +97 -0
- package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js.map +1 -0
- package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +16 -4
- package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js +1 -1
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +21 -64
- package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js +54 -0
- package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js.map +1 -0
- package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +83 -6
- package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +10 -34
- package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js +45 -0
- package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js.map +1 -0
- package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js +16 -3
- package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js +335 -0
- package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js.map +1 -0
- package/packages/ai/src/lib/resolvePathToControllable.js +677 -0
- package/packages/ai/src/lib/resolvePathToControllable.js.map +1 -0
- package/packages/ai/src/lib/splitOutsideParentheses.js +3 -1
- package/packages/ai/src/lib/splitOutsideParentheses.js.map +1 -1
- package/packages/ai/src/lib/worker/SerializableDataStructure.js +29 -0
- package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
- package/packages/ai/src/lib/worker/analyzeScopeWorker.js +98 -1
- package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
- package/packages/analyze/index.js +1 -0
- package/packages/analyze/index.js.map +1 -1
- package/packages/analyze/src/lib/FileAnalyzer.js +75 -36
- package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
- package/packages/analyze/src/lib/ProjectAnalyzer.js +96 -26
- package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
- package/packages/analyze/src/lib/analysisContext.js +30 -5
- package/packages/analyze/src/lib/analysisContext.js.map +1 -1
- package/packages/analyze/src/lib/asts/nodes/index.js +1 -0
- package/packages/analyze/src/lib/asts/nodes/index.js.map +1 -1
- package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js +52 -0
- package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js.map +1 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js +14 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js +14 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js +6 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js +6 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js +39 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js +2 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +428 -123
- package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +42 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/dependencyResolver.js +5 -0
- package/packages/analyze/src/lib/files/analyze/dependencyResolver.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +2 -0
- package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +2 -1
- package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +31 -10
- package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeChange.js +21 -11
- package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeEntity.js +9 -8
- package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeInitial.js +9 -10
- package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeRemixRoute.js +3 -2
- package/packages/analyze/src/lib/files/analyzeRemixRoute.js.map +1 -1
- package/packages/analyze/src/lib/files/enums/steps.js +1 -1
- package/packages/analyze/src/lib/files/enums/steps.js.map +1 -1
- package/packages/analyze/src/lib/files/getImportedExports.js +17 -8
- package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js +880 -0
- package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js.map +1 -0
- package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +255 -0
- package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -0
- package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js +85 -0
- package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js.map +1 -0
- package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +550 -62
- package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js +29 -34
- package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +404 -85
- package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +144 -0
- package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -0
- package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +56 -69
- package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +4 -8
- package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +875 -141
- package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js +46 -9
- package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js.map +1 -1
- package/packages/analyze/src/lib/files/setImportedExports.js +2 -1
- package/packages/analyze/src/lib/files/setImportedExports.js.map +1 -1
- package/packages/analyze/src/lib/index.js +1 -0
- package/packages/analyze/src/lib/index.js.map +1 -1
- package/packages/analyze/src/lib/utils/getFileByPath.js +12 -0
- package/packages/analyze/src/lib/utils/getFileByPath.js.map +1 -0
- package/packages/aws/src/lib/ecs/ecsDefineContainer.js +2 -2
- package/packages/aws/src/lib/ecs/ecsDefineContainer.js.map +1 -1
- package/packages/aws/src/lib/ecs/ecsTaskFactory.js +17 -61
- package/packages/aws/src/lib/ecs/ecsTaskFactory.js.map +1 -1
- package/packages/database/src/lib/analysisBranchToDb.js +1 -1
- package/packages/database/src/lib/analysisBranchToDb.js.map +1 -1
- package/packages/database/src/lib/analysisToDb.js +1 -1
- package/packages/database/src/lib/analysisToDb.js.map +1 -1
- package/packages/database/src/lib/branchToDb.js +1 -1
- package/packages/database/src/lib/branchToDb.js.map +1 -1
- package/packages/database/src/lib/commitBranchToDb.js +1 -1
- package/packages/database/src/lib/commitBranchToDb.js.map +1 -1
- package/packages/database/src/lib/commitToDb.js +1 -1
- package/packages/database/src/lib/commitToDb.js.map +1 -1
- package/packages/database/src/lib/fileToDb.js +1 -1
- package/packages/database/src/lib/fileToDb.js.map +1 -1
- package/packages/database/src/lib/kysely/db.js +13 -3
- package/packages/database/src/lib/kysely/db.js.map +1 -1
- package/packages/database/src/lib/kysely/tables/commitsTable.js +3 -0
- package/packages/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
- package/packages/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
- package/packages/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
- package/packages/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
- package/packages/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
- package/packages/database/src/lib/loadAnalyses.js +45 -2
- package/packages/database/src/lib/loadAnalyses.js.map +1 -1
- package/packages/database/src/lib/loadAnalysis.js +8 -0
- package/packages/database/src/lib/loadAnalysis.js.map +1 -1
- package/packages/database/src/lib/loadBranch.js +11 -1
- package/packages/database/src/lib/loadBranch.js.map +1 -1
- package/packages/database/src/lib/loadCommit.js +7 -0
- package/packages/database/src/lib/loadCommit.js.map +1 -1
- package/packages/database/src/lib/loadCommits.js +22 -1
- package/packages/database/src/lib/loadCommits.js.map +1 -1
- package/packages/database/src/lib/loadEntities.js +23 -4
- package/packages/database/src/lib/loadEntities.js.map +1 -1
- package/packages/database/src/lib/loadEntityBranches.js +9 -0
- package/packages/database/src/lib/loadEntityBranches.js.map +1 -1
- package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +23 -5
- package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
- package/packages/database/src/lib/projectToDb.js +1 -1
- package/packages/database/src/lib/projectToDb.js.map +1 -1
- package/packages/database/src/lib/saveFiles.js +1 -1
- package/packages/database/src/lib/saveFiles.js.map +1 -1
- package/packages/database/src/lib/scenarioToDb.js +1 -1
- package/packages/database/src/lib/scenarioToDb.js.map +1 -1
- package/packages/database/src/lib/updateCommitMetadata.js +5 -4
- package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
- package/packages/generate/index.js +3 -0
- package/packages/generate/index.js.map +1 -1
- package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
- package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
- package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
- package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
- package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
- package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
- package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
- package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
- package/packages/generate/src/lib/deepMerge.js +27 -1
- package/packages/generate/src/lib/deepMerge.js.map +1 -1
- package/packages/generate/src/lib/directExecutionScript.js +10 -1
- package/packages/generate/src/lib/directExecutionScript.js.map +1 -1
- package/packages/generate/src/lib/getComponentScenarioPath.js +7 -3
- package/packages/generate/src/lib/getComponentScenarioPath.js.map +1 -1
- package/packages/generate/src/lib/scenarioComponentForServer.js +89 -0
- package/packages/generate/src/lib/scenarioComponentForServer.js.map +1 -0
- package/packages/github/src/lib/loadOrCreateCommit.js +10 -0
- package/packages/github/src/lib/loadOrCreateCommit.js.map +1 -1
- package/packages/github/src/lib/syncPrimaryBranch.js +3 -0
- package/packages/github/src/lib/syncPrimaryBranch.js.map +1 -1
- package/packages/process/index.js +3 -0
- package/packages/process/index.js.map +1 -0
- package/packages/process/src/GlobalProcessManager.js.map +1 -0
- package/{background/src/lib/process → packages/process/src}/ProcessManager.js +1 -1
- package/packages/process/src/ProcessManager.js.map +1 -0
- package/packages/process/src/index.js.map +1 -0
- package/packages/process/src/managedExecAsync.js.map +1 -0
- package/packages/types/index.js.map +1 -1
- package/packages/utils/src/lib/applyUniversalMocks.js +26 -2
- package/packages/utils/src/lib/applyUniversalMocks.js.map +1 -1
- package/packages/utils/src/lib/fs/rsyncCopy.js +93 -2
- package/packages/utils/src/lib/fs/rsyncCopy.js.map +1 -1
- package/packages/utils/src/lib/lightweightEntityExtractor.js +25 -0
- package/packages/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
- package/packages/utils/src/lib/safeFileName.js +29 -3
- package/packages/utils/src/lib/safeFileName.js.map +1 -1
- package/scripts/finalize-analyzer.cjs +8 -74
- package/analyzer-template/packages/ai/src/lib/findMatchingAttribute.ts +0 -102
- package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +0 -197
- package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +0 -271
- package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +0 -294
- package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.ts +0 -67
- package/analyzer-template/packages/ai/src/lib/transformMockDataToMatchSchema.ts +0 -156
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +0 -115
- package/analyzer-template/process/INTEGRATION_COMPLETE.md +0 -333
- package/analyzer-template/process/INTEGRATION_EXAMPLE.md +0 -525
- package/analyzer-template/process/README.md +0 -507
- package/background/src/lib/process/GlobalProcessManager.js.map +0 -1
- package/background/src/lib/process/ProcessManager.js.map +0 -1
- package/background/src/lib/process/index.js.map +0 -1
- package/background/src/lib/process/managedExecAsync.js.map +0 -1
- package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +0 -238
- package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/EntityItem-D4htqD-x.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-Catz6XEN.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-TlHocYno.js +0 -26
- package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-CVMmGuIc.js +0 -3
- package/codeyam-cli/src/webserver/build/client/assets/LogViewer-JkfQ-VaI.js +0 -3
- package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-CVZ0H4BL.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-BrMAP1nP.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-CJhE4cCv.js +0 -5
- package/codeyam-cli/src/webserver/build/client/assets/_index-faVIcr_i.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-CLMa2sgx.js +0 -7
- package/codeyam-cli/src/webserver/build/client/assets/chevron-down-DwYjrK_h.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/chunk-WWGJGFF6-CgXbbZRx.js +0 -26
- package/codeyam-cli/src/webserver/build/client/assets/circle-check-B2oHQ-zo.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-BBYuR56H.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/dev.empty-CT0Q5lVu.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-Bj5GHkhb.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-eW5z9AyZ.js +0 -5
- package/codeyam-cli/src/webserver/build/client/assets/entry.client-B9tSboXM.js +0 -5
- package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-CmO-EZAB.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/files-DLinnTOx.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/git-CIxwBQvb.js +0 -12
- package/codeyam-cli/src/webserver/build/client/assets/globals-xPz593l2.css +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-XQCGvadH.js +0 -5
- package/codeyam-cli/src/webserver/build/client/assets/index-_LjBsTxX.js +0 -8
- package/codeyam-cli/src/webserver/build/client/assets/loader-circle-D_EGChhq.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/manifest-ca438c41.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/root-CHHYHuzL.js +0 -16
- package/codeyam-cli/src/webserver/build/client/assets/search-DY8yoDpH.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/server-build-CMKNK2uU.css +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/settings-BT6wVHd5.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/simulations-gv3H7JV7.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-BthANBVv.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/useReportContext-CANr3QJ5.js +0 -1
- package/codeyam-cli/src/webserver/build/server/assets/index-BtBPtyHx.js +0 -1
- package/codeyam-cli/src/webserver/build/server/assets/server-build-N2cTnejq.js +0 -166
- package/codeyam-cli/templates/debug-command.md +0 -141
- package/packages/ai/src/lib/findMatchingAttribute.js +0 -77
- package/packages/ai/src/lib/findMatchingAttribute.js.map +0 -1
- package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +0 -136
- package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +0 -1
- package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +0 -220
- package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +0 -1
- package/packages/ai/src/lib/generateEntityKeyAttributes.js +0 -241
- package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +0 -1
- package/packages/ai/src/lib/isFrontend.js +0 -5
- package/packages/ai/src/lib/isFrontend.js.map +0 -1
- package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js +0 -40
- package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js.map +0 -1
- package/packages/ai/src/lib/transformMockDataToMatchSchema.js +0 -124
- package/packages/ai/src/lib/transformMockDataToMatchSchema.js.map +0 -1
- package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +0 -72
- package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +0 -1
- /package/analyzer-template/{process → packages/process/src}/GlobalProcessManager.ts +0 -0
- /package/analyzer-template/{process → packages/process/src}/ProcessManager.ts +0 -0
- /package/analyzer-template/{process → packages/process/src}/index.ts +0 -0
- /package/analyzer-template/{process → packages/process/src}/managedExecAsync.ts +0 -0
- /package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-CMKNK2uU.css → styles-CMKNK2uU.css} +0 -0
- /package/{background/src/lib/process → packages/process/src}/GlobalProcessManager.js +0 -0
- /package/{background/src/lib/process → packages/process/src}/index.js +0 -0
- /package/{background/src/lib/process → packages/process/src}/managedExecAsync.js +0 -0
|
@@ -1,166 +0,0 @@
|
|
|
1
|
-
import{jsx as n,jsxs as c,Fragment as se}from"react/jsx-runtime";import{PassThrough as lo}from"node:stream";import{createReadableStreamFromReadable as co}from"@react-router/node";import{ServerRouter as uo,useFetcher as we,useLocation as Yn,useNavigate as _t,Link as oe,UNSAFE_withComponentProps as je,Meta as mo,Links as ho,ScrollRestoration as po,Scripts as fo,useLoaderData as Le,useRevalidator as ft,Outlet as go,data as $,useParams as ea,useSearchParams as Fn,useActionData as yo}from"react-router";import{isbot as xo}from"isbot";import{renderToPipeableStream as bo}from"react-dom/server";import{useState as A,useEffect as J,useCallback as X,createContext as zn,useContext as on,useRef as be,useMemo as Z}from"react";import{Settings as br,CheckCircle2 as Bn,Bug as ta,AlertTriangle as jn,Loader2 as $e,HomeIcon as vo,GitCommitIcon as vr,File as wo,ActivityIcon as Co,SettingsIcon as No,PanelsTopLeftIcon as So,ComponentIcon as Eo,FileText as wr,Code as Cr,Box as Ao,List as _o,BarChart3 as Po,Tag as Mo,Image as Qe,Code2 as na,Activity as Sn,ChevronDown as Jt,CircleEqual as ko,PauseCircle as To,Ban as Io,CheckCircle as Ro,AlertCircle as jo,Search as ra,FolderOpen as Do,CodeXml as $o,Zap as Lo}from"lucide-react";import"fetch-retry";import Oo from"better-sqlite3";import{Pool as Yo}from"pg";import*as W from"fs";import et,{existsSync as Fo}from"fs";import*as q from"path";import he from"path";import{OperationNodeTransformer as zo,Kysely as aa,ParseJSONResultsPlugin as Bo,SqliteDialect as Uo,PostgresDialect as Ho,sql as Ie}from"kysely";import*as qo from"kysely/helpers/sqlite";import*as Go from"kysely/helpers/postgres";import xe from"typescript";import*as Ne from"fs/promises";import Ce,{writeFile as Wo,readFile as Jo}from"fs/promises";import*as Ko from"os";import Dn from"os";import Vo from"prompts";import Kt from"chalk";import Un,{randomUUID as Pt}from"crypto";import{spawn as Hn,exec as qn,execSync as Se}from"child_process";import{promisify as Gn}from"util";import Qo from"dotenv";import Zo,{EventEmitter as Xo}from"events";import{v4 as es}from"uuid";import{fileURLToPath as oa}from"url";import{ResizableBox as ts}from"react-resizable";import ns from"openai";import rs from"p-queue";import Nr from"p-retry";import{DynamoDBClient as sn,PutItemCommand as as}from"@aws-sdk/client-dynamodb";import{LRUCache as Wn}from"lru-cache";import"pluralize";import"piscina";import os from"json5";import{marshall as ss}from"@aws-sdk/util-dynamodb";import{Prism as is}from"react-syntax-highlighter";import{vscDarkPlus as ls}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as cs}from"node:crypto";import ds from"v8";import us from"react-diff-viewer-continued";const sa=5e3;function ms(e,t,r,a,o){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((s,i)=>{let l=!1,d=e.headers.get("user-agent"),u=d&&xo(d)||a.isSpaMode?"onAllReady":"onShellReady",m=setTimeout(()=>p(),sa+1e3);const{pipe:h,abort:p}=bo(n(uo,{context:a,url:e.url}),{[u](){l=!0;const f=new lo({final(y){clearTimeout(m),m=void 0,y()}}),g=co(f);r.set("Content-Type","text/html"),h(f),s(new Response(g,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const hs=Object.freeze(Object.defineProperty({__proto__:null,default:ms,streamTimeout:sa},Symbol.toStringTag,{value:"Module"}));function ps({id:e,selected:t,onClick:r,icon:a,name:o}){const[s,i]=A(!1);J(()=>{i(!0)},[]);const l=X(()=>{r?.(e)},[r,e]);return c("button",{className:`
|
|
2
|
-
w-full aspect-square p-3 cursor-pointer focus:outline-none
|
|
3
|
-
flex flex-col items-center justify-center gap-1 text-[#626262]
|
|
4
|
-
hover:bg-[#d8d8d8] text-xs font-ibmPlexSans uppercase
|
|
5
|
-
`,onClick:l,children:[n("div",{className:`${t?"bg-primary-100 text-cygray-10":""} w-10 h-10 rounded-lg flex items-center justify-center`,children:s&&a}),n("span",{className:`${t?"text-primary-100":""} whitespace-nowrap`,children:o})]})}const fs="/assets/cy-logo-cli-C1gnJVOL.svg";function gs(e){return e.scenarioId?`Scenario: ${e.scenarioId.slice(0,8)}...`:e.entitySha?`Entity: ${e.entitySha.slice(0,8)}...`:"General feedback"}function ia({isOpen:e,onClose:t,context:r,defaultEmail:a="",screenshotDataUrl:o}){const[s,i]=A(""),[l,d]=A(a),[u,m]=A(!1),[h,p]=A(!1),[f,g]=A(null),[y,b]=A(null),x=we(),w=x.state!=="idle";if(x.data&&!h&&!y){const E=x.data;E.success&&E.reportId?(p(!0),g(E.reportId)):E.error&&b(E.error)}const C=async()=>{b(null);const E=new FormData;if(E.append("issueType","other"),E.append("description",s),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),o)try{const S=await(await fetch(o)).blob();E.append("screenshot",S,"screenshot.jpg")}catch(v){console.error("Failed to convert screenshot:",v)}x.submit(E,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},N=()=>{i(""),m(!1),p(!1),g(null),b(null),t()},M=E=>{E.key==="Escape"&&N()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:M,children:c("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl",children:[c("div",{className:"flex items-center justify-between mb-6",children:[c("div",{className:"flex items-center gap-3",children:[w?n("div",{className:"animate-spin",children:n(br,{size:24,style:{strokeWidth:1.5}})}):h?n(Bn,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(ta,{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:N,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?c("div",{children:[c("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!"}),c("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:N,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):c("div",{children:[c("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[c("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:gs(r)}),n("button",{type:"button",onClick:()=>m(!u),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:u?"Hide":"Details"})]}),u&&c("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1",children:[c("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),c("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&c("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&c("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&c("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),o&&c("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:o,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),c("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:s,onChange:E=>i(E.target.value),placeholder:"Describe what you expected vs what happened...",rows:4,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"})]}),c("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=>d(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]"})]}),c("div",{className:"mb-6 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(jn,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),c("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:x.formData?"Uploading report...":"Creating archive..."})}),y&&c("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(jn,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),c("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:y})]})]}),c("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:N,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:()=>{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?c(se,{children:[n("div",{className:"animate-spin",children:n(br,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):y?"Try Again":"Submit Report"})]})]})]})}):null}const Sr={source:"navbar"},Jn=zn(void 0);function ys({children:e}){const[t,r]=A(Sr),a=X(s=>{r(s)},[]),o=X(()=>{r(Sr)},[]);return n(Jn.Provider,{value:{contextData:t,setContextData:a,resetContextData:o},children:e})}function nt(e){const t=on(Jn),r=be(t);J(()=>{if(r.current)return r.current.setContextData(e),()=>{r.current?.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId])}function xs(){const e=on(Jn),t=Yn();return e?{source:e.contextData.source,entitySha:e.contextData.entitySha,scenarioId:e.contextData.scenarioId,analysisId:e.contextData.analysisId,currentUrl:t.pathname}:{source:"navbar",currentUrl:t.pathname}}function bs(){const e=Yn(),t=_t(),[r,a]=A(),[o,s]=A(!1),[i,l]=A(!1),[d,u]=A(null),m=we();J(()=>{m.state==="idle"&&!m.data&&m.load("/api/generate-report")},[m]);const h=m.data?.defaultEmail||"",p={width:"24px",height:"24px",strokeWidth:1.5},f=[{id:"dashboard",icon:n(vo,{style:p}),link:"/",name:"Dashboard"},{id:"simulations",icon:c("svg",{width:"24",height:"24",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:p,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"},{id:"git",icon:n(vr,{style:p}),link:"/git",name:"Git"},{id:"files",icon:n(wo,{style:p}),link:"/files",name:"Files"},{id:"activity",icon:n(Co,{style:p}),link:"/activity",name:"Activity"},{id:"settings",icon:n(No,{style:p}),link:"/settings",name:"Settings"},{id:"commits",icon:n(vr,{style:p}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(So,{style:p}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(Eo,{style:p}),link:"/components",name:"Components",hidden:!0}],g=X(w=>{const C=f.find(N=>N.id===w);C?.link&&t(C.link),a(N=>N===w?void 0:w)},[f,t]);J(()=>{const w={dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],files:["files"],settings:["settings"],pages:["pages"],components:["components"]};for(const[C,N]of Object.entries(w))if(N.some(M=>M==="/"?e.pathname==="/":e.pathname.includes(M))){a(C);return}a(void 0)},[e]);const y=async()=>{l(!0);try{const{default:w}=await import("html2canvas-pro"),N=(await w(document.body)).toDataURL("image/jpeg",.8);u(N),s(!0)}catch(w){console.error("Screenshot capture failed:",w),s(!0)}finally{l(!1)}},b=()=>{s(!1),u(null)},x=xs();return c(se,{children:[c("div",{id:"sidebar",className:"relative w-full h-screen bg-cygray-30 flex flex-col justify-between py-3",children:[c("div",{className:"w-full flex flex-col items-center",children:[n("div",{children:n(oe,{to:"/",className:"flex items-center justify-center h-20 cursor-pointer",children:n("img",{src:fs,alt:"CodeYam",className:"h-8"})})}),f.filter(w=>!w.hidden).map(w=>n(ps,{id:w.id,selected:w.id===r,onClick:g,icon:w.icon,name:w.name},`sidebar-button-${w.id}`))]}),n("div",{className:"w-full flex flex-col items-center pb-2",children:c("button",{onClick:()=>{y()},disabled:i,className:"flex flex-col items-center gap-1 p-2 rounded-lg text-gray-600 hover:bg-gray-100 hover:text-gray-900 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait",title:"Report an issue",children:[i?n($e,{style:p,className:"animate-spin"}):n(ta,{style:p}),n("span",{className:"text-[10px] font-medium",children:i?"Capturing...":"Report Issue"})]})})]}),o&&n(ia,{isOpen:!0,onClose:b,context:x,defaultEmail:h,screenshotDataUrl:d??void 0})]})}const la=zn(void 0);function vs({children:e}){const[t,r]=A([]),a=X((s,i="info",l=5e3)=>{const u={id:`toast-${Date.now()}-${Math.random()}`,message:s,type:i,duration:l};r(m=>[...m,u])},[]),o=X(s=>{r(i=>i.filter(l=>l.id!==s))},[]);return n(la.Provider,{value:{toasts:t,showToast:a,closeToast:o},children:e})}function Kn(){const e=on(la);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function ws({toast:e,onClose:t}){J(()=>{const o=e.duration||5e3;if(o>0){const s=setTimeout(()=>{t(e.id)},o);return()=>clearTimeout(s)}},[e.id,e.duration,t]);const r={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return c("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 Cs({toasts:e,onClose:t}){return e.length===0?null:c("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
|
|
6
|
-
@keyframes slideIn {
|
|
7
|
-
from {
|
|
8
|
-
transform: translateX(400px);
|
|
9
|
-
opacity: 0;
|
|
10
|
-
}
|
|
11
|
-
to {
|
|
12
|
-
transform: translateX(0);
|
|
13
|
-
opacity: 1;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
`}),e.map(r=>n(ws,{toast:r,onClose:t},r.id))]})}function rt(e,t){const[r,a]=A(""),[o,s]=A(!1),[i,l]=A(null),[d,u]=A(!1);J(()=>{t&&(u(!1),s(!1),l(null))},[t]),J(()=>{if(!e||!t){t||a("");return}const h=async()=>{try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const y=(await f.text()).trim().split(`
|
|
17
|
-
`).filter(w=>w.length>0);if(y.length<3){s(!1),u(!1),l(null),a("");return}const b=y.filter(w=>w.includes("CodeYam Log Level 1"));if(b.length>0){const w=b[b.length-1];a(w.replace(/.*CodeYam Log Level 1: /,""))}const x=y.find(w=>w.includes("$$INTERACTIVE_SERVER_URL$$:"));if(x){const w=x.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();l(w),u(!0)}y.some(w=>w.includes("CodeYam: Exiting start.js"))&&s(!0)}}catch{}};h().catch(()=>{});const p=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(p)},[e,t]);const m=X(()=>{a(""),s(!1),l(null),u(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:o,resetLogs:m}}function gt({projectSlug:e,onClose:t}){const[r,a]=A("Loading logs..."),[o,s]=A(!0),[i,l]=A(!0),[d,u]=A("all"),m=be(null);return J(()=>{const h=async()=>{try{const p=await fetch(`/api/logs/${e}`);if(p.ok){const f=await p.text();if(d==="all")a(f);else{const g=f.trim().split(`
|
|
18
|
-
`).filter(y=>{if(y.length===0)return!1;const b=y.match(/^.*CodeYam Log Level (\d+):/);return!!b&&Number(b[1])<=d});a(g.map(y=>y.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
|
|
19
|
-
`))}i&&m.current&&setTimeout(()=>{m.current?.scrollTo({top:m.current.scrollHeight,behavior:"smooth"})},100)}else a(`Error: ${p.status} - ${await p.text()}`)}catch(p){a(`Error fetching logs: ${p.message}`)}};if(h().catch(()=>{}),o){const p=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(p)}},[e,o,i,d]),J(()=>{const h=p=>{p.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:c("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:[c("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[c("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),c("div",{className:"flex items-center gap-4",children:[c("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),c("select",{value:d,onChange:h=>u(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"})]})]}),c("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:o,onChange:h=>s(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),c("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:m,children:r})]})})}function Pe({type:e}){const t={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"}},r=t[e]||t.other,a=()=>{switch(e){case"library":return n(na,{size:14,color:r.iconColor});case"visual":return n(Qe,{size:14,color:r.iconColor});case"type":return n(Mo,{size:14,color:r.iconColor});case"data":return n(Po,{size:14,color:r.iconColor});case"index":return n(_o,{size:14,color:r.iconColor});case"functionCall":return n(Cr,{size:14,color:r.iconColor});case"class":return n(Ao,{size:14,color:r.iconColor});case"method":return n(Cr,{size:14,color:r.iconColor});case"other":return n(wr,{size:14,color:r.iconColor});default:return n(wr,{size:14,color:r.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${r.bgColor}`,style:{width:"18px",height:"18px"},children:a()})}function ca({filePath:e,maxLength:t=60,className:r,style:a}){const s=((l,d)=>{if(l.length<=d)return l;const u="...",m=d-u.length,h=Math.ceil(m*.4),p=Math.floor(m*.6),f=l.slice(0,h),g=l.slice(-p),y=f.lastIndexOf("/"),b=g.indexOf("/"),x=y>h*.5?f.slice(0,y+1):f,w=b!==-1&&b<p*.5?g.slice(b):g;return`${x}${u}${w}`})(e,t),i=s!==e;return n("span",{className:r||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...a,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:s})}function En({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:a=50,showScenarioCount:o=!1,scenarioCount:s=0,additionalContent:i}){return c("div",{className:"flex flex-col gap-1",children:[c("div",{className:"flex items-center gap-1",children:[n(Pe,{type:e.entityType||"other"}),c(oe,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:t,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,o&&s>0&&` (${s})`]}),n(ca,{filePath:e.filePath,maxLength:a,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}function Ns({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:a=!1,queuedJobCount:o=0,queueJobs:s=[],currentlyExecuting:i=null,historicalRuns:l=[]}){const[d,u]=A(!1),[m,h]=A(!1),[p,f]=A(!1),[g,y]=A(null),b=!!i||s.length>0,x=!!i,w=i?.entities||r;e?.analysisCompletedAt,e?.readyToBeCaptured,e?.capturesCompleted;const C=e?.currentEntityShas&&e.currentEntityShas.length>0,N=b,{lastLine:M,isCompleted:E}=rt(t,N),v=x||N&&!E&&!b,S=(()=>{if(N)return!1;const R=Date.now()-30*1e3;if(e?.createdAt&&C){const O=e.analysisCompletedAt||e.createdAt;if(new Date(O).getTime()>R)return!0}if(l.length>0){const O=l[0],k=O.analysisCompletedAt||O.archivedAt||O.createdAt;if(k&&new Date(k).getTime()>R)return!0}return!1})(),I=(()=>{const R=Date.now()-1440*60*1e3;if(e?.createdAt&&C){const O=e.analysisCompletedAt||e.createdAt;if(new Date(O).getTime()>R)return!0}if(l.length>0){const O=l[0],k=O.analysisCompletedAt||O.archivedAt||O.createdAt;if(k&&new Date(k).getTime()>R)return!0}return!1})(),P=a||v||o>0||S;return J(()=>{const T=i?.id||null;P?T!==g&&(h(!0),f(!1),g!==null&&y(null)):(g!==null&&y(null),!I&&m&&!p&&h(!1))},[P,I,m,p,g,i?.id]),c(se,{children:[c("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${m?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!m&&c("div",{onClick:()=>{h(!0),f(!0),y(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[v?n($e,{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(Sn,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:v?"Analyzing...":"Activity: No Activity Yet"}),v&&n("button",{onClick:T=>{T.stopPropagation(),u(!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"})]}),m&&c("div",{children:[c("div",{className:"flex items-center justify-between px-3 py-2",children:[c("div",{className:"flex items-center gap-2",children:[v?n($e,{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(Sn,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:v?"Analyzing...":"Activity"})]}),c("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>u(!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),y(i?.id||null)},className:"p-1 rounded hover:bg-gray-100 transition-colors cursor-pointer",title:"Collapse","aria-label":"Collapse",children:n(Jt,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),c("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[v&&w.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Sn,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Current Activity"})]}),w[0]&&n("div",{className:"space-y-1",children:n(En,{entity:w[0],nameSize:"11px",pathSize:"10px",pathMaxLength:150,additionalContent:M?n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:M}):void 0})})]}),s.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(ko,{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:s.map(T=>n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:T.entities.length>0&&c("div",{className:"space-y-1.5",children:[T.entities.slice(0,3).map(R=>n(En,{entity:R,nameSize:"10px",pathSize:"9px",pathMaxLength:120},R.sha)),T.entities.length>3&&c("div",{style:{fontSize:"9px",color:"#646464",fontStyle:"italic"},children:["+",T.entities.length-3," more"]})]})},T.id))})]}),I&&l.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Bn,{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:l.slice(0,3).map((T,R)=>{const O=T.entities||[],k=T.analysisCompletedAt||T.archivedAt||T.createdAt||"",j=(()=>{if(!k)return"";const Y=Date.now()-new Date(k).getTime(),te=Math.floor(Y/6e4),ne=Math.floor(Y/36e5);return ne>0?`${ne}h ago`:te>0?`${te}m ago`:"just now"})(),D=O.slice(0,3).map(Y=>({...Y,scenarioCount:Y.analyses?.[0]?.scenarios?.length||0}));return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:O.length>0&&c("div",{className:"space-y-1.5",children:[D.map((Y,te)=>c("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(En,{entity:Y,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:Y.scenarioCount})}),te===0&&j&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:j})]},Y.sha)),O.length>3&&c("div",{style:{fontSize:"9px",color:"#646464",fontStyle:"italic"},children:["+",O.length-3," more"]})]})},R)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(oe,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&t&&n(gt,{projectSlug:t,onClose:()=>u(!1)})]})}function Me(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function Mt(e){const{file_id:t,project_id:r,commit_id:a,file_path:o,entity_type:s,entity_branches:i,analyses:l,commit:d,created_at:u,updated_at:m,...h}=e,p=(i??[]).map(y=>y.branch_id),f=l?l.map(Ue):void 0,g=d?at(d):void 0;return Me({...h,fileId:t,projectId:r,commitId:a,filePath:o,entityType:s,commit:g,analyses:f,branchIds:p,createdAt:u,updatedAt:m})}function Vn(e){return Me({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 Qn(e){const{branches:t,files:r,analyzed_at:a,content_changed_at:o,created_at:s,updated_at:i,github_token:l,configuration:d,team_id:u,...m}=e;return Me({...m,branches:t?t.map(ht):void 0,files:r?r.map(Vn):void 0,analyzedAt:a,contentChangedAt:o,createdAt:s,updatedAt:i})}function Ss(e){const{id:t,project_id:r,user_id:a,scenario_id:o,thumbs_up:s,user:i}=e,l=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return Me({id:t,projectId:r,userId:a,scenarioId:o,thumbsUp:!!s,user:l})}function Es(e){const{id:t,project_id:r,user_id:a,scenario_id:o,text:s,created_at:i,updated_at:l,user:d}=e,u=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return Me({id:t,projectId:r,userId:a,scenarioId:o,text:s,createdAt:i,updatedAt:l,user:u})}function da(e){const{project_id:t,analysis_id:r,previous_version_id:a,analysis:o,user_scenarios:s,scenario_comments:i,approved:l,...d}=e,u=o?Ue(o):void 0,m=s?s.map(Ss):void 0,h=i?i.map(Es):void 0;return Me({...d,projectId:t,analysisId:r,previousVersionId:a,analysis:u,userScenarios:m,comments:h})}function As(e){return Me({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?Ue(e.analysis):void 0,entity:e.entity?Mt(e.entity):void 0,branch:e.branch?ht(e.branch):void 0,createdAt:e.created_at})}function Ue(e){const{project_id:t,commit_id:r,file_id:a,file_path:o,entity_sha:s,entity_type:i,entity_name:l,previous_analysis_id:d,file:u,entity:m,commit:h,project:p,scenarios:f,analysis_branches:g,dependency_analyzed_tree_sha:y,analyzed_tree_sha:b,branch_commit_sha:x,committed_at:w,completed_at:C,created_at:N,updated_at:M,indirect:E,...v}=e,S=m?Mt(m):void 0,I=u?Vn(u):void 0,P=p?Qn(p):void 0,T=h?at(h):void 0,R=f?f.map(da):void 0,O=g?g.map(As):void 0,k=O?O.map(j=>j.branch):void 0;return Me({...v,projectId:t,commitId:r,fileId:a,filePath:o,entitySha:s,entityType:i,entityName:l,previousAnalysisId:d,entity:S,file:I,commit:T,project:P,scenarios:R,analysisBranches:O,branches:k,dependencyAnalyzedTreeSha:y,analyzedTreeSha:b,branchCommitSha:x,committedAt:w,completedAt:C,createdAt:N,updatedAt:M,indirect:!!E})}function Zn(e){return Me({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?at(e.commit):void 0,branch:e.branch?ht(e.branch):void 0})}function _s(e){const{project_id:t,commit_id:r,created_at:a,updated_at:o,success:s,...i}=e;return Me({...i,projectId:t,commitId:r,createdAt:a,updatedAt:o,success:!!s})}function at(e){const{project_id:t,branch_id:r,branch:a,background_jobs:o,merged_branch_id:s,mergedBranch:i,ai_message:l,html_url:d,author:u,analyses:m,entities:h,commit_branches:p,committed_at:f,analyzed_at:g,...y}=e,b=a?ht(a):void 0,x=i?ht(i):void 0,w=o?.length>0?_s(o[o.length-1]):void 0,C=(m??[]).map(Ue),N=(h??[]).map(Mt),M=p?.length>0?p.map(Zn):void 0;return u&&(u.username=u.preferredUsername??u.username),Me({...y,projectId:t,branchId:r,branch:b,backgroundJob:w,mergedBranchId:s,mergedBranch:x,aiMessage:l,htmlUrl:d,author:u,analyses:C,entities:N,commitBranches:M,committedAt:f,analyzedAt:g})}function ht(e){const{project_id:t,content_changed_at:r,commits:a,analysis_branches:o,active_at:s,created_at:i,updated_at:l,primary:d,...u}=e,m=a?a.map(at):void 0,h=o?o.flatMap(p=>Ue(p.analysis)):void 0;return Me({...u,projectId:t,contentChangedAt:r,commits:m,analyses:h,activeAt:s,createdAt:i,updatedAt:l,primary:!!d})}class Ps{#e=new Ms;transformQuery(t){return this.#e.transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}class Ms extends zo{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 z=()=>null,ks={analyzed_at:z(),configuration:z(),content_changed_at:z(),created_at:z(),description:z(),github_token:z(),id:z(),metadata:z(),name:z(),path:z(),slug:z(),team_id:z(),updated_at:z()},Ts=Object.keys(ks),Is={active:z(),analysis_id:z(),branch_id:z(),created_at:z(),entity_sha:z(),id:z()},Rs=Object.keys(Is),js={active_at:z(),content_changed_at:z(),created_at:z(),id:z(),metadata:z(),name:z(),primary:z(),project_id:z(),ref:z(),sha:z(),updated_at:z()},ua=Object.keys(js),Ds={ai_message:z(),analyzed_at:z(),author_github_username:z(),branch_id:z(),committed_at:z(),created_at:z(),files:z(),html_url:z(),id:z(),merged_branch_id:z(),message:z(),metadata:z(),project_id:z(),sha:z(),title:z(),url:z()},$s=Object.keys(Ds),Ls={commit_id:z(),created_at:z(),description:z(),documentation:z(),entity_type:z(),file_id:z(),file_path:z(),metadata:z(),name:z(),project_id:z(),quality:z(),sha:z(),updated_at:z()},ma=Object.keys(Ls),Os={active:z(),branch_id:z(),entity_sha:z()},Ys=Object.keys(Os),Fs={created_at:z(),deleted:z(),id:z(),metadata:z(),name:z(),path:z(),project_id:z(),updated_at:z()},zs=Object.keys(Fs),Bs={analysis_id:z(),approved:z(),created_at:z(),description:z(),id:z(),metadata:z(),name:z(),previous_version_id:z(),project_id:z()},Xn=Object.keys(Bs),Us=!!tt("ENABLE_QUERY_LOGGING"),Hs=!!tt("ENABLE_QUERY_ERROR_LOGGING");tt("USE_LOCAL_POSTGRESQL_FOR_TESTING");let Lt;function fe(){if(!Lt){const e=pa();if(e==="sqlite")Lt=qs();else if(e==="postgresql")Lt=Gs();else throw new Error(`Unknown database type: ${e}`)}return Lt}function qs(e){if(e||(e=tt("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=W.existsSync(e),r=q.dirname(e);if(!W.existsSync(r))W.mkdirSync(r,{recursive:!0,mode:493});else try{W.chmodSync(r,493)}catch(o){console.warn(`Warning: Could not set permissions on database directory: ${o.message}`)}const a=new Oo(e,{readonly:!1,fileMustExist:!1});if(a.pragma("journal_mode = WAL"),a.pragma("synchronous = FULL"),!process.env.CLAUDE_CODE_MODE)try{const o=a.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();t&&o.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(o){console.error("CodeYam DB ERROR: Failed to verify database schema:",o)}return new aa({dialect:new Uo({database:a}),plugins:[new Bo,new Ps],log:ha})}function Gs(){const e=Js();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new Yo({connectionString:e});return t.on("error",(r,a)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new aa({dialect:new Ho({pool:t}),log:ha})}let An=null;function ot(){return An||(An=Ws(pa())),An}function ha(e){e.level==="error"?Hs&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):Us&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function Ws(e){if(e==="sqlite")return qo;if(e==="postgresql")return Go;throw new Error(`Unknown database type: ${e}`)}function pa(){if(tt("SQLITE_PATH"))return"sqlite";if(tt("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function Js(){const e=tt("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function tt(e){return typeof window<"u"?window.env?.[e]:process.env[e]}var ln=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(ln||{});const cn="Default Scenario";let Ks="<main>";function Vs(){return Ks}function ie(...e){const t=Vs(),r=e.map(o=>{if(o)return typeof o=="string"?o:o instanceof Error?`${o.name}: ${o.message}
|
|
20
|
-
${o.stack}`:typeof o=="object"?Qs(o):String(o)}).filter(Boolean).join(`
|
|
21
|
-
`),a=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(a+`
|
|
22
|
-
`);return}console.log(a.replace(/\n/g,"\r"))}function Qs(e,t=2){function r(a,o=new WeakMap){return a===null||typeof a!="object"?a:o.has(a)?`"[Circular: ${a.constructor.name}]"`:(o.set(a,!0),Array.isArray(a)?`[${a.map(l=>{const d=r(l,o);return typeof l=="string"?`"${d}"`:d}).join(",")}]`:`{${Object.entries(a).map(([i,l])=>{let d;return typeof l>"u"?null:(typeof l=="function"?d=`"(function: ${l.name||"anonymous"})"`:l instanceof Date?d=`"${l.toISOString()}"`:typeof l=="object"&&l!==null?d=r(l,o):typeof l=="string"?d=`"${l.replace(/"/g,'\\"')}"`:d=JSON.stringify(l),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(a){const o=r(e);if(!t)return o;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(s){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:s,pureStringifyError:a,serialized:o}),o}}}function Vt(e,t){try{let r=function(s){if(xe.isFunctionDeclaration(s)&&Ct(s)){const i=s.name?.text||"default",l=s.getText(a),d=_n(s);o.push({name:i,code:l,sha:Ve(t,i,l),entityType:"function",isDefault:d})}else if(xe.isClassDeclaration(s)&&Ct(s)){const i=s.name?.text||"default",l=s.getText(a),d=_n(s),u=l.includes("React.")||l.includes("jsx")||l.includes("tsx");o.push({name:i,code:l,sha:Ve(t,i,l),entityType:u?"component":"class",isDefault:d})}else if(xe.isInterfaceDeclaration(s)&&Ct(s)){const i=s.name.text,l=s.getText(a);o.push({name:i,code:l,sha:Ve(t,i,l),entityType:"interface",isDefault:!1})}else if(xe.isTypeAliasDeclaration(s)&&Ct(s)){const i=s.name.text,l=s.getText(a);o.push({name:i,code:l,sha:Ve(t,i,l),entityType:"type",isDefault:!1})}else if(xe.isVariableStatement(s)&&Ct(s)){const i=_n(s);s.declarationList.declarations.forEach(l=>{if(xe.isIdentifier(l.name)){const d=l.name.text,u=s.getText(a),m=l.initializer?.getText(a)||"",h=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&m.includes("=>")&&(m.includes("<")||m.includes("React."));o.push({name:d,code:u,sha:Ve(t,d,u),entityType:h?"component":"variable",isDefault:i})}})}else if(xe.isExportAssignment(s)){const i=s.getText(a);o.push({name:"default",code:i,sha:Ve(t,"default",i),entityType:"unknown",isDefault:!0})}else if(xe.isExportDeclaration(s)&&s.exportClause&&xe.isNamedExports(s.exportClause)){const i=s.getText(a);for(const l of s.exportClause.elements){const d=l.name.text;o.push({name:d,code:i,sha:Ve(t,d,i),entityType:"unknown",isDefault:!1})}}xe.forEachChild(s,r)};const a=xe.createSourceFile(t,e,xe.ScriptTarget.Latest,!0),o=[];return r(a),o}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function Ct(e){if(!xe.canHaveModifiers(e))return!1;const t=xe.getModifiers(e);return t?t.some(r=>r.kind===xe.SyntaxKind.ExportKeyword):!1}function _n(e){if(!xe.canHaveModifiers(e))return!1;const t=xe.getModifiers(e);return t?t.some(r=>r.kind===xe.SyntaxKind.DefaultKeyword):!1}function Ve(e,t,r){const a=Un.createHash("sha256");return a.update(`${e}:${t}:${r}`),a.digest("hex").substring(0,40)}function Zs(e){const{webapp:t,port:r,environmentVariables:a,packageManager:o}=e,s=t?.startCommand;if(!s)return`${o} ${o==="npm"?"run ":""}dev`;const i=s.args?.map(u=>u.replace(/\$PORT/g,String(r)))??[],l=[];for(const u of a)if(u.key&&u.value!==void 0){const m=String(u.value).replace(/'/g,"'\\''");l.push(`${u.key}='${m}'`)}if(s.env)for(const[u,m]of Object.entries(s.env)){const p=String(m).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");l.push(`${u}='${p}'`)}const d=l.length>0?l.join(" ")+" ":"";return s.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${s.command} ${i.join(" ")}`}function Xs(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=q.normalize(e),a=[...t].sort((o,s)=>(s.path?.length??0)-(o.path?.length??0));for(const o of a){const s=q.normalize(o.path??".");if(s==="."||r.startsWith(s+q.sep)||r===s)return o}return t[0]}function ei(e){const{filePath:t,webapps:r,environmentVariables:a,port:o,packageManager:s}=e;if(!r||r.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=Xs(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const l=Zs({webapp:i,port:o,environmentVariables:a,packageManager:s});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??s,startCommand:l,url:`http://localhost:${o}/static/codeyam-sample`}}function dn(e,t,r=[]){const a=Array.isArray(t)?t:[t];return o=>o.columns(a).doUpdateSet(s=>{const i=Object.keys(e).filter(l=>l!==t&&!r.includes(l));return Object.fromEntries(i.map(l=>[l,s.ref(`excluded.${l}`)]))})}function ti(e){const{jsonObjectFrom:t}=ot();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 ni({ids:e,analysisId:t}){const r=fe();try{let a=r.deleteFrom("scenarios");if(e){if(e.length===0)return;a=a.where("id","in",e)}else if(t)a=a.where("analysis_id","=",t);else throw ie("CodeYam Error: No deletion criteria provided",null,{ids:e,analysisId:t}),new Error("No deletion criteria provided for scenarios");await a.execute()}catch(a){throw ie("CodeYam Error: Database error deleting scenarios",a,{ids:e,analysisId:t}),a}}function ri(...e){try{const t=Un.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 Er(e,t){return t.map(r=>ai(e,r))}function ai(e,t){return Ie` ${Ie.ref(e)}.${Ie.ref(t)}`.as(t)}function oi(e,t,r){return t.map(a=>si(e,a,r))}function si(e,t,r){return Ie` ${Ie.ref(e)}.${Ie.ref(t)}`.as(`_cy_${r}:${t}`)}function ii(e,...t){const r={};for(const[a,o]of Object.entries(e)){const s=a.match(/^_cy_(.+?):(.+)$/);if(s){const[,i,l]=s;if(t.includes(i)){r[i]||(r[i]={}),r[i][l]=o;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${a}'`);continue}r[a]=o}return r}const li=50;function ci(e,t){return e.length<=t?[e]:Array.from({length:Math.ceil(e.length/t)},(r,a)=>e.slice(a*t,a*t+t))}function Ar({projectId:e,ids:t,fileIds:r,entityName:a,entityShas:o,commitIds:s,branchCommitSha:i,limit:l}){const d=fe(),{jsonObjectFrom:u,jsonArrayFrom:m}=ot();let h=d.selectFrom("analyses").selectAll("analyses");if(e&&(h=h.where("project_id","=",e)),t){if(t.length===0)return null;h=h.where("id","in",t)}if(r){if(r.length===0)return null;h=h.where("file_id","in",r)}if(s){if(s.length===0)return null;h=h.where("commit_id","in",s)}return a&&(h=h.where("entity_name","=",a)),o&&(h=h.where("entity_sha","in",o)),i&&(h=h.where("branch_commit_sha","=",i)),l&&(h=h.limit(l)),d.with("filtered_analyses",()=>h).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(p=>[u(p.selectFrom("entities").select(Er("entities",ma)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),m(p.selectFrom("scenarios").select(Er("scenarios",Xn)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),m(p.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function Et(e){const{ids:t,fileIds:r,entityShas:a,commitIds:o}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:a,key:"entityShas"},commit_id:{arr:o,key:"commitIds"}}).find(([d,{arr:u}])=>u?.length>0);let l=[];if(i){const[d,{arr:u,key:m}]=i,h=ci(u,li),p=[];for(let f=0;f<h.length;f++){const g=h[f],b=await Ar({...e,[m]:g}).execute();b&&p.push(...b)}l=p}else{const u=await Ar(e).execute();if(!u||u.length===0)return ie("CodeYam: No analyses found",null,e),null;l=u}return l.length===0?null:l.map(Ue)}catch(s){return ie("CodeYam Error: Database error in loadAnalyses",s,e),null}}function di(e,t){const{jsonArrayFrom:r,jsonObjectFrom:a}=ot();let o=e.selectFrom("analysis_branches").select(Rs).select(s=>a(s.selectFrom("branches").select(ua).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(o=t(o)),r(o)}async function We({id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:o,entityName:s,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:u,includeCommitAndBranch:m,includeScenarios:h,includeBranches:p}){const f=fe();try{let g=f.selectFrom("analyses").selectAll("analyses");e&&(g=g.where("id","=",e)),r&&(g=g.where("project_id","=",r)),i?g=g.where("dependency_analyzed_tree_sha","=",i):l?g=g.where("analyzed_tree_sha","=",l):a&&(g=g.where("file_id","=",a)),s&&(g=g.where("entity_name","=",s)),o?g=g.where("commit_id","=",o):g=g.orderBy("created_at","desc").limit(1),t&&(g=g.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:y,jsonArrayFrom:b}=ot();g=g.select(w=>{const C=[];return C.push(y(w.selectFrom("entities").select(ma).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&C.push(y(w.selectFrom("files").select(zs).whereRef("files.id","=","analyses.file_id")).as("file")),u&&C.push(y(w.selectFrom("projects").select(Ts).whereRef("projects.id","=","analyses.project_id")).as("project")),h&&C.push(b(w.selectFrom("scenarios").select(Xn).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),p&&C.push(di(w,N=>N.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),m&&C.push(y(w.selectFrom("commits").select($s).select(N=>ti(N).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),C});const x=await g.executeTakeFirst();return x?Ue(x):(ie("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:o,entityName:s,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:u,includeCommitAndBranch:m,includeScenarios:h,includeBranches:p}),null)}catch(g){return ie("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:o,entityName:s,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:u,includeCommitAndBranch:m,includeScenarios:h,includeBranches:p}),null}}async function fa({projectId:e,ids:t,names:r,includeInactive:a}){const o=fe();try{let s=o.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];s=s.where("id","in",t)}if(r){if(r.length===0)return[];s=s.where("name","in",r)}return a||(s=s.where("active_at","is not",null)),(await s.execute()).map(ht)}catch(s){return ie("CodeYam Error: Database error loading branches",s,{projectId:e,ids:t,names:r,includeInactive:a}),[]}}async function ui({projectId:e,commitId:t,branchId:r,active:a,includeBranches:o}){const s=fe();try{let i=s.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(o,u=>u.select(oi("branches",ua,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),a!==void 0&&(i=i.where("commit_branches.active","=",a));const l=await i.execute();return!l||l.length===0?null:l.map(u=>ii(u,"branch")).map(Zn)}catch(i){return ie("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:a,includeBranches:o}),null}}async function mi(e){if(e.length===0)return new Map;const t=fe();try{const r=await t.selectFrom("commits").select(["id","branch_id","merged_branch_id"]).where("id","in",e).execute(),a=new Set;if(r.forEach(s=>{s.branch_id&&a.add(s.branch_id),s.merged_branch_id&&a.add(s.merged_branch_id)}),a.size===0)return new Map;const o=await t.selectFrom("branches").selectAll().where("id","in",Array.from(a)).execute();return new Map(o.map(s=>[s.id,s]))}catch(r){return ie("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function hi(e){if(e.length===0)return new Map;const t=fe(),{jsonObjectFrom:r,jsonArrayFrom:a}=ot();try{const o=await t.selectFrom("analyses").selectAll("analyses").select(i=>[r(i.selectFrom("files").select(["id","name","path"]).whereRef("files.id","=","analyses.file_id")).as("file"),a(i.selectFrom("scenarios").select(Xn).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),s=new Map;return o.forEach(i=>{const l=s.get(i.commit_id)||[];l.push(i),s.set(i.commit_id,l)}),s}catch(o){return ie("CodeYam Error: Loading analyses for commits",o,{commitIds:e}),new Map}}async function pi(e){if(e.length===0)return new Map;const t=fe();try{const r=await t.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),a=new Map;return r.forEach(o=>{const s=a.get(o.commit_id)||[];s.push(o),a.set(o.commit_id,s)}),a}catch(r){return ie("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function Qt({projectId:e,branchId:t,ids:r,shas:a,fileNames:o,limit:s=10}){if(!e&&!r)throw new Error("Must provide projectId or ids");const i=fe(),{jsonObjectFrom:l}=ot();try{let d=i.selectFrom("commits").selectAll("commits").select(y=>[l(y.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",y.ref("commits.author_github_username"))).as("author")]);if(e&&(d=d.where("project_id","=",e)),r){if(r.length===0)return[];d=d.where("id","in",r)}if(a){if(a.length===0)return[];d=d.where("sha","in",a)}if(o&&o.length>0){const y=Ie.join(o.map(b=>Ie`${b}`),Ie`, `);d=d.where(Ie`
|
|
23
|
-
EXISTS (
|
|
24
|
-
SELECT 1
|
|
25
|
-
FROM json_each(${Ie.ref("commits.files")}) AS f
|
|
26
|
-
WHERE json_extract(f.value, '$.fileName') IN (${y})
|
|
27
|
-
)
|
|
28
|
-
`)}t&&(d=d.where("branch_id","=",t));const u=await d.orderBy("committed_at","desc").limit(s).execute();if(!u||u.length===0)return[];const m=u.map(y=>y.id),[h,p,f]=await Promise.all([mi(m),hi(m),pi(m)]);return u.map(y=>{const b=y.branch_id?h.get(y.branch_id):void 0,x=y.merged_branch_id?h.get(y.merged_branch_id):void 0,w=p.get(y.id)||[],C=f.get(y.id)||[];return{...y,branch:b,mergedBranch:x,analyses:w,entities:C}}).map(at)}catch(d){return ie("CodeYam Error: Database error loading commits",d,{projectId:e,branchId:t,ids:r,shas:a,limit:s}),[]}}async function pt({projectId:e,branchId:t,fileIds:r,filePaths:a,names:o,shas:s}){if(r&&r.length==0||a&&a.length==0||o&&o.length==0||s&&s.length==0)return[];if(s&&s.length>50){const l=[];for(let d=0;d<s.length;d+=50){const u=s.slice(d,d+50),m=await pt({projectId:e,branchId:t,fileIds:r,filePaths:a,names:o,shas:u});m&&l.push(...m)}return l}const i=fe();try{const d=await i.selectFrom("entities").selectAll("entities").$if(!!t,u=>u.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,u=>u.where("entities.project_id","=",e)).$if(!!s,u=>u.where("entities.sha","in",s)).$if(!!a,u=>u.where("entities.file_path","in",a)).$if(!!o,u=>u.where("entities.name","in",o)).$if(!!r,u=>u.where("entities.file_id","in",r)).execute();return!d||d.length===0?(console.log("Load Entities: No entities found",{projectId:e,fileIds:r,filePaths:a,shas:s}),null):d.map(Mt)}catch(l){return console.log("Load Entities: Error occurred",l,{projectId:e,fileIds:r,filePaths:a,shas:s}),null}}function fi(e,t){const{jsonArrayFrom:r}=ot();let a=e.selectFrom("entity_branches").select(Ys);return t&&(a=t(a)),r(a)}async function ga({projectId:e,sha:t}){const r=fe();try{const a=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(o=>fi(o,s=>s.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return a?Mt(a):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&ie("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:t}),null)}catch(a){return ie("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:t}),null}}const Pn=1e3;async function ya({projectId:e,filePaths:t,fileIds:r,fileNames:a}){if(t&&t.length>50){const l=[];for(let d=0;d<t.length;d+=50){const u=t.slice(d,d+50),m=await ya({projectId:e,filePaths:u,fileIds:r,fileNames:a});m&&l.push(...m)}return l}const o=fe(),s=[];let i=0;try{for(;;){let l=o.selectFrom("files").selectAll().where("project_id","=",e).limit(Pn).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(a){if(a.length===0)return[];l=l.where("name","in",a)}const d=await l.execute();if(!d||d.length===0||(s.push(...d),d.length<Pn))break;i+=Pn}return s?.map(Vn)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function gi({id:e,slug:t,withBranches:r,withFiles:a,silent:o}){try{let i=fe().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 o||console.log("CodeYam Error: Error loading project",{id:e,slug:t,withBranches:r,withFiles:a}),null;const d=Qn(l);return a&&(d.files=await ya({projectId:d.id})),r&&(d.branches=await fa({projectId:d.id,includeInactive:!1})),d}catch(s){return o||console.log("CodeYam Error: Error loading project",s),null}}function Zt(e,t){const r={...e};for(const a in t){const o=t[a],s=e[a];o!=null&&typeof o=="object"&&!Array.isArray(o)&&s!==void 0&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[a]=Zt(s,o):o!==void 0&&(r[a]=o)}return r}async function ut({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:a,archiveCurrentRun:o,updateCallback:s}){try{return await fe().transaction().execute(async i=>{const l=await i.selectFrom("commits").selectAll().$if(!!e,m=>m.where("id","=",e)).$if(!!t,m=>m.where("sha","=",t)).executeTakeFirst();if(!l)return ie(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const d=l.metadata||{};if(a)a.lastUpdatedAt??=new Date().toISOString(),a.currentEntityShas!==void 0&&(console.log("[updateCommitMetadata] Updating currentRun.currentEntityShas"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Previous entity SHAs:",d.currentRun?.currentEntityShas),console.log("[updateCommitMetadata] New entity SHAs:",a.currentEntityShas),console.log("[updateCommitMetadata] Archive flag:",o)),r=Zt(r??{},{currentRun:a});else if(!r&&!s)return d;const u=r?Zt(d,r):d;if(o&&u.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Current run entity SHAs:",u.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${u.currentRun.analyzerPid}, capture=${u.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${u.currentRun.analysesCompleted}, captures=${u.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${u.historicalRuns?.length||0}`);const m={...u.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(m,null,2)),u.historicalRuns=[...u.historicalRuns||[],m],console.log(`[updateCommitMetadata] Historical runs after archiving: ${u.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(u.historicalRuns.map(h=>({entityShas:h.currentEntityShas,archivedAt:h.archivedAt,completed:{analyses:h.analysesCompleted,captures:h.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}s&&await s(u,at(l));try{return await i.updateTable("commits").set({metadata:JSON.stringify(u)}).where("id","=",l.id).returningAll().executeTakeFirst()?u:(ie(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),d)}catch(m){return ie(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,m),d}})}catch(i){return ie(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}`,i),null}}async function xa(e,t,r="analysis"){try{return await fe().transaction().execute(async a=>{const o=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!o)return ie(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const s=Ue(o);return t(s.metadata,s),await a.updateTable("analyses").set({metadata:JSON.stringify(s.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?s.metadata:(ie(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return ie(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function kt(e,t,r="capture"){try{return await fe().transaction().execute(async a=>{const o=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!o)return ie(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const s=Ue(o);return t(s.status,s),await a.updateTable("analyses").set({status:JSON.stringify(s.status)}).where("id","=",e).returningAll().executeTakeFirst()?s.status:(ie(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return ie(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function yi({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:a}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await fe().transaction().execute(async o=>{const s=await o.selectFrom("projects").selectAll().$if(!!e,d=>d.where("id","=",e)).$if(!!t,d=>d.where("slug","=",t)).executeTakeFirst();if(!s)return ie(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=s.metadata||{};if(!r&&!a)return i;const l=r?Zt(i,r):i;a&&await a(l,Qn(s));try{return await o.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",s.id).returningAll().executeTakeFirst()?l:(ie(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return ie(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(o){return ie(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,o),null}}function xi(e){const{id:t,projectId:r,analysisId:a,previousVersionId:o,analysis:s,metadata:i,data:l,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:t??Pt(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:a,previous_version_id:o}}async function bi(e){if(e.length===0)return[];const t=fe(),r=e.map(xi);try{return(await t.insertInto("scenarios").values(r).onConflict(dn(r[0],"id",["created_at"])).returningAll().execute()).map(da)}catch(a){return ie("CodeYam Error: Database error upserting scenarios",a,{scenarioCount:e.length}),null}}function vi(e){const{id:t,commitId:r,branchId:a,...o}=e;return delete o.commit,delete o.branch,{...o,id:t??Pt(),commit_id:r,branch_id:a}}async function _r(e){if(e.length===0)return[];const t=fe(),r=e.map(vi);try{return(await t.insertInto("commit_branches").values(r).onConflict(dn(r[0],"id",["created_at"])).returningAll().execute()).map(Zn)}catch(a){return ie("CodeYam Error: Database error upserting commit branches",a,{commitBranchCount:e.length,commitBranchIds:e.map(o=>o.id)}),[]}}async function wi(e,t){const r=fe(),a={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(a).onConflict(dn(a,"username",[])).returningAll().executeTakeFirst()||null}catch(o){return ie("CodeYam Error: Error upserting github user",o,{username:e,avatarUrl:t}),null}}function Ci(e,t){const{id:r,projectId:a,branchId:o,mergedBranchId:s,aiMessage:i,htmlUrl:l,analyzedAt:d,committedAt:u,author:m,metadata:h,files:p,...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??Pt(),project_id:a??String(t),metadata:h?JSON.stringify(h):void 0,files:p?JSON.stringify(p):void 0,branch_id:o,merged_branch_id:s,author_github_username:m?.username,html_url:l,ai_message:i,analyzed_at:d,committed_at:u}}async function Ni({projectId:e,commits:t}){const r=fe();try{const a=t.reduce((i,l)=>{const{author:d}=l;return d?.username&&d?.avatarUrl&&(i[d.username]=d.avatarUrl),i},{});for(const i in a)await wi(i,a[i]);const o=t.map(i=>Ci(i,e));return(await r.insertInto("commits").values(o).onConflict(dn(o[0],"id",["created_at"])).returningAll().execute()).map(at)}catch(a){return ie("CodeYam Error: Error saving commits",a,{projectId:e,commitCount:t.length,commitIds:t.map(o=>o.id).filter(Boolean)}),[]}}const Xt=q.join(Ko.homedir(),".codeyam","secrets.json"),en=q.join(process.cwd(),".codeyam","secrets.json");async function yt(){let e={};try{if(W.existsSync(en)){const s=await Ne.readFile(en,"utf8");e=JSON.parse(s)}}catch{console.warn(Kt.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(W.existsSync(Xt)){const s=await Ne.readFile(Xt,"utf8");e={...JSON.parse(s),...e}}}catch{console.warn(Kt.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 a=e.ANTHROPIC_API_KEY||process.env.ANTHROPIC_API_KEY;a&&(t.ANTHROPIC_API_KEY=a);const o=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return o&&(t.GROQ_API_KEY=o),t}async function Si(e,t=!0){const r=t?Xt:en,a=q.dirname(r);await Ne.mkdir(a,{recursive:!0}),await Ne.writeFile(r,JSON.stringify(e,null,2)),await Ne.chmod(r,384)}function Ei(e=!0){return e?Xt:en}async function Pr(){const e=await yt(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function Ai(e){console.log(),console.log(Kt.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const a=await Vo({type:"password",name:"key",message:"OpenAI API Key",validate:o=>o&&!o.startsWith("sk-")?"OpenAI API key should start with sk-":!0});a.key&&(t.OPENAI_API_KEY=a.key);break}return t}async function _i(e=!0){const t=await Pr();if(t.isValid)return t.secrets;const r=await Ai(t.missing),o={...await yt(),...r};await Si(o,e);const s=Ei(e);return console.log(Kt.green(`✓ Configuration saved to ${s}`)),(await Pr()).secrets}function ba(e=process.cwd()){let t=q.resolve(e);const r=q.parse(t).root;for(;t!==r;){const o=q.join(t,".codeyam","config.json");if(W.existsSync(o))return t;t=q.dirname(t)}const a=q.join(r,".codeyam","config.json");return W.existsSync(a)?r:null}let va=ba();function de(){return va}function Pi(e){va=e}function wa(e){const t={...e};for(const r in e)if(r.includes(".")){const a=r.replace(/\./g,"");t[a]=e[r]}return t}const Mi={"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>`};wa(Mi);const ki={"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>`};wa(ki);function $n(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)}const a={...e};for(const o in t)if(t[o]===null)a[o]=null;else if(Array.isArray(t[o])){a[o]=[];for(let s=0;s<t[o].length;s++){const i=t[o][s];typeof i=="object"&&i!==null?a[o][s]=$n(a?.[o]?.[s],i,r):a[o][s]=i}}else typeof t[o]=="object"&&t[o]!==null?a[o]=$n(a[o]??{},t[o],r):a[o]=t[o];return a}catch(a){throw console.log("CodeYam: Error merging data",e,t),a}}async function Ti({projectId:e,commit:t,branch:r}){let a;const o={commitId:t.id,branchId:r.id,active:!0},s=await ui({projectId:e,commitId:t.id,includeBranches:!0});if(s&&s.length>0){a=s.sort((d,u)=>(d.branch.metadata?.permanent?.order??999)-(u.branch.metadata?.permanent?.order??999))[0]?.branch,a&&r.metadata?.permanent?.order!==void 0&&(r.metadata?.permanent?.order<=a.metadata?.permanent?.order?a=r:o.active=!1);const l=s.filter(d=>d.active&&d.branch.id!==a.id||!d.active&&d.branch.id===a.id);l.length>0&&await _r(l.map(d=>({...d,active:d.branchId===a.id})))}s?.find(l=>l.branchId===o.branchId)||await _r([o])}function xt(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=de();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return he.join(e,".codeyam","db.sqlite3")}async function Ae(){const e=await _i();process.env.SQLITE_PATH=xt(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Re(e){await Ae();const t=await gi({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const a=(await fa({projectId:t.id,names:["_local"]}))?.[0];if(!a)throw new Error(`Local development branch not found for project "${e}". Please run "codeyam init" to set up local analysis.`);return{project:t,branch:a}}async function Ii(e,t,r){await Ae();const a=ri(`${e.slug}-local-${Date.now()}-${Math.random()}`),o={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:r.map(i=>({fileName:i,status:"modified",patch:""})),metadata:{baseline:!1,receivedAt:new Date().toISOString()}},s=await Ni({projectId:e.id,commits:[o]});if(!s||s.length===0)throw new Error("Failed to create fake commit");return await Ti({projectId:e.id,commit:s[0],branch:t}),s[0]}async function Tt(){await Ae();const e=await pt({});if(!e||e.length===0)return e;const t=e.filter(l=>!l.metadata?.isSuperseded),r=t.map(l=>l.sha),a=t.map(l=>l.metadata?.previousVersionWithAnalyses).filter(l=>!!l),o=[...new Set([...r,...a])],s=await Et({entityShas:o}),i=new Map;if(s)for(const l of s)i.has(l.entitySha)||i.set(l.entitySha,[]),i.get(l.entitySha).push(l);return t.map(l=>{const d=i.get(l.sha)||[];if(d.length>0)return{...l,analyses:d};const u=l.metadata?.previousVersionWithAnalyses;if(u){const m=i.get(u)||[];return{...l,analyses:m}}return{...l,analyses:[]}})}async function It(e,t){await Ae();const r=await Et({entityShas:[e],limit:1});if(r&&r.length>0&&t){const a=await ga({projectId:r[0].projectId,sha:e});if(a)for(const o of r)o.entity=a}return r||[]}async function ze(e){await Ae();const t=await ke();if(!t)return null;const{project:r}=await Re(t);return await ga({projectId:r.id,sha:e})}async function Ca(e){await Ae();const t=[],r=[];if(e.metadata?.importedExports&&e.metadata.importedExports.length>0){const a=e.metadata.importedExports;for(const o of a){if(!o.filePath||!o.name)continue;const s=await pt({projectId:e.projectId,filePaths:[o.filePath],names:[o.name]});if(s&&s.length>0){const i=s[0],l=await Et({entityShas:[i.sha],limit:1});let d,u,m;if(l&&l.length>0&&l[0].scenarios){const h=l[0],p=h.scenarios||[],f=p.length,g=p.find(b=>b.metadata?.screenshotPaths?.[0]);g&&(d=g.metadata?.screenshotPaths?.[0],u=g.name),m={status:i.metadata?.previousVersionWithAnalyses||h.entitySha!==i.sha?"out_of_date":"up_to_date",scenarioCount:f,timestamp:h.createdAt?new Date(h.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else m={status:"not_analyzed"};t.push({...i,screenshotPath:d,scenarioName:u,analysisStatus:m})}}}if(e.metadata?.importedBy){const a=[];for(const o in e.metadata.importedBy)for(const s in e.metadata.importedBy[o]){const i=e.metadata.importedBy[o][s];i.shas&&a.push(...i.shas)}if(a.length>0){const o=await pt({projectId:e.projectId,shas:a});if(o)for(const s of o){const i=await Et({entityShas:[s.sha],limit:1});let l,d,u;if(i&&i.length>0&&i[0].scenarios){const m=i[0],h=m.scenarios||[],p=h.length,f=h.find(y=>y.metadata?.screenshotPaths?.[0]);f&&(l=f.metadata?.screenshotPaths?.[0],d=f.name),u={status:s.metadata?.previousVersionWithAnalyses||m.entitySha!==s.sha?"out_of_date":"up_to_date",scenarioCount:p,timestamp:m.createdAt?new Date(m.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else u={status:"not_analyzed"};r.push({...s,screenshotPath:l,scenarioName:d,analysisStatus:u})}}}return{importedEntities:t,importingEntities:r}}async function ke(){try{const e=de();if(!e)return null;const t=he.join(e,".codeyam","config.json");return JSON.parse(await Ce.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function st(){await Ae();try{const e=await ke();if(!e)return null;const{project:t,branch:r}=await Re(e),a=await Qt({projectId:t.id,branchId:r.id,limit:1});return a&&a.length>0?a[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function er(){try{const e=de();if(!e)return null;const t=he.join(e,".codeyam","config.json");return JSON.parse(await Ce.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function Na(e){try{const t=de();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=he.join(t,e.filePath);return await Ce.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function Sa(e){if(await Ae(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await pt({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),a=await Et({entityShas:r}),o=new Map;if(a)for(const i of a)o.has(i.entitySha)||o.set(i.entitySha,[]),o.get(i.entitySha).push(i);for(const[i,l]of o.entries())l.sort((d,u)=>{const m=new Date(d.createdAt||0).getTime();return new Date(u.createdAt||0).getTime()-m});const s=t.map(i=>({...i,analyses:o.get(i.sha)||[]}));return s.sort((i,l)=>{const d=i.analyses[0]?.createdAt||i.createdAt||"",u=l.analyses[0]?.createdAt||l.createdAt||"";return new Date(u).getTime()-new Date(d).getTime()}),s}async function Ea(e){try{const t=de();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=he.join(t,".codeyam","config.json"),a=await Ce.readFile(r,"utf8"),o=JSON.parse(a),s={...o,...e},i=JSON.stringify(s,null,2);if(await Ce.writeFile(r,i,"utf8"),o.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 yi({projectSlug:o.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const Ri=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:Tt,getAnalysesForEntity:It,getCurrentCommit:st,getEntityBySha:ze,getEntityCodeFromFilesystem:Na,getEntityHistory:Sa,getProjectConfig:er,getProjectSlug:ke,getRelatedEntities:Ca,updateProjectConfig:Ea},Symbol.toStringTag,{value:"Module"})),Aa="secrets.json";function _a(e){return he.join(e,".codeyam",Aa)}function Pa(){return he.join(Dn.homedir(),".codeyam",Aa)}async function un(e){let t={};try{const r=Pa(),a=await Ce.readFile(r,"utf-8");t=JSON.parse(a)}catch{}try{const r=_a(e),a=await Ce.readFile(r,"utf-8"),o=JSON.parse(a);t={...t,...o}}catch{}return t}async function ji(e,t,r=!0){const a=r?Pa():_a(e),o=he.dirname(a);await Ce.mkdir(o,{recursive:!0}),await Ce.writeFile(a,JSON.stringify(t,null,2)+`
|
|
29
|
-
`,"utf-8")}async function Di(e){const t=await un(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 $i="/assets/globals-xPz593l2.css";function Li({text:e,subtext:t,linkText:r,linkTo:a}){const[o,s]=A(!1);return o?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:c("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[c("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"})})}),c("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(oe,{to:a,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:()=>s(!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 tn(e){return q.join(e,".codeyam","queue.json")}function Nt(e){const t=tn(e);if(!W.existsSync(t))return{paused:!1,jobs:[]};try{const r=W.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function Oi(e,t){const r=tn(e),a=q.dirname(r);W.existsSync(a)||W.mkdirSync(a,{recursive:!0});try{W.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(o){throw console.error("Failed to save queue state:",o),o}}async function Yi({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:a=!1,silent:o=!1,extraArgs:s=[]}){return new Promise((i,l)=>{const d=e.endsWith("/")?e:`${e}/`,u=t.endsWith("/")?t:`${t}/`,m=["-a"];a||m.push("--delete","--force"),m.push(...s);for(const f of r)m.push(`--exclude=${f}`);m.push(d,u);const h=Date.now(),p=Hn("rsync",m);p.on("exit",f=>{if(f===0){if(!o){const g=((Date.now()-h)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${g}s]`)}i()}else l(new Error(`rsync failed with exit code ${f}`))}),p.on("error",f=>{o||console.log("Error occurred:",f),l(f)})})}const Fi=Gn(qn);async function zi(e){return new Promise(t=>setTimeout(t,e))}function Bi(e){try{return process.kill(e,0),!0}catch{return!1}}async function Ma(e){try{const{stdout:t}=await Fi(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
|
|
30
|
-
`).filter(o=>o.trim()).map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o)),a=[...r];for(const o of r){const s=await Ma(o);a.push(...s)}return a}catch{return[]}}function Mr(e,t,r){try{process.kill(e,t)}catch(a){r?.(`Error sending ${t} to process ${e}: ${a}`)}}async function Ui(e,t,r){const a=await Ma(e);for(const o of a.reverse())await Mr(o,t,r);await Mr(e,t,r)}async function nn(e,t=console.log,r=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let a=0;async function o(s,i){await Ui(e,s,t);for(let l=0;l<i;l++)if(await zi(1e3),a+=1e3,!await Bi(e))return t(`Process tree ${e} successfully killed with ${s} after ${a/1e3} seconds.`),!0;return t(`Process tree still running after ${s}...`),!1}if(await o("SIGINT",5)||await o("SIGTERM",5))return!0;for(let s=0;s<r;s++)if(await o("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${a/1e3} seconds.`),!1}function Hi(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??=[],e.historicalRuns.push(e.currentRun)),e.currentRun={id:cs(),createdAt:t}}Qo.config({quiet:!0});var ka=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(ka||{});class qi extends Zo{constructor(){super(...arguments),this.processes=new Map}register(t){const r=es(),{process:a,type:o,name:s,metadata:i,parentId:l}=t,d={id:r,type:o,name:s,pid:a.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:l,children:[]};if(this.processes.set(r,{info:d,process:a}),l){const h=this.processes.get(l);h&&(h.info.children=h.info.children||[],h.info.children.push(r))}const u=(h,p)=>{this.handleProcessExit(r,h,p)},m=h=>{this.handleProcessError(r,h)};return a.on("exit",u),a.on("error",m),a.__cleanup=()=>{a.removeListener("exit",u),a.removeListener("error",m)},this.emit("processStarted",d),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 a=this.processes.get(t);if(!a)throw new Error(`Process not found: ${t}`);const{info:o,process:s}=a;if(o.state==="completed"||o.state==="failed"||o.state==="killed")return;if(r.shutdownChildren&&o.children&&o.children.length>0&&await Promise.all(o.children.map(l=>this.shutdown(l,r))),s.pid)try{await nn(s.pid,l=>console.log(`[Process ${t}] ${l}`))}catch(l){console.warn(`Error killing process ${t}:`,l)}await new Promise(l=>setTimeout(l,100)),o.state==="running"&&(o.state="killed",o.endedAt=Date.now());const i=s.__cleanup;i&&i()}async shutdownByType(t,r={}){const a=this.listByType(t);await Promise.all(a.map(o=>this.shutdown(o.id,r)))}async shutdownAll(t={}){const r=this.listAll();await Promise.all(r.map(a=>this.shutdown(a.id,t)))}cleanupCompleted(t={}){const{retentionMs:r=6e4}=t,a=Date.now();for(const[o,s]of this.processes.entries()){const{info:i}=s;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&a-i.endedAt>r){const l=s.process.__cleanup;l&&l(),this.processes.delete(o)}}}handleProcessExit(t,r,a){const o=this.processes.get(t);if(!o)return;const{info:s}=o;s.endedAt=Date.now(),s.exitCode=r,s.signal=a,r===0?s.state="completed":a?s.state="killed":s.state="failed",this.emit("processExited",s)}handleProcessError(t,r){const a=this.processes.get(t);if(!a)return;const{info:o}=a;o.endedAt=Date.now(),o.state="failed",o.metadata={...o.metadata,error:r.message},this.emit("processExited",o)}}let Mn=null;function Gi(){return Mn||(Mn=new qi),Mn}const Wi={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function Ji({command:e,args:t,workingDir:r,outputOptions:a=Wi,processName:o,env:s}){const i={...process.env,...s||{},CODEYAM_PROCESS_NAME:`codeyam-${o}`},l=Hn(e,t,{cwd:r,env:i});return Gi().register({process:l,type:ka.Other,name:o,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(m=>{const h=f=>{const g=he.join(r,"log.txt");W.appendFile(g,f,y=>{y&&console.log("Error writing to log file:",y)})},p=(f,g="")=>{const y=new Date().toLocaleString();return f.split(`
|
|
31
|
-
`).map(x=>x.trim()?`[${y}]${g} ${x}`:x).join(`
|
|
32
|
-
`)};l.stdout.on("data",function(f){const g=f?.toString()??"",y=p(g);a.stdoutToConsole&&console.log(y),a.stdoutToFile&&h(y+`
|
|
33
|
-
`),a.stdoutCallback&&a.stdoutCallback(g)}),l.stderr.on("data",function(f){const g=f?.toString()??"",y=p(g,"<STDERR>");a.stderrToConsole&&console.error(y),a.stderrToFile&&h(y+`
|
|
34
|
-
`),a.stderrCallback&&a.stderrCallback(g)}),l.on("exit",function(f){m(f)})}),process:l}}function Ki(e){const t=[];return Object.keys(e).forEach(r=>{const a=e[r];a!==void 0&&(typeof a=="boolean"?a&&t.push(`--${r}`):a!==null&&t.push(`--${r}`,String(a)))}),t}function Vi({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:a}){const o=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
|
|
35
|
-
`);W.writeFileSync(`${e}/.env`,o);const s=Ki(r);return Ji({command:"node",args:["--enable-source-maps","./dist/project/start.js",...s],workingDir:e,outputOptions:a,processName:"analyzer",env:t})}const Qi="/tmp/codeyam/local-dev";function Ta(e){return q.join(Qi,e)}function Ia(e){return q.join(Ta(e),"codeyam")}function it(e){return q.join(Ta(e),"project")}function mn(e){return q.join(Ia(e),"log.txt")}const Zi=[".sync-metadata.json","__codeyamMocks__"];async function Xi(e,t={}){const{port:r,silent:a=!0}=t,o=it(e);if(r)try{Se(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:a?"ignore":"inherit"})}catch{}try{Se(`lsof +D "${o}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:a?"ignore":"inherit"})}catch{}await new Promise(s=>setTimeout(s,500))}async function el(e,t={}){const{killProcesses:r=!0,port:a,silent:o=!0}=t,s=it(e),i=[],l=[];if(!W.existsSync(s))return{removed:i,errors:l};r&&await Xi(e,{port:a,silent:o});for(const d of Zi){const u=q.join(s,d);if(W.existsSync(u))try{(await Ne.stat(u)).isDirectory()?await Ne.rm(u,{recursive:!0,force:!0}):await Ne.unlink(u),i.push(d)}catch(m){l.push(`${d}: ${m instanceof Error?m.message:String(m)}`)}}return{removed:i,errors:l}}const tl=q.dirname(oa(import.meta.url));function nl(e){let t=e;for(;t!==q.dirname(t);){const r=q.join(t,"package.json");if(W.existsSync(r))try{if(JSON.parse(W.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=q.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function tr(){const e=nl(tl);return q.join(e,"analyzer-template")}function bt(e){return Ia(e)}async function kr(e){const t=tr(),r=bt(e);if(!W.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await Ne.mkdir(q.dirname(r),{recursive:!0}),await Yi({sourcePath:t,destinationPath:r,silent:!0})}function hn(e,t,r,a){const o=bt(e);if(!W.existsSync(o))throw new Error(`Analyzer not found at ${o}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const s=void 0;return Vi({absoluteCodeyamRootPath:o,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:s,stderrToConsole:!1,stderrToFile:!0,stderrCallback:s}})}function rl(e){const t=tr(),r=bt(e),a=q.join(t,".build-info.json"),o=q.join(r,".build-info.json");if(!W.existsSync(a))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!W.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!W.existsSync(o))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const s=JSON.parse(W.readFileSync(a,"utf8")),i=JSON.parse(W.readFileSync(o,"utf8"));return s.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${s.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(s){return{isFresh:!1,reason:`Error reading build markers: ${s.message}`}}}async function al(e,t){const r=bt(e);if(!W.existsSync(r)){t.update("Creating analyzer..."),await kr(e);return}const a=rl(e);a.isFresh||(t.update(`Updating analyzer (${a.reason})...`),await kr(e))}async function Ra(e){await el(e,{killProcesses:!1})}const ol=q.dirname(oa(import.meta.url));function ja(){let e=ol;for(;e!==q.dirname(e);){const t=q.join(e,"package.json");if(W.existsSync(t))try{if(JSON.parse(W.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=q.dirname(e)}return null}function sl(){const e=ja();return e?q.join(e,"package.json"):null}function qt(e){if(!W.existsSync(e))return null;try{return JSON.parse(W.readFileSync(e,"utf8"))}catch{return null}}function Da(e){let t="unknown";const r=ja(),a=sl();if(a)try{t=JSON.parse(W.readFileSync(a,"utf8")).version||"unknown"}catch{}let o=null;if(r){const m=[q.join(r,"src/webserver/build-info.json"),q.join(r,"codeyam-cli/src/webserver/build-info.json")];for(const h of m)if(o=qt(h),o)break}const s=tr(),i=q.join(s,".build-info.json"),l=qt(i);let d=null;if(e){const m=bt(e),h=q.join(m,".build-info.json");d=qt(h)}let u=!1;return l&&d?u=l.buildTime>d.buildTime:l&&!d&&e&&(u=!0),{cliVersion:t,webserverVersion:o,templateVersion:l,cachedAnalyzerVersion:d,isCacheStale:u}}function $a(e){const t=bt(e),r=q.join(t,".build-info.json");return qt(r)?.version??null}class il extends Xo{watcher=null;dbPath=null;isWatching=!1;constructor(){super(),this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=xt();const{default:t}=await import("chokidar"),r=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=t.watch(r,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",a=>{const o=Date.now(),s=new Date(o).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${a}`),console.log(`[dbNotifier] Timestamp: ${s} (${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(t){console.error("Failed to start database watcher:",t),this.emit("error",t)}}notifyChange(t="unknown"){const r=Date.now(),a=new Date(r).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${t}`),console.log(`[dbNotifier] Timestamp: ${a} (${r})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:t,timestamp:r})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const Ze=new il;async function ll(e,t){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await cl(e,t);else if(e.type==="recapture")await dl(e,t);else if(e.type==="debug-setup")await ul(e,t);else if(e.type==="interactive-start")await ml(e,t);else if(e.type==="interactive-stop")await hl(e,t);else throw new Error(`Unknown job type: ${e.type}`);console.log(`[Queue] Job ${e.id} completed successfully`)}catch(r){throw console.error(`[Queue] Job ${e.id} failed:`,r),r}}async function cl(e,t){const{projectSlug:r,commitSha:a,entityShas:o}=e;if(!a)throw new Error("Analysis job missing commitSha");const s=o||[],{project:i}=await Re(r);await Ra(r),await al(r,{update:g=>console.log(`[Queue] ${g}`)});const l=$a(r),d={...await yt(),PROJECT_SLUG:r,USE_WORKER_THREADS:"true",COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:xt(),...s.length>0?{ENTITY_SHAS:s.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...l?{ANALYZER_VERSION:l}:{}},u=i.metadata?.webapps?.[0];if(!u)throw new Error("No webapps found in project metadata");const m=e.onlyDataStructure,h={packageManager:i.metadata?.packageManager||"npm",absoluteProjectRootPath:it(r),port:0,noServer:!0,framework:u.framework,...m?{}:{orchestrateCapture:"local-sequential"}},p=hn(r,d,h),f=g=>{try{return process.kill(g,0),!0}catch{return!1}};await ut({commitSha:a,runStatusUpdate:{currentEntityShas:s,entityCount:s.length||e.filePaths?.length||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:p.process.pid}}),Ze.notifyChange("commit");try{try{const g=new Promise((y,b)=>setTimeout(()=>b(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([p.promise,g]),await ut({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),Ze.notifyChange("commit"),await ut({commitSha:a,runStatusUpdate:{currentEntityShas:[]}}),Ze.notifyChange("commit"),await new Promise(y=>setTimeout(y,2e3))}finally{if(p.process.pid)try{f(p.process.pid)&&await nn(p.process.pid,()=>{})}catch{}}}catch(g){if(console.error(`[Queue] Analysis job ${e.id} failed:`,g),p.process.pid&&f(p.process.pid))try{await nn(p.process.pid,()=>{})}catch{}try{await ut({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:g instanceof Error?g.message:String(g)}}),Ze.notifyChange("commit")}catch(y){console.error("[Queue] Failed to update commit metadata after job failure:",y)}throw g}}async function dl(e,t){const{projectSlug:r,analysisId:a,scenarioId:o,defaultWidth:s}=e;if(!a)throw new Error("Recapture job missing analysisId");const i=await We({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);if(s){const{getDatabase:p}=await import("./index-BtBPtyHx.js"),f=p(),g=await f.selectFrom("entities").select(["metadata"]).where("sha","=",i.entitySha).executeTakeFirst();let y={};g?.metadata&&(typeof g.metadata=="string"?y=JSON.parse(g.metadata):y=g.metadata),y.defaultWidth=s,await f.updateTable("entities").set({metadata:JSON.stringify(y)}).where("sha","=",i.entitySha).execute()}await kt(a,p=>{if(p.readyToBeCaptured=!0,p.scenarios)for(const f of p.scenarios)(!o||f.name===o)&&(delete f.screenshotStartedAt,delete f.screenshotFinishedAt,delete f.interactiveStartedAt,delete f.interactiveFinishedAt,delete f.error,delete f.errorStack)});const{project:l}=await Re(r),d=$a(r),u={...await yt(),PROJECT_SLUG:r,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:xt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...d?{ANALYZER_VERSION:d}:{}},m={packageManager:l.metadata?.packageManager||"npm",absoluteProjectRootPath:it(r),port:void 0,noServer:!0,framework:l.metadata?.webapps?.[0]?.framework??ln.Next,orchestrateCapture:"local-sequential"},h=hn(r,u,m);try{await h.promise}finally{try{h.process.kill("SIGTERM")}catch{}}}async function ul(e,t){const{projectSlug:r,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Debug setup job missing analysisId");const s=await We({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!s||!s.commit)throw new Error(`Analysis ${a} not found`);const{project:i}=await Re(r);await Ra(r);const l={...await yt(),PROJECT_SLUG:r,USE_WORKER_THREADS:"true",COMMIT_SHA:s.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:xt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,PREP_ONLY:"true"};o&&(l.SCENARIO_IDS=o);const d={packageManager:i.metadata?.packageManager||"npm",absoluteProjectRootPath:it(r),port:void 0,noServer:!1,framework:i.metadata?.webapps?.[0]?.framework||ln.Next},m=await hn(r,l,d).promise;if(m!==0)throw new Error(`Prep process exited with code ${m}`)}async function ml(e,t){const{projectSlug:r,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Interactive start job missing analysisId");const s=await We({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!s||!s.commit)throw new Error(`Analysis ${a} not found`);const{project:i}=await Re(r),l={...await yt(),PROJECT_SLUG:r,USE_WORKER_THREADS:"true",COMMIT_SHA:s.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:xt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,INTERACTIVE_MODE:"true"};o&&(l.SCENARIO_IDS=o);const d={packageManager:i.metadata?.packageManager||"npm",absoluteProjectRootPath:it(r),port:void 0,noServer:!1,framework:i.metadata?.webapps?.[0]?.framework||ln.Next};await kt(a,m=>{m.readyToBeCaptured=!0});const u=hn(r,l,d);await xa(a,m=>{m.interactiveMode={pid:u.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${a}, PID: ${u.process.pid}`)}async function hl(e,t){const{projectSlug:r,analysisId:a}=e;if(!a)throw new Error("Interactive stop job missing analysisId");const o=await We({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!o)throw new Error(`Analysis ${a} not found`);const s=o.metadata?.interactiveMode;if(!s?.pid){console.log(`[Queue] No interactive mode process found for analysis ${a}`);return}const i=s.pid;console.log(`[Queue] Stopping interactive mode for analysis ${a}, killing PID: ${i}`);try{try{process.kill(i,0)}catch{console.log(`[Queue] Process ${i} already exited`);return}await nn(i,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${i}`)}catch(l){throw console.error(`[Queue] Failed to kill process ${i}:`,l),l}finally{await xa(a,l=>{l.interactiveMode=null})}}class pl{constructor(t,r){this.processing=!1,this.completionCallbacks=new Map,this.completedJobs=new Map,this.projectRoot=t,this.state={paused:!1,jobs:[]},this.onStateChange=r}start(){this.state=Nt(this.projectRoot),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||Pt(),a={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(a),this.save(),console.log(`[Queue] Enqueued job ${r} (${a.type})`);const o=new Promise((s,i)=>{this.completionCallbacks.set(r,l=>{l?i(l):s()})});return this.state.paused||this.processNext().catch(s=>{console.error("[Queue] ERROR in processNext():",s)}),{jobId:r,completion:o}}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)}async processNext(){if(this.state.paused||this.processing||this.state.jobs.length===0)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 ll(t,this.projectRoot),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`)}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?.message||"Unknown error",completedAt:new Date().toISOString()});const a=this.completionCallbacks.get(t.id);a&&(a(r),this.completionCallbacks.delete(t.id))}finally{this.processing=!1,!this.state.paused&&this.state.jobs.length>0&&setImmediate(()=>{this.processNext()})}}save(){Oi(this.projectRoot,this.state),this.onStateChange&&this.onStateChange()}}class fl{constructor(t,r,a=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=a}start(){const t=tn(this.projectRoot);if(!W.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=tn(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=W.watch(r,(a,o)=>{o==="queue.json"&&(this.stop(),this.watchFile(t),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(a){console.error("[QueueFileWatcher] Failed to watch directory:",a)}}watchFile(t){try{this.watcher=W.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 gl{constructor(t,r,a){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=a,this.cachedState=Nt(r)}start(){this.cachedState=Nt(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 fl(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,a;const o=new Promise((i,l)=>{r=i,a=l}),s=`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),a(i)}),{jobId:s,completion:o}}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 a=await r.text();throw new Error(`Failed to enqueue: ${r.status} ${a}`)}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 a=await r.text();throw new Error(`Failed to ${t}: ${r.status} ${a}`)}this.refreshState()}getState(){return this.cachedState=Nt(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=Nt(this.projectRoot),this.onStateChange&&this.onStateChange()}async isServerAlive(){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),a=await fetch(`${this.serverInfo.url}/api/health`,{signal:t.signal});return clearTimeout(r),a.ok}catch{return!1}}getServerInfo(){return{...this.serverInfo}}stop(){this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null)}}function yl(e){const t=q.join(e,".codeyam","server.json");if(!W.existsSync(t))return null;try{const r=W.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function xl(e){try{return process.kill(e,0),!0}catch{return!1}}async function bl(e){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),a=await fetch(`${e}/api/health`,{signal:t.signal});return clearTimeout(r),a.ok}catch{return!1}}async function vl(e){const t=yl(e);return!t||!xl(t.pid)||!await bl(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}let mt=null,Ot=null;async function wl(){if(!mt){if(Ot){await Ot;return}Ot=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||ba()||process.cwd();Pi(e),console.log(`[GlobalQueue] Project root: ${e}`);const t=await vl(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new gl(t,e,()=>{Ze.notifyChange("unknown")});await r.start(),mt=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new pl(e,()=>{Ze.notifyChange("unknown")});await r.start(),mt=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Ot}}async function He(){return mt||await wl(),mt}function Cl(){return mt}const Nl=()=>[{rel:"stylesheet",href:$i},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}];async function Sl({request:e,context:t}){try{const r=de()||process.cwd(),[a,o,s]=await Promise.all([st(),ke(),un(r)]);if(!o)throw new Error("Project slug not found");const l=(t.analysisQueue||Cl())?.getState(),d=await Promise.all((l?.jobs||[]).map(async N=>{const M=[];if(N.entityShas&&N.entityShas.length>0){const E=N.entityShas.map(S=>ze(S)),v=await Promise.all(E);M.push(...v.filter(S=>S!==null))}return{...N,entities:M}}));let u=null;if(l?.currentlyExecuting){const N=l.currentlyExecuting,M=[];if(N.entityShas&&N.entityShas.length>0){const E=N.entityShas.map(S=>ze(S)),v=await Promise.all(E);M.push(...v.filter(S=>S!==null))}u={...N,entities:M}}let m=a?.metadata?.currentRun?.currentEntityShas||[];if(m.length===0){const N=a?.metadata?.historicalRuns||[];if(N.length>0){const E=[...N].sort((v,S)=>{const I=v.archivedAt||v.createdAt||"";return(S.archivedAt||S.createdAt||"").localeCompare(I)})[0];if(E){const v=E.analysisCompletedAt||E.createdAt;if(v){const S=new Date(v).getTime(),P=Date.now()-1440*60*1e3;S>P&&(m=E.currentEntityShas||[])}}}}const p=(await Promise.all(m.map(N=>ze(N)))).filter(N=>N!==null),f=[];s.ANTHROPIC_API_KEY&&f.push("ANTHROPIC_API_KEY"),s.GROQ_API_KEY&&f.push("GROQ_API_KEY"),s.OPENAI_API_KEY&&f.push("OPENAI_API_KEY"),s.OPENROUTER_API_KEY&&f.push("OPENROUTER_API_KEY");const{project:g,branch:y}=await Re(o),b=await Qt({projectId:g.id,branchId:y.id,limit:20}),x=[];for(const N of b){const M=N.metadata?.historicalRuns||[];for(const E of M){const v=E.currentEntityShas||[];if(v.length>0){const S=v.map(T=>ze(T)),P=(await Promise.all(S)).filter(T=>T!==null);x.push({...E,entities:P})}else x.push(E)}}const w=x.sort((N,M)=>{const E=N.archivedAt||N.analysisCompletedAt||N.createdAt||"";return(M.archivedAt||M.analysisCompletedAt||M.createdAt||"").localeCompare(E)}),C={currentRun:a?.metadata?.currentRun,projectSlug:o,currentEntities:p,availableAPIKeys:f,queuedJobCount:d.length,queueJobs:d,currentlyExecuting:u,historicalRuns:w};return $(C)}catch(r){return console.error("Failed to load root data:",r),$({currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[]})}}function El(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:a,queuedJobCount:o,queueJobs:s,currentlyExecuting:i,historicalRuns:l}=Le(),{toasts:d,closeToast:u}=Kn(),m=ft(),h=be(m),p=Yn();J(()=>{h.current=m},[m]);const f=p.pathname.startsWith("/entity/")&&p.pathname.includes("/edit/")||p.pathname.startsWith("/dev/");return J(()=>{const g=new EventSource("/api/events");let y=null,b=0;const x=2e3;return g.addEventListener("message",w=>{if(JSON.parse(w.data).type==="db-change"){const N=Date.now(),M=N-b;M<x?(y&&clearTimeout(y),y=setTimeout(()=>{h.current.revalidate(),b=Date.now(),y=null},x-M)):(h.current.revalidate(),b=N)}}),g.addEventListener("error",w=>{console.error("SSE connection error:",w)}),()=>{y&&clearTimeout(y),g.close()}},[]),c(se,{children:[c("div",{className:`min-h-screen ${f?"":"grid"} bg-cygray-10`,style:f?void 0:{gridTemplateColumns:"96px minmax(900px, 1fr)"},children:[!f&&n(bs,{}),c("div",{className:"max-h-screen overflow-auto bg-white",children:[a.length===0&&n(Li,{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"}),n(go,{})]})]}),n(Cs,{toasts:d,onClose:u}),n(Ns,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:o,queueJobs:s,currentlyExecuting:i,historicalRuns:l})]})}const Al=je(function(){return c("html",{lang:"en",children:[c("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(mo,{}),n(ho,{})]}),c("body",{children:[n(vs,{children:n(ys,{children:n(El,{})})}),n(po,{}),n(fo,{})]})]})}),_l=Object.freeze(Object.defineProperty({__proto__:null,default:Al,links:Nl,loader:Sl},Symbol.toStringTag,{value:"Module"})),La=zn({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),nr=()=>{const e=on(La);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},pn=({children:e})=>{const[t,r]=A({height:720,width:1200}),[a,o]=A(1),[s,i]=A(1200),l=be(null),d=X(({height:h,width:p})=>{r(f=>({height:h??f.height,width:p??f.width}))},[]),u=X(h=>{o(h)},[]),m=X(h=>{i(h)},[]);return n(La.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:l,scale:a,updateScale:u,maxWidth:s,updateMaxWidth:m},children:e})},Pl=ts,Ml=typeof window<"u",kl=1200,Tl=720,Tr=30,Il=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:a=1440,defaultHeight:o=900,onDataOverride:s,onIframeLoad:i,onScaleChange:l,onDimensionChange:d})=>{const[u,m]=A(!1),[h,p]=A(!1),[f,g]=A(kl),[y,b]=A(Tl),[x,w]=A(null),[C,N]=A(null),{dimensions:M,updateDimensions:E,iframeRef:v,updateScale:S,updateMaxWidth:I}=nr(),P=Z(()=>Math.min(1,f/M.width),[f,M.width]),T=C!==null?C:P;J(()=>{u||(S(T),l?.(T))},[T,S,l,u]),J(()=>{I(f)},[f,I]);const R=X(()=>{m(!0),N(P)},[P]),O=X(()=>{m(!1),N(null)},[]),k=X((ne,F)=>{const H=C!==null?C:1,_=Math.round(F.size.width/H);E({width:_}),d?.(_,M.height)},[E,C,d,M.height]),j=X(()=>{setTimeout(()=>{p(!0)},100),i&&i()},[i]);J(()=>{const ne=F=>{if(F.data.type==="codeyam-resize"){if(t&&F.data.name!==t||M.height===F.data.height||F.data.height===0)return;E({height:F.data.height})}};return window.addEventListener("message",ne),()=>{window.removeEventListener("message",ne)}},[v,t,a,M,E]),J(()=>{h&&s&&s(v.current)},[h,s,v]),J(()=>{if(!t)return;const ne=setInterval(()=>{v?.current?.contentWindow?.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(ne)},[t,v]),J(()=>{const ne=()=>{const F=document.getElementById("scenario-container");if(!F)return;const H=F.getBoundingClientRect(),_=F.clientWidth-Tr*2,B=window.innerHeight-H.top-Tr*2,U=Math.max(B,400),V=window.innerHeight-H.top;g(_),b(U),w(V)};return ne(),window.addEventListener("resize",ne),()=>window.removeEventListener("resize",ne)},[]),J(()=>{E({width:a,height:o})},[a,o,E]);const D=Z(()=>M.width*T,[M.width,T]),Y=Z(()=>{const ne=M.height,F=ne*T;return ne&&ne!==720&&ne!==900&&F<y?F:y},[M.height,y,T]),te=X(()=>{window.history.back()},[]);return Ml?c("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:x?{height:`${x}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
|
|
36
|
-
.react-resizable-handle-e {
|
|
37
|
-
display: flex !important;
|
|
38
|
-
align-items: center !important;
|
|
39
|
-
justify-content: center !important;
|
|
40
|
-
width: 6px !important;
|
|
41
|
-
height: 48px !important;
|
|
42
|
-
right: -8px !important;
|
|
43
|
-
top: 50% !important;
|
|
44
|
-
transform: translateY(-50%) !important;
|
|
45
|
-
cursor: ew-resize !important;
|
|
46
|
-
background: #d1d5db !important;
|
|
47
|
-
border-radius: 3px !important;
|
|
48
|
-
opacity: 0 !important;
|
|
49
|
-
transition: all 0.2s ease !important;
|
|
50
|
-
}
|
|
51
|
-
.react-resizable-handle-e:hover {
|
|
52
|
-
opacity: 0.8 !important;
|
|
53
|
-
background: #9ca3af !important;
|
|
54
|
-
}
|
|
55
|
-
.react-resizable:hover .react-resizable-handle-e {
|
|
56
|
-
opacity: 0.4 !important;
|
|
57
|
-
}
|
|
58
|
-
`}),n(Pl,{width:D,height:Y,minConstraints:[300,200],maxConstraints:[f,y],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:R,onResizeStop:O,onResize:k,children:n("div",{className:"overflow-auto",style:{width:`${D}px`,height:`${Y}px`},children:n("div",{style:{width:`${M.width}px`,height:`${M.height}px`,transform:`scale(${T})`,transformOrigin:"top left"},children:r?n("iframe",{ref:v,className:"w-full h-full rounded-lg",src:r,onLoad:j,sandbox:"allow-scripts allow-same-origin"}):c("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:te,children:"Go back"})]})})})},`resizable-box-${e}`)]}):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..."})})};function Rl({presets:e,customSizes:t,currentWidth:r,currentHeight:a,scale:o,onSizeChange:s,onSaveCustomSize:i,onRemoveCustomSize:l,className:d=""}){const[u,m]=A(!1),[h,p]=A(String(r)),[f,g]=A(String(a)),[y,b]=A(!1),[x,w]=A(!1),C=be(null);J(()=>{y||p(String(r))},[r,y]),J(()=>{x||g(String(a))},[a,x]),J(()=>{const R=O=>{C.current&&!C.current.contains(O.target)&&m(!1)};return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[]);const N=Z(()=>{const R=e.find(k=>k.width===r&&k.height===a);if(R)return R.name;const O=t.find(k=>k.width===r&&k.height===a);return O?O.name:"Custom"},[e,t,r,a]),M=N==="Custom",E=R=>{s(R.width,R.height),m(!1)},v=R=>{const O=R.target.value;p(O);const k=parseInt(O,10);!isNaN(k)&&k>0&&s(k,a)},S=R=>{const O=R.target.value;g(O);const k=parseInt(O,10);!isNaN(k)&&k>0&&s(r,k)},I=()=>{b(!1);const R=parseInt(h,10);(isNaN(R)||R<=0)&&p(String(r))},P=()=>{w(!1);const R=parseInt(f,10);(isNaN(R)||R<=0)&&g(String(a))},T=R=>{(R.key==="Enter"||R.key==="Escape")&&R.target.blur()};return c("div",{className:`flex items-center gap-3 ${d}`,children:[c("div",{className:"relative",ref:C,children:[c("button",{onClick:()=>m(!u),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 ${u?"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"})})]}),u&&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:c("div",{className:"py-1",children:[e.length>0&&c(se,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(R=>c("button",{onClick:()=>E(R),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===R.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:R.name}),c("span",{className:"text-xs text-gray-500",children:[R.width," x ",R.height]})]},R.name))]}),t.length>0&&c(se,{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((R,O)=>R.width-O.width).map(R=>c("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${N===R.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[c("button",{onClick:()=>E(R),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:R.name}),c("span",{className:"text-xs text-gray-500",children:[R.width," x ",R.height]})]}),l&&n("button",{onClick:O=>{O.stopPropagation(),N===R.name&&e.length>0&&s(e[0].width,e[0].height),l(R.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"})})})]},R.name))]})]})})]}),c("div",{className:"flex items-center gap-1 text-sm",children:[c("div",{className:"flex items-center",children:[n("input",{type:"text",value:h,onChange:v,onFocus:()=>b(!0),onBlur:I,onKeyDown:T,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:"×"}),c("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:S,onFocus:()=>w(!0),onBlur:P,onKeyDown:T,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"})]}),o!==void 0&&o<1&&c("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(o*100),"%)"]})]}),M&&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 kn(e,t,r){if(Array.isArray(e)){if(!isNaN(parseInt(t)))return e[parseInt(t)];for(const a of e)if(a.name===t||a.title===t||a.id===t)return a}return e[t]}function Ln(e){return e&&(typeof e=="object"||Array.isArray(e))}function jl(e){return Array.isArray(e)?e.length:void 0}function Dl(e){const{data:t,structure:r}=e;if(!(!t&&!r)){if(Array.isArray(r))return Array.isArray(t)?t.map((a,o)=>o.toString()):[];if(typeof r=="object")return[...new Set([...Object.keys(t),...Object.keys(r)])].sort((o,s)=>{const i=Ln(t[o]),l=Ln(t[s]);return i&&!l?1:!i&&l?-1:o.localeCompare(s)});if(typeof t=="object")return Object.keys(t).sort((o,s)=>o.localeCompare(s))}}function $l({scenarioFormData:e,handleInputChange:t}){return c("div",{className:"p-3 flex flex-col gap-3",children:[c("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"})]}),c("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 Ll({path:e,namedPath:t,isArray:r,count:a,onClick:o}){const s=X(()=>{o&&o(e)},[o,e]);return c("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:s,children:[c("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"})}),c("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],a!==void 0&&` (${a})`]})]}),c("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 Oa=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Oa||{});const Ol=({name:e,value:t,options:r,onChange:a})=>{const o=X(s=>{a({target:{name:e,value:s.target.value}})},[e,a]);return n("select",{name:e,value:t,onChange:o,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((s,i)=>n("option",{value:s.trim(),children:s.trim()},i))})},Yl=({name:e,value:t,onChange:r})=>{const a=X(o=>{const s=o.target.checked;r({target:{name:e,value:s}})},[e,r]);return n("label",{className:"flex items-center gap-2 cursor-pointer",children:n("input",{type:"checkbox",name:e,checked:t,onChange:a,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
|
|
59
|
-
bg-gray-300 checked:bg-blue-600
|
|
60
|
-
after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
|
|
61
|
-
after:bg-white after:rounded-full after:transition-transform
|
|
62
|
-
checked:after:translate-x-4`})})};function Fl({dataType:e,path:t,value:r,onChange:a}){const o=Z(()=>t[t.length-1],[t]),s=Z(()=>t.join("-"),[t]),i=X(d=>{a(t,d.target.value)},[a,t]),l=X(d=>{a(t,d.target.value)},[a,t]);return c("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:s,className:"capitalize text-sm font-medium text-gray-700",children:o==="~~codeyam-code~~"?"Dynamic Field":o}),e.includes("|")?n(Ol,{name:s,value:r,options:e.split("|"),onChange:i}):e===Oa.BOOLEAN?n(Yl,{name:s,value:r??!1,onChange:l}):n("input",{id:s,name:s,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-${s}`)]})}function zl({analysis:e,scenarioName:t,dataItem:r,onResult:a,onGenerateData:o}){const[s,i]=A(!1),[l,d]=A(""),u=X(async()=>{if(!o){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const h=e.scenarios.find(b=>b.name===t);if(!h)throw new Error("Scenario not found");const p=e.scenarios.find(b=>b.name===cn),f=await o(l,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const g=(b,x)=>{const w=Object.assign({},b);return y(b)&&y(x)&&Object.keys(x).forEach(C=>{y(x[C])?C in b?w[C]=g(b[C],x[C]):Object.assign(w,{[C]:x[C]}):Object.assign(w,{[C]:x[C]})}),w},y=b=>b&&typeof b=="object"&&!Array.isArray(b);h.metadata.data=g(g(p?.metadata.data||{},h.metadata.data),f.data||{}),a(h),i(!1),d("")}catch(h){console.error("Error generating AI data:",h),i(!1)}},[e,l,r,t,a,o]),m=X(h=>{d(h.target.value)},[]);return c("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:m,value:l}),n("button",{type:"button",disabled:s,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:()=>{u()},children:s?c(se,{children:[c("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 Bl({namedPath:e,path:t,last:r,onClick:a}){const o=X(()=>a(r?t.slice(0,-1):t),[r,t,a]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:o,children:e[e.length-1]})}function Ul({dataItem:e,onClick:t}){const r=X(()=>t([]),[t]),a=Z(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return c("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&&c("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(a).map((o,s)=>c("div",{className:"flex items-center gap-1",children:[n(Bl,{namedPath:e.namedPath.slice(0,s+a+1),path:e.path.slice(0,s+a+1),last:s+a===e.namedPath.length-1,onClick:t}),s+a<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-${o}-${s+a}`))]})}function Ir({analysis:e,scenarioName:t,dataItem:r,onClick:a,onChange:o,onAIResult:s,onGenerateData:i,saveFeedback:l}){const d=Z(()=>r.data,[r]),u=Z(()=>Dl(r),[r]);return c("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(Ul,{dataItem:r,onClick:a}),c("div",{className:"flex flex-col gap-3",children:[n(zl,{analysis:e,scenarioName:t,dataItem:r,onResult:s,onGenerateData:i}),u?.map((m,h)=>{if(Ln(d[m])){let f=m;isNaN(Number(m))||(f=d[m].name??d[m].title??d[m].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(m)+1}`);const g=[...r.path,m],y=[...r.namedPath,f];return n(Ll,{path:g,namedPath:y,isArray:Array.isArray(d),count:jl(d[m]),onClick:a},`data-${m}-${h}`)}if(m==="id")return null;const p=[...r.path,m];return n(Fl,{dataType:r.structure?.[m]??"string",path:p,value:d[m],onChange:o},`InputField-${p.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),c("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const m=document.getElementById("recapture-input");m&&(m.value="false")},disabled: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?.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const m=document.getElementById("recapture-input");m&&(m.value="true")},disabled: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?.message&&!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 Rr({title:e,children:t,defaultOpen:r=!1,borderT:a=!1,borderB:o=!1}){const[s,i]=A(r),l=[];return a&&l.push("border-t"),o&&l.push("border-b"),c("div",{className:`${l.join(" ")} border-gray-300`,children:[c("button",{type:"button",onClick:()=>i(!s),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 ${s?"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"})})]}),s&&n("div",{className:"px-4 py-3",children:t})]})}const Hl=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:a,shouldCreateNewScenario:o,onSave:s,onNavigate:i,iframeRef:l,onGenerateData:d,saveFeedback:u})=>{const m=X((v,S)=>{const I=Object.assign({},v),P=T=>T&&typeof T=="object"&&!Array.isArray(T);return P(v)&&P(S)&&Object.keys(S).forEach(T=>{P(S[T])?T in v?I[T]=m(v[T],S[T]):Object.assign(I,{[T]:S[T]}):Object.assign(I,{[T]:S[T]})}),I},[]),[h,p]=A({name:e.name,description:e.description,data:m(t.metadata.data,e.metadata.data)}),[f,g]=A(null),y=Z(()=>({...h.data}),[h]),b=Z(()=>({...y.mockData?{"Retrieved Data":y.mockData}:{},...y.argumentsData?{"Function Arguments":y.argumentsData}:{}}),[y]),x=Z(()=>{const v={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(v).reduce((S,I)=>{if(I.includes(".")){const[P,T]=I.split(".");S[P]||(S[P]={}),S[P][T]=v[I]}else S[I]=v[I];return S},{})},[r]),w=X(async v=>{v.preventDefault();const I=v.target.querySelector('input[name="recapture"]')?.value==="true",P={mockData:h.data.mockData??{},argumentsData:h.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:h.name,shouldRecapture:I,dataToSave:P,rawFormData:h.data,iframePayload:{arguments:y.argumentsData??[],...y.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(P,null,2).substring(0,1e3));const T=a?.scenarios.map(R=>!o&&R.name===e.name?{...R,name:h.name,description:h.description,metadata:{...R.metadata,data:P}}:R);o&&T.push({name:h.name,description:h.description,metadata:{data:P,interactiveExamplePath:a?.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",T),s&&await s(T,{recapture:I}),i&&i(h.name)},[a,e.name,h,y,o,s,i]),C=X(v=>{p(S=>({...S,[v.target.name]:v.target.value}))},[]),N=X(v=>{g(S=>{if(!S)return null;for(const I of[{arguments:v.metadata.data.argumentsData},v.metadata.data.mockData]){let P=I;for(const T of S.path)if(P=kn(P,T),!P)break;P&&(S.data=P)}return{...S}}),p({name:v.name,description:v.description,data:v.metadata.data})},[]),M=X((v,S)=>{p(I=>{for(const P of[{"Function Arguments":I.data.argumentsData},{"Retrieved Data":I.data.mockData}]){let T=P;for(const R of v.slice(0,-1))if(T=kn(T,R),!T)break;if(T){const R=T[v[v.length-1]];g(O=>O?(O.namedPath[O.namedPath.length-1]===R&&(O.namedPath[O.namedPath.length-1]=S.toString()),O.data[v[v.length-1]]=S,{...O}):null),T[v[v.length-1]]=S}}return{...I}})},[]),E=X(v=>{if(v.length===0){g(null);return}let S=b;const I=[];let P=x;for(const T of v){if(I.push(isNaN(parseInt(T))?T:S[T]?.name??S[T]?.title??S[T]?.id??T),S=kn(S,T),!S){console.log("Data not found",S,T),g(null);return}Array.isArray(P)?P=P[0]:P=P[T]}g({path:v,namedPath:I,data:S,structure:P})},[b,x]);return J(()=>{const v=S=>{S.data.type==="codeyam-log"&&S.data.data?.includes("Error")&&console.error("[ScenarioEditor] Error from iframe:",S.data.data)};return window.addEventListener("message",v),()=>window.removeEventListener("message",v)},[]),J(()=>{if(l?.current?.contentWindow){const v={arguments:y.argumentsData??[],...y.mockData??{}},S={type:"codeyam-override-data",name:e.name,data:JSON.stringify(v)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:S.type,name:S.name,dataPreview:JSON.stringify(v).substring(0,200)+"...",fullData:v}),l.current.contentWindow.postMessage(S,"*")}},[y,e,l]),n("form",{method:"post",onSubmit:v=>{w(v)},children:f?n(Ir,{analysis:a,scenarioName:h.name,dataItem:f,onClick:E,onChange:M,onAIResult:N,onGenerateData:d,saveFeedback:u}):c(se,{children:[n(Rr,{title:"Edit Name and Description",borderT:!0,children:n($l,{scenarioFormData:h,handleInputChange:C})}),e.metadata.data&&n(Rr,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(Ir,{analysis:a,scenarioName:h.name,dataItem:{path:[],namedPath:[],data:b,structure:x},onClick:E,onChange:M,onAIResult:N,onGenerateData:d,saveFeedback:u})})]})})};function jr(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function fn({analysisId:e,scenarioId:t,scenarioName:r,projectSlug:a,enabled:o=!0,refreshTrigger:s=0}){const i=we(),[l,d]=A(null),[u,m]=A(!1),[h,p]=A(!1),[f,g]=A(!1),y=be(!1),b=be(null),x=be(null),[w,C]=A(0),[N,M]=A(0),E=be(null),v=be(!1),{interactiveUrl:S,resetLogs:I}=rt(a,o),P=be(t),T=be(s);J(()=>{T.current!==s&&(T.current=s,l&&(console.log("[useInteractiveMode] Manual refresh triggered"),p(!0),g(!1),C(0),M(O=>O+1),v.current=!1,E.current&&(clearTimeout(E.current),E.current=null)))},[s,l]),J(()=>{if(P.current!==t&&(P.current=t,b.current&&x.current&&r)){const O=jr(x.current),k=jr(r),j=b.current.replace(O,k);d(j),p(!0),g(!1),C(0),M(D=>D+1),v.current=!1,E.current&&(clearTimeout(E.current),E.current=null);return}},[t,r]),J(()=>{if(S){const O=S+"?width=600px";b.current=O,r&&(x.current=r),d(O),m(!1),p(!0)}},[S]),J(()=>{const O=k=>{k.data.type==="codeyam-resize"&&(v.current||(v.current=!0,E.current&&(clearTimeout(E.current),E.current=null),C(0),g(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{p(!1)})})))};return window.addEventListener("message",O),()=>window.removeEventListener("message",O)},[]);const R=()=>{v.current=!1,E.current&&clearTimeout(E.current);const O=500*Math.pow(2,w);E.current=setTimeout(()=>{v.current||(w<2?(C(k=>k+1),M(k=>k+1),p(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),g(!0),p(!1)))},O)};return J(()=>{o&&!y.current&&t&&e&&(y.current=!0,m(!0),g(!1),d(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(k){console.error("[useInteractiveMode] Failed to clear log file:",k)}I(),i.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[o,t,e,I,a]),J(()=>{const O=e,k=()=>{if(y.current&&O){const D=new URLSearchParams({action:"stop",analysisId:O});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const Y=navigator.sendBeacon("/api/interactive-mode",D);console.log("[useInteractiveMode] sendBeacon result:",Y),Y||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:D,keepalive:!0}).catch(te=>console.error("Failed to stop interactive mode:",te)))}},j=()=>{k()};return window.addEventListener("beforeunload",j),()=>{window.removeEventListener("beforeunload",j),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:y.current,analysisId:O}),k()}},[e]),{interactiveServerUrl:l,isStarting:u,isLoading:h,showIframe:f,iframeKey:N,onIframeLoad:R}}function gn({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:a,isLoading:o,showIframe:s,iframeKey:i,onIframeLoad:l,onScaleChange:d,onDimensionChange:u,projectSlug:m,defaultWidth:h=1440,defaultHeight:p=900,retryCount:f=0}){const{lastLine:g}=rt(m??null,a||o);return r?c("div",{className:"flex-1 min-h-0 relative",children:[n("div",{style:{opacity:s?1:0},children:n(Il,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:h,defaultHeight:p,onIframeLoad:l,onScaleChange:d,onDimensionChange:u},i)}),!s&&(a||o)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center gap-3",children:[n("div",{className:"w-12 h-12",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"})})}),c("div",{className:"text-center",children:[n("p",{className:"text-base font-semibold text-[#005c75] mb-1",children:a&&!r?"Starting interactive mode...":`Checking server stability. Attempt #${f+1}..`}),g&&!r&&n("p",{className:"text-xs font-mono text-[#666] leading-relaxed",children:g}),r&&f>0&&c("p",{className:"text-xs font-mono text-[#666] leading-relaxed",children:["Waiting for application to initialize... (attempt"," ",f+1,")"]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:c("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:o?"Interactive mode ready: launching...":"Starting Interactive Mode..."}),g&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl font-['IBM_Plex_Mono']",children:g}),n("p",{className:"text-xs text-[#8e8e8e] text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:o?"Loading the page in the background...":"Setting up the dev server for this scenario..."})]})})}const ql=({data:e})=>[{title:e?.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Gl({params:e}){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 a=await It(t,!0),o=a&&a.length>0?a[0]:null;if(!o)throw new Response("Analysis not found",{status:404});const s=o.scenarios?.find(d=>d.id===r);if(!s)throw new Response("Scenario not found",{status:404});const i=o.scenarios?.find(d=>d.name===cn),l=await ke();return $({analysis:o,scenario:s,defaultScenario:i||s,entitySha:t,projectSlug:l})}function Wl(){const e=Le(),t=e.analysis,r=e.scenario,a=e.defaultScenario,o=e.entitySha,s=e.projectSlug,i=_t(),{iframeRef:l}=nr(),[d,u]=A(!1),[m,h]=A(null),[p,f]=A(null),[g,y]=A(!1),[b,x]=A(!1),[w,C]=A(null),{interactiveServerUrl:N,isStarting:M,isLoading:E,showIframe:v,iframeKey:S,onIframeLoad:I}=fn({analysisId:t?.id,scenarioId:r?.id,scenarioName:r?.name,projectSlug:s,enabled:!0}),P=X(async(k,j)=>{u(!0),h(null),f(null),console.log("[EditScenario] Starting save with options:",j),console.log("[EditScenario] Scenarios to save:",k);try{const D={analysis:t,scenarios:k};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:k.length,scenarioNames:k.map(ne=>ne.name)});const Y=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)}),te=await Y.json();if(console.log("[EditScenario] API response:",te),!Y.ok||!te.success)throw new Error(te.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),j?.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 ne={serverUrl:N,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",ne);const F=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ne)});console.log("[EditScenario] Capture response status:",F.status);const H=await F.json();if(console.log("[EditScenario] Capture response body:",H),!F.ok||!H.success)throw console.error("[EditScenario] Capture failed:",H),new Error(H.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",H),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),h("Recapture successful")}else if(j?.recapture&&!N){console.log("[EditScenario] No running server, using queued recapture");const ne=new FormData;ne.append("analysisId",t.id||""),ne.append("scenarioId",r.id||"");const F=await fetch("/api/recapture-scenario",{method:"POST",body:ne}),H=await F.json();if(!F.ok||!H.success)throw new Error(H.error||"Failed to trigger recapture");console.log("Recapture queued:",H),f(H.jobId),h("Changes saved. Screenshot recapture queued.")}else h("Changes saved successfully.")}catch(D){console.error("Error saving scenarios:",D),h(`Error: ${D instanceof Error?D.message:String(D)}`)}finally{u(!1)}},[t,r.id,N]),T=X(k=>{},[]),R=X(async(k,j)=>{const D=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:k,existingScenarios:t.scenarios,scenariosDataStructure:t.metadata?.scenariosDataStructure,editingMockName:r.name,editingMockData:j?.data})}),Y=await D.json();if(!D.ok||!Y.success)throw new Error(Y.error||"Failed to generate scenario data");return Y.data},[t,r.name]),O=X(async()=>{if(!r.id){C("Cannot delete scenario without ID");return}y(!0),C(null);try{const k=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:r.metadata?.screenshotPaths||[]})}),j=await k.json();if(!k.ok||!j.success)throw new Error(j.error||"Failed to delete scenario");i(`/entity/${o}`)}catch(k){console.error("[EditScenario] Error deleting scenario:",k),C(k instanceof Error?k.message:"Failed to delete scenario"),x(!1)}finally{y(!1)}},[r.id,r.metadata?.screenshotPaths,o,i]);return c("div",{className:"h-screen bg-gray-50 flex flex-col",children:[c("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:c(oe,{to:`/entity/${o}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",t.entity?.name]})}),c("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})]}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[c("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n(Hl,{currentScenario:r,defaultScenario:a,dataStructure:t.metadata?.scenariosDataStructure||{},analysis:t,shouldCreateNewScenario:!1,onSave:P,onNavigate:T,iframeRef:l,onGenerateData:R,saveFeedback:{isSaving:d,message:m,isError:m?.startsWith("Error")??!1}}),m==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(oe,{to:`/entity/${o}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),c("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."}),b?c("div",{className:"space-y-3",children:[c("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),c("div",{className:"flex gap-2",children:[n("button",{onClick:()=>{O()},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:()=>x(!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:()=>x(!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(gn,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:N,isStarting:M,isLoading:E,showIframe:v,iframeKey:S,onIframeLoad:I,projectSlug:s,defaultWidth:1440,defaultHeight:900})})]})]})}const Jl=je(function(){return n(pn,{children:n(Wl,{})})}),Kl=Object.freeze(Object.defineProperty({__proto__:null,default:Jl,loader:Gl,meta:ql},Symbol.toStringTag,{value:"Module"})),Vl=({data:e})=>[{title:e?.entity?`Create Scenario - ${e.entity.name} - CodeYam`:"Create Scenario - CodeYam"},{name:"description",content:"Create a new scenario"}];async function Ql({params:e}){const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await It(t,!0),a=r&&r.length>0?r[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const o=a.scenarios?.find(i=>i.name===cn);if(!o)throw new Response("Default scenario not found",{status:404});const s=await ke();return $({analysis:a,defaultScenario:o,entity:a.entity,entitySha:t,projectSlug:s})}function Zl(){const{analysis:e,defaultScenario:t,entity:r,entitySha:a,projectSlug:o}=Le(),s=_t(),{iframeRef:i}=nr(),[l,d]=A(""),[u,m]=A(!1),[h,p]=A(!1),[f,g]=A(null),[y,b]=A(null),{interactiveServerUrl:x,isStarting:w,isLoading:C,showIframe:N,iframeKey:M,onIframeLoad:E}=fn({analysisId:e?.id,scenarioId:t?.id,scenarioName:t?.name,projectSlug:o,enabled:!0}),v=X(async()=>{if(!l.trim()){g("Please describe how you want to change the scenario");return}m(!0),g(null),b("Generating scenario with AI...");try{const I=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,existingScenarios:e.scenarios,scenariosDataStructure:e.metadata?.scenariosDataStructure})}),P=await I.json();if(!I.ok||!P.success)throw new Error(P.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",P.data);const T=P.data;if(!T.name||!T.data)throw new Error("AI response missing required fields (name or data)");b("Saving new scenario..."),p(!0);const R={name:T.name,description:T.description||l,metadata:{data:T.data,interactiveExamplePath:t.metadata?.interactiveExamplePath}},O=[...e.scenarios||[],R],k=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:O})}),j=await k.json();if(!k.ok||!j.success)throw new Error(j.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",j);const D=j.analysis?.scenarios?.find(Y=>Y.name===T.name);if(!D?.id){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),b("Scenario created! Redirecting..."),setTimeout(()=>s(`/entity/${a}`),1e3);return}if(x){b("Capturing screenshot...");const Y=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:x,scenarioId:D.id,projectId:e.projectId,viewportWidth:1440})}),te=await Y.json();!Y.ok||!te.success?(console.error("[CreateScenario] Capture failed:",te),b("Scenario created! (Screenshot capture failed)")):b("Scenario created and captured!")}else b("Scenario created!");setTimeout(()=>{s(`/entity/${a}/scenarios/${D.id}`)},1e3)}catch(I){console.error("[CreateScenario] Error:",I),g(I instanceof Error?I.message:String(I)),b(null)}finally{m(!1),p(!1)}},[l,e,t,a,x,s]),S=u||h;return c("div",{className:"h-screen bg-gray-50 flex flex-col",children:[c("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:c(oe,{to:`/entity/${a}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",r?.name]})}),n("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:"Create New Scenario"}),n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:"Create a new scenario based on the Default Scenario"})]}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[c("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",children:[c("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. Describe how you'd like to change it to create your new scenario."})]}),c("div",{className:"flex-1",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"How would you like to change it for your new scenario?"}),n("textarea",{id:"prompt",value:l,onChange:I=>d(I.target.value),placeholder:"e.g., Show an empty state with no items in the list, or Display an error message when the API fails, or Show a user with admin privileges...",className:"w-full h-40 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm resize-none",disabled:S})]}),c("div",{className:"mt-6 space-y-3",children:[n("button",{onClick:()=>{v()},disabled:S||!l.trim(),className:"w-full px-4 py-2 bg-[#005c75] text-white rounded-md text-sm font-medium hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors",children:S?"Creating...":"Create Scenario"}),y&&n("div",{className:"text-sm text-blue-600 bg-blue-50 px-3 py-2 rounded-md",children:y}),f&&n("div",{className:"text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:f})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(gn,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:x,isStarting:w,isLoading:C,showIframe:N,iframeKey:M,onIframeLoad:E,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const Xl=je(function(){return n(pn,{children:n(Zl,{})})}),ec=Object.freeze(Object.defineProperty({__proto__:null,default:Xl,loader:Ql,meta:Vl},Symbol.toStringTag,{value:"Module"}));var K;(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={}))})(K||(K={}));function Ya(e,t){return e?Object.values(K.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const Fa=Ya(process.env.DEFAULT_SMALLER_MODEL,K.Model.OPENAI_GPT4_1_MINI),tc=Ya(process.env.DEFAULT_LARGER_MODEL,K.Model.OPENAI_GPT4_1),De={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},Tn={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},nc={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},In={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},Ge={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},rc={[K.Model.OPENAI_GPT5_1]:{id:K.Model.OPENAI_GPT5_1,provider:De,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[K.Model.OPENAI_GPT5]:{id:K.Model.OPENAI_GPT5,provider:De,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[K.Model.OPENAI_GPT5_MINI]:{id:K.Model.OPENAI_GPT5_MINI,provider:De,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[K.Model.OPENAI_GPT5_NANO]:{id:K.Model.OPENAI_GPT5_NANO,provider:De,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[K.Model.OPENAI_GPT4_1]:{id:K.Model.OPENAI_GPT4_1,provider:De,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[K.Model.OPENAI_GPT4_1_MINI]:{id:K.Model.OPENAI_GPT4_1_MINI,provider:De,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[K.Model.OPENAI_GPT4_O]:{id:K.Model.OPENAI_GPT4_O,provider:De,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[K.Model.OPENAI_GPT4_O_MINI]:{id:K.Model.OPENAI_GPT4_O_MINI,provider:De,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[K.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:K.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:Tn,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[K.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:K.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:Tn,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[K.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:K.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:Tn,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[K.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:K.Model.OPENAI_GPT_OSS_120B_GROQ,provider:nc,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[K.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:K.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:Ge,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[K.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:K.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:Ge,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[K.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:K.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:Ge,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[K.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:K.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:Ge,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[K.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:K.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:Ge,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[K.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:K.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:In,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[K.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:K.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:In,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[K.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:K.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:In,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[K.Model.PHIND_CODELLAMA]:{id:K.Model.PHIND_CODELLAMA,provider:De,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[K.Model.GOOGLE_GEMINI_PRO]:{id:K.Model.GOOGLE_GEMINI_PRO,provider:Ge,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[K.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:K.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:Ge,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[K.Model.META_CODELLAMA_34B_INSTRUCT]:{id:K.Model.META_CODELLAMA_34B_INSTRUCT,provider:Ge,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[K.Model.OPENAI_GPT4_PREVIEW]:{id:K.Model.OPENAI_GPT4_PREVIEW,provider:De,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function yn(e){const t=rc[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function ac(e){return yn(e).maxCompletionTokens}function oc(e){return yn(e).pricing}const Dr=1e6;function sc({model:e,usage:t}){const r=oc(e);return r?t.prompt_tokens*(r.input/Dr)+t.completion_tokens*(r.output/Dr):null}function ic({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 a=t.usage||{prompt_tokens:0,completion_tokens:0},o=sc({model:r,usage:a});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:a.prompt_tokens,output_tokens:a.completion_tokens,cost:o?Math.round(o*1e5)/1e5:void 0}}function lc({messages:{system:e,prompt:t},model:r,responseType:a,jsonSchema:o}){const s=r??Fa,i=yn(s);ac(s);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:a==="json_schema"&&o?{type:"json_schema",json_schema:{name:o.name,schema:o.schema,strict:o.strict!==!1}}:{type:a&&a=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}Gn(qn);const Yt=new rs({concurrency:100,timeout:1200*1e3,throwOnTimeout:!0,autoStart:!0}),$r={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},Ft={};async function On({type:e,systemMessage:t,prompt:r,jsonResponse:a=!0,jsonSchema:o,model:s=Fa,attempts:i=0}){if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await cc(e,process.env.CODEYAM_LLM_FIXTURES_DIR);console.log(`CodeYam Debug: LLM Pool [queued=${Yt.size}, running=${Yt.pending}]`);const l=Date.now();let d,u=0;const m=yn(s),h=process.env[m.provider.apiKeyEnvVar];if(!h)throw new Error(`API key not found for provider ${m.provider.name}. Please set ${m.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${m.provider.name} for AI request`);const p=new ns({apiKey:h,baseURL:m.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:s,responseType:o?"json_schema":a?"json_object":"text",jsonSchema:o},g=lc(f),y=await Yt.add(()=>(d=Date.now(),Nr(()=>p.chat.completions.create(g,{timeout:300*1e3}),{...$r,onFailedAttempt:E=>{u++,console.log(`CodeYam Error: Completion call failed [model=${s}]`,{error:E,prompt:r,systemMessage:t,attempts:i,retryCount:u})}})),{throwOnTimeout:!0}),b=Date.now(),x=ic({chatRequest:f,chatCompletion:y,model:s});if(!x)throw new Error("Failed to get LLM call stats");x.retries=u,x.wait_ms=d-l,x.duration_ms=b-l;const w=y.choices?.[0];let C=null;if(w){if(!w.finish_reason)throw console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({chatCompletion:y,chatRequest:f},null,2)),new Error("completionCall(): missing finish_reason in LLM response");C=w.message?.content}let N=C;C&&(N=C.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const M=a?N&&(N.match(/\{[\s\S]*\}/)?.[0]??N):N;if(!M){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:M,rawCompletion:C,chatCompletion:y,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await On({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:s,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(M.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:C,prompt:r,systemMessage:t}),new Error("Empty completion");if(a)try{JSON.parse(M)}catch(E){if(console.log("CodeYam Error: Invalid JSON in completion",{error:E.message,model:s,completion:M.substring(0,500),rawCompletion:C?.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:E.message});const v=`Your previous response contained invalid JSON with the following error:
|
|
63
|
-
|
|
64
|
-
${E.message}
|
|
65
|
-
|
|
66
|
-
Here was your previous response:
|
|
67
|
-
\`\`\`
|
|
68
|
-
${M}
|
|
69
|
-
\`\`\`
|
|
70
|
-
|
|
71
|
-
Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,S=await Yt.add(()=>Nr(()=>p.chat.completions.create({...g,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:M},{role:"user",content:v}]},{timeout:300*1e3}),{...$r,onFailedAttempt:R=>{console.log("CodeYam Error: Correction call failed",{error:R,attempts:i})}}),{throwOnTimeout:!0}),I=S.choices?.[0]?.message?.content;let P=I;I&&(P=I.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const T=P&&(P.match(/\{[\s\S]*\}/)?.[0]??P);if(!T)throw new Error("Correction attempt returned empty completion");try{JSON.parse(T),console.log("CodeYam: JSON correction successful");const R=Date.now();return x.duration_ms=R-l,{finishReason:S.choices[0].finish_reason,completion:T,stats:x}}catch(R){return console.log("CodeYam Error: Corrected JSON still invalid",{error:R.message,correctedCompletion:T.substring(0,500)}),await On({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:s,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${E.message}`)}return{finishReason:y.choices[0].finish_reason,completion:M,stats:x}}async function cc(e,t){const r=await import("fs"),a=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!r.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 o=r.readdirSync(t).filter(h=>h.endsWith(".json"));if(o.length===0)throw new Error(`No LLM fixture files found in ${t}`);const s={};for(const h of o)try{const p=r.readFileSync(a.join(t,h),"utf-8"),f=JSON.parse(p);s[f.prompt_type]||(s[f.prompt_type]=[]),s[f.prompt_type].push(f)}catch(p){console.warn(`Failed to parse LLM fixture file ${h}:`,p)}const i=s[e];if(!i||i.length===0){const h=Object.keys(s).join(", ");throw new Error(`No captured LLM call found for type '${e}'. Available types: ${h}`)}const l=`${t}::${e}`;Ft[l]||(Ft[l]=0);const d=Ft[l];Ft[l]=(d+1)%i.length;const u=i[d];console.log(`CodeYam Test: Replaying LLM response for '${e}' [${d+1}/${i.length}]`);let m;try{m=JSON.parse(u.response).choices?.[0]?.message?.content||u.response}catch{m=u.response}return{finishReason:"stop",completion:m,stats:{model:u.model??"fixture",prompt_type:e,system_message:u.system_message??"",prompt_text:u.prompt_text??"",response:u.response??"",input_tokens:u.input_tokens??0,output_tokens:u.output_tokens??0,cost:u.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(o){throw console.error("CodeYam Test Error: Failed to replay LLM call:",o),o}}function Lr(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function dc(e){const{propsJson:t,...r}=e,a=JSON.stringify(t,null,2),o=Pt(),s=Date.now(),i={...r,id:o,created_at:s,props:a};let l;const d=`${i.object_id}_${o}.json`;if(process.env.DYNAMODB_PATH?l=q.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(l=q.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),l)try{const m=q.dirname(l);return await Ne.mkdir(m,{recursive:!0}),await Ne.writeFile(l,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${l}`),{id:o}}catch(m){return console.log("CodeYam Error: Failed to save LLM call to local file",m),{id:"-1"}}const u=Lr();if(!u)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[m,h]of Object.entries(i))typeof h>"u"&&console.log(`CodeYam Warning: LLM call ${o} property ${m} with explicit value 'undefined'`);try{return await new sn().send(new as({TableName:Lr(),Item:ss(i,{removeUndefinedValues:!0})})),{id:o}}catch(m){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${u}`,m),{id:"-1"}}}new sn({});new sn({});new sn({});const uc=3,mc=2,rr=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+uc*String(t).length*(1+mc)});new Wn(rr());new Wn(rr());new Wn(rr());class hc{constructor(){this.byMethodName=new Map,this.byClassAndMethod=new Map}register(t,r,a){this.byMethodName.has(t)||this.byMethodName.set(t,[]),this.byMethodName.get(t).push(r),a&&(this.byClassAndMethod.has(a)||this.byClassAndMethod.set(a,new Map),this.byClassAndMethod.get(a).set(t,r))}getByMethodName(t){return this.byMethodName.get(t)}getByClassAndMethod(t,r){return this.byClassAndMethod.get(t)?.get(r)}}class pc{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class fc{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class gc{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];if(a.addType(s,"function"),a.addEquivalence(s.withParameter(1),r.withElement("*")),o.args.length>1){const i=o.args[1];a.addEquivalence(s.withParameter(0),i)}}}isComplete(){return!0}}class yc{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();o&&o.args.forEach(s=>{a.addEquivalence(t,s)}),a.addType(t,"array"),a.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class xc{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.withReturnValues();a.addType(o,"array")}isComplete(){return!0}}class bc{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>2)for(let s=2;s<o.args.length;s++){const i=o.args[s];a.addEquivalence(r.withElement("*"),i)}}isComplete(){return!0}}class vc{getReturnType(){return"number"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0)for(let s=0;s<o.args.length;s++)a.addEquivalence(r.withElement("*"),t.withParameter(s))}isComplete(){return!0}}class wc{getReturnType(){return"string"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addEquivalence(t.withParameter(0),s)}}isComplete(){return!0}}class Cc{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Nc{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Sc{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array"),a.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class Ec{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Ac{getReturnType(){return"object"}addEquivalences(t,r,a){const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"array")}}isComplete(){return!0}}class _c{getReturnType(){return"unknown"}addEquivalences(t,r,a){const o=t.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),r),a.addEquivalence(t.withProperty("functionCallReturnValue"),s.withProperty("returnValue"))}}isComplete(){return!0}}class Pc{getReturnType(){return"unknown"}addEquivalences(t,r,a){t.getLastFunctionCallSegment()}isComplete(){return!0}}class Mc{getReturnType(){return"array"}addEquivalences(t,r,a){const o=t.getLastFunctionCallSegment();if(a.addType(t.withParameter(1),"function"),o&&o.args.length>0){const s=o.args[0];a.addEquivalence(t.withParameter(0),s)}}isComplete(){return!0}}function kc(){const e=new hc;return e.register("filter",new pc,"Array"),e.register("map",new Cc,"Array"),e.register("flatMap",new Nc,"Array"),e.register("join",new wc,"Array"),e.register("find",new fc,"Array"),e.register("findLast",new Ec,"Array"),e.register("at",new Sc,"Array"),e.register("reduce",new gc,"Array"),e.register("concat",new yc,"Array"),e.register("slice",new xc,"Array"),e.register("splice",new bc,"Array"),e.register("push",new vc,"Array"),e.register("fromEntries",new Ac,"Object"),e.register("then",new _c,"Promise"),e.register("useState",new Mc,"React"),e.register("useMemo",new Pc,"React"),e}kc();class Tc{constructor(t){this.depth=0,this.traceCount=0,this.defaultOutput=(r,a)=>{const o=" ".repeat(this.depth),s=this.timestamps?`[${Date.now()}] `:"";a?console.info(`${s}${o}${r}`,JSON.stringify(a)):console.info(`${s}${o}${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 Tc({enabled:!1});const Ic=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),Rc=new Set(["find","findLast","at","pop","shift"]),jc=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),Dc=new Set([...Ic,...Rc,...jc]),$c=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Lc=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Oc=new Set([...$c,...Lc]);[...Dc,...Oc];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"));function za(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 os.parse(e)}catch(r){const o=r.message.match(/invalid character .* at (\d+):(\d+)/);if(o){const s=parseInt(o[2],10);if(e.substring(s-2,s-1)==='"')return e=e.substring(0,s-2)+"\\"+e.substring(s-2),za(e)}return null}}function Yc({description:e,existingScenarios:t,scenariosDataStructure:r}){return`Mock Scenario Data Structure:
|
|
72
|
-
\`\`\`
|
|
73
|
-
${JSON.stringify(r,null,2)}
|
|
74
|
-
\`\` Existing Mock Scenario Data:
|
|
75
|
-
\`\`\`
|
|
76
|
-
${JSON.stringify(t,null,2)}
|
|
77
|
-
\`\`\`
|
|
78
|
-
New Scenario user-created prompt: "${e}"
|
|
79
|
-
`}function Fc({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:o}){const s=a.find(i=>i.name===cn);return`Mock Scenario Data Structure:
|
|
80
|
-
\`\`\`
|
|
81
|
-
${JSON.stringify({props:o.arguments,dataVariables:o.dataForMocks},null,2)}
|
|
82
|
-
\`\`\`
|
|
83
|
-
|
|
84
|
-
Existing Mock Scenario Data:
|
|
85
|
-
\`\`\`
|
|
86
|
-
${JSON.stringify(a.map(i=>({name:i.name,data:$n(s.metadata.data,i.metadata.data)})),null,2)}
|
|
87
|
-
\`\`\`
|
|
88
|
-
|
|
89
|
-
Mock Scenario that should be edited: "${t}"
|
|
90
|
-
${r?`The portion of the data that should be edited:
|
|
91
|
-
\`\`\`
|
|
92
|
-
${JSON.stringify(r,null,2)}
|
|
93
|
-
\`\`\``:""}
|
|
94
|
-
|
|
95
|
-
How this data should be changed: "${e}"
|
|
96
|
-
`}async function zc({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:o,model:s}){const i=t?Fc({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:o}):Yc({description:e,existingScenarios:a,scenariosDataStructure:o}),l=await On({type:"guessScenarioDataFromDescription",systemMessage:t?Uc(r):Bc,prompt:i,model:s??tc});await dc({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:o,model:s},...l.stats});const{completion:d}=l;return d?za(d):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const Bc=`
|
|
97
|
-
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.
|
|
98
|
-
|
|
99
|
-
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.
|
|
100
|
-
|
|
101
|
-
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.
|
|
102
|
-
|
|
103
|
-
You must respond with valid JSON following this format of this TS type definition:
|
|
104
|
-
\`\`\`
|
|
105
|
-
export type ScenarioData = {
|
|
106
|
-
name: string;
|
|
107
|
-
description: string;
|
|
108
|
-
data: {
|
|
109
|
-
mockData: { [key: string]: unknown };
|
|
110
|
-
argumentsData: { [key: string]: unknown };
|
|
111
|
-
};
|
|
112
|
-
};
|
|
113
|
-
|
|
114
|
-
\`\`\`
|
|
115
|
-
`,Uc=e=>`
|
|
116
|
-
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.
|
|
117
|
-
|
|
118
|
-
Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
|
|
119
|
-
${e?`
|
|
120
|
-
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.`:""}
|
|
121
|
-
|
|
122
|
-
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.
|
|
123
|
-
|
|
124
|
-
You must respond with valid JSON following this type definition:
|
|
125
|
-
\`\`\`
|
|
126
|
-
{
|
|
127
|
-
data: {
|
|
128
|
-
mockData: { [key: string]: unknown };
|
|
129
|
-
argumentsData: { [key: string]: unknown };
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
\`\`\`
|
|
133
|
-
`;async function Hc({request:e}){if(e.method!=="POST")return $({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:a,scenariosDataStructure:o,editingMockName:s,editingMockData:i}=t;if(!r)return $({error:"Missing required field: description"},{status:400});const l=await zc({description:r,existingScenarios:a??[],scenariosDataStructure:o,editingMockName:s,editingMockData:i}),d=l?.data||l;return $({success:!0,data:d})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),$({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const qc=Object.freeze(Object.defineProperty({__proto__:null,action:Hc},Symbol.toStringTag,{value:"Module"}));async function Gc(e,t){const r=de();if(!r)return{entityCalls:[],analysisCalls:[]};const a=q.join(r,".codeyam","llm-calls");try{await Ne.access(a)}catch{return{entityCalls:[],analysisCalls:[]}}const o=[],s=[];try{const l=(await Ne.readdir(a)).filter(x=>x.endsWith(".json")),d=`${e}_`,u=t?`${t}_`:null,m=[],h=[];for(const x of l)x.startsWith(d)||u&&x.startsWith(u)?m.push(x):h.push(x);const p=m.map(async x=>{try{const w=q.join(a,x),C=await Ne.readFile(w,"utf-8");return JSON.parse(C)}catch{return null}}),f=h.map(async x=>{try{const w=q.join(a,x),C=await Ne.readFile(w,"utf-8"),N=JSON.parse(C);return N.object_id===e||t&&N.object_id===t?N:null}catch{return null}}),[g,y]=await Promise.all([Promise.all(p),Promise.all(f)]),b=[...g,...y].filter(x=>x!==null);for(const x of b)x.object_id===e?o.push(x):t&&x.object_id===t&&s.push(x);o.sort((x,w)=>w.created_at-x.created_at),s.sort((x,w)=>w.created_at-x.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:o,analysisCalls:s}}async function Wc({params:e,request:t}){const{entitySha:r}=e;if(!r)return $({error:"Entity SHA is required"},{status:400});const o=new URL(t.url).searchParams.get("analysisId")||void 0,s=await Gc(r,o);return $(s)}const Jc=Object.freeze(Object.defineProperty({__proto__:null,loader:Wc},Symbol.toStringTag,{value:"Module"}));function Kc(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=Se("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return Vc(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function Vc(e){const t=e.trim().split(`
|
|
134
|
-
`).filter(a=>a.length>0),r=[];for(const a of t){const o=a[0],s=a[1];let i=a.slice(2).replace(/^[ \t]+/,""),l,d=!1,u;if(o==="A"||s==="A")l="added",d=o==="A";else if(o==="M"||s==="M")l="modified",d=o==="M";else if(o==="D"||s==="D")l="deleted",d=o==="D";else if(o==="R"||s==="R"){l="renamed",d=o==="R";const m=i.indexOf(" -> ");m!==-1&&(u=i.slice(0,m).trim(),i=i.slice(m+4).trim())}else s==="?"?(l="untracked",d=!1):(l="modified",d=o!==" "&&o!=="?");if(i.endsWith("/")){const m=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=he.join(m,i);try{const p=(g,y)=>{const b=et.readdirSync(g,{withFileTypes:!0}),x=[];for(const w of b){const C=he.join(g,w.name),N=he.relative(m,C);w.isDirectory()?x.push(...p(C,y)):w.isFile()&&x.push(N)}return x},f=p(h,m);for(const g of f)r.push({path:g,status:l,staged:d,...u&&{oldPath:u}})}catch(p){console.error(`Failed to expand directory ${i}:`,p)}}else r.push({path:i,status:l,staged:d,...u&&{oldPath:u}})}return r}function Qc(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Se("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 Zc(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const a=Se('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(a)return a[1];try{return Se("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return Se("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 Xc(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Se('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
135
|
-
`).filter(a=>a.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function Ba(){const e=de();return e?Kc(e):[]}function ed(){const e=de();return e?Qc(e):null}function td(){const e=de();return e?Zc(e):"main"}function nd(){const e=de();return e?Xc(e):[]}function Ua(e,t){const r=de();return r?rd(e,t,r):[]}function rd(e,t,r){const a=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Se(`git diff --name-status ${e}...${t}`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
136
|
-
`).filter(i=>i.length>0).map(i=>{const l=i.split(" "),d=l[0];let u=l[1],m,h;return d==="A"?h="added":d==="M"?h="modified":d==="D"?h="deleted":d.startsWith("R")?(h="renamed",m=l[1],u=l[2]):h="modified",{path:u,status:h,...m&&{oldPath:m}}})}catch(o){return console.error("Failed to get branch diff:",o),[]}}function ad(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let a="";try{a=Se(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{a=""}let o="";try{o=et.readFileSync(he.join(r,e),"utf8")}catch(s){console.error(`Failed to read current file ${e}:`,s),o=""}return{oldContent:a,newContent:o,fileName:e}}catch(a){return console.error(`Failed to get diff for ${e}:`,a),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function od(e){const t=de();return t?ad(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function sd(e,t,r,a){const o=a||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=Se(`git show ${t}:"${e}"`,{cwd:o,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let i="";try{i=Se(`git show ${r}:"${e}"`,{cwd:o,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:s,newContent:i,fileName:e}}catch(s){return console.error(`Failed to get branch diff for ${e}:`,s),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Gt(e,t,r){const a=de();return a?sd(e,t,r,a):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Or(e,t){try{return Se(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]})?.toString()?.trim()??null}catch(r){return console.error(`Failed to get commit SHA for ${e}:`,r),""}}function id(e,t,r,a){const o=Un.createHash("sha256");return o.update(`${e}:${t}:${r}:${a}`),o.digest("hex").substring(0,16)}function Ha(){const e=de();if(!e)throw new Error("No project root found");const t=he.join(e,".codeyam","cache","branch-entity-diff");return et.existsSync(t)||et.mkdirSync(t,{recursive:!0}),t}function ld(e){try{const t=Ha(),r=he.join(t,`${e}.json`);if(!et.existsSync(r))return null;const a=et.readFileSync(r,"utf8");return JSON.parse(a)}catch(t){return console.error("Failed to read cache:",t),null}}function cd(e,t){try{const r=Ha(),a=he.join(r,`${e}.json`);et.writeFileSync(a,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function dd(e,t,r){const a=Vt(t,e),o=Vt(r,e),s=new Map(a.map(m=>[m.name,m])),i=new Map(o.map(m=>[m.name,m])),l=[],d=[],u=[];for(const[m,h]of i){const p=s.get(m);p?p.sha!==h.sha&&d.push({name:m,baseSha:p.sha,compareSha:h.sha,entityType:h.entityType}):l.push(h)}for(const[m,h]of s)i.has(m)||u.push(h);return{filePath:e,newEntities:l,modifiedEntities:d,deletedEntities:u}}function ud(e,t){const r=de();if(!r)throw new Error("No project root found");const a=Or(e,r),o=Or(t,r);if(!a||!o)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const s=id(e,t,a,o),i=ld(s);if(i)return console.log(`Using cached branch entity diff: ${s}`),i;const l=Ua(e,t),d=[];for(const m of l)if(m.path.match(/\.(tsx?|jsx?)$/))if(m.status==="deleted"){const h=Gt(m.path,e,t),p=Vt(h.oldContent,m.path);d.push({filePath:m.path,newEntities:[],modifiedEntities:[],deletedEntities:p})}else if(m.status==="added"){const h=Gt(m.path,e,t),p=Vt(h.newContent,m.path);d.push({filePath:m.path,newEntities:p,modifiedEntities:[],deletedEntities:[]})}else{const h=Gt(m.path,e,t),p=dd(m.path,h.oldContent,h.newContent);(p.newEntities.length>0||p.modifiedEntities.length>0||p.deletedEntities.length>0)&&d.push(p)}const u={baseBranch:e,compareBranch:t,baseCommitSha:a,compareCommitSha:o,fileComparisons:d,cacheKey:s,computedAt:new Date().toISOString()};return cd(s,u),u}function md({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),a=t.searchParams.get("compare");if(!r||!a)return $({error:"Missing required parameters: base and compare"},{status:400});const o=ud(r,a);return $(o)}catch(t){return console.error("Failed to compute branch entity diff:",t),$({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const hd=Object.freeze(Object.defineProperty({__proto__:null,loader:md},Symbol.toStringTag,{value:"Module"}));async function pd({request:e}){if(e.method!=="POST")return $({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:a,projectId:o,viewportWidth:s=1440}=t;if(!r||!a||!o)return $({error:"Missing required fields: serverUrl, scenarioId, and projectId"},{status:400});console.log(`[Capture] URL to capture: ${r}`),console.log(`[Capture] Scenario ID from request: ${a}`);const i=de();if(!i)return $({error:"Project root not found"},{status:500});const l=q.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:r,scenarioId:a,projectId:o,projectRoot:i,viewportWidth:s}),u=await new Promise(p=>{const f=q.join(i,".codeyam","db.sqlite3"),g=Hn("npx",["tsx",l,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let y="",b="";g.stdout.on("data",x=>{const w=x.toString();y+=w;const C=w.trim().split(`
|
|
137
|
-
`);for(const N of C)N.includes("[Capture]")&&console.log(N)}),g.stderr.on("data",x=>{const w=x.toString();b+=w,console.error("[Capture:Error]",w.trim())}),g.on("close",x=>{p(x===0?{success:!0,output:y}:{success:!1,output:y,error:b||`Process exited with code ${x}`})}),g.on("error",x=>{console.error("[Capture] Failed to spawn child process:",x),p({success:!1,output:"",error:x.message})})});if(!u.success)return $({error:"Failed to capture screenshot",details:u.error},{status:500});const m=u.output.match(/\[Capture\] RESULT:(.+)/);if(!m)return $({error:"Failed to parse capture result"},{status:500});const h=JSON.parse(m[1]);return $(h)}catch(t){return console.error("[Capture] Error:",t),$({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const fd=Object.freeze(Object.defineProperty({__proto__:null,action:pd},Symbol.toStringTag,{value:"Module"}));async function gd(e,t,r){console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await Ae();const a=await We({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const o=fe(),s=a.entitySha,i=await o.selectFrom("entities").select(["metadata"]).where("sha","=",s).executeTakeFirst();let l={};if(i?.metadata&&(typeof i.metadata=="string"?l=JSON.parse(i.metadata):l=i.metadata),l.defaultWidth=t,await o.updateTable("entities").set({metadata:JSON.stringify(l)}).where("sha","=",s).execute(),console.log(`[recapture] Updated defaultWidth for entity ${s} to ${t}`),!a.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${a.scenarios?.length||0} scenarios`),await kt(e,f=>{if(f&&(f.readyToBeCaptured=!0,f.scenarios))for(const g of f.scenarios)delete g.screenshotStartedAt,delete g.screenshotFinishedAt,delete g.interactiveStartedAt,delete g.interactiveFinishedAt}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const d=de();if(!d)throw new Error("Project root not found");const u=q.join(d,".codeyam","config.json"),m=JSON.parse(W.readFileSync(u,"utf8")),{projectSlug:h}=m;if(!h)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:h,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${p}`),{jobId:p}}async function yd(e,t,r){console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await Ae();const a=await We({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);if(!a.commit)throw new Error(`Commit not found for analysis ${e}`);const o=a.scenarios?.find(m=>m.id===t);if(!o)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: ${o.name}`),await kt(e,m=>{if(m&&(m.readyToBeCaptured=!0,m.scenarios)){const h=m.scenarios.find(p=>p.name===o.name);h&&(delete h.error,delete h.errorStack,delete h.screenshotStartedAt,delete h.screenshotFinishedAt,delete h.interactiveStartedAt,delete h.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${o.name} for recapture`);const s=de();if(!s)throw new Error("Project root not found");const i=q.join(s,".codeyam","config.json"),l=JSON.parse(W.readFileSync(i,"utf8")),{projectSlug:d}=l;if(!d)throw new Error("Project slug not found in config");const{jobId:u}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:d,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${u}`),{jobId:u}}async function xd({request:e,context:t}){if(e.method!=="POST")return $({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await He()),!r)return $({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("analysisId"),s=a.get("scenarioId");if(!o||!s)return $({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${o}, scenario ${s}`);const i=await yd(o,s,r);return console.log("[API] Scenario recapture queued",i),$({success:!0,message:"Scenario recapture queued",...i})}catch(a){return console.log("[API] Error during scenario recapture:",a),$({error:"Failed to recapture scenario",details:a instanceof Error?a.message:String(a)},{status:500})}}const bd=Object.freeze(Object.defineProperty({__proto__:null,action:xd},Symbol.toStringTag,{value:"Module"}));async function vd({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 a=mn(r);try{return await Wo(a,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(o){console.error("[api.logs] Error clearing log file:",o);const s=o instanceof Error?o.message:String(o);return new Response(`Error clearing log file: ${s}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function wd({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=mn(t);try{if(!Fo(r))return new Response("No logs available yet. Analysis may not have started.",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});const a=await Jo(r,"utf-8");return!a||a.trim().length===0?new Response("Log file is empty. Waiting for analysis to start...",{headers:{"Content-Type":"text/plain; charset=utf-8"}}):new Response(a,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(a){console.error("[api.logs] Error reading log file:",a);const o=a instanceof Error?a.message:String(a);return new Response(`Error reading log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const Cd=Object.freeze(Object.defineProperty({__proto__:null,action:vd,loader:wd},Symbol.toStringTag,{value:"Module"}));async function Nd(e,t){console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await Ae();const r=await We({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const a=r.scenarios?.find(s=>s.id===t);if(!a)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${a.name}`);const o={returnValue:{status:"success",data:a.metadata?.data?.argumentsData?.[0]||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify(a.metadata?.data?.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}`),o}async function Sd({request:e}){if(e.method!=="POST")return $({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),a=t.get("scenarioId");if(!r||!a)return $({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${a}`);const o=await Nd(r,a);return console.log("[API] Function execution completed successfully"),$({success:!0,result:o})}catch(t){return console.log("[API] Error during function execution:",t),$({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const Ed=Object.freeze(Object.defineProperty({__proto__:null,action:Sd},Symbol.toStringTag,{value:"Module"}));function Ad({request:e}){return $({status:"ok"})}async function _d({request:e,context:t}){if(e.method!=="POST")return $({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await He()),!r)return console.error("[Interactive Mode API] Queue not initialized"),$({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("action"),s=a.get("analysisId"),i=a.get("scenarioId");if(!o||!s)return $({error:"Missing required fields: action and analysisId"},{status:400});if(o!=="start"&&o!=="stop")return $({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await ke();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return $({error:"Project not initialized"},{status:500});if(o==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:s,scenarioId:i,projectSlug:l});return $({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:s,projectSlug:l});return $({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:d})}}catch(a){console.error("[Interactive Mode API] Error:",a);const o=a instanceof Error?a.message:String(a),s=a instanceof Error?a.stack:void 0;return console.error("[Interactive Mode API] Error stack:",s),$({error:"Failed to control interactive mode",details:o},{status:500})}}const Pd=Object.freeze(Object.defineProperty({__proto__:null,action:_d,loader:Ad},Symbol.toStringTag,{value:"Module"}));async function Md({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,screenshotPaths:a}=t;if(!r)return Response.json({error:"Missing required field: scenarioId"},{status:400});if(console.log(`[API] Deleting scenario ${r}`),a&&a.length>0){const o=de();if(o)for(const s of a){const i=he.join(o,".codeyam","captures","screenshots",s);try{await Ce.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(l){console.log(`[API] Could not delete screenshot ${i}:`,l instanceof Error?l.message:l)}}}return await ni({ids:[r]}),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 kd=Object.freeze(Object.defineProperty({__proto__:null,action:Md},Symbol.toStringTag,{value:"Module"})),Wt="/tmp/codeyam",Yr=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",qa=500,Td=qa*1024*1024;function dt(e,t){try{return Se(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function Fr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Id(e){return dt("config user.email",e)}function Rd(e,t=20){const r=q.join(Wt,"local-dev",e,"codeyam","log.txt");if(!W.existsSync(r))return[];try{return W.readFileSync(r,"utf8").split(`
|
|
138
|
-
`).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}function jd(e){const{projectRoot:t,projectSlug:r,outputPath:a,feedback:o,screenshot:s,onProgress:i}=e,l=i||(()=>{});l("Gathering metadata...");const d=dt("rev-parse HEAD",t)||"unknown",u=dt("rev-parse --abbrev-ref HEAD",t)||"unknown",m=dt("status --porcelain",t),h=dt("remote get-url origin",t),p=m!==null&&m.length>0,f=Da(r),g={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:d,branch:u,isDirty:p,remoteUrl:h},versions:{cli:f.cliVersion,webserver:f.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:o};l("Preparing report...");const y=dt("ls-files --cached --others --exclude-standard",t);if(y===null)throw new Error("Could not run git ls-files. Is this a git repository?");const b=new Set(y.split(`
|
|
139
|
-
`).filter(Boolean));b.add(".codeyam"),b.add(".git");const x=Date.now(),w=q.join(Wt,`report-staging-${x}`),C=q.join(w,"report"),N=q.join(C,"project");W.mkdirSync(N,{recursive:!0});try{for(const I of b){const P=q.join(t,I),T=q.join(N,I);if(W.existsSync(P)){const R=q.dirname(T);W.mkdirSync(R,{recursive:!0}),W.statSync(P).isDirectory()?W.cpSync(P,T,{recursive:!0}):W.copyFileSync(P,T)}}W.writeFileSync(q.join(C,"report-meta.json"),JSON.stringify(g,null,2));const M=q.join(Wt,"local-dev",r,"codeyam","log.txt");W.existsSync(M)?W.copyFileSync(M,q.join(C,"codeyam-log.txt")):W.writeFileSync(q.join(C,"codeyam-log.txt"),`# Log file not found
|
|
140
|
-
`),s&&s.length>0&&(W.writeFileSync(q.join(C,"screenshot.jpg"),s),l(`Screenshot included (${Fr(s.length)})`)),l("Creating archive...");const E=q.join(Wt,`report-${r}-${x}.tar.gz`),v=a||E;try{Se(`tar -czf "${v}" -C "${w}" report`,{stdio:"pipe"})}catch(I){throw new Error(`tar failed: ${I.message}`)}const S=W.statSync(v);if(S.size>Td)throw W.unlinkSync(v),new Error(`Report too large: ${Fr(S.size)} (max: ${qa} MB). Try removing large files from the project or adding them to .gitignore`);return{path:v,metadata:g,size:S.size}}finally{W.rmSync(w,{recursive:!0,force:!0})}}async function Dd(e){const{archivePath:t,projectSlug:r,metadata:a,onProgress:o}=e,s=o||(()=>{}),i=W.statSync(t);s("Requesting upload URL...");const l=await fetch(`${Yr}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:r,fileSizeBytes:i.size,metadata:{timestamp:a.timestamp,git:a.git,versions:a.versions,system:a.system,feedback:a.feedback}})});if(!l.ok){const f=await l.json();throw new Error(f.error||`Server returned ${l.status}`)}const{reportId:d,uploadUrl:u}=await l.json();s("Uploading report...");const m=W.readFileSync(t),h=await fetch(u,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:m});if(!h.ok)throw new Error(`Upload failed: ${h.status}`);s("Confirming upload...");const p=await fetch(`${Yr}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:d})});if(!p.ok){const f=await p.json();throw new Error(f.error||`Confirm failed: ${p.status}`)}return{reportId:d}}async function $d({request:e}){if(e.method!=="POST")return $({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),a=t.get("description"),o=t.get("email"),s=t.get("source"),i=t.get("entitySha"),l=t.get("scenarioId"),d=t.get("analysisId"),u=t.get("currentUrl"),m=t.get("screenshot");let h;if(m&&m.size>0){const x=await m.arrayBuffer();h=Buffer.from(x),console.log(`[Report] Screenshot received: ${m.size} bytes`)}const p=de();if(!p)return $({error:"Project root not found"},{status:500});const f=await ke();if(!f)return $({error:"Project slug not found"},{status:500});const g={issueType:r||"other",description:a||void 0,email:o||void 0,source:s||"navbar",entitySha:i||void 0,scenarioId:l||void 0,analysisId:d||void 0,currentUrl:u||void 0,recentActivity:Rd(f,20)};console.log(`[Report] Generating report for ${f}...`),console.log(`[Report] Context: ${g.source}, issue: ${g.issueType}`);const y=await jd({projectRoot:p,projectSlug:f,feedback:g,screenshot:h,onProgress:x=>{console.log(`[Report] ${x}`)}});console.log(`[Report] Archive created: ${y.path} (${y.size} bytes)`);const b=await Dd({archivePath:y.path,projectSlug:f,metadata:y.metadata,onProgress:x=>{console.log(`[Report] ${x}`)}});return console.log(`[Report] Upload complete: ${b.reportId}`),$({success:!0,reportId:b.reportId,size:y.size})}catch(t){return console.error("[Report] Error:",t),$({error:t.message||"Failed to generate report"},{status:500})}}function Ld(){const e=de(),t=e?Id(e):null;return $({defaultEmail:t})}const Od=Object.freeze(Object.defineProperty({__proto__:null,action:$d,loader:Ld},Symbol.toStringTag,{value:"Module"})),zr=Gn(qn);async function Yd({request:e}){const r=new URL(e.url).searchParams.get("pids");if(!r)return Response.json({error:"Missing pids parameter"},{status:400});const a=r.split(",").map(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s));if(a.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const o=await Promise.all(a.map(async s=>{const i=Fd(s),l=i?await zd(s):null;return{pid:s,isRunning:i,processName:l}}));return Response.json({processes:o})}function Fd(e){try{return process.kill(e,0),!0}catch{return!1}}async function zd(e){try{const{stdout:t}=await zr(`ps -p ${e} -o comm=`);return t.trim()||null}catch{try{const{stdout:r}=await zr(`ps -p ${e} -o args=`),a=r.trim(),o=a.match(/codeyam-(\w+)/);return o?`codeyam-${o[1]}`:a.split(" ")[0]||null}catch{return null}}}const Bd=Object.freeze(Object.defineProperty({__proto__:null,loader:Yd},Symbol.toStringTag,{value:"Module"}));async function Ud({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:a}=t;if(!r||!a)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 ${a.length} scenarios to save`),a.forEach((l,d)=>{const u=l.metadata?.data?.argumentsData,m=Array.isArray(u)&&u.length>0?JSON.stringify(u[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${d}: ${l.name}`,{id:l.id,projectId:l.projectId,analysisId:l.analysisId,hasMetadata:!!l.metadata,hasData:!!l.metadata?.data,mockDataKeys:l.metadata?.data?.mockData?Object.keys(l.metadata.data.mockData):[],argumentsDataLength:Array.isArray(u)?u.length:"not-array",argumentsDataPreview:m})});const o=a.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),s=await bi(o);if(!s||s.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 ${s.length} scenarios to database`),s.forEach((l,d)=>{const u=l.metadata?.data?.argumentsData;console.log(`[API] Saved scenario ${d}: ${l.name}`,{id:l.id,argumentsDataLength:Array.isArray(u)?u.length:"not-array"})});const i={...r,scenarios:s};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 Hd=Object.freeze(Object.defineProperty({__proto__:null,action:Ud},Symbol.toStringTag,{value:"Module"}));async function qd({request:e}){try{const t=await e.json(),{pid:r,signal:a="SIGTERM",commitSha:o}=t;if(!r||typeof r!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!Br(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,a)}catch(m){return Response.json({error:"Failed to kill process",pid:r,details:m instanceof Error?m.message:String(m)},{status:500})}const i=3e4,l=500,d=Date.now();let u=!0;for(;u&&Date.now()-d<i;)await new Promise(m=>setTimeout(m,l)),u=Br(r);if(u){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(m=>setTimeout(m,2e3))}catch(m){console.error(`Failed to SIGKILL process ${r}:`,m)}}if(o)try{await ut({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(m){console.error("Failed to update database after killing process:",m)}return Response.json({success:!0,pid:r,signal:a,message:`Process ${r} killed successfully`,waitedMs:Date.now()-d})}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 Br(e){try{return process.kill(e,0),!0}catch{return!1}}const Gd=Object.freeze(Object.defineProperty({__proto__:null,action:qd},Symbol.toStringTag,{value:"Module"}));async function Wd({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=de();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const a=he.join(r,".codeyam","captures","screenshots",t);try{await Ce.access(a);const o=await Ce.readFile(a),s=he.extname(a).toLowerCase(),i=s===".png"?"image/png":s===".jpg"||s===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(o,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const Jd=Object.freeze(Object.defineProperty({__proto__:null,loader:Wd},Symbol.toStringTag,{value:"Module"}));function Kd({scenarioName:e,className:t=""}){return n("div",{className:`flex items-center justify-center rounded-[4px] flex-shrink-0 ${t}`,style:{width:"160px",height:"90px",backgroundColor:"#f5f8fa"},"aria-label":e?`Loading ${e}`:"Loading scenario",children:n($e,{size:20,strokeWidth:2,className:"animate-spin",style:{color:"#005c75"}})})}const Ur={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 ar({type:e,className:t=""}){const r=Ur[e]||Ur.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 Vd={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 zt({variant:e,pid:t,label:r,className:a=""}){const o=Vd[e],s=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] ${a}`,style:{backgroundColor:o.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:o.borderColor,height:"20px"},children:n("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:o.textColor},children:s})})}async function Qd({request:e,context:t,params:r}){let a=t.analysisQueue;a||(a=await He());const o=new URL(e.url),s=parseInt(o.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!a)return $({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:s,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:l,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1},{status:500});const d=a.getState(),u=await ke();let m=null;if(u&&d?.currentlyExecuting?.commitSha){const{project:k,branch:j}=await Re(u),D=await Qt({projectId:k.id,branchId:j.id,shas:[d.currentlyExecuting.commitSha]});m=D&&D.length>0?D[0]:null}else m=await st();const h=async k=>{const j=await ze(k);if(!j)return null;const{getAnalysesForEntity:D}=await Promise.resolve().then(()=>Ri),Y=await D(k,!1);return{...j,analyses:Y||[]}},p=await Promise.all((d?.jobs||[]).map(async k=>{const j=[];if(k.entityShas&&k.entityShas.length>0){const D=k.entityShas.map(te=>h(te)),Y=await Promise.all(D);j.push(...Y.filter(te=>te!==null))}return{...k,entities:j}}));let f=null;if(d?.currentlyExecuting){const k=d.currentlyExecuting,j=[];if(k.entityShas&&k.entityShas.length>0){const D=k.entityShas.map(te=>h(te)),Y=await Promise.all(D);j.push(...Y.filter(te=>te!==null))}f={...k,entities:j}}const g=m?.metadata?.currentRun?.currentEntityShas||[],b=(await Promise.all(g.map(k=>h(k)))).filter(k=>k!==null),x=[];if(u)try{const{project:k,branch:j}=await Re(u),D=await Qt({projectId:k.id,branchId:j.id,limit:100});for(const Y of D){const te=Y.metadata?.historicalRuns||[];x.push(...te)}}catch(k){console.error("[activity.tsx] Failed to load historical runs from commits:",k)}const w=[...x].sort((k,j)=>{const D=k.archivedAt||k.createdAt||"";return(j.archivedAt||j.createdAt||"").localeCompare(D)}),C=(s-1)*i,N=C+i,M=w.slice(C,N),E=Math.ceil(w.length/i),v=await Promise.all(M.map(async k=>{const j=k.currentEntityShas||[];if(j.length===0)return{...k,entities:[]};const D=await Promise.all(j.map(Y=>h(Y)));return{...k,entities:D.filter(Y=>Y!==null)}})),S=!!f,I=p.length,P=w.filter(k=>{const j=!!k.failedAt,D=k.readyToBeCaptured,Y=k.capturesCompleted??0,te=D===void 0?!0:D===0||Y>=D;return!j&&!!k.analysisCompletedAt&&te}),R=(await Promise.all(P.slice(0,3).map(async k=>{const j=k.currentEntityShas||[];if(j.length===0)return{run:k,entities:[]};const D=await Promise.all(j.map(Y=>h(Y)));return{run:k,entities:D.filter(Y=>Y!==null)}}))).flatMap(({run:k,entities:j})=>j.map(D=>({...D,runId:k.id,completedAt:k.analysisCompletedAt||k.archivedAt||k.createdAt})));let O=[];if(m?.metadata?.currentRun?.analysisCompletedAt&&b.length>0){const k=b[0].sha,j=await It(k);j&&j.length>0&&j[0].scenarios&&(O=j[0].scenarios)}return $({state:{...d,jobs:p,currentlyExecuting:f},currentRun:m?.metadata?.currentRun,historicalRuns:v,totalHistoricalRuns:w.length,currentPage:s,totalPages:E,projectSlug:u,commitSha:m?.sha,queueJobs:p,currentlyExecuting:f,currentEntities:b,tab:l,hasCurrentActivity:S,queuedCount:I,recentCompletedEntities:R,hasMoreCompletedRuns:P.length>3,currentEntityScenarios:O})}function Zd({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:a}){const o=[{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:a>0,count:a}];return n("div",{className:"border-b border-gray-200 mb-6",children:n("nav",{className:"flex gap-8",children:o.map(s=>{const i=e===s.id;return n(oe,{to:s.id==="current"?"/activity":`/activity/${s.id}`,className:`
|
|
141
|
-
relative pb-4 px-2 text-sm font-medium transition-colors cursor-pointer
|
|
142
|
-
${i?"border-b-2":"text-gray-500 hover:text-gray-700"}
|
|
143
|
-
`,style:i?{color:"#005C75",borderColor:"#005C75"}:{},children:c("span",{className:"flex items-center gap-2",children:[s.label,s.count!==null&&s.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:s.count}),s.count===null&&s.hasContent&&n("span",{className:`
|
|
144
|
-
inline-block w-2 h-2 rounded-full
|
|
145
|
-
${i?"":"bg-gray-400"}
|
|
146
|
-
`,style:i?{backgroundColor:"#005C75"}:{}})]})},s.id)})})})}function Xd({currentlyExecuting:e,currentRun:t,state:r,projectSlug:a,commitSha:o,onShowLogs:s,recentCompletedEntities:i,hasMoreCompletedRuns:l,currentEntityScenarios:d}){const[u,m]=A({}),[h,p]=A({isKilling:!1,current:0,total:0}),f=ft(),g=!!e,y=e?.entities||[],b=!!t?.analysisCompletedAt,x=b&&!!t?.capturePid,w=!b,C=g,N=d||[],{lastLine:M}=rt(a,C);J(()=>{if(!t)return;const v=[t.analyzerPid,t.capturePid].filter(T=>!!T);if(v.length===0)return;let S=!0;const I=async()=>{try{const R=await(await fetch(`/api/process-status?pids=${v.join(",")}`)).json();if(R.processes&&S){const O={};R.processes.forEach(k=>{O[k.pid]={isRunning:k.isRunning,processName:k.processName}}),m(O)}}catch(T){S&&console.error("Failed to fetch process statuses:",T)}};I();const P=setInterval(()=>{I()},5e3);return()=>{S=!1,clearInterval(P)}},[t?.analyzerPid,t?.capturePid]);const E=y?.[0];return c("div",{className:"flex flex-col gap-[45px]",children:[C?c("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"2px solid #005C75"},children:[c("div",{className:"flex items-center gap-2 mb-[15px]",children:[n($e,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:x?"Capturing...":"Analyzing..."})]}),E&&c("div",{className:"bg-white border border-[#e1e1e1] rounded-[4px] mb-[15px]",style:{height:"60px",padding:"0 15px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[c("div",{className:"inline-grid place-items-start relative",style:{gridTemplateColumns:"max-content",gridTemplateRows:"max-content",lineHeight:0},children:[n("div",{className:"relative",style:{gridArea:"1 / 1",marginLeft:"10px",marginTop:"8.97px"},children:n("div",{style:{transform:"scale(1.33)"},children:n(Pe,{type:E.entityType||"other"})})}),c("div",{className:"flex flex-col gap-[1px] relative",style:{gridArea:"1 / 1",marginLeft:"49px",marginTop:"0"},children:[c("div",{className:"flex items-center gap-[14px]",children:[n(oe,{to:`/entity/${E.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:E.name}),E.entityType&&n(ar,{type:E.entityType})]}),n("div",{className:"truncate",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:E.filePath,children:E.filePath})]})]}),n("button",{onClick:s,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"})]}),x&&N&&N.length>0&&n("div",{className:"flex gap-2 overflow-x-auto mb-[15px]",children:N.map(v=>n(Kd,{scenarioName:v.name},v.id))}),M&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:M}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-2",children:[c("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),t?.analyzerPid&&n(zt,{variant:"analyzer",pid:t.analyzerPid}),t?.analyzerPid&&(w||u[t.analyzerPid]?.isRunning)&&n(zt,{variant:"running"}),t?.capturePid&&n(zt,{variant:"capture",pid:t.capturePid}),t?.capturePid&&(x||u[t.capturePid]?.isRunning)&&n(zt,{variant:"running"})]}),(u[t?.analyzerPid]?.isRunning||u[t?.capturePid]?.isRunning)&&n("button",{onClick:()=>{const v=[t?.analyzerPid,t?.capturePid].filter(P=>!!P&&u[P]?.isRunning);if(v.length===0)return;const S=v.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${S})?`))return;p({isKilling:!0,current:1,total:v.length}),(async()=>{for(let P=0;P<v.length;P++){const T=v[P];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:T,commitSha:o||""})})}catch(R){console.error(`Failed to kill process ${T}:`,R)}P<v.length-1&&p({isKilling:!0,current:P+2,total:v.length})}p({isKilling:!1,current:0,total:0}),f.revalidate()})()},disabled:h.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:h.isKilling?"Killing...":"Kill All Processes"})]})]}):c("div",{className:"bg-[#efefef] rounded-xl p-8 text-center",children:[n("div",{className:"flex justify-center mb-4",children:n("div",{className:"p-[10px] bg-gray-200 rounded",children:n(To,{size:24,className:"text-gray-600"})})}),n("h3",{className:"font-semibold text-gray-700 mb-2",style:{fontSize:"16px",lineHeight:"24px"},children:"No Current Activity"}),c("p",{className:"text-gray-500",style:{fontSize:"14px",lineHeight:"18px"},children:["There are no analyses currently running. Trigger an analysis from the"," ",n(oe,{to:"/git",className:"text-[#005C75] underline hover:text-[#004a5e] font-medium cursor-pointer",children:"Git"})," ","or"," ",n(oe,{to:"/files",className:"text-[#005C75] underline hover:text-[#004a5e] font-medium cursor-pointer",children:"Files"})," ","page."]})]}),i&&i.length>0&&c("div",{children:[n("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434",marginBottom:"16px"},children:"Recently Completed Analyses"}),n("div",{className:"flex flex-col gap-4",children:i.map(v=>{const S=v.analyses?.[0],I=S?.scenarios||[];return S?.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#f2fcf9",border:"2px solid #aff1a9"},children:c("div",{className:"flex flex-col gap-[15px]",children:[c("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",style:{transform:"scale(1.33)",marginLeft:"10px"},children:n(Pe,{type:v.entityType||"other"})}),c("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[c("div",{className:"flex items-center gap-[5px]",children:[n(oe,{to:`/entity/${v.sha}`,className:"hover:underline cursor-pointer",title:v.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:v.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:v.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"13px",lineHeight:"18px",color:"#646464",fontWeight:400,width:"422px"},className:"truncate",title:v.filePath,children:v.filePath})]}),n("div",{className:"flex-1"}),n("div",{className:"flex-shrink-0",children:n("button",{onClick:s,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:P=>{P.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:P=>{P.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),I.length>0?n("div",{className:"flex gap-[10px] overflow-x-auto",children:I.map((P,T)=>{if(!P.id)return null;const R=P.metadata?.screenshotPaths?.[0];return n(oe,{to:`/entity/${v.sha}/scenarios/${P.id}`,className:"border border-[#ccc] border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"144px",height:"96px"},children:R?n("img",{src:`/api/screenshot/${R}`,alt:P.name,className:"w-full h-full object-contain bg-gray-100"}):n("div",{className:"w-full h-full bg-gray-100 flex items-center justify-center text-xs text-gray-400",children:"No preview"})},T)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464"},children:"No scenarios available"})]})},v.sha)})})]})]})}function eu({queueJobs:e,state:t,currentRun:r}){return!e||e.length===0?c("div",{className:"rounded-xl p-12 text-center",style:{backgroundColor:"#EFEFEF"},children:[n("div",{className:"flex justify-center mb-4",children:n(ListTodo,{size:24,style:{color:"#646464"}})}),n("h3",{className:"font-semibold mb-2",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:"No Queued Jobs"}),n("p",{style:{fontSize:"14px",lineHeight:"18px",color:"#646464"},children:"Analysis jobs will appear here when they are queued but not yet started."})]}):c("div",{children:[c("div",{className:"flex items-center justify-between mb-4",children:[c("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:()=>{(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(a){console.error("Failed to cancel jobs:",a)}})()},className:"px-3 py-1 rounded transition-colors",style:{backgroundColor:"#fee2e2",color:"#991b1b",fontSize:"12px",fontWeight:600},children:"Cancel All"})]}),n("div",{className:"flex flex-col gap-4",children:e.map((a,o)=>{const s=a.entities?.[0];return n("div",{className:"rounded-lg p-4",style:{backgroundColor:"#f6f9fc",border:"2px solid #005C75"},children:c("div",{className:"flex items-start justify-between",children:[c("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{className:"flex items-center justify-center rounded-full flex-shrink-0",style:{width:"24px",height:"24px",backgroundColor:"#005C75",color:"white",fontSize:"12px",fontWeight:600},children:o+1}),s&&c("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)",marginTop:"2px"},children:n(Pe,{type:s.entityType||"other"})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(oe,{to:`/entity/${s.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:s.name}),s.entityType&&n(ar,{type:s.entityType})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:s.filePath})]})]})]}),n("button",{onClick:()=>{(async()=>{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:a.id})}),window.location.reload()}catch(i){console.error("Failed to cancel job:",i)}})()},className:"transition-colors",style:{fontSize:"12px",fontWeight:600,color:"#991b1b"},children:"Cancel"})]})},a.id)})})]})}function tu({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:a,tab:o}){if(t===0)return c("div",{className:"rounded-xl p-12 text-center",style:{backgroundColor:"#EFEFEF"},children:[n("div",{className:"flex justify-center mb-4",children:n(Io,{size:24,style:{color:"#646464"}})}),n("h3",{className:"font-semibold mb-2",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:"No Historic Activity"}),n("p",{style:{fontSize:"14px",lineHeight:"18px",color:"#646464"},children:"Completed analyses will appear here for historical reference."})]});const s=[];return e.forEach(i=>{i.entities&&i.entities.length>0&&i.entities.forEach(l=>{s.push({...l,runCreatedAt:i.createdAt})})}),n("div",{className:"flex flex-col gap-4",children:s.slice(0,20).map(i=>{const d=i.analyses?.[0]?.scenarios||[],u=!i.isUncommitted;return c("div",{className:"rounded-lg p-4",style:{backgroundColor:u?"#f2fcf9":"#fef9e7",border:"2px solid",borderColor:u?"#aff1a9":"#f9d689"},children:[c("div",{className:"flex items-start justify-between mb-3",children:[c("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)",marginTop:"2px"},children:n(Pe,{type:i.entityType||"other"})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(oe,{to:`/entity/${i.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:i.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:u?"#e8ffe6":"#fef3cd",color:u?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:u?"Up to date":"Out of date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#646464"},children:i.filePath})]})]}),n(oe,{to:`/entity/${i.sha}`,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),d.length>0&&c("div",{className:"flex gap-2 overflow-x-auto",children:[d.slice(0,8).map((m,h)=>{if(!m.id)return null;const p=m.metadata?.screenshotPaths?.[0];return n(oe,{to:`/entity/${i.sha}/scenarios/${m.id}`,className:"border border-gray-300 rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px"},children:p?n("img",{src:`/api/screenshot/${p}`,alt:m.name,className:"w-full h-full object-cover bg-gray-100"}):n("div",{className:"w-full h-full bg-gray-100 flex items-center justify-center text-xs text-gray-400",children:"No preview"})},h)}),d.length>8&&c("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",d.length-8," more"]})]})]},`${i.sha}-${i.runCreatedAt}`)})})}const nu=je(function(){const t=Le(),r=ea(),[a,o]=A(!1);nt({source:"activity-page"});const s=r.tab||"current";return t?c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-bold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-gray-600",children:"View queued, current, and historical analysis activity"})]}),n(Zd,{activeTab:s,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),s==="current"&&n(Xd,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>o(!0),recentCompletedEntities:t.recentCompletedEntities||[],hasMoreCompletedRuns:t.hasMoreCompletedRuns||!1,currentEntityScenarios:t.currentEntityScenarios||[]}),s==="queued"&&n(eu,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),s==="historic"&&n(tu,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:s}),a&&t.projectSlug&&n(gt,{projectSlug:t.projectSlug,onClose:()=>o(!1)})]}):n("div",{className:"px-20 py-12",children:n("div",{className:"text-center",children:n("p",{className:"text-gray-600",children:"Loading..."})})})}),ru=Object.freeze(Object.defineProperty({__proto__:null,default:nu,loader:Qd},Symbol.toStringTag,{value:"Module"}));async function Ga(e,t,r){await Ae();const a=await We({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw new Error(`Analysis ${e} not found`);if(!a.commit)throw new Error(`Commit not found for analysis ${e}`);const o=de();if(!o)throw new Error("Project root not found");const s=q.join(o,".codeyam","config.json"),i=JSON.parse(W.readFileSync(s,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const d=mn(l);try{W.writeFileSync(d,"","utf8")}catch{}const{project:u}=await Re(l),m=u.metadata?.packageManager||"npm",h=3112,p=it(l),f=u.metadata?.webapps||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const g=i.environmentVariables||[],y=ei({filePath:a.filePath,webapps:f,environmentVariables:g,port:h,packageManager:m});await kt(e,N=>{if(N&&(N.readyToBeCaptured=!0,N.scenarios))for(const M of N.scenarios)(!t||M.name===t)&&(delete M.screenshotStartedAt,delete M.screenshotFinishedAt,delete M.interactiveStartedAt,delete M.interactiveFinishedAt,delete M.error,delete M.errorStack)});const{jobId:b}=r.enqueue({type:"debug-setup",commitSha:a.commit.sha,projectSlug:l,analysisId:e,scenarioId:t,prepOnly:!0}),x=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:p}]},{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 ${p}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:x,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${h}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:b,analysisId:e,scenarioId:t,projectPath:p,projectSlug:l,port:h,packageManager:m,framework:y.framework,instructions:w}}async function au({request:e,context:t}){const r=new URL(e.url),a=r.searchParams.get("analysisId"),o=r.searchParams.get("scenarioId")||void 0;if(!a)return $({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 s=t.analysisQueue;if(s||(s=await He()),!s)return $({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:a,scenarioId:o});try{const i=await Ga(a,o,s);return $({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),$({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function ou({request:e,context:t}){if(e.method!=="POST")return $({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await He()),!r)return $({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("analysisId"),s=a.get("scenarioId");if(!o)return $({error:"Missing required field: analysisId"},{status:400});const i=await Ga(o,s,r);return $({...i,success:!0,message:"Debug setup queued"})}catch(a){console.error("[Debug Setup API] Error during debug setup:",a);const o=a instanceof Error?a.message:String(a),s=a instanceof Error?a.stack:void 0;return console.error("[Debug Setup API] Error stack:",s),$({error:"Failed to setup debug environment",details:o},{status:500})}}const su=Object.freeze(Object.defineProperty({__proto__:null,action:ou,loader:au},Symbol.toStringTag,{value:"Module"}));async function iu({request:e,context:t}){if(e.method!=="POST")return $({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await He()),!r)return $({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("analysisId"),s=a.get("defaultWidth");if(!o||!s)return $({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(s,10);if(isNaN(i)||i<320||i>3840)return $({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${o} with width ${i}`);const l=await gd(o,i,r);return console.log("[API] Recapture queued",l),$({success:!0,message:"Recapture queued",...l})}catch(a){return console.log("[API] Error during recapture:",a),$({error:"Failed to recapture screenshots",details:a instanceof Error?a.message:String(a)},{status:500})}}const lu=Object.freeze(Object.defineProperty({__proto__:null,action:iu},Symbol.toStringTag,{value:"Module"}));function cu(e,t){const r=e.metadata?.isUncommitted===!0,a=e.analyses&&e.analyses.length>0&&e.analyses.some(i=>i.scenarios&&i.scenarios.length>0);if(!r){const i=!!e.metadata?.previousVersionWithAnalyses,l=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return i||l?a?{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:"○"}}:a?{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 o=!!e.metadata?.previousCommittedSha;if(!!e.metadata?.previousVersionWithAnalyses||o){const i=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===e.metadata?.previousVersionWithAnalyses;return a&&!i?{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:"●"}}:a?{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 a?{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 du(e){return cu(e).hasOutdatedSimulations}function Be({screenshotPath:e,cacheBuster:t,alt:r,className:a="",title:o}){const[s,i]=A("loading"),[l,d]=A(!1),u=be(null),m=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,h=()=>{i("success"),d(!0)},p=()=>{i("error"),d(!1)};return J(()=>{i("loading"),d(!1);const f=u.current;f?.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[m]),e?c("div",{className:"relative w-full h-full flex items-center justify-center",title:o,children:[n("img",{ref:u,src:m,alt:r,onLoad:h,onError:p,className:a||"max-w-full max-h-full object-contain",style:{visibility:l?"visible":"hidden",position:l?"relative":"absolute"}}),s==="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"})})}),s==="error"&&c("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:o,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}function Wa(e,t,r,a,o){const s=t?.scenarios?.find(Y=>Y.name===e.name),i=!!s?.startedAt,l=!!s?.screenshotStartedAt,d=!!s?.screenshotFinishedAt,u=!!s?.finishedAt,m=1800*1e3,h=l&&!d&&s?.screenshotStartedAt&&Date.now()-new Date(s.screenshotStartedAt).getTime()>m,p=!!e.metadata?.screenshotPaths?.[0]||!!e.metadata?.executionResult,f=l&&!d,g=s?.error,y=e.metadata?.executionResult?.error,b=[];if(t?.errors&&t.errors.length>0)for(const Y of t.errors)b.push({source:`${Y.phase} phase`,message:Y.message});if(t?.steps)for(const Y of t.steps)Y.error&&b.push({source:Y.name,message:Y.error});const x=!p&&!g&&!y&&b.length>0,w=!!(g||y||h||x),C=h?"Capture timed out after 30 minutes":(typeof g=="string"?g:null)||y?.message||(x?`Analysis error: ${b[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.":s?.errorStack||y?.stack||null,E=(a&&o?o.jobs.some(Y=>Y.entityShas?.includes(a)||Y.type==="analysis"&&Y.entityShas&&Y.entityShas.length===0)||o.currentlyExecuting?.entityShas?.includes(a):!1)&&!i&&!w||!!s?.analyzing&&!i&&!w,v=i&&!l&&!u&&!w,S=(E||v||f)&&!w,I=(E||v)&&r===!1&&!p;let P;I?P="crashed":w?P="error":p||u?P="completed":f?P="capturing":v?P="starting":E?P="queued":P="pending";let T="📷",R="pending",O=!1,k=`Not captured: ${e.name}`;const j="border-gray-300",D=w||I?"bg-red-50":"bg-white";return w||I?(T="⚠️",R="error",k=`Error: ${I?"Analysis process crashed":C||"Unknown error"}`):E?(T="⋯",R="queued",k=`Queued: ${e.name}`):v?(T="⋯",R="starting",O=!0,k=`Starting server for ${e.name}...`):f&&!w?(T="⋯",R="capturing",O=!0,k=`Capturing ${e.name}...`):p&&(T="✓",R="completed",k=e.name),{hasError:w||I,errorMessage:I?"Analysis process crashed":C,errorStack:I?"Process terminated unexpectedly before completing analysis":N,isCapturing:f,isCaptured:p,hasCrashed:I,isAnalyzing:S,isQueued:E,isServerStarting:v,status:P,icon:T,iconType:R,shouldSpin:O,title:k,borderColor:j,bgColor:D}}function Ja({scenario:e,entitySha:t,size:r="medium",showBorder:a=!0,isOutdated:o=!1}){const s=Wa(e,void 0,void 0,t,void 0),i=e.metadata?.executionResult,l=!!i,u=(e.metadata?.data?.argumentsData||[]).length,m=i?.returnValue!==void 0&&i?.returnValue!==null,h=i?.sideEffects?.consoleOutput?.length||0,p=i?.timing?.duration||0;let f=0;u>0&&f++,u>2&&f++,m&&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]"},b=s.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:l?o?{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"},x=a?`border-2 ${b.border}`:"",w=Array.from({length:3},(N,M)=>n("div",{className:`w-1 h-1 rounded-full ${M<f?b.icon.replace("text-","bg-"):"bg-gray-300"}`},M)),C=s.hasError?`Error: ${s.errorMessage||"Unknown error"}`:l?`${e.name}
|
|
147
|
-
${u} args → ${m?"value":"void"}${h>0?` (${h} logs)`:""}
|
|
148
|
-
${p}ms`:`Not executed: ${e.name}`;return c(oe,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${g.width} ${g.height} ${x} rounded ${b.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:C,children:[n("div",{className:`${b.icon} ${g.iconSize} font-mono font-bold`,children:s.hasError?"⚠":l?"ƒ":"○"}),l&&!s.hasError&&c("div",{className:`flex items-center gap-0.5 ${g.textSize} ${b.badge} px-1 rounded`,children:[n("span",{children:u}),n("span",{children:"→"}),n("span",{children:m?"✓":"∅"})]}),l&&!s.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:w}),l&&!s.hasError&&p>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${g.textSize} ${b.badge} px-1 rounded`,children:p>1e3?`${Math.round(p/1e3)}s`:`${p}ms`}),l&&!s.hasError&&h>0&&r==="medium"&&c("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",h]})]})}function uu({scenario:e,entity:t,analysisStatus:r,queueState:a,processIsRunning:o,size:s="medium",cacheBuster:i,className:l="",viewMode:d}){if(t.entityType==="library")return n(Ja,{scenario:e,entitySha:t.sha,size:s==="small"?"small":"medium"});const m=Wa(e,r,o,t.sha,a),h=s==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:s==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},p=`relative ${h.containerClass} ${l}`,f=()=>{const y=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${y}/${d}`:y};if(m.isCaptured){const y=e.metadata?.screenshotPaths?.[0];return n(oe,{to:f(),className:`${p} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(Be,{screenshotPath:y,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const g=()=>{const y={size:s==="small"?16:s==="large"?24:20,strokeWidth:2},w=c(se,{children:[n("style",{children:`
|
|
149
|
-
@keyframes strongPulse {
|
|
150
|
-
0%, 100% { opacity: 0.2; }
|
|
151
|
-
50% { opacity: 1; }
|
|
152
|
-
}
|
|
153
|
-
`}),c("div",{className:`${s==="small"?"text-base":s==="large"?"text-2xl":"text-xl"} font-bold tracking-widest flex items-center justify-center text-gray-600`,children:[n("span",{style:{animation:"strongPulse 1.5s ease-in-out infinite"},children:"."}),n("span",{style:{animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"},children:"."}),n("span",{style:{animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"},children:"."})]})]});if(m.shouldSpin||m.iconType==="queued"||m.iconType==="pending")return w;switch(m.iconType){case"starting":case"capturing":return w;case"error":return n(jo,{...y});case"completed":return n(Ro,{...y});default:return w}};return n(oe,{to:f(),className:`${p} ${m.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:m.title,children:n("div",{className:h.iconSize,children:g()})})}const Bt=70;function mu({scenarios:e,analysis:t,selectedScenario:r,entitySha:a,cacheBuster:o,activeTab:s,entityType:i,entity:l,queueState:d,processIsRunning:u,viewMode:m,setViewMode:h,onDebugSetup:p,debugFetcher:f}){const g=be(null),[y,b]=A(new Set);J(()=>{g.current&&s==="scenarios"&&g.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[r?.id,s]);const x=N=>`/entity/${a}/scenarios/${N}`,w=N=>{b(M=>{const E=new Set(M);return E.has(N)?E.delete(N):E.add(N),E})},C=(N,M=2)=>{const v=N.split(`
|
|
154
|
-
`).slice(0,M).join(" ").trim();return v.length>Bt?v.substring(0,Bt-3):(N.split(`
|
|
155
|
-
`).length>M||N.length>v.length,v)};return c("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3",children:[h&&c("div",{children:[n("div",{className:"text-[10px] text-[#626262] font-medium mb-[6px]",children:"View"}),c("div",{className:"grid grid-cols-2 gap-0",role:"group","aria-label":"View mode selector",children:[n("button",{className:`px-[7px] h-[22px] text-[10px] font-medium rounded-l-[4px] border border-[#c7c7c7] transition-colors cursor-pointer ${m==="screenshot"?"bg-white text-[#3e3e3e] border-[#c7c7c7]":"bg-[#e1e1e1] text-[#626262] border-[rgba(0,92,117,0.05)] hover:bg-[#d4d4d4]"}`,onClick:()=>h("screenshot"),"aria-label":"Screenshot view","aria-pressed":m==="screenshot",children:"📸 Screenshot"}),n("button",{className:`px-[7px] h-[22px] text-[10px] font-medium rounded-r-[4px] border border-[#c7c7c7] border-l-0 transition-colors cursor-pointer ${m==="interactive"?"bg-white text-[#3e3e3e] border-[#c7c7c7]":"bg-[#e1e1e1] text-[#626262] border-[rgba(0,92,117,0.05)] hover:bg-[#d4d4d4]"}`,onClick:()=>h("interactive"),"aria-label":"Interactive view","aria-pressed":m==="interactive",children:"🎮 Interactive"})]})]}),r&&c("div",{className:"grid grid-cols-2 gap-1",children:[n(oe,{to:`/entity/${a}/scenarios/${r.id}/edit`,className:"h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] no-underline flex items-center justify-center",title:"Edit Scenario Data",children:"Edit Scenario"}),n("button",{className:"h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:bg-gray-400 disabled:text-gray-600 disabled:cursor-not-allowed flex items-center justify-center",onClick:p,disabled:f?.state!=="idle",title:"Setup Debug Environment",children:f?.state==="idle"?"Debug Scenario":"Setting up..."})]}),l&&l.filePath&&n("div",{children:n(oe,{to:`/entity/${a}/create-scenario`,className:"w-full px-[10px] 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] no-underline flex items-center justify-center",children:"Create New Scenario"})}),n("div",{className:"border-t border-[#e1e1e1] pt-3",children:n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Scenarios"})}),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((N,M)=>{const E=r?.id===N.id,v=y.has(N.id||"");return N.id?c(oe,{to:x(N.id),ref:E?g:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${E?"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(uu,{scenario:N,entity:{sha:a,entityType:i},analysisStatus:t?.status,queueState:d,processIsRunning:u,size:"large",cacheBuster:o,viewMode:m})}),c("div",{className:"px-[7px] py-[6.444px]",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${v?"":"line-clamp-1"}`,children:N.name}),N.description&&n("div",{className:"mt-[4px]",children:c("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[v?N.description:C(N.description),!v&&N.description.length>Bt&&c(se,{children:["...",n("button",{onClick:S=>{S.preventDefault(),S.stopPropagation(),w(N.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),v&&N.description.length>Bt&&n("button",{onClick:S=>{S.preventDefault(),S.stopPropagation(),w(N.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},M):null})})})]})}function hu({scenario:e,entitySha:t,onApply:r,onSave:a,onEditMockData:o,onDelete:s,isApplying:i=!1,isSaving:l=!1,saveMessage:d=null,showDeleteConfirm:u=!1,onShowDeleteConfirm:m,isDeleting:h=!1,deleteError:p=null}){const[f,g]=A(""),y=async()=>{await r(f)},b=async x=>{await a(f,x),x||g("")};return c("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[c("div",{className:"border-b border-[#e1e1e1] pb-3",children:[c("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(oe,{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})]}),c("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[c("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:x=>g(x.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}),c("button",{onClick:()=>{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&&c("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"}),c("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:o,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"})]}),d&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${d.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:d}),d==="Recapture successful"&&n("div",{children:n(oe,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),c("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[n("button",{onClick:()=>{b(!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:()=>{b(!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"}),s&&c(se,{children:[u?c("div",{className:"flex flex-col gap-1",children:[c("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),c("div",{className:"flex gap-1",children:[n("button",{onClick:()=>{s()},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:()=>m?.(!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:()=>m?.(!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"}),p&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:p})]})]})]})}function pu({scenario:e,analysis:t,entity:r}){const a=e.metadata?.executionResult||null,o=e.metadata?.data?.argumentsData||[],s=i=>{if(!i)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const l=[],d=i.sideEffects?.consoleOutput||[];d.length>0&&(l.push(`Console Output: ${d.length} log ${d.length===1?"entry":"entries"} captured`),d.forEach(h=>{l.push(` [${h.level.toUpperCase()}] ${h.args.join(" ")}`)}));const u=i.sideEffects?.fileWrites||[];u.length>0&&(l.push(`
|
|
156
|
-
File System Operations: ${u.length} ${u.length===1?"operation":"operations"} detected`),u.forEach(h=>{l.push(` ${h.operation}: ${h.path}${h.size?` (${h.size} bytes)`:""}`)}));const m=i.sideEffects?.apiCalls||[];return m.length>0&&(l.push(`
|
|
157
|
-
API Calls: ${m.length} ${m.length===1?"call":"calls"} made`),m.forEach(h=>{l.push(` ${h.method} ${h.url}${h.status?` → ${h.status}`:""}${h.duration?` (${h.duration}ms)`:""}`)})),i.error&&l.push(`
|
|
158
|
-
Error: ${i.error.name||"Error"}: ${i.error.message}`),l.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":l.join(`
|
|
159
|
-
`)};return c("div",{className:"flex w-full h-full gap-0",children:[c("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(o,null,2)})})]}),c("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:a?n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:a.returnValue!==void 0?JSON.stringify(a.returnValue,null,2):"undefined"}):n("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),c("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:s(a)})})]})]})}const Ut=10,fu=1024;function gu({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:a}){const[o,s]=A(null),i=be(null),l=Z(()=>[...a].sort((y,b)=>y.width-b.width),[a]),{fittingPresets:d,overflowPresets:u}=Z(()=>{const y=[],b=[];for(const x of l)x.width<=fu?y.push(x):b.push(x);return b.sort((x,w)=>w.width-x.width),{fittingPresets:y,overflowPresets:b}},[l]),m=X(y=>{if(!i.current)return null;const b=i.current.getBoundingClientRect(),x=y-b.left,w=b.width,C=w/2,M=(d.length>0?d[d.length-1].width:0)/2,E=C-M,v=C+M,S=u.length>0?(u.length-1)*Ut:0;if(u.length>0){if(x<E){if(x<=S){const P=Math.min(Math.floor(x/Ut),u.length-1);return u[P]}return u[u.length-1]}if(x>v){const P=w-x;if(P<=S){const T=Math.min(Math.floor(P/Ut),u.length-1);return u[T]}return u[u.length-1]}}const I=Math.abs(x-C);for(let P=d.length-1;P>=0;P--){const T=d[P],R=d[P-1],O=T.width/2,k=R?R.width/2:0;if(I<=O&&I>=k)return T}return d[0]||u[u.length-1]||null},[d,u]),h=X(y=>{const b=m(y.clientX);s(b)},[m]),p=X(()=>{s(null)},[]),f=X(y=>{const b=m(y.clientX);b&&r(b)},[m,r]),g=o||{name:t,width:e};return c("div",{ref:i,className:"relative h-6 bg-[#f6f9fc] shrink-0 overflow-hidden cursor-pointer",onMouseMove:h,onMouseLeave:p,onClick:f,children:[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-[rgba(0,92,117,0.15)]",style:{width:`${e}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:d.map(y=>{const b=y.width===e,x=o?.name===y.name,w=y.width/2;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${w}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${b||x?"bg-[#005c75]":"bg-[rgba(0,92,117,0.25)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${w}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${b||x?"bg-[#005c75]":"bg-[rgba(0,92,117,0.25)]"}`})})]},y.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:u.map((y,b)=>{const x=b*Ut,w=y.width===e,C=o?.name===y.name;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${x}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${w||C?"bg-[#005c75]":"bg-[rgba(0,92,117,0.25)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{right:`${x}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${w||C?"bg-[#005c75]":"bg-[rgba(0,92,117,0.25)]"}`})})]},y.name)})}),n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:c("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${o?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[g.name," - ",g.width,"px"]})})]})}function yu({width:e,height:t,onSave:r,onCancel:a}){const[o,s]=A(""),[i,l]=A(""),d=()=>{const m=o.trim();if(!m){l("Please enter a name for this custom size");return}r(m)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:c("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[c("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: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"})})})]}),c("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"}),c("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),c("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:o,onChange:m=>{s(m.target.value),l("")},onKeyDown:m=>{m.key==="Enter"&&o.trim()&&d(),m.key==="Escape"&&a()},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})]}),c("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:a,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 cursor-pointer",children:"Cancel"}),n("button",{onClick:d,disabled:!o.trim(),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 cursor-pointer disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function xu(e){const[t,r]=A([]),a=e?`codeyam-custom-sizes-${e}`:null;J(()=>{if(!a||typeof window>"u"){r([]);return}try{const l=localStorage.getItem(a);if(l){const d=JSON.parse(l);Array.isArray(d)&&r(d)}}catch(l){console.error("[useCustomSizes] Failed to load custom sizes:",l),r([])}},[a]);const o=X(l=>{if(!(!a||typeof window>"u"))try{localStorage.setItem(a,JSON.stringify(l))}catch(d){console.error("[useCustomSizes] Failed to save custom sizes:",d)}},[a]),s=X((l,d,u)=>{r(m=>{const h=m.findIndex(g=>g.name===l),p={name:l,width:d,height:u};let f;return h>=0?(f=[...m],f[h]=p):f=[...m,p],o(f),f})},[o]),i=X(l=>{r(d=>{const u=d.filter(m=>m.name!==l);return o(u),u})},[o]);return{customSizes:t,addCustomSize:s,removeCustomSize:i}}function rn({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:a="",duration:o=2e3,ariaLabel:s}){const[i,l]=A(!1),d=X(()=>{navigator.clipboard.writeText(e).then(()=>{l(!0),setTimeout(()=>l(!1),o)}).catch(u=>{console.error("Failed to copy:",u)})},[e,o]);return n("button",{onClick:d,className:`cursor-pointer ${a}`,disabled:i,"aria-label":s||(i?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?r:t})}function St({scenarioId:e,analysisId:t}){const[r,a]=A(!1),[o,s]=A(!1),[i,l]=A(null),d=e||t;if(!d)return null;const u=`/debug ${d}`,m=async()=>{s(!0);try{const{default:p}=await import("html2canvas-pro"),g=(await p(document.body,{scale:.5})).toDataURL("image/jpeg",.8);l(g),a(!0)}catch(p){console.error("Screenshot capture failed:",p),a(!0)}finally{s(!1)}};return c(se,{children:[n("div",{className:"mt-4 p-4 bg-blue-50 border border-blue-200 rounded-lg",children:c("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-blue-600 text-xl shrink-0",children:"🤖"}),c("div",{className:"flex-1",children:[n("h4",{className:"text-sm font-semibold text-blue-800 m-0 mb-2",children:"Claude can help debug this error"}),n("p",{className:"text-sm text-blue-700 m-0 mb-3",children:"Simply run this command in Claude Code:"}),c("div",{className:"flex items-center gap-2 bg-white border border-blue-200 rounded p-3 mb-4",children:[n("code",{className:"text-sm text-blue-900 font-mono flex-1 wrap-break-word",children:u}),n(rn,{content:u,label:"Copy",copiedLabel:"Copied!",className:"px-3 py-1 bg-blue-600 text-white text-xs font-medium rounded hover:bg-blue-700 transition-colors shrink-0"})]}),c("div",{className:"pt-3 border-t border-blue-200",children:[n("p",{className:"text-xs text-blue-700 m-0 mb-2",children:"If Claude is unable to address this issue or suggests reporting it, please do so."}),n("button",{onClick:()=>{m()},disabled:o,className:"cursor-pointer px-3 py-1.5 bg-white border border-blue-300 text-blue-700 text-xs font-medium rounded hover:bg-blue-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:o?"Capturing...":"Report Issue"})]})]})]})}),n(ia,{isOpen:r,onClose:()=>{a(!1),l(null)},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 Hr=1440,Ht=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}];function Ka({selectedScenario:e,analysis:t,entity:r,viewMode:a,cacheBuster:o,hasScenarios:s,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:d=!0}){const u=we(),[m,h]=A(!1),[p,f]=A(!1),[g,y]=A({name:"Desktop",width:Hr,height:900}),[b,x]=A(Hr),[w,C]=A(1),{customSizes:N,addCustomSize:M,removeCustomSize:E}=xu(l),v=Z(()=>[...Ht,...N],[N]),S=(Q,L)=>{x(Q);const ae=v.find(me=>me.width===Q&&me.height===L);y({name:ae?.name||"Custom",width:Q,height:L})},I=Q=>{x(Q.width),y({name:Q.name,width:Q.width,height:Q.height})},P=Q=>{M(Q,g.width,g.height??900),f(!1),y(L=>({...L,name:Q}))},T=(Q,L)=>{x(Q);const ae=v.find(me=>me.width===Q&&me.height===L);y(me=>({name:ae?.name||"Custom",width:Q,height:me.height}))},R=e?.metadata?.screenshotPaths?.[0],O=Z(()=>!e||!t?.status?.scenarios?null:t.status.scenarios.find(Q=>Q.name===e.name),[e,t?.status?.scenarios]),k=Z(()=>{const Q=[];if(t?.status?.errors&&t.status.errors.length>0)for(const L of t.status.errors)Q.push({source:`${L.phase} phase`,message:L.message,stack:L.stack});if(t?.status?.steps)for(const L of t.status.steps)L.error&&Q.push({source:L.name,message:L.error,stack:L.errorStack});return Q},[t?.status?.errors,t?.status?.steps]),j=O?.error||(e?.metadata?.error?"Error during capture":null),D=O?.errorStack,{interactiveServerUrl:Y,isStarting:te,isLoading:ne,showIframe:F,iframeKey:H,onIframeLoad:_}=fn({analysisId:t?.id,scenarioId:e?.id,scenarioName:e?.name,projectSlug:l,enabled:a==="interactive"}),B=Z(()=>Y||null,[Y]),U=!i&&s&&e&&!e.metadata?.screenshotPaths?.[0]&&t?.status?.scenarios?.some(Q=>Q.name===e.name&&Q.screenshotStartedAt&&!Q.screenshotFinishedAt),{lastLine:V}=rt(l,i||a==="interactive"||U||!1);return e?c(se,{children:[n("main",{className:"flex-1 bg-[#f9f9f9] overflow-auto flex flex-col min-w-0",children:(i||U)&&!R&&!j&&a==="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:c("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[c("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:U?`Capturing ${r?.name}`:`Analyzing ${r?.name}`}),n("p",{className:"text-base text-gray-600 leading-relaxed m-0 mb-2",children:U?`Taking screenshots for ${t?.scenarios?.length||0} scenario${t?.scenarios?.length!==1?"s":""}...`:`Generating simulations and scenarios for this ${r?.entityType} entity...`}),e&&c("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),V&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:c("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),c("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:V,children:V})]})]})}),l&&n("button",{onClick:()=>h(!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."})]})}):a==="screenshot"&&(R||j)||a==="interactive"&&(B||te)||a==="data"?c(se,{children:[j&&!R&&n("div",{className:"bg-red-50 border-l-4 border-red-500 mx-5 mt-4 p-4 rounded-r overflow-auto",role:"alert",children:c("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-red-500 text-xl shrink-0","aria-hidden":"true",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-sm font-semibold text-red-800 m-0 mb-2",children:"Capture Error"}),n("div",{className:"max-h-[200px] overflow-auto",children:n("p",{className:"text-sm text-red-700 m-0 mb-2 font-mono whitespace-pre-wrap wrap-break-word",children:j})}),D&&c("details",{className:"mt-2",children:[n("summary",{className:"text-xs text-red-600 cursor-pointer hover:text-red-800 font-medium",children:"View stack trace"}),n("div",{className:"mt-2 p-3 bg-red-100 rounded max-h-[300px] overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:D})})]}),n(St,{scenarioId:e?.id,analysisId:t?.id})]})]})}),a==="interactive"?c("div",{className:"flex-1 flex flex-col min-h-0",children:[B&&n("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center",children:n(Rl,{presets:[...Ht],customSizes:N,currentWidth:g.width,currentHeight:g.height??900,scale:w,onSizeChange:S,onSaveCustomSize:()=>f(!0),onRemoveCustomSize:E})}),B&&n("div",{className:"bg-[#f6f9fc] border-b border-[rgba(0,92,117,0.25)] flex justify-center",children:n("div",{style:{maxWidth:`${Ht[Ht.length-1].width}px`,width:"100%"},children:n(gu,{currentViewportWidth:b,currentPresetName:g.name,onDevicePresetClick:I,devicePresets:v})})}),n(gn,{scenarioId:e.id,scenarioName:e.name,iframeUrl:B,isStarting:te,isLoading:ne,showIframe:F,iframeKey:H,onIframeLoad:_,onScaleChange:C,onDimensionChange:T,projectSlug:l,defaultWidth:g.width,defaultHeight:g.height})]}):a==="data"?n("div",{className:"flex-1 min-h-0",children:n(pu,{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:`${b}px`},children:(R||!j)&&n(Be,{screenshotPath:R,cacheBuster:o,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&&!R?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:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),c("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),c("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."]}),V&&c("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:V})]}),l&&n("button",{onClick:()=>h(!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"})]})]})})}):j?c("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!d&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:c("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[c("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"})]}),c("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."}),c("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(oe,{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:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("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."}),c("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:j})})]}),D&&c("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:D})})]}),n(St,{scenarioId:e?.id,analysisId:t?.id})]})]})})]}):k.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:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Analysis Error"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:k.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${k.length} errors occurred during analysis. Screenshot capture was not completed.`}),k.map((Q,L)=>c("div",{className:"bg-white border border-red-200 rounded p-4 mb-4 last:mb-0",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:Q.source}),n("div",{className:"max-h-[200px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:Q.message})}),Q.stack&&c("details",{className:"mt-2",children:[n("summary",{className:"text-xs text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"View stack trace"}),n("div",{className:"mt-2 bg-red-50 border border-red-200 rounded p-3 max-h-[200px] overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:Q.stack})})]})]},L)),n(St,{scenarioId:e?.id,analysisId:t?.id})]})]})})}):c("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(gt,{projectSlug:l,onClose:()=>h(!1)}),p&&n(yu,{width:g.width,height:g.height??900,onSave:P,onCancel:()=>f(!1)})]}):!s&&r?i?n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:c("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:U?"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."}),V&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:V}),l&&n("button",{onClick:()=>h(!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"})]})}):k.length>0?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 bg-[#f6f9fc] overflow-auto",children:c("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl",children:[c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Analysis Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:k.length===1?"An error occurred during analysis. No scenarios were generated.":`${k.length} errors occurred during analysis. No scenarios were generated.`}),k.map((Q,L)=>c("div",{className:"bg-white border border-red-200 rounded p-4 mb-4 last:mb-0",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:Q.source}),n("div",{className:"max-h-[200px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:Q.message})}),Q.stack&&c("details",{className:"mt-2",children:[n("summary",{className:"text-xs text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"View stack trace"}),n("div",{className:"mt-2 bg-red-50 border border-red-200 rounded p-3 max-h-[200px] overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:Q.stack})})]})]},L))]})]}),r.filePath&&n("div",{className:"flex justify-center mt-4",children:n("button",{onClick:()=>{u.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:u.state!=="idle",className:"h-[42px] px-6 py-2 bg-[#005c75] text-white border-none rounded-lg text-sm font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:u.state!=="idle"?"Retrying...":"Retry Analysis"})}),n(St,{analysisId:t?.id})]})}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:c("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:()=>{u.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:u.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:u.state!=="idle"?"Analyzing...":"Analyze"})]})}):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"})})}function qr({hasIndirectBadge:e,onAnalyze:t}){return c(se,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:c("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"})]})}),c("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 bu({entity:e,history:t}){const[r,a]=A("entity"),[o,s]=A(new Set),i=t.filter(m=>m.analyses.length>0).length,l=Z(()=>{const m=new Map;return t.forEach(h=>{h.analyses.forEach(p=>{p.scenarios?.forEach(f=>{m.has(f.name)||m.set(f.name,[]),m.get(f.name).push({version:h,analysis:p,scenario:f})})})}),Array.from(m.entries()).map(([h,p])=>({name:h,description:p[0]?.scenario.description||"",versions:p.sort((f,g)=>{const y=new Date(f.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-y})}))},[t]),d=l.length,u=m=>{s(h=>{const p=new Set(h);return p.has(m)?p.delete(m):p.add(m),p})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:c("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:c("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[c("button",{onClick:()=>a("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})]}),c("button",{onClick:()=>a("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:d})]})]})}),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"?c("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((m,h)=>c("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]"}),c("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:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3",children:[m.sha===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("span",{className:"text-xs font-mono text-[#646464] leading-5",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e]",children:m.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:m.createdAt&&new Date(m.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),m.analyses.length>0?n("div",{children:m.analyses.map((p,f)=>n("div",{children:!p.scenarios||p.scenarios.length===0?n(qr,{hasIndirectBadge:p.indirect,onAnalyze:()=>{console.log("Analyze version:",m.sha)}}):c(se,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-end gap-2",children:[p.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"}),c("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[p.scenarios.length," scenario",p.scenarios.length!==1?"s":""]})]})}),p.metadata?.scenarioChangesOverview&&n("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:c("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[c("span",{className:"font-medium",children:["What Changed:"," "]}),p.metadata.scenarioChangesOverview]})}),p.scenarios&&p.scenarios.length>0&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:p.scenarios.map((g,y)=>{const b=g.metadata?.screenshotPaths?.[0],x=`${g.name}-${y}`;return c("div",{className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:b?n(Be,{screenshotPath:b,alt:g.name,className:"max-w-full max-h-full object-contain rounded-sm"}):c("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:g.name})})]},x)})})})]})},p.id||f))}):n(qr,{onAnalyze:()=>{console.log("Analyze version:",m.sha)}})]})]},m.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((m,h)=>{const p=o.has(m.name),f=p?m.versions:m.versions.slice(0,1),g=m.versions.length-1;return m.versions[0]?.version.sha,e?.sha,c("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]"}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("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:m.name}),m.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:m.description})]}),c("div",{className:"p-5 bg-white",children:[f.map((b,x)=>{const{version:w,analysis:C,scenario:N}=b,M=N.metadata?.screenshotPaths?.[0],E=x===0;return c("div",{className:`flex gap-5 items-start ${E?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n("div",{className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0",children:M?n(Be,{screenshotPath:M,alt:N.name,className:"max-w-full max-h-full object-contain rounded-sm"}):c("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"})]})}),c("div",{className:"flex-1 flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[w.sha===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"}),E&&m.versions.length>1&&c("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[m.versions.length," versions"]})]}),c("p",{className:"text-xs font-mono text-[#646464] m-0 leading-5",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e]",children:w.sha.substring(0,8)})]}),C.createdAt&&c("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(C.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),C.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}-${x}`)}),g>0&&c("button",{onClick:()=>u(m.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 ${p?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),p?"Hide":`${g} previous version${g!==1?"s":""}`]})]})]})]},m.name)})})]})})}function Gr({entity:e,analysisInfo:t,from:r}){return n(oe,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:c("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(Be,{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(Pe,{type:e.entityType})})}),c("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(Pe,{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&&c("div",{className:"flex items-center gap-2 mt-2",children:[c("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"?c(se,{children:[c("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"})]}),n("button",{className:"w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium cursor-pointer transition-colors hover:bg-[#004a5c]",onClick:a=>{a.preventDefault()},children:"Analyze"})]}):t.status==="up_to_date"?c("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"})]}):c(se,{children:[c("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"})]}),n("button",{className:"w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium cursor-pointer transition-colors hover:bg-[#004a5c]",onClick:a=>{a.preventDefault()},children:"Analyze"})]})})]})]})},e.sha)}const Wr=e=>{const t=e.analysisStatus?.status||"not_analyzed",r=e.analysisStatus?.scenarioCount||0,a=e.analysisStatus?.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:a}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:r>0,scenarioCount:r,timestamp:a}};function vu({importedEntities:e,importingEntities:t}){const[r]=Fn(),a=r.get("from"),o=e.length>0,s=t.length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:c("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("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."})]}),n("button",{className:"px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c]",children:"Analyze All"})]}),o?n("div",{className:"p-6 space-y-4",children:e.map(i=>n(Gr,{entity:i,analysisInfo:Wr(i),from:a},i.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."})})]}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("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."})]}),n("button",{className:"px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c]",children:"Analyze All"})]}),s?n("div",{className:"p-6 space-y-4",children:t.map(i=>n(Gr,{entity:i,analysisInfo:Wr(i),from:a},i.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 wu({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(vu,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function Cu({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(At,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function At({data:e,depth:t,defaultExpanded:r,maxDepth:a,objectKey:o,showInlineToggle:s=!1}){const[i,l]=A(r||t<2);if(J(()=>{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 d=typeof e;if(d==="string")return c("span",{className:"text-green-600",children:['"',e,'"']});if(d==="number")return n("span",{className:"text-blue-600",children:e});if(d==="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:"[]"}):c("span",{children:[c("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:[c("span",{children:[i?"▼":"▶"," ","["]}),!i&&c("span",{children:[e.length,"]"]})]}),i?c(se,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((u,m)=>n("div",{className:"py-0.5",children:n(At,{data:u,depth:t+1,defaultExpanded:r,maxDepth:a})},m))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const u=Object.keys(e);if(u.length===0)return n("span",{className:"text-gray-600",children:"{}"});const m=p=>p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,h=p=>Array.isArray(p)&&p.length>0;return c("span",{children:[c("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:[c("span",{children:[i?"▼":"▶"," ","{"]}),!i&&c("span",{children:[u.length,"}"]})]}),i?c(se,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:u.map(p=>{const f=e[p],g=m(f),y=h(f);return n("div",{className:"py-0.5",children:g?n(or,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):y?n(sr,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):c(se,{children:[c("span",{className:"text-orange-600",children:[p,": "]}),n(At,{data:f,depth:t+1,defaultExpanded:r,maxDepth:a})]})},p)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function or({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:o}){const[s,i]=A(a||r<2),l=Object.keys(t);return J(()=>{i(a||r<2)},[a,r]),c(se,{children:[c("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(!s),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:s?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!s&&c("span",{className:"text-gray-600",children:[l.length,"}"]})]}),s&&c(se,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:l.map(d=>{const u=t[d],m=u!==null&&typeof u=="object"&&!Array.isArray(u)&&Object.keys(u).length>0,h=Array.isArray(u)&&u.length>0;return n("div",{className:"py-0.5",children:m?n(or,{propertyKey:d,value:u,depth:r+1,defaultExpanded:a,maxDepth:o}):h?n(sr,{propertyKey:d,value:u,depth:r+1,defaultExpanded:a,maxDepth:o}):c(se,{children:[c("span",{className:"text-orange-600",children:[d,": "]}),n(At,{data:u,depth:r+2,defaultExpanded:a,maxDepth:o})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function sr({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:o}){const[s,i]=A(a||r<2);return J(()=>{i(a||r<2)},[a,r]),c(se,{children:[c("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(!s),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:s?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!s&&c("span",{className:"text-gray-600",children:[t.length,"]"]})]}),s&&c(se,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((l,d)=>{const u=l!==null&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,m=Array.isArray(l)&&l.length>0;return n("div",{className:"py-0.5",children:u?n(or,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:a,maxDepth:o}):m?n(sr,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:a,maxDepth:o}):n(At,{data:l,depth:r+2,defaultExpanded:a,maxDepth:o})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function Rn({label:e,count:t,isActive:r,onClick:a,badgeColorActive:o,badgeTextActive:s}){return c("button",{onClick:a,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?`${o} ${s}`:"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 Jr({label:e,isActive:t,onClick:r,disabled:a=!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:a,children:e})}function Kr({call:e,scenarioName:t}){const[r,a]=A(!1),[o,s]=A("system"),i=p=>new Date(p).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),l=p=>p?`$${p.toFixed(4)}`:null,d=(p,f)=>{if(!p&&!f)return null;const g=[];return p&&g.push(`${p.toLocaleString()} in`),f&&g.push(`${f.toLocaleString()} out`),g.join(" / ")},u=Z(()=>{try{const p=JSON.parse(e.response);return p.choices?.[0]?.message?.content?p.choices[0].message.content:p.content?.[0]?.text?p.content[0].text:e.response}catch{return e.response}},[e.response]),m=Z(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),h=Z(()=>{if(t)return t;try{return JSON.parse(e.props)?.scenario?.name||null}catch{return null}},[e.props,t]);return c("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:()=>a(!r),children:c("div",{className:"flex items-start justify-between gap-4",children:[c("div",{className:"flex-1 min-w-0",children:[c("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"})]}),c("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&n("span",{children:d(e.input_tokens,e.output_tokens)}),l(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:l(e.cost)})]}),c("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&&c("div",{className:"border-t border-[#e1e1e1]",children:[c("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>s("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>s("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>s("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>s("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),o&&c("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[o==="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"})}),o==="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})}),o==="response"&&c("div",{children:[e.error&&c("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:u})]}),o==="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:m})]}),e.error&&!o&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:c("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const Vr=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function Nu({entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:o}){const[s,i]=A("entity"),[l,d]=A("isolatedDataStructure"),[u,m]=A(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[h,p]=A("entity"),{entityLlmCalls:f,scenarioLlmCalls:g,totalLlmCalls:y}=Z(()=>{if(!o)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const C=[...o.entityCalls,...o.analysisCalls],N=C.filter(E=>E.object_type==="entity"||Vr.includes(E.prompt_type)),M=C.filter(E=>E.object_type!=="entity"&&!Vr.includes(E.prompt_type));return N.sort((E,v)=>v.created_at-E.created_at),M.sort((E,v)=>v.created_at-E.created_at),{entityLlmCalls:N,scenarioLlmCalls:M,totalLlmCalls:C.length}},[o]),b=[{id:"isolatedDataStructure",title:"Isolated Data Structure",data:e?.metadata?.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:t?.metadata?.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:e?.metadata?.isolatedDataStructure?.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"keyAttributes",title:"Key Attributes",data:t?.metadata?.keyAttributes,description:"Important attributes identified during analysis"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":e?.metadata?.importedExports,"External Dependencies":e?.metadata?.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:t?.metadata?.scenariosDataStructure,description:"Structure template used across all scenarios"}],x=b.filter(C=>C.data!==void 0&&C.data!==null).length;let w=null;if(s==="entity"){const C=b.find(N=>N.id===l);C&&C.data!==void 0&&C.data!==null&&(w={title:C.title,description:C.description,data:C.data})}else if(s==="scenarios"&&u){const C=r.find(N=>(N.id||N.name)===u.scenarioId);C&&(w={title:C.name,description:C.description||"Scenario data and configuration",data:C.metadata})}return c("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:c("div",{className:"flex border-b border-gray-200 relative",children:[n(Rn,{label:"Entity",isActive:s==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(Rn,{label:"Scenarios",count:r.length,isActive:s==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(Rn,{label:"LLM Calls",count:y,isActive:s==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),t?.metadata?.analyzerVersion&&c("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})]})]})}),s==="llm-calls"?c("div",{className:"flex-1 min-h-0",children:[c("div",{className:"flex gap-4 mb-4",children:[c("button",{onClick:()=>p("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,")"]}),c("button",{onClick:()=>p("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(C=>n(Kr,{call:C},C.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(C=>n(Kr,{call:C},C.id))})]}):c("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:s==="entity"?c(se,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),x===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:b.map(C=>{const N=C.data!==void 0&&C.data!==null;return n(Jr,{label:C.title,isActive:l===C.id,onClick:()=>d(C.id),disabled:!N},C.id)})})]}):c(se,{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(C=>{const N=C.id||C.name,M=u?.scenarioId===N;return n(Jr,{label:C.name,isActive:M,onClick:()=>m({scenarioId:N})},N)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:w?n(Su,{title:w.title,description:w.description,data:w.data}):s==="scenarios"&&r.length===0?n(Qr,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:a}):s==="entity"?n(Qr,{title:"No Entity Data Yet",description:"Entity data structures will appear here after analysis is complete.",onAnalyze:a}):n("div",{className:"p-6 text-center py-12 text-gray-500",children:"Select a section to view data"})})]})]})}function Qr({title:e,description:t,onAnalyze:r}){return c("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 Su({title:e,description:t,data:r}){const[a,o]=A(!0),[s,i]=A("Copy JSON");return c(se,{children:[c("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})]}),c("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[c("div",{className:"flex gap-2",children:[n("button",{onClick:()=>o(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${a?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),n("button",{onClick:()=>o(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${a?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),n("button",{onClick:()=>{const d=JSON.stringify(r,null,2);navigator.clipboard.writeText(d),i("Copied!"),setTimeout(()=>i("Copy JSON"),2e3)},className:"px-4 h-8 bg-[#343434] hover:bg-[#232323] text-white text-sm font-medium rounded border-none cursor-pointer transition-colors whitespace-nowrap",children:s})]}),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(Cu,{data:r,defaultExpanded:a,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function Eu({entity:e,analysis:t,scenarios:r,onAnalyze:a}){const o=we();return J(()=>{if(e?.sha&&o.state==="idle"&&!o.data){const s=t?.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;o.load(s)}},[e?.sha,t?.id,o.state,o.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(Nu,{entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:o.data})})}const Au={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},_u={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},Pu=2e3,Mu=e=>{if(!e)return"typescript";switch(e.split(".").pop()?.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 ku({entity:e,entityCode:t}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:c("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[c("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[c("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?.filePath})]}),t&&n(rn,{content:t,label:"Copy Code",duration:Pu,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(is,{language:Mu(e?.filePath),style:ls,showLineNumbers:!0,customStyle:Au,lineNumberStyle:_u,children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const Tu=({data:e})=>[{title:e?.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function Iu({currentParams:e,nextParams:t,currentUrl:r,nextUrl:a,formMethod:o,defaultShouldRevalidate:s}){return r.pathname===a.pathname&&r.search===a.search?s:!!(e.sha!==t.sha||o)}async function Ru({params:e,request:t,context:r}){const{sha:a}=e;if(!a)throw new Response("Entity SHA is required",{status:400});const s=new URL(t.url).searchParams.get("from"),l=(e["*"]||"").split("/").filter(Boolean),d=l[0]||"scenarios",u=l[1]||null,m=l[2]||null,h=r.analysisQueue,p=h?h.getState():{paused:!1,jobs:[]},[f,g,y,b,x]=await Promise.all([ze(a),It(a,!1),ke(),st(),Di(de()||process.cwd())]),w=g&&g.length>0?g[0]:null;let C={importedEntities:[],importingEntities:[]},N=null,M=[];return f&&(C=await Ca(f),N=await Na(f),M=await Sa(f)),$({entity:f??void 0,analysis:w??void 0,projectSlug:y,from:s,relatedEntities:C,entityCode:N??void 0,history:M,tab:d,scenarioId:u,viewModeFromUrl:m,currentCommit:b,hasAnApiKey:x,queueState:p})}const ju=je(function(){const t=Le(),o=(ea()["*"]||"").split("/").filter(Boolean),s=o[0]||"scenarios",i=o[1]||null,l=o[2]||null,d=t.entity,u=t.analysis,m=t.projectSlug;t.from;const h=t.relatedEntities,p=t.entityCode,f=t.history,g=t.currentCommit,y=t.hasAnApiKey,b=t.queueState,x=u?.scenarios||[],w=_t(),C=be(null);J(()=>{C.current===null&&(C.current=window.history.length)},[]);const N=()=>{if(typeof window>"u")return;const G=window.history.state;if(G===null||G?.idx===void 0||G?.idx===0)w("/");else{const le=window.history.length,ce=C.current;if(ce!==null&&le>ce){const ve=le-ce+1;w(-ve)}else w(-1)}},M=!!b.currentlyExecuting,E=s,v=Z(()=>{if(E!=="scenarios")return null;if(i){const G=x.find(le=>le.id===i);if(G)return G}return x.length>0?x[0]:null},[E,i,x]);nt({source:v?"scenario-page":"entity-page",entitySha:d?.sha,scenarioId:v?.id,analysisId:u?.id});const[S,I]=A(()=>l&&l!=="edit"?l:d?.entityType==="library"?"data":"screenshot");J(()=>{l&&l!==S&&l!=="edit"&&I(l)},[l]);const P=l==="edit",[T,R]=A(!1),[O,k]=A(!1),[j,D]=A(null),[Y,te]=A(!1),[ne,F]=A(!1),[H,_]=A(null),[B,U]=A(null),[V,ee]=A(0),{interactiveServerUrl:ye,isStarting:Q,isLoading:L,showIframe:ae,iframeKey:me,onIframeLoad:vt}=fn({analysisId:u?.id,scenarioId:v?.id,scenarioName:v?.name,projectSlug:m,enabled:P&&!!v,refreshTrigger:V}),[xn,bn]=A(!1),[vn,mr]=A(""),[Je,qe]=A(!1),[Rt,jt]=A(Date.now()),[Oe,lt]=A(null),[Dt,Ke]=A(!1),[$t,re]=A(!1),ge=we(),pe=we(),Te=we(),Ye=we(),Ee=ft(),wn=g?.metadata?.currentRun,hr=!!wn?.createdAt&&!wn?.analysisCompletedAt,eo=b.jobs.some(G=>G.entityShas?.includes(d?.sha||"")||G.type==="analysis"&&G.commitSha===g?.sha&&G.entityShas&&G.entityShas.length===0),pr=wn?.currentEntityShas?.includes(d?.sha||"")??!1,Cn=pr;d?.metadata?.defaultWidth||u?.metadata?.defaultWidth,ge.state==="submitting"||ge.state,Z(()=>!!v?.metadata?.interactiveExamplePath,[v]);const{isCompleted:fr}=rt(m,Je);J(()=>{ge.state==="idle"&&ge.data&&(ge.data.success?setTimeout(()=>{jt(Date.now()),Ee.revalidate(),qe(!1)},1500):ge.data.error&&(qe(!1),alert(`Recapture failed: ${ge.data.error}`)))},[ge.state,ge.data,Ee]),J(()=>{Je&&fr&&setTimeout(()=>{jt(Date.now()),Ee.revalidate(),qe(!1)},1500)},[Je,fr,Ee]),J(()=>{if(pe.state==="idle"&&pe.data)if(pe.data.success){lt(pe.data),Ke(!0);const G=pe.data.jobId;if(G){const le=async()=>{try{const ve=await fetch("/api/queue?queryType=job&jobId="+encodeURIComponent(G));if(!ve.ok){const _e=await ve.text();console.error("[Debug Setup] Poll failed with status",ve.status,":",_e);return}(await ve.json()).status==="completed"&&(clearInterval(ce),lt(_e=>_e?{..._e,complete:!0,instructions:{title:"Debug Environment Ready ✓",sections:_e.instructions?.sections?.map(ue=>ue.heading==="Status"?{heading:"Status",items:[{content:"Setup complete! Your debug environment is ready."},...ue.items.slice(1)]}:ue.heading==="What's Happening"?null:ue.heading==="Next Steps (Once Complete)"?{...ue,heading:"Next Steps"}:ue).filter(Boolean)||[]}}:null))}catch(ve){console.error("[Debug Setup] Error polling queue:",ve)}},ce=setInterval(()=>{le().catch(()=>{})},2e3);return()=>{clearInterval(ce)}}else console.warn("[Debug Setup] No job ID returned from debug setup!")}else pe.data.error&&(console.error("[Debug Setup] Error:",pe.data.error),alert(`Debug setup failed: ${pe.data.error}`))},[pe.state,pe.data]),J(()=>{Te.state==="idle"&&Te.data&&(Te.data.success?setTimeout(()=>{jt(Date.now()),Ee.revalidate(),qe(!1)},1500):Te.data.error&&(qe(!1),alert(`Recapture failed: ${Te.data.error}`)))},[Te.state,Te.data,Ee]);const gr=()=>{d&&Ye.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})};J(()=>{Ye.state==="idle"&&Ye.data&&(Ye.data.success?Ee.revalidate():Ye.data.error&&alert(`Analysis failed: ${Ye.data.error}`))},[Ye.state,Ye.data,d?.sha,Ee]),J(()=>{const G=setTimeout(()=>{Ee.revalidate()},500);return()=>clearTimeout(G)},[]),J(()=>{if(hr||Cn){const G=setInterval(()=>{Ee.revalidate()},3e3);return()=>clearInterval(G)}else{const G=setInterval(()=>{Ee.revalidate()},5e3),le=setTimeout(()=>{clearInterval(G)},3e4);return()=>{clearInterval(G),clearTimeout(le)}}},[hr,Cn,Ee]);const to=(G,le)=>G==="scenarios"?`/entity/${d?.sha}/scenarios`:`/entity/${d?.sha}/${G}`,no=(G,le)=>`/entity/${d?.sha}/scenarios/${G}/${le}`,ro=G=>{I(G),v?.id&&w(no(v.id,G),{replace:!0})},ao=async G=>{if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:G,hasSelectedScenario:!!v,hasAnalysis:!!u}),!v||!u){const le="Error: No scenario or analysis available";console.error("[EntityDetail]",le),D(le);return}R(!0),D(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:G,scenarioId:v.id,scenarioName:v.name,currentData:v.data});try{const le=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:G,existingScenarios:u.scenarios,scenariosDataStructure:u.metadata?.scenariosDataStructure,editingMockName:v.name,editingMockData:B||v.metadata?.data})}),ce=await le.json();if(!le.ok||!ce.success)throw new Error(ce.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",ce.data),U(ce.data);const ve=(u.scenarios||[]).map(ue=>ue.id===v.id?{...ue,metadata:{...ue.metadata,data:ce.data}}:ue),ct=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:u,scenarios:ve})}),_e=await ct.json();if(!ct.ok||!_e.success)throw console.error("[EntityDetail] Temp save failed:",_e),new Error(_e.error||"Failed to apply preview");if(D("Generating preview. Capturing screenshot..."),ye){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:ye});const ue=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:ye,scenarioId:v.id,projectId:u.projectId,viewportWidth:1440})}),wt=await ue.json();!ue.ok||!wt.success?(console.error("[EntityDetail] Direct capture failed:",wt),D("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),D('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const ue=new FormData;ue.append("analysisId",u.id||""),ue.append("scenarioId",v.id||"");const wt=await fetch("/api/recapture-scenario",{method:"POST",body:ue}),Nn=await wt.json();!wt.ok||!Nn.success?(console.warn("[EntityDetail] Recapture failed:",Nn.error),D("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",Nn.jobId),D('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}ee(ue=>ue+1),Ee.revalidate()}catch(le){console.error("Error applying changes:",le),D(`Error: ${le instanceof Error?le.message:String(le)}`)}finally{R(!1)}},oo=async(G,le)=>{if(!v||!u){D("Error: No scenario or analysis available");return}k(!0),D(null),console.log("[EntityDetail] Saving scenario to database",{description:G,saveAsNew:le});try{const ce=B||v.metadata?.data;let ve;if(le){const ue={...v,id:`${v.name}-${Date.now()}`,name:`${v.name} (Copy)`,metadata:{...v.metadata,data:ce},description:G||v.description};ve=[...u.scenarios||[],ue]}else ve=(u.scenarios||[]).map(ue=>ue.id===v.id?{...ue,metadata:{...ue.metadata,data:ce},description:G||ue.description}:ue);const ct=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:u,scenarios:ve})}),_e=await ct.json();if(!ct.ok||!_e.success)throw new Error(_e.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),D(le?"New scenario created successfully":"Scenario saved successfully"),U(null),Ee.revalidate()}catch(ce){console.error("Error saving scenario:",ce),D(`Error: ${ce instanceof Error?ce.message:String(ce)}`)}finally{k(!1)}},so=()=>{console.log("[EntityDetail] Edit mock data clicked"),D("Mock data editor coming soon")},io=async()=>{if(!v?.id){_("Cannot delete scenario without ID");return}te(!0),_(null);try{const G=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:v.id,screenshotPaths:v.metadata?.screenshotPaths||[]})}),le=await G.json();if(!G.ok||!le.success)throw new Error(le.error||"Failed to delete scenario");w(`/entity/${d?.sha}/scenarios`)}catch(G){console.error("[EntityDetail] Error deleting scenario:",G),_(G instanceof Error?G.message:"Failed to delete scenario"),F(!1)}finally{te(!1)}},yr=d?du(d):!1,xr=u!==null;return n(pn,{children:c("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:c("div",{className:"flex items-center h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-1.5 min-w-0",children:[n("button",{onClick:N,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-sm font-semibold text-black m-0 leading-[20px] shrink-0",children:d?.name}),pr?c("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[c("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",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..."]}):eo?n("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#f3e5f5",color:"#6a1b9a",height:"23px"},children:"Queued"}):xr?yr?n("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"23px"},children:"Out of date"}):n("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"23px"},children:"Up to date"}):n("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#f9f9f9",color:"#646464",height:"23px"},children:"Not analyzed"}),n("span",{className:"text-[#e1e1e1] mx-1.5 shrink-0",children:"|"}),n("span",{className:"text-sm text-[#626262] font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d?.filePath,children:d?.filePath})]}),n("div",{className:"flex items-center gap-3 shrink-0",children:(!xr||yr)&&n("button",{onClick:gr,disabled:Ye.state!=="idle",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 disabled:bg-gray-400 disabled:cursor-not-allowed",children:"Analyze"})})]})}),n("div",{className:"bg-[#efefef] border-b border-[#e1e1e1] shrink-0",children:n("div",{className:"flex items-center gap-6 h-10 px-[15px] shrink-0",children:[{id:"scenarios",label:"Scenarios",count:x.length},{id:"related",label:"Related Entities",count:h.importedEntities.length+h.importingEntities.length},{id:"data",label:"Data Structure"},{id:"code",label:"Code"},{id:"history",label:"History"}].map(G=>c(oe,{to:to(G.id),className:`flex items-center justify-center gap-3 shrink-0 text-sm rounded-md transition-colors no-underline ${E===G.id?"bg-[#343434] text-[#efefef] font-medium h-8 px-6":"text-[#3e3e3e] font-normal hover:bg-gray-100 py-1 px-[15px]"}`,children:[G.label,G.count!==void 0&&n("span",{className:`w-[25px] h-5 rounded-md text-xs font-normal flex items-center justify-center ${E===G.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:G.count})]},G.id))})}),c("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[E==="scenarios"&&c(se,{children:[P&&v?n(hu,{scenario:v,entitySha:d?.sha||"",onApply:ao,onSave:oo,onEditMockData:so,onDelete:io,isApplying:T,isSaving:O,saveMessage:j,showDeleteConfirm:ne,onShowDeleteConfirm:F,isDeleting:Y,deleteError:H}):n(mu,{scenarios:x,analysis:u,selectedScenario:v,entitySha:d?.sha||"",cacheBuster:Rt,activeTab:E,entityType:d?.entityType,entity:d,queueState:b,processIsRunning:M,viewMode:S,setViewMode:ro,onDebugSetup:()=>{!v?.id||!u?.id||pe.submit({analysisId:u.id,scenarioId:v.id},{method:"post",action:"/api/debug-setup"})},debugFetcher:pe}),P&&v?n(gn,{scenarioId:v.id||v.name,scenarioName:v.name,iframeUrl:ye,isStarting:Q,isLoading:L,showIframe:ae,iframeKey:me,onIframeLoad:vt,projectSlug:m,defaultWidth:1440,defaultHeight:900}):n(Ka,{selectedScenario:v,analysis:u,entity:d,viewMode:S,cacheBuster:Rt,hasScenarios:x.length>0,isAnalyzing:Cn,projectSlug:m,hasAnApiKey:y})]}),E==="related"&&n(wu,{relatedEntities:h}),E==="data"&&n(Eu,{entity:d,analysis:u,scenarios:x,onAnalyze:gr}),E==="code"&&n(ku,{entity:d,entityCode:p}),E==="history"&&n(bu,{entity:d,history:f})]}),$t&&m&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>re(!1),children:c("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:G=>G.stopPropagation(),children:[c("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:()=>re(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(gt,{projectSlug:m,onClose:()=>re(!1)})})]})}),Dt&&Oe&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>Ke(!1),children:c("div",{className:"bg-white rounded-xl max-w-200 w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:G=>G.stopPropagation(),children:[c("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("div",{className:"flex items-center gap-3",children:n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:Oe.instructions?.title||"Debug Environment Ready"})}),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:()=>Ke(!1),children:"×"})]}),n("div",{className:"px-6",children:n(St,{scenarioId:v?.id,analysisId:u?.id})}),n("div",{className:"px-6 py-6 overflow-y-auto flex-1",children:n("div",{className:"p-0",children:Oe.instructions?.sections?.map((G,le)=>c("div",{className:"mb-6 last:mb-0",children:[c("h3",{className:"text-base font-semibold text-gray-900 m-0 mb-3 pb-2 border-b-2 border-gray-200 flex items-center gap-2",children:[G.heading==="Status"&&!Oe.complete&&n("div",{className:"w-6 h-6 border-3 border-purple-600 border-t-transparent rounded-full animate-spin",style:{borderWidth:"3px"}}),G.heading]}),G.items.map((ce,ve)=>c("div",{className:"mb-3 pl-0 last:mb-0",children:[ce.label&&n("div",{className:"font-semibold text-gray-700 mb-1 text-sm",children:ce.label}),ce.isCode?c("div",{className:"relative mt-1",children:[n("code",{className:"block bg-gray-800 text-gray-50 px-3 py-2.5 pr-[90px] rounded-md text-[13px] font-mono overflow-x-auto",children:ce.content}),n(rn,{content:ce.content,label:"📋 Copy",className:"absolute top-2 right-2 px-2.5 py-1 bg-purple-600/90 text-white border-none rounded text-[11px] font-semibold cursor-pointer transition-all backdrop-blur hover:bg-purple-700/95 hover:scale-105 active:scale-95 disabled:opacity-75 disabled:cursor-not-allowed disabled:scale-100"})]}):ce.isLink?c("div",{className:"flex items-center gap-2 mt-1",children:[n("a",{href:ce.content,target:"_blank",rel:"noopener noreferrer",className:"text-purple-600 hover:text-purple-800 underline text-sm font-medium",children:ce.content}),n(rn,{content:ce.content,label:"📋",className:"px-2 py-1 bg-gray-200 text-gray-700 border-none rounded text-[11px] font-semibold cursor-pointer transition-all hover:bg-gray-300 hover:scale-105 active:scale-95"})]}):n("div",{className:"text-gray-600 text-sm leading-relaxed",children:ce.content})]},ve))]},le))})}),n("div",{className:"px-6 py-6 border-t border-gray-200 flex justify-end gap-3",children:n("button",{className:"px-5 py-2.5 bg-gray-500 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-gray-600",onClick:()=>Ke(!1),children:"Close"})})]})})]})})}),Du=Object.freeze(Object.defineProperty({__proto__:null,default:ju,loader:Ru,meta:Tu,shouldRevalidate:Iu},Symbol.toStringTag,{value:"Module"}));async function $u(e){const{entityShas:t,filePaths:r,context:a,scenarioCount:o,queue:s}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await Ae();const i=de();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=he.join(i,".codeyam","config.json"),d=JSON.parse(await Ce.readFile(l,"utf8")),{projectSlug:u,branchId:m}=d;if(!u||!m)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${u}, Branch: ${m}`);const h=mn(u);try{await Ce.writeFile(h,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:p,branch:f}=await Re(u);let g=r;if(!g||g.length===0){console.log("[analyzeEntities] Loading entities to determine file paths...");const x=await pt({shas:t});if(!x||x.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);g=[...new Set(x.map(w=>w.filePath).filter(w=>!!w))],console.log(`[analyzeEntities] Found ${g.length} unique files`)}if(!g||g.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${g.length} files...`);const y=await Ii(p,f,g);console.log(`[analyzeEntities] Created commit ${y.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await ut({commitSha:y.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),currentEntityShas:t,entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:(x,w)=>{if(!x)return;const C=x.currentRun;if(C&&C.id&&C.archivedAt)return;C&&(C.analysesCompleted&&C.analysesCompleted>0||C.capturesCompleted&&C.capturesCompleted>0)&&Hi(x)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:b}=s.enqueue({type:"analysis",commitSha:y.sha,projectSlug:u,filePaths:g,entityShas:t,...a?{context:a}:{},...o?{scenarioCount:o}:{}});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 Lu({request:e,context:t}){if(e.method!=="POST")return $({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await He()),!r)return $({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("entitySha"),s=a.get("entityShas"),i=a.get("filePath"),l=a.get("context"),d=a.get("scenarioCount");let u;if(s)u=s.split(",").filter(Boolean);else if(o)u=[o];else return $({error:"Missing required field: entitySha or entityShas"},{status:400});if(u.length===0)return $({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${u.length} entity(ies)`);const{jobId:m}=await $u({entityShas:u,filePaths:i?[i]:void 0,context:l||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${m}`),$({success:!0,message:`Analysis queued for ${u.length} entity(ies)`,entityCount:u.length,jobId:m})}catch(a){return console.error("[API] Error starting analysis:",a),$({error:"Failed to start analysis",details:a.message},{status:500})}}const Ou=Object.freeze(Object.defineProperty({__proto__:null,action:Lu},Symbol.toStringTag,{value:"Module"}));function ir(e){switch(e){case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:c("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"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 Va(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 o=t.getHours(),s=t.getMinutes(),i=o>=12?"pm":"am",l=o%12||12,d=s.toString().padStart(2,"0");return`Today, ${l}:${d} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function Fe(e,t=[]){if(t.some(i=>!!(i.entityShas?.includes(e.sha)||i.entities?.some(l=>l.sha===e.sha))))return"analyzing";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const a=e.analyses[0],o=a.createdAt?new Date(a.createdAt).getTime():0,s=e.metadata?.editedAt?new Date(e.metadata.editedAt).getTime():0;return o>=s?"up-to-date":"out-of-date"}const Yu=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function Fu({request:e,context:t}){try{const r=t.analysisQueue,a=r?r.getState():{paused:!1,jobs:[]},o=await Tt();return $({entities:o||[],queueState:a})}catch(r){return console.error("Failed to load simulations:",r),$({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const zu=je(function(){const t=Le(),r=t.entities,a=t.queueState;nt({source:"simulations-page"});const[o,s]=A(""),[i,l]=A("visual"),d=Z(()=>{const y=[];return r.forEach(b=>{const x=b.analyses?.[0];if(x?.scenarios){const w=x.scenarios.filter(C=>C.metadata?.screenshotPaths?.[0]).map(C=>({scenarioName:C.name,scenarioDescription:C.description||"",screenshotPath:C.metadata?.screenshotPaths?.[0]||"",scenarioId:C.id}));w.length>0&&y.push({entity:b,screenshots:w,createdAt:x.createdAt||""})}}),y.sort((b,x)=>new Date(x.createdAt).getTime()-new Date(b.createdAt).getTime()),y},[r]),u=Z(()=>r.filter(y=>!y.analyses?.[0]?.scenarios?.some(w=>w.metadata?.screenshotPaths?.[0])),[r]),m=Z(()=>d.filter(({entity:y})=>{const b=!o||y.name.toLowerCase().includes(o.toLowerCase()),x=i==="all"||y.entityType===i;return b&&x}),[d,o,i]),h=Z(()=>u.filter(y=>{const b=!o||y.name.toLowerCase().includes(o.toLowerCase()),x=i==="all"||y.entityType===i;return b&&x}),[u,o,i]),p=X(y=>{s(y.target.value)},[]),f=X(y=>{l(y.target.value)},[]),g=d.length>0;return n("div",{className:"bg-[#f9f9f9] min-h-screen overflow-y-auto",children:c("div",{className:"px-12 py-6",children:[c("div",{className:"mb-6",children:[n("h1",{className:"text-3xl font-bold text-gray-900 m-0",children:"Simulations"}),n("p",{className:"text-sm text-gray-600 mt-2",children:"A visual gallery of your recently captured simulations."})]}),!g&&c("div",{className:"rounded-lg mb-6 flex items-center",style:{backgroundColor:"#cbf3fa",paddingLeft:"17px",paddingRight:"17px",paddingTop:"24px",paddingBottom:"24px",gap:"15px"},children:[n("div",{className:"shrink-0 flex items-center justify-center",style:{width:"33px",height:"33px"},children:n(Qe,{className:"w-8 h-8",style:{color:"#005c75"}})}),c("div",{children:[n("p",{className:"m-0 mb-0",style:{color:"#005c75",fontSize:"14px",lineHeight:"18px",fontWeight:400},children:"This page will display a visual gallery of your recently captured component simulations."}),n("p",{className:"m-0",style:{color:"#005c75",fontSize:"18px",lineHeight:"26px",fontWeight:600},children:"Start by analyzing your first component below."})]})]}),c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-6",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative",children:[c("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 py-2 pr-8 text-sm 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(Jt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(ra,{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 py-2 text-sm placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:o,onChange:p})]})]})]}),g&&m.length>0&&n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:c("div",{className:"flex items-center gap-1.5 px-3 py-2",children:[n("span",{children:"ENTITY"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"text-[#3e3e3e]",children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),c("div",{className:"flex flex-col gap-3",children:[g&&(m.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(se,{children:m.map(({entity:y,screenshots:b})=>n(Bu,{entity:y,screenshots:b,queueJobs:a?.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(Uu,{entity:y},y.sha)))]})]})})});function Bu({entity:e,screenshots:t,queueJobs:r}){const a=_t(),o=t.length||(e.analyses?.[0]?.scenarios?.length??0),s=d=>{a(`/entity/${e.sha}/scenarios/${d}?from=simulations`)},i=Fe(e,r),l=ir(i);return n("div",{className:"bg-white rounded hover:bg-gray-50 transition-colors",children:c("div",{className:"px-5 pb-[15px]",children:[c("div",{className:"flex items-center justify-between py-[10px]",children:[c(oe,{to:`/entity/${e.sha}`,className:"flex items-center gap-2 no-underline",children:[n(Pe,{type:e.entityType}),c("span",{className:"font-['IBM_Plex_Sans'] font-medium text-[12px] leading-[15px] text-[#343434]",children:[e.name," (",o,")"]})]}),c("div",{className:"flex items-center gap-2.5",children:[c("span",{className:"px-2 rounded inline-flex items-center gap-1.5 max-w-full whitespace-nowrap overflow-hidden",style:{backgroundColor:l.bgColor,color:l.textColor,height:"23px",fontSize:"10px",lineHeight:"15px"},children:[l.icon,l.text]}),n("button",{onClick:()=>{a(`/entity/${e.sha}/logs`)},className:"bg-[#e0e9ec] text-[#005c75] rounded font-['IBM_Plex_Sans'] font-semibold hover:bg-[#d0dfe5] transition-colors px-[10px] py-0 cursor-pointer border-none",style:{fontSize:"10px",lineHeight:"22px"},children:"View Logs"})]})]}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-1",children:t.length>0?t.map(d=>n("button",{onClick:()=>s(d.scenarioId||""),className:"shrink-0 block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border border-gray-200 overflow-hidden bg-gray-100 flex items-center justify-center transition-all",style:{"--hover-border":"#005C75"},onMouseEnter:u=>{u.currentTarget.style.borderColor="#005C75",u.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)"},onMouseLeave:u=>{u.currentTarget.style.borderColor="#d1d5db",u.currentTarget.style.boxShadow="none"},children:n(Be,{screenshotPath:d.screenshotPath,alt:d.scenarioName,className:"max-w-full max-h-full object-contain"})})},d.scenarioId)):n("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function Uu({entity:e}){const t=we(),[r,a]=A(!1),o=()=>{a(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return J(()=>{t.state==="idle"&&r&&a(!1)},[t.state,r]),n("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer",onClick:o,children:c("div",{className:"px-5 py-4 flex items-center",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(Pe,{type:e.entityType}),c("div",{className:"min-w-0",children:[c("div",{className:"flex items-center gap-3 mb-0.5",children:[n(oe,{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:Va(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?c("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($e,{size:14,className:"animate-spin"}),"Analyzing..."]}):n("button",{onClick:o,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 Hu=Object.freeze(Object.defineProperty({__proto__:null,default:zu,loader:Fu,meta:Yu},Symbol.toStringTag,{value:"Module"}));function qu({request:e,context:t}){const r=t.dbNotifier||Ze;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 a=new ReadableStream({start(o){const s=new TextEncoder;o.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
160
|
-
|
|
161
|
-
`)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",d),clearInterval(u);try{o.close()}catch{}}},d=m=>{try{o.enqueue(s.encode(`data: ${JSON.stringify({type:"db-change",changeType:m.type,timestamp:m.timestamp})}
|
|
162
|
-
|
|
163
|
-
`))}catch{l()}};r.on("change",d);const u=setInterval(()=>{try{o.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
164
|
-
|
|
165
|
-
`))}catch{l()}},3e4);e.signal.addEventListener("abort",l)}});return new Response(a,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const Gu=Object.freeze(Object.defineProperty({__proto__:null,loader:qu},Symbol.toStringTag,{value:"Module"}));function Xe(){const e=process.memoryUsage(),t=ds.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(Dn.totalmem()/1024/1024),freeMemory:Math.round(Dn.freemem()/1024/1024)}}}function Wu(){const e=Xe();console.log(`
|
|
166
|
-
[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 Ju(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=Xe();global.gc();const t=Xe(),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 Ku(){const e=Xe(),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},a=[];return r.highHeapUsage&&a.push(`High heap usage: ${t.toFixed(1)}% of limit`),r.highExternalMemory&&a.push(`High external memory: ${e.process.external} MB`),r.highArrayBuffers&&a.push(`High ArrayBuffer usage: ${e.process.arrayBuffers} MB`),r.nearHeapLimit&&a.push(`Near heap limit: only ${e.heap.totalAvailableSize} MB available`),{indicators:r,warnings:a,hasIssues:a.length>0}}function Vu({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 a=Ju(),o=Xe();return Response.json({success:a,message:a?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:o})}case"detailed":{const a=Wu();return Response.json({success:!0,stats:a})}case"leaks":{const a=Ku(),o=Xe();return Response.json({success:!0,leakCheck:a,stats:o})}default:{const a=Xe();return Response.json({success:!0,stats:a,actions:{gc:"/api/memory?action=gc - Force garbage collection (requires --expose-gc)",detailed:"/api/memory?action=detailed - Log detailed stats to console",leaks:"/api/memory?action=leaks - Check for memory leak indicators"}})}}}catch(a){return console.error("[Memory API] Error:",a),Response.json({success:!1,error:a.message},{status:500})}}const Qu=Object.freeze(Object.defineProperty({__proto__:null,loader:Vu},Symbol.toStringTag,{value:"Module"}));async function Zu({request:e,context:t}){let r=t.analysisQueue;if(r||(r=await He()),!r)return $({error:"Queue not initialized"},{status:500});const a=new URL(e.url),o=a.searchParams.get("queryType");if(!o)return $({error:"Missing queryType parameter for GET request"},{status:400});if(o==="job"){const s=a.searchParams.get("jobId");if(!s)return $({error:"Missing jobId parameter for job query"},{status:400});const i=r.getState();if(i.currentlyExecuting?.id===s)return $({jobId:s,status:"running",job:i.currentlyExecuting});const l=i.jobs.find(u=>u.id===s);if(l){const u=i.jobs.indexOf(l);return $({jobId:s,status:"queued",position:u,job:l})}const d=r.getJobResult(s);return d?$({jobId:s,status:d.status==="error"?"failed":"completed",error:d.error}):$({jobId:s,status:"completed"})}if(o==="full"){const s=r.getState(),i=await Promise.all(s.jobs.map(async d=>{const u=[];if(d.entityShas&&d.entityShas.length>0){const m=d.entityShas.map(p=>ze(p)),h=await Promise.all(m);u.push(...h.filter(p=>p!==null))}return{id:d.id,type:d.type,commitSha:d.commitSha,projectSlug:d.projectSlug,queuedAt:d.queuedAt,entities:u,filePaths:d.filePaths}}));let l;if(s.currentlyExecuting){const d=s.currentlyExecuting,u=[];if(d.entityShas&&d.entityShas.length>0){const m=d.entityShas.map(p=>ze(p)),h=await Promise.all(m);u.push(...h.filter(p=>p!==null))}l={id:d.id,type:d.type,commitSha:d.commitSha,projectSlug:d.projectSlug,queuedAt:d.queuedAt,entities:u,filePaths:d.filePaths}}return $({state:{...s,jobsWithEntities:i,currentlyExecutingWithEntities:l}})}return $({error:"Unknown queryType"},{status:400})}async function Xu({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?.analysisQueue);let r=t.analysisQueue;if(r||(r=await He(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),$({error:"Queue not initialized"},{status:500});const a=await e.json(),{action:o,...s}=a;if(console.log("[Queue API] Action:",o,"Params:",Object.keys(s)),o==="enqueue"){const{jobId:i,completion:l}=r.enqueue(s);return l.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),$({jobId:i,status:"queued"})}return o==="resume"?(r.resume(),$({status:"resumed"})):o==="pause"?(r.pause(),$({status:"paused"})):$({error:"Unknown action"},{status:400})}const em=Object.freeze(Object.defineProperty({__proto__:null,action:Xu,loader:Zu},Symbol.toStringTag,{value:"Module"})),tm=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],nm=je(function(){return we(),n(pn,{children:c("div",{className:"h-screen bg-[#f9f9f9] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-center h-full px-6 gap-6",children:[c("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"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[c("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"})]}),c("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:c("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[c("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"})]}),c("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"})]})}),c("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(Ka,{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})]})]})})}),rm=Object.freeze(Object.defineProperty({__proto__:null,default:nm,meta:tm},Symbol.toStringTag,{value:"Module"})),am=()=>[{title:"CodeYam - Settings"},{name:"description",content:"Configure project settings"}];async function om({request:e}){try{const t=await er();if(!t)return $({config:null,secrets:null,versionInfo:null,error:"Project configuration not found"});const r=de()||process.cwd(),a=await un(r),o=Da(t.projectSlug);return $({config:t,secrets:{GROQ_API_KEY:a.GROQ_API_KEY||"",ANTHROPIC_API_KEY:a.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:a.OPENAI_API_KEY||""},versionInfo:o,error:null})}catch(t){return console.error("Failed to load config:",t),$({config:null,secrets:null,versionInfo:null,error:"Failed to load configuration"})}}function sm(e){if(!e||!e.trim())return;const t=e.trim().split(/\s+/);if(t.length===0)return;const r=t[0],a=t.length>1?t.slice(1):void 0;return{command:r,args:a}}async function im({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),a=t.get("startCommands"),o=t.get("groqApiKey"),s=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),l=t.get("pathsToIgnore");let d;if(r)try{d=JSON.parse(r)}catch{return $({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let u;if(a)try{u=JSON.parse(a)}catch{return $({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let m;l&&(m=l.split(",").map(g=>g.trim()).map(g=>g.startsWith('"')&&g.endsWith('"')||g.startsWith("'")&&g.endsWith("'")?g.slice(1,-1):g).filter(g=>g.length>0));let h;if(u){const g=await er();g?.webapps&&(h=g.webapps.map((y,b)=>{if(u[b]!==void 0){const x=sm(u[b]);return{...y,startCommand:x}}return y}))}if(!await Ea({universalMocks:d,pathsToIgnore:m,webapps:h}))return $({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let f=!1;if(o!==void 0||s!==void 0||i!==void 0){const g=de()||process.cwd(),y=await un(g);f=o!==void 0&&o!==(y.GROQ_API_KEY||"")||s!==void 0&&s!==(y.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(y.OPENAI_API_KEY||""),await ji(g,{...y,GROQ_API_KEY:o||void 0,ANTHROPIC_API_KEY:s||void 0,OPENAI_API_KEY:i||void 0},!0)}return $({success:!0,error:null,requiresRestart:f})}catch(t){return console.log("[Settings Action] Failed to save config:",t),$({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function Zr(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Xr({mock:e,onSave:t,onCancel:r}){const[a,o]=A(e.entityName),[s,i]=A(e.filePath),[l,d]=A(e.content);return c("div",{className:"space-y-3",children:[c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:a,onChange:m=>o(m.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"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:s,onChange:m=>i(m.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"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:l,onChange:m=>d(m.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' }"})]}),c("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(!a.trim()||!s.trim()||!l.trim()){alert("All fields are required");return}t({entityName:a,filePath:s,content:l})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function lm(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const cm=je(function(){const{config:t,secrets:r,versionInfo:a,error:o}=Le(),s=yo(),i=we(),l=ft(),[d,u]=A("project-metadata");nt({source:"settings-page"});const[m,h]=A(t?.universalMocks||[]),[p,f]=A((t?.pathsToIgnore||[]).join(", ")),[g,y]=A((t?.pathsToIgnore||[]).join(", ")),[b,x]=A(r?.GROQ_API_KEY||""),[w,C]=A(r?.ANTHROPIC_API_KEY||""),[N,M]=A(r?.OPENAI_API_KEY||""),[E,v]=A(!1),[S,I]=A(!1),[P,T]=A(!1),[R,O]=A(!1),[k,j]=A(!1),[D,Y]=A(!1),[te,ne]=A(null),[F,H]=A(!1),[_,B]=A({});J(()=>{if(t){h(t.universalMocks||[]);const L=(t.pathsToIgnore||[]).join(", ");f(L),y(L);const ae={};t.webapps?.forEach((me,vt)=>{me.startCommand&&(ae[vt]=Zr(me.startCommand))}),B(ae)}r&&(x(r.GROQ_API_KEY||""),C(r.ANTHROPIC_API_KEY||""),M(r.OPENAI_API_KEY||""))},[t,r]),J(()=>{if(s?.success){O(!0);const L=setTimeout(()=>O(!1),3e3);return()=>clearTimeout(L)}},[s]),J(()=>{if(i.state==="idle"&&i.data&&!D){console.log("[Settings] Fetcher data:",i.data);const L=i.data;if(L.success){console.log("[Settings] Save successful, revalidating..."),O(!0),Y(!0),(p!==g||L.requiresRestart)&&j(!0),l.revalidate();const ae=setTimeout(()=>{O(!1),Y(!1)},3e3);return()=>clearTimeout(ae)}}},[i.state,i.data,D,l,p,g]);const U=L=>{L.preventDefault();const ae=new FormData(L.currentTarget);ae.set("universalMocks",JSON.stringify(m)),ae.set("startCommands",JSON.stringify(_)),console.log("[Settings] Submitting form data:",{universalMocks:ae.get("universalMocks"),startCommands:ae.get("startCommands"),openAiApiKey:ae.get("openAiApiKey")?"***":"(empty)"}),i.submit(ae,{method:"post"})},V=L=>{h([...m,L]),H(!1)},ee=(L,ae)=>{const me=[...m];me[L]=ae,h(me),ne(null)},ye=L=>{h(m.filter((ae,me)=>me!==L))};if(o)return c("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 Q=[{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:"current-configuration",label:"Current Configuration"}];return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-36 py-12 font-sans",children:[c("div",{className:"mb-8 flex justify-between items-start",children:[c("div",{children:[n("h1",{className:"text-3xl font-bold text-gray-900",children:"Settings"}),n("p",{className:"text-sm text-gray-500 mt-2",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:i.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:i.state==="submitting"?"Saving...":"Save Settings"})]}),c("div",{className:"flex gap-8 items-start",children:[n("nav",{className:"w-64 flex-shrink-0",children:n("ul",{className:"space-y-1",children:Q.map(L=>n("li",{children:n("button",{type:"button",onClick:()=>u(L.id),className:`w-full text-left px-0 py-2.5 text-sm transition-colors ${d===L.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:L.label})},L.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:c("form",{id:"settings-form",onSubmit:U,className:"space-y-6",children:[d==="project-metadata"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),c("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t?.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((L,ae)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:L.path==="."?"Root":L.path})]}),L.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:L.appDirectory})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:L.framework})]}),L.startCommand&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",c("span",{className:"text-gray-900 font-mono text-xs",children:[L.startCommand.command," ",L.startCommand.args?.join(" ")]})]})]})},ae))}):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`."})]})]}),d==="ai-provider"&&c("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."}),c("div",{className:"space-y-6",children:[c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("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."}),c("div",{className:"flex gap-3 text-xs",children:[c("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"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),c("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"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:E?"text":"password",id:"groqApiKey",name:"groqApiKey",value:b,onChange:L=>x(L.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:()=>v(!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",children:E?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("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."}),c("div",{className:"flex gap-3 text-xs",children:[c("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"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),c("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"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:S?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:w,onChange:L=>C(L.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:()=>I(!S),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",children:S?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("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."}),c("div",{className:"flex gap-3 text-xs",children:[c("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"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),c("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"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:P?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:N,onChange:L=>M(L.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(!P),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",children:P?"Hide":"Show"})]})]})]})]})]}),d==="commands"&&c("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?.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((L,ae)=>c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[c("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:L.path==="."?"Root":L.path}),n("div",{className:"text-sm text-gray-600",children:L.framework})]}),c("div",{children:[n("label",{htmlFor:`startCommand-${ae}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${ae}`,name:`startCommand-${ae}`,value:_[ae]||"",onChange:me=>B({..._,[ae]:me.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"})]})]},ae))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),d==="paths-to-ignore"&&c("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:p,onChange:L=>f(L.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"}),c("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"})]})]}),d==="universal-mocks"&&c("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"}),m.length===0?c("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:()=>H(!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:m.map((L,ae)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:te===ae?n(Xr,{mock:L,onSave:me=>ee(ae,me),onCancel:()=>ne(null)}):n(se,{children:c("div",{className:"flex justify-between items-start mb-2",children:[c("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:L.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:L.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:L.content})]}),c("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>ne(ae),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:()=>ye(ae),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},ae))}),m.length>0&&n("button",{type:"button",onClick:()=>H(!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"})]}),d==="current-configuration"&&c("div",{className:"space-y-6",children:[t&&c("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:c("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&c("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&&c("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((L,ae)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:L.path==="."?"Root":L.path})]}),L.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:L.appDirectory})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:L.framework})]}),L.startCommand&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:Zr(L.startCommand)})]})]})},ae))})]})]}),a&&c("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:c("div",{className:"space-y-2 text-sm",children:[a.webserverVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",n("span",{className:"text-gray-900 font-mono",children:a.webserverVersion.version||"unknown"})]}),a.templateVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",n("span",{className:"font-mono text-gray-900",children:a.templateVersion.version||a.templateVersion.gitCommit?.slice(0,7)||"unknown"}),a.templateVersion.buildTimestamp&&c("span",{className:"text-gray-500 ml-2",children:["(built"," ",lm(a.templateVersion.buildTimestamp),")"]})]}),a.cachedAnalyzerVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"font-mono text-gray-900",children:a.cachedAnalyzerVersion.version||a.cachedAnalyzerVersion.gitCommit?.slice(0,7)||"unknown"}),a.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"})]}),!a.cachedAnalyzerVersion&&t?.projectSlug&&c("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"})]})]})})]})]})]})})]}),(R||k||s?.error||i.data&&typeof i.data=="object"&&"error"in i.data)&&c("div",{className:"mt-6 max-w-5xl mx-auto space-y-3",children:[R&&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!"}),k&&c("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:"}),n("code",{className:"ml-2 bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"})]}),s?.error&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:s.error}),(()=>{if(i.data&&typeof i.data=="object"&&"error"in i.data){const L=i.data;return typeof L.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:L.error}):null}return null})()]}),F&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:c("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(Xr,{mock:{entityName:"",filePath:"",content:""},onSave:V,onCancel:()=>H(!1)})]})})]})})}),dm=Object.freeze(Object.defineProperty({__proto__:null,action:im,default:cm,loader:om,meta:am},Symbol.toStringTag,{value:"Module"}));async function um({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=de();if(!r)return new Response("Project root not found",{status:500});const o=he.extname(t)!==""?t:`${t}.html`,s=he.join(r,".codeyam","captures","static",o);try{await Ce.access(s);let i=await Ce.readFile(s);const l=he.extname(s).toLowerCase();let d="application/octet-stream";if(l===".html"){d="text/html";let u=i.toString("utf-8");const m=u.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(m)try{const p=m[1].match(/=\s*(\{[\s\S]*\})/);if(p){const f=JSON.parse(p[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const g=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;u=u.replace(m[0],g)}}catch(h){console.error("[Static] Failed to parse Remix context:",h)}i=Buffer.from(u,"utf-8")}else l===".js"||l===".mjs"?d="application/javascript":l===".css"?d="text/css":l===".json"?d="application/json":l===".png"?d="image/png":l===".jpg"||l===".jpeg"?d="image/jpeg":l===".svg"?d="image/svg+xml":l===".woff"?d="font/woff":l===".woff2"?d="font/woff2":l===".ttf"&&(d="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const mm=Object.freeze(Object.defineProperty({__proto__:null,loader:um},Symbol.toStringTag,{value:"Module"}));function hm(e,t,r=10){const a=new Map,o=d=>d.entityType==="visual"||d.entityType==="library";for(const d of e)o(d)&&a.set(d.sha,{entity:d,depth:0});const s=new Map;for(const d of t){const u=d.metadata?.importedBy;if(u)for(const m of Object.keys(u))for(const h of Object.keys(u[m])){const{shas:p}=u[m][h];for(const f of p)s.has(d.sha)||s.set(d.sha,new Set),s.get(d.sha).add(f)}}const i=[],l=new Set;for(const d of e)i.push({sha:d.sha,depth:0}),l.add(d.sha);for(;i.length>0;){const{sha:d,depth:u}=i.shift();if(u>=r)continue;const m=s.get(d);if(m)for(const h of m){if(l.has(h))continue;l.add(h);const p=t.find(f=>f.sha===h);if(p){if(o(p)){const f=u+1,g=a.get(h);(!g||f<g.depth)&&a.set(h,{entity:p,depth:f})}i.push({sha:h,depth:u+1})}}}return Array.from(a.values()).sort((d,u)=>d.depth!==u.depth?d.depth-u.depth:d.entity.name.localeCompare(u.entity.name))}function an(e){const t=new Map;for(const a of e)t.has(a.name)||t.set(a.name,[]),t.get(a.name).push(a);const r=[];for(const a of t.values())if(a.length===1)r.push(a[0]);else{const o=a.sort((s,i)=>{const l=s.metadata?.editedAt||s.createdAt||"";return(i.metadata?.editedAt||i.createdAt||"").localeCompare(l)});r.push(o[0])}return r}function Qa(e,t){const r=new Map,a=new Set(e.map(o=>o.path));for(const o of e)o.status==="renamed"&&o.oldPath&&a.add(o.oldPath);for(const o of e){const s=t.filter(d=>d.filePath===o.path||o.status==="renamed"&&o.oldPath&&d.filePath===o.oldPath),i=s.filter(d=>a.has(d.filePath)&&d.metadata?.isUncommitted&&!d.metadata?.isSuperseded),l=an(i);r.set(o.path,{status:o,entities:s,editedEntities:l})}return r}function pm(e,t,r){const a=new Map;if(!r){for(const s of e)if(s.status==="deleted")a.set(s.path,{status:s,entities:[]});else{const i=t.filter(d=>d.filePath===s.path||s.status==="renamed"&&s.oldPath&&d.filePath===s.oldPath),l=an(i);a.set(s.path,{status:s,entities:l})}return a}const o=new Map;for(const s of r.fileComparisons){const i=new Set;for(const l of s.newEntities)i.add(l.name);for(const l of s.modifiedEntities)i.add(l.name);for(const l of s.deletedEntities)i.add(l.name);i.size>0&&o.set(s.filePath,i)}for(const s of e){const i=o.get(s.path);if(s.status==="deleted")a.set(s.path,{status:s,entities:[]});else{const l=i?t.filter(u=>(u.filePath===s.path||s.status==="renamed"&&s.oldPath&&u.filePath===s.oldPath)&&i.has(u.name)):[],d=an(l);a.set(s.path,{status:s,entities:d})}}return a}function fm(e,t){const r=new Map,a=Za(e,t);for(const o of a){const i=hm([o],t).filter(({depth:l})=>l>0);r.set(o.sha,i)}return r}function Za(e,t){const r=new Set(e.map(o=>o.path));for(const o of e)o.status==="renamed"&&o.oldPath&&r.add(o.oldPath);const a=t.filter(o=>r.has(o.filePath)&&o.metadata?.isUncommitted&&!o.metadata?.isSuperseded);return an(a)}const gm="/assets/codeyam-name-logo-CvKwUgHo.svg",ym=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function xm({request:e,context:t}){try{const r=t.analysisQueue,a=r?r.getState():{paused:!1,jobs:[]},[o,s,i]=await Promise.all([Tt(),ke(),st()]),l=Ba(),d=o?Qa(l,o):new Map,u=Array.from(d.entries()).sort((S,I)=>S[0].localeCompare(I[0])),m=o?.length||0,h=o?.filter(S=>S.entityType==="visual").length||0,p=o?.filter(S=>S.entityType==="library").length||0,f=o?Za(l,o):[],g=f.length,y=o?.filter(S=>(S.analyses??[]).filter(I=>I.scenarios&&I.scenarios.length>0).length>0).length||0,b=o?.reduce((S,I)=>{const P=I.analyses?.[0]?.scenarios?.length||0;return S+P},0)||0,x=o?.reduce((S,I)=>{const T=(I.analyses?.[0]?.scenarios||[]).filter(R=>R.metadata?.screenshotPaths?.[0]).length;return S+T},0)||0,w=[];o?.forEach(S=>{const I=S.analyses?.[0];I?.scenarios&&I.scenarios.forEach(P=>{const T=P.metadata?.screenshotPaths?.[0];T&&w.push({entitySha:S.sha,entityName:S.name,scenarioId:P.id,scenarioName:P.name,screenshotPath:T,createdAt:I.createdAt||""})})}),w.sort((S,I)=>new Date(I.createdAt).getTime()-new Date(S.createdAt).getTime());const C=w.slice(0,16),N=o?.filter(S=>S.entityType==="visual").filter(S=>!S.analyses?.[0]?.scenarios?.some(T=>T.metadata?.screenshotPaths?.[0])).slice(0,8)||[],E=i?.metadata?.currentRun?.currentEntityShas?.length||0,v=a.jobs.length||0;return $({stats:{totalEntities:m,visualEntities:h,libraryEntities:p,uncommittedEntities:g,entitiesWithAnalyses:y,totalScenarios:b,capturedScreenshots:x,currentlyAnalyzing:E,filesOnQueue:v},uncommittedFiles:u,uncommittedEntitiesList:f,recentSimulations:C,visualEntitiesForSimulation:N,projectSlug:s,queueState:a,currentCommit:i})}catch(r){return console.error("Failed to load dashboard data:",r),$({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 bm=je(function(){const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:a,recentSimulations:o,visualEntitiesForSimulation:s,projectSlug:i,queueState:l,currentCommit:d}=Le(),u=we(),m=ft(),{showToast:h}=Kn();nt({source:"dashboard"});const[p,f]=A(new Set),[g,y]=A(null),[b,x]=A(!1),[w,C]=A(!1),{lastLine:N,isCompleted:M,resetLogs:E}=rt(i,!!g),{simulatingEntity:v,scenarios:S,scenarioStatuses:I,allScenariosCaptured:P}=Z(()=>{const _={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!g)return _;const B=s?.find(L=>L.sha===g);if(!B)return _;const U=B.analyses?.[0],V=U?.scenarios||[],ee=U?.status?.scenarios||[],ye=ee.filter(L=>L.screenshotFinishedAt).length,Q=V.length>0&&ye===V.length;return{simulatingEntity:B,scenarios:V,scenarioStatuses:ee,allScenariosCaptured:Q}},[g,s]);J(()=>{(M||P)&&y(null)},[M,P]);const T=d?.metadata?.currentRun,R=new Set(T?.currentEntityShas||[]),O=new Set(l.jobs.flatMap(_=>_.entityShas||[])),k=new Set(l.currentlyExecuting?.entityShas||[]),j=a.filter(_=>_.entityType==="visual"||_.entityType==="library"),D=j.filter(_=>!R.has(_.sha)&&!O.has(_.sha)&&!k.has(_.sha)),Y=()=>{if(D.length===0){h("All entities are already queued or analyzing","info",3e3);return}console.log("Analyzing uncommitted entities not yet queued:",D.length),console.log("Entity SHAs:",D.map(_=>_.sha)),C(!0),h(`Starting analysis for ${D.length} entities...`,"info",3e3),u.submit({entityShas:D.map(_=>_.sha).join(",")},{method:"post",action:"/api/analyze"})};J(()=>{if(u.state==="idle"&&u.data){const _=u.data;_.success?(console.log("[Analyze All] Success:",_.message),h(`Analysis started for ${_.entityCount} entities in ${_.fileCount} files. Watch the logs for progress.`,"success",6e3),C(!1)):_.error&&(console.error("[Analyze All] Error:",_.error),h(`Error: ${_.error}`,"error",8e3),C(!1))}},[u.state,u.data,h]);const te=(_,B)=>{console.log("Simulating entity:",_);const U=s?.find(V=>V.sha===_);y(_),E(),h(`Starting analysis for ${U?.name||"entity"}...`,"info",3e3),u.submit({entitySha:_,filePath:B},{method:"post",action:"/api/analyze"})},ne=_=>{f(B=>{const U=new Set(B);return U.has(_)?U.delete(_):U.add(_),U})},F=Z(()=>{const _=new Map;return o.forEach(B=>{const U=B.entitySha;_.has(U)||_.set(U,[]),_.get(U).push(B)}),Array.from(_.entries()).map(([B,U])=>({entitySha:B,entityName:U[0].entityName,scenarios:U}))},[o]),H=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#F59E0B"},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981"},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6"},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9"}];return n("div",{className:"bg-cygray-10 min-h-screen",children:c("div",{className:"pt-10 pb-6 px-12",children:[c("header",{className:"mb-8 flex justify-between items-center",children:[c("div",{className:"flex items-center gap-2",children:[n("img",{src:gm,alt:"CodeYam",className:"h-3.5"}),n("span",{className:"text-gray-400 text-sm",children:"|"}),c("h1",{className:"text-sm font-normal text-gray-600 m-0",children:["Overview of"," ",n("span",{className:"font-semibold",children:i?i.replace(/-/g," ").replace(/\b\w/g,_=>_.toUpperCase()):"Project"})]})]}),m.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:H.map((_,B)=>n(oe,{to:_.link,className:"flex-1 bg-white rounded-xl border border-gray-200 overflow-hidden flex transition-all hover:shadow-lg hover:-translate-y-0.5 no-underline cursor-pointer",style:{borderLeft:`4px solid ${_.color}`},children:c("div",{className:"px-6 py-4 flex flex-col gap-3 flex-1",children:[c("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[n("div",{className:"text-xs text-gray-700 font-medium",children:_.label}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 sm:hidden md:flex",style:{color:_.color},children:"View All →"})]}),c("div",{className:"flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-3",children:[c("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${_.color}15`},children:[_.iconType==="folder"&&n(Do,{size:20,style:{color:_.color}}),_.iconType==="check"&&n(Bn,{size:20,style:{color:_.color}}),_.iconType==="image"&&n(Qe,{size:20,style:{color:_.color}}),_.iconType==="code-xml"&&n($o,{size:20,style:{color:_.color}})]}),n("div",{className:"text-2xl font-bold text-gray-900 leading-none",children:_.value})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:_.color},children:"View All →"})]})]})},B))}),c("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[c("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[c("div",{className:"flex justify-between items-start mb-5",children:[c("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 ${a.length} uncommitted entit${a.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),j.length>0&&n("button",{onClick:Y,disabled:u.state!=="idle"||w||D.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:_=>_.currentTarget.style.backgroundColor="#004560",onMouseLeave:_=>_.currentTarget.style.backgroundColor="#005C75",children:u.state!=="idle"||w?"Starting analysis...":D.length===0?"All Queued":`Analyze All (${D.length})`})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([_,B])=>{const U=p.has(_),V=B.editedEntities||[];return c("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#306AFF"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>ne(_),role:"button",tabIndex:0,children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:U?"▼":"▶"}),c("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[c("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"})})})]}),c("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:_}),c("span",{className:"text-xs text-gray-500",children:[V.length," entit",V.length!==1?"ies":"y"]})]})]})}),U&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:V.length>0?V.map(ee=>{const ye=R.has(ee.sha),Q=O.has(ee.sha)||k.has(ee.sha);return c(oe,{to:`/entity/${ee.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:L=>L.currentTarget.style.borderColor="#005C75",onMouseLeave:L=>L.currentTarget.style.borderColor="inherit",children:[c("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:ee.entityType==="visual"?"#8B5CF615":ee.entityType==="library"?"#6366F1":"#EC4899"},children:[ee.entityType==="visual"&&n(Qe,{size:16,style:{color:"#8B5CF6"}}),ee.entityType==="library"&&n(na,{size:16,className:"text-white"}),ee.entityType==="other"&&n(Lo,{size:16,className:"text-white"})]}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:ee.name}),ee.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),ee.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),ee.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),ee.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:ee.description})]}),c("div",{className:"flex items-center gap-2 shrink-0",children:[ye&&c("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($e,{size:14,className:"animate-spin"}),"Analyzing..."]}),!ye&&Q&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!ye&&!Q&&n("button",{onClick:L=>{L.preventDefault(),L.stopPropagation(),h(`Starting analysis for ${ee.name}...`,"info",3e3),u.submit({entityShas:ee.sha},{method:"post",action:"/api/analyze"})},disabled:u.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:L=>L.currentTarget.style.backgroundColor="#004560",onMouseLeave:L=>L.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},ee.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},_)})}):c("div",{className:"py-12 px-6 text-center flex flex-col items-center bg-gray-50 rounded-lg min-h-50 justify-center",children:[c("svg",{width:"52",height:"68",viewBox:"0 0 26 34",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"mb-4 opacity-40",children:[c("g",{clipPath:"url(#clip0_784_10631)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H18.9423L26.0318 7.14651V31.4562C26.0318 32.8693 24.8863 34.0148 23.4732 34.0148H2.55857C1.14551 34.0148 0 32.8693 0 31.4562V2.55857Z",fill:"#D9D9D9"}),n("path",{d:"M18.9453 7.08081H26.0261L18.9453 0V7.08081Z",fill:"#646464"}),n("line",{x1:"3.92188",y1:"13.3633",x2:"21.7341",y2:"13.3633",stroke:"#646464",strokeWidth:"1.27929"}),n("line",{x1:"3.92188",y1:"19.4863",x2:"13.0321",y2:"19.4863",stroke:"#646464",strokeWidth:"1.27929"}),n("line",{x1:"3.92188",y1:"25.6016",x2:"21.7341",y2:"25.6016",stroke:"#646464",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10631",children:n("rect",{width:"26",height:"34",fill:"white"})})})]}),n("p",{className:"text-sm font-medium text-gray-400 m-0 mb-2",children:"No Uncommitted Changes."})]})]}),c("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:c("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:o.length>0?`Latest ${o.length} captured screenshot${o.length!==1?"s":""}`:"No simulations captured yet"})]})}),o.length>0&&!g?c(se,{children:[n("div",{className:"space-y-6 mb-5",children:F.map(_=>c("div",{children:[c("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(Qe,{size:16,style:{color:"#8B5CF6"}})}),n(oe,{to:`/entity/${_.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:_.entityName})]}),n("div",{className:"grid grid-cols-4 gap-3",children:_.scenarios.map((B,U)=>n(oe,{to:B.scenarioId?`/entity/${B.entitySha}/scenarios/${B.scenarioId}`:`/entity/${B.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:V=>{V.currentTarget.style.borderColor="#005C75",V.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:V=>{V.currentTarget.style.borderColor="#E5E7EB",V.currentTarget.style.boxShadow="none"},title:`${B.scenarioName}`,children:n(Be,{screenshotPath:B.screenshotPath,alt:B.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},U))})]},_.entitySha))}),n(oe,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:_=>_.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:_=>_.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):g?c("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[v&&n("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(Pe,{type:"visual"})}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",v.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:v.filePath})]})]})}),P?c("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:"✅"}),c("span",{children:["Complete (",S.length," scenario",S.length!==1?"s":"",")"]})]}):N?c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n($e,{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:()=>x(!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"})]}):u.state!=="idle"?c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n($e,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n($e,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),S.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:S.slice(0,8).map((_,B)=>{const U=_.metadata?.screenshotPaths?.[0],V=I.find(Q=>Q.name===_.name),ee=V?.screenshotStartedAt&&!V?.screenshotFinishedAt;return U?n(oe,{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(Be,{screenshotPath:U,alt:_.name,title:_.name,className:"max-w-full max-h-full object-contain object-center"})},B):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:`Capturing ${_.name}...`,children:n("span",{className:ee?"animate-pulse":"text-gray-400",children:ee?"⋯":"⏹️"})},B)})})]}):c("div",{className:"flex flex-col items-center",children:[c("div",{className:"py-12 px-6 text-center bg-gray-50 rounded-lg w-full flex flex-col items-center justify-center min-h-50",children:[n("div",{className:"mb-4 bg-[#efefef] rounded-lg p-3",children:n(Qe,{size:28,style:{color:"#999999"},strokeWidth:1.5})}),n("p",{className:"text-gray-700 m-0 font-semibold",children:"Start by analyzing your first component below."})]}),(s?.length??0)>0?n(se,{children:n("div",{className:"flex flex-col gap-3 mt-6 w-full",children:(g&&v?[v]:s||[]).map(_=>n("div",{className:"flex flex-col gap-3",children:c("div",{className:"flex items-center gap-4 p-4 bg-white border border-gray-200 rounded-lg transition-colors",style:{borderLeft:"4px solid #8B5CF6"},onMouseEnter:B=>{B.currentTarget.style.backgroundColor="#F9FAFB"},onMouseLeave:B=>{B.currentTarget.style.backgroundColor="white"},children:[c(oe,{to:`/entity/${_.sha}`,className:"flex items-center gap-4 flex-1 min-w-0 no-underline",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(Qe,{size:16,style:{color:"#8B5CF6"}})}),c("div",{className:"flex-1 min-w-0",children:[n("div",{className:"font-semibold text-gray-900 text-sm mb-1",children:_.name}),n("div",{className:"text-xs text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:_.filePath})]})]}),n("button",{onClick:()=>te(_.sha,_.filePath||""),disabled:u.state!=="idle"||g!==null,className:"px-4 py-2 text-white border-none rounded text-sm font-medium cursor-pointer transition-all whitespace-nowrap shrink-0 disabled:bg-gray-400 disabled:cursor-not-allowed disabled:translate-y-0",style:{backgroundColor:"#005C75"},onMouseEnter:B=>B.currentTarget.style.backgroundColor="#004560",onMouseLeave:B=>B.currentTarget.style.backgroundColor="#005C75",title:g?"Please wait for current analysis to complete":"Analyze this entity",children:"Analyze"})]})},_.sha))})}):n("p",{className:"text-base text-gray-600 m-0 mb-6 leading-relaxed mt-6",children:"Run analysis on your visual components to create simulations and capture screenshots"})]})]})]}),b&&i&&n(gt,{projectSlug:i,onClose:()=>x(!1)})]})})}),vm=Object.freeze(Object.defineProperty({__proto__:null,default:bm,loader:xm,meta:ym},Symbol.toStringTag,{value:"Module"}));function Xa(e){const t=we(),{showToast:r}=Kn();J(()=>{if(t.state==="idle"&&t.data){const i=t.data;i?.error&&r(`Error: ${i.error}`,"error",6e3)}},[t.state,t.data,r]);const a=i=>{console.log("Generate analysis clicked for entity:",i.sha,i.name);const l=new FormData;l.append("entitySha",i.sha),l.append("filePath",i.filePath||""),t.submit(l,{method:"post",action:"/api/analyze"})},o=i=>{const l=i.filter(m=>m.entityType==="visual"||m.entityType==="library");console.log("Generate analysis for all entities:",l.length);const d=l.map(m=>m.sha).join(","),u=new FormData;u.append("entityShas",d),t.submit(u,{method:"post",action:"/api/analyze"})},s=i=>e?.includes(i)??!1;return{isAnalyzing:t.state!=="idle",handleGenerateSimulation:a,handleGenerateAllSimulations:o,isEntityBeingAnalyzed:s}}function lr({showActions:e=!1,sortOrder:t="desc",onSortChange:r}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:c("div",{className:"flex justify-between items-center px-3 py-2",children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"160px"},children:n("span",{children:"SIMULATIONS"})}),c("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),n("div",{className:"flex items-center justify-center",style:{width:"127px"},children:n("span",{children:"STATE"})}),c("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:a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),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("span",{className:"text-center",style:{width:"96px"}})]})]})]})})}function wm({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"}},a={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 s=a[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:s.textColor},children:s.label})})}const o=r[e]||{label:"?",bgColor:"bg-gray-500"};return c("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 ${o.bgColor}`,title:e,children:o.label}),o.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 cr({filePath:e,isExpanded:t,onToggle:r,fileStatus:a,simulationPreviews:o,entityCount:s,state:i,lastModified:l,actionButton:d,uncommittedCount:u,children:m}){const h=ir(i);return c("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #306AFF",borderRadius:"8px"}:{borderRadius:"8px"},children:[c("div",{className:"flex justify-between items-center p-3 cursor-pointer select-none transition-colors hover:bg-gray-200",style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),r())},children:[c("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(ca,{filePath:e}),a&&n(wm,{status:typeof a=="string"?a:a.status,variant:"full"}),u!==void 0&&u>0&&c("span",{className:"text-[10px] text-amber-500 font-medium shrink-0 whitespace-nowrap",children:[u," uncommitted"]})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex gap-1.5 items-center justify-center h-[38px]",style:{width:"160px"},children:o}),c("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:c("span",{className:"text-[13px] text-[#3e3e3e]",children:[s," ",s===1?"entity":"entities"]})})}),n("div",{className:"flex items-center justify-center",style:{width:"127px"},children:c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 max-w-full whitespace-nowrap overflow-hidden text-ellipsis",style:{backgroundColor:h.bgColor,color:h.textColor,height:"26px"},children:[h.icon,h.text]})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:Va(l)}),n("div",{style:{width:"96px"},className:"flex justify-center",children:d})]})]})]}),t&&m&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-2",children:m})]})}function dr({entities:e,maxPreviews:t=3}){const r=[];for(const a of e){if(r.length>=t)break;const o=a.analyses?.[0]?.scenarios||[];if(a.entityType==="library"){const s=o.find(i=>i.metadata?.executionResult||i.metadata?.error);s&&r.push({type:"library",scenario:s,entitySha:a.sha})}else if(a.entityType==="visual"){const s=o.find(i=>i.metadata?.screenshotPaths?.[0]);if(s){const i=s.metadata?.screenshotPaths?.[0],l=!!s.metadata?.error;i&&r.push({type:"screenshot",screenshot:i,hasError:l})}}}return r.length===0?n("span",{className:"text-gray-400 text-center w-full font-light text-[14px]",children:"—"}):n(se,{children:r.map((a,o)=>{if(a.type==="screenshot"&&a.screenshot){const s=a.hasError?"border-red-400":"border-gray-200";return c("div",{className:`relative w-[50px] h-[38px] border ${s} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center`,children:[n(Be,{screenshotPath:a.screenshot,alt:`Preview ${o+1}`,className:"max-w-full max-h-full object-contain object-center"}),a.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(jn,{size:12,color:"white"})})]},`screenshot-${o}`)}return a.type==="library"&&a.scenario&&a.entitySha?n(Ja,{scenario:a.scenario,entitySha:a.entitySha,size:"small",showBorder:!0},`library-${o}`):null})})}function ur({entity:e,isBeingAnalyzed:t,isQueued:r,onGenerateSimulation:a}){const o=t||r?[{entityShas:[e.sha]}]:[],s=Fe(e,o),i=ir(s),d=(e.entityType==="visual"||e.entityType==="library")&&(s==="not-analyzed"||s==="out-of-date")&&!t&&!r;return c("div",{className:"bg-white rounded-lg flex items-center justify-between p-3 transition-colors hover:bg-gray-100",children:[c("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(Pe,{type:"type"})})}):n(Pe,{type:e.entityType||"other"}),n("span",{className:"font-['IBM_Plex_Sans'] font-medium text-[14px] leading-[18px] text-black",children:e.name}),n(ar,{type:e.entityType||"other"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),c("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{className:"flex items-center justify-center",style:{width:"127px"},children:c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 max-w-full whitespace-nowrap overflow-hidden",style:{backgroundColor:i.bgColor,color:i.textColor,height:"26px"},children:[i.icon,i.text]})}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"96px"},className:"flex justify-center items-center",children:d&&n("button",{onClick:u=>{u.stopPropagation(),a(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"})})]})]})]})}function Cm({entities:e,page:t,itemsPerPage:r=50,currentRun:a,filter:o,entityType:s,queueState:i,onGenerateSimulation:l,onGenerateAllSimulations:d}){const[u,m]=Fn(),[h,p]=A(new Set),[f,g]=A(""),[y,b]=A(!1),[x,w]=A("all"),[C,N]=A("desc"),M=s||"all",E=Z(()=>{let j=e;return M!=="all"&&(j=j.filter(D=>D.entityType===M)),o==="analyzed"&&(j=j.filter(D=>D.analyses&&D.analyses.length>0)),j},[e,M,o]),v=Z(()=>{const j=new Map,D=new Map,Y=new Map;E.forEach(F=>{const H=`${F.filePath}::${F.name}`,_=D.get(H);if(!_)D.set(H,F),Y.set(H,[]);else{const B=_.metadata?.editedAt||_.createdAt||"",U=F.metadata?.editedAt||F.createdAt||"";let V=!1;if(U>B)V=!0;else if(U===B){const ee=_.createdAt||"";V=(F.createdAt||"")>ee}V?(Y.get(H).push(_),D.set(H,F)):Y.get(H).push(F)}}),D.forEach((F,H)=>{if(!(F.analyses&&F.analyses.length>0)&&F.metadata?.previousVersionWithAnalyses){const U=(Y.get(H)||[]).find(V=>V.sha===F.metadata?.previousVersionWithAnalyses);U&&U.analyses&&U.analyses.length>0&&(F.analyses=U.analyses)}}),Array.from(D.values()).sort((F,H)=>{const _=!F.metadata?.notExported&&!F.metadata?.namedExport,B=!H.metadata?.notExported&&!H.metadata?.namedExport;return _&&!B?-1:!_&&B?1:0}).forEach(F=>{const H=F.filePath??"No File Path";j.has(H)||j.set(H,{filePath:H,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const _=j.get(H);_.entities.push(F),_.totalCount++,F.metadata?.isUncommitted&&_.uncommittedCount++;const B=F.analyses?.[0]?.scenarios?.length||0;_.simulationCount+=B;const U=F.metadata?.editedAt||F.updatedAt;U&&(!_.lastUpdated||new Date(U)>new Date(_.lastUpdated))&&(_.lastUpdated=U)});const te=i?.jobs||[];j.forEach(F=>{const H=F.entities.map(_=>Fe(_,te));H.includes("analyzing")?F.state="analyzing":H.includes("out-of-date")?F.state="out-of-date":H.includes("not-analyzed")?F.state="not-analyzed":F.state="up-to-date"}),j.forEach(F=>{for(const H of F.entities){if(F.previewScreenshots.length+F.previewLibraryScenarios.length>=3)break;const B=H.analyses?.[0]?.scenarios||[];if(H.entityType==="library"){const U=B.find(V=>V.metadata?.executionResult||V.metadata?.error);U&&F.previewLibraryScenarios.push({scenario:U,entitySha:H.sha})}else{const U=B.find(V=>V.metadata?.screenshotPaths?.[0]);if(U){const V=U.metadata?.screenshotPaths?.[0],ee=!!U.metadata?.error;V&&!F.previewScreenshots.includes(V)&&(F.previewScreenshots.push(V),F.previewScreenshotErrors.push(ee))}}}});const ne=Array.from(j.values());return ne.sort((F,H)=>{if(o==="analyzed"){const U=Math.max(...F.entities.filter(ee=>ee.analyses?.[0]?.createdAt).map(ee=>new Date(ee.analyses[0].createdAt).getTime()),0),V=Math.max(...H.entities.filter(ee=>ee.analyses?.[0]?.createdAt).map(ee=>new Date(ee.analyses[0].createdAt).getTime()),0);return C==="desc"?V-U:U-V}if(F.uncommittedCount>0&&H.uncommittedCount===0)return-1;if(F.uncommittedCount===0&&H.uncommittedCount>0)return 1;const _=F.lastUpdated?new Date(F.lastUpdated).getTime():0,B=H.lastUpdated?new Date(H.lastUpdated).getTime():0;return C==="desc"?B-_:_-B}),ne},[E,o,C]),S=Z(()=>{let j=v;if(x!=="all"&&(j=j.filter(D=>D.state===x)),f.trim()){const D=f.toLowerCase();j=j.filter(Y=>Y.filePath.toLowerCase().includes(D))}return j},[v,f,x]),I=(t-1)*r,P=I+r,T=S.slice(I,P),R=Math.ceil(S.length/r),O=j=>{p(D=>{const Y=new Set(D);return Y.has(j)?Y.delete(j):Y.add(j),Y})};return c("div",{children:[c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-6",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative w-[130px]",children:[c("select",{value:M,onChange:j=>{const D=j.target.value,Y=new URLSearchParams(u);D==="all"?Y.delete("entityType"):Y.set("entityType",D),Y.set("page","1"),m(Y)},className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[12px] 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(Jt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-2 h-2 text-gray-500 pointer-events-none"})]}),c("div",{className:"relative w-[130px]",children:[c("select",{value:x,onChange:j=>w(j.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[12px] 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:"out-of-date",children:"Out of date"}),n("option",{value:"not-analyzed",children:"Not analyzed"})]}),n(Jt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-2 h-2 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(ra,{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:f,onChange:j=>g(j.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[12px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]}),n("button",{onClick:()=>{y?(p(new Set),b(!1)):(p(new Set(T.map(j=>j.filePath))),b(!0))},className:"px-[10px] h-[39px] border-none rounded text-[12px] font-medium cursor-pointer transition-colors whitespace-nowrap bg-[#005c75] text-white hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed w-[130px]",children:y?"Collapse All":"Expand All"})]})]}),n(lr,{showActions:!0,sortOrder:C,onSortChange:()=>{N(j=>j==="desc"?"asc":"desc")}}),n("div",{className:"flex flex-col gap-3",children:T.map(j=>{const D=h.has(j.filePath),te=j.entities.filter(_=>(_.entityType==="visual"||_.entityType==="library")&&(Fe(_,i?.jobs||[])==="not-analyzed"||Fe(_,i?.jobs||[])==="out-of-date")).length>0,ne=_=>a?.currentEntityShas?.includes(_)||!1,F=_=>i?.jobs?.some(B=>B.entityShas?.includes(_))||!1,H=_=>{l?.(_)};return n(cr,{filePath:j.filePath,isExpanded:D,onToggle:()=>O(j.filePath),simulationPreviews:n(dr,{entities:j.entities,maxPreviews:3}),entityCount:j.totalCount,state:j.state,lastModified:j.lastUpdated,uncommittedCount:j.uncommittedCount,actionButton:te?n("button",{onClick:_=>{_.stopPropagation();const B=j.entities.filter(U=>(U.entityType==="visual"||U.entityType==="library")&&(Fe(U,i?.jobs||[])==="not-analyzed"||Fe(U,i?.jobs||[])==="out-of-date"));d?.(B)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):void 0,children:j.entities.map(_=>n(ur,{entity:_,isBeingAnalyzed:ne(_.sha),isQueued:F(_.sha),onGenerateSimulation:H},_.sha))},j.filePath)})}),R>1&&c("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(u),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),c("span",{children:["Page ",t," of ",R]}),t<R&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(u),page:String(t+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const Nm=()=>[{title:"CodeYam - Files & Entities"},{name:"description",content:"Browse your codebase files and entities"}];async function Sm({request:e,context:t}){try{const r=new URL(e.url),a=parseInt(r.searchParams.get("page")||"1"),o=r.searchParams.get("filter")||null,s=r.searchParams.get("entityType"),i=t.analysisQueue,l=i?i.getState():{paused:!1,jobs:[]},[d,u]=await Promise.all([Tt(),st()]);return $({entities:d,currentCommit:u,page:a,filter:o,entityType:s,queueState:l})}catch(r){return console.error("Failed to load entities:",r),$({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const Em=je(function(){const{entities:t,currentCommit:r,page:a,filter:o,entityType:s,queueState:i}=Le(),l=ft();nt({source:"files-page"});const{handleGenerateSimulation:d,handleGenerateAllSimulations:u}=Xa(r?.metadata?.currentRun?.currentEntityShas),m=Z(()=>{if(!t)return[];const f=new Set([]);for(const g of t)f.add(g.filePath??"No File Path");return Array.from(f)},[t]),h=Z(()=>t?t.sort((f,g)=>f.metadata?.isUncommitted&&!g.metadata?.isUncommitted?-1:!f.metadata?.isUncommitted&&g.metadata?.isUncommitted?1:new Date(g.metadata?.editedAt||0).getTime()-new Date(f.metadata?.editedAt||0).getTime()):[],[t]),p=Z(()=>{if(!t)return[];const f=new Set([]);for(const g of t)g.metadata?.isUncommitted&&f.add(g.filePath??"No File Path");return Array.from(f)},[t]);return t?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-12 py-6 font-sans",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-bold text-gray-900",children:"Files & Entities"}),c("div",{className:"flex items-center gap-4 text-sm text-gray-600 mt-2",children:[l.state==="loading"&&n("span",{className:"text-blue-600 font-medium animate-pulse",children:"🔄"}),c("span",{children:[m.length," files"]}),n("span",{className:"text-gray-300",children:"|"}),c("span",{children:[t.length," entities"]}),n("span",{className:"text-gray-300",children:"|"}),c("span",{className:"text-amber-500 font-medium",children:[p.length," uncommitted files"]})]})]}),n(Cm,{entities:h,page:a,itemsPerPage:50,currentRun:r?.metadata?.currentRun,filter:o,entityType:s,queueState:i,onGenerateSimulation:d,onGenerateAllSimulations:u})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-3xl font-bold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:"Unable to retrieve entities"})]})})}),Am=Object.freeze(Object.defineProperty({__proto__:null,default:Em,loader:Sm,meta:Nm},Symbol.toStringTag,{value:"Module"}));function _m(e,t,r){const[a,o]=A(()=>new Set(t)),[s,i]=A(()=>new Set(r)),l=be([]),d=be([]);return J(()=>{(t.length!==l.current.length||t.some((y,b)=>y!==l.current[b]))&&(l.current=t,o(y=>{const b=new Set(y);return t.forEach(x=>{y.has(x)||b.add(x)}),b}))},[t]),J(()=>{(r.length!==d.current.length||r.some((y,b)=>y!==d.current[b]))&&(d.current=r,i(y=>{const b=new Set(y);return r.forEach(x=>{y.has(x)||b.add(x)}),b}))},[r]),{expandedUncommitted:a,expandedBranch:s,setExpandedUncommitted:o,setExpandedBranch:i,toggleFile:(g,y,b)=>{b(x=>{const w=new Set(x);return w.has(g)?w.delete(g):w.add(g),w})},expandAllUncommitted:()=>{o(new Set(t))},collapseAllUncommitted:()=>{o(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function Pm(e,t,r){const[a,o]=A(null),[s,i]=A(null),l=we();J(()=>{l.data?.oldContent!==void 0&&l.data?.newContent!==void 0&&i({oldContent:l.data.oldContent,newContent:l.data.newContent,fileName:l.data.fileName})},[l.data]);const d=h=>{o({type:"file",path:h}),i(null);const p=new FormData;p.append("actionType","getDiff"),p.append("filePath",h),p.append("diffType",r==="branch"?"branch":"uncommitted"),p.append("baseBranch",e),p.append("currentBranch",t||""),l.submit(p,{method:"post"})},u=(h,p)=>{o({type:"entity",path:h,entitySha:p}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",h),f.append("diffType",r==="branch"?"branch":"uncommitted"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",p),l.submit(f,{method:"post"})},m=()=>{o(null),i(null)};return{diffView:a,diffContent:s,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:u,handleCloseDiff:m}}function Mm({diffView:e,diffContent:t,isLoading:r,entities:a,onClose:o}){const[s,i]=A(!1),[l,d]=A(!1);return J(()=>{d(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:c("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[c("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[c("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&&c("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",a.find(u=>u.sha===e.entitySha)?.name||e.entitySha]})]}),c("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!s),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:s?"Show changes only":"Show full file",children:s?"Show Changes Only":"Show Full File"}),n("button",{onClick:o,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(us,{oldValue:t.oldContent,newValue:t.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!s,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:o,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 km({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:a}){return n("div",{children:c("nav",{className:"flex gap-8 items-center",children:[c("button",{onClick:()=>t("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-[#005C75]":"text-gray-500 hover:text-gray-700"}`,children:[c("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-[-1px] left-0 right-0 h-[2px] bg-[#005C75]"})]}),c("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-[#005C75]":"text-gray-500 hover:text-gray-700"}`,children:[c("span",{className:"flex items-center gap-2",children:["Branch Changes",a>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:a})]}),e==="branch"&&n("span",{className:"absolute bottom-[-1px] left-0 right-0 h-[2px] bg-[#005C75]"})]})]})})}function Tm({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:a,isEntityQueued:o,projectSlug:s,baseBranch:i,currentBranch:l,sortOrder:d,onToggleFile:u,onShowFileDiff:m,onGenerateSimulation:h,onSortChange:p}){const f=Z(()=>{const b=[];return e.forEach(([x,{editedEntities:w}])=>{const C=w.filter(N=>a(N.sha)||o(N.sha)).map(N=>N.sha);C.length>0&&b.push({entityShas:C})}),b},[e,a,o]),g=Z(()=>{const b=new Map;return e.forEach(([x,{editedEntities:w}])=>{const C=w.map(v=>Fe(v,f));let N;C.includes("analyzing")?N="analyzing":C.includes("out-of-date")?N="out-of-date":C.includes("not-analyzed")?N="not-analyzed":N="up-to-date";const M=w.reduce((v,S)=>{const I=S.metadata?.editedAt||S.updatedAt;return I&&(!v||new Date(I)>new Date(v))?I:v},null),E=w.filter(v=>v.entityType==="visual"||v.entityType==="library").length;b.set(x,{state:N,lastModified:M,analyzableCount:E})}),b},[e,f]),y=Z(()=>[...e].sort((b,x)=>{const w=g.get(b[0]),C=g.get(x[0]),N=w?.lastModified,M=C?.lastModified;if(!N&&!M)return 0;if(!N)return 1;if(!M)return-1;const E=new Date(N).getTime(),v=new Date(M).getTime();return d==="desc"?v-E:E-v}),[e,g,d]);return e.length===0?c("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."})]}):c("div",{children:[n(lr,{showActions:!0,sortOrder:d,onSortChange:p}),n("div",{className:"flex flex-col gap-3",children:y.map(([b,{status:x,editedEntities:w}])=>{const C=r.has(b),N=g.get(b),{state:M,lastModified:E,analyzableCount:v}=N,S=v>0&&(M==="not-analyzed"||M==="out-of-date");return n(cr,{filePath:b,isExpanded:C,onToggle:()=>u(b),fileStatus:x,simulationPreviews:n(dr,{entities:w,maxPreviews:3}),entityCount:w.length,state:M,lastModified:E,actionButton:S?n("button",{onClick:I=>{I.stopPropagation(),w.filter(P=>(P.entityType==="visual"||P.entityType==="library")&&!a(P.sha)&&!o(P.sha)).forEach(P=>h(P))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze"}):void 0,children:w.map(I=>n(ur,{entity:I,isBeingAnalyzed:a(I.sha),isQueued:o(I.sha),onGenerateSimulation:h},I.sha))},b)})})]})}function Im({files:e,currentBranch:t,defaultBranch:r,baseBranch:a,allBranches:o,expandedFiles:s,isEntityBeingAnalyzed:i,isEntityQueued:l,sortOrder:d,onToggleFile:u,onBranchChange:m,onGenerateSimulation:h,onSortChange:p}){const f=e.flatMap(([b,{entities:x}])=>{const w=x.filter(C=>i(C.sha)||l(C.sha)).map(C=>C.sha);return w.length>0?[{entityShas:w}]:[]}),g=b=>{const x=b.map(w=>Fe(w,f));return x.includes("analyzing")?"analyzing":x.includes("out-of-date")?"out-of-date":x.includes("not-analyzed")?"not-analyzed":"up-to-date"},y=Z(()=>[...e].sort((b,x)=>{const w=b[1].entities.reduce((E,v)=>{const S=v.metadata?.editedAt||v.updatedAt;return S?E?new Date(S)>new Date(E)?S:E:S:E},null),C=x[1].entities.reduce((E,v)=>{const S=v.metadata?.editedAt||v.updatedAt;return S?E?new Date(S)>new Date(E)?S:E:S:E},null);if(!w&&!C)return 0;if(!w)return 1;if(!C)return-1;const N=new Date(w).getTime(),M=new Date(C).getTime();return d==="desc"?M-N:N-M}),[e,d]);return c("div",{children:[n("div",{className:"mb-5",children:t===r?c("p",{className:"text-[14px] font-['IBM_Plex_Sans'] font-normal text-[#626262] leading-[18px]",children:["Currently on the primary branch"," ",n("strong",{className:"text-gray-900 font-semibold",children:t})]}):c("p",{className:"text-[14px] font-['IBM_Plex_Sans'] font-normal text-[#3e3e3e] leading-[18px]",children:["Changes in"," ",n("strong",{className:"font-['IBM_Plex_Sans'] font-semibold text-[#232323]",children:t})," ","compared to:"," ",n("select",{value:a,onChange:b=>m(b.target.value),className:"py-0.5 px-2.5 bg-white border border-[#efefef] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal text-[#232323] cursor-pointer hover:border-gray-300 leading-[15px] h-[25px]",style:{paddingRight:"26px",backgroundPosition:"right 6px center",backgroundRepeat:"no-repeat",backgroundSize:"8px 4px",appearance:"none",backgroundImage:`url("data:image/svg+xml;charset=UTF-8,%3csvg width='8' height='4' viewBox='0 0 8 4' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M1 0.5L4 3.5L7 0.5' stroke='%233e3e3e' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e")`},children:o.filter(b=>b!==t).map(b=>n("option",{value:b,children:b},b))})]})}),t===r?c("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 Branch Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"You're on the primary branch. Switch to a feature branch to see changes."})]}):e.length>0?c("div",{children:[n(lr,{showActions:!0,sortOrder:d,onSortChange:p}),n("div",{className:"flex flex-col gap-3",children:y.map(([b,{status:x,entities:w}])=>{const C=s.has(b),N=g(w),M=w.reduce((S,I)=>{const P=I.metadata?.editedAt||I.updatedAt;return P?S?new Date(P)>new Date(S)?P:S:P:S},null),v=w.filter(S=>S.entityType==="visual"||S.entityType==="library").length>0&&(N==="not-analyzed"||N==="out-of-date");return n(cr,{filePath:b,isExpanded:C,onToggle:()=>u(b),fileStatus:x,simulationPreviews:n(dr,{entities:w,maxPreviews:3}),entityCount:w.length,state:N,lastModified:M,actionButton:v?n("button",{onClick:S=>{S.stopPropagation(),w.filter(I=>(I.entityType==="visual"||I.entityType==="library")&&!i(I.sha)&&!l(I.sha)).forEach(I=>h(I))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze"}):void 0,children:w.map(S=>n(ur,{entity:S,isBeingAnalyzed:i(S.sha),isQueued:l(S.sha),onGenerateSimulation:h},S.sha))},b)})})]}):c("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 Branch Changes"}),c("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:["This branch is up to date with ",a,"."]})]})]})}const Rm=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function jm({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const a=t.get("filePath"),o=t.get("diffType"),s=t.get("baseBranch"),i=t.get("currentBranch"),l=t.get("entitySha");let d;return o==="branch"?d=Gt(a,s,i):d=od(a),$({...d,entitySha:l})}return $({error:"Unknown action"},{status:400})}async function Dm({request:e,context:t}){try{const a=new URL(e.url).searchParams.get("compare"),o=t.analysisQueue,s=o?o.getState():{paused:!1,jobs:[]},[i,l,d]=await Promise.all([Tt(),st(),ke()]),u=Ba(),m=ed(),h=td(),p=nd(),f=a||h;let g=[];return m&&m!==f&&(g=Ua(f,m)),$({entities:i||[],gitStatus:u,currentBranch:m,defaultBranch:h,allBranches:p,baseBranch:f,branchDiff:g,currentCommit:l,projectSlug:d,queueState:s})}catch(r){return console.error("Failed to load git data:",r),$({entities:[],gitStatus:[],currentBranch:null,defaultBranch:"main",allBranches:[],baseBranch:"main",branchDiff:[],currentCommit:null,projectSlug:null,queueState:{paused:!1,jobs:[]},error:"Failed to load git data"})}}const $m=je(function(){const{entities:t,gitStatus:r,currentBranch:a,defaultBranch:o,allBranches:s,baseBranch:i,branchDiff:l,currentCommit:d,projectSlug:u,queueState:m}=Le();nt({source:"git-page"});const[h,p]=Fn(),[f,g]=A("uncommitted"),[y,b]=A(null),[x,w]=A("desc"),C=h.get("expanded")==="true",N=()=>{w(re=>re==="desc"?"asc":"desc")},M=we(),E=M.data;J(()=>{f==="branch"&&a&&i&&a!==i&&M.state==="idle"&&!E&&M.load(`/api/branch-entity-diff?base=${encodeURIComponent(i)}&compare=${encodeURIComponent(a)}`)},[f,a,i,M,E]);const v=Z(()=>{const re=Qa(r,t);return Array.from(re.entries()).sort((ge,pe)=>ge[0].localeCompare(pe[0]))},[r,t]),S=Z(()=>{const re=pm(l,t,E);return Array.from(re.entries()).sort((ge,pe)=>ge[0].localeCompare(pe[0]))},[l,t,E]),I=Z(()=>fm(r,t),[r,t]),P=Z(()=>v.map(([re])=>re),[v]),T=Z(()=>S.map(([re])=>re),[S]),{expandedUncommitted:R,expandedBranch:O,setExpandedUncommitted:k,setExpandedBranch:j,toggleFile:D,expandAllUncommitted:Y,collapseAllUncommitted:te,expandAllBranch:ne,collapseAllBranch:F}=_m(C,P,T),{diffView:H,diffContent:_,isLoading:B,handleShowFileDiff:U,handleCloseDiff:V}=Pm(i,a,f),ee=d?.metadata?.currentRun,ye=new Set(ee?.currentEntityShas||[]),Q=new Set(m.jobs.flatMap(re=>re.entityShas||[])),L=new Set(m.currentlyExecuting?.entityShas||[]),{isAnalyzing:ae,handleGenerateSimulation:me,handleGenerateAllSimulations:vt,isEntityBeingAnalyzed:xn}=Xa(ee?.currentEntityShas),bn=re=>Q.has(re)||L.has(re),vn=re=>{re===o?h.delete("compare"):h.set("compare",re),p(h)},mr=()=>{const ge=(f==="uncommitted"?v.flatMap(([pe,Te])=>Te.editedEntities):S.flatMap(([pe,Te])=>Te.entities)).filter(pe=>!ye.has(pe.sha)&&!Q.has(pe.sha)&&!L.has(pe.sha));vt(ge)},Je=v.length,qe=S.length,Rt=f==="uncommitted"?Je:qe,Oe=(f==="uncommitted"?v.flatMap(([re,ge])=>ge.editedEntities):S.flatMap(([re,ge])=>ge.entities)).filter(re=>re.entityType==="visual"||re.entityType==="library"),lt=Oe.length>0&&Oe.every(re=>ye.has(re.sha)),Dt=Oe.length>0&&!lt&&Oe.every(re=>Q.has(re.sha)||L.has(re.sha)),Ke=ae||lt||Dt,$t=lt?"Analyzing...":Dt?"Queued...":ae?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-12 py-6",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-bold text-gray-900 m-0 mb-2",children:"Git Changes"}),n("div",{className:"flex items-center gap-4 text-sm text-gray-600",children:a&&c(se,{children:[n("span",{className:"text-xs",children:"Branch:"}),s.length>0?n("select",{value:a,onChange:re=>vn(re.target.value),className:"text-gray-900 font-medium px-2 py-1 border border-gray-300 rounded text-sm hover:border-gray-400 focus:outline-none focus:border-blue-500",style:{paddingRight:"26px",backgroundPosition:"right 6px center",backgroundRepeat:"no-repeat",backgroundSize:"16px",appearance:"none",backgroundImage:`url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e")`},children:s.map(re=>c("option",{value:re,children:[re," ",re===o?"(default)":""]},re))}):n("span",{className:"text-gray-900 font-medium",children:a})]})})]}),c("div",{className:"relative",children:[c("div",{className:"flex items-center justify-between",children:[n(km,{activeTab:f,onTabChange:g,uncommittedCount:Je,branchCount:qe}),Rt>0&&c("div",{className:"flex gap-3 self-center -translate-y-1.5",children:[n("button",{onClick:f==="uncommitted"?Y:ne,className:"px-3 py-1.5 text-xs font-['IBM_Plex_Sans'] font-medium text-[#005c75] hover:text-[#004a5e] hover:bg-gray-100 rounded transition-colors cursor-pointer",children:"Expand All"}),n("button",{onClick:f==="uncommitted"?te:F,className:"px-3 py-1.5 text-xs font-['IBM_Plex_Sans'] font-medium text-[#005c75] hover:text-[#004a5e] hover:bg-gray-100 rounded transition-colors cursor-pointer",children:"Collapse All"}),n("button",{onClick:mr,disabled:Ke,className:"px-4 py-1.5 bg-[#005c75] text-white rounded text-xs font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed",title:Ke?$t:`Analyze all ${f} entities`,children:$t})]})]}),n("div",{className:"border-b border-gray-200 mb-6"})]}),c("div",{className:"overflow-hidden",children:[f==="uncommitted"&&n(Tm,{files:v,entityImpactMap:I,expandedFiles:R,isEntityBeingAnalyzed:xn,isEntityQueued:bn,projectSlug:u,baseBranch:i,currentBranch:a,sortOrder:x,onToggleFile:re=>D(re,R,k),onShowFileDiff:U,onGenerateSimulation:me,onSortChange:N}),f==="branch"&&a&&n(Im,{files:S,currentBranch:a,defaultBranch:o,baseBranch:i,allBranches:s,expandedFiles:O,isEntityBeingAnalyzed:xn,isEntityQueued:bn,sortOrder:x,onToggleFile:re=>D(re,O,j),onBranchChange:vn,onGenerateSimulation:me,onSortChange:N})]}),H&&n(Mm,{diffView:H,diffContent:_,isLoading:B,entities:t,onClose:V}),y&&u&&n(gt,{projectSlug:u,onClose:()=>b(null)})]})})}),Lm=Object.freeze(Object.defineProperty({__proto__:null,action:jm,default:$m,loader:Dm,meta:Rm},Symbol.toStringTag,{value:"Module"})),Eh={entry:{module:"/assets/entry.client-B9tSboXM.js",imports:["/assets/chunk-WWGJGFF6-CgXbbZRx.js","/assets/index-_LjBsTxX.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,hasErrorBoundary:!1,module:"/assets/root-CHHYHuzL.js",imports:["/assets/chunk-WWGJGFF6-CgXbbZRx.js","/assets/index-_LjBsTxX.js","/assets/ReportIssueModal-CVZ0H4BL.js","/assets/useReportContext-CANr3QJ5.js","/assets/loader-circle-D_EGChhq.js","/assets/createLucideIcon-BBYuR56H.js","/assets/useToast-Bbf4Hokd.js","/assets/useLastLogLine-Blr5oZDE.js","/assets/LogViewer-JkfQ-VaI.js","/assets/EntityTypeIcon-Catz6XEN.js","/assets/TruncatedFilePath-C06nsHKY.js","/assets/chevron-down-DwYjrK_h.js","/assets/circle-check-B2oHQ-zo.js","/assets/triangle-alert-BthANBVv.js"],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,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-eW5z9AyZ.js",imports:["/assets/chunk-WWGJGFF6-CgXbbZRx.js","/assets/InteractivePreview-TlHocYno.js","/assets/useLastLogLine-Blr5oZDE.js","/assets/index-_LjBsTxX.js"],css:["/assets/InteractivePreview-CMKNK2uU.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,hasErrorBoundary:!1,module:"/assets/entity._sha_.create-scenario-Bj5GHkhb.js",imports:["/assets/chunk-WWGJGFF6-CgXbbZRx.js","/assets/InteractivePreview-TlHocYno.js","/assets/useLastLogLine-Blr5oZDE.js","/assets/index-_LjBsTxX.js"],css:["/assets/InteractivePreview-CMKNK2uU.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,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.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,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.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,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,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.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,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.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,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.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,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,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,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.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,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.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,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.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,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-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,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.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,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,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-CLMa2sgx.js",imports:["/assets/chunk-WWGJGFF6-CgXbbZRx.js","/assets/LogViewer-JkfQ-VaI.js","/assets/useLastLogLine-Blr5oZDE.js","/assets/useReportContext-CANr3QJ5.js","/assets/loader-circle-D_EGChhq.js","/assets/EntityTypeIcon-Catz6XEN.js","/assets/EntityTypeBadge-kykTbcnD.js","/assets/createLucideIcon-BBYuR56H.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,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.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,hasErrorBoundary:!1,module:"/assets/api.recapture-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,hasErrorBoundary:!1,module:"/assets/entity._sha._-CYqBrC9s.js",imports:["/assets/chunk-WWGJGFF6-CgXbbZRx.js","/assets/useLastLogLine-Blr5oZDE.js","/assets/InteractivePreview-TlHocYno.js","/assets/SafeScreenshot-BrMAP1nP.js","/assets/LibraryFunctionPreview-CVMmGuIc.js","/assets/createLucideIcon-BBYuR56H.js","/assets/ScenarioViewer-CJhE4cCv.js","/assets/EntityTypeIcon-Catz6XEN.js","/assets/LogViewer-JkfQ-VaI.js","/assets/useReportContext-CANr3QJ5.js","/assets/index-_LjBsTxX.js","/assets/ReportIssueModal-CVZ0H4BL.js","/assets/circle-check-B2oHQ-zo.js","/assets/triangle-alert-BthANBVv.js"],css:["/assets/InteractivePreview-CMKNK2uU.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,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,hasErrorBoundary:!1,module:"/assets/simulations-gv3H7JV7.js",imports:["/assets/chunk-WWGJGFF6-CgXbbZRx.js","/assets/useReportContext-CANr3QJ5.js","/assets/SafeScreenshot-BrMAP1nP.js","/assets/EntityTypeIcon-Catz6XEN.js","/assets/fileTableUtils-CmO-EZAB.js","/assets/chevron-down-DwYjrK_h.js","/assets/search-DY8yoDpH.js","/assets/loader-circle-D_EGChhq.js","/assets/createLucideIcon-BBYuR56H.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,hasErrorBoundary:!1,module:"/assets/api.events-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:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!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,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,hasErrorBoundary:!1,module:"/assets/dev.empty-CT0Q5lVu.js",imports:["/assets/chunk-WWGJGFF6-CgXbbZRx.js","/assets/ScenarioViewer-CJhE4cCv.js","/assets/InteractivePreview-TlHocYno.js","/assets/LogViewer-JkfQ-VaI.js","/assets/SafeScreenshot-BrMAP1nP.js","/assets/useLastLogLine-Blr5oZDE.js","/assets/ReportIssueModal-CVZ0H4BL.js","/assets/createLucideIcon-BBYuR56H.js","/assets/circle-check-B2oHQ-zo.js","/assets/triangle-alert-BthANBVv.js","/assets/index-_LjBsTxX.js"],css:["/assets/InteractivePreview-CMKNK2uU.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,hasErrorBoundary:!1,module:"/assets/settings-BT6wVHd5.js",imports:["/assets/chunk-WWGJGFF6-CgXbbZRx.js","/assets/useReportContext-CANr3QJ5.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,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,hasErrorBoundary:!1,module:"/assets/_index-faVIcr_i.js",imports:["/assets/chunk-WWGJGFF6-CgXbbZRx.js","/assets/useLastLogLine-Blr5oZDE.js","/assets/useToast-Bbf4Hokd.js","/assets/useReportContext-CANr3QJ5.js","/assets/LogViewer-JkfQ-VaI.js","/assets/EntityTypeIcon-Catz6XEN.js","/assets/SafeScreenshot-BrMAP1nP.js","/assets/createLucideIcon-BBYuR56H.js","/assets/circle-check-B2oHQ-zo.js","/assets/loader-circle-D_EGChhq.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,hasErrorBoundary:!1,module:"/assets/files-DLinnTOx.js",imports:["/assets/chunk-WWGJGFF6-CgXbbZRx.js","/assets/useReportContext-CANr3QJ5.js","/assets/EntityItem-D4htqD-x.js","/assets/fileTableUtils-CmO-EZAB.js","/assets/chevron-down-DwYjrK_h.js","/assets/search-DY8yoDpH.js","/assets/useToast-Bbf4Hokd.js","/assets/TruncatedFilePath-C06nsHKY.js","/assets/SafeScreenshot-BrMAP1nP.js","/assets/LibraryFunctionPreview-CVMmGuIc.js","/assets/triangle-alert-BthANBVv.js","/assets/createLucideIcon-BBYuR56H.js","/assets/EntityTypeIcon-Catz6XEN.js","/assets/EntityTypeBadge-kykTbcnD.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,hasErrorBoundary:!1,module:"/assets/git-CIxwBQvb.js",imports:["/assets/chunk-WWGJGFF6-CgXbbZRx.js","/assets/useReportContext-CANr3QJ5.js","/assets/EntityItem-D4htqD-x.js","/assets/LogViewer-JkfQ-VaI.js","/assets/fileTableUtils-CmO-EZAB.js","/assets/useToast-Bbf4Hokd.js","/assets/TruncatedFilePath-C06nsHKY.js","/assets/SafeScreenshot-BrMAP1nP.js","/assets/LibraryFunctionPreview-CVMmGuIc.js","/assets/triangle-alert-BthANBVv.js","/assets/createLucideIcon-BBYuR56H.js","/assets/EntityTypeIcon-Catz6XEN.js","/assets/EntityTypeBadge-kykTbcnD.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-ca438c41.js",version:"ca438c41",sri:void 0},Ah="build/client",_h="/",Ph={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},Mh=!0,kh=!1,Th=[],Ih={mode:"lazy",manifestPath:"/__manifest"},Rh="/",jh={module:hs},Dh={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:_l},"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:Kl},"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:ec},"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:qc},"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:Jc},"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:hd},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:fd},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:bd},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:Cd},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:Ed},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:Pd},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:kd},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:Od},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:Bd},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:Hd},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:Gd},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:Jd},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:ru},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:su},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:lu},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:Du},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:Ou},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:Hu},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:Gu},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:Qu},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:em},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:rm},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:dm},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:mm},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:vm},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:Am},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:Lm}};export{wi as A,bi as B,fe as C,qs as D,Gs as E,ot as F,Rs as G,ua as H,$s as I,ma as J,Ys as K,zs as L,Ah as M,_h as N,Ph as O,Ts as P,Mh as Q,kh as R,Xn as S,Th as T,Ih as U,Rh as V,jh as W,Dh as X,Eh as Y,As as a,ht as b,at as c,Ue as d,Mt as e,Vn as f,Qn as g,da as h,Ss as i,ni as j,ri as k,Et as l,We as m,fa as n,ui as o,Qt as p,pt as q,ga as r,ya as s,gi as t,ut as u,xa as v,kt as w,yi as x,_r as y,Ni as z};
|