@codeyam/codeyam-cli 0.1.0-staging.323686 → 0.1.0-staging.483fdc2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/analyzer-template/.build-info.json +7 -7
- package/analyzer-template/log.txt +3 -3
- package/analyzer-template/package.json +2 -2
- package/analyzer-template/packages/ai/index.ts +6 -1
- package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +39 -17
- package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +67 -9
- package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +308 -50
- package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +15 -6
- package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +664 -242
- 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 +20 -1
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +35 -13
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.ts +160 -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 +289 -83
- package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +269 -1
- package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +9 -5
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +11 -3
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +1 -1
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +297 -7
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.ts +1 -1
- package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +90 -96
- package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +10 -7
- package/analyzer-template/packages/ai/src/lib/resolvePathToControllable.ts +25 -13
- package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +4 -3
- package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +65 -59
- package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +113 -26
- 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 +20 -6
- package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +14 -4
- package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +4 -2
- package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +0 -3
- package/analyzer-template/packages/analyze/src/lib/files/analyzeRemixRoute.ts +4 -5
- package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +14 -12
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +57 -13
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +29 -0
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +35 -4
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +117 -9
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +199 -17
- 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/utils/getFileByPath.ts +19 -0
- package/analyzer-template/packages/aws/package.json +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +5 -5
- 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/package.json +1 -1
- package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +6 -5
- package/analyzer-template/packages/types/src/types/ScopeAnalysis.ts +6 -1
- package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +5 -5
- 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/project/constructMockCode.ts +54 -9
- package/analyzer-template/project/writeMockDataTsx.ts +73 -2
- package/background/src/lib/virtualized/project/constructMockCode.js +45 -3
- package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
- package/background/src/lib/virtualized/project/writeMockDataTsx.js +71 -2
- package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
- package/codeyam-cli/scripts/apply-setup.js +146 -0
- package/codeyam-cli/scripts/apply-setup.js.map +1 -1
- package/codeyam-cli/src/commands/debug.js +7 -5
- package/codeyam-cli/src/commands/debug.js.map +1 -1
- package/codeyam-cli/src/utils/install-skills.js +22 -0
- package/codeyam-cli/src/utils/install-skills.js.map +1 -1
- package/codeyam-cli/src/utils/reviewedRules.js +92 -0
- package/codeyam-cli/src/utils/reviewedRules.js.map +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/globals-CX9f-5xM.css +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{manifest-7522edd4.js → manifest-bba56ec1.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/memory-DuTFSyJ2.js +92 -0
- package/codeyam-cli/src/webserver/build/client/assets/{root-eVAaavTS.js → root-DTfSQARG.js} +6 -6
- package/codeyam-cli/src/webserver/build/server/assets/{index-DVzYx8PN.js → index-TD1f-DHV.js} +1 -1
- package/codeyam-cli/src/webserver/build/server/assets/server-build-BQ-1XyEa.js +258 -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/templates/codeyam:memory.md +174 -233
- package/codeyam-cli/templates/codeyam:new-rule.md +41 -2
- package/codeyam-cli/templates/rule-reflection-hook.py +161 -0
- package/codeyam-cli/templates/rules-instructions.md +126 -0
- package/package.json +1 -1
- package/packages/ai/index.js +2 -1
- package/packages/ai/index.js.map +1 -1
- package/packages/ai/src/lib/analyzeScope.js +29 -12
- package/packages/ai/src/lib/analyzeScope.js.map +1 -1
- package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +54 -8
- package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
- package/packages/ai/src/lib/astScopes/processExpression.js +239 -43
- package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +503 -165
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.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 +22 -1
- package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +34 -9
- package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js +159 -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 +237 -73
- package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
- package/packages/ai/src/lib/generateEntityScenarioData.js +195 -1
- package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
- package/packages/ai/src/lib/generateEntityScenarios.js +7 -1
- package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
- package/packages/ai/src/lib/generateExecutionFlows.js +10 -2
- package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -1
- package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +209 -3
- package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -1
- package/packages/ai/src/lib/mergeStatements.js +70 -51
- package/packages/ai/src/lib/mergeStatements.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +10 -4
- package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
- package/packages/ai/src/lib/resolvePathToControllable.js +24 -14
- package/packages/ai/src/lib/resolvePathToControllable.js.map +1 -1
- package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/FileAnalyzer.js +60 -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/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 +13 -5
- package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +14 -4
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.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 +0 -3
- package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.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/getImportedExports.js +11 -7
- package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +52 -10
- package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +25 -8
- package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +34 -4
- package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +56 -8
- package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +168 -9
- package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.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/utils/getFileByPath.js +12 -0
- package/packages/analyze/src/lib/utils/getFileByPath.js.map +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/globals-D3yhhV8x.css +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/memory-yxFcrxBX.js +0 -92
- package/codeyam-cli/src/webserver/build/server/assets/server-build-4Cr0uToj.js +0 -257
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
var zs=Object.defineProperty;var wa=e=>{throw TypeError(e)};var Ys=(e,r,n)=>r in e?zs(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n;var sr=(e,r,n)=>Ys(e,typeof r!="symbol"?r+"":r,n),Bs=(e,r,n)=>r.has(e)||wa("Cannot "+n);var va=(e,r,n)=>(Bs(e,r,"read from private field"),n?n.call(e):r.get(e)),Ca=(e,r,n)=>r.has(e)?wa("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(e):r.set(e,n);import{jsx as t,jsxs as l,Fragment as ce}from"react/jsx-runtime";import{PassThrough as Us}from"node:stream";import{createReadableStreamFromReadable as Ws}from"@react-router/node";import{ServerRouter as Hs,useFetcher as Ae,useLocation as Pr,useNavigate as _t,Link as oe,UNSAFE_withComponentProps as Oe,Meta as qs,Links as Js,ScrollRestoration as Gs,Scripts as Vs,useLoaderData as We,useRevalidator as rt,Outlet as Qs,data as J,useSearchParams as Qt,useParams as io,useActionData as Ks}from"react-router";import{isbot as Zs}from"isbot";import{renderToPipeableStream as Xs}from"react-dom/server";import{useState as P,useEffect as te,useCallback as se,createContext as Cn,useContext as Mr,useRef as Ee,useMemo as ne}from"react";import{Settings as Na,CheckCircle2 as Nn,Bug as lo,AlertTriangle as mn,Check as co,Copy as Sn,Loader2 as Ze,HomeIcon as ei,GitCommitIcon as Sa,File as ti,RefreshCw as ri,BookOpen as ni,SettingsIcon as ai,PanelsTopLeftIcon as oi,ComponentIcon as si,FileText as Ea,Code as Aa,Box as ii,List as li,BarChart3 as ci,Tag as di,Image as Ht,Code2 as uo,Activity as Vr,ChevronDown as qt,CircleEqual as ui,Pause as hi,ListTodo as mi,PauseCircle as pi,FileCode as ho,GripVertical as fi,Ban as gi,CheckCircle as yi,Search as En,FolderOpen as xi,CodeXml as bi,Zap as wi,Terminal as mo,Pencil as vi,Trash2 as Ci,X as po,ChevronRight as An,Folder as fo,ArrowLeft as Ni,Plus as ka,FolderTree as Si,Filter as Ei,ChevronsUpDown as go,ChevronsDownUp as yo}from"lucide-react";import"fetch-retry";import Ai from"better-sqlite3";import{Pool as ki}from"pg";import*as K from"fs";import Nt,{existsSync as Pi}from"fs";import*as ee from"path";import ue from"path";import{OperationNodeTransformer as Mi,Kysely as xo,ParseJSONResultsPlugin as _i,SqliteDialect as Ti,PostgresDialect as Ii,sql as Qe}from"kysely";import*as $i from"kysely/helpers/sqlite";import*as ji from"kysely/helpers/postgres";import Me from"typescript";import*as Ie from"fs/promises";import pe,{writeFile as Ri,readFile as Di}from"fs/promises";import*as Li from"os";import pn from"os";import Fi from"prompts";import gr from"chalk";import*as Oi from"crypto";import kn,{randomUUID as Kt}from"crypto";import{execSync as _e,spawn as _r,exec as Pn}from"child_process";import{fileURLToPath as Mn}from"url";import{promisify as _n}from"util";import zi from"dotenv";import Yi,{EventEmitter as Bi}from"events";import{v4 as Ui}from"uuid";import Wi from"openai";import Hi from"p-queue";import Pa from"p-retry";import{DynamoDBClient as Tr,PutItemCommand as qi}from"@aws-sdk/client-dynamodb";import{LRUCache as Tn}from"lru-cache";import"pluralize";import"piscina";import Ji from"json5";import{marshall as Gi}from"@aws-sdk/util-dynamodb";import Vi from"v8";import{Prism as Qi}from"react-syntax-highlighter";import{vscDarkPlus as Ki}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as Zi}from"node:crypto";import{minimatch as bo}from"minimatch";import Xi from"react-markdown";import el from"remark-gfm";import tl from"react-diff-viewer-continued";const wo=5e3;function rl(e,r,n,a,o){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:r,headers:n}):new Promise((s,i)=>{let c=!1,d=e.headers.get("user-agent"),h=d&&Zs(d)||a.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>p(),wo+1e3);const{pipe:m,abort:p}=Xs(t(Hs,{context:a,url:e.url}),{[h](){c=!0;const f=new Us({final(g){clearTimeout(u),u=void 0,g()}}),y=Ws(f);n.set("Content-Type","text/html"),m(f),s(new Response(y,{headers:n,status:r}))},onShellError(f){i(f)},onError(f){r=500,c&&console.error(f)}})})}const nl=Object.freeze(Object.defineProperty({__proto__:null,default:rl,streamTimeout:wo},Symbol.toStringTag,{value:"Module"}));function al({id:e,selected:r,onClick:n,icon:a,name:o}){const[s,i]=P(!1);te(()=>{i(!0)},[]);const c=se(()=>{n==null||n(e)},[n,e]);return l("button",{className:`
|
|
2
|
+
w-full px-1.5 py-2 cursor-pointer focus:outline-none
|
|
3
|
+
flex flex-col items-center justify-center gap-1 transition-colors
|
|
4
|
+
${r?"text-[#CBF3FA]":"text-[#568B94] hover:text-[#CBF3FA]"}
|
|
5
|
+
`,onClick:c,children:[t("div",{className:`${r?"bg-[#CBF3FA] text-[#022A35]":""} w-9 h-9 rounded-lg flex items-center justify-center transition-colors`,children:s&&a}),t("span",{className:`text-[10px] font-normal text-center leading-tight ${r?"text-[#CBF3FA]":""}`,style:r?{color:"#CBF3FA !important"}:void 0,children:o})]})}const vo="/assets/cy-logo-cli-CCKUIm0S.svg";function ol(e){return e.scenarioName&&e.entityName?`${e.entityName} → "${e.scenarioName}"`:e.entityName?e.entityName:e.scenarioId?`Scenario: ${e.scenarioId.slice(0,8)}...`:e.entitySha?`Entity: ${e.entitySha.slice(0,8)}...`:"General feedback"}function sl({content:e,className:r=""}){const[n,a]=P(!1),o=se(()=>{navigator.clipboard.writeText(e).then(()=>{a(!0),setTimeout(()=>a(!1),2e3)}).catch(s=>{console.error("Failed to copy:",s)})},[e]);return t("button",{onClick:o,className:`cursor-pointer flex items-center gap-1 ${r}`,disabled:n,"aria-label":n?"Copied to clipboard":"Copy to clipboard",children:n?l(ce,{children:[t(co,{size:14}),"Copied"]}):l(ce,{children:[t(Sn,{size:14}),"Copy"]})})}function Co({isOpen:e,onClose:r,context:n,defaultEmail:a="",screenshotDataUrl:o}){const[s,i]=P(""),[c,d]=P(a),[h,u]=P(!1),[m,p]=P(!1),[f,y]=P(null),[g,b]=P(null),w=Ae(),x=w.state!=="idle",v=!!(n.scenarioId||n.analysisId),C=n.analysisId||n.scenarioId||"",k=()=>{const I=`/codeyam:diagnose ${C}`;return s.trim()?`${I} ${s.trim()}`:I};if(w.data&&!m&&!g){const I=w.data;I.success&&I.reportId?(p(!0),y(I.reportId)):I.error&&b(I.error)}const N=async()=>{b(null);const I=new FormData;if(I.append("issueType","other"),I.append("description",s),I.append("email",c),I.append("source",n.source),I.append("entitySha",n.entitySha||""),I.append("scenarioId",n.scenarioId||""),I.append("analysisId",n.analysisId||""),I.append("currentUrl",n.currentUrl),I.append("entityName",n.entityName||""),I.append("entityType",n.entityType||""),I.append("scenarioName",n.scenarioName||""),I.append("errorMessage",n.errorMessage||""),o)try{const R=await(await fetch(o)).blob();I.append("screenshot",R,"screenshot.jpg")}catch(j){console.error("Failed to convert screenshot:",j)}w.submit(I,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},E=()=>{i(""),u(!1),p(!1),y(null),b(null),r()},A=I=>{I.key==="Escape"&&E()};return e?t("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:A,children:l("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl max-h-[90vh] overflow-y-auto",children:[l("div",{className:"flex items-center justify-between mb-6",children:[l("div",{className:"flex items-center gap-3",children:[x?t("div",{className:"animate-spin",children:t(Na,{size:24,style:{strokeWidth:1.5}})}):m?t(Nn,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):t(lo,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),t("h2",{className:"text-xl font-semibold text-gray-900",children:m?"Report Submitted":"Report Issue"})]}),t("button",{onClick:E,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:t("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),m?l("div",{children:[l("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[t("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),l("p",{className:"text-xs text-green-700",children:["Report ID:"," ",t("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),t("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."}),t("div",{className:"flex justify-end",children:t("button",{onClick:E,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):l("div",{children:[l("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[l("div",{className:"flex items-center justify-between",children:[t("div",{className:"text-sm font-medium text-gray-900",title:`${n.source}${n.entitySha?` • Entity: ${n.entitySha}`:""}${n.scenarioId?` • Scenario: ${n.scenarioId}`:""}${n.analysisId?` • Analysis: ${n.analysisId}`:""}`,children:ol(n)}),t("button",{type:"button",onClick:()=>u(!h),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:h?"Hide":"Details"})]}),h&&l("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[l("div",{children:[t("span",{className:"text-gray-400",children:"Source:"})," ",n.source]}),l("div",{children:[t("span",{className:"text-gray-400",children:"URL:"})," ",n.currentUrl]}),n.entitySha&&l("div",{children:[t("span",{className:"text-gray-400",children:"Entity:"})," ",t("code",{className:"bg-gray-100 px-1 rounded",children:n.entitySha})]}),n.scenarioId&&l("div",{children:[t("span",{className:"text-gray-400",children:"Scenario:"})," ",t("code",{className:"bg-gray-100 px-1 rounded",children:n.scenarioId})]}),n.analysisId&&l("div",{children:[t("span",{className:"text-gray-400",children:"Analysis:"})," ",t("code",{className:"bg-gray-100 px-1 rounded",children:n.analysisId})]})]})]}),o&&l("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[t("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),t("img",{src:o,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),l("div",{className:"mb-4",children:[t("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),t("textarea",{id:"description",value:s,onChange:I=>i(I.target.value),placeholder:"Optional: Describe what you expected vs what happened...",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] resize-none"})]}),v&&l(ce,{children:[l("div",{className:"mb-4 p-4 bg-purple-50 rounded-lg border border-purple-200",children:[l("div",{className:"flex items-center gap-2 mb-2",children:[t("span",{className:"text-lg",children:"🔧"}),t("h3",{className:"text-sm font-semibold text-purple-900",children:"Diagnose & Fix (Recommended)"})]}),t("p",{className:"text-xs text-purple-700 mb-3",children:"Run this command in Claude Code to investigate the issue locally and potentially fix it. A detailed report will also be uploaded."}),l("div",{className:"relative",children:[t("div",{className:"bg-gray-800 text-gray-50 px-3 py-2.5 pr-20 rounded-md text-xs font-mono overflow-x-auto whitespace-nowrap",children:k()}),t(sl,{content:k(),className:"absolute top-1.5 right-2 px-2 py-1 bg-purple-600 text-white border-none rounded text-[11px] font-medium hover:bg-purple-700 transition-colors"})]})]}),l("div",{className:"relative my-5",children:[t("div",{className:"absolute inset-0 flex items-center",children:t("div",{className:"w-full border-t border-gray-300"})}),t("div",{className:"relative flex justify-center",children:t("span",{className:"bg-white px-3 text-xs text-gray-500 uppercase",children:"or"})})]})]}),l("div",{className:v?"opacity-75":"",children:[v&&l("div",{className:"flex items-center gap-2 mb-3",children:[t("span",{className:"text-lg",children:"📤"}),t("h3",{className:"text-sm font-semibold text-gray-700",children:"Quick Report"}),t("span",{className:"text-xs text-gray-500",children:"(won't investigate locally)"})]}),l("div",{className:"mb-4",children:[t("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),t("input",{id:"email",type:"email",value:c,onChange:I=>d(I.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]"})]}),l("div",{className:"mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[t(mn,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),l("div",{className:"text-xs text-amber-800",children:[t("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),t("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."})]})]}),x&&t("div",{className:"mb-4 text-center",children:t("p",{className:"text-sm text-gray-600",children:w.formData?"Uploading report...":"Creating archive..."})}),g&&l("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[t(mn,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),l("div",{className:"text-xs text-red-800",children:[t("p",{className:"font-medium mb-1",children:"Upload failed"}),t("p",{children:g})]})]}),l("div",{className:"flex gap-3 justify-end",children:[t("button",{onClick:E,disabled:x,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"}),t("button",{onClick:()=>void N(),disabled:x,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:x?l(ce,{children:[t("div",{className:"animate-spin",children:t(Na,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):g?"Try Again":"Submit Report"})]})]})]})]})}):null}const Ma={source:"navbar"},In=Cn(void 0);function il({children:e}){const[r,n]=P(Ma),a=se(s=>{n(s)},[]),o=se(()=>{n(Ma)},[]);return t(In.Provider,{value:{contextData:r,setContextData:a,resetContextData:o},children:e})}function mt(e){const r=Mr(In),n=Ee(r);te(()=>{if(n.current)return n.current.setContextData(e),()=>{var a;(a=n.current)==null||a.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId,e.entityName,e.entityType,e.scenarioName,e.errorMessage])}function ll(){const e=Mr(In),r=Pr();return e?{source:e.contextData.source,entitySha:e.contextData.entitySha,scenarioId:e.contextData.scenarioId,analysisId:e.contextData.analysisId,currentUrl:r.pathname,entityName:e.contextData.entityName,entityType:e.contextData.entityType,scenarioName:e.contextData.scenarioName,errorMessage:e.contextData.errorMessage}:{source:"navbar",currentUrl:r.pathname}}function cl(){var x;const e=Pr(),r=_t(),[n,a]=P(),[o,s]=P(!1),[i,c]=P(!1),[d,h]=P(null),u=Ae();te(()=>{u.state==="idle"&&!u.data&&u.load("/api/generate-report")},[u]);const m=((x=u.data)==null?void 0:x.defaultEmail)||"",p={width:"20px",height:"20px",strokeWidth:1.5},f=[{id:"dashboard",icon:t(ei,{style:p}),link:"/",name:"Dashboard"},{id:"simulations",icon:l("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:p,children:[t("path",{d:"M9 12.75V15.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),t("path",{d:"M6 15.75H12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),t("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"}),t("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"}),t("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:t(Sa,{style:p}),link:"/git",name:"Git"},{id:"files",icon:t(ti,{style:p}),link:"/files",name:"Files"},{id:"activity",icon:t(ri,{style:p}),link:"/activity",name:"Activity"},{id:"memory",icon:t(ni,{style:p}),link:"/memory",name:"Memory"},{id:"settings",icon:t(ai,{style:p}),link:"/settings",name:"Settings"},{id:"commits",icon:t(Sa,{style:p}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:t(oi,{style:p}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:t(si,{style:p}),link:"/components",name:"Components",hidden:!0}],y=se(v=>{const C=f.find(k=>k.id===v);C!=null&&C.link&&r(C.link),a(k=>k===v?void 0:v)},[f,r]);te(()=>{const v={dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],memory:["memory"],files:["files"],settings:["settings"],pages:["pages"],components:["components"]};for(const[C,k]of Object.entries(v))if(k.some(N=>N==="/"?e.pathname==="/":e.pathname.includes(N))){a(C);return}a(void 0)},[e]);const g=async()=>{c(!0);try{const{default:v}=await import("html2canvas-pro"),k=(await v(document.body)).toDataURL("image/jpeg",.8);h(k),s(!0)}catch(v){console.error("Screenshot capture failed:",v),s(!0)}finally{c(!1)}},b=()=>{s(!1),h(null)},w=ll();return l(ce,{children:[l("div",{id:"sidebar",className:"relative w-full h-screen bg-[#051C22] flex flex-col justify-between py-3",children:[l("div",{className:"w-full flex flex-col items-center",children:[t("div",{className:"py-3 mt-2 mb-4",children:t(oe,{to:"/",className:"flex items-center justify-center cursor-pointer",children:t("img",{src:vo,alt:"CodeYam",className:"h-6"})})}),f.filter(v=>!v.hidden).map(v=>t(al,{id:v.id,selected:v.id===n,onClick:y,icon:v.icon,name:v.name},`sidebar-button-${v.id}`))]}),t("div",{className:"w-full flex flex-col items-center pb-2",children:l("button",{onClick:()=>void g(),disabled:i,className:"w-full px-1.5 py-2 flex flex-col items-center justify-center gap-1 text-[#568B94] hover:text-[#CBF3FA] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait",children:[t("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center",children:i?t(Ze,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):t(lo,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),t("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:i?"Capturing...":`Report
|
|
6
|
+
Bug`})]})})]}),o&&t(Co,{isOpen:!0,onClose:b,context:w,defaultEmail:m,screenshotDataUrl:d??void 0})]})}const No=Cn(void 0);function dl({children:e}){const[r,n]=P([]),a=se((s,i="info",c=5e3)=>{const h={id:`toast-${Date.now()}-${Math.random()}`,message:s,type:i,duration:c};n(u=>[...u,h])},[]),o=se(s=>{n(i=>i.filter(c=>c.id!==s))},[]);return t(No.Provider,{value:{toasts:r,showToast:a,closeToast:o},children:e})}function $n(){const e=Mr(No);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function ul({toast:e,onClose:r}){te(()=>{const o=e.duration||5e3;if(o>0){const s=setTimeout(()=>{r(e.id)},o);return()=>clearTimeout(s)}},[e.id,e.duration,r]);const n={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return l("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:[t("span",{className:"text-2xl",children:n[e.type]}),t("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),t("button",{onClick:()=>r(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 hl({toasts:e,onClose:r}){return e.length===0?null:l("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[t("style",{children:`
|
|
7
|
+
@keyframes slideIn {
|
|
8
|
+
from {
|
|
9
|
+
transform: translateX(400px);
|
|
10
|
+
opacity: 0;
|
|
11
|
+
}
|
|
12
|
+
to {
|
|
13
|
+
transform: translateX(0);
|
|
14
|
+
opacity: 1;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
`}),e.map(n=>t(ul,{toast:n,onClose:r},n.id))]})}function pt(e,r){const[n,a]=P(""),[o,s]=P(!1),[i,c]=P(null),[d,h]=P(!1);te(()=>{r&&(h(!1),s(!1),c(null))},[r]),te(()=>{if(!e||!r){r||a("");return}const m=async()=>{try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const g=(await f.text()).trim().split(`
|
|
18
|
+
`).filter(x=>x.length>0);if(g.length<3){s(!1),h(!1),c(null),a("");return}const b=g.filter(x=>x.includes("CodeYam Log Level 1"));if(b.length>0){const x=b[b.length-1];a(x.replace(/.*CodeYam Log Level 1: /,""))}const w=g.find(x=>x.includes("$$INTERACTIVE_SERVER_URL$$:"));if(w){const x=w.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();c(x),h(!0)}g.some(x=>x.includes("CodeYam: Exiting start.js"))&&s(!0)}}catch{}};m().catch(()=>{});const p=setInterval(()=>{m().catch(()=>{})},2e3);return()=>clearInterval(p)},[e,r]);const u=se(()=>{a(""),s(!1),c(null),h(!1)},[]);return{lastLine:n,interactiveUrl:i,isCompleted:o,resetLogs:u}}function dt({projectSlug:e,onClose:r}){const[n,a]=P("Loading logs..."),[o,s]=P(!0),[i,c]=P(!0),[d,h]=P("all"),u=Ee(null);return te(()=>{const m=async()=>{try{const p=await fetch(`/api/logs/${e}`);if(p.ok){const f=await p.text();if(d==="all")a(f);else{const y=f.trim().split(`
|
|
19
|
+
`).filter(g=>{if(g.length===0)return!1;const b=g.match(/^.*CodeYam Log Level (\d+):/);return!!b&&Number(b[1])<=d});a(y.map(g=>g.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
|
|
20
|
+
`))}i&&u.current&&setTimeout(()=>{var y;(y=u.current)==null||y.scrollTo({top:u.current.scrollHeight,behavior:"smooth"})},100)}else a(`Error: ${p.status} - ${await p.text()}`)}catch(p){a(`Error fetching logs: ${p.message}`)}};if(m().catch(()=>{}),o){const p=setInterval(()=>{m().catch(()=>{})},2e3);return()=>clearInterval(p)}},[e,o,i,d]),te(()=>{const m=p=>{p.key==="Escape"&&r()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[r]),t("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:r,children:l("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:m=>m.stopPropagation(),children:[l("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[l("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),l("div",{className:"flex items-center gap-4",children:[l("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[t("span",{children:"Log Level:"}),l("select",{value:d,onChange:m=>h(m.target.value==="all"?"all":Number(m.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:[t("option",{value:"1",children:"1"}),t("option",{value:"2",children:"2"}),t("option",{value:"3",children:"3"}),t("option",{value:"4",children:"4"}),t("option",{value:"all",children:"All"})]})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[t("input",{type:"checkbox",checked:o,onChange:m=>s(m.target.checked),className:"cursor-pointer"}),t("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[t("input",{type:"checkbox",checked:i,onChange:m=>c(m.target.checked),className:"cursor-pointer"}),t("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),t("button",{onClick:r,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:"✕"})]})]}),t("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:u,children:n})]})})}function Ue({type:e,size:r="default"}){const n={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"}},a=n[e]||n.other,o=r==="large"?18:14,s=r==="large"?32:18,i=()=>{switch(e){case"library":return t(uo,{size:o,color:a.iconColor});case"visual":return t(Ht,{size:o,color:a.iconColor});case"type":return t(di,{size:o,color:a.iconColor});case"data":return t(ci,{size:o,color:a.iconColor});case"index":return t(li,{size:o,color:a.iconColor});case"functionCall":return t(Aa,{size:o,color:a.iconColor});case"class":return t(ii,{size:o,color:a.iconColor});case"method":return t(Aa,{size:o,color:a.iconColor});case"other":return t(Ea,{size:o,color:a.iconColor});default:return t(Ea,{size:o,color:a.iconColor})}};return t("span",{className:`flex items-center justify-center rounded ${a.bgColor}`,style:{width:`${s}px`,height:`${s}px`},children:i()})}function So({filePath:e,maxLength:r=60,className:n,style:a}){const s=((c,d)=>{if(c.length<=d)return c;const h="...",u=d-h.length,m=Math.ceil(u*.4),p=Math.floor(u*.6),f=c.slice(0,m),y=c.slice(-p),g=f.lastIndexOf("/"),b=y.indexOf("/"),w=g>m*.5?f.slice(0,g+1):f,x=b!==-1&&b<p*.5?y.slice(b):y;return`${w}${h}${x}`})(e,r),i=s!==e;return t("span",{className:n||"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 Qr({entity:e,nameSize:r="11px",pathSize:n="10px",pathMaxLength:a=50,showScenarioCount:o=!1,scenarioCount:s=0,additionalContent:i}){return l("div",{className:"flex flex-col gap-1",children:[l("div",{className:"flex items-center gap-1",children:[t(Ue,{type:e.entityType||"other"}),l(oe,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:r,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,o&&s>0&&` (${s})`]}),t(So,{filePath:e.filePath,maxLength:a,style:{fontSize:n,color:"#8E8E8E"}})]}),i]})}const Kr={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function ml({currentRun:e,projectSlug:r,currentEntities:n=[],isAnalysisStarting:a=!1,queuedJobCount:o=0,queueJobs:s=[],currentlyExecuting:i=null,historicalRuns:c=[]}){var U,B,D;const[d,h]=P(!1),[u,m]=P(!1),[p,f]=P(null),[y,g]=P(new Set),[b,w]=P(new Set),[x,v]=P(!1),C=!!i||s.length>0,k=!!i,N=(i==null?void 0:i.entities)||n,E=!!(e!=null&&e.analysisCompletedAt),A=(e==null?void 0:e.readyToBeCaptured)??0,I=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||E&&(A===0||I>=A);const j=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,R=C,{lastLine:M}=pt(r,R),T=k||s.length>0,$=new Set(((U=i==null?void 0:i.entities)==null?void 0:U.map(L=>L.sha))||[]),z=c.filter(L=>!(L.currentEntityShas||[]).some(S=>$.has(S))),G=(()=>{const _=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&j){const S=e.analysisCompletedAt||e.createdAt;if(new Date(S).getTime()>_)return!0}if(z.length>0){const S=z[0],F=S.analysisCompletedAt||S.archivedAt||S.createdAt;if(F&&new Date(F).getTime()>_)return!0}return!1})();return te(()=>{const L=(i==null?void 0:i.id)||null;C&&!u&&L!==p&&m(!0),!C&&p!==null&&f(null)},[C,i==null?void 0:i.id,u,p]),l(ce,{children:[l("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${u?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!u&&l("div",{onClick:()=>{m(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[T?t(Ze,{size:16,className:"animate-spin",style:{color:"#005C75"}}):t("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:t(Vr,{size:16,style:{color:"#005C75"}})}),t("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:T?"Analyzing...":"Activity: No Activity Yet"}),T&&t("button",{onClick:L=>{L.stopPropagation(),h(!0)},className:"ml-auto px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),u&&l("div",{children:[l("div",{className:"flex items-center justify-between px-3 py-2",children:[l("div",{className:"flex items-center gap-2",children:[T?t(Ze,{size:16,className:"animate-spin",style:{color:"#005C75"}}):t("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:t(Vr,{size:16,style:{color:"#005C75"}})}),t("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:T?"Analyzing...":"Activity"})]}),l("div",{className:"flex items-center gap-2",children:[t("button",{onClick:()=>h(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),t("button",{onClick:()=>{m(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:t(qt,{size:16,style:{color:"#646464"}})})]})]}),t("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),l("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[T&&i&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[t(Vr,{size:12,style:{color:"#005C75"}}),t("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Current Activity"})]}),t("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:N.length>0?l("div",{className:"space-y-1.5",children:[(x?N:N.slice(0,3)).map(L=>t(Qr,{entity:L,nameSize:"11px",pathSize:"10px",pathMaxLength:150},L.sha)),N.length>3&&t("button",{onClick:()=>v(L=>!L),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Kr,"aria-label":x?"Show fewer entities":`Show ${N.length-3} more entities`,children:x?"Show less":`+${N.length-3} more`}),M&&t("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:M})]}):l("div",{children:[i.entityNames&&i.entityNames.length>0?l("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((L,_)=>t("div",{style:{fontSize:"11px",color:"#343434"},children:L},_)),i.entityNames.length>5&&l("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):l("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((B=i.entityShas)==null?void 0:B.length)||0," ",((D=i.entityShas)==null?void 0:D.length)===1?"entity":"entities","..."]}),M&&t("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:M})]})})]}),s.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[t(ui,{size:12,style:{color:"#005C75"}}),t("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Queued Activity"})]}),t("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:s.map(L=>{var F,O;const _=y.has(L.id),S=_?L.entities:L.entities.slice(0,3);return t("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:L.entities.length>0?l("div",{className:"space-y-1.5",children:[S.map(H=>t(Qr,{entity:H,nameSize:"10px",pathSize:"9px",pathMaxLength:120},H.sha)),L.entities.length>3&&t("button",{onClick:()=>{g(H=>{const ae=new Set(H);return ae.has(L.id)?ae.delete(L.id):ae.add(L.id),ae})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Kr,"aria-label":_?"Show fewer entities":`Show ${L.entities.length-3} more entities`,children:_?"Show less":`+${L.entities.length-3} more`})]}):l("div",{style:{fontSize:"10px",color:"#343434"},children:[L.type==="analysis"&&t(ce,{children:L.entityNames&&L.entityNames.length>0?l("div",{className:"space-y-0.5",children:[L.entityNames.slice(0,5).map((H,ae)=>t("div",{children:H},ae)),L.entityNames.length>5&&l("div",{className:"italic",children:["+",L.entityNames.length-5," more"]})]}):`Analyzing ${((F=L.entityShas)==null?void 0:F.length)||0} ${((O=L.entityShas)==null?void 0:O.length)===1?"entity":"entities"}`}),L.type==="recapture"&&"Recapturing scenario",L.type==="debug-setup"&&"Setting up debug environment"]})},L.id)})})]}),G&&z.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[t(Nn,{size:12,style:{color:"#005C75"}}),t("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Recently Completed"})]}),t("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:z.slice(0,3).map((L,_)=>{const S=L.entities||[],F=L.analysisCompletedAt||L.archivedAt||L.createdAt||"",O=(()=>{if(!F)return"";const Y=Date.now()-new Date(F).getTime(),W=Math.floor(Y/6e4),Q=Math.floor(Y/36e5);return Q>0?`${Q}h ago`:W>0?`${W}m ago`:"just now"})(),H=b.has(_),V=(H?S:S.slice(0,3)).map(Y=>{var W,Q,q;return{...Y,scenarioCount:((q=(Q=(W=Y.analyses)==null?void 0:W[0])==null?void 0:Q.scenarios)==null?void 0:q.length)||0}});return t("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:S.length>0&&l("div",{className:"space-y-1.5",children:[V.map((Y,W)=>l("div",{className:"flex items-start justify-between gap-2",children:[t("div",{className:"flex-1 min-w-0",children:t(Qr,{entity:Y,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:Y.scenarioCount})}),W===0&&O&&t("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:O})]},Y.sha)),S.length>3&&t("button",{onClick:()=>{w(Y=>{const W=new Set(Y);return W.has(_)?W.delete(_):W.add(_),W})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Kr,"aria-label":H?"Show fewer entities":`Show ${S.length-3} more entities`,children:H?"Show less":`+${S.length-3} more`})]})},_)})})]})]}),t("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),t("div",{className:"px-3 pb-2",children:t(oe,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&r&&t(dt,{projectSlug:r,onClose:()=>h(!1)})]})}function He(e){return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,n===null?void 0:n]))}function Zt(e){const{file_id:r,project_id:n,commit_id:a,file_path:o,entity_type:s,entity_branches:i,analyses:c,commit:d,created_at:h,updated_at:u,...m}=e,p=(i??[]).map(g=>g.branch_id),f=c?c.map(nt):void 0,y=d?St(d):void 0;return He({...m,fileId:r,projectId:n,commitId:a,filePath:o,entityType:s,commit:y,analyses:f,branchIds:p,createdAt:h,updatedAt:u})}function jn(e){return He({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 Rn(e){const{branches:r,files:n,analyzed_at:a,content_changed_at:o,created_at:s,updated_at:i,github_token:c,configuration:d,team_id:h,...u}=e;return He({...u,branches:r?r.map(Pt):void 0,files:n?n.map(jn):void 0,analyzedAt:a,contentChangedAt:o,createdAt:s,updatedAt:i})}function pl(e){const{id:r,project_id:n,user_id:a,scenario_id:o,thumbs_up:s,user:i}=e,c=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return He({id:r,projectId:n,userId:a,scenarioId:o,thumbsUp:!!s,user:c})}function fl(e){const{id:r,project_id:n,user_id:a,scenario_id:o,text:s,created_at:i,updated_at:c,user:d}=e,h=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return He({id:r,projectId:n,userId:a,scenarioId:o,text:s,createdAt:i,updatedAt:c,user:h})}function Eo(e){const{project_id:r,analysis_id:n,previous_version_id:a,analysis:o,user_scenarios:s,scenario_comments:i,approved:c,...d}=e,h=o?nt(o):void 0,u=s?s.map(pl):void 0,m=i?i.map(fl):void 0;return He({...d,projectId:r,analysisId:n,previousVersionId:a,analysis:h,userScenarios:u,comments:m})}function gl(e){return He({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?nt(e.analysis):void 0,entity:e.entity?Zt(e.entity):void 0,branch:e.branch?Pt(e.branch):void 0,createdAt:e.created_at})}function nt(e){const{project_id:r,commit_id:n,file_id:a,file_path:o,entity_sha:s,entity_type:i,entity_name:c,previous_analysis_id:d,file:h,entity:u,commit:m,project:p,scenarios:f,analysis_branches:y,dependency_analyzed_tree_sha:g,analyzed_tree_sha:b,branch_commit_sha:w,committed_at:x,completed_at:v,created_at:C,updated_at:k,indirect:N,...E}=e,A=u?Zt(u):void 0,I=h?jn(h):void 0,j=p?Rn(p):void 0,R=m?St(m):void 0,M=f?f.map(Eo):void 0,T=y?y.map(gl):void 0,$=T?T.map(z=>z.branch):void 0;return He({...E,projectId:r,commitId:n,fileId:a,filePath:o,entitySha:s,entityType:i,entityName:c,previousAnalysisId:d,entity:A,file:I,commit:R,project:j,scenarios:M,analysisBranches:T,branches:$,dependencyAnalyzedTreeSha:g,analyzedTreeSha:b,branchCommitSha:w,committedAt:x,completedAt:v,createdAt:C,updatedAt:k,indirect:!!N})}function Dn(e){return He({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?St(e.commit):void 0,branch:e.branch?Pt(e.branch):void 0})}function yl(e){const{project_id:r,commit_id:n,created_at:a,updated_at:o,success:s,...i}=e;return He({...i,projectId:r,commitId:n,createdAt:a,updatedAt:o,success:!!s})}function St(e){const{project_id:r,branch_id:n,branch:a,background_jobs:o,merged_branch_id:s,mergedBranch:i,ai_message:c,html_url:d,author:h,analyses:u,entities:m,commit_branches:p,committed_at:f,analyzed_at:y,...g}=e,b=a?Pt(a):void 0,w=i?Pt(i):void 0,x=(o==null?void 0:o.length)>0?yl(o[o.length-1]):void 0,v=(u??[]).map(nt),C=(m??[]).map(Zt),k=(p==null?void 0:p.length)>0?p.map(Dn):void 0;return h&&(h.username=h.preferredUsername??h.username),He({...g,projectId:r,branchId:n,branch:b,backgroundJob:x,mergedBranchId:s,mergedBranch:w,aiMessage:c,htmlUrl:d,author:h,analyses:v,entities:C,commitBranches:k,committedAt:f,analyzedAt:y})}function Pt(e){const{project_id:r,content_changed_at:n,commits:a,analysis_branches:o,active_at:s,created_at:i,updated_at:c,primary:d,...h}=e,u=a?a.map(St):void 0,m=o?o.flatMap(p=>nt(p.analysis)):void 0;return He({...h,projectId:r,contentChangedAt:n,commits:u,analyses:m,activeAt:s,createdAt:i,updatedAt:c,primary:!!d})}var kr;class xl{constructor(){Ca(this,kr,new bl)}transformQuery(r){return va(this,kr).transformNode(r.node)}transformResult(r){return Promise.resolve(r.result)}}kr=new WeakMap;class bl extends Mi{transformValue(r){return{...super.transformValue(r),value:typeof r.value=="boolean"?r.value?1:0:r.value}}transformPrimitiveValueList(r){return{...r,values:r.values.map(n=>typeof n=="boolean"?n?1:0:n)}}}const X=()=>null,wl={analyzed_at:X(),configuration:X(),content_changed_at:X(),created_at:X(),description:X(),github_token:X(),id:X(),metadata:X(),name:X(),path:X(),slug:X(),team_id:X(),updated_at:X()},vl=Object.keys(wl),Cl={active:X(),analysis_id:X(),branch_id:X(),created_at:X(),entity_sha:X(),id:X()},Nl=Object.keys(Cl),Sl={active_at:X(),content_changed_at:X(),created_at:X(),id:X(),metadata:X(),name:X(),primary:X(),project_id:X(),ref:X(),sha:X(),updated_at:X()},Ao=Object.keys(Sl),El={ai_message:X(),analyzed_at:X(),author_github_username:X(),branch_id:X(),committed_at:X(),created_at:X(),files:X(),html_url:X(),id:X(),merged_branch_id:X(),message:X(),metadata:X(),project_id:X(),sha:X(),title:X(),url:X()},ko=Object.keys(El);ko.filter(e=>e!=="files");const Al={commit_id:X(),created_at:X(),description:X(),documentation:X(),entity_type:X(),file_id:X(),file_path:X(),metadata:X(),name:X(),project_id:X(),quality:X(),sha:X(),updated_at:X()},Po=Object.keys(Al),kl={active:X(),branch_id:X(),entity_sha:X()},Pl=Object.keys(kl),Ml={created_at:X(),deleted:X(),id:X(),metadata:X(),name:X(),path:X(),project_id:X(),updated_at:X()},_l=Object.keys(Ml),Tl={analysis_id:X(),approved:X(),created_at:X(),description:X(),id:X(),metadata:X(),name:X(),previous_version_id:X(),project_id:X()},yr=Object.keys(Tl),Il=!!Et("ENABLE_QUERY_LOGGING"),$l=!!Et("ENABLE_QUERY_ERROR_LOGGING");Et("USE_LOCAL_POSTGRESQL_FOR_TESTING");let ir;function ve(){if(!ir){const e=_o();if(e==="sqlite")ir=jl();else if(e==="postgresql")ir=Rl();else throw new Error(`Unknown database type: ${e}`)}return ir}function jl(e){if(e||(e=Et("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const r=K.existsSync(e),n=ee.dirname(e);if(!K.existsSync(n))K.mkdirSync(n,{recursive:!0,mode:493});else try{K.chmodSync(n,493)}catch(o){console.warn(`Warning: Could not set permissions on database directory: ${o.message}`)}const a=new Ai(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();r&&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 xo({dialect:new Ti({database:a}),plugins:[new _i,new xl],log:Mo})}function Rl(){const e=Ll();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const r=new ki({connectionString:e,max:3,idleTimeoutMillis:1e4});return r.on("error",(n,a)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",n)}),new xo({dialect:new Ii({pool:r}),log:Mo})}let Zr=null;function At(){return Zr||(Zr=Dl(_o())),Zr}function Mo(e){e.level==="error"?$l&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):Il&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function Dl(e){if(e==="sqlite")return $i;if(e==="postgresql")return ji;throw new Error(`Unknown database type: ${e}`)}function _o(){if(Et("SQLITE_PATH"))return"sqlite";if(Et("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function Ll(){const e=Et("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function Et(e){var r;return typeof window<"u"?(r=window.env)==null?void 0:r[e]:process.env[e]}var Xt=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(Xt||{});const Ir="Default Scenario";let Fl="<main>";function Ol(){return Fl}function _a(e,...r){ge(`CodeYam Log Level ${e}: ${r[0]}`,...r.slice(1))}function ge(...e){const r=Ol(),n=e.map(o=>{if(o)return typeof o=="string"?o:o instanceof Error?`${o.name}: ${o.message}
|
|
21
|
+
${o.stack}`:typeof o=="object"?zl(o):String(o)}).filter(Boolean).join(`
|
|
22
|
+
`),a=`${r} ${n}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(a+`
|
|
23
|
+
`);return}console.log(a.replace(/\n/g,"\r"))}function zl(e,r=2){function n(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(c=>{const d=n(c,o);return typeof c=="string"?`"${d}"`:d}).join(",")}]`:`{${Object.entries(a).map(([i,c])=>{let d;return typeof c>"u"?null:(typeof c=="function"?d=`"(function: ${c.name||"anonymous"})"`:c instanceof Date?d=`"${c.toISOString()}"`:typeof c=="object"&&c!==null?d=n(c,o):typeof c=="string"?d=`"${c.replace(/"/g,'\\"')}"`:d=JSON.stringify(c),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,r)}catch(a){const o=n(e);if(!r)return o;try{return JSON.stringify(JSON.parse(n(e)),null,r)}catch(s){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:s,pureStringifyError:a,serialized:o}),o}}}function xr(e,r){try{let n=function(s){var i,c;if(Me.isFunctionDeclaration(s)&&Ot(s)){const d=((i=s.name)==null?void 0:i.text)||"default",h=s.getText(a),u=Xr(s);o.push({name:d,code:h,sha:xt(r,d,h),entityType:"function",isDefault:u})}else if(Me.isClassDeclaration(s)&&Ot(s)){const d=((c=s.name)==null?void 0:c.text)||"default",h=s.getText(a),u=Xr(s),m=h.includes("React.")||h.includes("jsx")||h.includes("tsx");o.push({name:d,code:h,sha:xt(r,d,h),entityType:m?"component":"class",isDefault:u})}else if(Me.isInterfaceDeclaration(s)&&Ot(s)){const d=s.name.text,h=s.getText(a);o.push({name:d,code:h,sha:xt(r,d,h),entityType:"interface",isDefault:!1})}else if(Me.isTypeAliasDeclaration(s)&&Ot(s)){const d=s.name.text,h=s.getText(a);o.push({name:d,code:h,sha:xt(r,d,h),entityType:"type",isDefault:!1})}else if(Me.isVariableStatement(s)&&Ot(s)){const d=Xr(s);s.declarationList.declarations.forEach(h=>{var u;if(Me.isIdentifier(h.name)){const m=h.name.text,p=s.getText(a),f=((u=h.initializer)==null?void 0:u.getText(a))||"",y=(r.endsWith(".tsx")||r.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));o.push({name:m,code:p,sha:xt(r,m,p),entityType:y?"component":"variable",isDefault:d})}})}else if(Me.isExportAssignment(s)){const d=s.getText(a);o.push({name:"default",code:d,sha:xt(r,"default",d),entityType:"unknown",isDefault:!0})}else if(Me.isExportDeclaration(s)&&s.exportClause&&Me.isNamedExports(s.exportClause)){const d=s.getText(a);for(const h of s.exportClause.elements){const u=h.name.text;o.push({name:u,code:d,sha:xt(r,u,d),entityType:"unknown",isDefault:!1})}}Me.forEachChild(s,n)};const a=Me.createSourceFile(r,e,Me.ScriptTarget.Latest,!0),o=[];return n(a),o}catch(n){return console.error(`Failed to extract entities from ${r}:`,n),[]}}function Ot(e){if(!Me.canHaveModifiers(e))return!1;const r=Me.getModifiers(e);return r?r.some(n=>n.kind===Me.SyntaxKind.ExportKeyword):!1}function Xr(e){if(!Me.canHaveModifiers(e))return!1;const r=Me.getModifiers(e);return r?r.some(n=>n.kind===Me.SyntaxKind.DefaultKeyword):!1}function xt(e,r,n){const a=kn.createHash("sha256");return a.update(`${e}:${r}:${n}`),a.digest("hex").substring(0,40)}function Yl(e){var h;const{webapp:r,port:n,environmentVariables:a,packageManager:o}=e,s=r==null?void 0:r.startCommand;if(!s)return`${o} ${o==="npm"?"run ":""}dev`;const i=((h=s.args)==null?void 0:h.map(u=>u.replace(/\$PORT/g,String(n))))??[],c=[];for(const u of a)if(u.key&&u.value!==void 0){const m=String(u.value).replace(/'/g,"'\\''");c.push(`${u.key}='${m}'`)}if(s.env)for(const[u,m]of Object.entries(s.env)){const f=String(m).replace(/\$PORT/g,String(n)).replace(/'/g,"'\\''");c.push(`${u}='${f}'`)}const d=c.length>0?c.join(" ")+" ":"";return s.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${s.command} ${i.join(" ")}`}function Bl(e,r){if(!r||r.length===0)return;if(r.length===1)return r[0];const n=ee.normalize(e),a=[...r].sort((o,s)=>{var i,c;return(((i=s.path)==null?void 0:i.length)??0)-(((c=o.path)==null?void 0:c.length)??0)});for(const o of a){const s=ee.normalize(o.path??".");if(s==="."||n.startsWith(s+ee.sep)||n===s)return o}return r[0]}function Ul(e){const{filePath:r,webapps:n,environmentVariables:a,port:o,packageManager:s}=e;if(!n||n.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=Bl(r,n);if(!i)throw new Error("Could not find webapp for file path: "+r);const c=Yl({webapp:i,port:o,environmentVariables:a,packageManager:s});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??s,startCommand:c,url:`http://localhost:${o}/static/codeyam-sample`}}function $r(e,r,n=[]){const a=Array.isArray(r)?r:[r];return o=>o.columns(a).doUpdateSet(s=>{const i=Object.keys(e).filter(c=>c!==r&&!n.includes(c));return Object.fromEntries(i.map(c=>[c,s.ref(`excluded.${c}`)]))})}function Wl(e){const{jsonObjectFrom:r}=At();return r(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 Hl({ids:e,analysisId:r}){const n=ve();try{let a=n.deleteFrom("scenarios");if(e){if(e.length===0)return;a=a.where("id","in",e)}else if(r)a=a.where("analysis_id","=",r);else throw ge("CodeYam Error: No deletion criteria provided",null,{ids:e,analysisId:r}),new Error("No deletion criteria provided for scenarios");await a.execute()}catch(a){throw ge("CodeYam Error: Database error deleting scenarios",a,{ids:e,analysisId:r}),a}}function ql(...e){try{const r=kn.createHash("sha256");for(const n of e)r.update(n);return r.digest("hex")}catch(r){throw console.log("CodeYam Error: Error generating sha",e),r}}function en(e,r){return r.map(n=>Jl(e,n))}function Jl(e,r){return Qe` ${Qe.ref(e)}.${Qe.ref(r)}`.as(r)}function Gl(e,r,n){return r.map(a=>Vl(e,a,n))}function Vl(e,r,n){return Qe` ${Qe.ref(e)}.${Qe.ref(r)}`.as(`_cy_${n}:${r}`)}function Ql(e,...r){const n={};for(const[a,o]of Object.entries(e)){const s=a.match(/^_cy_(.+?):(.+)$/);if(s){const[,i,c]=s;if(r.includes(i)){n[i]||(n[i]={}),n[i][c]=o;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${a}'`);continue}n[a]=o}return n}const Kl=50;function Zl(e,r){return e.length<=r?[e]:Array.from({length:Math.ceil(e.length/r)},(n,a)=>e.slice(a*r,a*r+r))}function Ta({projectId:e,ids:r,fileIds:n,entityName:a,entityShas:o,commitIds:s,branchCommitSha:i,limit:c,excludeMetadata:d}){const h=ve(),{jsonObjectFrom:u,jsonArrayFrom:m}=At();let p=d?h.selectFrom("analyses").select(["analyses.id","analyses.project_id","analyses.file_id","analyses.commit_id","analyses.entity_sha","analyses.entity_name","analyses.entity_type","analyses.file_path","analyses.status","analyses.created_at","analyses.updated_at","analyses.tree_sha","analyses.analyzed_tree_sha","analyses.dependency_analyzed_tree_sha","analyses.previous_analysis_id","analyses.branch_commit_sha","analyses.indirect","analyses.committed_at","analyses.completed_at"]):h.selectFrom("analyses").selectAll("analyses");if(e&&(p=p.where("project_id","=",e)),r){if(r.length===0)return null;p=p.where("id","in",r)}if(n){if(n.length===0)return null;p=p.where("file_id","in",n)}if(s){if(s.length===0)return null;p=p.where("commit_id","in",s)}return a&&(p=p.where("entity_name","=",a)),o&&(p=p.where("entity_sha","in",o)),i&&(p=p.where("branch_commit_sha","=",i)),c&&(p=p.limit(c)),d?h.with("filtered_analyses",()=>p).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[m(f.selectFrom("scenarios").select(en("scenarios",yr)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),m(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):h.with("filtered_analyses",()=>p).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select(en("entities",Po)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),m(f.selectFrom("scenarios").select(en("scenarios",yr)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),m(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function ut(e){const{ids:r,fileIds:n,entityShas:a,commitIds:o}=e;try{const i=Object.entries({id:{arr:r,key:"ids"},file_id:{arr:n,key:"fileIds"},entity_sha:{arr:a,key:"entityShas"},commit_id:{arr:o,key:"commitIds"}}).find(([d,{arr:h}])=>(h==null?void 0:h.length)>0);let c=[];if(i){const[d,{arr:h,key:u}]=i,m=Zl(h,Kl),p=[];for(let f=0;f<m.length;f++){const y=m[f],b=await Ta({...e,[u]:y}).execute();b&&p.push(...b)}c=p}else{const h=await Ta(e).execute();if(!h||h.length===0)return ge("CodeYam: No analyses found",null,e),null;c=h}return c.length===0?null:c.map(nt)}catch(s){return ge("CodeYam Error: Database error in loadAnalyses",s,e),null}}function Xl(e,r){const{jsonArrayFrom:n,jsonObjectFrom:a}=At();let o=e.selectFrom("analysis_branches").select(Nl).select(s=>a(s.selectFrom("branches").select(Ao).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return r&&(o=r(o)),n(o)}async function at({id:e,analysisBranchId:r,projectId:n,fileId:a,commitId:o,entityName:s,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}){const f=ve(),y=Date.now();try{let g=f.selectFrom("analyses").selectAll("analyses");e&&(g=g.where("id","=",e)),n&&(g=g.where("project_id","=",n)),i?g=g.where("dependency_analyzed_tree_sha","=",i):c?g=g.where("analyzed_tree_sha","=",c):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),r&&(g=g.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",r));const{jsonObjectFrom:b,jsonArrayFrom:w}=At();g=g.select(C=>{const k=[];return k.push(b(C.selectFrom("entities").select(Po).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&k.push(b(C.selectFrom("files").select(_l).whereRef("files.id","=","analyses.file_id")).as("file")),h&&k.push(b(C.selectFrom("projects").select(vl).whereRef("projects.id","=","analyses.project_id")).as("project")),m&&k.push(w(C.selectFrom("scenarios").select(yr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),p&&k.push(Xl(C,N=>N.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&k.push(b(C.selectFrom("commits").select(ko).select(N=>Wl(N).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),k});const x=await g.executeTakeFirst(),v=Date.now()-y;if(!x)return ge("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:r,projectId:n,fileId:a,commitId:o,entityName:s,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}),null;if(v>100&&u){const C=x.commit,k=C!=null&&C.files?JSON.stringify(C.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${v}ms (files: ${Math.round(k/1024)}KB)`,{id:x.id,entityName:x.entity_name})}return nt(x)}catch(g){return ge("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:r,projectId:n,fileId:a,commitId:o,entityName:s,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}),null}}async function To({projectId:e,ids:r,names:n,includeInactive:a}){const o=ve();try{let s=o.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(r){if(r.length===0)return[];s=s.where("id","in",r)}if(n){if(n.length===0)return[];s=s.where("name","in",n)}return a||(s=s.where("active_at","is not",null)),(await s.execute()).map(Pt)}catch(s){return ge("CodeYam Error: Database error loading branches",s,{projectId:e,ids:r,names:n,includeInactive:a}),[]}}async function ec({projectId:e,commitId:r,branchId:n,active:a,includeBranches:o}){const s=ve();try{let i=s.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(o,h=>h.select(Gl("branches",Ao,"branch"))).where("branches.project_id","=",e);r&&(i=i.where("commit_branches.commit_id","=",r)),n&&(i=i.where("commit_branches.branch_id","=",n)),a!==void 0&&(i=i.where("commit_branches.active","=",a));const c=await i.execute();return!c||c.length===0?null:c.map(h=>Ql(h,"branch")).map(Dn)}catch(i){return ge("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:r,branchId:n,active:a,includeBranches:o}),null}}async function tc(e){if(e.length===0)return new Map;const r=ve();try{const n=await r.selectFrom("commits").select(["id","branch_id","merged_branch_id"]).where("id","in",e).execute(),a=new Set;if(n.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 r.selectFrom("branches").selectAll().where("id","in",Array.from(a)).execute();return new Map(o.map(s=>[s.id,s]))}catch(n){return ge("CodeYam Error: Loading branches for commits",n,{commitIds:e}),new Map}}async function rc(e){if(e.length===0)return new Map;const r=ve(),{jsonObjectFrom:n,jsonArrayFrom:a}=At();try{const o=await r.selectFrom("analyses").selectAll("analyses").select(i=>[n(i.selectFrom("files").select(["id","name","path"]).whereRef("files.id","=","analyses.file_id")).as("file"),a(i.selectFrom("scenarios").select(yr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),s=new Map;return o.forEach(i=>{const c=s.get(i.commit_id)||[];c.push(i),s.set(i.commit_id,c)}),s}catch(o){return ge("CodeYam Error: Loading analyses for commits",o,{commitIds:e}),new Map}}async function nc(e){if(e.length===0)return new Map;const r=ve();try{const n=await r.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),a=new Map;return n.forEach(o=>{const s=a.get(o.commit_id)||[];s.push(o),a.set(o.commit_id,s)}),a}catch(n){return ge("CodeYam Error: Loading entities for commits",n,{commitIds:e}),new Map}}async function br({projectId:e,branchId:r,ids:n,shas:a,fileNames:o,limit:s=10,skipRelations:i=!1}){if(!e&&!n)throw new Error("Must provide projectId or ids");const c=ve(),{jsonObjectFrom:d}=At(),h=Date.now();try{let u=c.selectFrom("commits").selectAll("commits").select(x=>[d(x.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",x.ref("commits.author_github_username"))).as("author")]);if(e&&(u=u.where("project_id","=",e)),n){if(n.length===0)return[];u=u.where("id","in",n)}if(a){if(a.length===0)return[];u=u.where("sha","in",a)}if(o&&o.length>0){const x=Qe.join(o.map(v=>Qe`${v}`),Qe`, `);u=u.where(Qe`
|
|
24
|
+
EXISTS (
|
|
25
|
+
SELECT 1
|
|
26
|
+
FROM json_each(${Qe.ref("commits.files")}) AS f
|
|
27
|
+
WHERE json_extract(f.value, '$.fileName') IN (${x})
|
|
28
|
+
)
|
|
29
|
+
`)}r&&(u=u.where("branch_id","=",r));const m=await u.orderBy("committed_at","desc").limit(s).execute(),p=Date.now()-h;if(!m||m.length===0)return[];if(p>100){const x=m.reduce((v,C)=>v+(C.files?JSON.stringify(C.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${p}ms (${m.length} commits, totalFiles: ${Math.round(x/1024)}KB)`)}if(i)return m.map(v=>({...v,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(St);const f=m.map(x=>x.id),[y,g,b]=await Promise.all([tc(f),rc(f),nc(f)]);return m.map(x=>{const v=x.branch_id?y.get(x.branch_id):void 0,C=x.merged_branch_id?y.get(x.merged_branch_id):void 0,k=g.get(x.id)||[],N=b.get(x.id)||[];return{...x,branch:v,mergedBranch:C,analyses:k,entities:N}}).map(St)}catch(u){return ge("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:r,ids:n,shas:a,limit:s}),[]}}async function ht({projectId:e,branchId:r,fileIds:n,filePaths:a,names:o,shas:s,excludeMetadata:i}){if(n&&n.length==0||a&&a.length==0||o&&o.length==0||s&&s.length==0)return[];if(s&&s.length>50){const d=[];for(let h=0;h<s.length;h+=50){const u=s.slice(h,h+50),m=await ht({projectId:e,branchId:r,fileIds:n,filePaths:a,names:o,shas:u,excludeMetadata:i});m&&d.push(...m)}return d}const c=ve();try{const u=await(i?c.selectFrom("entities").select(["entities.project_id","entities.file_id","entities.commit_id","entities.name","entities.sha","entities.entity_type","entities.file_path","entities.description","entities.documentation","entities.quality","entities.created_at","entities.updated_at"]):c.selectFrom("entities").selectAll("entities")).$if(!!r,m=>m.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",r)).$if(!!e,m=>m.where("entities.project_id","=",e)).$if(!!s,m=>m.where("entities.sha","in",s)).$if(!!a,m=>m.where("entities.file_path","in",a)).$if(!!o,m=>m.where("entities.name","in",o)).$if(!!n,m=>m.where("entities.file_id","in",n)).execute();return!u||u.length===0?(console.log("Load Entities: No entities found",{projectId:e,fileIds:n,filePaths:a,shas:s}),null):u.map(Zt)}catch(d){return console.log("Load Entities: Error occurred",d,{projectId:e,fileIds:n,filePaths:a,shas:s}),null}}function ac(e,r){const{jsonArrayFrom:n}=At();let a=e.selectFrom("entity_branches").select(Pl);return r&&(a=r(a)),n(a)}async function Io({projectId:e,sha:r}){const n=ve();try{const a=await n.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(o=>ac(o,s=>s.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",r).executeTakeFirst();return a?Zt(a):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&ge("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:r}),null)}catch(a){return ge("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:r}),null}}const tn=1e3;async function $o({projectId:e,filePaths:r,fileIds:n,fileNames:a}){if(r&&r.length>50){const c=[];for(let d=0;d<r.length;d+=50){const h=r.slice(d,d+50),u=await $o({projectId:e,filePaths:h,fileIds:n,fileNames:a});u&&c.push(...u)}return c}const o=ve(),s=[];let i=0;try{for(;;){let c=o.selectFrom("files").selectAll().where("project_id","=",e).limit(tn).offset(i);if(r){if(r.length===0)return[];c=c.where("path","in",r)}if(n){if(n.length===0)return[];c=c.where("id","in",n)}if(a){if(a.length===0)return[];c=c.where("name","in",a)}const d=await c.execute();if(!d||d.length===0||(s.push(...d),d.length<tn))break;i+=tn}return s==null?void 0:s.map(jn)}catch(c){return console.log("CodeYam Error: Error loading project files in loadFiles",c),null}}async function oc({id:e,slug:r,withBranches:n,withFiles:a,silent:o}){try{let i=ve().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(r)i=i.where("slug","=",r);else throw new Error("Either id or slug must be provided");const c=await i.executeTakeFirst();if(!c)return o||console.log("CodeYam Error: Error loading project",{id:e,slug:r,withBranches:n,withFiles:a}),null;const d=Rn(c);return a&&(d.files=await $o({projectId:d.id})),n&&(d.branches=await To({projectId:d.id,includeInactive:!1})),d}catch(s){return o||console.log("CodeYam Error: Error loading project",s),null}}function wr(e,r){const n={...e};for(const a in r){const o=r[a],s=e[a];o!=null&&typeof o=="object"&&!Array.isArray(o)&&s!==void 0&&s!==null&&typeof s=="object"&&!Array.isArray(s)?n[a]=wr(s,o):o!==void 0&&(n[a]=o)}return n}async function ct({commitId:e,commitSha:r,metadataUpdate:n,runStatusUpdate:a,archiveCurrentRun:o,updateCallback:s}){try{return await ve().transaction().execute(async i=>{var u,m;const c=await i.selectFrom("commits").select(["id","metadata"]).$if(!!e,p=>p.where("id","=",e)).$if(!!r,p=>p.where("sha","=",r)).executeTakeFirst();if(!c)return ge(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const d=c.metadata||{};if(a)a.lastUpdatedAt??(a.lastUpdatedAt=new Date().toISOString()),a.currentEntityShas!==void 0&&(console.log("[updateCommitMetadata] Updating currentRun.currentEntityShas"),console.log(`[updateCommitMetadata] Commit SHA: ${r}`),console.log("[updateCommitMetadata] Previous entity SHAs:",(u=d.currentRun)==null?void 0:u.currentEntityShas),console.log("[updateCommitMetadata] New entity SHAs:",a.currentEntityShas),console.log("[updateCommitMetadata] Archive flag:",o)),n=wr(n??{},{currentRun:a});else if(!n&&!s)return d;const h=n?wr(d,n):d;if(o&&h.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${r}`),console.log("[updateCommitMetadata] Current run entity SHAs:",h.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${h.currentRun.analyzerPid}, capture=${h.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${h.currentRun.analysesCompleted}, captures=${h.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${((m=h.historicalRuns)==null?void 0:m.length)||0}`);const p={...h.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(p,null,2)),h.historicalRuns=[...h.historicalRuns||[],p],console.log(`[updateCommitMetadata] Historical runs after archiving: ${h.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(h.historicalRuns.map(f=>({entityShas:f.currentEntityShas,archivedAt:f.archivedAt,completed:{analyses:f.analysesCompleted,captures:f.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}s&&await s(h);try{return await i.updateTable("commits").set({metadata:JSON.stringify(h)}).where("id","=",c.id).returning(["id"]).executeTakeFirst()?h:(ge(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),d)}catch(p){return ge(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,p),d}})}catch(i){return ge(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}`,i),null}}async function jo(e,r,n="analysis"){try{return await ve().transaction().execute(async a=>{const o=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!o)return ge(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${n})`,null,{analysisId:e,source:n}),null;const s=nt(o);return r(s.metadata,s),await a.updateTable("analyses").set({metadata:JSON.stringify(s.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?s.metadata:(ge(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${n})`,null,{analysisId:e,source:n}),null)})}catch(a){return ge(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${n})`,a,{analysisId:e,source:n}),null}}async function Tt(e,r,n="capture"){try{return await ve().transaction().execute(async a=>{const o=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!o)return ge(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${n})`,null,{analysisId:e,source:n}),null;const s=nt(o);return r(s.status,s),await a.updateTable("analyses").set({status:JSON.stringify(s.status)}).where("id","=",e).returningAll().executeTakeFirst()?s.status:(ge(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${n})`,null,{analysisId:e,source:n}),null)})}catch(a){return ge(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${n})`,a,{analysisId:e,source:n}),null}}async function sc({projectId:e,projectSlug:r,metadataUpdate:n,updateCallback:a}){if(!e&&!r)throw new Error("Either projectId or projectSlug must be provided");try{return await ve().transaction().execute(async o=>{const s=await o.selectFrom("projects").selectAll().$if(!!e,d=>d.where("id","=",e)).$if(!!r,d=>d.where("slug","=",r)).executeTakeFirst();if(!s)return ge(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=s.metadata||{};if(!n&&!a)return i;const c=n?wr(i,n):i;a&&await a(c,Rn(s));try{return await o.updateTable("projects").set({metadata:JSON.stringify(c)}).where("id","=",s.id).returningAll().executeTakeFirst()?c:(ge(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return ge(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(o){return ge(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,o),null}}function ic(e){const{id:r,projectId:n,analysisId:a,previousVersionId:o,analysis:s,metadata:i,data:c,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:r??Kt(),metadata:i?JSON.stringify(i):null,project_id:n,analysis_id:a,previous_version_id:o}}async function lc(e){if(e.length===0)return[];const r=ve(),n=e.map(ic);try{return(await r.insertInto("scenarios").values(n).onConflict($r(n[0],"id",["created_at"])).returningAll().execute()).map(Eo)}catch(a){return ge("CodeYam Error: Database error upserting scenarios",a,{scenarioCount:e.length}),null}}function cc(e){const{id:r,commitId:n,branchId:a,...o}=e;return delete o.commit,delete o.branch,{...o,id:r??Kt(),commit_id:n,branch_id:a}}async function Ia(e){if(e.length===0)return[];const r=ve(),n=e.map(cc);try{return(await r.insertInto("commit_branches").values(n).onConflict($r(n[0],"id",["created_at"])).returningAll().execute()).map(Dn)}catch(a){return ge("CodeYam Error: Database error upserting commit branches",a,{commitBranchCount:e.length,commitBranchIds:e.map(o=>o.id)}),[]}}async function dc(e,r){const n=ve(),a={username:e,avatar_url:r};try{return await n.insertInto("github_users").values(a).onConflict($r(a,"username",[])).returningAll().executeTakeFirst()||null}catch(o){return ge("CodeYam Error: Error upserting github user",o,{username:e,avatarUrl:r}),null}}function uc(e,r){const{id:n,projectId:a,branchId:o,mergedBranchId:s,aiMessage:i,htmlUrl:c,analyzedAt:d,committedAt:h,author:u,metadata:m,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:n??Kt(),project_id:a??String(r),metadata:m?JSON.stringify(m):void 0,files:p?JSON.stringify(p):void 0,branch_id:o,merged_branch_id:s,author_github_username:u==null?void 0:u.username,html_url:c,ai_message:i,analyzed_at:d,committed_at:h}}async function hc({projectId:e,commits:r}){const n=ve();try{const a=r.reduce((i,c)=>{const{author:d}=c;return d!=null&&d.username&&(d!=null&&d.avatarUrl)&&(i[d.username]=d.avatarUrl),i},{});for(const i in a)await dc(i,a[i]);const o=r.map(i=>uc(i,e));return(await n.insertInto("commits").values(o).onConflict($r(o[0],"id",["created_at"])).returningAll().execute()).map(St)}catch(a){return ge("CodeYam Error: Error saving commits",a,{projectId:e,commitCount:r.length,commitIds:r.map(o=>o.id).filter(Boolean)}),[]}}const vr=ee.join(Li.homedir(),".codeyam","secrets.json"),Cr=ee.join(process.cwd(),".codeyam","secrets.json");async function ft(){let e={};try{if(K.existsSync(Cr)){const s=await Ie.readFile(Cr,"utf8");e=JSON.parse(s)}}catch{console.warn(gr.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(K.existsSync(vr)){const s=await Ie.readFile(vr,"utf8");e={...JSON.parse(s),...e}}}catch{console.warn(gr.yellow("⚠ Could not read home secrets file, falling back to environment variables"))}const r={},n=e.OPENAI_API_KEY||process.env.OPENAI_API_KEY;n&&(r.OPENAI_API_KEY=n);const a=e.ANTHROPIC_API_KEY||process.env.ANTHROPIC_API_KEY;a&&(r.ANTHROPIC_API_KEY=a);const o=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return o&&(r.GROQ_API_KEY=o),r}async function mc(e,r=!0){const n=r?vr:Cr,a=ee.dirname(n);await Ie.mkdir(a,{recursive:!0}),await Ie.writeFile(n,JSON.stringify(e,null,2)),await Ie.chmod(n,384)}function pc(e=!0){return e?vr:Cr}async function $a(){const e=await ft(),r=[];for(const n of r)e[n];return{isValid:!0,missing:[],secrets:e}}async function fc(e){console.log(),console.log(gr.blue("ℹ Configuration needed")),console.log();const r={};for(const n of e)switch(n){case"OPENAI_API_KEY":const a=await Fi({type:"password",name:"key",message:"OpenAI API Key",validate:o=>o&&!o.startsWith("sk-")?"OpenAI API key should start with sk-":!0});a.key&&(r.OPENAI_API_KEY=a.key);break}return r}async function gc(e=!0){const r=await $a();if(r.isValid)return r.secrets;const n=await fc(r.missing),o={...await ft(),...n};await mc(o,e);const s=pc(e);return console.log(gr.green(`✓ Configuration saved to ${s}`)),(await $a()).secrets}function Ro(e=process.cwd()){let r=ee.resolve(e);const n=ee.parse(r).root;for(;r!==n;){const o=ee.join(r,".codeyam","config.json");if(K.existsSync(o))return r;r=ee.dirname(r)}const a=ee.join(n,".codeyam","config.json");return K.existsSync(a)?n:null}let Do=Ro();function fe(){return Do}function yc(e){Do=e}function Lo(e){const r={...e};for(const n in e)if(n.includes(".")){const a=n.replace(/\./g,"");r[a]=e[n]}return r}const xc={"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>`};Lo(xc);const bc={"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>`};Lo(bc);function zt(e,r,n=new WeakSet){if(!r)return e;if(!e)return r;try{if(typeof r=="object"&&r!==null){if(n.has(r))throw new Error("Circular reference detected during deep merge");n.add(r)}if(Array.isArray(r)){const o=Array.isArray(e)?e:[],s=[];for(let i=0;i<r.length;i++){const c=r[i];c&&typeof c=="object"&&!Array.isArray(c)||Array.isArray(c)?s[i]=zt(o[i],c,n):s[i]=c}return s}const a={...e};for(const o in r)if(r[o]===null)a[o]=null;else if(Array.isArray(r[o])){const s=Array.isArray(e[o])?e[o]:[];a[o]=[];for(let i=0;i<r[o].length;i++){const c=r[o][i];typeof c=="object"&&c!==null?a[o][i]=zt(s[i],c,n):a[o][i]=c}}else typeof r[o]=="object"&&r[o]!==null?a[o]=zt(a[o]??{},r[o],n):a[o]=r[o];return a}catch(a){throw console.log("CodeYam: Error merging data",e,r),a}}async function wc({projectId:e,commit:r,branch:n}){var c,d,h,u,m,p,f;let a;const o={commitId:r.id,branchId:n.id,active:!0},s=await ec({projectId:e,commitId:r.id,includeBranches:!0});if(s&&s.length>0){a=(c=s.sort((g,b)=>{var w,x,v,C;return(((x=(w=g.branch.metadata)==null?void 0:w.permanent)==null?void 0:x.order)??999)-(((C=(v=b.branch.metadata)==null?void 0:v.permanent)==null?void 0:C.order)??999)})[0])==null?void 0:c.branch,a&&((h=(d=n.metadata)==null?void 0:d.permanent)==null?void 0:h.order)!==void 0&&(((m=(u=n.metadata)==null?void 0:u.permanent)==null?void 0:m.order)<=((f=(p=a.metadata)==null?void 0:p.permanent)==null?void 0:f.order)?a=n:o.active=!1);const y=s.filter(g=>g.active&&g.branch.id!==a.id||!g.active&&g.branch.id===a.id);y.length>0&&await Ia(y.map(g=>({...g,active:g.branchId===a.id})))}(s==null?void 0:s.find(y=>y.branchId===o.branchId))||await Ia([o])}function gt(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=fe();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return ue.join(e,".codeyam","db.sqlite3")}async function $e(){const e=await gc();process.env.SQLITE_PATH=gt(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Fe(e){await $e();const r=await oc({slug:e});if(!r)throw new Error(`Project with slug "${e}" not found in database`);const n=await To({projectId:r.id,names:["_local"]}),a=n==null?void 0:n[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:r,branch:a}}async function vc(e,r,n){await $e();const a=fe(),o=ql(`${e.slug}-local-${Date.now()}-${Math.random()}`),s=n.map(d=>{let h="";if(a)try{if(h=_e(`git diff HEAD -- "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!h)try{const u=_e(`cat "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const m=u.split(`
|
|
30
|
+
`);h=`@@ -0,0 +1,${m.length} @@
|
|
31
|
+
${m.map(p=>`+${p}`).join(`
|
|
32
|
+
`)}`}}catch{}}catch{}return{fileName:d,status:"modified",patch:h}}),i={sha:o,projectId:e.id,branchId:r.id,message:`Local analysis: ${n.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${o}`,htmlUrl:`local://codeyam/${e.slug}/${o}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:s,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},c=await hc({projectId:e.id,commits:[i]});if(!c||c.length===0)throw new Error("Failed to create fake commit");return await wc({projectId:e.id,commit:c[0],branch:r}),c[0]}async function er(){await $e();const e=await ht({excludeMetadata:!0});if(!e||e.length===0)return[];const r=e.filter(d=>{var h;return!((h=d.metadata)!=null&&h.isSuperseded)}),n=r.map(d=>d.sha),a=r.map(d=>{var h;return(h=d.metadata)==null?void 0:h.previousVersionWithAnalyses}).filter(d=>!!d),o=[...new Set([...n,...a])],s=await ut({entityShas:o,excludeMetadata:!0}),i=new Map;if(s)for(const d of s)i.has(d.entitySha)||i.set(d.entitySha,[]),i.get(d.entitySha).push(d);return r.map(d=>{var m;const h=i.get(d.sha)||[];if(h.length>0)return{...d,analyses:h};const u=(m=d.metadata)==null?void 0:m.previousVersionWithAnalyses;if(u){const p=i.get(u)||[];return{...d,analyses:p}}return{...d,analyses:[]}})}async function jr(e,r){await $e();const n=await ut({entityShas:[e],limit:1});if(n&&n.length>0&&r){const a=await Io({projectId:n[0].projectId,sha:e});if(a)for(const o of n)o.entity=a}return n||[]}async function Ln(e){if(await $e(),e.name&&e.projectId){const n=await ut({projectId:e.projectId,entityName:e.name,limit:10});if(n&&n.length>0){const a=n.filter(s=>{const i=s.scenarios&&s.scenarios.length>0,c=!e.filePath||s.filePath===e.filePath;return i&&c});if(a.length>0)return a.sort((s,i)=>{const c=new Date(s.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),a[0];const o=n.filter(s=>s.scenarios&&s.scenarios.length>0);if(o.length>0)return o.sort((s,i)=>{const c=new Date(s.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),o[0]}}const r=await ut({entityShas:[e.sha],limit:1});return r&&r.length>0?r[0]:null}async function Fo(e){await $e();const r=await ut({entityShas:[e],limit:1});return(r==null?void 0:r[0])??null}async function Mt(e){await $e();const r=await ze();if(!r)return null;const{project:n}=await Fe(r);return await Io({projectId:n.id,sha:e})}async function Oo(e){var a,o,s,i,c,d,h,u;await $e();const r=[],n=[];if((a=e.metadata)!=null&&a.importedExports&&e.metadata.importedExports.length>0){const m=e.metadata.importedExports;for(const p of m){if(!p.filePath||!p.name)continue;const f=await ht({projectId:e.projectId,filePaths:[p.filePath],names:[p.name]});if(f&&f.length>0){const y=f[0],g=await ut({entityShas:[y.sha],limit:1});let b,w,x;if(g&&g.length>0&&g[0].scenarios){const v=g[0],C=v.scenarios||[],k=C.length,N=C.find(A=>{var I,j;return(j=(I=A.metadata)==null?void 0:I.screenshotPaths)==null?void 0:j[0]});N&&(b=(s=(o=N.metadata)==null?void 0:o.screenshotPaths)==null?void 0:s[0],w=N.name),x={status:((i=y.metadata)==null?void 0:i.previousVersionWithAnalyses)||v.entitySha!==y.sha?"out_of_date":"up_to_date",scenarioCount:k,timestamp:v.createdAt?new Date(v.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else x={status:"not_analyzed"};r.push({...y,screenshotPath:b,scenarioName:w,analysisStatus:x})}}}if((c=e.metadata)!=null&&c.importedBy){const m=[];for(const p in e.metadata.importedBy)for(const f in e.metadata.importedBy[p]){const y=e.metadata.importedBy[p][f];y.shas&&m.push(...y.shas)}if(m.length>0){const p=await ht({projectId:e.projectId,shas:m});if(p)for(const f of p){const y=await ut({entityShas:[f.sha],limit:1});let g,b,w;if(y&&y.length>0&&y[0].scenarios){const x=y[0],v=x.scenarios||[],C=v.length,k=v.find(E=>{var A,I;return(I=(A=E.metadata)==null?void 0:A.screenshotPaths)==null?void 0:I[0]});k&&(g=(h=(d=k.metadata)==null?void 0:d.screenshotPaths)==null?void 0:h[0],b=k.name),w={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||x.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:C,timestamp:x.createdAt?new Date(x.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else w={status:"not_analyzed"};n.push({...f,screenshotPath:g,scenarioName:b,analysisStatus:w})}}}return{importedEntities:r,importingEntities:n}}async function ze(){try{const e=fe();if(!e)return null;const r=ue.join(e,".codeyam","config.json");return JSON.parse(await pe.readFile(r,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function It(){await $e();try{const e=await ze();if(!e)return null;const{project:r,branch:n}=await Fe(e),a=await br({projectId:r.id,branchId:n.id,limit:1,skipRelations:!0});return a&&a.length>0?a[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function Fn(){try{const e=fe();if(!e)return null;const r=ue.join(e,".codeyam","config.json");return JSON.parse(await pe.readFile(r,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function zo(e){try{const r=fe();if(!r)return console.error("[getEntityCodeFromFilesystem] No project root found"),null;if(!e.filePath)return console.error("[getEntityCodeFromFilesystem] Entity has no filePath"),null;const n=ue.join(r,e.filePath);return await pe.readFile(n,"utf8")}catch(r){return console.error("[getEntityCodeFromFilesystem] Error reading file:",r),null}}async function Yo(e){try{const r=fe();if(!r||!e.filePath)return!1;const n=ue.join(r,e.filePath),o=(await pe.stat(n)).mtime.getTime(),s=e.updatedAt||e.createdAt;if(!s)return!1;const i=new Date(s).getTime();return o>i+1e3}catch{return!1}}async function Bo(e){if(await $e(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const r=await ht({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!r||r.length===0)return[];const n=r.map(i=>i.sha),a=await ut({entityShas:n}),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,c]of o.entries())c.sort((d,h)=>{const u=new Date(d.createdAt||0).getTime();return new Date(h.createdAt||0).getTime()-u});const s=r.map(i=>({...i,analyses:o.get(i.sha)||[]}));return s.sort((i,c)=>{var u,m;const d=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",h=((m=c.analyses[0])==null?void 0:m.createdAt)||c.createdAt||"";return new Date(h).getTime()-new Date(d).getTime()}),s}async function Uo(e){try{const r=fe();if(!r)return console.error("[updateProjectConfig] No project root found"),!1;const n=ue.join(r,".codeyam","config.json"),a=await pe.readFile(n,"utf8"),o=JSON.parse(a),s={...o,...e},i=JSON.stringify(s,null,2);if(await pe.writeFile(n,i,"utf8"),o.projectSlug){const c={};e.universalMocks!==void 0&&(c.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(c.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(c.webapps=e.webapps),await sc({projectSlug:o.projectSlug,metadataUpdate:c})}return!0}catch(r){return console.error("[updateProjectConfig] Error:",r),!1}}const Cc=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:er,getAnalysesForEntity:jr,getAnalysisForExactEntitySha:Fo,getCurrentCommit:It,getEntityBySha:Mt,getEntityCodeFromFilesystem:zo,getEntityHistory:Bo,getLatestAnalysisForEntity:Ln,getProjectConfig:Fn,getProjectSlug:ze,getRelatedEntities:Oo,hasFileBeenModifiedSinceEntity:Yo,updateProjectConfig:Uo},Symbol.toStringTag,{value:"Module"})),Wo="secrets.json";function Ho(e){return ue.join(e,".codeyam",Wo)}function qo(){return ue.join(pn.homedir(),".codeyam",Wo)}async function Rr(e){let r={};try{const n=qo(),a=await pe.readFile(n,"utf-8");r=JSON.parse(a)}catch{}try{const n=Ho(e),a=await pe.readFile(n,"utf-8"),o=JSON.parse(a);r={...r,...o}}catch{}return r}async function Nc(e,r,n=!0){const a=n?qo():Ho(e),o=ue.dirname(a);await pe.mkdir(o,{recursive:!0}),await pe.writeFile(a,JSON.stringify(r,null,2)+`
|
|
33
|
+
`,"utf-8")}async function Sc(e){const r=await Rr(e);return!!(r.ANTHROPIC_API_KEY&&r.ANTHROPIC_API_KEY.length>0)||!!(r.OPENAI_API_KEY&&r.OPENAI_API_KEY.length>0)||!!(r.GROQ_API_KEY&&r.GROQ_API_KEY.length>0)||!!(r.OPENROUTER_API_KEY&&r.OPENROUTER_API_KEY.length>0)}async function Ec({sourcePath:e,destinationPath:r,excludes:n=[],keepExisting:a=!1,silent:o=!1,extraArgs:s=[]}){return new Promise((i,c)=>{const d=e.endsWith("/")?e:`${e}/`,h=r.endsWith("/")?r:`${r}/`,u=["-a"];a||u.push("--delete","--force"),u.push(...s);for(const f of n)u.push(`--exclude=${f}`);u.push(d,h);const m=Date.now(),p=_r("rsync",u);p.on("exit",f=>{if(f===0){if(!o){const y=((Date.now()-m)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${r} [Time: ${y}s]`)}i()}else c(new Error(`rsync failed with exit code ${f}`))}),p.on("error",f=>{o||console.log("Error occurred:",f),c(f)})})}const Ac=_n(Pn);async function kc(e){return new Promise(r=>setTimeout(r,e))}function Pc(e){try{return process.kill(e,0),!0}catch{return!1}}async function Jo(e){try{const{stdout:r}=await Ac(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),n=r.trim().split(`
|
|
34
|
+
`).filter(o=>o.trim()).map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o)),a=[...n];for(const o of n){const s=await Jo(o);a.push(...s)}return a}catch{return[]}}function ja(e,r,n){try{process.kill(e,r)}catch(a){n==null||n(`Error sending ${r} to process ${e}: ${a}`)}}async function Mc(e,r,n){const a=await Jo(e);for(const o of a.reverse())await ja(o,r,n);await ja(e,r,n)}async function Jt(e,r=console.log,n=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let a=0;async function o(s,i){await Mc(e,s,r);for(let c=0;c<i;c++)if(await kc(1e3),a+=1e3,!await Pc(e))return r(`Process tree ${e} successfully killed with ${s} after ${a/1e3} seconds.`),!0;return r(`Process tree still running after ${s}...`),!1}if(await o("SIGINT",5)||await o("SIGTERM",5))return!0;for(let s=0;s<n;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 _c(e){const r=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=r,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:Zi(),createdAt:r}}zi.config({quiet:!0});var Go=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(Go||{});class Tc extends Yi{constructor(){super(...arguments),this.processes=new Map}register(r){const n=Ui(),{process:a,type:o,name:s,metadata:i,parentId:c}=r,d={id:n,type:o,name:s,pid:a.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:c,children:[]};if(this.processes.set(n,{info:d,process:a}),c){const m=this.processes.get(c);m&&(m.info.children=m.info.children||[],m.info.children.push(n))}const h=(m,p)=>{this.handleProcessExit(n,m,p)},u=m=>{this.handleProcessError(n,m)};return a.on("exit",h),a.on("error",u),a.__cleanup=()=>{a.removeListener("exit",h),a.removeListener("error",u)},this.emit("processStarted",d),n}unregister(r){const n=this.processes.get(r);return n?(n.process.__cleanup&&n.process.__cleanup(),this.processes.delete(r),!0):!1}getInfo(r){const n=this.processes.get(r);return n?{...n.info}:null}listAll(){return Array.from(this.processes.values()).map(r=>({...r.info}))}listByType(r){return this.listAll().filter(n=>n.type===r)}listByState(r){return this.listAll().filter(n=>n.state===r)}findByName(r){return this.listAll().filter(n=>n.name===r)}async shutdown(r,n={}){const a=this.processes.get(r);if(!a)throw new Error(`Process not found: ${r}`);const{info:o,process:s}=a;if(o.state==="completed"||o.state==="failed"||o.state==="killed")return;if(n.shutdownChildren&&o.children&&o.children.length>0&&await Promise.all(o.children.map(c=>this.shutdown(c,n))),s.pid)try{await Jt(s.pid,c=>console.log(`[Process ${r}] ${c}`))}catch(c){console.warn(`Error killing process ${r}:`,c)}await new Promise(c=>setTimeout(c,100)),o.state==="running"&&(o.state="killed",o.endedAt=Date.now());const i=s.__cleanup;i&&i()}async shutdownByType(r,n={}){const a=this.listByType(r);await Promise.all(a.map(o=>this.shutdown(o.id,n)))}async shutdownAll(r={}){const n=this.listAll();await Promise.all(n.map(a=>this.shutdown(a.id,r)))}cleanupCompleted(r={}){const{retentionMs:n=6e4}=r,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>n){const c=s.process.__cleanup;c&&c(),this.processes.delete(o)}}}handleProcessExit(r,n,a){const o=this.processes.get(r);if(!o)return;const{info:s}=o;s.endedAt=Date.now(),s.exitCode=n,s.signal=a,n===0?s.state="completed":a?s.state="killed":s.state="failed",this.emit("processExited",s)}handleProcessError(r,n){const a=this.processes.get(r);if(!a)return;const{info:o}=a;o.endedAt=Date.now(),o.state="failed",o.metadata={...o.metadata,error:n.message},this.emit("processExited",o)}}let rn=null;function Ic(){return rn||(rn=new Tc),rn}const $c={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function jc({command:e,args:r,workingDir:n,outputOptions:a=$c,processName:o,env:s}){const i={...process.env,...s||{},CODEYAM_PROCESS_NAME:`codeyam-${o}`},c=_r(e,r,{cwd:n,env:i});return Ic().register({process:c,type:Go.Other,name:o,metadata:{command:e,args:r,workingDir:n}}),{promise:new Promise(u=>{const m=f=>{const y=ue.join(n,"log.txt");K.appendFile(y,f,g=>{g&&console.log("Error writing to log file:",g)})},p=(f,y="")=>{const g=new Date().toLocaleString();return f.split(`
|
|
35
|
+
`).map(w=>w.trim()?`[${g}]${y} ${w}`:w).join(`
|
|
36
|
+
`)};c.stdout.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=p(y);a.stdoutToConsole&&console.log(g),a.stdoutToFile&&m(g+`
|
|
37
|
+
`),a.stdoutCallback&&a.stdoutCallback(y)}),c.stderr.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=p(y,"<STDERR>");a.stderrToConsole&&console.error(g),a.stderrToFile&&m(g+`
|
|
38
|
+
`),a.stderrCallback&&a.stderrCallback(y)}),c.on("exit",function(f){u(f)})}),process:c}}function Rc(e){const r=[];return Object.keys(e).forEach(n=>{const a=e[n];a!==void 0&&(typeof a=="boolean"?a&&r.push(`--${n}`):a!==null&&r.push(`--${n}`,String(a)))}),r}function Dc({absoluteCodeyamRootPath:e,startEnv:r,startArgs:n,outputOptions:a}){const o=Object.entries(r).map(([i,c])=>`${i}=${c}`).join(`
|
|
39
|
+
`);K.writeFileSync(`${e}/.env`,o);const s=Rc(n);return jc({command:"node",args:["--enable-source-maps","./dist/project/start.js",...s],workingDir:e,outputOptions:a,processName:"analyzer",env:r})}const Lc="/tmp/codeyam/local-dev";function Vo(e){return ee.join(Lc,e)}function Qo(e){return ee.join(Vo(e),"codeyam")}function ot(e){return ee.join(Vo(e),"project")}function Dr(e){return ee.join(Qo(e),"log.txt")}const Fc=[".sync-metadata.json","__codeyamMocks__"];async function Oc(e,r={}){const{port:n,silent:a=!0}=r,o=ot(e);if(n)try{_e(`lsof -ti:${n} | xargs kill -9 2>/dev/null || true`,{stdio:a?"ignore":"inherit"})}catch{}try{_e(`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 zc(e,r={}){const{killProcesses:n=!0,port:a,silent:o=!0}=r,s=ot(e),i=[],c=[];if(!K.existsSync(s))return{removed:i,errors:c};n&&await Oc(e,{port:a,silent:o});for(const d of Fc){const h=ee.join(s,d);if(K.existsSync(h))try{(await Ie.stat(h)).isDirectory()?await Ie.rm(h,{recursive:!0,force:!0}):await Ie.unlink(h),i.push(d)}catch(u){c.push(`${d}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:c}}const Yc=ee.dirname(Mn(import.meta.url));function Bc(e){let r=e;for(;r!==ee.dirname(r);){const n=ee.join(r,"package.json");if(K.existsSync(n))try{if(JSON.parse(K.readFileSync(n,"utf8")).name==="@codeyam/codeyam-cli")return r}catch{}r=ee.dirname(r)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function On(){const e=Bc(Yc);return ee.join(e,"analyzer-template")}function $t(e){return Qo(e)}async function Ra(e){const r=On(),n=$t(e);if(!K.existsSync(r))throw new Error(`Analyzer template not found at ${r}. Did the build process complete successfully?`);await Ie.mkdir(ee.dirname(n),{recursive:!0}),await Ec({sourcePath:r,destinationPath:n,silent:!0})}function jt(e,r,n,a){const o=$t(e);if(!K.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 Dc({absoluteCodeyamRootPath:o,startEnv:r,startArgs:n,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:s,stderrToConsole:!1,stderrToFile:!0,stderrCallback:s}})}function Uc(e){const r=On(),n=$t(e),a=ee.join(r,".build-info.json"),o=ee.join(n,".build-info.json");if(!K.existsSync(a))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!K.existsSync(n))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!K.existsSync(o))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const s=JSON.parse(K.readFileSync(a,"utf8")),i=JSON.parse(K.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 tr(e,r){const n=$t(e);if(!K.existsSync(n)){r.update("Creating analyzer..."),await Ra(e);return}const a=Uc(e);a.isFresh||(r.update(`Updating analyzer (${a.reason})...`),await Ra(e))}async function zn(e){await zc(e,{killProcesses:!1})}const Wc=ee.dirname(Mn(import.meta.url));function Ko(){let e=Wc;for(;e!==ee.dirname(e);){const r=ee.join(e,"package.json");if(K.existsSync(r))try{if(JSON.parse(K.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=ee.dirname(e)}return null}function Wt(e){if(!K.existsSync(e))return null;try{return JSON.parse(K.readFileSync(e,"utf8"))}catch{return null}}function Hc(){const e=Ko();if(e){const r=[ee.join(e,"src/webserver/build-info.json"),ee.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const n of r){const a=Wt(n);if(a!=null&&a.semanticVersion)return a.semanticVersion}}return"unknown"}const Yn=Hc();function Zo(e){const r=Ko();let n=null;if(r){const d=[ee.join(r,"src/webserver/build-info.json"),ee.join(r,"codeyam-cli/src/webserver/build-info.json")];for(const h of d)if(n=Wt(h),n)break}const a=On(),o=ee.join(a,".build-info.json"),s=Wt(o);let i=null;if(e){const d=$t(e),h=ee.join(d,".build-info.json");i=Wt(h)}let c=!1;return s&&i?c=s.buildTime>i.buildTime:s&&!i&&e&&(c=!0),{cliVersion:Yn,webserverVersion:n,templateVersion:s,cachedAnalyzerVersion:i,isCacheStale:c}}function Lr(e){const r=$t(e),n=ee.join(r,".build-info.json"),a=Wt(n);return(a==null?void 0:a.version)??null}function Xo(){const e=fe();return e?ee.join(e,".codeyam","server.json"):null}function es(){const e=Xo();if(!e||!K.existsSync(e))return null;try{const r=K.readFileSync(e,"utf8");return JSON.parse(r)}catch{return null}}function qc(){const e=Xo();if(e)try{K.unlinkSync(e)}catch{}}const Jc="/assets/globals-CX9f-5xM.css";function Gc({text:e,subtext:r,linkText:n,linkTo:a}){const[o,s]=P(!1);return o?null:t("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:l("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3 flex-1",children:[t("div",{className:"shrink-0",children:t("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:t("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"})})}),l("div",{className:"flex-1",children:[t("p",{className:"text-sm font-medium text-blue-900",children:e}),t("p",{className:"text-xs text-blue-700 mt-0.5",children:r})]}),t(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:n})]}),t("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:t("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:t("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}function Vc({serverVersion:e}){const[r,n]=P("stale"),[a,o]=P(null),s=async()=>{n("restarting"),o(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");n("reconnecting");let c=0;const d=30,h=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}c++,c<d?setTimeout(()=>void u(),h):(o("Server took too long to restart. Please refresh manually."),n("stale"))};setTimeout(()=>void u(),500)}catch(i){o(i instanceof Error?i.message:"Failed to restart server"),n("stale")}};return t("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:t("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:l("div",{className:"flex items-center gap-3 flex-1",children:[t("div",{className:"shrink-0",children:t("svg",{className:"w-5 h-5 text-amber-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:t("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),l("div",{className:"flex-1",children:[r==="stale"&&l(ce,{children:[t("p",{className:"text-sm font-medium text-amber-900",children:"Dashboard server is out of date"}),l("p",{className:"text-xs text-amber-700 mt-0.5",children:["Server version: ",e,". A newer version of CodeYam CLI is installed. Restart the server to get the latest features."]}),a&&t("p",{className:"text-xs text-red-600 mt-1",children:a})]}),r==="restarting"&&l(ce,{children:[t("p",{className:"text-sm font-medium text-amber-900",children:"Restarting server..."}),t("p",{className:"text-xs text-amber-700 mt-0.5",children:"Please wait while the server restarts."})]}),r==="reconnecting"&&l(ce,{children:[t("p",{className:"text-sm font-medium text-amber-900",children:"Reconnecting..."}),t("p",{className:"text-xs text-amber-700 mt-0.5",children:"Waiting for the server to come back online."})]})]}),r==="stale"&&t("button",{type:"button",onClick:()=>void s(),className:"shrink-0 px-4 py-2 bg-amber-600 text-white text-sm font-medium rounded hover:bg-amber-700 transition-colors cursor-pointer",children:"Restart Server"}),(r==="restarting"||r==="reconnecting")&&l("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 text-amber-700 text-sm",children:[l("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("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"})]}),r==="restarting"?"Stopping...":"Reconnecting..."]})]})})})}function Nr(e){return ee.join(e,".codeyam","queue.json")}function Yt(e){const r=Nr(e);if(!K.existsSync(r))return{paused:!1,jobs:[]};try{const n=K.readFileSync(r,"utf8");return JSON.parse(n)}catch(n){return console.error("Failed to load queue state:",n),{paused:!1,jobs:[]}}}function Qc(e,r){const n=Nr(e),a=ee.dirname(n);K.existsSync(a)||K.mkdirSync(a,{recursive:!0});try{K.writeFileSync(n,JSON.stringify(r,null,2),"utf8")}catch(o){throw console.error("Failed to save queue state:",o),o}}async function Kc(e,r,n){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await Zc(e,r,n);else if(e.type==="baseline")await Xc(e,r,n);else if(e.type==="recapture")await ed(e,r,n);else if(e.type==="capture-only")await td(e,r,n);else if(e.type==="debug-setup")await rd(e,r,n);else if(e.type==="interactive-start")await nd(e,r,n);else if(e.type==="interactive-stop")await ad(e,r,n);else throw new Error(`Unknown job type: ${e.type}`);console.log(`[Queue] Job ${e.id} completed successfully`)}catch(a){throw console.error(`[Queue] Job ${e.id} failed:`,a),a}}async function Zc(e,r,n){var g,b,w,x;const{projectSlug:a,commitSha:o,entityShas:s}=e;if(!o)throw new Error("Analysis job missing commitSha");const i=s||[],{project:c}=await Fe(a);await zn(a),await tr(a,{update:v=>console.log(`[Queue] ${v}`)});const d=Lr(a),h={...await ft(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:o,CODEYAM_LOCAL_PROJECT_PATH:r,SQLITE_PATH:gt(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...d?{ANALYZER_VERSION:d}:{}},u=(b=(g=c.metadata)==null?void 0:g.webapps)==null?void 0:b[0];if(!u)throw new Error("No webapps found in project metadata");const m=e.onlyDataStructure,p={packageManager:((w=c.metadata)==null?void 0:w.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:0,noServer:!0,framework:u.framework,...m?{}:{orchestrateCapture:"local-sequential"}},f=jt(a,h,p),y=v=>{try{return process.kill(v,0),!0}catch{return!1}};await ct({commitSha:o,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((x=e.filePaths)==null?void 0:x.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:f.process.pid}}),n==null||n.notifyChange("commit");try{try{const v=new Promise((C,k)=>setTimeout(()=>k(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,v]),await ct({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),n==null||n.notifyChange("commit"),await ct({commitSha:o,runStatusUpdate:{currentEntityShas:[]}}),n==null||n.notifyChange("commit"),await new Promise(C=>setTimeout(C,2e3))}finally{if(f.process.pid)try{y(f.process.pid)&&await Jt(f.process.pid,()=>{})}catch{}}}catch(v){if(console.error(`[Queue] Analysis job ${e.id} failed:`,v),f.process.pid&&y(f.process.pid))try{await Jt(f.process.pid,()=>{})}catch{}try{await ct({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:v instanceof Error?v.message:String(v)}}),n==null||n.notifyChange("commit")}catch(C){console.error("[Queue] Failed to update commit metadata after job failure:",C)}throw v}}async function Xc(e,r,n){var p,f,y;const{projectSlug:a,commitSha:o}=e;if(!o)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${a}`);const{project:s}=await Fe(a);await zn(a),await tr(a,{update:g=>console.log(`[Queue] ${g}`)});const i=Lr(a),c={...await ft(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:o,CODEYAM_LOCAL_PROJECT_PATH:r,SQLITE_PATH:gt(),...i?{ANALYZER_VERSION:i}:{}},d=(f=(p=s.metadata)==null?void 0:p.webapps)==null?void 0:f[0];if(!d)throw new Error("No webapps found in project metadata");const h={packageManager:((y=s.metadata)==null?void 0:y.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:0,noServer:!0,framework:d.framework,orchestrateCapture:"local-sequential"},u=jt(a,c,h),m=g=>{try{return process.kill(g,0),!0}catch{return!1}};await ct({commitSha:o,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:u.process.pid}}),n==null||n.notifyChange("commit");try{const g=new Promise((b,w)=>setTimeout(()=>w(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([u.promise,g]),await ct({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),n==null||n.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${a}`),await new Promise(b=>setTimeout(b,2e3))}finally{if(u.process.pid)try{m(u.process.pid)&&await Jt(u.process.pid,()=>{})}catch{}}}async function ed(e,r,n){var f,y,g,b;const{projectSlug:a,analysisId:o,scenarioId:s,defaultWidth:i}=e;if(!o)throw new Error("Recapture job missing analysisId");const c=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${o} not found`);if(i){const{getDatabase:w}=await import("./index-TD1f-DHV.js"),x=w(),v=await x.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let C={};v!=null&&v.metadata&&(typeof v.metadata=="string"?C=JSON.parse(v.metadata):C=v.metadata),C.defaultWidth=i,await x.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",c.entitySha).execute()}await Tt(o,w=>{if(w.readyToBeCaptured=!0,w.scenarios)for(const x of w.scenarios)(!s||x.name===s)&&(delete x.finishedAt,delete x.startedAt,delete x.screenshotStartedAt,delete x.screenshotFinishedAt,delete x.interactiveStartedAt,delete x.interactiveFinishedAt,delete x.error,delete x.errorStack);delete w.finishedAt});const{project:d}=await Fe(a);await tr(a,{update:w=>console.log(`[Queue] ${w}`)});const h=Lr(a),u={...await ft(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:r,SQLITE_PATH:gt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,...s?{SCENARIO_IDS:s}:{},...h?{ANALYZER_VERSION:h}:{}},m={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!0,framework:((b=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:b.framework)??Xt.Next,orchestrateCapture:"local-sequential"},p=jt(a,u,m);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function td(e,r,n){var f,y,g,b;const{projectSlug:a,analysisId:o,scenarioId:s,defaultWidth:i}=e;if(!o)throw new Error("Capture-only job missing analysisId");const c=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${o} not found`);if(i){const{getDatabase:w}=await import("./index-TD1f-DHV.js"),x=w(),v=await x.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let C={};v!=null&&v.metadata&&(typeof v.metadata=="string"?C=JSON.parse(v.metadata):C=v.metadata),C.defaultWidth=i,await x.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",c.entitySha).execute()}await Tt(o,w=>{if(w.readyToBeCaptured=!0,w.scenarios)for(const x of w.scenarios)(!s||x.name===s)&&(delete x.finishedAt,delete x.startedAt,delete x.screenshotStartedAt,delete x.screenshotFinishedAt,delete x.interactiveStartedAt,delete x.interactiveFinishedAt,delete x.error,delete x.errorStack);delete w.finishedAt});const{project:d}=await Fe(a);await tr(a,{update:w=>console.log(`[Queue] ${w}`)});const h=Lr(a);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await ft(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:r,SQLITE_PATH:gt(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:o,...s?{SCENARIO_IDS:s}:{},...h?{ANALYZER_VERSION:h}:{}},m={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!0,fast:!0,framework:((b=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:b.framework)??Xt.Next,orchestrateCapture:"local-sequential"},p=jt(a,u,m);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function rd(e,r,n){var p,f,y,g;const{projectSlug:a,analysisId:o,scenarioId:s}=e;if(!o)throw new Error("Debug setup job missing analysisId");const i=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${o} not found`);const{project:c}=await Fe(a);await zn(a),await tr(a,{update:b=>console.log(`[Queue] ${b}`)});const d={...await ft(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:r,SQLITE_PATH:gt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,PREP_ONLY:"true"};s&&(d.SCENARIO_IDS=s);const h={packageManager:((p=c.metadata)==null?void 0:p.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!1,framework:((g=(y=(f=c.metadata)==null?void 0:f.webapps)==null?void 0:y[0])==null?void 0:g.framework)||Xt.Next},m=await jt(a,d,h).promise;if(m!==0)throw new Error(`Prep process exited with code ${m}`)}async function nd(e,r,n){var m,p,f,y;const{projectSlug:a,analysisId:o,scenarioId:s}=e;if(!o)throw new Error("Interactive start job missing analysisId");const i=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${o} not found`);const{project:c}=await Fe(a),d={...await ft(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:r,SQLITE_PATH:gt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,INTERACTIVE_MODE:"true"};s&&(d.SCENARIO_IDS=s);const h={packageManager:((m=c.metadata)==null?void 0:m.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!1,framework:((y=(f=(p=c.metadata)==null?void 0:p.webapps)==null?void 0:f[0])==null?void 0:y.framework)||Xt.Next};await Tt(o,g=>{g.readyToBeCaptured=!0});const u=jt(a,d,h);await jo(o,g=>{g.interactiveMode={pid:u.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${o}, PID: ${u.process.pid}`)}async function ad(e,r,n){var d;const{projectSlug:a,analysisId:o}=e;if(!o)throw new Error("Interactive stop job missing analysisId");const s=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw new Error(`Analysis ${o} not found`);const i=(d=s.metadata)==null?void 0:d.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${o}`);return}const c=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${o}, killing PID: ${c}`);try{try{process.kill(c,0)}catch{console.log(`[Queue] Process ${c} already exited`);return}await Jt(c,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${c}`)}catch(h){throw console.error(`[Queue] Failed to kill process ${c}:`,h),h}finally{await jo(o,h=>{h.interactiveMode=null})}}class od{constructor(r,n){this.processing=!1,this.completionCallbacks=new Map,this.completedJobs=new Map,this.projectRoot=r,this.state={paused:!1,jobs:[]},n&&(typeof n=="function"?this.notifier={notifyChange:()=>n()}:this.notifier=n)}start(){this.state=Yt(this.projectRoot),this.state.jobs.length>0?(this.state.currentlyExecuting&&(console.log(`[Queue] Clearing stale currentlyExecuting job from previous session: ${this.state.currentlyExecuting.id}`),this.state.currentlyExecuting=void 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(r){const n=r.commitSha||Kt(),a={...r,id:n,queuedAt:new Date().toISOString()};this.state.jobs.push(a),this.save(),console.log(`[Queue] Enqueued job ${n} (${a.type})`);const o=new Promise((s,i)=>{this.completionCallbacks.set(n,c=>{c?i(c):s()})});return this.state.paused||this.processNext().catch(s=>{console.error("[Queue] ERROR in processNext():",s)}),{jobId:n,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(r){return this.completedJobs.get(r)}removeJob(r){const n=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(o=>o.id!==r);const a=this.state.jobs.length<n;if(a){console.log(`[Queue] Removed job ${r}`),this.save();const o=this.completionCallbacks.get(r);o&&(setImmediate(()=>o(new Error("Job cancelled by user"))),this.completionCallbacks.delete(r))}else console.log(`[Queue] Job ${r} not found in queue`);return a}clearQueue(){const r=this.state.jobs.length;return r===0?0:(this.state.jobs.forEach(n=>{const a=this.completionCallbacks.get(n.id);a&&(setImmediate(()=>a(new Error("Job cancelled by user"))),this.completionCallbacks.delete(n.id))}),this.state.jobs=[],console.log(`[Queue] Cleared ${r} jobs`),this.save(),r)}reorderJob(r,n){const a=this.state.jobs.findIndex(i=>i.id===r);if(a===-1)return console.log(`[Queue] Job ${r} not found in queue`),!1;const o=n==="up"?a-1:a+1;if(o<0||o>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${r} ${n}: at boundary`),!1;const s=this.state.jobs[a];return this.state.jobs[a]=this.state.jobs[o],this.state.jobs[o]=s,console.log(`[Queue] Moved job ${r} ${n} (position ${a} -> ${o})`),this.save(),!0}async processNext(){if(this.state.paused||this.processing)return;if(this.state.jobs.length===0){console.log("[Queue] No jobs to process");return}this.processing=!0;const r=this.state.jobs[0];console.log(`[Queue] Starting job ${r.id} (${r.type})`);try{this.state.currentlyExecuting=this.state.jobs.shift(),this.save(),await Kc(r,this.projectRoot,this.notifier),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(r.id,{id:r.id,status:"success",completedAt:new Date().toISOString()});const n=this.completionCallbacks.get(r.id);n&&(n(),this.completionCallbacks.delete(r.id)),console.log(`[Queue] Job ${r.id} completed successfully`)}catch(n){console.error(`[Queue] Job ${r.id} failed:`,n),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(r.id,{id:r.id,status:"error",error:(n==null?void 0:n.message)||"Unknown error",completedAt:new Date().toISOString()});const a=this.completionCallbacks.get(r.id);a&&(a(n),this.completionCallbacks.delete(r.id))}finally{this.processing=!1,!this.state.paused&&this.state.jobs.length>0&&setImmediate(()=>void this.processNext())}}save(){Qc(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class sd{constructor(r,n,a=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=r,this.onChange=n,this.debounceMs=a}start(){const r=Nr(this.projectRoot);if(!K.existsSync(r)){console.log("[QueueFileWatcher] Queue file does not exist yet, will start watching when created"),this.watchDirectory();return}this.watchFile(r)}watchDirectory(){const r=Nr(this.projectRoot),n=r.substring(0,r.lastIndexOf("/"));try{this.watcher=K.watch(n,(a,o)=>{o==="queue.json"&&(this.stop(),this.watchFile(r),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(a){console.error("[QueueFileWatcher] Failed to watch directory:",a)}}watchFile(r){try{this.watcher=K.watch(r,n=>{n==="change"&&this.notifyChange()}),console.log("[QueueFileWatcher] Watching queue.json for changes")}catch(n){console.error("[QueueFileWatcher] Failed to watch queue file:",n)}}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 id{constructor(r,n,a){this.fileWatcher=null,this.serverInfo=r,this.projectRoot=n,this.onStateChange=a,this.cachedState=Yt(n)}start(){this.cachedState=Yt(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 sd(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(r){let n,a;const o=new Promise((i,c)=>{n=i,a=c}),s=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(r).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),n()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),a(i)}),{jobId:s,completion:o}}async enqueueRemote(r){const n=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...r})});if(!n.ok){const a=await n.text();throw new Error(`Failed to enqueue: ${n.status} ${a}`)}return n.json()}resume(){console.log("[ProxyQueue] Sending resume command to background server"),this.sendAction("resume").catch(r=>{console.error("[ProxyQueue] Failed to resume:",r)})}pause(){console.log("[ProxyQueue] Sending pause command to background server"),this.sendAction("pause").catch(r=>{console.error("[ProxyQueue] Failed to pause:",r)})}async sendAction(r){const n=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:r})});if(!n.ok){const a=await n.text();throw new Error(`Failed to ${r}: ${n.status} ${a}`)}this.refreshState()}getState(){return this.cachedState=Yt(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=Yt(this.projectRoot),this.onStateChange&&this.onStateChange()}async isServerAlive(){try{const r=new AbortController,n=setTimeout(()=>r.abort(),2e3),a=await fetch(`${this.serverInfo.url}/api/health`,{signal:r.signal});return clearTimeout(n),a.ok}catch{return!1}}getServerInfo(){return{...this.serverInfo}}stop(){this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null)}}function ld(e){const r=ee.join(e,".codeyam","server.json");if(!K.existsSync(r))return null;try{const n=K.readFileSync(r,"utf8");return JSON.parse(n)}catch{return null}}function cd(e){try{return process.kill(e,0),!0}catch{return!1}}async function dd(e){try{const r=new AbortController,n=setTimeout(()=>r.abort(),2e3),a=await fetch(`${e}/api/health`,{signal:r.signal});return clearTimeout(n),a.ok}catch{return!1}}async function ud(e){const r=ld(e);return!r||!cd(r.pid)||!await dd(r.url)?null:{url:r.url,port:r.port,pid:r.pid}}class hd extends Bi{constructor(){super();sr(this,"watcher",null);sr(this,"dbPath",null);sr(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=gt();const{default:n}=await import("chokidar"),a=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=n.watch(a,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",o=>{const s=Date.now(),i=new Date(s).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${o}`),console.log(`[dbNotifier] Timestamp: ${i} (${s})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:s})}).on("error",o=>{console.error("Database watcher error:",o),this.emit("error",o)}),this.isWatching=!0}catch(n){console.error("Failed to start database watcher:",n),this.emit("error",n)}}notifyChange(n="unknown"){const a=Date.now(),o=new Date(a).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${n}`),console.log(`[dbNotifier] Timestamp: ${o} (${a})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:n,timestamp:a})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const fn=new hd;let vt=null,Bt=null;async function md(){if(!vt){if(Bt){await Bt;return}Bt=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||Ro()||process.cwd();yc(e),console.log(`[GlobalQueue] Project root: ${e}`);const r=await ud(e);if(r){console.log(`[GlobalQueue] Detected background server at ${r.url} (PID: ${r.pid})`),console.log("[GlobalQueue] Using proxy queue");const n=new id(r,e,()=>{fn.notifyChange("unknown")});await n.start(),vt=n}else{console.log("[GlobalQueue] No background server detected, using local queue");const n=new od(e,fn);await n.start(),vt=n}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Bt}}async function st(){return vt||await md(),vt}function pd(){return vt||(Bt&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const fd=()=>[{rel:"stylesheet",href:Jc},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}];async function gd({request:e,context:r}){var n,a,o,s,i,c,d;try{const h=fe()||process.cwd(),[u,m]=await Promise.all([ze(),Rr(h)]);if(!u)throw new Error("Project slug not found");const{project:p,branch:f}=await Fe(u),y=await br({projectId:p.id,branchId:f.id,limit:20,skipRelations:!0}),g=y.length>0?y[0]:null,b=r.analysisQueue||pd(),w=b==null?void 0:b.getState(),x=async U=>{if(!U||U.length===0)return[];const B=Math.min(Math.max(U.length*2e3,1e4),6e4),D=new Promise(_=>setTimeout(()=>{console.warn(`[Loader] Entity fetch timeout after ${B}ms for ${U.length} entities`),_([])},B)),L=ht({shas:U,excludeMetadata:!0}).then(_=>_||[]);return Promise.race([L,D])},v=await Promise.all(((w==null?void 0:w.jobs)||[]).map(async U=>{var D;const B=await x(U.entityShas||[]);return B.length===0&&((D=U.entityShas)!=null&&D.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",U.id),{...U,entities:B}}));let C=null;if(w!=null&&w.currentlyExecuting){const U=w.currentlyExecuting,B=await x(U.entityShas||[]);B.length===0&&((n=U.entityShas)!=null&&n.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",U.id),C={...U,entities:B}}const k=C?v.filter(U=>U.id!==C.id):v;let N=((o=(a=g==null?void 0:g.metadata)==null?void 0:a.currentRun)==null?void 0:o.currentEntityShas)||[];if(N.length===0){const U=((s=g==null?void 0:g.metadata)==null?void 0:s.historicalRuns)||[];if(U.length>0){const D=[...U].sort((L,_)=>{const S=L.archivedAt||L.createdAt||"";return(_.archivedAt||_.createdAt||"").localeCompare(S)})[0];if(D){const L=D.analysisCompletedAt||D.createdAt;if(L){const _=new Date(L).getTime(),F=Date.now()-1440*60*1e3;_>F&&(N=D.currentEntityShas||[])}}}}const E=await x(N),A=[];m.ANTHROPIC_API_KEY&&A.push("ANTHROPIC_API_KEY"),m.GROQ_API_KEY&&A.push("GROQ_API_KEY"),m.OPENAI_API_KEY&&A.push("OPENAI_API_KEY"),m.OPENROUTER_API_KEY&&A.push("OPENROUTER_API_KEY");const I=[];for(const U of y){const B=((i=U.metadata)==null?void 0:i.historicalRuns)||[];for(const D of B){const L=D.currentEntityShas||[];if(L.length>0){const _=await x(L);I.push({...D,entities:_})}else I.push(D)}}const j=I.sort((U,B)=>{const D=U.archivedAt||U.analysisCompletedAt||U.createdAt||"";return(B.archivedAt||B.analysisCompletedAt||B.createdAt||"").localeCompare(D)}),R=new Set(((c=C==null?void 0:C.entities)==null?void 0:c.map(U=>U.sha))||[]),M=j.filter(U=>!(U.currentEntityShas||[]).some(D=>R.has(D))),T=es(),$=(T==null?void 0:T.cliVersion)??"unknown",z=$!=="unknown"&&$!==Yn,G={currentRun:(d=g==null?void 0:g.metadata)==null?void 0:d.currentRun,projectSlug:u,currentEntities:E,availableAPIKeys:A,queuedJobCount:k.length,queueJobs:k,currentlyExecuting:C,historicalRuns:M,isServerOutOfDate:z,serverVersion:$};return J(G)}catch(h){return console.error("Failed to load root data:",h),J({currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[],isServerOutOfDate:!1,serverVersion:"unknown"})}}function yd(){const{currentRun:e,projectSlug:r,currentEntities:n,availableAPIKeys:a,queuedJobCount:o,queueJobs:s,currentlyExecuting:i,historicalRuns:c,isServerOutOfDate:d,serverVersion:h}=We(),{toasts:u,closeToast:m}=$n(),p=rt(),f=Ee(p),y=Pr();te(()=>{f.current=p},[p]);const g=y.pathname.startsWith("/entity/")&&y.pathname.includes("/edit/")||y.pathname.startsWith("/dev/"),b=y.pathname.includes("/fullscreen");return te(()=>{const w=new EventSource("/api/events");let x=null,v=0;const C=2e3;return w.addEventListener("message",k=>{const N=JSON.parse(k.data);if(N.type==="queue")f.current.revalidate(),v=Date.now();else if(N.type==="db-change"||N.type==="unknown"){const E=Date.now(),A=E-v;A<C?(x&&clearTimeout(x),x=setTimeout(()=>{f.current.revalidate(),v=Date.now(),x=null},C-A)):(f.current.revalidate(),v=E)}}),w.addEventListener("error",k=>{console.error("SSE connection error:",k)}),()=>{x&&clearTimeout(x),w.close()}},[]),l(ce,{children:[l("div",{className:`min-h-screen ${g?"":"grid"} bg-cygray-10`,style:g?void 0:{gridTemplateColumns:"65px minmax(900px, 1fr)"},children:[!g&&t(cl,{}),l("div",{className:"max-h-screen overflow-auto bg-cygray-10",children:[d&&t(Vc,{serverVersion:h}),a.length===0&&t(Gc,{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"}),t(Qs,{})]})]}),t(hl,{toasts:u,onClose:m}),!b&&t(ml,{currentRun:e,projectSlug:r,currentEntities:n,isAnalysisStarting:!1,queuedJobCount:o,queueJobs:s,currentlyExecuting:i,historicalRuns:c})]})}const xd=Oe(function(){return l("html",{lang:"en",children:[l("head",{children:[t("meta",{charSet:"utf-8"}),t("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),t(qs,{}),t(Js,{})]}),l("body",{children:[t(dl,{children:t(il,{children:t(yd,{})})}),t(Gs,{}),t(Vs,{})]})]})}),bd=Object.freeze(Object.defineProperty({__proto__:null,default:xd,links:fd,loader:gd},Symbol.toStringTag,{value:"Module"}));function Da(e){const r=e.replace(/[^a-zA-Z0-9_]+/g,"_");return r.slice(0,1).toUpperCase()+r.slice(1)}function rr({analysisId:e,scenarioId:r,scenarioName:n,projectSlug:a,enabled:o=!0,refreshTrigger:s=0}){const i=Ae(),[c,d]=P(null),[h,u]=P(!1),[m,p]=P(!1),[f,y]=P(!1),g=Ee(!1),b=Ee(null),w=Ee(null),[x,v]=P(0),[C,k]=P(0),N=Ee(null),E=Ee(!1),{interactiveUrl:A,resetLogs:I}=pt(a,o),j=Ee(r),R=Ee(s);te(()=>{R.current!==s&&(R.current=s,c&&(console.log("[useInteractiveMode] Manual refresh triggered"),p(!0),y(!1),v(0),k(T=>T+1),E.current=!1,N.current&&(clearTimeout(N.current),N.current=null)))},[s,c]),te(()=>{if(j.current!==r&&(j.current=r,b.current&&w.current&&n)){const T=Da(w.current),$=Da(n),z=b.current.replace(T,$);d(z),p(!0),y(!1),v(0),k(G=>G+1),E.current=!1,N.current&&(clearTimeout(N.current),N.current=null);return}},[r,n]),te(()=>{if(A){const T=A+"?width=600px";b.current=T,n&&(w.current=n),d(T),u(!1),p(!0)}},[A]),te(()=>{const T=$=>{$.data.type==="codeyam-resize"&&(E.current||(E.current=!0,N.current&&(clearTimeout(N.current),N.current=null),v(0),y(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{p(!1)})})))};return window.addEventListener("message",T),()=>window.removeEventListener("message",T)},[]);const M=()=>{E.current=!1,N.current&&clearTimeout(N.current);const T=500*Math.pow(2,x);N.current=setTimeout(()=>{E.current||(x<2?(v($=>$+1),k($=>$+1),p(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),y(!0),p(!1)))},T)};return te(()=>{o&&!g.current&&r&&e&&(g.current=!0,u(!0),y(!1),d(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch($){console.error("[useInteractiveMode] Failed to clear log file:",$)}I(),i.submit({action:"start",analysisId:e,scenarioId:r},{method:"post",action:"/api/interactive-mode"})})())},[o,r,e,I,a]),te(()=>{const T=e,$=()=>{if(g.current&&T){const G=new URLSearchParams({action:"stop",analysisId:T});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const U=navigator.sendBeacon("/api/interactive-mode",G);console.log("[useInteractiveMode] sendBeacon result:",U),U||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:G,keepalive:!0}).catch(B=>console.error("Failed to stop interactive mode:",B)))}},z=()=>{$()};return window.addEventListener("beforeunload",z),()=>{window.removeEventListener("beforeunload",z),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:g.current,analysisId:T}),$()}},[e]),{interactiveServerUrl:c,isStarting:h,isLoading:m,showIframe:f,iframeKey:C,onIframeLoad:M}}const lr=10,wd=1024;function ts({currentViewportWidth:e,currentPresetName:r,onDevicePresetClick:n,devicePresets:a,onHoverChange:o,hideLabel:s=!1,lightMode:i=!1}){const[c,d]=P(null),h=Ee(null),u=ne(()=>[...a].sort((x,v)=>x.width-v.width),[a]),{fittingPresets:m,overflowPresets:p}=ne(()=>{const x=[],v=[];for(const C of u)C.width<=wd?x.push(C):v.push(C);return v.sort((C,k)=>k.width-C.width),{fittingPresets:x,overflowPresets:v}},[u]),f=se(x=>{if(!h.current)return null;const v=h.current.getBoundingClientRect(),C=x-v.left,k=v.width,N=k/2,A=(m.length>0?m[m.length-1].width:0)/2,I=N-A,j=N+A,R=p.length>0?(p.length-1)*lr:0;if(p.length>0){if(C<I){if(C<=R){const T=Math.min(Math.floor(C/lr),p.length-1);return p[T]}return p[p.length-1]}if(C>j){const T=k-C;if(T<=R){const $=Math.min(Math.floor(T/lr),p.length-1);return p[$]}return p[p.length-1]}}const M=Math.abs(C-N);for(let T=m.length-1;T>=0;T--){const $=m[T],z=m[T-1],G=$.width/2,U=z?z.width/2:0;if(M<=G&&M>=U)return $}return m[0]||p[p.length-1]||null},[m,p]),y=se(x=>{const v=f(x.clientX);d(v),o==null||o(v)},[f,o]),g=se(()=>{d(null),o==null||o(null)},[o]),b=se(x=>{const v=f(x.clientX);v&&n(v)},[f,n]),w=c||{name:r,width:e};return l("div",{ref:h,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:y,onMouseLeave:g,onClick:b,children:[c&&t("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:t("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${c.width}px`}})}),t("div",{className:"absolute inset-0 pointer-events-none",children:m.map(x=>{const v=x.width===e,C=(c==null?void 0:c.name)===x.name,k=x.width/2;return l("div",{children:[t("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${k}px)`},children:t("div",{className:`w-0.5 h-full transition-colors duration-75 ${v||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),t("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${k}px)`},children:t("div",{className:`w-0.5 h-full transition-colors duration-75 ${v||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},x.name)})}),t("div",{className:"absolute inset-0 pointer-events-none",children:p.map((x,v)=>{const C=v*lr,k=x.width===e,N=(c==null?void 0:c.name)===x.name;return l("div",{children:[t("div",{className:"absolute top-0 bottom-0",style:{left:`${C}px`},children:t("div",{className:`w-0.5 h-full transition-colors duration-75 ${k||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),t("div",{className:"absolute top-0 bottom-0",style:{right:`${C}px`},children:t("div",{className:`w-0.5 h-full transition-colors duration-75 ${k||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},x.name)})}),!s&&t("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:l("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${c?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[w.name," - ",w.width,"px"]})})]})}function rs({width:e,height:r,onSave:n,onCancel:a}){const[o,s]=P(""),[i,c]=P(""),d=()=>{const u=o.trim();if(!u){c("Please enter a name for this custom size");return}n(u)};return t("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:l("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[l("div",{className:"flex items-center justify-between mb-6",children:[t("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),t("button",{onClick:a,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:t("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),l("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[t("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),l("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",r,"px"]})]}),l("div",{className:"mb-6",children:[t("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),t("input",{id:"custom-size-name",type:"text",value:o,onChange:u=>{s(u.target.value),c("")},onKeyDown:u=>{u.key==="Enter"&&o.trim()&&d(),u.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&&t("p",{className:"mt-1 text-sm text-red-600",children:i})]}),l("div",{className:"flex gap-3 justify-end",children:[t("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"}),t("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 ns(e){const[r,n]=P([]),a=e?`codeyam-custom-sizes-${e}`:null;te(()=>{if(!a||typeof window>"u"){n([]);return}try{const c=localStorage.getItem(a);if(c){const d=JSON.parse(c);Array.isArray(d)&&n(d)}}catch(c){console.error("[useCustomSizes] Failed to load custom sizes:",c),n([])}},[a]);const o=se(c=>{if(!(!a||typeof window>"u"))try{localStorage.setItem(a,JSON.stringify(c))}catch(d){console.error("[useCustomSizes] Failed to save custom sizes:",d)}},[a]),s=se((c,d,h)=>{n(u=>{const m=u.findIndex(y=>y.name===c),p={name:c,width:d,height:h};let f;return m>=0?(f=[...u],f[m]=p):f=[...u,p],o(f),f})},[o]),i=se(c=>{n(d=>{const h=d.filter(u=>u.name!==c);return o(h),h})},[o]);return{customSizes:r,addCustomSize:s,removeCustomSize:i}}function Sr(){return l("div",{className:"spinner-container",children:[t("span",{className:"loader"}),t("style",{children:`
|
|
40
|
+
.loader {
|
|
41
|
+
width: 48px;
|
|
42
|
+
height: 48px;
|
|
43
|
+
border: 3px solid rgba(0, 92, 117, 0.2);
|
|
44
|
+
border-radius: 50%;
|
|
45
|
+
display: inline-block;
|
|
46
|
+
position: relative;
|
|
47
|
+
box-sizing: border-box;
|
|
48
|
+
animation: rotation 1s linear infinite;
|
|
49
|
+
}
|
|
50
|
+
.loader::after {
|
|
51
|
+
content: '';
|
|
52
|
+
box-sizing: border-box;
|
|
53
|
+
position: absolute;
|
|
54
|
+
left: 50%;
|
|
55
|
+
top: 50%;
|
|
56
|
+
transform: translate(-50%, -50%);
|
|
57
|
+
width: 56px;
|
|
58
|
+
height: 56px;
|
|
59
|
+
border-radius: 50%;
|
|
60
|
+
border: 3px solid;
|
|
61
|
+
border-color: #005c75 transparent;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
@keyframes rotation {
|
|
65
|
+
0% {
|
|
66
|
+
transform: rotate(0deg);
|
|
67
|
+
}
|
|
68
|
+
100% {
|
|
69
|
+
transform: rotate(360deg);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
`})]})}const La=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],vd=80;function Er(){const[e,r]=P(0);return te(()=>{const n=setInterval(()=>{r(a=>(a+1)%La.length)},vd);return()=>clearInterval(n)},[]),t("span",{className:"inline-block mr-2",children:La[e]})}async function Cd({params:e}){var c;const{sha:r,scenarioId:n}=e;if(!r||!n)throw J("Invalid parameters",{status:400});const a=await Mt(r);if(!a)throw J("Entity not found",{status:404});const o=await Ln(a),s=((c=o==null?void 0:o.scenarios)==null?void 0:c.find(d=>d.id===n))||null;if(!s)throw J("Scenario not found",{status:404});const i=await ze();return J({entity:a,scenario:s,analysis:o,projectSlug:i})}const nn=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],Nd=Oe(function(){const{entity:r,scenario:n,analysis:a,projectSlug:o}=We(),s=_t(),[i]=Qt(),[c,d]=P(null),[h,u]=P(1440),[m,p]=P({name:"Desktop",width:1440,height:900}),[f,y]=P(!1),[g,b]=P(null),{customSizes:w,addCustomSize:x}=ns(o),v=ne(()=>[...nn,...w],[w]),{interactiveServerUrl:C,isStarting:k,isLoading:N,showIframe:E,iframeKey:A,onIframeLoad:I}=rr({analysisId:a==null?void 0:a.id,scenarioId:n==null?void 0:n.id,scenarioName:n==null?void 0:n.name,projectSlug:o,enabled:!0}),{lastLine:j}=pt(o,k||N),R=()=>{s(`/entity/${r.sha}`)},M=(O,H)=>{u(O);const ae=v.find(Y=>Y.width===O&&Y.height===H);d(ae||null),p({name:(ae==null?void 0:ae.name)||"Custom",width:O,height:H})},T=O=>{d(O),u(O.width),p({name:O.name,width:O.width,height:O.height})},$=O=>{x(O,m.width,m.height??900),y(!1),p(H=>({...H,name:O}))},z=((a==null?void 0:a.scenarios)||[]).filter(O=>{var H;return!((H=O.metadata)!=null&&H.sameAsDefault)}),G=z.findIndex(O=>O.id===(n==null?void 0:n.id)),U=G+1,B=z.length,D=G>0,L=G<z.length-1,_=()=>{if(D){const O=z[G-1],H=encodeURIComponent(`/entity/${r.sha}/scenarios/${O.id}/fullscreen`);s(`/entity/${r.sha}/scenarios/${O.id}/fullscreen?from=${H}`)}},S=()=>{if(L){const O=z[G+1],H=encodeURIComponent(`/entity/${r.sha}/scenarios/${O.id}/fullscreen`);s(`/entity/${r.sha}/scenarios/${O.id}/fullscreen?from=${H}`)}},F=k||N||!E;return l("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[l("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[t("img",{src:vo,alt:"CodeYam",className:"h-6 brightness-0 invert"}),t("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:r.name}),l("div",{className:"flex items-center gap-2 shrink-0",children:[t("button",{onClick:_,disabled:!D,className:`${D?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:t("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:t("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),l("span",{className:"text-gray-400 text-sm",children:[U,"/",B]}),t("button",{onClick:S,disabled:!L,className:`${L?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:t("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:t("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),l("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[t("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:n==null?void 0:n.name}),(n==null?void 0:n.description)&&l("div",{className:"relative group min-w-0",children:[t("span",{className:"text-gray-400 text-xs truncate block",children:n.description}),t("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:n.description})]})]})]}),t("button",{onClick:R,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:t("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:t("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),l("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[t("div",{className:"absolute inset-0 flex justify-center",children:t("div",{style:{maxWidth:`${nn[nn.length-1].width}px`,width:"100%"},children:t(ts,{currentViewportWidth:h,currentPresetName:m.name,onDevicePresetClick:T,devicePresets:v,hideLabel:!0,onHoverChange:b,lightMode:!0})})}),l("div",{className:"relative z-10 flex items-center gap-2",children:[l("div",{className:"relative w-28 h-5",children:[l("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[t("span",{className:"leading-none",children:(g==null?void 0:g.name)||m.name}),t("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:t("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l("select",{value:m.name,onChange:O=>{const H=v.find(ae=>ae.name===O.target.value);H&&T(H)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[v.map(O=>t("option",{value:O.name,children:O.name},O.name)),m.name==="Custom"&&t("option",{value:"Custom",children:"Custom"})]})]}),t("input",{type:"number",value:m.width,onChange:O=>{const H=parseInt(O.target.value,10);!isNaN(H)&&H>0&&M(H,m.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),t("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),t("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:m.height??900}),m.name==="Custom"&&t("button",{onClick:()=>y(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),t("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
|
|
73
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
74
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
75
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
76
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
77
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:C?l("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${m.width}px`,maxHeight:`${m.height}px`},children:[F&&t("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[t("div",{className:"mb-4",children:t(Sr,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[t("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),t("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),j&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[t(Er,{}),j]})]})]})}),t("iframe",{src:C,className:"w-full h-full border-none",title:`Interactive preview: ${n==null?void 0:n.name}`,onLoad:I,style:{opacity:E?1:0}},A)]}):l("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[t("div",{className:"mb-4",children:t(Sr,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[t("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),t("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),j&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[t(Er,{}),j]})]})]})}),f&&t(rs,{width:m.width,height:m.height??900,onSave:$,onCancel:()=>y(!1)})]})}),Sd=Object.freeze(Object.defineProperty({__proto__:null,default:Nd,loader:Cd},Symbol.toStringTag,{value:"Module"})),as=Cn({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),Bn=()=>{const e=Mr(as);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},Fr=({children:e})=>{const[r,n]=P({height:720,width:1200}),[a,o]=P(1),[s,i]=P(1200),c=Ee(null),d=se(({height:m,width:p})=>{n(f=>({height:m??f.height,width:p??f.width}))},[]),h=se(m=>{o(m)},[]),u=se(m=>{i(m)},[]);return t(as.Provider,{value:{dimensions:r,updateDimensions:d,iframeRef:c,scale:a,updateScale:h,maxWidth:s,updateMaxWidth:u},children:e})},Ed=typeof window<"u";function Ad(){const[e,r]=P(null);return te(()=>{import("react-resizable").then(n=>{r(()=>n.ResizableBox)}),Promise.resolve({ })},[]),e}const kd=1200,Pd=720,Fa=30,Md=({id:e,scenarioName:r,iframeUrl:n,defaultWidth:a=1440,defaultHeight:o=900,onDataOverride:s,onIframeLoad:i,onScaleChange:c,onDimensionChange:d})=>{const h=Ad(),[u,m]=P(!1),[p,f]=P(!1),[y,g]=P(kd),[b,w]=P(Pd),[x,v]=P(null),[C,k]=P(null),{dimensions:N,updateDimensions:E,iframeRef:A,updateScale:I,updateMaxWidth:j}=Bn(),R=ne(()=>Math.min(1,y/N.width),[y,N.width]),M=C!==null?C:R;te(()=>{u||(I(M),c==null||c(M))},[M,I,c,u]),te(()=>{j(y)},[y,j]);const T=se(()=>{m(!0),k(R)},[R]),$=se(()=>{m(!1),k(null)},[]),z=se((L,_)=>{const S=C!==null?C:1,F=Math.round(_.size.width/S);E({width:F}),d==null||d(F,N.height)},[E,C,d,N.height]),G=se(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);te(()=>{const L=_=>{if(_.data.type==="codeyam-resize"){if(r&&_.data.name!==r||N.height===_.data.height||_.data.height===0)return;E({height:_.data.height})}};return window.addEventListener("message",L),()=>{window.removeEventListener("message",L)}},[A,r,a,N,E]),te(()=>{p&&s&&s(A.current)},[p,s,A]),te(()=>{if(!r)return;const L=setInterval(()=>{var _,S;(S=(_=A==null?void 0:A.current)==null?void 0:_.contentWindow)==null||S.postMessage({type:"codeyam-respond",name:r},"*")},1e3);return()=>clearInterval(L)},[r,A]),te(()=>{const L=()=>{const _=document.getElementById("scenario-container");if(!_)return;const S=_.getBoundingClientRect(),F=_.clientWidth-Fa*2,O=window.innerHeight-S.top-Fa*2,H=Math.max(O,400),ae=window.innerHeight-S.top;g(F),w(H),v(ae)};return L(),window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[]),te(()=>{E({width:a,height:o})},[a,o,E]);const U=ne(()=>N.width*M,[N.width,M]),B=ne(()=>{const L=N.height,_=L*M;return L&&L!==720&&L!==900&&_<b?_:b},[N.height,b,M]),D=se(()=>{window.history.back()},[]);return!Ed||!h?t("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:t("p",{className:"text-gray-500",children:"Loading interactive view..."})}):l("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:x?{height:`${x}px`}:{},children:[u&&t("div",{className:"fixed inset-0 z-50 bg-transparent"}),t("style",{children:`
|
|
78
|
+
.react-resizable-handle-e {
|
|
79
|
+
display: flex !important;
|
|
80
|
+
align-items: center !important;
|
|
81
|
+
justify-content: center !important;
|
|
82
|
+
width: 6px !important;
|
|
83
|
+
height: 48px !important;
|
|
84
|
+
right: -8px !important;
|
|
85
|
+
top: 50% !important;
|
|
86
|
+
transform: translateY(-50%) !important;
|
|
87
|
+
cursor: ew-resize !important;
|
|
88
|
+
background: #d1d5db !important;
|
|
89
|
+
border-radius: 3px !important;
|
|
90
|
+
opacity: 0 !important;
|
|
91
|
+
transition: all 0.2s ease !important;
|
|
92
|
+
}
|
|
93
|
+
.react-resizable-handle-e:hover {
|
|
94
|
+
opacity: 0.8 !important;
|
|
95
|
+
background: #9ca3af !important;
|
|
96
|
+
}
|
|
97
|
+
.react-resizable:hover .react-resizable-handle-e {
|
|
98
|
+
opacity: 0.4 !important;
|
|
99
|
+
}
|
|
100
|
+
`}),t(h,{width:U,height:B,minConstraints:[300,200],maxConstraints:[y,b],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:T,onResizeStop:$,onResize:z,children:t("div",{className:"overflow-auto",style:{width:`${U}px`,height:`${B}px`},children:t("div",{style:{width:`${N.width}px`,height:`${N.height}px`,transform:`scale(${M})`,transformOrigin:"top left"},children:n?t("iframe",{ref:A,className:"w-full h-full rounded-lg",src:n,onLoad:G,sandbox:"allow-scripts allow-same-origin"}):l("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[t("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),t("span",{className:"text-blue-600 cursor-pointer",onClick:D,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function _d({presets:e,customSizes:r,currentWidth:n,currentHeight:a,scale:o,onSizeChange:s,onSaveCustomSize:i,onRemoveCustomSize:c,className:d=""}){const[h,u]=P(!1),[m,p]=P(String(n)),[f,y]=P(String(a)),[g,b]=P(!1),[w,x]=P(!1),v=Ee(null);te(()=>{g||p(String(n))},[n,g]),te(()=>{w||y(String(a))},[a,w]),te(()=>{const M=T=>{v.current&&!v.current.contains(T.target)&&u(!1)};return document.addEventListener("mousedown",M),()=>document.removeEventListener("mousedown",M)},[]);const C=ne(()=>{const M=e.find($=>$.width===n&&$.height===a);if(M)return M.name;const T=r.find($=>$.width===n&&$.height===a);return T?T.name:"Custom"},[e,r,n,a]),k=C==="Custom",N=M=>{s(M.width,M.height),u(!1)},E=M=>{const T=M.target.value;p(T);const $=parseInt(T,10);!isNaN($)&&$>0&&s($,a)},A=M=>{const T=M.target.value;y(T);const $=parseInt(T,10);!isNaN($)&&$>0&&s(n,$)},I=()=>{b(!1);const M=parseInt(m,10);(isNaN(M)||M<=0)&&p(String(n))},j=()=>{x(!1);const M=parseInt(f,10);(isNaN(M)||M<=0)&&y(String(a))},R=M=>{(M.key==="Enter"||M.key==="Escape")&&M.target.blur()};return l("div",{className:`flex items-center gap-3 ${d}`,children:[l("div",{className:"relative",ref:v,children:[l("button",{onClick:()=>u(!h),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:[t("span",{children:C}),t("svg",{className:`w-4 h-4 transition-transform ${h?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),h&&t("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:l("div",{className:"py-1",children:[e.length>0&&l(ce,{children:[t("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(M=>l("button",{onClick:()=>N(M),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${C===M.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[t("span",{children:M.name}),l("span",{className:"text-xs text-gray-500",children:[M.width," x ",M.height]})]},M.name))]}),r.length>0&&l(ce,{children:[t("div",{className:"border-t border-gray-100 my-1"}),t("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Custom"}),[...r].sort((M,T)=>M.width-T.width).map(M=>l("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${C===M.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[l("button",{onClick:()=>N(M),className:"flex-1 text-left px-3 py-2 text-sm flex justify-between items-center gap-4 whitespace-nowrap cursor-pointer",children:[t("span",{children:M.name}),l("span",{className:"text-xs text-gray-500",children:[M.width," x ",M.height]})]}),c&&t("button",{onClick:T=>{T.stopPropagation(),C===M.name&&e.length>0&&s(e[0].width,e[0].height),c(M.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:t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},M.name))]})]})})]}),l("div",{className:"flex items-center gap-1 text-sm",children:[l("div",{className:"flex items-center",children:[t("input",{type:"text",value:m,onChange:E,onFocus:()=>b(!0),onBlur:I,onKeyDown:R,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]"}),t("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"})]}),t("span",{className:"text-gray-400 mx-1",children:"×"}),l("div",{className:"flex items-center",children:[t("input",{type:"text",value:f,onChange:A,onFocus:()=>x(!0),onBlur:j,onKeyDown:R,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]"}),t("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&&l("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(o*100),"%)"]})]}),k&&t("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 an(e,r,n){if(Array.isArray(e)){if(!isNaN(parseInt(r)))return e[parseInt(r)];for(const a of e)if(a.name===r||a.title===r||a.id===r)return a}return e[r]}function gn(e){return e&&(typeof e=="object"||Array.isArray(e))}function Td(e){return Array.isArray(e)?e.length:void 0}function Id(e){const{data:r,structure:n}=e;if(!(!r&&!n)){if(Array.isArray(n))return Array.isArray(r)?r.map((a,o)=>o.toString()):[];if(typeof n=="object")return[...new Set([...Object.keys(r),...Object.keys(n)])].sort((o,s)=>{const i=gn(r[o]),c=gn(r[s]);return i&&!c?1:!i&&c?-1:o.localeCompare(s)});if(typeof r=="object")return Object.keys(r).sort((o,s)=>o.localeCompare(s))}}function $d({scenarioFormData:e,handleInputChange:r}){return l("div",{className:"p-3 flex flex-col gap-3",children:[l("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[t("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),t("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:r,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"})]}),l("div",{className:"grid w-full gap-1.5 pt-2",children:[t("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),t("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:r,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]"})]}),t("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 jd({path:e,namedPath:r,isArray:n,count:a,onClick:o}){const s=se(()=>{o&&o(e)},[o,e]);return l("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:[l("div",{className:"flex items-center gap-3",children:[n&&t("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),l("div",{className:"capitalize font-medium text-gray-900",children:[r[r.length-1],a!==void 0&&` (${a})`]})]}),l("div",{className:"flex items-center gap-3",children:[n&&t("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:t("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"})}),t("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var os=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(os||{});const Rd=({name:e,value:r,options:n,onChange:a})=>{const o=se(s=>{a({target:{name:e,value:s.target.value}})},[e,a]);return t("select",{name:e,value:r,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:n.map((s,i)=>t("option",{value:s.trim(),children:s.trim()},i))})},Dd=({name:e,value:r,onChange:n})=>{const a=se(o=>{const s=o.target.checked;n({target:{name:e,value:s}})},[e,n]);return t("label",{className:"flex items-center gap-2 cursor-pointer",children:t("input",{type:"checkbox",name:e,checked:r,onChange:a,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
|
|
101
|
+
bg-gray-300 checked:bg-blue-600
|
|
102
|
+
after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
|
|
103
|
+
after:bg-white after:rounded-full after:transition-transform
|
|
104
|
+
checked:after:translate-x-4`})})};function Ld({dataType:e,path:r,value:n,onChange:a}){const o=ne(()=>r[r.length-1],[r]),s=ne(()=>r.join("-"),[r]),i=se(d=>{a(r,d.target.value)},[a,r]),c=se(d=>{a(r,d.target.value)},[a,r]);return l("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[t("label",{htmlFor:s,className:"capitalize text-sm font-medium text-gray-700",children:o==="~~codeyam-code~~"?"Dynamic Field":o}),e.includes("|")?t(Rd,{name:s,value:n,options:e.split("|"),onChange:i}):e===os.BOOLEAN?t(Dd,{name:s,value:n??!1,onChange:c}):t("input",{id:s,name:s,type:"text",value:JSON.stringify(n??"").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 Fd({analysis:e,scenarioName:r,dataItem:n,onResult:a,onGenerateData:o}){const[s,i]=P(!1),[c,d]=P(""),h=se(async()=>{if(!o){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const m=e.scenarios.find(b=>b.name===r);if(!m)throw new Error("Scenario not found");const p=e.scenarios.find(b=>b.name===Ir),f=await o(c,n);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const y=(b,w)=>{const x=Object.assign({},b);return g(b)&&g(w)&&Object.keys(w).forEach(v=>{g(w[v])?v in b?x[v]=y(b[v],w[v]):Object.assign(x,{[v]:w[v]}):Object.assign(x,{[v]:w[v]})}),x},g=b=>b&&typeof b=="object"&&!Array.isArray(b);m.metadata.data=y(y((p==null?void 0:p.metadata.data)||{},m.metadata.data),f.data||{}),a(m),i(!1),d("")}catch(m){console.error("Error generating AI data:",m),i(!1)}},[e,c,n,r,a,o]),u=se(m=>{d(m.target.value)},[]);return l("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[t("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),t("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:c}),t("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 ${c.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void h(),children:s?l(ce,{children:[l("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:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("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 Od({namedPath:e,path:r,last:n,onClick:a}){const o=se(()=>a(n?r.slice(0,-1):r),[n,r,a]);return t("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:o,children:e[e.length-1]})}function zd({dataItem:e,onClick:r}){const n=se(()=>r([]),[r]),a=ne(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return l("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[t("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:n,children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&l("div",{className:"flex items-center gap-1",children:[t("div",{children:"..."}),t("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(a).map((o,s)=>l("div",{className:"flex items-center gap-1",children:[t(Od,{namedPath:e.namedPath.slice(0,s+a+1),path:e.path.slice(0,s+a+1),last:s+a===e.namedPath.length-1,onClick:r}),s+a<e.namedPath.length-1&&t("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},`path-${o}-${s+a}`))]})}function Oa({analysis:e,scenarioName:r,dataItem:n,onClick:a,onChange:o,onAIResult:s,onGenerateData:i,saveFeedback:c}){const d=ne(()=>n.data,[n]),h=ne(()=>Id(n),[n]);return l("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[n.path.length>0&&t(zd,{dataItem:n,onClick:a}),l("div",{className:"flex flex-col gap-3",children:[t(Fd,{analysis:e,scenarioName:r,dataItem:n,onResult:s,onGenerateData:i}),h==null?void 0:h.map((u,m)=>{var f;if(gn(d[u])){let y=u;isNaN(Number(u))||(y=d[u].name??d[u].title??d[u].id??`${n.path[n.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const g=[...n.path,u],b=[...n.namedPath,y];return t(jd,{path:g,namedPath:b,isArray:Array.isArray(d),count:Td(d[u]),onClick:a},`data-${u}-${m}`)}if(u==="id")return null;const p=[...n.path,u];return t(Ld,{dataType:((f=n.structure)==null?void 0:f[u])??"string",path:p,value:d[u],onChange:o},`InputField-${p.join("-")}`)})]}),t("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),l("div",{className:"flex gap-2",children:[t("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:c==null?void 0:c.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:c!=null&&c.isSaving?"Saving...":"Save Changes"}),t("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled:c==null?void 0:c.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"})]}),(c==null?void 0:c.message)&&!(c!=null&&c.isSaving)&&t("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${c.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:c.message})]})}function za({title:e,children:r,defaultOpen:n=!1,borderT:a=!1,borderB:o=!1}){const[s,i]=P(n),c=[];return a&&c.push("border-t"),o&&c.push("border-b"),l("div",{className:`${c.join(" ")} border-gray-300`,children:[l("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:[t("span",{children:e}),t("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:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),s&&t("div",{className:"px-4 py-3",children:r})]})}const Yd=({currentScenario:e,defaultScenario:r,dataStructure:n,analysis:a,shouldCreateNewScenario:o,onSave:s,onNavigate:i,iframeRef:c,onGenerateData:d,saveFeedback:h})=>{const u=se((E,A)=>{const I=Object.assign({},E),j=R=>R&&typeof R=="object"&&!Array.isArray(R);return j(E)&&j(A)&&Object.keys(A).forEach(R=>{j(A[R])?R in E?I[R]=u(E[R],A[R]):Object.assign(I,{[R]:A[R]}):Object.assign(I,{[R]:A[R]})}),I},[]),[m,p]=P({name:e.name,description:e.description,data:u(r.metadata.data,e.metadata.data)}),[f,y]=P(null),g=ne(()=>({...m.data}),[m]),b=ne(()=>({...g.mockData?{"Retrieved Data":g.mockData}:{},...g.argumentsData?{"Function Arguments":g.argumentsData}:{}}),[g]),w=ne(()=>{const E={...n.arguments?{"Function Arguments":n.arguments}:{},...n.dataForMocks?{"Retrieved Data":n.dataForMocks}:{}};return Object.keys(E).reduce((A,I)=>{if(I.includes(".")){const[j,R]=I.split(".");A[j]||(A[j]={}),A[j][R]=E[I]}else A[I]=E[I];return A},{})},[n]),x=se(async E=>{E.preventDefault();const A=E.target.querySelector('input[name="recapture"]'),I=(A==null?void 0:A.value)==="true",j={mockData:m.data.mockData??{},argumentsData:m.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:m.name,shouldRecapture:I,dataToSave:j,rawFormData:m.data,iframePayload:{arguments:g.argumentsData??[],...g.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(j,null,2).substring(0,1e3));const R=a==null?void 0:a.scenarios.map(M=>!o&&M.name===e.name?{...M,name:m.name,description:m.description,metadata:{...M.metadata,data:j}}:M);o&&R.push({name:m.name,description:m.description,metadata:{data:j,interactiveExamplePath:a==null?void 0:a.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",R),s&&await s(R,{recapture:I}),i&&i(m.name)},[a,e.name,m,g,o,s,i]),v=se(E=>{p(A=>({...A,[E.target.name]:E.target.value}))},[]),C=se(E=>{y(A=>{if(!A)return null;for(const I of[{arguments:E.metadata.data.argumentsData},E.metadata.data.mockData]){let j=I;for(const R of A.path)if(j=an(j,R),!j)break;j&&(A.data=j)}return{...A}}),p({name:E.name,description:E.description,data:E.metadata.data})},[]),k=se((E,A)=>{p(I=>{for(const j of[{"Function Arguments":I.data.argumentsData},{"Retrieved Data":I.data.mockData}]){let R=j;for(const M of E.slice(0,-1))if(R=an(R,M),!R)break;if(R){const M=R[E[E.length-1]];y(T=>T?(T.namedPath[T.namedPath.length-1]===M&&(T.namedPath[T.namedPath.length-1]=A.toString()),T.data[E[E.length-1]]=A,{...T}):null),R[E[E.length-1]]=A}}return{...I}})},[]),N=se(E=>{var R,M,T;if(E.length===0){y(null);return}let A=b;const I=[];let j=w;for(const $ of E){if(I.push(isNaN(parseInt($))?$:((R=A[$])==null?void 0:R.name)??((M=A[$])==null?void 0:M.title)??((T=A[$])==null?void 0:T.id)??$),A=an(A,$),!A){console.log("Data not found",A,$),y(null);return}Array.isArray(j)?j=j[0]:j=j[$]}y({path:E,namedPath:I,data:A,structure:j})},[b,w]);return te(()=>{const E=A=>{var I;A.data.type==="codeyam-log"&&((I=A.data.data)!=null&&I.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",A.data.data)};return window.addEventListener("message",E),()=>window.removeEventListener("message",E)},[]),te(()=>{var E;if((E=c==null?void 0:c.current)!=null&&E.contentWindow){const A={arguments:g.argumentsData??[],...g.mockData??{}},I={type:"codeyam-override-data",name:e.name,data:JSON.stringify(A)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:I.type,name:I.name,dataPreview:JSON.stringify(A).substring(0,200)+"...",fullData:A}),c.current.contentWindow.postMessage(I,"*")}},[g,e,c]),t("form",{method:"post",onSubmit:E=>void x(E),children:f?t(Oa,{analysis:a,scenarioName:m.name,dataItem:f,onClick:N,onChange:k,onAIResult:C,onGenerateData:d,saveFeedback:h}):l(ce,{children:[t(za,{title:"Edit Name and Description",borderT:!0,children:t($d,{scenarioFormData:m,handleInputChange:v})}),e.metadata.data&&t(za,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:t(Oa,{analysis:a,scenarioName:m.name,dataItem:{path:[],namedPath:[],data:b,structure:w},onClick:N,onChange:k,onAIResult:C,onGenerateData:d,saveFeedback:h})})]})})};function Or({scenarioId:e,scenarioName:r,iframeUrl:n,isStarting:a,isLoading:o,showIframe:s,iframeKey:i,onIframeLoad:c,onScaleChange:d,onDimensionChange:h,projectSlug:u,defaultWidth:m=1440,defaultHeight:p=900,retryCount:f=0}){const{lastLine:y}=pt(u??null,a||o);return n?l("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[t("div",{style:{opacity:s?1:0,background:"transparent"},children:t(Md,{id:e,scenarioName:r,iframeUrl:n,defaultWidth:m,defaultHeight:p,onIframeLoad:c,onScaleChange:d,onDimensionChange:h},i)}),!s&&(a||o)&&t("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[t("div",{className:"mb-4",children:t(Sr,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[t("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),t("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[t(Er,{}),y]})]})]})})]}):t("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center",children:l("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[t("div",{className:"mb-4",children:t(Sr,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[t("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),t("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[t(Er,{}),y]})]})]})})}const Bd=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Ud({params:e}){var d,h;const{sha:r,scenarioId:n}=e;if(!r)throw new Response("Entity SHA is required",{status:400});if(!n)throw new Response("Scenario ID is required",{status:400});const a=await jr(r,!0),o=a&&a.length>0?a[0]:null;if(!o)throw new Response("Analysis not found",{status:404});const s=(d=o.scenarios)==null?void 0:d.find(u=>u.id===n);if(!s)throw new Response("Scenario not found",{status:404});const i=(h=o.scenarios)==null?void 0:h.find(u=>u.name===Ir),c=await ze();return J({analysis:o,scenario:s,defaultScenario:i||s,entitySha:r,projectSlug:c})}function Wd(){var $,z,G;const e=We(),r=e.analysis,n=e.scenario,a=e.defaultScenario,o=e.entitySha,s=e.projectSlug,i=_t(),{iframeRef:c}=Bn(),[d,h]=P(!1),[u,m]=P(null),[p,f]=P(null),[y,g]=P(!1),[b,w]=P(!1),[x,v]=P(null),{interactiveServerUrl:C,isStarting:k,isLoading:N,showIframe:E,iframeKey:A,onIframeLoad:I}=rr({analysisId:r==null?void 0:r.id,scenarioId:n==null?void 0:n.id,scenarioName:n==null?void 0:n.name,projectSlug:s,enabled:!0}),j=se(async(U,B)=>{h(!0),m(null),f(null),console.log("[EditScenario] Starting save with options:",B),console.log("[EditScenario] Scenarios to save:",U);try{const D={analysis:r,scenarios:U};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:r.id,scenarioCount:U.length,scenarioNames:U.map(S=>S.name)});const L=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)}),_=await L.json();if(console.log("[EditScenario] API response:",_),!L.ok||!_.success)throw new Error(_.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),B!=null&&B.recapture&&n.id&&C){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:n.id,projectId:r.projectId,serverUrl:C}),m("Changes saved. Capturing screenshot...");const S={serverUrl:C,scenarioId:n.id,projectId:r.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",S);const F=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});console.log("[EditScenario] Capture response status:",F.status);const O=await F.json();if(console.log("[EditScenario] Capture response body:",O),!F.ok||!O.success)throw console.error("[EditScenario] Capture failed:",O),new Error(O.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",O),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),m("Recapture successful")}else if(B!=null&&B.recapture&&!C){console.log("[EditScenario] No running server, using queued recapture");const S=new FormData;S.append("analysisId",r.id||""),S.append("scenarioId",n.id||"");const F=await fetch("/api/recapture-scenario",{method:"POST",body:S}),O=await F.json();if(!F.ok||!O.success)throw new Error(O.error||"Failed to trigger recapture");console.log("Recapture queued:",O),f(O.jobId),m("Changes saved. Screenshot recapture queued.")}else m("Changes saved successfully.")}catch(D){console.error("Error saving scenarios:",D),m(`Error: ${D instanceof Error?D.message:String(D)}`)}finally{h(!1)}},[r,n.id,C]),R=se(U=>{},[]),M=se(async(U,B)=>{var _;const D=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:U,existingScenarios:r.scenarios,scenariosDataStructure:(_=r.metadata)==null?void 0:_.scenariosDataStructure,editingMockName:n.name,editingMockData:B==null?void 0:B.data})}),L=await D.json();if(!D.ok||!L.success)throw new Error(L.error||"Failed to generate scenario data");return L.data},[r,n.name]),T=se(async()=>{var U;if(!n.id){v("Cannot delete scenario without ID");return}g(!0),v(null);try{const B=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:n.id,screenshotPaths:((U=n.metadata)==null?void 0:U.screenshotPaths)||[]})}),D=await B.json();if(!B.ok||!D.success)throw new Error(D.error||"Failed to delete scenario");i(`/entity/${o}`)}catch(B){console.error("[EditScenario] Error deleting scenario:",B),v(B instanceof Error?B.message:"Failed to delete scenario"),w(!1)}finally{g(!1)}},[n.id,($=n.metadata)==null?void 0:$.screenshotPaths,o,i]);return l("div",{className:"h-screen bg-gray-50 flex flex-col",children:[l("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[t("div",{className:"mb-4",children:l(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 ",(z=r.entity)==null?void 0:z.name]})}),l("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",n.name]}),n.description&&t("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:n.description})]}),l("div",{className:"flex flex-1 gap-0 min-h-0",children:[l("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[t(Yd,{currentScenario:n,defaultScenario:a,dataStructure:((G=r.metadata)==null?void 0:G.scenariosDataStructure)||{},analysis:r,shouldCreateNewScenario:!1,onSave:j,onNavigate:R,iframeRef:c,onGenerateData:M,saveFeedback:{isSaving:d,message:u,isError:(u==null?void 0:u.startsWith("Error"))??!1}}),u==="Recapture successful"&&t("div",{className:"px-4 pb-4",children:t(oe,{to:`/entity/${o}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),l("div",{className:"border-t border-gray-200 p-4 mt-4",children:[t("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),b?l("div",{className:"space-y-3",children:[l("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',n.name,'"?']}),l("div",{className:"flex gap-2",children:[t("button",{onClick:()=>void T(),disabled:y,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:y?"Deleting...":"Yes, Delete"}),t("button",{onClick:()=>w(!1),disabled:y,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"})]})]}):t("button",{onClick:()=>w(!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"}),x&&t("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:x})]})]}),t("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:t(Or,{scenarioId:n.id||n.name,scenarioName:n.name,iframeUrl:C,isStarting:k,isLoading:N,showIframe:E,iframeKey:A,onIframeLoad:I,projectSlug:s,defaultWidth:1440,defaultHeight:900})})]})]})}const Hd=Oe(function(){return t(Fr,{children:t(Wd,{})})}),qd=Object.freeze(Object.defineProperty({__proto__:null,default:Hd,loader:Ud,meta:Bd},Symbol.toStringTag,{value:"Module"}));function Jd({executionFlows:e,selections:r,onChange:n,disabled:a=!1}){const o=se(i=>r.some(c=>c.flowId===i),[r]),s=se(i=>{o(i.id)?n(r.filter(c=>c.flowId!==i.id)):n([...r,{flowId:i.id,flowName:i.name}])},[r,n,o]);return e.length===0?t("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):t("div",{className:"space-y-3",children:e.map(i=>{const c=o(i.id),d=i.usedInScenarios.length>0;return l("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[l("label",{className:"flex items-start gap-2 cursor-pointer",children:[t("input",{type:"checkbox",checked:c,onChange:()=>s(i),disabled:a,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[t("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!d&&t("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&t("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&t("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&t("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),c&&i.requiredValues.length>0&&l("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[t("span",{className:"text-gray-700 font-medium",children:"Required values:"}),t("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((h,u)=>l("li",{className:"text-gray-600",children:[t("code",{className:"bg-gray-100 px-1 rounded",children:h.attributePath})," ",t("span",{className:"text-gray-400",children:h.comparison})," ",t("code",{className:"bg-gray-100 px-1 rounded",children:h.value})]},u))})]})]},i.id)})})}function Un(e,r){const n=(e||[]).map(d=>({...d,usedInScenarios:[]})),a=new Map;n.forEach(d=>{a.set(d.id,d)});const o=[];r.forEach(d=>{var u;const h=((u=d.metadata)==null?void 0:u.coveredFlows)||[];h.forEach(m=>{const p=a.get(m);p&&p.usedInScenarios.push({id:d.id||"",name:d.name})}),o.push({scenario:d,coveredFlowIds:h})});const s=n.length,i=n.filter(d=>d.usedInScenarios.length>0).length,c=s>0?i/s*100:0;return{executionFlows:n,totalFlows:s,coveredFlows:i,coveragePercentage:c,scenariosWithFlows:o}}function Gd(e){return e.executionFlows.filter(r=>r.usedInScenarios.length===0)}const Vd=({data:e})=>[{title:e!=null&&e.entity?`Create Scenario - ${e.entity.name} - CodeYam`:"Create Scenario - CodeYam"},{name:"description",content:"Create a new scenario"}];async function Qd({params:e}){var i;const{sha:r}=e;if(!r)throw new Response("Entity SHA is required",{status:400});const n=await jr(r,!0),a=n&&n.length>0?n[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const o=(i=a.scenarios)==null?void 0:i.find(c=>c.name===Ir);if(!o)throw new Response("Default scenario not found",{status:404});const s=await ze();return J({analysis:a,defaultScenario:o,entity:a.entity,entitySha:r,projectSlug:s})}function Kd(){var D;const{analysis:e,defaultScenario:r,entity:n,entitySha:a,projectSlug:o}=We(),s=_t(),{iframeRef:i}=Bn(),[c,d]=P(""),[h,u]=P(400),[m,p]=P(!1),[f,y]=P(!1),[g,b]=P(!1),[w,x]=P(null),[v,C]=P(null),[k,N]=P([]),E=ne(()=>{var _;return!((_=e==null?void 0:e.metadata)!=null&&_.executionFlows)||!(e!=null&&e.scenarios)?[]:Un(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:A,isStarting:I,isLoading:j,showIframe:R,iframeKey:M,onIframeLoad:T}=rr({analysisId:e==null?void 0:e.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0}),$=se(async()=>{var L,_,S,F;if(!c.trim()&&k.length===0){x("Please describe how you want to change the scenario or select execution flows");return}y(!0),x(null),C("Generating scenario with AI...");try{const O=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:c,existingScenarios:e.scenarios,scenariosDataStructure:(L=e.metadata)==null?void 0:L.scenariosDataStructure,flowSelections:k.length>0?k:void 0})}),H=await O.json();if(!O.ok||!H.success)throw new Error(H.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",H.data);const ae=H.data;if(!ae.name||!ae.data)throw new Error("AI response missing required fields (name or data)");C("Saving new scenario..."),b(!0);const V={name:ae.name,description:ae.description||c,metadata:{data:ae.data,interactiveExamplePath:(_=r.metadata)==null?void 0:_.interactiveExamplePath}},Y=[...e.scenarios||[],V],W=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:Y})}),Q=await W.json();if(!W.ok||!Q.success)throw new Error(Q.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",Q);const q=(F=(S=Q.analysis)==null?void 0:S.scenarios)==null?void 0:F.find(Z=>Z.name===ae.name);if(!(q!=null&&q.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),C("Scenario created! Redirecting..."),setTimeout(()=>void s(`/entity/${a}`),1e3);return}if(A){C("Capturing screenshot...");const Z=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:A,scenarioId:q.id,projectId:e.projectId,viewportWidth:1440})}),de=await Z.json();!Z.ok||!de.success?(console.error("[CreateScenario] Capture failed:",de),C("Scenario created! (Screenshot capture failed)")):C("Scenario created and captured!")}else C("Scenario created!");setTimeout(()=>{s(`/entity/${a}/scenarios/${q.id}`)},1e3)}catch(O){console.error("[CreateScenario] Error:",O),x(O instanceof Error?O.message:String(O)),C(null)}finally{y(!1),b(!1)}},[c,k,e,r,a,A,s]),z=f||g,G=se(()=>{p(!0)},[]),U=se(L=>{if(!m)return;const _=L.clientX;_>=250&&_<=600&&u(_)},[m]),B=se(()=>{p(!1)},[]);return te(()=>(m?(document.addEventListener("mousemove",U),document.addEventListener("mouseup",B)):(document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",B)),()=>{document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",B)}),[m,U,B]),l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[t("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-end h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[t("button",{onClick:()=>void s(`/entity/${a}`),className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:t("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:t("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),t("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:n==null?void 0:n.name}),t("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:n==null?void 0:n.filePath,children:n==null?void 0:n.filePath})]}),l("div",{className:"flex items-end gap-8 shrink-0",children:[t(oe,{to:`/entity/${a}/scenarios`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-medium border-b-2",style:{color:"#005C75",borderColor:"#005C75"},children:l("span",{className:"flex items-center gap-2",children:["Scenarios",t("span",{className:"inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full bg-[#cbf3fa] text-[#005c75]",children:((D=e==null?void 0:e.scenarios)==null?void 0:D.length)||0})]})}),t(oe,{to:`/entity/${a}/related`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Related Entities"}),t(oe,{to:`/entity/${a}/code`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Code"}),t(oe,{to:`/entity/${a}/data`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Data Structure"}),t(oe,{to:`/entity/${a}/history`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"History"})]})]})}),l("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[l("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${h}px`},children:[l("div",{className:"mb-6",children:[t("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),t("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select execution flows and/or describe how you'd like to change it."})]}),E.length>0&&l("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[l("summary",{className:"px-3 py-2 text-sm font-medium text-gray-700 cursor-pointer hover:bg-gray-50 rounded-lg",children:["Select Execution Flows"," ",k.length>0&&l("span",{className:"text-blue-600",children:["(",k.length," selected)"]})]}),t("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:t(Jd,{executionFlows:E,selections:k,onChange:N,disabled:z})})]}),l("div",{className:"mb-4",children:[t("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"Describe your scenario"}),t("textarea",{id:"prompt",value:c,onChange:L=>d(L.target.value),placeholder:"e.g., Show an empty state with no items...",className:"w-full h-32 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm resize-none",disabled:z})]}),l("div",{className:"space-y-2",children:[t("button",{onClick:()=>void $(),disabled:z||!c.trim()&&k.length===0,className:"w-full px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium cursor-pointer transition-colors hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed",children:z?"Creating...":"Create Scenario"}),v&&t("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:v}),w&&t("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:w})]})]}),l("div",{onMouseDown:G,style:{width:"20px",position:"absolute",top:0,left:`${h-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[t("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:m?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),t("div",{style:{position:"absolute",top:"50%",left:"10px",transform:"translate(-50%, -50%)",width:"8px",height:"40px",background:"#fff",border:"1px solid rgba(0,0,0,0.15)",borderRadius:"4px",cursor:"col-resize"}})]}),t("main",{className:"flex-1 overflow-auto flex items-center justify-center min-w-0",style:{backgroundImage:`
|
|
105
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
106
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
107
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
108
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
109
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:t(Or,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:A,isStarting:I,isLoading:j,showIframe:R,iframeKey:M,onIframeLoad:T,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const Zd=Oe(function(){return t(Fr,{children:t(Kd,{})})}),Xd=Object.freeze(Object.defineProperty({__proto__:null,default:Zd,loader:Qd,meta:Vd},Symbol.toStringTag,{value:"Module"}));var ie;(e=>{(r=>{r.OPENAI_GPT5_1="openai/gpt-5.1",r.OPENAI_GPT5="openai/gpt-5",r.OPENAI_GPT5_MINI="openai/gpt-5-mini",r.OPENAI_GPT5_NANO="openai/gpt-5-nano",r.OPENAI_GPT4_1="openai/gpt-4.1",r.OPENAI_GPT4_1_MINI="openai/gpt-4.1-mini",r.OPENAI_GPT4_O="openai/gpt-4o",r.OPENAI_GPT4_O_MINI="openai/gpt-4o-mini",r.OPENAI_GPT_OSS_120B_GROQ="openai/gpt-oss-120b-groq",r.OPENAI_GPT_OSS_120B_DEEPINFRA="openai/gpt-oss-120b-deepinfra",r.QWEN3_235B_INSTRUCT_DEEPINFRA="qwen/qwen3-235b-instruct-deepinfra",r.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA="qwen/qwen3-coder-480b-instruct-deepinfra",r.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA="google/gemini-2.5-pro-deepinfra",r.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA="google/gemini-2.5-flash-deepinfra",r.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER="google/gemini-2.5-flash-lite-openrouter",r.META_LLAMA_4_MAVERICK_OPENROUTER="meta-llama/llama-4-maverick-openrouter",r.DEEPSEEK_V3_1_TERMINUS_OPENROUTER="deepseek/v3.1-terminus-openrouter",r.ANTHROPIC_CLAUDE_4_5_HAIKU="anthropic/claude-4.5-haiku",r.ANTHROPIC_CLAUDE_4_5_SONNET="anthropic/claude-4.5-sonnet",r.ANTHROPIC_CLAUDE_4_5_OPUS="anthropic/claude-4.5-opus",r.PHIND_CODELLAMA="phind/codellama",r.GOOGLE_GEMINI_PRO="google/gemini-pro",r.GOOGLE_PALM_2_CODE_CHAT_32K="google/palm-2-code-chat-32k",r.META_CODELLAMA_34B_INSTRUCT="meta-llama/codellama-34b-instruct",r.OPENAI_GPT4_PREVIEW="openai/gpt-4-preview"})(e.Model||(e.Model={}))})(ie||(ie={}));function ss(e,r){return e?Object.values(ie.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${r}`),r):r}const is=ss(process.env.DEFAULT_SMALLER_MODEL,ie.Model.OPENAI_GPT4_1_MINI),eu=ss(process.env.DEFAULT_LARGER_MODEL,ie.Model.OPENAI_GPT4_1),Ke={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},on={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},tu={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},sn={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},it={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},ru={[ie.Model.OPENAI_GPT5_1]:{id:ie.Model.OPENAI_GPT5_1,provider:Ke,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[ie.Model.OPENAI_GPT5]:{id:ie.Model.OPENAI_GPT5,provider:Ke,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[ie.Model.OPENAI_GPT5_MINI]:{id:ie.Model.OPENAI_GPT5_MINI,provider:Ke,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[ie.Model.OPENAI_GPT5_NANO]:{id:ie.Model.OPENAI_GPT5_NANO,provider:Ke,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[ie.Model.OPENAI_GPT4_1]:{id:ie.Model.OPENAI_GPT4_1,provider:Ke,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[ie.Model.OPENAI_GPT4_1_MINI]:{id:ie.Model.OPENAI_GPT4_1_MINI,provider:Ke,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ie.Model.OPENAI_GPT4_O]:{id:ie.Model.OPENAI_GPT4_O,provider:Ke,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[ie.Model.OPENAI_GPT4_O_MINI]:{id:ie.Model.OPENAI_GPT4_O_MINI,provider:Ke,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[ie.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:ie.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:on,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[ie.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:ie.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:on,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[ie.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:ie.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:on,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[ie.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:ie.Model.OPENAI_GPT_OSS_120B_GROQ,provider:tu,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[ie.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:ie.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:it,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[ie.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:ie.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:it,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[ie.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:ie.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:it,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ie.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:ie.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:it,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[ie.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:ie.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:it,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[ie.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:ie.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:sn,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[ie.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:ie.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:sn,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[ie.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:ie.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:sn,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[ie.Model.PHIND_CODELLAMA]:{id:ie.Model.PHIND_CODELLAMA,provider:Ke,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ie.Model.GOOGLE_GEMINI_PRO]:{id:ie.Model.GOOGLE_GEMINI_PRO,provider:it,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ie.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:ie.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:it,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ie.Model.META_CODELLAMA_34B_INSTRUCT]:{id:ie.Model.META_CODELLAMA_34B_INSTRUCT,provider:it,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ie.Model.OPENAI_GPT4_PREVIEW]:{id:ie.Model.OPENAI_GPT4_PREVIEW,provider:Ke,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function zr(e){const r=ru[e];if(!r)throw new Error(`Unknown model: ${e}`);return r}function nu(e){return zr(e).maxCompletionTokens}function au(e){return zr(e).pricing}const Ya=1e6;function ou({model:e,usage:r}){const n=au(e);return n?r.prompt_tokens*(n.input/Ya)+r.completion_tokens*(n.output/Ya):null}function su({chatRequest:e,chatCompletion:r,model:n}){if("error"in r&&r.error)return{model:n,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(r,null,2),error:JSON.stringify(r.error)};const a=r.usage||{prompt_tokens:0,completion_tokens:0},o=ou({model:n,usage:a});return{model:n,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(r,null,2),input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,cost:o?Math.round(o*1e5)/1e5:void 0}}function iu({messages:{system:e,prompt:r},model:n,responseType:a,jsonSchema:o}){const s=n??is,i=zr(s);nu(s);const c=[];return e&&c.push({role:"system",content:e}),c.push({role:"user",content:[{type:"text",text:r}]}),{messages:c,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}}}const yn="/tmp/codeyam-e2e-tracking";let ln,cn;function lu(){return ln===void 0&&(ln=process.env.CODEYAM_E2E_TRACK_DATA==="true"),ln}function cu(){return cn===void 0&&(cn=!process.env.CODEYAM_LLM_FIXTURES_DIR),cn}function du(){K.existsSync(yn)||K.mkdirSync(yn,{recursive:!0})}function uu(e){const r=JSON.stringify(e,null,0);return Oi.createHash("md5").update(r).digest("hex")}function hu(e,r,n){return[e].join("_")+".json"}function ls(e,r,n,a){if(!lu())return;du();const o=hu(e),s=ee.join(yn,o),i=uu(r);if(cu()){const c={timestamp:Date.now(),checkpoint:e,entityName:n,scenarioName:a,dataHash:i,data:r};K.writeFileSync(s,JSON.stringify(c,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(K.existsSync(s)){const c=JSON.parse(K.readFileSync(s,"utf-8")),d={matches:i===c.dataHash,firstRunHash:c.dataHash};if(d.matches)console.log(`[E2E Tracking] Match at ${e} hash=${i.substring(0,8)}`);else{d.differences=xn(c.data,r),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${c.dataHash}`),console.log(` Second run hash: ${i}`);const h=s.replace(".json","_DIFF.json");K.writeFileSync(h,JSON.stringify({checkpoint:e,entityName:n,scenarioName:a,firstRun:c.data,secondRun:r,differences:d.differences},null,2)),console.log(` Diff saved to: ${h}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function xn(e,r,n=""){const a=[];if(typeof e!=typeof r)return a.push(`${n||"root"}: type mismatch (${typeof e} vs ${typeof r})`),a;if(e===null||r===null)return e!==r&&a.push(`${n||"root"}: ${JSON.stringify(e)} vs ${JSON.stringify(r)}`),a;if(Array.isArray(e)&&Array.isArray(r)){e.length!==r.length&&a.push(`${n||"root"}: array length ${e.length} vs ${r.length}`);const o=Math.max(e.length,r.length);for(let s=0;s<o;s++)a.push(...xn(e[s],r[s],`${n}[${s}]`));return a}if(typeof e=="object"&&typeof r=="object"){const o=Object.keys(e),s=Object.keys(r),i=Array.from(new Set([...o,...s]));for(const c of i){const d=e[c],h=r[c];c in e?c in r?a.push(...xn(d,h,`${n?n+".":""}${c}`)):a.push(`${n?n+".":""}${c}: missing in second run`):a.push(`${n?n+".":""}${c}: missing in first run`)}return a}if(e!==r){const o=JSON.stringify(e),s=JSON.stringify(r);o.length<100&&s.length<100?a.push(`${n||"root"}: ${o} vs ${s}`):a.push(`${n||"root"}: values differ (${o.length} chars vs ${s.length} chars)`)}return a}_n(Pn);const cr=new Hi({concurrency:100,timeout:1200*1e3,throwOnTimeout:!0,autoStart:!0}),Ba={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},lt={};async function bn({type:e,systemMessage:r,prompt:n,jsonResponse:a=!0,jsonSchema:o,model:s=is,attempts:i=0}){var N,E,A,I,j,R,M;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await mu(e,process.env.CODEYAM_LLM_FIXTURES_DIR,r);console.log(`CodeYam Debug: LLM Pool [queued=${cr.size}, running=${cr.pending}]`);const c=Date.now();let d,h=0;const u=zr(s),m=process.env[u.provider.apiKeyEnvVar];if(!m)throw new Error(`API key not found for provider ${u.provider.name}. Please set ${u.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${u.provider.name} for AI request`);const p=new Wi({apiKey:m,baseURL:u.provider.baseURL}),f={type:e,messages:{system:r,prompt:n},model:s,responseType:o?"json_schema":a?"json_object":"text",jsonSchema:o},y=iu(f),g=await cr.add(()=>(d=Date.now(),Pa(async()=>{const T=Date.now(),$=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],z=setInterval(()=>{const G=Math.floor((Date.now()-T)/1e3),U=Math.floor(G/10)%$.length;_a(1,`${$[U]} [type=${e}, model=${s}, elapsed=${G}s]`)},1e4);try{return await p.chat.completions.create(y,{timeout:300*1e3})}finally{clearInterval(z)}},{...Ba,onFailedAttempt:T=>{h++,console.log(`CodeYam Error: Completion call failed [model=${s}]`,{error:T,prompt:n,systemMessage:r,attempts:i,retryCount:h})}})),{throwOnTimeout:!0}),b=Date.now(),w=su({chatRequest:f,chatCompletion:g,model:s});if(!w)throw new Error("Failed to get LLM call stats");w.retries=h,w.wait_ms=d-c,w.duration_ms=b-c;const x=(N=g.choices)==null?void 0:N[0];let v=null;if(x){if(!x.finish_reason)throw console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({chatCompletion:g,chatRequest:f},null,2)),new Error("completionCall(): missing finish_reason in LLM response");v=(E=x.message)==null?void 0:E.content}let C=v;v&&(C=v.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const k=a?C&&(((A=C.match(/\{[\s\S]*\}/))==null?void 0:A[0])??C):C;if(!k){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:k,rawCompletion:v,chatCompletion:g,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:n,systemMessage:r,attempts:i}),await bn({type:e,systemMessage:r,prompt:n,jsonResponse:a,model:s,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(k.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:v,prompt:n,systemMessage:r}),new Error("Empty completion");if(a)try{JSON.parse(k)}catch(T){if(console.log("CodeYam Error: Invalid JSON in completion",{error:T.message,model:s,completion:k.substring(0,500),rawCompletion:v==null?void 0:v.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:T.message});const $=`Your previous response contained invalid JSON with the following error:
|
|
110
|
+
|
|
111
|
+
${T.message}
|
|
112
|
+
|
|
113
|
+
Here was your previous response:
|
|
114
|
+
\`\`\`
|
|
115
|
+
${k}
|
|
116
|
+
\`\`\`
|
|
117
|
+
|
|
118
|
+
Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,z=await cr.add(()=>Pa(async()=>{const D=Date.now(),L=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],_=setInterval(()=>{const S=Math.floor((Date.now()-D)/1e3),F=Math.floor(S/10)%L.length;_a(1,`${L[F]} [type=${e}, model=${s}, elapsed=${S}s]`)},1e4);try{return await p.chat.completions.create({...y,messages:[{role:"system",content:r},{role:"user",content:n},{role:"assistant",content:k},{role:"user",content:$}]},{timeout:300*1e3})}finally{clearInterval(_)}},{...Ba,onFailedAttempt:D=>{console.log("CodeYam Error: Correction call failed",{error:D,attempts:i})}}),{throwOnTimeout:!0}),G=(R=(j=(I=z.choices)==null?void 0:I[0])==null?void 0:j.message)==null?void 0:R.content;let U=G;G&&(U=G.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const B=U&&(((M=U.match(/\{[\s\S]*\}/))==null?void 0:M[0])??U);if(!B)throw new Error("Correction attempt returned empty completion");try{JSON.parse(B),console.log("CodeYam: JSON correction successful");const D=Date.now();return w.duration_ms=D-c,{finishReason:z.choices[0].finish_reason,completion:B,stats:w}}catch(D){return console.log("CodeYam Error: Corrected JSON still invalid",{error:D.message,correctedCompletion:B.substring(0,500)}),await bn({type:e,systemMessage:r,prompt:n,jsonResponse:a,model:s,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${T.message}`)}return ls(`completionCall_${e}`,{completion:k,finishReason:g.choices[0].finish_reason}),{finishReason:g.choices[0].finish_reason,completion:k,stats:w}}async function mu(e,r,n){var s,i,c,d,h;const a=await import("fs"),o=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${r}`);try{if(!a.existsSync(r))throw console.log(`CodeYam Test: Fixtures directory does not exist yet: ${r}`),new Error(`No LLM fixture files found - directory does not exist: ${r}`);const u=a.readdirSync(r).filter(x=>x.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${r}`);const m={};for(const x of u)try{const v=a.readFileSync(o.join(r,x),"utf-8"),C=JSON.parse(v);m[C.prompt_type]||(m[C.prompt_type]=[]),m[C.prompt_type].push(C)}catch(v){console.warn(`Failed to parse LLM fixture file ${x}:`,v)}for(const x of Object.keys(m))m[x].sort((v,C)=>{const k=v.created_at??0,N=C.created_at??0;return k-N});const p=m[e];if(!p||p.length===0){const x=Object.keys(m).join(", ");return console.warn(`CodeYam Test: No captured LLM call found for type '${e}'. Available types: ${x}`),{finishReason:"stop",completion:"{}",stats:{model:"fixture-fallback",prompt_type:e,system_message:"",prompt_text:"",response:"{}",input_tokens:0,output_tokens:0,cost:0}}}let f;if(["generateEntityScenarioData","generateChunkMockData","generateMissingMockData"].includes(e)&&n){const x=n.match(/Scenario name must match exactly: "([^"]+)"/),v=x==null?void 0:x[1];if(v){const C={};for(const N of p)try{const A=((s=JSON.parse(N.props||"{}").scenario)==null?void 0:s.name)||"__NO_SCENARIO__";C[A]||(C[A]=[]),C[A].push(N)}catch{}const k=C[v];if(k&&k.length>0){const N=`${r}::${e}::${v}`;lt[N]===void 0&&(lt[N]=0);const E=lt[N];lt[N]=(E+1)%k.length,f=k[E],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${v}' [${E+1}/${k.length}]`)}else{const N=Object.keys(C).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${v}'. Available: [${N}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const x=`${r}::${e}`;lt[x]===void 0&&(lt[x]=0);const v=lt[x];lt[x]=(v+1)%p.length,f=p[v],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${v+1}/${p.length}]`)}let g;try{g=((d=(c=(i=JSON.parse(f.response).choices)==null?void 0:i[0])==null?void 0:c.message)==null?void 0:d.content)||f.response}catch{g=f.response}let b=g;g&&(b=g.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const w=b&&(((h=b.match(/\{[\s\S]*\}/))==null?void 0:h[0])??b);return ls(`completionCall_${e}`,{completion:w||"",finishReason:"stop"}),{finishReason:"stop",completion:w||"",stats:{model:f.model??"fixture",prompt_type:e,system_message:f.system_message??"",prompt_text:f.prompt_text??"",response:f.response??"",input_tokens:f.input_tokens??0,output_tokens:f.output_tokens??0,cost:f.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(u){throw console.error("CodeYam Test Error: Failed to replay LLM call:",u),u}}function Ua(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function pu(e){const{propsJson:r,...n}=e,a=JSON.stringify(r,null,2),o=Kt(),s=Date.now(),i={...n,id:o,created_at:s,props:a};let c;const d=`${i.object_id}_${o}.json`;if(process.env.DYNAMODB_PATH?c=ee.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(c=ee.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),c)try{const u=ee.dirname(c);return await Ie.mkdir(u,{recursive:!0}),await Ie.writeFile(c,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${c}`),{id:o}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const h=Ua();if(!h)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,m]of Object.entries(i))typeof m>"u"&&console.log(`CodeYam Warning: LLM call ${o} property ${u} with explicit value 'undefined'`);try{return await new Tr().send(new qi({TableName:Ua(),Item:Gi(i,{removeUndefinedValues:!0})})),{id:o}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${h}`,u),{id:"-1"}}}new Tr({});new Tr({});new Tr({});const fu=3,gu=2,Wn=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,r)=>16+fu*String(r).length*(1+gu)});new Tn(Wn());new Tn(Wn());new Tn(Wn());class yu{constructor(){this.byMethodName=new Map,this.byClassAndMethod=new Map}register(r,n,a){this.byMethodName.has(r)||this.byMethodName.set(r,[]),this.byMethodName.get(r).push(n),a&&(this.byClassAndMethod.has(a)||this.byClassAndMethod.set(a,new Map),this.byClassAndMethod.get(a).set(r,n))}getByMethodName(r){return this.byMethodName.get(r)}getByClassAndMethod(r,n){var a;return(a=this.byClassAndMethod.get(r))==null?void 0:a.get(n)}}class xu{getReturnType(){return"array"}addEquivalences(r,n,a){a.addType(n,"array"),a.addType(r,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n.withElement("*"))}}isComplete(){return!0}}class bu{getReturnType(){return"boolean"}addEquivalences(r,n,a){a.addType(n,"array"),a.addType(r,"boolean");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n.withElement("*"))}}isComplete(){return!0}}class wu{getReturnType(){return"boolean"}addEquivalences(r,n,a){a.addType(n,"array"),a.addType(r,"boolean");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n.withElement("*"))}}isComplete(){return!0}}class vu{getReturnType(){return"unknown"}addEquivalences(r,n,a){a.addType(n,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n.withElement("*"))}}isComplete(){return!0}}class Cu{getReturnType(){return"unknown"}addEquivalences(r,n,a){a.addType(n,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];if(a.addType(s,"function"),a.addEquivalence(s.withParameter(1),n.withElement("*")),o.args.length>1){const i=o.args[1];a.addEquivalence(s.withParameter(0),i)}}}isComplete(){return!0}}class Nu{getReturnType(){return"unknown"}addEquivalences(r,n,a){a.addType(n,"unknown");const o=r.getLastFunctionCallSegment();o&&o.args.forEach(s=>{a.addEquivalence(r,s)}),a.addEquivalence(r,n.withElement("*"))}isComplete(){return!0}}class Su{getReturnType(){return"unknown"}addEquivalences(r,n,a){a.addType(n,"unknown");const o=r.withReturnValues();a.addType(o,"unknown")}isComplete(){return!0}}class Eu{getReturnType(){return"array"}addEquivalences(r,n,a){a.addType(n,"array"),a.addType(r,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>2)for(let s=2;s<o.args.length;s++){const i=o.args[s];a.addEquivalence(n.withElement("*"),i)}}isComplete(){return!0}}class Au{getReturnType(){return"number"}addEquivalences(r,n,a){a.addType(n,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0)for(let s=0;s<o.args.length;s++)a.addEquivalence(n.withElement("*"),r.withParameter(s))}isComplete(){return!0}}class ku{getReturnType(){return"string"}addEquivalences(r,n,a){a.addType(n,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addEquivalence(r.withParameter(0),s)}}isComplete(){return!0}}class Pu{getReturnType(){return"array"}addEquivalences(r,n,a){a.addType(n,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n.withElement("*"))}}isComplete(){return!0}}class Mu{getReturnType(){return"array"}addEquivalences(r,n,a){a.addType(n,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n.withElement("*"))}}isComplete(){return!0}}class _u{getReturnType(){return"unknown"}addEquivalences(r,n,a){a.addType(n,"unknown"),a.addEquivalence(r.withReturnValues(),n.withElement("*"))}isComplete(){return!0}}class Tu{getReturnType(){return"unknown"}addEquivalences(r,n,a){a.addType(n,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n.withElement("*"))}}isComplete(){return!0}}class Iu{getReturnType(){return"object"}addEquivalences(r,n,a){const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"array")}}isComplete(){return!0}}class $u{getReturnType(){return"string[]"}addEquivalences(r,n,a){a.addType(n,"string"),a.addType(r,"string[]"),a.addEquivalence(r.withReturnValues().withElement("*"),n)}isComplete(){return!0}}class ju{getReturnType(){return"unknown"}addEquivalences(r,n,a){const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n),a.addEquivalence(r.withProperty("functionCallReturnValue"),s.withProperty("returnValue"))}}isComplete(){return!0}}class Ru{getReturnType(){return"unknown"}addEquivalences(r,n,a){r.getLastFunctionCallSegment()}isComplete(){return!0}}class Du{getReturnType(){return"array"}addEquivalences(r,n,a){const o=r.getLastFunctionCallSegment();if(a.addType(r.withParameter(1),"function"),o&&o.args.length>0){const s=o.args[0];a.addEquivalence(r.withParameter(0),s)}}isComplete(){return!0}}function Lu(){const e=new yu;return e.register("filter",new xu,"Array"),e.register("map",new Pu,"Array"),e.register("flatMap",new Mu,"Array"),e.register("join",new ku,"Array"),e.register("find",new vu,"Array"),e.register("findLast",new Tu,"Array"),e.register("at",new _u,"Array"),e.register("reduce",new Cu,"Array"),e.register("concat",new Nu,"Array"),e.register("slice",new Su,"Array"),e.register("splice",new Eu,"Array"),e.register("push",new Au,"Array"),e.register("some",new bu,"Array"),e.register("every",new wu,"Array"),e.register("fromEntries",new Iu,"Object"),e.register("split",new $u,"String"),e.register("then",new ju,"Promise"),e.register("useState",new Du,"React"),e.register("useMemo",new Ru,"React"),e}Lu();new Set(Object.getOwnPropertyNames(Array.prototype).filter(e=>typeof Array.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(String.prototype).filter(e=>typeof String.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Number.prototype).filter(e=>typeof Number.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Boolean.prototype).filter(e=>typeof Boolean.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Date.prototype).filter(e=>typeof Date.prototype[e]=="function"));const Fu=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),Ou=new Set(["find","findLast","at","pop","shift"]),zu=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),Yu=new Set([...Fu,...Ou,...zu]),Bu=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Uu=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Wu=new Set([...Bu,...Uu]);[...Yu,...Wu];class Hu{constructor(r){this.depth=0,this.traceCount=0,this.defaultOutput=(n,a)=>{const o=" ".repeat(this.depth),s=this.timestamps?`[${Date.now()}] `:"";a?console.info(`${s}${o}${n}`,JSON.stringify(a)):console.info(`${s}${o}${n}`)},this.enabled=r.enabled,this.pathPatterns=r.pathPatterns??[],this.scopePatterns=r.scopePatterns??[],this.maxDepth=r.maxDepth??50,this.output=r.output??this.defaultOutput,this.timestamps=r.timestamps??!1}shouldTrace(r){return!this.enabled||this.depth>=this.maxDepth?!1:!!(this.pathPatterns.length===0&&this.scopePatterns.length===0||r.path&&this.pathPatterns.length>0&&this.pathPatterns.some(n=>n.test(r.path))||r.scope&&this.scopePatterns.length>0&&this.scopePatterns.some(n=>n.test(r.scope)))}trace(r,n={}){this.shouldTrace(n)&&(this.traceCount++,this.output(`[TRACE] ${r}`,n))}traceEnter(r,n={}){this.shouldTrace(n)&&(this.traceCount++,this.output(`[ENTER] ${r}`,n),this.depth++)}traceExit(r,n={}){this.depth>0&&this.depth--,this.shouldTrace(n)&&this.output(`[EXIT] ${r}`,n)}traceWarn(r,n={}){this.shouldTrace(n)&&(this.traceCount++,this.output(`[WARN] ${r}`,n))}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 Hu({enabled:!1});function cs(e){if(e==null)return null;const r=e.match(/```json\s*([\s\S]*?)\s*```/);r&&(e=r[1]),e=e.replace(/"[^"]+"\s*:\s*undefined\s*,?\s*/g,""),e=e.replace(/,(\s*[}\]])/g,"$1");try{return Ji.parse(e)}catch(n){const o=n.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),cs(e)}return null}}function qu({description:e,existingScenarios:r,scenariosDataStructure:n,flowSelections:a}){let o="";return a&&a.length>0&&(o=`
|
|
119
|
+
User-selected Execution Flow Values:
|
|
120
|
+
The user has specifically requested these values be used in the scenario:
|
|
121
|
+
${a.map(s=>` - ${s.path}: ${s.value}${s.isCustom?" (custom value)":""}`).join(`
|
|
122
|
+
`)}
|
|
123
|
+
|
|
124
|
+
IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
|
|
125
|
+
`),`Mock Scenario Data Structure:
|
|
126
|
+
\`\`\`
|
|
127
|
+
${JSON.stringify(n,null,2)}
|
|
128
|
+
\`\`\`
|
|
129
|
+
Existing Mock Scenario Data:
|
|
130
|
+
\`\`\`
|
|
131
|
+
${JSON.stringify(r,null,2)}
|
|
132
|
+
\`\`\`
|
|
133
|
+
${o}
|
|
134
|
+
New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
|
|
135
|
+
`}function Ju({description:e,editingMockName:r,editingMockData:n,existingScenarios:a,scenariosDataStructure:o}){const s=a.find(i=>i.name===Ir);return`Mock Scenario Data Structure:
|
|
136
|
+
\`\`\`
|
|
137
|
+
${JSON.stringify({props:o.arguments,dataVariables:o.dataForMocks},null,2)}
|
|
138
|
+
\`\`\`
|
|
139
|
+
|
|
140
|
+
Existing Mock Scenario Data:
|
|
141
|
+
\`\`\`
|
|
142
|
+
${JSON.stringify(a.map(i=>({name:i.name,data:zt(s.metadata.data,i.metadata.data)})),null,2)}
|
|
143
|
+
\`\`\`
|
|
144
|
+
|
|
145
|
+
Mock Scenario that should be edited: "${r}"
|
|
146
|
+
${n?`The portion of the data that should be edited:
|
|
147
|
+
\`\`\`
|
|
148
|
+
${JSON.stringify(n,null,2)}
|
|
149
|
+
\`\`\``:""}
|
|
150
|
+
|
|
151
|
+
How this data should be changed: "${e}"
|
|
152
|
+
`}async function Gu({description:e,editingMockName:r,editingMockData:n,existingScenarios:a,scenariosDataStructure:o,flowSelections:s,model:i}){const c=r?Ju({description:e,editingMockName:r,editingMockData:n,existingScenarios:a,scenariosDataStructure:o}):qu({description:e,existingScenarios:a,scenariosDataStructure:o,flowSelections:s}),d=await bn({type:"guessScenarioDataFromDescription",systemMessage:r?Qu(n):Vu,prompt:c,model:i??eu});await pu({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:r,editingMockData:n,existingScenarios:a,scenariosDataStructure:o,model:i},...d.stats});const{completion:h}=d;return h?cs(h):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const Vu=`
|
|
153
|
+
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.
|
|
154
|
+
|
|
155
|
+
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.
|
|
156
|
+
|
|
157
|
+
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.
|
|
158
|
+
|
|
159
|
+
You must respond with valid JSON following this format of this TS type definition:
|
|
160
|
+
\`\`\`
|
|
161
|
+
export type ScenarioData = {
|
|
162
|
+
name: string;
|
|
163
|
+
description: string;
|
|
164
|
+
data: {
|
|
165
|
+
mockData: { [key: string]: unknown };
|
|
166
|
+
argumentsData: { [key: string]: unknown };
|
|
167
|
+
};
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
\`\`\`
|
|
171
|
+
`,Qu=e=>`
|
|
172
|
+
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.
|
|
173
|
+
|
|
174
|
+
Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
|
|
175
|
+
${e?`
|
|
176
|
+
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.`:""}
|
|
177
|
+
|
|
178
|
+
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.
|
|
179
|
+
|
|
180
|
+
You must respond with valid JSON following this type definition:
|
|
181
|
+
\`\`\`
|
|
182
|
+
{
|
|
183
|
+
data: {
|
|
184
|
+
mockData: { [key: string]: unknown };
|
|
185
|
+
argumentsData: { [key: string]: unknown };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
\`\`\`
|
|
189
|
+
`;async function Ku({request:e}){if(e.method!=="POST")return J({error:"Method not allowed"},{status:405});try{const r=await e.json(),{description:n,existingScenarios:a,scenariosDataStructure:o,editingMockName:s,editingMockData:i,flowSelections:c}=r;if(!n&&(!c||c.length===0))return J({error:"Missing required field: description or flowSelections"},{status:400});const d=await Gu({description:n||"",existingScenarios:a??[],scenariosDataStructure:o,editingMockName:s,editingMockData:i,flowSelections:c}),h=(d==null?void 0:d.data)||d;return J({success:!0,data:h})}catch(r){return console.error("[Generate Scenario Data API] Error:",r),J({error:"Failed to generate scenario data",details:r instanceof Error?r.message:String(r)},{status:500})}}const Zu=Object.freeze(Object.defineProperty({__proto__:null,action:Ku},Symbol.toStringTag,{value:"Module"}));async function Xu(e,r){const n=fe();if(!n)return{entityCalls:[],analysisCalls:[]};const a=ee.join(n,".codeyam","llm-calls");try{await Ie.access(a)}catch{return{entityCalls:[],analysisCalls:[]}}const o=[],s=[];try{const c=(await Ie.readdir(a)).filter(w=>w.endsWith(".json")),d=`${e}_`,h=r?`${r}_`:null,u=[],m=[];for(const w of c)w.startsWith(d)||h&&w.startsWith(h)?u.push(w):m.push(w);const p=u.map(async w=>{try{const x=ee.join(a,w),v=await Ie.readFile(x,"utf-8");return JSON.parse(v)}catch{return null}}),f=m.map(async w=>{try{const x=ee.join(a,w),v=await Ie.readFile(x,"utf-8"),C=JSON.parse(v);return C.object_id===e||r&&C.object_id===r?C:null}catch{return null}}),[y,g]=await Promise.all([Promise.all(p),Promise.all(f)]),b=[...y,...g].filter(w=>w!==null);for(const w of b)w.object_id===e?o.push(w):r&&w.object_id===r&&s.push(w);o.sort((w,x)=>x.created_at-w.created_at),s.sort((w,x)=>x.created_at-w.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:o,analysisCalls:s}}async function eh({params:e,request:r}){const{entitySha:n}=e;if(!n)return J({error:"Entity SHA is required"},{status:400});const o=new URL(r.url).searchParams.get("analysisId")||void 0,s=await Xu(n,o);return J(s)}const th=Object.freeze(Object.defineProperty({__proto__:null,loader:eh},Symbol.toStringTag,{value:"Module"}));function rh(e){const r=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const n=_e("git status --porcelain",{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return nh(n)}catch(n){return console.error("Failed to get git status:",n),[]}}function nh(e){const r=e.trim().split(`
|
|
190
|
+
`).filter(a=>a.length>0),n=[];for(const a of r){const o=a[0],s=a[1];let i=a.slice(2).replace(/^[ \t]+/,""),c,d=!1,h;if(o==="A"||s==="A")c="added",d=o==="A";else if(o==="M"||s==="M")c="modified",d=o==="M";else if(o==="D"||s==="D")c="deleted",d=o==="D";else if(o==="R"||s==="R"){c="renamed",d=o==="R";const u=i.indexOf(" -> ");u!==-1&&(h=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else s==="?"?(c="untracked",d=!1):(c="modified",d=o!==" "&&o!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),m=ue.join(u,i);try{const p=(y,g)=>{const b=Nt.readdirSync(y,{withFileTypes:!0}),w=[];for(const x of b){const v=ue.join(y,x.name),C=ue.relative(u,v);x.isDirectory()?w.push(...p(v,g)):x.isFile()&&w.push(C)}return w},f=p(m,u);for(const y of f)n.push({path:y,status:c,staged:d,...h&&{oldPath:h}})}catch(p){console.error(`Failed to expand directory ${i}:`,p)}}else n.push({path:i,status:c,staged:d,...h&&{oldPath:h}})}return n}function ah(e){const r=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return _e("git branch --show-current",{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch(n){return console.error("Failed to get current branch:",n),null}}function oh(e){const r=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const a=_e('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""',{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().match(/refs\/remotes\/origin\/(.+)/);if(a)return a[1];try{return _e("git show-ref --verify --quiet refs/heads/main",{cwd:r,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return _e("git show-ref --verify --quiet refs/heads/master",{cwd:r,stdio:["pipe","pipe","ignore"]}),"master"}catch{return"main"}}}catch(n){return console.error("Failed to get default branch:",n),"main"}}function sh(e){const r=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return _e('git branch --format="%(refname:short)"',{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
191
|
+
`).filter(a=>a.length>0)}catch(n){return console.error("Failed to get branches:",n),[]}}function ds(){const e=fe();return e?rh(e):[]}function ih(){const e=fe();return e?ah(e):null}function lh(){const e=fe();return e?oh(e):"main"}function ch(){const e=fe();return e?sh(e):[]}function us(e,r){const n=fe();return n?dh(e,r,n):[]}function dh(e,r,n){const a=n||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return _e(`git diff --name-status ${e}...${r}`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
192
|
+
`).filter(i=>i.length>0).map(i=>{const c=i.split(" "),d=c[0];let h=c[1],u,m;return d==="A"?m="added":d==="M"?m="modified":d==="D"?m="deleted":d.startsWith("R")?(m="renamed",u=c[1],h=c[2]):m="modified",{path:h,status:m,...u&&{oldPath:u}}})}catch(o){return console.error("Failed to get branch diff:",o),[]}}function uh(e,r){const n=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let a="";try{a=_e(`git show HEAD:"${e}"`,{cwd:n,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{a=""}let o="";try{o=Nt.readFileSync(ue.join(n,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 hh(e){const r=fe();return r?uh(e,r):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function mh(e,r,n,a){const o=a||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=_e(`git show ${r}:"${e}"`,{cwd:o,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let i="";try{i=_e(`git show ${n}:"${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 pr(e,r,n){const a=fe();return a?mh(e,r,n,a):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Wa(e,r){var n,a;try{return((a=(n=_e(`git rev-parse ${e}`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:n.toString())==null?void 0:a.trim())??null}catch(o){return console.error(`Failed to get commit SHA for ${e}:`,o),""}}function ph(e,r,n,a){const o=kn.createHash("sha256");return o.update(`${e}:${r}:${n}:${a}`),o.digest("hex").substring(0,16)}function hs(){const e=fe();if(!e)throw new Error("No project root found");const r=ue.join(e,".codeyam","cache","branch-entity-diff");return Nt.existsSync(r)||Nt.mkdirSync(r,{recursive:!0}),r}function fh(e){try{const r=hs(),n=ue.join(r,`${e}.json`);if(!Nt.existsSync(n))return null;const a=Nt.readFileSync(n,"utf8");return JSON.parse(a)}catch(r){return console.error("Failed to read cache:",r),null}}function gh(e,r){try{const n=hs(),a=ue.join(n,`${e}.json`);Nt.writeFileSync(a,JSON.stringify(r,null,2))}catch(n){console.error("Failed to write cache:",n)}}function yh(e,r,n){const a=xr(r,e),o=xr(n,e),s=new Map(a.map(u=>[u.name,u])),i=new Map(o.map(u=>[u.name,u])),c=[],d=[],h=[];for(const[u,m]of i){const p=s.get(u);p?p.sha!==m.sha&&d.push({name:u,baseSha:p.sha,compareSha:m.sha,entityType:m.entityType}):c.push(m)}for(const[u,m]of s)i.has(u)||h.push(m);return{filePath:e,newEntities:c,modifiedEntities:d,deletedEntities:h}}function xh(e,r){const n=fe();if(!n)throw new Error("No project root found");const a=Wa(e,n),o=Wa(r,n);if(!a||!o)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${r}`);const s=ph(e,r,a,o),i=fh(s);if(i)return console.log(`Using cached branch entity diff: ${s}`),i;const c=us(e,r),d=[];for(const u of c)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const m=pr(u.path,e,r),p=xr(m.oldContent,u.path);d.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:p})}else if(u.status==="added"){const m=pr(u.path,e,r),p=xr(m.newContent,u.path);d.push({filePath:u.path,newEntities:p,modifiedEntities:[],deletedEntities:[]})}else{const m=pr(u.path,e,r),p=yh(u.path,m.oldContent,m.newContent);(p.newEntities.length>0||p.modifiedEntities.length>0||p.deletedEntities.length>0)&&d.push(p)}const h={baseBranch:e,compareBranch:r,baseCommitSha:a,compareCommitSha:o,fileComparisons:d,cacheKey:s,computedAt:new Date().toISOString()};return gh(s,h),h}function bh({request:e}){try{const r=new URL(e.url),n=r.searchParams.get("base"),a=r.searchParams.get("compare");if(!n||!a)return J({error:"Missing required parameters: base and compare"},{status:400});const o=xh(n,a);return J(o)}catch(r){return console.error("Failed to compute branch entity diff:",r),J({error:"Failed to compute branch entity diff",details:r instanceof Error?r.message:String(r)},{status:500})}}const wh=Object.freeze(Object.defineProperty({__proto__:null,loader:bh},Symbol.toStringTag,{value:"Module"}));async function vh({request:e}){if(e.method!=="POST")return J({error:"Method not allowed"},{status:405});try{const r=await e.json(),{serverUrl:n,scenarioId:a,projectId:o,viewportWidth:s=1440}=r;if(!n||!a||!o)return J({error:"Missing required fields: serverUrl, scenarioId, and projectId"},{status:400});console.log(`[Capture] URL to capture: ${n}`),console.log(`[Capture] Scenario ID from request: ${a}`);const i=fe();if(!i)return J({error:"Project root not found"},{status:500});const c=ee.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:n,scenarioId:a,projectId:o,projectRoot:i,viewportWidth:s}),h=await new Promise(p=>{const f=ee.join(i,".codeyam","db.sqlite3"),y=_r("npx",["tsx",c,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let g="",b="";y.stdout.on("data",w=>{const x=w.toString();g+=x;const v=x.trim().split(`
|
|
193
|
+
`);for(const C of v)C.includes("[Capture]")&&console.log(C)}),y.stderr.on("data",w=>{const x=w.toString();b+=x,console.error("[Capture:Error]",x.trim())}),y.on("close",w=>{p(w===0?{success:!0,output:g}:{success:!1,output:g,error:b||`Process exited with code ${w}`})}),y.on("error",w=>{console.error("[Capture] Failed to spawn child process:",w),p({success:!1,output:"",error:w.message})})});if(!h.success)return J({error:"Failed to capture screenshot",details:h.error},{status:500});const u=h.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return J({error:"Failed to parse capture result"},{status:500});const m=JSON.parse(u[1]);return J(m)}catch(r){return console.error("[Capture] Error:",r),J({error:"Failed to capture screenshot",details:r instanceof Error?r.message:String(r)},{status:500})}}const Ch=Object.freeze(Object.defineProperty({__proto__:null,action:vh},Symbol.toStringTag,{value:"Module"}));async function Nh(e,r,n){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${r}`),await $e();const a=await at({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const o=ve(),s=a.entitySha,i=await o.selectFrom("entities").select(["metadata"]).where("sha","=",s).executeTakeFirst();let c={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?c=JSON.parse(i.metadata):c=i.metadata),c.defaultWidth=r,await o.updateTable("entities").set({metadata:JSON.stringify(c)}).where("sha","=",s).execute(),console.log(`[recapture] Updated defaultWidth for entity ${s} to ${r}`),!a.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=a.scenarios)==null?void 0:f.length)||0} scenarios`),await Tt(e,y=>{if(y){if(y.readyToBeCaptured=!0,y.scenarios)for(const g of y.scenarios)delete g.finishedAt,delete g.startedAt,delete g.screenshotStartedAt,delete g.screenshotFinishedAt,delete g.interactiveStartedAt,delete g.interactiveFinishedAt,delete g.error,delete g.errorStack;delete y.finishedAt}}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const d=fe();if(!d)throw new Error("Project root not found");const h=ee.join(d,".codeyam","config.json"),u=JSON.parse(K.readFileSync(h,"utf8")),{projectSlug:m}=u;if(!m)throw new Error("Project slug not found in config");const{jobId:p}=n.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:m,analysisId:e,defaultWidth:r});return console.log(`[recapture] Recapture job queued with ID: ${p}`),{jobId:p}}async function Sh(e,r,n){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${r}`),await $e();const a=await at({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=(u=a.scenarios)==null?void 0:u.find(m=>m.id===r);if(!o)throw console.log(`[recapture] Scenario ${r} not found in analysis ${e}`),new Error(`Scenario ${r} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${o.name}`),await Tt(e,m=>{if(m&&(m.readyToBeCaptured=!0,delete m.finishedAt,m.scenarios)){const p=m.scenarios.find(f=>f.name===o.name);p&&(delete p.finishedAt,delete p.startedAt,delete p.error,delete p.errorStack,delete p.screenshotStartedAt,delete p.screenshotFinishedAt,delete p.interactiveStartedAt,delete p.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${o.name} for recapture`);const s=fe();if(!s)throw new Error("Project root not found");const i=ee.join(s,".codeyam","config.json"),c=JSON.parse(K.readFileSync(i,"utf8")),{projectSlug:d}=c;if(!d)throw new Error("Project slug not found in config");const{jobId:h}=n.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:d,analysisId:e,scenarioId:r});return console.log(`[recapture] Scenario recapture job queued with ID: ${h}`),{jobId:h}}async function Eh({request:e,context:r}){if(e.method!=="POST")return J({error:"Method not allowed"},{status:405});let n=r.analysisQueue;if(n||(n=await st()),!n)return J({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("analysisId"),s=a.get("scenarioId");if(!o||!s)return J({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${o}, scenario ${s}`);const i=await Sh(o,s,n);return console.log("[API] Scenario recapture queued",i),J({success:!0,message:"Scenario recapture queued",...i})}catch(a){return console.log("[API] Error during scenario recapture:",a),J({error:"Failed to recapture scenario",details:a instanceof Error?a.message:String(a)},{status:500})}}const Ah=Object.freeze(Object.defineProperty({__proto__:null,action:Eh},Symbol.toStringTag,{value:"Module"}));async function kh({params:e,request:r}){const{projectSlug:n}=e;if(!n)return new Response("Project slug is required",{status:400});if(r.method!=="DELETE")return new Response("Method not allowed",{status:405});const a=Dr(n);try{return await Ri(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 Ph({params:e}){const{projectSlug:r}=e;if(!r)return new Response("Project slug is required",{status:400});const n=Dr(r);try{if(!Pi(n))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 Di(n,"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 Mh=Object.freeze(Object.defineProperty({__proto__:null,action:kh,loader:Ph},Symbol.toStringTag,{value:"Module"}));async function _h(e,r){var s,i,c,d,h,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${r}`),await $e();const n=await at({id:e,includeScenarios:!0,includeFile:!0});if(!n)throw new Error(`Analysis ${e} not found`);const a=(s=n.scenarios)==null?void 0:s.find(m=>m.id===r);if(!a)throw new Error(`Scenario ${r} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${n.entityName} with scenario ${a.name}`);const o={returnValue:{status:"success",data:((d=(c=(i=a.metadata)==null?void 0:i.data)==null?void 0:c.argumentsData)==null?void 0:d[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${n.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(h=a.metadata)==null?void 0:h.data)==null?void 0:u.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${n.entityName}`),o}async function Th({request:e}){if(e.method!=="POST")return J({error:"Method not allowed"},{status:405});try{const r=await e.formData(),n=r.get("analysisId"),a=r.get("scenarioId");if(!n||!a)return J({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${n}, scenario ${a}`);const o=await _h(n,a);return console.log("[API] Function execution completed successfully"),J({success:!0,result:o})}catch(r){return console.log("[API] Error during function execution:",r),J({success:!1,error:"Failed to execute function",details:r instanceof Error?r.message:String(r)},{status:500})}}const Ih=Object.freeze(Object.defineProperty({__proto__:null,action:Th},Symbol.toStringTag,{value:"Module"}));function $h({request:e}){return J({status:"ok"})}async function jh({request:e,context:r}){if(e.method!=="POST")return J({error:"Method not allowed"},{status:405});let n=r.analysisQueue;if(n||(n=await st()),!n)return console.error("[Interactive Mode API] Queue not initialized"),J({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 J({error:"Missing required fields: action and analysisId"},{status:400});if(o!=="start"&&o!=="stop")return J({error:'Invalid action. Must be "start" or "stop"'},{status:400});const c=await ze();if(console.log("[Interactive Mode API] projectSlug:",c),!c)return J({error:"Project not initialized"},{status:500});if(o==="start"){const d=await n.enqueue({type:"interactive-start",analysisId:s,scenarioId:i,projectSlug:c});return J({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await n.enqueue({type:"interactive-stop",analysisId:s,projectSlug:c});return J({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),J({error:"Failed to control interactive mode",details:o},{status:500})}}const Rh=Object.freeze(Object.defineProperty({__proto__:null,action:jh,loader:$h},Symbol.toStringTag,{value:"Module"}));async function Dh({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const r=await e.json(),{scenarioId:n,screenshotPaths:a}=r;if(!n)return Response.json({error:"Missing required field: scenarioId"},{status:400});if(console.log(`[API] Deleting scenario ${n}`),a&&a.length>0){const o=fe();if(o)for(const s of a){const i=ue.join(o,".codeyam","captures","screenshots",s);try{await pe.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(c){console.log(`[API] Could not delete screenshot ${i}:`,c instanceof Error?c.message:c)}}}return await Hl({ids:[n]}),console.log(`[API] Scenario ${n} deleted successfully`),Response.json({success:!0,message:"Scenario deleted successfully"})}catch(r){return console.error("[API] Error deleting scenario:",r),Response.json({error:"Failed to delete scenario",details:r instanceof Error?r.message:String(r)},{status:500})}}const Lh=Object.freeze(Object.defineProperty({__proto__:null,action:Dh},Symbol.toStringTag,{value:"Module"})),Gt="/tmp/codeyam",wn=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",ms=500,Fh=ms*1024*1024;function wt(e,r){try{return _e(`git ${e}`,{cwd:r,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 Oh(e){return wt("config user.email",e)}function zh(e){const r=ee.join(e,".codeyam","debug-report.md");if(!K.existsSync(r))return null;try{return K.readFileSync(r,"utf8")}catch{return null}}function Yh(e,r=20){const n=ee.join(Gt,"local-dev",e,"codeyam","log.txt");if(!K.existsSync(n))return[];try{return K.readFileSync(n,"utf8").split(`
|
|
194
|
+
`).filter(i=>i.includes("CodeYam Log Level 1")).slice(-r)}catch{return[]}}async function Bh(e){try{const r=await fetch(`${wn}/api/reports/check-base`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseSha:e})});if(!r.ok)return!1;const{hasBase:n}=await r.json();return n}catch{return!1}}function Uh(e,r){try{_e(`git archive HEAD | gzip > "${r}"`,{cwd:e,stdio:"pipe",shell:"/bin/bash"})}catch(n){throw new Error(`Failed to create base archive: ${n.message}`)}}function Wh(e){const{projectRoot:r,projectSlug:n,outputPath:a,metadata:o,screenshot:s,onProgress:i}=e,c=i||(()=>{}),d=Date.now(),h=ee.join(Gt,`delta-staging-${d}`),u=ee.join(h,"delta");K.mkdirSync(u,{recursive:!0});try{const m=wt("diff --binary HEAD",r)||"";K.writeFileSync(ee.join(u,"tracked.patch"),m?m+`
|
|
195
|
+
`:"");const p=wt("ls-files --others --exclude-standard",r);if(p){const b=ee.join(u,"untracked");K.mkdirSync(b,{recursive:!0});for(const w of p.split(`
|
|
196
|
+
`).filter(Boolean)){const x=ee.join(r,w),v=ee.join(b,w);if(K.existsSync(x)){const C=ee.dirname(v);K.mkdirSync(C,{recursive:!0}),K.statSync(x).isFile()&&K.copyFileSync(x,v)}}}const f=ee.join(r,".codeyam");if(K.existsSync(f)){const b=ee.join(u,"codeyam");K.cpSync(f,b,{recursive:!0})}K.writeFileSync(ee.join(u,"meta.json"),JSON.stringify(o,null,2));const y=ee.join(Gt,"local-dev",n,"codeyam","log.txt");K.existsSync(y)?K.copyFileSync(y,ee.join(u,"codeyam-log.txt")):K.writeFileSync(ee.join(u,"codeyam-log.txt"),`# Log file not found
|
|
197
|
+
`);const g=ee.join(r,".codeyam","debug-report.md");K.existsSync(g)&&(K.copyFileSync(g,ee.join(u,"debug-report.md")),c("Debug report included")),s&&s.length>0&&(K.writeFileSync(ee.join(u,"screenshot.jpg"),s),c(`Screenshot included (${fr(s.length)})`));try{_e(`tar -czf "${a}" -C "${h}" delta`,{stdio:"pipe"})}catch(b){throw new Error(`tar failed: ${b.message}`)}}finally{K.rmSync(h,{recursive:!0,force:!0})}}async function Hh(e){const{projectRoot:r,projectSlug:n,feedback:a,screenshot:o,onProgress:s}=e,i=s||(()=>{});i("Gathering metadata...");const c=wt("rev-parse HEAD",r);if(!c)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const d=wt("rev-parse --abbrev-ref HEAD",r)||"unknown",h=wt("status --porcelain",r),u=wt("remote get-url origin",r),m=h!==null&&h.length>0,p=Zo(n),f=zh(r);let y=a;f&&(y={...a||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /codeyam:diagnose workflow"));const g={timestamp:new Date().toISOString(),projectSlug:n,git:{sha:c,branch:d,isDirty:m,remoteUrl:u},versions:{cli:p.cliVersion,webserver:p.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:y},b=Date.now(),w=ee.join(Gt,`base-${c}-${b}.tar.gz`),x=ee.join(Gt,`delta-${n}-${b}.tar.gz`);i("Checking for existing base...");const v=await Bh(c);let C=null;v?i("Server already has base, skipping..."):(i("Generating base archive..."),Uh(r,w),C=K.statSync(w).size,i(`Base archive: ${fr(C)}`)),i("Generating delta archive..."),Wh({projectRoot:r,projectSlug:n,outputPath:x,metadata:g,screenshot:o,onProgress:s});const N=K.statSync(x).size;i(`Delta archive: ${fr(N)}`);const E=(C||0)+N;if(E>Fh)throw K.existsSync(w)&&K.unlinkSync(w),K.unlinkSync(x),new Error(`Bundle too large: ${fr(E)} (max: ${ms} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:v?null:w,deltaPath:x,metadata:g,baseSha:c,baseSize:C,deltaSize:N}}async function qh(e){const{basePath:r,deltaPath:n,projectSlug:a,metadata:o,baseSha:s,deltaSize:i,onProgress:c}=e,d=c||(()=>{}),h=K.statSync(n),u=r?K.statSync(r):null,m=h.size+((u==null?void 0:u.size)||0);d("Requesting upload URLs...");const p=await fetch(`${wn}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:a,fileSizeBytes:m,baseSha:s,needsBaseUpload:r!==null,deltaSizeBytes:i,metadata:{timestamp:o.timestamp,git:o.git,versions:o.versions,system:o.system,feedback:o.feedback}})});if(!p.ok){const v=await p.json();throw new Error(v.error||`Server returned ${p.status}`)}const{reportId:f,deltaUploadUrl:y,baseUploadUrl:g}=await p.json(),b=[];if(r&&g){d("Uploading base...");const v=K.readFileSync(r);b.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:v}).then(C=>{if(!C.ok)throw new Error(`Base upload failed: ${C.status}`)}))}d("Uploading delta...");const w=K.readFileSync(n);b.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:w}).then(v=>{if(!v.ok)throw new Error(`Delta upload failed: ${v.status}`)})),await Promise.all(b),d("Confirming upload...");const x=await fetch(`${wn}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!x.ok){const v=await x.json();throw new Error(v.error||`Confirm failed: ${x.status}`)}return r&&K.existsSync(r)&&K.unlinkSync(r),K.unlinkSync(n),{bundleId:f}}async function Jh({request:e}){if(e.method!=="POST")return J({error:"Method not allowed"},{status:405});try{const r=await e.formData(),n=r.get("issueType"),a=r.get("description"),o=r.get("email"),s=r.get("source"),i=r.get("entitySha"),c=r.get("scenarioId"),d=r.get("analysisId"),h=r.get("currentUrl"),u=r.get("entityName"),m=r.get("entityType"),p=r.get("scenarioName"),f=r.get("errorMessage"),y=r.get("screenshot");let g=a||void 0;!g&&u&&(p?g=`Issue on ${u} scenario "${p}"`:g=`Issue on ${u}`);let b;if(y&&y.size>0){const E=await y.arrayBuffer();b=Buffer.from(E),console.log(`[Bundle] Screenshot received: ${y.size} bytes`)}const w=fe();if(!w)return J({error:"Project root not found"},{status:500});const x=await ze();if(!x)return J({error:"Project slug not found"},{status:500});const v={issueType:n||"other",description:g,email:o||void 0,source:s||"navbar",entitySha:i||void 0,scenarioId:c||void 0,analysisId:d||void 0,currentUrl:h||void 0,recentActivity:Yh(x,20),entityName:u||void 0,entityType:m||void 0,scenarioName:p||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${x}...`),console.log(`[Bundle] Context: ${v.source}, issue: ${v.issueType}`);const C=await Hh({projectRoot:w,projectSlug:x,feedback:v,screenshot:b,onProgress:E=>{console.log(`[Bundle] ${E}`)}}),k=(C.baseSize||0)+C.deltaSize;console.log(`[Bundle] Archives created: delta=${C.deltaSize} bytes${C.basePath?`, base=${C.baseSize} bytes`:" (base reused)"}`);const N=await qh({basePath:C.basePath,deltaPath:C.deltaPath,projectSlug:x,metadata:C.metadata,baseSha:C.baseSha,deltaSize:C.deltaSize,onProgress:E=>{console.log(`[Bundle] ${E}`)}});return console.log(`[Bundle] Upload complete: ${N.bundleId}`),J({success:!0,reportId:N.bundleId,size:k})}catch(r){return console.error("[Bundle] Error:",r),J({error:r.message||"Failed to generate bundle"},{status:500})}}function Gh(){const e=fe(),r=e?Oh(e):null;return J({defaultEmail:r})}const Vh=Object.freeze(Object.defineProperty({__proto__:null,action:Jh,loader:Gh},Symbol.toStringTag,{value:"Module"}));function Ct(){const e=process.memoryUsage(),r=Vi.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(r.total_heap_size/1024/1024),totalHeapSizeExecutable:Math.round(r.total_heap_size_executable/1024/1024),totalPhysicalSize:Math.round(r.total_physical_size/1024/1024),totalAvailableSize:Math.round(r.total_available_size/1024/1024),usedHeapSize:Math.round(r.used_heap_size/1024/1024),heapSizeLimit:Math.round(r.heap_size_limit/1024/1024),mallocedMemory:Math.round(r.malloced_memory/1024/1024),peakMallocedMemory:Math.round(r.peak_malloced_memory/1024/1024)},system:{totalMemory:Math.round(pn.totalmem()/1024/1024),freeMemory:Math.round(pn.freemem()/1024/1024)}}}function Qh(){const e=Ct();console.log(`
|
|
198
|
+
[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 r=(e.heap.usedHeapSize/e.heap.heapSizeLimit*100).toFixed(1);return console.log(` Heap Usage: ${r}% of limit`),e}function Kh(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=Ct();global.gc();const r=Ct(),n=e.process.heapUsed-r.process.heapUsed;return console.log(`[Memory Profiler] GC freed ${n} MB`),console.log(`[Memory Profiler] Heap: ${r.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 Zh(){const e=Ct(),r=e.heap.usedHeapSize/e.heap.heapSizeLimit*100,n={highHeapUsage:r>80,highExternalMemory:e.process.external>200,highArrayBuffers:e.process.arrayBuffers>100,nearHeapLimit:e.heap.totalAvailableSize<100},a=[];return n.highHeapUsage&&a.push(`High heap usage: ${r.toFixed(1)}% of limit`),n.highExternalMemory&&a.push(`High external memory: ${e.process.external} MB`),n.highArrayBuffers&&a.push(`High ArrayBuffer usage: ${e.process.arrayBuffers} MB`),n.nearHeapLimit&&a.push(`Near heap limit: only ${e.heap.totalAvailableSize} MB available`),{indicators:n,warnings:a,hasIssues:a.length>0}}function Xh({request:e}){const n=new URL(e.url).searchParams.get("action");try{switch(n){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=Kh(),o=Ct();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=Qh();return Response.json({success:!0,stats:a})}case"leaks":{const a=Zh(),o=Ct();return Response.json({success:!0,leakCheck:a,stats:o})}default:{const a=Ct();return Response.json({success:!0,stats:a,actions:{gc:"/api/memory-profile?action=gc - Force garbage collection (requires --expose-gc)",detailed:"/api/memory-profile?action=detailed - Log detailed stats to console",leaks:"/api/memory-profile?action=leaks - Check for memory leak indicators"}})}}}catch(a){return console.error("[Memory API] Error:",a),Response.json({success:!1,error:a.message},{status:500})}}const em=Object.freeze(Object.defineProperty({__proto__:null,loader:Xh},Symbol.toStringTag,{value:"Module"})),Ha=_n(Pn);async function tm({request:e}){const n=new URL(e.url).searchParams.get("pids");if(!n)return Response.json({error:"Missing pids parameter"},{status:400});const a=n.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=rm(s),c=i?await nm(s):null;return{pid:s,isRunning:i,processName:c}}));return Response.json({processes:o})}function rm(e){try{return process.kill(e,0),!0}catch{return!1}}async function nm(e){try{const{stdout:r}=await Ha(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:n}=await Ha(`ps -p ${e} -o args=`),a=n.trim(),o=a.match(/codeyam-(\w+)/);return o?`codeyam-${o[1]}`:a.split(" ")[0]||null}catch{return null}}}const am=Object.freeze(Object.defineProperty({__proto__:null,loader:tm},Symbol.toStringTag,{value:"Module"})),om=Mn(import.meta.url),sm=ee.dirname(om);function im({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const r=es(),n=fe()||(r==null?void 0:r.projectRoot);if(!n)throw new Error("Could not determine project root");const a=(r==null?void 0:r.port)||3111,o=ee.join(sm,"..","..","..","..","webserver","bootstrap.js"),s=ee.join(n,".codeyam","logs");K.existsSync(s)||K.mkdirSync(s,{recursive:!0});const i=K.openSync(ee.join(s,"background-server.log"),"a"),c=K.openSync(ee.join(s,"background-server-error.log"),"a"),d=new Date().toISOString();K.appendFileSync(ee.join(s,"background-server.log"),`
|
|
199
|
+
[${d}] Server restart requested via dashboard
|
|
200
|
+
`),qc();const h=_r("node",[o],{detached:!0,stdio:["ignore",i,c],env:{...process.env,CODEYAM_PORT:a.toString(),CODEYAM_ROOT_PATH:n,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});h.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${h.pid})`);const u=new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}});return setTimeout(()=>{console.log("[api.restart-server] Exiting old server process"),process.exit(0)},100),u}catch(r){return console.error("[api.restart-server] Error restarting server:",r),new Response(JSON.stringify({success:!1,error:r instanceof Error?r.message:"Unknown error"}),{status:500,headers:{"Content-Type":"application/json"}})}}const lm=Object.freeze(Object.defineProperty({__proto__:null,action:im},Symbol.toStringTag,{value:"Module"}));async function cm({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const r=await e.json(),{analysis:n,scenarios:a}=r;if(!n||!a)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${n.id}`),console.log(`[API] Received ${a.length} scenarios to save`),a.forEach((c,d)=>{var m,p,f,y,g;const h=(p=(m=c.metadata)==null?void 0:m.data)==null?void 0:p.argumentsData,u=Array.isArray(h)&&h.length>0?JSON.stringify(h[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${d}: ${c.name}`,{id:c.id,projectId:c.projectId,analysisId:c.analysisId,hasMetadata:!!c.metadata,hasData:!!((f=c.metadata)!=null&&f.data),mockDataKeys:(g=(y=c.metadata)==null?void 0:y.data)!=null&&g.mockData?Object.keys(c.metadata.data.mockData):[],argumentsDataLength:Array.isArray(h)?h.length:"not-array",argumentsDataPreview:u})});const o=a.map(c=>({...c,projectId:c.projectId||n.projectId,analysisId:c.analysisId||n.id})),s=await lc(o);if(!s||s.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${n.id}`),console.log(`[API] Saved ${s.length} scenarios to database`),s.forEach((c,d)=>{var u,m;const h=(m=(u=c.metadata)==null?void 0:u.data)==null?void 0:m.argumentsData;console.log(`[API] Saved scenario ${d}: ${c.name}`,{id:c.id,argumentsDataLength:Array.isArray(h)?h.length:"not-array"})});const i={...n,scenarios:s};return Response.json({success:!0,analysis:i})}catch(r){return console.error("[API] Error saving scenarios:",r),Response.json({error:"Failed to save scenarios",details:r instanceof Error?r.message:String(r)},{status:500})}}const dm=Object.freeze(Object.defineProperty({__proto__:null,action:cm},Symbol.toStringTag,{value:"Module"}));async function um({request:e}){try{const r=await e.json(),{pid:n,signal:a="SIGTERM",commitSha:o}=r;if(!n||typeof n!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!qa(n))return Response.json({error:"Process not running",pid:n},{status:404});try{process.kill(n,a)}catch(u){return Response.json({error:"Failed to kill process",pid:n,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,c=500,d=Date.now();let h=!0;for(;h&&Date.now()-d<i;)await new Promise(u=>setTimeout(u,c)),h=qa(n);if(h){console.warn(`Process ${n} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(n,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${n}:`,u)}}if(o)try{await ct({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${n} killed by user`}})}catch(u){console.error("Failed to update database after killing process:",u)}return Response.json({success:!0,pid:n,signal:a,message:`Process ${n} killed successfully`,waitedMs:Date.now()-d})}catch(r){return console.error("Error in kill-process API:",r),Response.json({error:"Internal server error",details:r instanceof Error?r.message:String(r)},{status:500})}}function qa(e){try{return process.kill(e,0),!0}catch{return!1}}const hm=Object.freeze(Object.defineProperty({__proto__:null,action:um},Symbol.toStringTag,{value:"Module"}));async function mm({params:e}){const r=e["*"];if(!r)return new Response("Screenshot path is required",{status:400});const n=fe();if(!n)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const a=ue.join(n,".codeyam","captures","screenshots",r);try{await pe.access(a);const o=await pe.readFile(a),s=ue.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 pm=Object.freeze(Object.defineProperty({__proto__:null,loader:mm},Symbol.toStringTag,{value:"Module"})),Ja={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 Hn({type:e,className:r=""}){const n=Ja[e]||Ja.other;return t("div",{className:`inline-flex items-center justify-center px-[4px] rounded-[4px] ${r}`,style:{backgroundColor:n.bgColor,color:n.textColor,height:"15px"},children:t("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-semibold leading-[15px] uppercase",children:n.label})})}const fm={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 dr({variant:e,pid:r,label:n,className:a=""}){const o=fm[e],s=n||(e==="analyzer"&&r?`Analyzer: ${r}`:e==="capture"&&r?`Capture: ${r}`:e==="running"?"Running":e==="error"?"Error":"");return t("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:t("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:o.textColor},children:s})})}function De({screenshotPath:e,cacheBuster:r,alt:n,className:a="",title:o}){const[s,i]=P("loading"),[c,d]=P(!1),h=Ee(null),u=r?`/api/screenshot/${e}?cb=${r}`:`/api/screenshot/${e}`,m=()=>{i("success"),d(!0)},p=()=>{i("error"),d(!1)};return te(()=>{i("loading"),d(!1);const f=h.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[u]),e?l("div",{className:"relative w-full h-full flex items-center justify-center",title:o,children:[t("img",{ref:h,src:u,alt:n,onLoad:m,onError:p,className:a||"max-w-full max-h-full object-contain",style:{visibility:c?"visible":"hidden",position:c?"relative":"absolute"}}),s==="loading"&&t("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:t("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t("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"&&l("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:[t("span",{className:"text-2xl text-gray-400",children:"📷"}),t("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):t("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:t("span",{className:"text-2xl text-gray-400",children:"📷"})})}let Ga=!1;function gm(){if(Ga)return;const e=document.createElement("style");e.textContent=`
|
|
201
|
+
@keyframes strongPulse {
|
|
202
|
+
0%, 100% { opacity: 0.2; }
|
|
203
|
+
50% { opacity: 1; }
|
|
204
|
+
}
|
|
205
|
+
`,document.head.appendChild(e),Ga=!0}function qn({size:e="medium",className:r=""}){typeof document<"u"&&gm();const n={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:a,centerDotSize:o,gap:s}=n[e];return l("div",{className:`flex items-center justify-center ${r}`,style:{gap:`${s}px`},role:"status","aria-label":"Loading",children:[t("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),t("div",{className:"rounded-full",style:{width:`${o}px`,height:`${o}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),t("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}async function ym({request:e,context:r,params:n}){var D,L,_,S,F,O,H,ae;let a=r.analysisQueue;a||(a=await st());const o=new URL(e.url),s=parseInt(o.searchParams.get("page")||"1",10),i=20,c=n.tab||"current";if(!a)return J({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:c,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const d=a.getState(),h=await ze();let u=null;if(h&&((D=d==null?void 0:d.currentlyExecuting)!=null&&D.commitSha)){const{project:V,branch:Y}=await Fe(h),W=await br({projectId:V.id,branchId:Y.id,shas:[d.currentlyExecuting.commitSha]});u=W&&W.length>0?W[0]:null}else u=await It();const m=async V=>{const Y=await Mt(V);if(!Y)return null;const{getAnalysesForEntity:W}=await Promise.resolve().then(()=>Cc),Q=await W(V,!1);return{...Y,analyses:Q||[]}},p=await Promise.all(((d==null?void 0:d.jobs)||[]).map(async V=>{const Y=[];if(V.entityShas&&V.entityShas.length>0){const W=V.entityShas.map(q=>m(q)),Q=await Promise.all(W);Y.push(...Q.filter(q=>q!==null))}return{...V,entities:Y}}));let f=null;if(d!=null&&d.currentlyExecuting){const V=d.currentlyExecuting,Y=[];if(V.entityShas&&V.entityShas.length>0){const W=V.entityShas.map(q=>m(q)),Q=await Promise.all(W);Y.push(...Q.filter(q=>q!==null))}f={...V,entities:Y}}const y=f?p.filter(V=>V.id!==f.id):p,g=((_=(L=u==null?void 0:u.metadata)==null?void 0:L.currentRun)==null?void 0:_.currentEntityShas)||[],w=(await Promise.all(g.map(V=>m(V)))).filter(V=>V!==null),x=[];if(h)try{const{project:V,branch:Y}=await Fe(h),W=await br({projectId:V.id,branchId:Y.id,limit:100});for(const Q of W){const q=((S=Q.metadata)==null?void 0:S.historicalRuns)||[];x.push(...q)}}catch(V){console.error("[activity.tsx] Failed to load historical runs from commits:",V)}const v=[...x].sort((V,Y)=>{const W=V.lastCaptureAt||V.analysisCompletedAt||V.archivedAt||V.createdAt||"";return(Y.lastCaptureAt||Y.analysisCompletedAt||Y.archivedAt||Y.createdAt||"").localeCompare(W)}),C=(s-1)*i,k=C+i,N=v.slice(C,k),E=Math.ceil(v.length/i),A=await Promise.all(N.map(async V=>{const Y=V.currentEntityShas||[];if(Y.length===0)return{...V,entities:[]};const W=await Promise.all(Y.map(Q=>m(Q)));return{...V,entities:W.filter(Q=>Q!==null)}})),I=!!f,j=y.length,R=v.filter(V=>{const Y=!!V.failedAt,W=V.readyToBeCaptured,Q=V.capturesCompleted??0,q=W===void 0?!0:W===0||Q>=W;return!Y&&!!V.analysisCompletedAt&&q}),M=new Set(((F=f==null?void 0:f.entities)==null?void 0:F.map(V=>V.sha))||[]),T=R.filter(V=>!(V.currentEntityShas||[]).some(W=>M.has(W))),z=(await Promise.all(T.slice(0,3).map(async V=>{const Y=V.currentEntityShas||[];if(Y.length===0)return{run:V,entities:[]};const W=await Promise.all(Y.map(Q=>m(Q)));return{run:V,entities:W.filter(Q=>Q!==null)}}))).flatMap(({run:V,entities:Y})=>Y.map(W=>({...W,runId:V.id,completedAt:V.lastCaptureAt||V.analysisCompletedAt||V.archivedAt||V.createdAt})));let G=[],U=null,B=null;if((H=(O=u==null?void 0:u.metadata)==null?void 0:O.currentRun)!=null&&H.analysisCompletedAt&&w.length>0){const V=w[0].sha;U=w[0];const Y=await jr(V);Y&&Y.length>0&&Y[0].scenarios&&(G=Y[0].scenarios,B=Y[0].status)}return J({state:{...d,jobs:y,currentlyExecuting:f},currentRun:(ae=u==null?void 0:u.metadata)==null?void 0:ae.currentRun,historicalRuns:A,totalHistoricalRuns:v.length,currentPage:s,totalPages:E,projectSlug:h,commitSha:u==null?void 0:u.sha,queueJobs:y,currentlyExecuting:f,currentEntities:w,tab:c,hasCurrentActivity:I,queuedCount:j,recentCompletedEntities:z,hasMoreCompletedRuns:T.length>3,currentEntityScenarios:G,currentEntityForScenarios:U,currentAnalysisStatus:B})}function xm({activeTab:e,hasCurrentActivity:r,queuedCount:n,historicCount:a}){const o=[{id:"current",label:"Current Activity",hasContent:r,count:r?1:null},{id:"queued",label:"Queued Activity",hasContent:n>0,count:n},{id:"historic",label:"Historic Activity",hasContent:a>0,count:a}];return t("div",{className:"border-b border-gray-200 mb-6",children:t("nav",{className:"flex gap-8",children:o.map(s=>{const i=e===s.id;return t(oe,{to:s.id==="current"?"/activity":`/activity/${s.id}`,className:`
|
|
206
|
+
relative pb-4 px-2 text-sm transition-colors cursor-pointer
|
|
207
|
+
${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
|
|
208
|
+
`,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[s.label,s.count!==null&&s.count>0&&t("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&&t("span",{className:`
|
|
209
|
+
inline-block w-2 h-2 rounded-full
|
|
210
|
+
${i?"":"bg-gray-400"}
|
|
211
|
+
`,style:i?{backgroundColor:"#005C75"}:{}})]})},s.id)})})})}function bm({currentlyExecuting:e,currentRun:r,state:n,projectSlug:a,commitSha:o,onShowLogs:s,recentCompletedEntities:i,hasMoreCompletedRuns:c,currentEntityScenarios:d,currentEntityForScenarios:h,currentAnalysisStatus:u}){var $,z,G,U;const[m,p]=P({}),[f,y]=P({isKilling:!1,current:0,total:0}),g=rt(),b=!!e,w=(e==null?void 0:e.entities)||[],x=!!(r!=null&&r.analysisCompletedAt),v=x&&!!(r!=null&&r.capturePid),C=!x,k=b,N=d||[],{lastLine:E}=pt(a,k);te(()=>{if(!r)return;const B=[r.analyzerPid,r.capturePid].filter(S=>!!S);if(B.length===0)return;let D=!0;const L=async()=>{try{const F=await(await fetch(`/api/process-status?pids=${B.join(",")}`)).json();if(F.processes&&D){const O={};F.processes.forEach(H=>{O[H.pid]={isRunning:H.isRunning,processName:H.processName}}),p(O)}}catch(S){D&&console.error("Failed to fetch process statuses:",S)}};L();const _=setInterval(()=>void L(),5e3);return()=>{D=!1,clearInterval(_)}},[r==null?void 0:r.analyzerPid,r==null?void 0:r.capturePid]);const[A,I]=P(!1),[j,R]=P(!1);te(()=>{w.length<=3&&A&&I(!1)},[w.length,A]),te(()=>{i.length<=3&&j&&R(!1)},[i.length,j]);const M=A?w:w.slice(0,3),T=w.length>3;return l("div",{className:"flex flex-col gap-[45px]",children:[k?l("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"1px solid #e0e9ec"},children:[l("div",{className:"flex items-center gap-2 mb-[15px]",children:[t(Ze,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),t("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:v?"Capturing...":"Analyzing..."})]}),M.map(B=>l("div",{className:"bg-white border border-[#e1e1e1] rounded-[4px] mb-[15px]",style:{height:"60px",padding:"0 15px",display:"flex",alignItems:"center",justifyContent:"space-between",boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1)"},children:[l("div",{className:"flex items-center gap-3",children:[t("div",{children:t(Ue,{type:B.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col gap-[1px]",children:[l("div",{className:"flex items-center gap-[14px]",children:[t(oe,{to:`/entity/${B.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:B.name}),B.entityType&&t(Hn,{type:B.entityType})]}),t("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:B.filePath,children:B.filePath})]})]}),t("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"})]},B.sha)),T&&!A&&l("button",{onClick:()=>I(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",w.length-3," more"," ",w.length-3===1?"entity":"entities"]}),A&&T&&t("button",{onClick:()=>I(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"}),v&&N&&N.length>0&&h&&t("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:N.map(B=>{var H,ae,V,Y;if(!B.id)return null;const D=(ae=(H=B.metadata)==null?void 0:H.screenshotPaths)==null?void 0:ae[0],L=(V=B.metadata)==null?void 0:V.noScreenshotSaved,_=D&&!L,S=(Y=u==null?void 0:u.scenarios)==null?void 0:Y.find(W=>W.name===B.name),O=S&&S.screenshotStartedAt&&!S.screenshotFinishedAt||!_&&!L;return t(oe,{to:`/entity/${h.sha}/scenarios/${B.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:O?"#f9f9f9":void 0,borderColor:O?"#efefef":"#ccc"},children:_?t(De,{screenshotPath:D,alt:B.name,className:"w-full h-full object-contain bg-gray-100"}):O?t("div",{className:"w-full h-full flex items-center justify-center",children:t(qn,{size:"medium"})}):t("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},B.id)})}),E&&t("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:E}),t("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((r==null?void 0:r.analyzerPid)||(r==null?void 0:r.capturePid))&&l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-2",children:[l("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(r==null?void 0:r.analyzerPid)&&t(dr,{variant:"analyzer",pid:r.analyzerPid}),(r==null?void 0:r.analyzerPid)&&(C||(($=m[r.analyzerPid])==null?void 0:$.isRunning))&&t(dr,{variant:"running"}),(r==null?void 0:r.capturePid)&&t(dr,{variant:"capture",pid:r.capturePid}),(r==null?void 0:r.capturePid)&&(v||((z=m[r.capturePid])==null?void 0:z.isRunning))&&t(dr,{variant:"running"})]}),(((G=m[r==null?void 0:r.analyzerPid])==null?void 0:G.isRunning)||((U=m[r==null?void 0:r.capturePid])==null?void 0:U.isRunning))&&t("button",{onClick:()=>{const B=[r==null?void 0:r.analyzerPid,r==null?void 0:r.capturePid].filter(_=>{var S;return!!_&&((S=m[_])==null?void 0:S.isRunning)});if(B.length===0)return;const D=B.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${D})?`))return;y({isKilling:!0,current:1,total:B.length}),(async()=>{for(let _=0;_<B.length;_++){const S=B[_];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:S,commitSha:o||""})})}catch(F){console.error(`Failed to kill process ${S}:`,F)}_<B.length-1&&y({isKilling:!0,current:_+2,total:B.length})}y({isKilling:!1,current:0,total:0}),g.revalidate()})()},disabled:f.isKilling,className:"px-[8px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:"#991b1b",color:"white",fontSize:"12px",lineHeight:"15px",fontWeight:500,height:"27px",width:"114px"},children:f.isKilling?"Killing...":"Kill All Processes"})]})]}):l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[t("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:t(hi,{size:24,style:{color:"#005C75"}})}),l("div",{children:[t("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Current Activity"}),l("p",{className:"text-sm",style:{color:"#8e8e8e"},children:["There are no analyses running. Trigger one from"," ",t(oe,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",t(oe,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),l(oe,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[t("span",{children:"+"}),t("span",{children:"New Analysis"})]})]}),i&&i.length>0&&l("div",{children:[t("h3",{className:"font-mono uppercase",style:{fontSize:"12px",lineHeight:"18px",color:"#8e8e8e",marginBottom:"16px",fontWeight:500,letterSpacing:"0.05em"},children:"Recently Completed Analyses"}),l("div",{className:"flex flex-col gap-4",children:[(j?i:i.slice(0,3)).map(B=>{var _;const D=(_=B.analyses)==null?void 0:_[0],L=(D==null?void 0:D.scenarios)||[];return D==null||D.status,t("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:l("div",{className:"flex flex-col gap-[15px]",children:[l("div",{className:"flex items-center",children:[t("div",{className:"flex-shrink-0",children:t(Ue,{type:B.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[l("div",{className:"flex items-center gap-[5px]",children:[t(oe,{to:`/entity/${B.sha}`,className:"hover:underline cursor-pointer",title:B.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:B.name}),t("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:"#e8ffe6",color:"#00925d",fontSize:"12px",lineHeight:"16px",fontWeight:400},children:B.isUncommitted?"Modified":"Up to date"})]}),t("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:B.filePath,children:B.filePath})]}),t("div",{className:"flex-1"}),t("div",{className:"flex-shrink-0",children:t("button",{onClick:s,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:S=>{S.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:S=>{S.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),t("div",{className:"border-t border-gray-200 mx-[-15px]"}),L.length>0?t("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:L.map(S=>{var ae,V,Y;if(!S.id)return null;const F=(V=(ae=S.metadata)==null?void 0:ae.screenshotPaths)==null?void 0:V[0],O=(Y=S.metadata)==null?void 0:Y.noScreenshotSaved,H=F&&!O;return l("div",{className:"shrink-0 flex flex-col gap-2",children:[t(oe,{to:`/entity/${B.sha}/scenarios/${S.id}`,className:"block cursor-pointer",children:t("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{backgroundColor:H?"#f3f4f6":"#FAFAFA",borderColor:H?"#d1d5db":"#BCCDD3",borderStyle:H?"solid":"dashed"},onMouseEnter:W=>{H&&(W.currentTarget.style.borderColor="#005C75",W.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:W=>{W.currentTarget.style.borderColor=H?"#d1d5db":"#BCCDD3",W.currentTarget.style.boxShadow="none"},children:H?t(De,{screenshotPath:F,alt:S.name,className:"max-w-full max-h-full object-contain"}):t("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})})}),t("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.name})]},S.id)})}):t("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},B.sha)}),i.length>3&&!j&&l("button",{onClick:()=>R(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",i.length-3," more"," ",i.length-3===1?"entity":"entities"]}),j&&i.length>3&&t("button",{onClick:()=>R(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})]})}function wm({queueJobs:e,state:r,currentRun:n}){if(!e||e.length===0)return l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[t("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:t(mi,{size:24,style:{color:"#005C75"}})}),l("div",{children:[t("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Queued Jobs"}),t("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Analysis jobs will appear here when they are queued but not yet started."})]})]}),l(oe,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[t("span",{children:"+"}),t("span",{children:"New Analysis"})]})]});const[a,o]=P(null),[s,i]=P(null),[c,d]=P(null),[h,u]=P(!1),[m,p]=P(!1),[f,y]=P(new Set),g=rt();te(()=>{e.length<=3&&m&&p(!1)},[e.length,m]);const b=N=>{o(N)},w=(N,E)=>{N.preventDefault(),i(E)},x=async(N,E)=>{if(N.preventDefault(),!a){i(null);return}const A=e.findIndex(R=>R.id===a);if(A===-1){o(null),i(null);return}if(A===E){o(null),i(null);return}const I=A<E?"down":"up",j=Math.abs(E-A);u(!0);try{for(let R=0;R<j;R++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:a,direction:I})});g.revalidate()}catch(R){console.error("Failed to reorder job:",R)}finally{u(!1),o(null),i(null)}},v=()=>{h||(o(null),i(null))},C=async N=>{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:N})}),window.location.reload()}catch(E){console.error("Failed to cancel job:",E)}},k=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(N){console.error("Failed to cancel jobs:",N)}};return l("div",{children:[l("div",{className:"flex items-center justify-between mb-4",children:[l("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:[e.length," Queued Job",e.length!==1?"s":""]}),e.length>0&&t("button",{onClick:()=>void k(),className:"px-[10px] py-0 rounded transition-colors cursor-pointer hover:bg-red-300",style:{backgroundColor:"#ffdcd9",color:"#ef4444",fontSize:"12px",fontWeight:500,height:"29px"},children:"Cancel All"})]}),l("div",{className:"flex flex-col gap-3",children:[(m?e:e.slice(0,3)).map(N=>{var T,$,z,G;const E=e.findIndex(U=>U.id===N.id),A=c===E,I=a===N.id,j=s===E,R=f.has(N.id),M=((T=N.entities)==null?void 0:T.length)>0?R?N.entities:N.entities.slice(0,3):[];return l("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:I||h?.5:1,transform:j&&a!==null&&!I?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:h?"not-allowed":I?"grabbing":"grab"},onMouseEnter:()=>d(E),onMouseLeave:()=>d(null),draggable:!h,onDragStart:U=>{b(N.id),U.dataTransfer.effectAllowed="move"},onDragOver:U=>w(U,E),onDrop:U=>void x(U,E),onDragEnd:v,children:[l("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[t(pi,{size:16,style:{color:"#005C75"}}),l("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",E+1]})]}),l("div",{className:"flex flex-col gap-2 mt-8",children:[M.length>0?l(ce,{children:[M.map(U=>t("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:t("div",{className:"flex items-center justify-between h-full px-[15px]",children:l("div",{className:"flex items-center gap-3 flex-1",children:[t("div",{children:t(Ue,{type:U.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[t(oe,{to:`/entity/${U.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:U.name}),U.entityType&&t(Hn,{type:U.entityType})]}),t("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:U.filePath})]})]})})},U.sha)),(($=N.entities)==null?void 0:$.length)>3&&t("button",{onClick:()=>{y(U=>{const B=new Set(U);return B.has(N.id)?B.delete(N.id):B.add(N.id),B})},className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"40px",fontSize:"12px",color:"#646464",fontWeight:500},children:R?"Show less":`+${N.entities.length-3} more ${N.entities.length-3===1?"entity":"entities"}`})]}):t("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:t("div",{className:"flex items-center justify-between h-full px-[15px]",children:l("div",{className:"flex items-center gap-3 flex-1",children:[t("div",{style:{transform:"scale(1.0)"},children:t(ho,{size:18,style:{color:"#8e8e8e"}})}),l("div",{className:"flex-1",children:[t("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((z=N.entityNames)==null?void 0:z[0])||(N.type==="analysis"?"Analysis Job":N.type==="recapture"?"Recapture Job":N.type==="debug-setup"?"Debug Setup":N.type.charAt(0).toUpperCase()+N.type.slice(1))}),t("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((G=N.filePaths)==null?void 0:G[0])||(N.filePaths&&N.filePaths.length>1?`${N.filePaths.length} files`:N.entityShas&&N.entityShas.length>0?`${N.entityShas.length} ${N.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),l("div",{className:"flex items-center justify-end gap-2 mt-1",children:[A&&t("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:t(fi,{size:20})}),t("button",{onClick:()=>void C(N.id),className:"transition-colors cursor-pointer hover:bg-red-100 rounded flex items-center justify-center",style:{fontSize:"10px",fontWeight:600,lineHeight:"22px",color:"#ef4444",backgroundColor:"#fef6f6",padding:"0 10px",height:"22px"},children:"Cancel"})]})]})]},N.id)}),e.length>3&&!m&&l("button",{onClick:()=>p(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",e.length-3," more"," ",e.length-3===1?"job":"jobs"]}),m&&e.length>3&&t("button",{onClick:()=>p(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})}function vm({historicalRuns:e,totalHistoricalRuns:r,currentPage:n,totalPages:a,tab:o,onShowLogs:s}){if(r===0)return l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[t("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:t(gi,{size:24,style:{color:"#005C75"}})}),l("div",{children:[t("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Historic Activity"}),t("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Completed analyses will appear here for historical reference."})]})]}),l(oe,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[t("span",{children:"+"}),t("span",{children:"New Analysis"})]})]});const[i,c]=P(!1),d=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(m=>{d.push({...m,runCreatedAt:u.createdAt})})});const h=i?d:d.slice(0,3);return l("div",{className:"flex flex-col gap-4",children:[h.map(u=>{var y;const m=(y=u.analyses)==null?void 0:y[0],p=(m==null?void 0:m.scenarios)||[],f=!u.isUncommitted;return l("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[l("div",{className:"flex items-start justify-between mb-3",children:[l("div",{className:"flex items-start gap-3 flex-1",children:[t("div",{children:t(Ue,{type:u.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[t(oe,{to:`/entity/${u.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:u.name}),t("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:f?"#e8ffe6":"#fef3cd",color:f?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:f?"Up to date":"Out of date"})]}),t("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},title:u.filePath,children:u.filePath})]})]}),t("button",{onClick:s,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),p.length>0&&l("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[p.slice(0,8).map(g=>{var v,C,k;if(!g.id)return null;const b=(C=(v=g.metadata)==null?void 0:v.screenshotPaths)==null?void 0:C[0],w=(k=g.metadata)==null?void 0:k.noScreenshotSaved,x=b&&!w;return t(oe,{to:`/entity/${u.sha}/scenarios/${g.id}`,className:"border rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px",borderColor:x?"#ccc":"#BCCDD3",borderStyle:x?"solid":"dashed"},children:x?t(De,{screenshotPath:b,alt:g.name,className:"w-full h-full object-cover bg-gray-100"}):t("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},g.id)}),p.length>8&&l("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",p.length-8," more"]})]})]},`${u.sha}-${u.runCreatedAt}`)}),d.length>3&&!i&&l("button",{onClick:()=>c(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",d.length-3," more"," ",d.length-3===1?"entity":"entities"]}),i&&d.length>3&&t("button",{onClick:()=>c(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})}const Cm=Oe(function(){const r=We(),n=io(),[a,o]=P(!1);mt({source:"activity-page"});const s=n.tab||"current";return r?l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[t("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Activity"}),t("p",{className:"text-[15px] text-gray-500",children:"View queued, current, and historical analysis activity."})]}),t(xm,{activeTab:s,hasCurrentActivity:r.hasCurrentActivity,queuedCount:r.queuedCount,historicCount:r.totalHistoricalRuns}),s==="current"&&t(bm,{currentlyExecuting:r.currentlyExecuting,currentRun:r.currentRun,state:r.state,projectSlug:r.projectSlug,commitSha:r.commitSha,onShowLogs:()=>o(!0),recentCompletedEntities:r.recentCompletedEntities||[],hasMoreCompletedRuns:r.hasMoreCompletedRuns||!1,currentEntityScenarios:r.currentEntityScenarios||[],currentEntityForScenarios:r.currentEntityForScenarios,currentAnalysisStatus:r.currentAnalysisStatus}),s==="queued"&&t(wm,{queueJobs:r.queueJobs,state:r.state,currentRun:r.currentRun}),s==="historic"&&t(vm,{historicalRuns:r.historicalRuns,totalHistoricalRuns:r.totalHistoricalRuns,currentPage:r.currentPage,totalPages:r.totalPages,tab:s,onShowLogs:()=>o(!0)}),a&&r.projectSlug&&t(dt,{projectSlug:r.projectSlug,onClose:()=>o(!1)})]}):t("div",{className:"px-20 py-12",children:t("div",{className:"text-center",children:t("p",{className:"text-gray-600",children:"Loading..."})})})}),Nm=Object.freeze(Object.defineProperty({__proto__:null,default:Cm,loader:ym},Symbol.toStringTag,{value:"Module"}));async function ps(e,r,n){var C,k;await $e();const a=await at({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=fe();if(!o)throw new Error("Project root not found");const s=ee.join(o,".codeyam","config.json"),i=JSON.parse(K.readFileSync(s,"utf8")),{projectSlug:c}=i;if(!c)throw new Error("Project slug not found in config");const d=Dr(c);try{K.writeFileSync(d,"","utf8")}catch{}const{project:h}=await Fe(c),u=((C=h.metadata)==null?void 0:C.packageManager)||"npm",m=3112,p=ot(c),f=((k=h.metadata)==null?void 0:k.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${c}`);const y=i.environmentVariables||[],g=Ul({filePath:a.filePath,webapps:f,environmentVariables:y,port:m,packageManager:u});await Tt(e,N=>{if(N&&(N.readyToBeCaptured=!0,N.scenarios))for(const E of N.scenarios)(!r||E.name===r)&&(delete E.screenshotStartedAt,delete E.screenshotFinishedAt,delete E.interactiveStartedAt,delete E.interactiveFinishedAt,delete E.error,delete E.errorStack)});const{jobId:b}=n.enqueue({type:"debug-setup",commitSha:a.commit.sha,projectSlug:c,analysisId:e,scenarioId:r,prepOnly:!0}),w=g.startCommand,x={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:w,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${m}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:b,analysisId:e,scenarioId:r,projectPath:p,projectSlug:c,port:m,packageManager:u,framework:g.framework,instructions:x}}async function Sm({request:e,context:r}){const n=new URL(e.url),a=n.searchParams.get("analysisId"),o=n.searchParams.get("scenarioId")||void 0;if(!a)return J({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=r.analysisQueue;if(s||(s=await st()),!s)return J({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:a,scenarioId:o});try{const i=await ps(a,o,s);return J({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),J({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function Em({request:e,context:r}){if(e.method!=="POST")return J({error:"Method not allowed"},{status:405});let n=r.analysisQueue;if(n||(n=await st()),!n)return J({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("analysisId"),s=a.get("scenarioId");if(!o)return J({error:"Missing required field: analysisId"},{status:400});const i=await ps(o,s,n);return J({...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),J({error:"Failed to setup debug environment",details:o},{status:500})}}const Am=Object.freeze(Object.defineProperty({__proto__:null,action:Em,loader:Sm},Symbol.toStringTag,{value:"Module"}));async function km({request:e,context:r}){if(e.method!=="POST")return J({error:"Method not allowed"},{status:405});let n=r.analysisQueue;if(n||(n=await st()),!n)return J({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("analysisId"),s=a.get("defaultWidth");if(!o||!s)return J({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(s,10);if(isNaN(i)||i<320||i>3840)return J({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${o} with width ${i}`);const c=await Nh(o,i,n);return console.log("[API] Recapture queued",c),J({success:!0,message:"Recapture queued",...c})}catch(a){return console.log("[API] Error during recapture:",a),J({error:"Failed to recapture screenshots",details:a instanceof Error?a.message:String(a)},{status:500})}}const Pm=Object.freeze(Object.defineProperty({__proto__:null,action:km},Symbol.toStringTag,{value:"Module"}));function Mm(e,r){var i,c,d,h,u;const n=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,a=e.analyses&&e.analyses.length>0&&e.analyses.some(m=>m.scenarios&&m.scenarios.length>0);if(!n){const m=!!((c=e.metadata)!=null&&c.previousVersionWithAnalyses),p=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return m||p?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=!!((d=e.metadata)!=null&&d.previousCommittedSha);if(!!((h=e.metadata)!=null&&h.previousVersionWithAnalyses)||o){const m=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return a&&!m?{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 _m(e){return Mm(e).hasOutdatedSimulations}function Yr(e,r,n,a,o){var U,B,D,L,_,S,F,O;const s=(U=r==null?void 0:r.scenarios)==null?void 0:U.find(H=>H.name===e.name),i=!!(s!=null&&s.startedAt),c=!!(s!=null&&s.screenshotStartedAt),d=!!(s!=null&&s.screenshotFinishedAt),h=!!(s!=null&&s.finishedAt),u=1800*1e3,m=c&&!d&&(s==null?void 0:s.screenshotStartedAt)&&Date.now()-new Date(s.screenshotStartedAt).getTime()>u,p=!!((D=(B=e.metadata)==null?void 0:B.screenshotPaths)!=null&&D[0])||!!((L=e.metadata)!=null&&L.executionResult),f=c&&!d,y=s==null?void 0:s.error,g=(S=(_=e.metadata)==null?void 0:_.executionResult)==null?void 0:S.error,b=[];if(r!=null&&r.errors&&r.errors.length>0)for(const H of r.errors)b.push({source:`${H.phase} phase`,message:H.message});if(r!=null&&r.steps)for(const H of r.steps)H.error&&b.push({source:H.name,message:H.error});const w=!p&&!y&&!g&&b.length>0,x=!!(y||g||m||w),v=m?"Capture timed out after 30 minutes":(typeof y=="string"?y:null)||(g==null?void 0:g.message)||(w?`Analysis error: ${b[0].message}`:null),C=m?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(s==null?void 0:s.errorStack)||(g==null?void 0:g.stack)||null,N=(a&&o?o.jobs.some(H=>{var ae;return((ae=H.entityShas)==null?void 0:ae.includes(a))||H.type==="analysis"&&H.entityShas&&H.entityShas.length===0})||((O=(F=o.currentlyExecuting)==null?void 0:F.entityShas)==null?void 0:O.includes(a)):!1)&&!i&&!x||!!(s!=null&&s.analyzing)&&!i&&!x,E=i&&!c&&!h&&!x,A=(N||E||f)&&!x,I=(N||E)&&n===!1&&!p;let j;I?j="crashed":x?j="error":p||h?j="completed":f?j="capturing":E?j="starting":N?j="queued":j="pending";let R="📷",M="pending",T=!1,$=`Not captured: ${e.name}`;const z="border-gray-300",G=x||I?"bg-red-50":"bg-white";return x||I?(R="⚠️",M="error",$=`Error: ${I?"Analysis process crashed":v||"Unknown error"}`):N?(R="⋯",M="queued",$=`Queued: ${e.name}`):E?(R="⋯",M="starting",T=!0,$=`Starting server for ${e.name}...`):f&&!x?(R="⋯",M="capturing",T=!0,$=`Capturing ${e.name}...`):p&&(R="✓",M="completed",$=e.name),{hasError:x||I,errorMessage:I?"Analysis process crashed":v,errorStack:I?"Process terminated unexpectedly before completing analysis":C,isCapturing:f,isCaptured:p,hasCrashed:I,isAnalyzing:A,isQueued:N,isServerStarting:E,status:j,icon:R,iconType:M,shouldSpin:T,title:$,borderColor:z,bgColor:G}}function fs({scenario:e,entitySha:r,size:n="medium",showBorder:a=!0,isOutdated:o=!1}){var C,k,N,E,A,I;const s=Yr(e,void 0,void 0,r,void 0),i=(C=e.metadata)==null?void 0:C.executionResult,c=!!i,h=(((N=(k=e.metadata)==null?void 0:k.data)==null?void 0:N.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,m=((A=(E=i==null?void 0:i.sideEffects)==null?void 0:E.consoleOutput)==null?void 0:A.length)||0,p=((I=i==null?void 0:i.timing)==null?void 0:I.duration)||0;let f=0;h>0&&f++,h>2&&f++,u&&f++,m>0&&f++,f=Math.min(3,f);const y=n==="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"}:c?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"},w=a?`border-2 ${b.border}`:"",x=Array.from({length:3},(j,R)=>t("div",{className:`w-1 h-1 rounded-full ${R<f?b.icon.replace("text-","bg-"):"bg-gray-300"}`},R)),v=s.hasError?`Error: ${s.errorMessage||"Unknown error"}`:c?`${e.name}
|
|
212
|
+
${h} args → ${u?"value":"void"}${m>0?` (${m} logs)`:""}
|
|
213
|
+
${p}ms`:`Not executed: ${e.name}`;return l(oe,{to:`/entity/${r}/scenarios/${e.id}`,className:`relative ${y.width} ${y.height} ${w} rounded ${b.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:v,onClick:j=>j.stopPropagation(),children:[t("div",{className:`${b.icon} ${y.iconSize} font-mono font-bold`,children:s.hasError?"⚠":c?"ƒ":"○"}),c&&!s.hasError&&l("div",{className:`flex items-center gap-0.5 ${y.textSize} ${b.badge} px-1 rounded`,children:[t("span",{children:h}),t("span",{children:"→"}),t("span",{children:u?"✓":"∅"})]}),c&&!s.hasError&&n==="medium"&&t("div",{className:"flex gap-0.5 mt-0.5",children:x}),c&&!s.hasError&&p>100&&n==="medium"&&t("div",{className:`absolute top-0.5 right-0.5 ${y.textSize} ${b.badge} px-1 rounded`,children:p>1e3?`${Math.round(p/1e3)}s`:`${p}ms`}),c&&!s.hasError&&m>0&&n==="medium"&&l("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",m]})]})}function vn({size:e=24,className:r=""}){return l("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:r,"aria-hidden":"true",children:[t("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),t("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),t("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function Va({scenario:e,entity:r,analysisStatus:n,queueState:a,processIsRunning:o,size:s="medium",cacheBuster:i,className:c="",viewMode:d}){var g,b;if(r.entityType==="library")return t(fs,{scenario:e,entitySha:r.sha,size:s==="small"?"small":"medium"});const u=Yr(e,n,o,r.sha,a),m=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 ${m.containerClass} ${c}`,f=()=>{const w=`/entity/${r.sha}/scenarios/${e.id}`;return d?`${w}/${d}`:w};if(u.isCaptured){const w=(b=(g=e.metadata)==null?void 0:g.screenshotPaths)==null?void 0:b[0];return t(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:t(De,{screenshotPath:w,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const y=()=>{const w={size:s==="small"?16:s==="large"?24:20,strokeWidth:2},x=t(qn,{size:s});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return x;switch(u.iconType){case"starting":case"capturing":return x;case"error":return l("div",{className:"flex flex-col items-center justify-center gap-1",children:[t(vn,{size:24}),t("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return t(yi,{...w});default:return x}};return t(oe,{to:f(),className:`${p} ${u.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:u.title,children:t("div",{className:m.iconSize,children:y()})})}const kt=70;function Tm({scenarios:e,hiddenScenarios:r=[],analysis:n,selectedScenario:a,entitySha:o,cacheBuster:s,activeTab:i,entityType:c,entity:d,queueState:h,processIsRunning:u,isEntityAnalyzing:m,areScenariosStale:p,viewMode:f,setViewMode:y,isBreakdownView:g}){var T,$,z,G,U,B;const b=Ee(null),[w,x]=P(new Set),[v,C]=P(!1);te(()=>{b.current&&i==="scenarios"&&b.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[a==null?void 0:a.id,i]);const k=D=>`/entity/${o}/scenarios/${D}`,N=D=>{x(L=>{const _=new Set(L);return _.has(D)?_.delete(D):_.add(D),_})},E=(D,L=2)=>{const S=D.split(`
|
|
214
|
+
`).slice(0,L).join(" ").trim();return S.length>kt?S.substring(0,kt-3):(D.split(`
|
|
215
|
+
`).length>L||D.length>S.length,S)},A=ne(()=>{var L;if(!((L=n==null?void 0:n.metadata)!=null&&L.executionFlows)||!(n!=null&&n.scenarios))return null;const D=n.scenarios.filter(_=>{var S;return!((S=_.metadata)!=null&&S.sameAsDefault)});return Un(n.metadata.executionFlows,D)},[n]),I=(A==null?void 0:A.totalFlows)||0,j=(A==null?void 0:A.coveredFlows)||0,R=(A==null?void 0:A.coveragePercentage)||0;(T=d==null?void 0:d.metadata)!=null&&T.defaultWidth||($=n==null?void 0:n.metadata)!=null&&$.defaultWidth;const M=(z=n==null?void 0:n.status)!=null&&z.finishedAt?new Date(n.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return l("aside",{className:"w-[250px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-4",children:[n&&e.length>0&&l("div",{className:"flex flex-col gap-2",children:[t("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),l("div",{className:"grid grid-cols-2 gap-2",children:[l(oe,{to:g?`/entity/${o}/scenarios/${(a==null?void 0:a.id)||((G=e[0])==null?void 0:G.id)}`:`/entity/${o}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[l("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(R),"%"]}),t("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),l(oe,{to:g?`/entity/${o}/scenarios/${(a==null?void 0:a.id)||((U=e[0])==null?void 0:U.id)}`:`/entity/${o}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[l("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[j,"/",I]}),t("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),l(oe,{to:g?`/entity/${o}/scenarios/${(a==null?void 0:a.id)||((B=e[0])==null?void 0:B.id)}`:`/entity/${o}/scenarios/breakdown`,className:`border rounded px-3 py-2 no-underline hover:shadow-sm transition-shadow flex items-center justify-between ${g?"bg-[#CBF3FA] border-[#CBF3FA]":"bg-[#F6F9FC] border-[#E0E9EC]"}`,children:[t("div",{className:"text-[11px] text-[#005c75] font-normal uppercase font-mono underline",children:"EXECUTION FLOWS"}),g?t("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:t("path",{d:"M3 3L9 9M9 3L3 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):t("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:t("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),d&&d.filePath&&t("div",{children:t(oe,{to:`/entity/${o}/create-scenario`,className:"w-full px-3 py-2 bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[11px] font-medium font-mono cursor-pointer transition-colors hover:bg-[#004a5e] no-underline flex items-center justify-center gap-1",children:"+ Create New Scenario"})}),e.length>0&&l("div",{className:"py-3 flex items-center justify-between",children:[l("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),M&&t("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:M})]}),m&&(p||e.length===0)?l("div",{className:"",children:[l("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[l("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[t("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),t("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..."]}),t("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):e.length===0?t("div",{className:"",children:t("p",{className:"text-[#8e8e8e] text-xs font-medium m-0 text-left leading-5",children:"No Scenarios"})}):t("div",{className:"overflow-y-auto flex-1",children:t("div",{className:"flex flex-col gap-[11.6px]",children:e.map((D,L)=>{const _=!g&&(a==null?void 0:a.id)===D.id,S=w.has(D.id||"");return D.id?l(oe,{to:k(D.id),ref:_?b:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${_?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[t("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:t(Va,{scenario:D,entity:{sha:o,entityType:c},analysisStatus:n==null?void 0:n.status,queueState:h,processIsRunning:u,size:"large",cacheBuster:s,viewMode:f})}),l("div",{className:"px-3 py-3",children:[t("div",{className:`text-xs font-semibold text-[#343434] ${S?"":"line-clamp-1"}`,children:D.name}),D.description&&t("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[S?D.description:E(D.description),!S&&D.description.length>kt&&l(ce,{children:["...",t("button",{onClick:F=>{F.preventDefault(),F.stopPropagation(),N(D.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),S&&D.description.length>kt&&t("button",{onClick:F=>{F.preventDefault(),F.stopPropagation(),N(D.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},L):null})})}),r.length>0&&!(m&&p)&&l("div",{className:"border-t border-[#e1e1e1] pt-3",children:[l("button",{onClick:()=>C(!v),className:"flex items-center gap-1 text-[10px] text-[#626262] font-medium cursor-pointer bg-transparent border-none p-0 hover:text-[#005c75] transition-colors w-full",children:[t("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`transition-transform ${v?"rotate-90":""}`,children:t("path",{d:"M3.5 2L6.5 5L3.5 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"Hidden Scenarios (",r.length,")"]}),v&&l("div",{className:"mt-2",children:[t("p",{className:"text-[10px] text-[#8e8e8e] leading-[14px] mb-3",children:"These scenarios were hidden because the screenshots did not differ from the Default Scenario."}),t("div",{className:"flex flex-col gap-[11.6px]",children:r.map((D,L)=>{const _=!g&&(a==null?void 0:a.id)===D.id,S=w.has(D.id||"");return D.id?l(oe,{to:`/entity/${o}/scenarios/${D.id}`,ref:_?b:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${_?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[t("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:t(Va,{scenario:D,entity:{sha:o,entityType:c},analysisStatus:n==null?void 0:n.status,queueState:h,processIsRunning:u,size:"large",cacheBuster:s,viewMode:f})}),l("div",{className:"px-3 py-3",children:[t("div",{className:`text-xs font-semibold text-[#343434] ${S?"":"line-clamp-1"}`,children:D.name}),D.description&&t("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[S?D.description:E(D.description),!S&&D.description.length>kt&&l(ce,{children:["...",t("button",{onClick:F=>{F.preventDefault(),F.stopPropagation(),N(D.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),S&&D.description.length>kt&&t("button",{onClick:F=>{F.preventDefault(),F.stopPropagation(),N(D.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},L):null})})]})]})]})}function Im({scenario:e,entitySha:r,onApply:n,onSave:a,onEditMockData:o,onDelete:s,isApplying:i=!1,isSaving:c=!1,saveMessage:d=null,showDeleteConfirm:h=!1,onShowDeleteConfirm:u,isDeleting:m=!1,deleteError:p=null}){const[f,y]=P(""),g=async()=>{await n(f)},b=async w=>{await a(f,w),w||y("")};return l("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[l("div",{className:"border-b border-[#e1e1e1] pb-3",children:[l("div",{className:"flex items-start justify-between mb-2",children:[t("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),t(oe,{to:`/entity/${r}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),t("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),l("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[l("div",{className:"pt-1",children:[t("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),t("textarea",{id:"ai-description",value:f,onChange:w=>y(w.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}),l("button",{onClick:()=>void g(),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&&l("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("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"]})]}),t("div",{className:"border-t border-[#e1e1e1] my-1"}),l("div",{className:"pt-1",children:[t("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),t("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),t("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&&t("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"&&t("div",{children:t(oe,{to:`/entity/${r}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),l("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[t("button",{onClick:()=>void b(!1),disabled:c||!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:c?"Saving...":"Save Scenario Data"}),t("button",{onClick:()=>void b(!0),disabled:c||!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&&l(ce,{children:[h?l("div",{className:"flex flex-col gap-1",children:[l("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),l("div",{className:"flex gap-1",children:[t("button",{onClick:()=>void s(),disabled:m,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:m?"Deleting...":"Yes, Delete"}),t("button",{onClick:()=>u==null?void 0:u(!1),disabled:m,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"})]})]}):t("button",{onClick:()=>u==null?void 0:u(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),p&&t("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:p})]})]})]})}function $m({scenario:e,analysis:r,entity:n}){var i,c,d;const a=((i=e.metadata)==null?void 0:i.executionResult)||null,o=((d=(c=e.metadata)==null?void 0:c.data)==null?void 0:d.argumentsData)||[],s=h=>{var y,g,b;if(!h)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const u=[],m=((y=h.sideEffects)==null?void 0:y.consoleOutput)||[];m.length>0&&(u.push(`Console Output: ${m.length} log ${m.length===1?"entry":"entries"} captured`),m.forEach(w=>{u.push(` [${w.level.toUpperCase()}] ${w.args.join(" ")}`)}));const p=((g=h.sideEffects)==null?void 0:g.fileWrites)||[];p.length>0&&(u.push(`
|
|
216
|
+
File System Operations: ${p.length} ${p.length===1?"operation":"operations"} detected`),p.forEach(w=>{u.push(` ${w.operation}: ${w.path}${w.size?` (${w.size} bytes)`:""}`)}));const f=((b=h.sideEffects)==null?void 0:b.apiCalls)||[];return f.length>0&&(u.push(`
|
|
217
|
+
API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(w=>{u.push(` ${w.method} ${w.url}${w.status?` → ${w.status}`:""}${w.duration?` (${w.duration}ms)`:""}`)})),h.error&&u.push(`
|
|
218
|
+
Error: ${h.error.name||"Error"}: ${h.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
|
|
219
|
+
`)};return l("div",{className:"flex w-full h-full gap-0",children:[l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[t("div",{className:"px-4 pt-3.5 pb-2.5",children:t("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),t("div",{className:"flex-1 overflow-auto px-4 pb-0",children:t("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(o,null,2)})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[t("div",{className:"px-4 pt-3.5 pb-2.5",children:t("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),t("div",{className:"flex-1 overflow-auto px-4 pb-0",children:a?t("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"}):t("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[t("div",{className:"px-4 pt-3.5 pb-2.5",children:t("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),t("div",{className:"flex-1 overflow-auto px-4 pb-4",children:t("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:s(a)})})]})]})}const bt={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function ur({scenarioId:e,analysisId:r}){const[n,a]=P(!1),[o,s]=P(!1),[i,c]=P(null),[d,h]=P(!1),u=e||r;if(!u)return null;const m=`/codeyam:diagnose ${u}`,p=async()=>{s(!0);try{const{default:y}=await import("html2canvas-pro"),b=(await y(document.body,{scale:.5})).toDataURL("image/jpeg",.8);c(b),a(!0)}catch(y){console.error("Screenshot capture failed:",y),a(!0)}finally{s(!1)}},f=()=>{a(!1),c(null)};return l(ce,{children:[l("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[t("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:bt.heading},children:"Claude can help debug this error."}),t("p",{className:"m-0 mb-4 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"18px",color:bt.subtext},children:"Simply run this command in Claude Code:"}),l("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:bt.commandBoxBg,borderColor:bt.commandBoxBorder,maxWidth:"505px",height:"35px",paddingLeft:"13px",paddingRight:"13px",paddingTop:"6px",paddingBottom:"6px"},children:[t("code",{className:"font-mono font-['IBM_Plex_Mono'] flex-1 text-left",style:{fontSize:"12px",lineHeight:"20px",color:bt.commandBoxText},children:m}),t("button",{onClick:y=>{y.stopPropagation(),navigator.clipboard.writeText(m),h(!0),setTimeout(()=>h(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:d?"#22c55e":bt.commandBoxText},title:d?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:d?t(co,{size:14}):t(Sn,{size:14})})]}),l("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",t("button",{onClick:()=>void p(),disabled:o,className:"underline cursor-pointer bg-transparent border-none p-0 font-normal hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:bt.link},children:o?"capturing...":"please do so here"}),"."]})]}),t(Co,{isOpen:n,onClose:f,context:{source:e?"scenario-page":"entity-page",entitySha:void 0,scenarioId:e,analysisId:r,currentUrl:typeof window<"u"?window.location.pathname:"/"},screenshotDataUrl:i??void 0})]})}const Qa=1440,hr=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],tt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function gs({selectedScenario:e,analysis:r,entity:n,viewMode:a,cacheBuster:o,hasScenarios:s,isAnalyzing:i=!1,projectSlug:c,hasAnApiKey:d=!0,processIsRunning:h,queueState:u}){var Q,q,Z,de,he,ye,be,Ne,we,ke,Te;const m=Ae(),[p,f]=P(!1),[y,g]=P(!1),[b,w]=P({name:"Desktop",width:Qa,height:900}),[x,v]=P(Qa),[C,k]=P(1),{customSizes:N,addCustomSize:E,removeCustomSize:A}=ns(c),I=ne(()=>[...hr,...N],[N]),j=(xe,je)=>{v(xe);const Pe=I.find(Ce=>Ce.width===xe&&Ce.height===je);w({name:(Pe==null?void 0:Pe.name)||"Custom",width:xe,height:je})},R=xe=>{v(xe.width),w({name:xe.name,width:xe.width,height:xe.height})},M=xe=>{E(xe,b.width,b.height??900),g(!1),w(je=>({...je,name:xe}))},T=(xe,je)=>{v(xe);const Pe=I.find(Ce=>Ce.width===xe&&Ce.height===je);w(Ce=>({name:(Pe==null?void 0:Pe.name)||"Custom",width:xe,height:Ce.height}))},$=(q=(Q=e==null?void 0:e.metadata)==null?void 0:Q.screenshotPaths)==null?void 0:q[0],z=ne(()=>e?Yr(e,r==null?void 0:r.status,h,n==null?void 0:n.sha,u):null,[e,r==null?void 0:r.status,h,n==null?void 0:n.sha,u]),G=ne(()=>{var je,Pe;const xe=[];if((je=r==null?void 0:r.status)!=null&&je.errors&&r.status.errors.length>0)for(const Ce of r.status.errors)xe.push({source:`${Ce.phase} phase`,message:Ce.message,stack:Ce.stack});if((Pe=r==null?void 0:r.status)!=null&&Pe.steps)for(const Ce of r.status.steps)Ce.error&&xe.push({source:Ce.name,message:Ce.error,stack:Ce.errorStack});return xe},[(Z=r==null?void 0:r.status)==null?void 0:Z.errors,(de=r==null?void 0:r.status)==null?void 0:de.steps]),U=(z==null?void 0:z.errorMessage)||null,B=(z==null?void 0:z.errorStack)||null,{interactiveServerUrl:D,isStarting:L,isLoading:_,showIframe:S,iframeKey:F,onIframeLoad:O}=rr({analysisId:r==null?void 0:r.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:c,enabled:a==="interactive"}),H=ne(()=>D||null,[D]),ae=!i&&s&&e&&!((ye=(he=e.metadata)==null?void 0:he.screenshotPaths)!=null&&ye[0])&&((Ne=(be=r==null?void 0:r.status)==null?void 0:be.scenarios)==null?void 0:Ne.some(xe=>xe.name===e.name&&xe.screenshotStartedAt&&!xe.screenshotFinishedAt)),{lastLine:V}=pt(c,i||a==="interactive"||ae||!1);if(!e){if(i&&n)return l(ce,{children:[t("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:l("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[t("div",{className:"w-12 h-12 mb-2",children:t("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:t("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),t("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:ae?"Capturing screenshots...":"Analyzing..."}),t("p",{className:"text-xs text-[#8e8e8e] text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:"This may take a few minutes."}),V&&t("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:V}),c&&t("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})}),p&&c&&t(dt,{projectSlug:c,onClose:()=>f(!1)})]});if(!s&&n&&!i){if(G.length>0){const xe=G.length===1?((we=G[0])==null?void 0:we.message)||"An error occurred during analysis.":`${G.length} errors occurred during analysis.`;return l(ce,{children:[t("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:l("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[t("div",{className:"p-4 rounded",style:{backgroundColor:tt.background,border:`2px solid ${tt.border}`},role:"alert",children:l("div",{className:"flex items-center gap-3",children:[t(vn,{size:24,className:"shrink-0"}),t("div",{className:"flex-1 min-w-0",children:l("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:tt.text},children:[t("span",{className:"font-semibold",children:"Analysis Error."})," ",xe," ",t("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:tt.link},children:"See logs"})," ","for details."]})})]})}),t("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:t(ur,{analysisId:r==null?void 0:r.id})})]})}),p&&c&&t(dt,{projectSlug:c,onClose:()=>f(!1)})]})}return t("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:l("div",{className:"max-w-[600px]",children:[t("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),t("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."}),n.filePath&&t("button",{onClick:()=>{m.submit({entitySha:n.sha,filePath:n.filePath},{method:"post",action:"/api/analyze"})},disabled:m.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:m.state!=="idle"?"Analyzing...":"Analyze"})]})})}return t("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:t("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return l(ce,{children:[t("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
|
|
220
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
221
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
222
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
223
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
224
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||ae&&!$)&&!U&&a==="screenshot"?t("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:l("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[l("div",{className:"mb-8",children:[t("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:t("span",{className:"text-5xl animate-spin",children:"⚙️"})}),t("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:ae?`Capturing ${n==null?void 0:n.name}`:`Analyzing ${n==null?void 0:n.name}`}),t("p",{className:"text-base text-gray-600 leading-relaxed m-0 mb-2",children:ae?`Taking screenshots for ${((ke=r==null?void 0:r.scenarios)==null?void 0:ke.length)||0} scenario${((Te=r==null?void 0:r.scenarios)==null?void 0:Te.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${n==null?void 0:n.entityType} entity...`}),e&&l("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),V&&t("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:l("div",{className:"flex items-start gap-3",children:[t("span",{className:"text-xl shrink-0",children:"📝"}),l("div",{className:"flex-1 min-w-0",children:[t("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),t("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:V,children:V})]})]})}),c&&t("button",{onClick:()=>f(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),t("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"&&($||U)||a==="interactive"&&(H||L)||a==="data"?l(ce,{children:[U&&!$&&t("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:l("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[t("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:tt.background,border:`2px solid ${tt.border}`,maxHeight:"50vh"},role:"alert",children:l("div",{className:"flex flex-col gap-3",children:[l("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:tt.text},children:[t(vn,{size:24,className:"shrink-0"}),t("div",{children:"Capture Error"})]}),l("div",{className:"text-center",children:[t("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:tt.link},children:"See logs"})," ","for details."]}),t("div",{className:"flex-1 min-w-0",children:t("div",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:tt.text},children:U})})]})}),t("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:t(ur,{scenarioId:e==null?void 0:e.id,analysisId:r==null?void 0:r.id})})]})}),a==="interactive"?l("div",{className:"flex-1 flex flex-col min-h-0",children:[H&&l("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center items-center gap-4",children:[t(_d,{presets:[...hr],customSizes:N,currentWidth:b.width,currentHeight:b.height??900,scale:C,onSizeChange:j,onSaveCustomSize:()=>g(!0),onRemoveCustomSize:A}),e&&n&&l(oe,{to:`/entity/${n.sha}/scenarios/${e.id}/fullscreen?from=${encodeURIComponent(`/entity/${n.sha}/scenarios/${e.id}/interactive`)}`,className:"flex items-center gap-2 px-4 py-2 bg-[#005c75] text-white rounded hover:bg-[#004a5c] transition-colors text-sm font-medium no-underline",title:"Open in fullscreen",children:[t("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:t("path",{d:"M2 5V2H5M11 2H14V5M14 11V14H11M5 14H2V11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Fullscreen"]})]}),H&&t("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:t("div",{style:{maxWidth:`${hr[hr.length-1].width}px`,width:"100%"},children:t(ts,{currentViewportWidth:x,currentPresetName:b.name,onDevicePresetClick:R,devicePresets:I})})}),t(Or,{scenarioId:e.id,scenarioName:e.name,iframeUrl:H,isStarting:L,isLoading:_,showIframe:S,iframeKey:F,onIframeLoad:O,onScaleChange:k,onDimensionChange:T,projectSlug:c,defaultWidth:b.width,defaultHeight:b.height})]}):a==="data"?t("div",{className:"flex-1 min-h-0",children:t($m,{scenario:e,analysis:r,entity:n})}):t("div",{className:"flex-1 flex flex-col",children:t("div",{className:"flex-1 p-6 flex items-center justify-center",children:t("div",{className:"transition-all duration-300",style:{maxWidth:`${x}px`},children:($||!U)&&t(De,{screenshotPath:$,cacheBuster:o,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):t("div",{className:"flex-1 flex flex-col",children:t("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!$?t("div",{className:"w-full h-full flex items-center justify-center",children:t("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:l("div",{className:"flex items-start gap-4 mb-6",children:[t("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),l("div",{className:"flex-1",children:[t("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),l("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",t("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),V&&l("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[t("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),t("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:V})]}),c&&t("button",{onClick:()=>f(!0),className:"mt-4 px-4 py-2 bg-[#005c75] text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-[#004a5e]",children:"📋 View Full Logs"})]})]})})}):U?l("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!d&&t("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:l("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[l("div",{className:"flex items-start gap-4",children:[t("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),t("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),l("div",{className:"bg-white border border-blue-200 rounded p-4",children:[t("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."}),l("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[t("li",{children:"You can use API keys for a variety of models"}),t("li",{children:"Faster analysis processing"}),t("li",{children:"Better handling of complex code structures"}),t("li",{children:"Improved scenario generation quality"})]})]}),t(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"})]})}),t("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[t("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[t("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),t("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),l("div",{className:"bg-white border border-red-200 rounded p-4",children:[t("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),t("div",{className:"max-h-[300px] overflow-auto",children:t("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:U})})]}),B&&l("details",{className:"mt-4",children:[t("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),t("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:t("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:B})})]}),t("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:t(ur,{scenarioId:e==null?void 0:e.id,analysisId:r==null?void 0:r.id})})]})]})})]}):G.length>0?t("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:t("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[t("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[t(AnalysisErrorDisplay,{errors:G,title:"Analysis Error",description:G.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${G.length} errors occurred during analysis. Screenshot capture was not completed.`}),t("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:t(ur,{scenarioId:e==null?void 0:e.id,analysisId:r==null?void 0:r.id})})]})]})})}):l("div",{className:"flex flex-col items-center gap-4 text-center",children:[t("span",{className:"text-6xl text-gray-300",children:"📷"}),t("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),t("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),p&&c&&t(dt,{projectSlug:c,onClose:()=>f(!1)}),y&&t(rs,{width:b.width,height:b.height??900,onSave:M,onCancel:()=>g(!1)})]})}function jm({analysis:e,entitySha:r}){rt();const[n,a]=P(e);te(()=>{a(e)},[e]);const[o,s]=P(null),i=ne(()=>{var m;if(!((m=n==null?void 0:n.metadata)!=null&&m.executionFlows)||!(n!=null&&n.scenarios))return null;const u=n.scenarios.filter(p=>{var f;return!((f=p.metadata)!=null&&f.sameAsDefault)});return Un(n.metadata.executionFlows,u)},[n]),c=ne(()=>i?Gd(i):[],[i]),d=ne(()=>n!=null&&n.scenarios?n.scenarios.filter(u=>{var m;return!((m=u.metadata)!=null&&m.sameAsDefault)}):[],[n]),h=u=>{var p;const m=((p=u.metadata)==null?void 0:p.coveredFlows)||[];return i?i.executionFlows.filter(f=>m.includes(f.id)):[]};return n?!i||i.executionFlows.length===0?t("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[t("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),t("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):t("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:l("div",{className:"p-6 space-y-6",children:[l("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[t("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),l("div",{className:"grid grid-cols-4 gap-4 text-center",children:[l("div",{className:"bg-gray-50 rounded-lg p-3",children:[t("div",{className:"text-2xl font-bold text-gray-900",children:d.length}),t("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[t("div",{className:"text-2xl font-bold text-gray-900",children:i.executionFlows.length}),t("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[l("div",{className:"text-2xl font-bold text-gray-900",children:[i.coveredFlows,"/",i.totalFlows]}),t("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[l("div",{className:`text-2xl font-bold ${i.coveragePercentage===100?"text-green-600":i.coveragePercentage>=50?"text-amber-600":"text-red-600"}`,children:[i.coveragePercentage.toFixed(0),"%"]}),t("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),l("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[t("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:l("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",d.length,")"]})}),t("div",{className:"divide-y divide-gray-100",children:d.length===0?l("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",t(oe,{to:`/entity/${r}/create-scenario`,className:"text-blue-600 hover:underline",children:"Create one"})]}):d.map(u=>{var f,y,g;const m=(y=(f=u.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0],p=h(u);return l("div",{className:"p-4 flex gap-4",children:[t("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:t(De,{screenshotPath:m,alt:u.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),l("div",{className:"flex-1 min-w-0",children:[t("div",{className:"flex items-start justify-between gap-2",children:l("div",{children:[t(oe,{to:`/entity/${r}/scenarios/${u.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:u.name}),((g=u.metadata)==null?void 0:g.error)&&t("span",{className:"ml-2 text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"Error"})]})}),t("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:u.description}),p.length>0&&t("div",{className:"flex flex-wrap gap-1 mt-2",children:p.map(b=>t("span",{className:`text-xs px-1.5 py-0.5 rounded ${b.isError?"bg-red-50 text-red-700":b.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:b.name},b.id))})]})]},u.id)})}),t("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:l(oe,{to:`/entity/${r}/create-scenario`,className:"w-full px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 flex items-center justify-center gap-2 no-underline",children:[t("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),c.length>0&&l("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[l("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[c.length," uncovered execution flow",c.length>1?"s":""," — consider adding scenarios to cover these"]}),l("div",{className:"flex flex-wrap gap-1",children:[c.slice(0,10).map(u=>l("span",{className:`text-xs px-2 py-0.5 rounded ${u.impact==="high"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[u.name,u.impact==="high"&&" (high impact)"]},u.id)),c.length>10&&l("span",{className:"text-xs text-amber-600",children:["+",c.length-10," more"]})]})]}),l("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[t("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:l("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",i.executionFlows.length,")"]})}),t("div",{className:"divide-y divide-gray-100",children:i.executionFlows.map(u=>{const m=o===u.id,p=u.usedInScenarios.length>0;return l("div",{children:[t("button",{onClick:()=>s(m?null:u.id),className:"w-full px-4 py-3 flex items-start justify-between text-left bg-transparent border-none cursor-pointer hover:bg-gray-50",children:l("div",{className:"flex items-start gap-3 flex-1",children:[t("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:m?"▼":"▶"}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[t("span",{className:"font-medium text-sm text-gray-900",children:u.name}),p?t("span",{className:"text-xs px-2 py-0.5 rounded bg-green-100 text-green-700",children:"Covered"}):t("span",{className:"text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700",children:"Uncovered"}),u.blocksOtherFlows&&t("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),u.impact==="high"&&t("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),u.isError&&t("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),u.description&&t("p",{className:"text-sm text-gray-600 mt-1 m-0",children:u.description})]})]})}),m&&l("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[u.requiredValues.length>0&&l("div",{className:"mb-4",children:[t("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),t("div",{className:"space-y-1",children:u.requiredValues.map((f,y)=>l("div",{className:"flex items-center gap-2 text-xs",children:[t("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children:f.attributePath}),t("span",{className:"text-gray-400",children:f.comparison}),t("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:f.value})]},y))})]}),p&&l("div",{children:[t("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),t("div",{className:"flex flex-wrap gap-1",children:u.usedInScenarios.map(f=>t("span",{className:"text-xs px-1.5 py-0.5 bg-green-50 text-green-700 rounded",children:f.name},f.id))})]}),u.codeSnippet&&l("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[t("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),t("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:t("code",{children:u.codeSnippet})})]})]})]},u.id)})})]})]})}):t("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[t("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),t("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function Ka({hasIndirectBadge:e,onAnalyze:r}){return l(ce,{children:[t("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-end gap-2",children:[e&&t("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),t("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"})]})}),l("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[t("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),t("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:r,children:"Analyze"})]})]})}function Rm({entity:e,history:r}){const[n,a]=P("entity"),[o,s]=P(new Set),i=r.filter(u=>u.analyses.length>0).length,c=ne(()=>{const u=new Map;return r.forEach(m=>{m.analyses.forEach(p=>{(p.scenarios??[]).filter(y=>{var g;return!((g=y.metadata)!=null&&g.sameAsDefault)}).forEach(y=>{u.has(y.name)||u.set(y.name,[]),u.get(y.name).push({version:m,analysis:p,scenario:y})})})}),Array.from(u.entries()).map(([m,p])=>{var f;return{name:m,description:((f=p[0])==null?void 0:f.scenario.description)||"",versions:p.sort((y,g)=>{const b=new Date(y.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-b})}})},[r]),d=c.length,h=u=>{s(m=>{const p=new Set(m);return p.has(u)?p.delete(u):p.add(u),p})};return t("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:l("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[t("div",{className:"mb-8",children:l("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[l("button",{onClick:()=>a("entity"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${n==="entity"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[t("span",{className:"text-base font-semibold leading-6",children:"Entity History"}),t("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${n==="entity"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:i})]}),l("button",{onClick:()=>a("scenarios"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${n==="scenarios"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[t("span",{className:"text-base font-normal leading-6",children:"Scenario Changes"}),t("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${n==="scenarios"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:d})]})]})}),r.length===0?t("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:t("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):n==="entity"?l("div",{className:"relative pl-12",children:[r.length>1&&t("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),r.map((u,m)=>l("div",{className:"relative mb-12 last:mb-0",children:[t("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[t("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3",children:[u.sha===(e==null?void 0:e.sha)&&t("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"}),l(oe,{to:`/entity/${u.sha}/scenarios`,className:"text-xs font-mono text-[#646464] leading-5 hover:text-[#005c75] transition-colors",children:["SHA:"," ",t("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:u.sha.substring(0,8)})]})]}),t("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:u.createdAt&&new Date(u.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),u.analyses.length>0?t("div",{children:u.analyses.map((p,f)=>{var g;const y=(p.scenarios??[]).filter(b=>{var w;return!((w=b.metadata)!=null&&w.sameAsDefault)});return t("div",{children:y.length===0?t(Ka,{hasIndirectBadge:p.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):l(ce,{children:[t("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-end gap-2",children:[p.indirect&&t("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),l("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[y.length," scenario",y.length!==1?"s":""]})]})}),((g=p.metadata)==null?void 0:g.scenarioChangesOverview)&&t("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:l("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[l("span",{className:"font-medium",children:["What Changed:"," "]}),p.metadata.scenarioChangesOverview]})}),y.length>0&&t("div",{className:"p-5 bg-white",children:t("div",{className:"flex gap-4 flex-wrap",children:y.map((b,w)=>{var C,k;const x=(k=(C=b.metadata)==null?void 0:C.screenshotPaths)==null?void 0:k[0],v=`${b.name}-${w}`;return l(oe,{to:`/entity/${u.sha}/scenarios/${b.id}`,className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden hover:border-[#005c75] hover:shadow-sm transition-all",children:[t("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:x?t(De,{screenshotPath:x,alt:b.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[t("span",{className:"text-gray-400 text-xl",children:"📷"}),t("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),t("div",{className:"p-[5.6px]",children:t("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:b.name})})]},v)})})})]})},p.id||f)})}):t(Ka,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):t("div",{className:"relative pl-12",children:c.length===0?t("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:t("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):c.map((u,m)=>{const p=o.has(u.name),f=p?u.versions:u.versions.slice(0,1),y=u.versions.length-1,g=u.versions[0];return g==null||g.version.sha,e==null||e.sha,l("div",{className:"relative mb-12 last:mb-0",children:[t("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[t("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&t("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),l("div",{className:"p-5 bg-white",children:[f.map((b,w)=>{var E,A;const{version:x,analysis:v,scenario:C}=b,k=(A=(E=C.metadata)==null?void 0:E.screenshotPaths)==null?void 0:A[0],N=w===0;return l("div",{className:`flex gap-5 items-start ${N?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[t(oe,{to:`/entity/${x.sha}/scenarios/${C.id}`,className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0 hover:border-[#005c75] hover:shadow-sm transition-all",children:k?t(De,{screenshotPath:k,alt:C.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[t("span",{className:"text-gray-400 text-xl",children:"📷"}),t("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),l("div",{className:"flex-1 flex flex-col gap-2",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[x.sha===(e==null?void 0:e.sha)&&t("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"}),N&&u.versions.length>1&&l("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[u.versions.length," versions"]})]}),l(oe,{to:`/entity/${x.sha}/scenarios`,className:"text-xs font-mono text-[#646464] m-0 leading-5 hover:text-[#005c75] transition-colors w-fit",children:["SHA:"," ",t("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:x.sha.substring(0,8)})]}),v.createdAt&&l("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(v.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),v.indirect&&t("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"})]})]},`${x.sha}-${w}`)}),y>0&&l("button",{onClick:()=>h(u.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[t("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${p?"rotate-180":""}`,children:t("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),p?"Hide":`${y} previous version${y!==1?"s":""}`]})]})]})]},u.name)})})]})})}function Za({entity:e,analysisInfo:r,from:n}){const a=Ae(),o=a.state!=="idle",s=e.entityType==="visual"||e.entityType==="library",i=c=>{c.preventDefault(),c.stopPropagation(),s&&a.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return t(oe,{to:`/entity/${e.sha}${n?`?from=${n}`:""}`,className:"block group cursor-pointer",children:l("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?t("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:t(De,{screenshotPath:e.screenshotPath,alt:e.name,className:"max-w-full max-h-full object-contain"})}):t("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:t("span",{className:"text-[40px]",children:t(Ue,{type:e.entityType})})}),l("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[t(Ue,{type:e.entityType}),t("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),t("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),r.hasScenarios&&l("div",{className:"flex items-center gap-2 mt-2",children:[l("span",{className:"px-[5px] py-0 bg-[#efefef] text-[#3e3e3e] rounded text-[10px] font-medium",children:[r.scenarioCount," scenarios"]}),t("span",{className:"text-xs text-[#8e8e8e]",children:r.timestamp})]})]}),t("div",{className:"shrink-0 ml-4",children:r.status==="not_analyzed"?l(ce,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[t("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),t("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),s&&t("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:o,children:o?"Analyzing...":"Analyze"})]}):r.status==="up_to_date"?l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[t("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),t("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):l(ce,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[t("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),t("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),s&&t("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:o,children:o?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const Xa=e=>{var o,s,i;const r=((o=e.analysisStatus)==null?void 0:o.status)||"not_analyzed",n=((s=e.analysisStatus)==null?void 0:s.scenarioCount)||0,a=(i=e.analysisStatus)==null?void 0:i.timestamp;return r==="not_analyzed"?{status:"not_analyzed",label:"Not analyzed",color:"gray"}:r==="up_to_date"?{status:"up_to_date",label:"Up to date",color:"green",hasScenarios:n>0,scenarioCount:n,timestamp:a}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:n>0,scenarioCount:n,timestamp:a}};function Dm({importedEntities:e,importingEntities:r}){const[n]=Qt(),a=n.get("from"),o=Ae(),s=o.state!=="idle",i=e.length>0,c=r.length>0,d=p=>p.filter(f=>f.entityType==="visual"||f.entityType==="library"),h=p=>{const f=d(p);f.length!==0&&o.submit({entityShas:f.map(y=>y.sha).join(",")},{method:"post",action:"/api/analyze"})},u=d(e).length>0,m=d(r).length>0;return t("div",{className:"max-w-[1400px] mx-auto",children:l("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-6 py-4 flex items-start justify-between",children:[l("div",{children:[l("div",{className:"flex items-center gap-2 mb-1",children:[t("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),t("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})]}),t("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&t("button",{onClick:()=>h(e),disabled:s,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:s?"Analyzing...":"Analyze All"})]}),i?t("div",{className:"p-6 space-y-4",children:e.map(p=>t(Za,{entity:p,analysisInfo:Xa(p),from:a},p.sha))}):t("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:t("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-6 py-4 flex items-start justify-between",children:[l("div",{children:[l("div",{className:"flex items-center gap-2 mb-1",children:[t("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),t("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:r.length})]}),t("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),m&&t("button",{onClick:()=>h(r),disabled:s,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:s?"Analyzing...":"Analyze All"})]}),c?t("div",{className:"p-6 space-y-4",children:r.map(p=>t(Za,{entity:p,analysisInfo:Xa(p),from:a},p.sha))}):t("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:t("p",{className:"text-sm text-[#646464] m-0 leading-[22px] text-center",children:"Not imported by any entity."})})]})]})})}function Lm({relatedEntities:e}){return t("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:t(Dm,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function Fm({data:e,defaultExpanded:r=!1,maxDepth:n=3}){return t("div",{className:"font-mono text-sm",children:t(Vt,{data:e,depth:0,defaultExpanded:r,maxDepth:n})})}function Vt({data:e,depth:r,defaultExpanded:n,maxDepth:a,objectKey:o,showInlineToggle:s=!1}){const[i,c]=P(n||r<2);if(te(()=>{c(n||r<2)},[n,r]),e===null)return t("span",{className:"text-gray-500",children:"null"});if(e===void 0)return t("span",{className:"text-gray-500",children:"undefined"});const d=typeof e;if(d==="string")return l("span",{className:"text-green-600",children:['"',e,'"']});if(d==="number")return t("span",{className:"text-blue-600",children:e});if(d==="boolean")return t("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?t("span",{className:"text-gray-600",children:"[]"}):l("span",{children:[l("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:()=>c(!i),children:[l("span",{children:[i?"▼":"▶"," ","["]}),!i&&l("span",{children:[e.length,"]"]})]}),i?l(ce,{children:[t("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((h,u)=>t("div",{className:"py-0.5",children:t(Vt,{data:h,depth:r+1,defaultExpanded:n,maxDepth:a})},u))}),t("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const h=Object.keys(e);if(h.length===0)return t("span",{className:"text-gray-600",children:"{}"});const u=p=>p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,m=p=>Array.isArray(p)&&p.length>0;return l("span",{children:[l("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:()=>c(!i),children:[l("span",{children:[i?"▼":"▶"," ","{"]}),!i&&l("span",{children:[h.length,"}"]})]}),i?l(ce,{children:[t("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:h.map(p=>{const f=e[p],y=u(f),g=m(f);return t("div",{className:"py-0.5",children:y?t(Jn,{propertyKey:p,value:f,depth:r,defaultExpanded:n,maxDepth:a}):g?t(Gn,{propertyKey:p,value:f,depth:r,defaultExpanded:n,maxDepth:a}):l(ce,{children:[l("span",{className:"text-orange-600",children:[p,": "]}),t(Vt,{data:f,depth:r+1,defaultExpanded:n,maxDepth:a})]})},p)})}),t("div",{className:"text-gray-600",children:"}"})]}):null]})}return t("span",{className:"text-gray-500",children:String(e)})}function Jn({propertyKey:e,value:r,depth:n,defaultExpanded:a,maxDepth:o}){const[s,i]=P(a||n<2),c=Object.keys(r);return te(()=>{i(a||n<2)},[a,n]),l(ce,{children:[l("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:[t("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:s?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),t("span",{className:"text-gray-600 ml-0.5",children:"{"}),!s&&l("span",{className:"text-gray-600",children:[c.length,"}"]})]}),s&&l(ce,{children:[t("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:c.map(d=>{const h=r[d],u=h!==null&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,m=Array.isArray(h)&&h.length>0;return t("div",{className:"py-0.5",children:u?t(Jn,{propertyKey:d,value:h,depth:n+1,defaultExpanded:a,maxDepth:o}):m?t(Gn,{propertyKey:d,value:h,depth:n+1,defaultExpanded:a,maxDepth:o}):l(ce,{children:[l("span",{className:"text-orange-600",children:[d,": "]}),t(Vt,{data:h,depth:n+2,defaultExpanded:a,maxDepth:o})]})},d)})}),t("div",{className:"text-gray-600",children:"}"})]})]})}function Gn({propertyKey:e,value:r,depth:n,defaultExpanded:a,maxDepth:o}){const[s,i]=P(a||n<2);return te(()=>{i(a||n<2)},[a,n]),l(ce,{children:[l("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:[t("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:s?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),t("span",{className:"text-gray-600 ml-0.5",children:"["}),!s&&l("span",{className:"text-gray-600",children:[r.length,"]"]})]}),s&&l(ce,{children:[t("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:r.map((c,d)=>{const h=c!==null&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,u=Array.isArray(c)&&c.length>0;return t("div",{className:"py-0.5",children:h?t(Jn,{propertyKey:d.toString(),value:c,depth:n+1,defaultExpanded:a,maxDepth:o}):u?t(Gn,{propertyKey:d.toString(),value:c,depth:n+1,defaultExpanded:a,maxDepth:o}):t(Vt,{data:c,depth:n+2,defaultExpanded:a,maxDepth:o})},d)})}),t("div",{className:"text-gray-600",children:"]"})]})]})}function dn({label:e,count:r,isActive:n,onClick:a,badgeColorActive:o,badgeTextActive:s}){return l("button",{onClick:a,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${n?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,r!==void 0&&t("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${n?`${o} ${s}`:"bg-gray-200 text-gray-700"}`,children:r}),n&&t("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function eo({label:e,isActive:r,onClick:n,disabled:a=!1}){return t("button",{onClick:n,className:`w-full text-left px-3 py-2.5 rounded-md transition-all text-sm cursor-pointer ${r?"bg-[#f6f9fc] text-[#005c75] font-medium border-l-2 border-[#005c75] pl-[10px]":"text-[#3e3e3e] hover:bg-gray-50"}`,disabled:a,children:e})}function to({call:e,scenarioName:r}){const[n,a]=P(!1),[o,s]=P("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}),c=p=>p?`$${p.toFixed(4)}`:null,d=(p,f)=>{if(!p&&!f)return null;const y=[];return p&&y.push(`${p.toLocaleString()} in`),f&&y.push(`${f.toLocaleString()} out`),y.join(" / ")},h=ne(()=>{var p,f,y,g,b;try{const w=JSON.parse(e.response);return(y=(f=(p=w.choices)==null?void 0:p[0])==null?void 0:f.message)!=null&&y.content?w.choices[0].message.content:(b=(g=w.content)==null?void 0:g[0])!=null&&b.text?w.content[0].text:e.response}catch{return e.response}},[e.response]),u=ne(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),m=ne(()=>{var p;if(r)return r;try{const f=JSON.parse(e.props);return((p=f==null?void 0:f.scenario)==null?void 0:p.name)||null}catch{return null}},[e.props,r]);return l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[t("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>a(!n),children:l("div",{className:"flex items-start justify-between gap-4",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[t("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}),t("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),m&&t("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:m}),e.error&&t("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),l("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[t("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&t("span",{children:d(e.input_tokens,e.output_tokens)}),c(e.cost)&&t("span",{className:"text-[#005c75] font-medium",children:c(e.cost)})]}),l("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.object_id,"_",e.id,".json"]})]}),t("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${n?"rotate-180":""}`,children:t("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),n&&l("div",{className:"border-t border-[#e1e1e1]",children:[l("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[t("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"}),t("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"}),t("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"}),t("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&&l("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[o==="system"&&t("div",{children:e.system_message?t("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}):t("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),o==="prompt"&&t("div",{children:t("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"&&l("div",{children:[e.error&&l("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[t("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),t("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),t("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:h})]}),o==="props"&&t("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),e.error&&!o&&t("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:l("p",{className:"text-xs text-[#dc2626] m-0",children:[t("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const ro=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function Om({entity:e,analysis:r,scenarios:n,onAnalyze:a,llmCalls:o}){var v,C,k,N,E,A,I,j,R;const[s,i]=P("entity"),[c,d]=P("analysis"),[h,u]=P(n.length>0?{scenarioId:n[0].id||n[0].name}:null),[m,p]=P("entity"),{entityLlmCalls:f,scenarioLlmCalls:y,totalLlmCalls:g}=ne(()=>{if(!o)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const M=[...o.entityCalls,...o.analysisCalls],T=M.filter(z=>z.object_type==="entity"||ro.includes(z.prompt_type)),$=M.filter(z=>z.object_type!=="entity"&&!ro.includes(z.prompt_type));return T.sort((z,G)=>G.created_at-z.created_at),$.sort((z,G)=>G.created_at-z.created_at),{entityLlmCalls:T,scenarioLlmCalls:$,totalLlmCalls:M.length}},[o]),b=[{id:"analysis",title:"Analysis",data:r?{id:r.id,status:r.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(v=e==null?void 0:e.metadata)==null?void 0:v.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(C=r==null?void 0:r.metadata)==null?void 0:C.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(N=(k=e==null?void 0:e.metadata)==null?void 0:k.isolatedDataStructure)==null?void 0:N.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(E=r==null?void 0:r.metadata)==null?void 0:E.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(A=e==null?void 0:e.metadata)==null?void 0:A.importedExports,"External Dependencies":(I=e==null?void 0:e.metadata)==null?void 0:I.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(j=r==null?void 0:r.metadata)==null?void 0:j.scenariosDataStructure,description:"Structure template used across all scenarios"}],w=b.filter(M=>M.data!==void 0&&M.data!==null).length;let x=null;if(s==="entity"){const M=b.find(T=>T.id===c);M&&M.data!==void 0&&M.data!==null&&(x={title:M.title,description:M.description,data:M.data})}else if(s==="scenarios"&&h){const M=n.find(T=>(T.id||T.name)===h.scenarioId);M&&(x={title:M.name,description:M.description||"Scenario data and configuration",data:M.metadata})}return l("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[t("div",{className:"mb-6 shrink-0",children:l("div",{className:"flex border-b border-gray-200 relative",children:[t(dn,{label:"Entity",isActive:s==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),t(dn,{label:"Scenarios",count:n.length,isActive:s==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),t(dn,{label:"LLM Calls",count:g,isActive:s==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((R=r==null?void 0:r.metadata)==null?void 0:R.analyzerVersion)&&l("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[t("span",{className:"font-medium",children:"Analyzer:"}),t("span",{className:"ml-1 font-mono",children:r.metadata.analyzerVersion})]})]})}),s==="llm-calls"?l("div",{className:"flex-1 min-h-0",children:[l("div",{className:"flex gap-4 mb-4",children:[l("button",{onClick:()=>p("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),l("button",{onClick:()=>p("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",y.length,")"]})]}),t("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:m==="entity"?f.length===0?t("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:t("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(M=>t(to,{call:M},M.id)):y.length===0?t("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:t("p",{className:"text-gray-500 text-sm m-0",children:"No scenario-level LLM calls found"})}):y.map(M=>t(to,{call:M},M.id))})]}):l("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[t("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:s==="entity"?l(ce,{children:[t("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),w===0?t("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):t("nav",{className:"space-y-1",children:b.map(M=>{const T=M.data!==void 0&&M.data!==null;return t(eo,{label:M.title,isActive:c===M.id,onClick:()=>d(M.id),disabled:!T},M.id)})})]}):l(ce,{children:[t("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"SCENARIOS"}),n.length===0?t("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No scenarios available."}):t("nav",{className:"space-y-1",children:n.map(M=>{const T=M.id||M.name,$=(h==null?void 0:h.scenarioId)===T;return t(eo,{label:M.name,isActive:$,onClick:()=>u({scenarioId:T})},T)})})]})}),t("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:x?t(zm,{title:x.title,description:x.description,data:x.data}):s==="scenarios"&&n.length===0?t(no,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:a}):s==="entity"?t(no,{title:"No Entity Data Yet",description:"Entity data structures will appear here after analysis is complete.",onAnalyze:a}):t("div",{className:"p-6 text-center py-12 text-gray-500",children:"Select a section to view data"})})]})]})}function no({title:e,description:r,onAnalyze:n}){return l("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[t("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),t("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:r}),n&&t("button",{onClick:n,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 zm({title:e,description:r,data:n}){const[a,o]=P(!0),[s,i]=P("Copy JSON");return l(ce,{children:[l("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[t("h3",{className:"text-base font-semibold text-black m-0",children:e}),t("p",{className:"text-sm text-[#646464] mt-1 m-0",children:r})]}),l("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[l("div",{className:"flex gap-2",children:[t("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"}),t("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"})]}),t("button",{onClick:()=>{const d=JSON.stringify(n,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})]}),t("div",{className:"overflow-y-auto flex-1",children:t("div",{className:"p-6",children:n?t("div",{className:"bg-gray-50 rounded-lg p-3 overflow-x-auto",children:t(Fm,{data:n,defaultExpanded:a,maxDepth:99})}):t("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function Ym({entity:e,analysis:r,scenarios:n,onAnalyze:a}){const o=Ae();return te(()=>{if(e!=null&&e.sha&&o.state==="idle"&&!o.data){const s=r!=null&&r.id?`/api/llm-calls/${e.sha}?analysisId=${r.id}`:`/api/llm-calls/${e.sha}`;o.load(s)}},[e==null?void 0:e.sha,r==null?void 0:r.id,o.state,o.data]),t("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:t(Om,{entity:e,analysis:r,scenarios:n,onAnalyze:a,llmCalls:o.data})})}function Bm({content:e,label:r="Copy",copiedLabel:n="✓ Copied!",className:a="",duration:o=2e3,ariaLabel:s}){const[i,c]=P(!1),d=se(()=>{navigator.clipboard.writeText(e).then(()=>{c(!0),setTimeout(()=>c(!1),o)}).catch(h=>{console.error("Failed to copy:",h)})},[e,o]);return t("button",{onClick:d,className:`cursor-pointer ${a}`,disabled:i,"aria-label":s||(i?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?n:r})}const Um={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},Wm={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},Hm=2e3,qm=e=>{var n;if(!e)return"typescript";switch((n=e.split(".").pop())==null?void 0:n.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 Jm({entity:e,entityCode:r}){const n=Pr(),a=Ee(null);return te(()=>{const o=n.hash;if(!o||!a.current)return;const s=o.match(/^#L(\d+)$/);if(!s)return;const i=parseInt(s[1],10);setTimeout(()=>{if(!a.current)return;const c=a.current.querySelector(`[data-line-number="${i}"]`);if(c&&c instanceof HTMLElement){c.scrollIntoView({behavior:"smooth",block:"center"});const d=c.style.backgroundColor;c.style.backgroundColor="rgba(255, 255, 0, 0.2)",setTimeout(()=>{c.style.backgroundColor=d},2e3)}},300)},[n.hash,r]),t("div",{ref:a,className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:l("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[l("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[l("div",{children:[t("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),t("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e==null?void 0:e.filePath})]}),r&&t(Bm,{content:r,label:"Copy Code",duration:Hm,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"})]}),t("div",{className:"p-0",children:r?t("div",{className:"relative",children:t(Qi,{language:qm(e==null?void 0:e.filePath),style:Ki,showLineNumbers:!0,customStyle:Um,lineNumberStyle:Wm,wrapLines:!0,lineProps:o=>({"data-line-number":o,style:{display:"block"}}),children:r})}):t("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const Gm=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function Vm({currentParams:e,nextParams:r,currentUrl:n,nextUrl:a,formMethod:o,defaultShouldRevalidate:s}){return n.pathname===a.pathname&&n.search===a.search?s:!!(e.sha!==r.sha||o)}async function Qm({params:e,request:r,context:n}){const{sha:a}=e;if(!a)throw new Response("Entity SHA is required",{status:400});const s=new URL(r.url).searchParams.get("from"),c=(e["*"]||"").split("/").filter(Boolean),d=c[0]||"scenarios",h=c[1]||null,u=c[2]||null,m=n.analysisQueue,p=m?m.getState():{paused:!1,jobs:[]},[f,y,g,b]=await Promise.all([Mt(a),ze(),It(),Sc(fe()||process.cwd())]),w=f?await Ln(f):null,x=f?await Fo(f.sha):null;let v={importedEntities:[],importingEntities:[]},C=null,k=[];f&&(v=await Oo(f),C=await zo(f),k=await Bo(f));const N=!!(f&&k.length>0&&k[0].sha!==f.sha),E=k.length>0?k[0].sha:null,A=!!(k.length>0&&k[0].analyses&&k[0].analyses.length>0),I=f?await Yo(f):!1;return J({entity:f??void 0,analysis:w??void 0,currentEntityAnalysis:x??void 0,projectSlug:y,from:s,relatedEntities:v,entityCode:C??void 0,hasNewerVersion:N,newestEntitySha:E,newestVersionHasAnalysis:A,fileModifiedSinceEntity:I,history:k,tab:d,scenarioId:h,viewModeFromUrl:u,currentCommit:g,hasAnApiKey:b,queueState:p})}const Km=Oe(function(){var oa,sa,ia,la,ca,da,ua,ha,ma,pa,fa,ga,ya,xa,ba;const r=We(),o=(io()["*"]||"").split("/").filter(Boolean),s=o[0]||"scenarios",i=o[1]||null,c=o[2]||null,d=r.entity,h=r.analysis,u=r.currentEntityAnalysis,m=u||h,p=r.projectSlug;r.from;const f=r.relatedEntities,y=r.entityCode,g=r.hasNewerVersion,b=r.newestEntitySha,w=r.newestVersionHasAnalysis,x=r.fileModifiedSinceEntity,v=r.history,C=r.currentCommit,k=r.hasAnApiKey,N=r.queueState;(oa=m==null?void 0:m.status)==null||oa.errors;const E=(m==null?void 0:m.scenarios)||[],A=E.filter(re=>{var me;return!((me=re.metadata)!=null&&me.sameAsDefault)}),I=E.filter(re=>{var me;return(me=re.metadata)==null?void 0:me.sameAsDefault}),j=_t(),R=Ee(null);te(()=>{R.current===null&&(R.current=window.history.length)},[]);const M=()=>{if(typeof window>"u")return;const re=window.history.state;if(re===null||(re==null?void 0:re.idx)===void 0||(re==null?void 0:re.idx)===0)j("/");else{const me=window.history.length,Be=R.current;if(Be!==null&&me>Be){const Se=me-Be+1;j(-Se)}else j(-1)}},T=!!N.currentlyExecuting,$=s,z=(sa=C==null?void 0:C.metadata)==null?void 0:sa.currentRun,G=!!(z!=null&&z.createdAt)&&!(z!=null&&z.analysisCompletedAt),U=!!(d!=null&&d.sha&&((ia=z==null?void 0:z.currentEntityShas)!=null&&ia.includes(d.sha))),B=!!(d!=null&&d.sha&&((ca=(la=N.currentlyExecuting)==null?void 0:la.entityShas)!=null&&ca.includes(d.sha))),D=!!(d!=null&&d.sha&&((da=N.jobs)!=null&&da.some(re=>{var me;return(me=re.entityShas)==null?void 0:me.includes(d.sha)}))),L=U||B||D,_=L&&((ua=m==null?void 0:m.status)==null?void 0:ua.finishedAt)!=null&&A.length>0&&m.entitySha!==(d==null?void 0:d.sha),S=ne(()=>{if($!=="scenarios")return null;if(i){const re=A.find(me=>me.id===i);if(re)return re}return A.length>0&&!L?A[0]:null},[$,i,A,L]),F=((pa=(ma=(ha=S==null?void 0:S.metadata)==null?void 0:ha.executionResult)==null?void 0:ma.error)==null?void 0:pa.message)||((ya=(ga=(fa=m==null?void 0:m.status)==null?void 0:fa.errors)==null?void 0:ga[0])==null?void 0:ya.message);mt({source:S?"scenario-page":"entity-page",entitySha:d==null?void 0:d.sha,scenarioId:S==null?void 0:S.id,analysisId:m==null?void 0:m.id,entityName:d==null?void 0:d.name,entityType:d==null?void 0:d.entityType,scenarioName:S==null?void 0:S.name,errorMessage:F});const[O,H]=P(()=>c&&c!=="edit"?c:(d==null?void 0:d.entityType)==="library"?"data":"screenshot");te(()=>{c&&c!==O&&c!=="edit"&&H(c)},[c]);const ae=c==="edit",[V,Y]=P(!1),[W,Q]=P(!1),[q,Z]=P(null),[de,he]=P(!1),[ye,be]=P(!1),[Ne,we]=P(null),[ke,Te]=P(null),[xe,je]=P(0),{interactiveServerUrl:Pe,isStarting:Ce,isLoading:nr,showIframe:le,iframeKey:qe,onIframeLoad:Je}=rr({analysisId:m==null?void 0:m.id,scenarioId:S==null?void 0:S.id,scenarioName:S==null?void 0:S.name,projectSlug:p,enabled:ae&&!!S,refreshTrigger:xe}),[Ur,zf]=P(!1),[Yf,Bf]=P(""),[ar,Dt]=P(!1),[ta,Wr]=P(Date.now()),[Ms,Hr]=P(!1),Xe=Ae(),yt=Ae(),Ye=Ae(),Re=rt(),_s=N.jobs.some(re=>{var me;return(d==null?void 0:d.sha)&&((me=re.entityShas)==null?void 0:me.includes(d.sha))||re.type==="analysis"&&re.commitSha===(C==null?void 0:C.sha)&&re.entityShas&&re.entityShas.length===0}),qr=L,ra=((xa=d==null?void 0:d.metadata)==null?void 0:xa.defaultWidth)||((ba=m==null?void 0:m.metadata)==null?void 0:ba.defaultWidth)||1440,Ts=Math.round(ra*(900/1440));Xe.state==="submitting"||Xe.state,ne(()=>{var re;return!!((re=S==null?void 0:S.metadata)!=null&&re.interactiveExamplePath)},[S]);const{isCompleted:na}=pt(p,ar);te(()=>{Xe.state==="idle"&&Xe.data&&(Xe.data.success?setTimeout(()=>{Wr(Date.now()),Re.revalidate(),Dt(!1)},1500):Xe.data.error&&(Dt(!1),alert(`Recapture failed: ${Xe.data.error}`)))},[Xe.state,Xe.data,Re]),te(()=>{ar&&na&&setTimeout(()=>{Wr(Date.now()),Re.revalidate(),Dt(!1)},1500)},[ar,na,Re]),te(()=>{yt.state==="idle"&&yt.data&&(yt.data.success?setTimeout(()=>{Wr(Date.now()),Re.revalidate(),Dt(!1)},1500):yt.data.error&&(Dt(!1),alert(`Recapture failed: ${yt.data.error}`)))},[yt.state,yt.data,Re]);const aa=()=>{d&&(g&&b&&b!==d.sha?(j(`/entity/${b}/scenarios`),setTimeout(()=>{Ye.submit({entitySha:b,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})},100)):Ye.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"}))};te(()=>{Ye.state==="idle"&&Ye.data&&(Ye.data.success?Re.revalidate():Ye.data.error&&alert(`Analysis failed: ${Ye.data.error}`))},[Ye.state,Ye.data,d==null?void 0:d.sha,Re]),te(()=>{const re=setTimeout(()=>{Re.revalidate()},500);return()=>clearTimeout(re)},[]),te(()=>{if(G||qr){const re=setInterval(()=>{Re.revalidate()},3e3);return()=>clearInterval(re)}else{const re=setInterval(()=>{Re.revalidate()},5e3),me=setTimeout(()=>{clearInterval(re)},3e4);return()=>{clearInterval(re),clearTimeout(me)}}},[G,qr,Re]);const Is=(re,me)=>re==="scenarios"?`/entity/${d==null?void 0:d.sha}/scenarios`:`/entity/${d==null?void 0:d.sha}/${re}`,$s=(re,me)=>`/entity/${d==null?void 0:d.sha}/scenarios/${re}/${me}`,js=re=>{H(re),S!=null&&S.id&&(re==="interactive"?j(`/entity/${d==null?void 0:d.sha}/scenarios/${S.id}/fullscreen`,{replace:!0}):j($s(S.id,re),{replace:!0}))},Rs=async re=>{var me,Be;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:re,hasSelectedScenario:!!S,hasAnalysis:!!m}),!S||!m){const Se="Error: No scenario or analysis available";console.error("[EntityDetail]",Se),Z(Se);return}Y(!0),Z(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:re,scenarioId:S.id,scenarioName:S.name,currentData:S.data});try{const Se=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:re,existingScenarios:m.scenarios,scenariosDataStructure:(me=m.metadata)==null?void 0:me.scenariosDataStructure,editingMockName:S.name,editingMockData:ke||((Be=S.metadata)==null?void 0:Be.data)})}),et=await Se.json();if(!Se.ok||!et.success)throw new Error(et.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",et.data),Te(et.data);const or=(m.scenarios||[]).map(Le=>Le.id===S.id?{...Le,metadata:{...Le.metadata,data:et.data}}:Le),Lt=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:or})}),Ge=await Lt.json();if(!Lt.ok||!Ge.success)throw console.error("[EntityDetail] Temp save failed:",Ge),new Error(Ge.error||"Failed to apply preview");if(Z("Generating preview. Capturing screenshot..."),Pe){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:Pe});const Le=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:Pe,scenarioId:S.id,projectId:m.projectId,viewportWidth:1440})}),Ft=await Le.json();!Le.ok||!Ft.success?(console.error("[EntityDetail] Direct capture failed:",Ft),Z("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),Z('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Le=new FormData;Le.append("analysisId",m.id||""),Le.append("scenarioId",S.id||"");const Ft=await fetch("/api/recapture-scenario",{method:"POST",body:Le}),Gr=await Ft.json();!Ft.ok||!Gr.success?(console.warn("[EntityDetail] Recapture failed:",Gr.error),Z("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",Gr.jobId),Z('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}je(Le=>Le+1),Re.revalidate()}catch(Se){console.error("Error applying changes:",Se),Z(`Error: ${Se instanceof Error?Se.message:String(Se)}`)}finally{Y(!1)}},Ds=async(re,me)=>{var Be;if(!S||!m){Z("Error: No scenario or analysis available");return}Q(!0),Z(null),console.log("[EntityDetail] Saving scenario to database",{description:re,saveAsNew:me});try{const Se=ke||((Be=S.metadata)==null?void 0:Be.data);let et;if(me){const Ge={...S,id:`${S.name}-${Date.now()}`,name:`${S.name} (Copy)`,metadata:{...S.metadata,data:Se},description:re||S.description};et=[...m.scenarios||[],Ge]}else et=(m.scenarios||[]).map(Ge=>Ge.id===S.id?{...Ge,metadata:{...Ge.metadata,data:Se},description:re||Ge.description}:Ge);const or=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:et})}),Lt=await or.json();if(!or.ok||!Lt.success)throw new Error(Lt.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),Z(me?"New scenario created successfully":"Scenario saved successfully"),Te(null),Re.revalidate()}catch(Se){console.error("Error saving scenario:",Se),Z(`Error: ${Se instanceof Error?Se.message:String(Se)}`)}finally{Q(!1)}},Ls=()=>{console.log("[EntityDetail] Edit mock data clicked"),Z("Mock data editor coming soon")},Fs=async()=>{var re;if(!(S!=null&&S.id)){we("Cannot delete scenario without ID");return}he(!0),we(null);try{const me=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:S.id,screenshotPaths:((re=S.metadata)==null?void 0:re.screenshotPaths)||[]})}),Be=await me.json();if(!me.ok||!Be.success)throw new Error(Be.error||"Failed to delete scenario");j(`/entity/${d==null?void 0:d.sha}/scenarios`)}catch(me){console.error("[EntityDetail] Error deleting scenario:",me),we(me instanceof Error?me.message:"Failed to delete scenario"),be(!1)}finally{he(!1)}},Jr=m&&d&&m.entitySha!==d.sha,Os=d?_m(d):!1;return t(Fr,{children:l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[t("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-end h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[t("button",{onClick:M,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:t("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:t("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),t("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:d==null?void 0:d.name}),t("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d==null?void 0:d.filePath,children:d==null?void 0:d.filePath})]}),t("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:A.length},{id:"related",label:"Related Entities",count:f.importedEntities.length+f.importingEntities.length},{id:"code",label:"Code"},{id:"data",label:"Data Structure"},{id:"history",label:"History"}].map(re=>t(oe,{to:Is(re.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${$===re.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:$===re.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[re.label,re.count!==void 0&&re.count>0&&t("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${$===re.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:re.count})]})},re.id))})]})}),(g||Jr&&!u||x&&Os)&&!L&&!_s&&t("div",{className:"border-b border-[#FEE585] px-6 py-3 flex items-center justify-center shrink-0",style:{backgroundColor:"#FEE585"},children:l("div",{className:"flex items-center gap-3",children:[t("svg",{className:"w-4 h-4",style:{color:"#714A25"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),t("span",{className:"text-sm font-semibold",style:{color:"#714A25"},children:Jr&&!g?"This entity version has not been analyzed yet.":"This entity has been recently changed."}),t("span",{className:"text-sm",style:{color:"#714A25"},children:g?"You are viewing an older version. A newer version is available.":Jr?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),g&&b&&w?t(oe,{to:`/entity/${b}/scenarios`,className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono cursor-pointer transition-colors no-underline",style:{backgroundColor:"#C69538"},onMouseEnter:re=>{re.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:re=>{re.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):t("button",{onClick:aa,disabled:Ye.state!=="idle",className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#C69538"},onMouseEnter:re=>{Ye.state==="idle"&&(re.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:re=>{Ye.state==="idle"&&(re.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),l("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[$==="scenarios"&&l(ce,{children:[ae&&S?t(Im,{scenario:S,entitySha:(d==null?void 0:d.sha)||"",onApply:Rs,onSave:Ds,onEditMockData:Ls,onDelete:Fs,isApplying:V,isSaving:W,saveMessage:q,showDeleteConfirm:ye,onShowDeleteConfirm:be,isDeleting:de,deleteError:Ne}):t(Tm,{scenarios:A,hiddenScenarios:I,analysis:m,selectedScenario:S,entitySha:(d==null?void 0:d.sha)||"",cacheBuster:ta,activeTab:$,entityType:d==null?void 0:d.entityType,entity:d,queueState:N,processIsRunning:T,isEntityAnalyzing:L,areScenariosStale:_,viewMode:O,setViewMode:js,isBreakdownView:i==="breakdown"}),i==="breakdown"?t(jm,{analysis:m??null,entitySha:(d==null?void 0:d.sha)||""}):ae&&S?t(Or,{scenarioId:S.id||S.name,scenarioName:S.name,iframeUrl:Pe,isStarting:Ce,isLoading:nr,showIframe:le,iframeKey:qe,onIframeLoad:Je,projectSlug:p,defaultWidth:1440,defaultHeight:900}):l("div",{className:"flex flex-col flex-1 min-h-0",children:[S&&l("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[l("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-xs font-semibold text-[#343434]",children:S.name}),l("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[ra," × ",Ts]})]}),l("div",{className:"flex items-center gap-2",children:[t(oe,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${S.id}/edit`,className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors no-underline flex items-center",title:"Edit Scenario Data",children:"Edit Scenario"}),l("button",{className:"px-3 py-1.5 bg-[#022A35] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#011a21] transition-colors flex items-center gap-1.5",onClick:()=>{alert("Download functionality coming soon")},title:"Download",children:[t("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:t("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"})}),"Download"]}),l(oe,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${S.id}/fullscreen`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Interactive Mode",children:[t("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:t("path",{d:"M8 5v14l11-7z"})}),"Interactive Mode"]})]})]}),t(gs,{selectedScenario:S,analysis:m,entity:d,viewMode:O,cacheBuster:ta,hasScenarios:A.length>0,isAnalyzing:qr,projectSlug:p,hasAnApiKey:k,processIsRunning:T,queueState:N})]})]}),$==="related"&&t(Lm,{relatedEntities:f}),$==="data"&&t(Ym,{entity:d,analysis:m,scenarios:A,onAnalyze:aa}),$==="code"&&t(Jm,{entity:d,entityCode:y}),$==="history"&&t(Rm,{entity:d,history:v})]}),Ms&&p&&t("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>Hr(!1),children:l("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:re=>re.stopPropagation(),children:[l("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[t("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),t("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:()=>Hr(!1),children:"×"})]}),t("div",{className:"flex-1 overflow-hidden",children:t(dt,{projectSlug:p,onClose:()=>Hr(!1)})})]})})]})})}),Zm=Object.freeze(Object.defineProperty({__proto__:null,default:Km,loader:Qm,meta:Gm,shouldRevalidate:Vm},Symbol.toStringTag,{value:"Module"}));async function Xm(e){const{entityShas:r,filePaths:n,context:a,scenarioCount:o,queue:s}=e;console.log(`[analyzeEntities] Starting analysis for ${r.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await $e();const i=fe();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const c=ue.join(i,".codeyam","config.json"),d=JSON.parse(await pe.readFile(c,"utf8")),{projectSlug:h,branchId:u}=d;if(!h||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${h}, Branch: ${u}`);const m=Dr(h);try{await pe.writeFile(m,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:p,branch:f}=await Fe(h);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const y=await ht({shas:r});if(!y||y.length===0)throw new Error(`No entities found for SHAs: ${r.join(", ")}`);let g=n;if((!g||g.length===0)&&(g=[...new Set(y.map(x=>x.filePath).filter(x=>!!x))],console.log(`[analyzeEntities] Found ${g.length} unique files`)),!g||g.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${g.length} files...`);const b=await vc(p,f,g);console.log(`[analyzeEntities] Created commit ${b.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await ct({commitSha:b.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:r.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:x=>{if(!x)return;const v=x.currentRun;if(v&&v.id&&v.archivedAt)return;v&&(v.analysesCompleted&&v.analysesCompleted>0||v.capturesCompleted&&v.capturesCompleted>0)&&_c(x)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:w}=s.enqueue({type:"analysis",commitSha:b.sha,projectSlug:h,filePaths:g,entityShas:r,entityNames:y.map(x=>x.name),...a?{context:a}:{},...o?{scenarioCount:o}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${w} for ${r.length} entities`),{jobId:w}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function ep({request:e,context:r}){if(e.method!=="POST")return J({error:"Method not allowed"},{status:405});let n=r.analysisQueue;if(n||(n=await st()),!n)return J({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("entitySha"),s=a.get("entityShas"),i=a.get("filePath"),c=a.get("context"),d=a.get("scenarioCount");let h;if(s)h=s.split(",").filter(Boolean);else if(o)h=[o];else return J({error:"Missing required field: entitySha or entityShas"},{status:400});if(h.length===0)return J({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${h.length} entity(ies)`);const u=await ht({shas:h}),p=[...new Set(u.map(y=>y.filePath).filter(y=>!!y))].length,{jobId:f}=await Xm({entityShas:h,filePaths:i?[i]:void 0,context:c||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:n});return console.log(`[API] Analysis queued with job ID: ${f}`),J({success:!0,message:`Analysis queued for ${h.length} entity(ies)`,entityCount:h.length,fileCount:p,jobId:f})}catch(a){return console.error("[API] Error starting analysis:",a),J({error:"Failed to start analysis",details:a.message},{status:500})}}const tp=Object.freeze(Object.defineProperty({__proto__:null,action:ep},Symbol.toStringTag,{value:"Module"}));function rp(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[t("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),t("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function ys(e){if(!e)return"Never";const r=new Date(e),n=new Date;if(r.getDate()===n.getDate()&&r.getMonth()===n.getMonth()&&r.getFullYear()===n.getFullYear()){const o=r.getHours(),s=r.getMinutes(),i=o>=12?"pm":"am",c=o%12||12,d=s.toString().padStart(2,"0");return`Today, ${c}:${d} ${i}`}return r.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function Ve(e,r=[],n=!1){var u,m;if(r.some(p=>{var f,y;return!!((f=p.entityShas)!=null&&f.includes(e.sha)||(y=p.entities)!=null&&y.some(g=>g.sha===e.sha))}))return n?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const o=e.analyses[0];if(!(((u=o.status)==null?void 0:u.scenarios)&&o.status.scenarios.length>0&&o.status.scenarios.some(p=>p.screenshotFinishedAt||p.finishedAt))||o.entitySha!==e.sha)return"not-analyzed";const i=o.createdAt?new Date(o.createdAt).getTime():0,c=(m=e.metadata)!=null&&m.editedAt?new Date(e.metadata.editedAt).getTime():0,d=o.scenarios||[],h=d.some(p=>{var f,y,g;return((y=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||((g=p.metadata)==null?void 0:g.executionResult)});return i>=c?d.length>0&&h?d.every(f=>{var y,g,b;return((g=(y=f.metadata)==null?void 0:y.screenshotPaths)==null?void 0:g[0])||((b=f.metadata)==null?void 0:b.executionResult)})?"up-to-date":"incomplete":d.length>0?"incomplete":"not-analyzed":"out-of-date"}const np=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function ap({request:e,context:r}){try{const n=r.analysisQueue,a=n?n.getState():{paused:!1,jobs:[]},o=await er();return J({entities:o||[],queueState:a})}catch(n){return console.error("Failed to load simulations:",n),J({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const op=Oe(function(){const r=We(),n=r.entities,a=r.queueState;mt({source:"simulations-page"});const[o,s]=P(""),[i,c]=P("visual"),d=ne(()=>{const g=[];return n.forEach(b=>{var x;const w=(x=b.analyses)==null?void 0:x[0];if(w!=null&&w.scenarios){const v=w.scenarios.filter(C=>{var k;return!((k=C.metadata)!=null&&k.sameAsDefault)}).map(C=>{var R,M,T,$,z;const k=(M=(R=C.metadata)==null?void 0:R.screenshotPaths)==null?void 0:M[0],N=(T=C.metadata)==null?void 0:T.noScreenshotSaved,E=k&&!N,A=(z=($=w.status)==null?void 0:$.scenarios)==null?void 0:z.find(G=>G.name===C.name),I=A&&A.screenshotStartedAt&&!A.screenshotFinishedAt;let j;return E?j="completed":I?j="capturing":j="error",{scenarioName:C.name,scenarioDescription:C.description||"",screenshotPath:k||"",scenarioId:C.id,state:j}}).filter(C=>C.state==="completed"||C.state==="capturing");v.length>0&&g.push({entity:b,screenshots:v,createdAt:w.createdAt||""})}}),g.sort((b,w)=>new Date(w.createdAt).getTime()-new Date(b.createdAt).getTime()),g},[n]),h=ne(()=>n.filter(g=>{var x,v;const b=(x=g.analyses)==null?void 0:x[0];return!((v=b==null?void 0:b.scenarios)==null?void 0:v.some(C=>{var k,N;return(N=(k=C.metadata)==null?void 0:k.screenshotPaths)==null?void 0:N[0]}))}),[n]),u=ne(()=>d.filter(({entity:g})=>{const b=!o||g.name.toLowerCase().includes(o.toLowerCase()),w=i==="all"||g.entityType===i;return b&&w}),[d,o,i]),m=ne(()=>h.filter(g=>{const b=!o||g.name.toLowerCase().includes(o.toLowerCase()),w=i==="all"||g.entityType===i;return b&&w}),[h,o,i]),p=se(g=>{s(g.target.value)},[]),f=se(g=>{c(g.target.value)},[]),y=d.length>0;return t("div",{className:"bg-[#F8F7F6] min-h-screen overflow-y-auto",children:l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[t("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),t("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!y&&t("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:l("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",t("strong",{children:"Start by analyzing your first component below."})]})}),l("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[t("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),l("div",{className:"flex gap-3",children:[l("div",{className:"relative",children:[l("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 pr-8 text-[13px] h-[39px] cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:i,onChange:f,children:[t("option",{value:"all",children:"All Types"}),t("option",{value:"visual",children:"Visual"}),t("option",{value:"library",children:"Library"})]}),t(qt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"flex-1 relative",children:[t(En,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),t("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-3 text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:o,onChange:p})]})]})]}),y&&u.length>0&&t("div",{className:"mb-2",children:l("div",{className:"flex items-center py-3",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[t("span",{style:{color:"#000000"},children:u.length})," ",u.length===1?"entity":"entities"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[t("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),t("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",t("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),t("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[t("span",{style:{color:"#000000"},children:u.reduce((g,{screenshots:b})=>g+b.length,0)})," ","scenarios"]})]})}),l("div",{className:"flex flex-col gap-3",children:[y&&(u.length===0?t("div",{className:"bg-white border border-gray-200 rounded-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):t(ce,{children:u.map(({entity:g,screenshots:b})=>t(sp,{entity:g,screenshots:b,queueJobs:(a==null?void 0:a.jobs)||[]},g.sha))})),!y&&(m.length===0?t("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."}):m.map(g=>t(ip,{entity:g},g.sha)))]})]})})});function sp({entity:e,screenshots:r,queueJobs:n}){var f,y,g;const a=_t(),o=Ae(),[s,i]=P(!1),c=r.length||(((g=(y=(f=e.analyses)==null?void 0:f[0])==null?void 0:y.scenarios)==null?void 0:g.length)??0),d=b=>{a(`/entity/${e.sha}/scenarios/${b}?from=simulations`)},h=()=>{i(!0),o.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};te(()=>{o.state==="idle"&&s&&i(!1)},[o.state,s]);const u=Ve(e,n),m=rp(u),p=u==="out-of-date";return t("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:l("div",{className:"flex flex-col",children:[l("div",{className:"flex items-center px-[15px] py-[15px]",children:[t("div",{className:"flex-shrink-0",children:t(Ue,{type:e.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[l("div",{className:"flex items-center gap-[5px]",children:[l(oe,{to:`/entity/${e.sha}`,className:"hover:underline cursor-pointer",title:e.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:[e.name," (",c,")"]}),t("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:m.bgColor,color:m.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:m.text})]}),t("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),t("div",{className:"flex-1"}),l("div",{className:"flex-shrink-0 flex items-center gap-2",children:[p&&t(ce,{children:s||o.state!=="idle"?l("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[t(Ze,{size:14,className:"animate-spin",style:{color:"#be185d"}}),t("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):t("button",{onClick:h,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#005c75",color:"#ffffff",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="#004d5e"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="#005c75"},children:"Re-analyze"})}),t("button",{onClick:()=>void a(`/entity/${e.sha}/logs`),className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})]})]}),t("div",{className:"border-t border-gray-200"}),t("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:r.length>0?r.map(b=>l("div",{className:"shrink-0 flex flex-col gap-2",children:[t("button",{onClick:()=>d(b.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:t("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:b.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:b.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:w=>{b.state==="completed"&&(w.currentTarget.style.borderColor="#005C75",w.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:w=>{w.currentTarget.style.borderColor=b.state==="capturing"?"#efefef":"#d1d5db",w.currentTarget.style.boxShadow="none"},children:b.state==="completed"?t(De,{screenshotPath:b.screenshotPath,alt:b.scenarioName,className:"max-w-full max-h-full object-contain"}):b.state==="capturing"?t(qn,{size:"medium"}):null})}),l("div",{className:"relative group",children:[t("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.scenarioName}),t("div",{className:"fixed hidden group-hover:block pointer-events-none",style:{zIndex:1e4,transform:"translateY(8px)"},children:l("div",{className:"bg-gray-100 text-gray-800 text-xs rounded-lg px-3 py-2 shadow-lg max-w-xs border border-gray-200",children:[b.scenarioName,b.scenarioDescription&&l(ce,{children:[": ",b.scenarioDescription]}),t("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-100 border-l border-t border-gray-200 transform rotate-45"})]})})]})]},b.scenarioId)):t("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function ip({entity:e}){const r=Ae(),[n,a]=P(!1),o=()=>{a(!0),r.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return te(()=>{r.state==="idle"&&n&&a(!1)},[r.state,n]),t("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:o,children:l("div",{className:"px-5 py-4 flex items-center",children:[l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[t(Ue,{type:e.entityType}),l("div",{className:"min-w-0",children:[l("div",{className:"flex items-center gap-3 mb-0.5",children:[t(oe,{to:`/entity/${e.sha}`,className:"text-sm font-medium text-gray-900 no-underline",children:e.name}),t("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"})]}),t("div",{className:"text-xs text-gray-400 truncate",children:e.filePath})]})]}),t("div",{className:"w-32 flex justify-center",children:t("span",{className:"text-[10px] text-gray-500 bg-gray-100 px-2 py-1 rounded",children:"Not analyzed"})}),t("div",{className:"w-32 text-center text-[10px] text-gray-500",children:ys(e.createdAt||null)}),t("div",{className:"w-24 flex justify-end",children:n||r.state!=="idle"?l("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[t(Ze,{size:14,className:"animate-spin"}),"Analyzing..."]}):t("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 lp=Object.freeze(Object.defineProperty({__proto__:null,default:op,loader:ap,meta:np},Symbol.toStringTag,{value:"Module"}));function cp({request:e,context:r}){const n=r.dbNotifier||fn;if(!n)return console.error("[SSE] ERROR: dbNotifier not found in context or global!"),new Response("Server configuration error",{status:500});n.start().catch(()=>{});const a=new ReadableStream({start(o){const s=new TextEncoder;o.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
225
|
+
|
|
226
|
+
`)),Math.random().toString(36).substring(7);let i=!1;const c=()=>{if(!i){i=!0,n.off("change",d),clearInterval(h);try{o.close()}catch{}}},d=u=>{try{o.enqueue(s.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
|
|
227
|
+
|
|
228
|
+
`))}catch{c()}};n.on("change",d);const h=setInterval(()=>{try{o.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
229
|
+
|
|
230
|
+
`))}catch{c()}},3e4);e.signal.addEventListener("abort",c)}});return new Response(a,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const dp=Object.freeze(Object.defineProperty({__proto__:null,loader:cp},Symbol.toStringTag,{value:"Module"}));function up(){return new Response(JSON.stringify({status:"ok",version:Yn,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const hp=Object.freeze(Object.defineProperty({__proto__:null,loader:up},Symbol.toStringTag,{value:"Module"}));function Vn(e){const r=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,n=e.match(r);if(!n)return{frontmatter:{},body:e};const a=n[1],o=n[2],s={},i=a.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/);i&&(s.paths=i[1].split(`
|
|
231
|
+
`).filter(h=>h.trim().startsWith("-")).map(h=>h.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean));const c=a.match(/category:\s*([^\n]+)/);if(c){const h=c[1].trim().replace(/['"]/g,"");(h==="architecture"||h==="testing"||h==="faq")&&(s.category=h)}const d=a.match(/timestamp:\s*([^\n]+)/);return d&&(s.timestamp=d[1].trim().replace(/['"]/g,"")),{frontmatter:s,body:o}}async function Rt(e,r=""){const n=[];try{const a=await pe.readdir(e,{withFileTypes:!0});for(const o of a){const s=r?`${r}/${o.name}`:o.name;if(o.isDirectory()){const i=await Rt(ue.join(e,o.name),s);n.push(...i)}else o.isFile()&&o.name.endsWith(".md")&&n.push(s)}}catch{}return n}async function mp(e){const r=await Rt(e),n=[];for(const a of r){const o=ue.join(e,a);try{const s=await pe.readFile(o,"utf-8"),{frontmatter:i,body:c}=Vn(s);n.push({filePath:a,absolutePath:o,frontmatter:i,body:c})}catch{}}return n}function pp(e,r){return!r.frontmatter.paths||r.frontmatter.paths.length===0?!1:r.frontmatter.paths.some(n=>bo(e,n,{matchBase:!0}))}const fp="reviewed-rules.json",un=1;function xs(e){return ue.join(e,".codeyam",fp)}async function Br(e){const r=xs(e);try{const n=await pe.readFile(r,"utf-8"),a=JSON.parse(n);return a.version!==un?(console.warn(`[reviewedRules] Unknown version ${a.version}, using empty state`),{version:un,rules:{}}):a}catch{return{version:un,rules:{}}}}async function bs(e,r){const n=xs(e),a=ue.dirname(n);await pe.mkdir(a,{recursive:!0}),await pe.writeFile(n,JSON.stringify(r,null,2),"utf-8")}function gp(e,r){if(!e)return!1;const n=new Date(e.lastModifiedWhenReviewed).getTime();return new Date(r).getTime()<=n}async function yp(e,r,n){const a=await Br(e);a.rules[r]={reviewedAt:new Date().toISOString(),lastModifiedWhenReviewed:n},await bs(e,a)}async function xp(e,r){const n=await Br(e);delete n.rules[r],await bs(e,n)}function ws(e,r){const n={};for(const a of e){const o=r.rules[a.filePath];n[a.filePath]=gp(o,a.lastModified)}return n}function vs(e){if(!e||e==="(diff not available)")return!1;const r=e.split(`
|
|
232
|
+
`).filter(a=>!(!a.startsWith("+")&&!a.startsWith("-")||a.startsWith("+++")||a.startsWith("---"))).map(a=>a.substring(1).trim());if(r.length===0)return!1;const n=/^timestamp:\s*[\d\-T:.Z]+$/;return r.every(a=>n.test(a))}async function bp({request:e}){const r=fe();if(!r)return Response.json({error:"Project root not found"},{status:500});const n=new URL(e.url),a=n.searchParams.get("action"),o=ue.join(r,".claude","rules");if(a==="recent-changes")return vp(r,o);if(a==="reviewed-status")return Cp(r,o);if(a==="audit")return Np(r,o);if(a==="source-files")return Sp(r);if(a==="rules-for-path"){const s=n.searchParams.get("path");return s?Ep(o,s):Response.json({error:"Missing required parameter: path"},{status:400})}try{const s=await Rt(o),i=[];for(const c of s){const d=ue.join(o,c);try{const h=await pe.readFile(d,"utf-8"),u=await pe.stat(d),{frontmatter:m,body:p}=Vn(h);i.push({filePath:c,content:h,frontmatter:m,body:p,lastModified:u.mtime.toISOString()})}catch{}}return i.sort((c,d)=>new Date(d.lastModified).getTime()-new Date(c.lastModified).getTime()),Response.json({memories:i})}catch(s){return console.error("[API] Error loading memories:",s),Response.json({error:"Failed to load memories",details:s instanceof Error?s.message:String(s)},{status:500})}}async function wp(e,r){const n=[];try{const a=r("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const o of a.split(`
|
|
233
|
+
`).filter(Boolean)){const s=o.substring(0,2);let i=o.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const c=i.replace(".claude/rules/","");let d="modified";const h=s[0],u=s[1];h==="A"||h==="?"?d="added":h==="D"||u==="D"?d="deleted":(h==="M"||u==="M")&&(d="modified");let m="";try{if(d==="deleted")m=r(`git diff HEAD -- "${i}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(d==="added"&&h==="?"){const p=`${e}/${i}`;try{const f=await pe.readFile(p,"utf-8");m=`diff --git a/${i} b/${i}
|
|
234
|
+
new file mode 100644
|
|
235
|
+
--- /dev/null
|
|
236
|
+
+++ b/${i}
|
|
237
|
+
@@ -0,0 +1,${f.split(`
|
|
238
|
+
`).length} @@
|
|
239
|
+
${f.split(`
|
|
240
|
+
`).map(y=>"+"+y).join(`
|
|
241
|
+
`)}`}catch{m="(content not available)"}}else m=r(`git diff HEAD -- "${i}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});m.length>5e3&&(m=m.substring(0,5e3)+`
|
|
242
|
+
... (truncated)`)}catch{m="(diff not available)"}d==="modified"&&vs(m)||n.push({filePath:c,changeType:d,diff:m})}}catch{}return n}async function vp(e,r){try{const{execSync:n}=await import("child_process"),a=[],o=await wp(e,n);o.length>0&&a.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:o});const i=n('git log --format="%H|%aI|%s" --since="60 days ago" -- .claude/rules/ 2>/dev/null || true',{cwd:e,encoding:"utf-8",maxBuffer:10*1024*1024}).split(`
|
|
243
|
+
`).filter(Boolean).slice(0,20);for(const m of i){const[p,f,...y]=m.split("|"),g=y.join("|");if(!p||!f)continue;const b=n(`git diff-tree --no-commit-id --name-status -r ${p} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),w=[];for(const x of b.split(`
|
|
244
|
+
`).filter(Boolean)){const[v,C]=x.split(" ");if(!C||!C.startsWith(".claude/rules/"))continue;const k=C.replace(".claude/rules/","");let N="modified";v==="A"?N="added":v==="D"&&(N="deleted");let E="";try{E=n(`git show ${p} --format="" -- "${C}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),E.length>5e3&&(E=E.substring(0,5e3)+`
|
|
245
|
+
... (truncated)`)}catch{E="(diff not available)"}N==="modified"&&vs(E)||w.push({filePath:k,changeType:N,diff:E})}w.length>0&&a.push({commitHash:p.substring(0,8),date:f,message:g,files:w})}const c=await Rt(r),d=[];for(const m of c){const p=ue.join(r,m);try{const f=await pe.stat(p);d.push({filePath:m,lastModified:f.mtime.toISOString()})}catch{}}const h=await Br(e),u=ws(d,h);return Response.json({changes:a,reviewedStatus:u})}catch(n){return console.error("[API] Error getting recent changes:",n),Response.json({changes:[],reviewedStatus:{}})}}async function Cp(e,r){try{const n=await Rt(r),a=[];for(const i of n){const c=ue.join(r,i);try{const d=await pe.stat(c);a.push({filePath:i,lastModified:d.mtime.toISOString()})}catch{}}const o=await Br(e),s=ws(a,o);return Response.json({reviewedStatus:s})}catch(n){return console.error("[API] Error getting reviewed status:",n),Response.json({reviewedStatus:{}})}}async function Cs(e){const r=[],n=[".ts",".tsx",".js",".jsx",".vue",".svelte"];async function a(o,s){try{const i=await pe.readdir(o,{withFileTypes:!0});for(const c of i){const d=ue.join(o,c.name),h=s?`${s}/${c.name}`:c.name;if(!(c.isDirectory()&&(c.name==="node_modules"||c.name===".git"||c.name==="dist"||c.name===".codeyam"||c.name===".claude"||c.name==="build"||c.name==="coverage"))){if(c.isDirectory())await a(d,h);else if(c.isFile()){const u=ue.extname(c.name);n.includes(u)&&r.push(h)}}}}catch{}}return await a(e,""),r}async function Np(e,r){try{const n=await mp(r),a=await Cs(e),o=[];for(const s of a){const i=n.filter(c=>pp(s,c));if(i.length>0){const c=i.reduce((d,h)=>d+h.body.length,0);o.push({filePath:s,matchingRules:i.map(d=>({filePath:d.filePath,patterns:d.frontmatter.paths||[],bodyLength:d.body.length})),totalTextLength:c})}}return o.sort((s,i)=>i.totalTextLength-s.totalTextLength),Response.json({topPaths:o.slice(0,10),totalFilesWithCoverage:o.length})}catch(n){return console.error("[API] Error getting audit data:",n),Response.json({error:"Failed to get audit data",details:n instanceof Error?n.message:String(n)},{status:500})}}async function Sp(e){try{const r=await Cs(e);return Response.json({files:r})}catch(r){return console.error("[API] Error getting source files:",r),Response.json({error:"Failed to get source files",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Ep(e,r){try{const n=await Rt(e),a=[];for(const s of n){const i=ue.join(e,s);try{const c=await pe.readFile(i,"utf-8"),d=await pe.stat(i),{frontmatter:h,body:u}=Vn(c);h.paths&&h.paths.some(m=>bo(r,m,{matchBase:!0}))&&a.push({filePath:s,content:c,frontmatter:h,body:u,lastModified:d.mtime.toISOString()})}catch{}}const o=a.reduce((s,i)=>s+i.body.length,0);return Response.json({rules:a,totalTextLength:o})}catch(n){return console.error("[API] Error getting rules for path:",n),Response.json({error:"Failed to get rules for path",details:n instanceof Error?n.message:String(n)},{status:500})}}async function Ap({request:e}){const r=fe();if(!r)return Response.json({error:"Project root not found"},{status:500});const n=ue.join(r,".claude","rules");try{const a=await e.json(),{action:o,filePath:s,content:i,lastModified:c}=a;if(!s)return Response.json({error:"Missing required field: filePath"},{status:400});if(o==="mark-reviewed")return c?(await yp(r,s,c),console.log(`[API] Rule marked as reviewed: ${s}`),Response.json({success:!0,message:"Rule marked as reviewed",filePath:s})):Response.json({error:"Missing required field: lastModified"},{status:400});if(o==="mark-unreviewed")return await xp(r,s),console.log(`[API] Rule marked as unreviewed: ${s}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:s});const d=ue.normalize(s);if(d.includes("..")||ue.isAbsolute(d))return Response.json({error:"Invalid file path"},{status:400});const h=ue.join(n,d);switch(o){case"create":case"update":return i?(await pe.mkdir(ue.dirname(h),{recursive:!0}),await pe.writeFile(h,i,"utf-8"),console.log(`[API] Memory ${o}d: ${s}`),Response.json({success:!0,message:`Memory ${o}d successfully`,filePath:s})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await pe.unlink(h),console.log(`[API] Memory deleted: ${s}`);const u=ue.dirname(h);try{(await pe.readdir(u)).length===0&&u!==n&&await pe.rmdir(u)}catch{}return Response.json({success:!0,message:"Memory deleted successfully"})}catch(u){if(u.code==="ENOENT")return Response.json({error:"Memory not found"},{status:404});throw u}default:return Response.json({error:"Invalid action. Must be create, update, or delete"},{status:400})}}catch(a){return console.error("[API] Error managing memory:",a),Response.json({error:"Failed to manage memory",details:a instanceof Error?a.message:String(a)},{status:500})}}const kp=Object.freeze(Object.defineProperty({__proto__:null,action:Ap,loader:bp},Symbol.toStringTag,{value:"Module"}));async function Pp({request:e,context:r}){var s;let n=r.analysisQueue;if(n||(n=await st()),!n)return J({error:"Queue not initialized"},{status:500});const a=new URL(e.url),o=a.searchParams.get("queryType");if(!o)return J({error:"Missing queryType parameter for GET request"},{status:400});if(o==="job"){const i=a.searchParams.get("jobId");if(!i)return J({error:"Missing jobId parameter for job query"},{status:400});const c=n.getState();if(((s=c.currentlyExecuting)==null?void 0:s.id)===i)return J({jobId:i,status:"running",job:c.currentlyExecuting});const d=c.jobs.find(u=>u.id===i);if(d){const u=c.jobs.indexOf(d);return J({jobId:i,status:"queued",position:u,job:d})}const h=n.getJobResult(i);return h?J({jobId:i,status:h.status==="error"?"failed":"completed",error:h.error}):J({jobId:i,status:"completed"})}if(o==="full"){const i=n.getState(),c=await Promise.all(i.jobs.map(async h=>{const u=[];if(h.entityShas&&h.entityShas.length>0){const m=h.entityShas.map(f=>Mt(f)),p=await Promise.all(m);u.push(...p.filter(f=>f!==null))}return{id:h.id,type:h.type,commitSha:h.commitSha,projectSlug:h.projectSlug,queuedAt:h.queuedAt,entities:u,filePaths:h.filePaths}}));let d;if(i.currentlyExecuting){const h=i.currentlyExecuting,u=[];if(h.entityShas&&h.entityShas.length>0){const m=h.entityShas.map(f=>Mt(f)),p=await Promise.all(m);u.push(...p.filter(f=>f!==null))}d={id:h.id,type:h.type,commitSha:h.commitSha,projectSlug:h.projectSlug,queuedAt:h.queuedAt,entities:u,filePaths:h.filePaths}}return J({state:{...i,jobsWithEntities:c,currentlyExecutingWithEntities:d}})}return J({error:"Unknown queryType"},{status:400})}async function Mp({request:e,context:r}){console.log("[Queue API] Received request"),console.log("[Queue API] Context keys:",Object.keys(r||{})),console.log("[Queue API] analysisQueue exists:",!!(r!=null&&r.analysisQueue));let n=r.analysisQueue;if(n||(n=await st(),console.log("[Queue API] Using global queue")),!n)return console.error("[Queue API] ERROR: Queue not initialized in context"),J({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:c}=n.enqueue(s);return c.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),J({jobId:i,status:"queued"})}if(o==="resume")return n.resume(),J({status:"resumed"});if(o==="pause")return n.pause(),J({status:"paused"});if(o==="remove"){const{jobId:i}=s;return i?n.removeJob(i)?J({status:"removed",jobId:i}):J({error:"Job not found in queue"},{status:404}):J({error:"Missing jobId parameter"},{status:400})}if(o==="clear"){const i=n.clearQueue();return J({status:"cleared",count:i})}if(o==="reorder"){const{jobId:i,direction:c}=s;return!i||!c?J({error:"Missing jobId or direction parameter"},{status:400}):c!=="up"&&c!=="down"?J({error:'Invalid direction: must be "up" or "down"'},{status:400}):n.reorderJob(i,c)?J({status:"reordered",jobId:i,direction:c}):J({error:"Could not reorder job (not found or at boundary)"},{status:400})}return J({error:"Unknown action"},{status:400})}const _p=Object.freeze(Object.defineProperty({__proto__:null,action:Mp,loader:Pp},Symbol.toStringTag,{value:"Module"})),Tp=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],Ip=Oe(function(){return Ae(),t(Fr,{children:l("div",{className:"h-screen bg-[#F8F7F6] flex flex-col overflow-hidden",children:[t("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-center h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0",children:[t("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:t("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),t("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),t("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"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[l("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[t("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),t("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),t("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"})]}),l("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[t("span",{className:"leading-[22px]",children:"Next Entity"}),t("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:t("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),t("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:l("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[l("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",t("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),l("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",t("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),t("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),t("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),t("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),l("div",{className:"flex flex-1 gap-0 min-h-0",children:[t("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:t("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),t(gs,{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})]})]})})}),$p=Object.freeze(Object.defineProperty({__proto__:null,default:Ip,meta:Tp},Symbol.toStringTag,{value:"Module"})),jp=()=>[{title:"CodeYam - Settings"},{name:"description",content:"Configure project settings"}];async function Rp({request:e}){try{const r=await Fn();if(!r)return J({config:null,secrets:null,versionInfo:null,error:"Project configuration not found"});const n=fe()||process.cwd(),a=await Rr(n),o=Zo(r.projectSlug);return J({config:r,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(r){return console.error("Failed to load config:",r),J({config:null,secrets:null,versionInfo:null,error:"Failed to load configuration"})}}function Dp(e){if(!e||!e.trim())return;const r=e.trim().split(/\s+/);if(r.length===0)return;const n=r[0],a=r.length>1?r.slice(1):void 0;return{command:n,args:a}}async function Lp({request:e}){try{const r=await e.formData(),n=r.get("universalMocks"),a=r.get("startCommands"),o=r.get("groqApiKey"),s=r.get("anthropicApiKey"),i=r.get("openAiApiKey"),c=r.get("pathsToIgnore");let d;if(n)try{d=JSON.parse(n)}catch{return J({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let h;if(a)try{h=JSON.parse(a)}catch{return J({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let u;c&&(u=c.split(",").map(y=>y.trim()).map(y=>y.startsWith('"')&&y.endsWith('"')||y.startsWith("'")&&y.endsWith("'")?y.slice(1,-1):y).filter(y=>y.length>0));let m;if(h){const y=await Fn();y!=null&&y.webapps&&(m=y.webapps.map((g,b)=>{if(h[b]!==void 0){const w=Dp(h[b]);return{...g,startCommand:w}}return g}))}if(!await Uo({universalMocks:d,pathsToIgnore:u,webapps:m}))return J({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 y=fe()||process.cwd(),g=await Rr(y);f=o!==void 0&&o!==(g.GROQ_API_KEY||"")||s!==void 0&&s!==(g.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(g.OPENAI_API_KEY||""),await Nc(y,{...g,GROQ_API_KEY:o||void 0,ANTHROPIC_API_KEY:s||void 0,OPENAI_API_KEY:i||void 0},!0)}return J({success:!0,error:null,requiresRestart:f})}catch(r){return console.log("[Settings Action] Failed to save config:",r),J({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function ao(e){if(!e)return"";const r=[e.command];return e.args&&e.args.length>0&&r.push(...e.args),r.join(" ")}function oo({mock:e,onSave:r,onCancel:n}){const[a,o]=P(e.entityName),[s,i]=P(e.filePath),[c,d]=P(e.content);return l("div",{className:"space-y-3",children:[l("div",{children:[t("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),t("input",{type:"text",value:a,onChange:u=>o(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., determineDatabaseType"})]}),l("div",{children:[t("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),t("input",{type:"text",value:s,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),l("div",{children:[t("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),t("textarea",{value:c,onChange:u=>d(u.target.value),rows:6,className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., function determineDatabaseType() { return 'postgresql' }"})]}),l("div",{className:"flex gap-2 justify-end",children:[t("button",{type:"button",onClick:n,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),t("button",{type:"button",onClick:()=>{if(!a.trim()||!s.trim()||!c.trim()){alert("All fields are required");return}r({entityName:a,filePath:s,content:c})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function Fp(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const Op=Oe(function(){var W,Q;const{config:r,secrets:n,versionInfo:a,error:o}=We(),s=Ks(),i=Ae(),c=rt(),[d,h]=P("project-metadata");mt({source:"settings-page"});const[u,m]=P((r==null?void 0:r.universalMocks)||[]),[p,f]=P(((r==null?void 0:r.pathsToIgnore)||[]).join(", ")),[y,g]=P(((r==null?void 0:r.pathsToIgnore)||[]).join(", ")),[b,w]=P((n==null?void 0:n.GROQ_API_KEY)||""),[x,v]=P((n==null?void 0:n.ANTHROPIC_API_KEY)||""),[C,k]=P((n==null?void 0:n.OPENAI_API_KEY)||""),[N,E]=P(!1),[A,I]=P(!1),[j,R]=P(!1),[M,T]=P(!1),[$,z]=P(!1),[G,U]=P(!1),[B,D]=P(null),[L,_]=P(!1),[S,F]=P({});te(()=>{var q;if(r){m(r.universalMocks||[]);const Z=(r.pathsToIgnore||[]).join(", ");f(Z),g(Z);const de={};(q=r.webapps)==null||q.forEach((he,ye)=>{he.startCommand&&(de[ye]=ao(he.startCommand))}),F(de)}n&&(w(n.GROQ_API_KEY||""),v(n.ANTHROPIC_API_KEY||""),k(n.OPENAI_API_KEY||""))},[r,n]),te(()=>{if(s!=null&&s.success){T(!0);const q=setTimeout(()=>T(!1),3e3);return()=>clearTimeout(q)}},[s]),te(()=>{if(i.state==="idle"&&i.data&&!G){console.log("[Settings] Fetcher data:",i.data);const q=i.data;if(q.success){console.log("[Settings] Save successful, revalidating..."),T(!0),U(!0),(p!==y||q.requiresRestart)&&z(!0),c.revalidate();const Z=setTimeout(()=>{T(!1),U(!1)},3e3);return()=>clearTimeout(Z)}}},[i.state,i.data,G,c,p,y]);const O=q=>{q.preventDefault();const Z=new FormData(q.currentTarget);Z.set("universalMocks",JSON.stringify(u)),Z.set("startCommands",JSON.stringify(S)),console.log("[Settings] Submitting form data:",{universalMocks:Z.get("universalMocks"),startCommands:Z.get("startCommands"),openAiApiKey:Z.get("openAiApiKey")?"***":"(empty)"}),i.submit(Z,{method:"post"})},H=q=>{m([...u,q]),_(!1)},ae=(q,Z)=>{const de=[...u];de[q]=Z,m(de),D(null)},V=q=>{m(u.filter((Z,de)=>de!==q))};if(o)return l("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[t("header",{className:"mb-6 pb-4 border-b border-gray-200",children:t("div",{className:"flex justify-between items-center",children:t("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),t("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:t("p",{className:"text-red-700",children:o})})]});const Y=[{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 t("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-20 pt-8 pb-12 font-sans",children:[l("div",{className:"mb-8 flex justify-between items-start",children:[l("div",{children:[t("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Settings"}),t("p",{className:"text-[15px] text-gray-500",children:"Project Configuration"})]}),t("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"})]}),l("div",{className:"flex gap-8 items-start",children:[t("nav",{className:"w-64 flex-shrink-0",children:t("ul",{className:"space-y-1",children:Y.map(q=>t("li",{children:t("button",{type:"button",onClick:()=>h(q.id),className:`w-full text-left px-0 py-2.5 text-sm transition-colors cursor-pointer ${d===q.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:q.label})},q.id))})}),t("div",{className:"flex-1 min-w-0 -mt-2",children:l("form",{id:"settings-form",onSubmit:O,className:"space-y-6",children:[d==="project-metadata"&&l("div",{children:[t("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),l("div",{className:"mb-6",children:[t("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),r!=null&&r.webapps&&r.webapps.length>0?t("div",{className:"space-y-3",children:r.webapps.map((q,Z)=>{var de;return t("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Path:"})," ",t("span",{className:"text-gray-900",children:q.path==="."?"Root":q.path})]}),q.appDirectory&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",t("span",{className:"text-gray-900",children:q.appDirectory})]}),l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",t("span",{className:"text-gray-900",children:q.framework})]}),q.startCommand&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",l("span",{className:"text-gray-900 font-mono text-xs",children:[q.startCommand.command," ",(de=q.startCommand.args)==null?void 0:de.join(" ")]})]})]})},Z)})}):t("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"}),t("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"&&l("div",{children:[t("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),t("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."}),l("div",{className:"space-y-6",children:[l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[t("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[t("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),t("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."}),l("div",{className:"flex gap-3 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[t("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[t("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[t("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),l("div",{className:"mt-4",children:[t("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[t("input",{type:N?"text":"password",id:"groqApiKey",name:"groqApiKey",value:b,onChange:q=>w(q.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]"}),t("button",{type:"button",onClick:()=>E(!N),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:N?"Hide":"Show"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[t("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[t("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),t("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."}),l("div",{className:"flex gap-3 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[t("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[t("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[t("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[t("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[t("input",{type:A?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:x,onChange:q=>v(q.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]"}),t("button",{type:"button",onClick:()=>I(!A),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:A?"Hide":"Show"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[t("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[t("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),t("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."}),l("div",{className:"flex gap-3 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[t("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[t("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[t("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[t("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[t("input",{type:j?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:C,onChange:q=>k(q.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]"}),t("button",{type:"button",onClick:()=>R(!j),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:j?"Hide":"Show"})]})]})]})]})]}),d==="commands"&&l("div",{children:[t("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),t("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),r!=null&&r.webapps&&r.webapps.length>0?t("div",{className:"space-y-4",children:r.webapps.map((q,Z)=>l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[l("div",{className:"mb-4",children:[t("div",{className:"text-base font-semibold text-gray-900 mb-1",children:q.path==="."?"Root":q.path}),t("div",{className:"text-sm text-gray-600",children:q.framework})]}),l("div",{children:[t("label",{htmlFor:`startCommand-${Z}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),t("input",{type:"text",id:`startCommand-${Z}`,name:`startCommand-${Z}`,value:S[Z]||"",onChange:de=>F({...S,[Z]:de.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]"}),t("p",{className:"mt-2 text-xs text-gray-500",children:"Use $PORT as a placeholder for the dynamic port number"})]})]},Z))}):t("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),d==="paths-to-ignore"&&l("div",{children:[t("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),t("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:p,onChange:q=>f(q.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"}),l("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",t("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",t("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",t("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),t("br",{}),t("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"&&l("div",{children:[t("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),t("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),u.length===0?l("div",{className:"mb-4",children:[t("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),t("button",{type:"button",onClick:()=>_(!0),className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}):t("div",{className:"space-y-3",children:u.map((q,Z)=>t("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:B===Z?t(oo,{mock:q,onSave:de=>ae(Z,de),onCancel:()=>D(null)}):t(ce,{children:l("div",{className:"flex justify-between items-start mb-2",children:[l("div",{className:"flex-1",children:[t("div",{className:"font-medium text-gray-800 mb-1",children:q.entityName}),t("div",{className:"text-sm text-gray-600 mb-2",children:q.filePath}),t("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:q.content})]}),l("div",{className:"flex gap-2 ml-3",children:[t("button",{type:"button",onClick:()=>D(Z),className:"px-3 py-1 bg-teal-600 text-white border-none rounded text-sm cursor-pointer hover:bg-teal-700",children:"Edit"}),t("button",{type:"button",onClick:()=>V(Z),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},Z))}),u.length>0&&t("button",{type:"button",onClick:()=>_(!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"&&l("div",{className:"space-y-6",children:[r&&l("div",{children:[t("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),t("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:l("div",{className:"space-y-2 text-sm",children:[r.projectSlug&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",t("span",{className:"text-gray-900",children:r.projectSlug})]}),r.packageManager&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",t("span",{className:"text-gray-900",children:r.packageManager})]})]})}),r.webapps&&r.webapps.length>0&&l("div",{children:[t("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),t("div",{className:"space-y-3",children:r.webapps.map((q,Z)=>t("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Path:"})," ",t("span",{className:"text-gray-900",children:q.path==="."?"Root":q.path})]}),q.appDirectory&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",t("span",{className:"text-gray-900",children:q.appDirectory})]}),l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",t("span",{className:"text-gray-900",children:q.framework})]}),q.startCommand&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",t("span",{className:"text-gray-900 font-mono text-xs",children:ao(q.startCommand)})]})]})},Z))})]})]}),a&&l("div",{className:"mt-6",children:[t("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),t("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[a.webserverVersion&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",t("span",{className:"text-gray-900 font-mono",children:a.webserverVersion.version||"unknown"})]}),a.templateVersion&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",t("span",{className:"font-mono text-gray-900",children:a.templateVersion.version||((W=a.templateVersion.gitCommit)==null?void 0:W.slice(0,7))||"unknown"}),a.templateVersion.buildTimestamp&&l("span",{className:"text-gray-500 ml-2",children:["(built"," ",Fp(a.templateVersion.buildTimestamp),")"]})]}),a.cachedAnalyzerVersion&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",t("span",{className:"font-mono text-gray-900",children:a.cachedAnalyzerVersion.version||((Q=a.cachedAnalyzerVersion.gitCommit)==null?void 0:Q.slice(0,7))||"unknown"}),a.isCacheStale?t("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"}):t("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]}),!a.cachedAnalyzerVersion&&(r==null?void 0:r.projectSlug)&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",t("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),(M||$||(s==null?void 0:s.error)||i.data&&typeof i.data=="object"&&"error"in i.data)&&l("div",{className:"mt-6 max-w-5xl mx-auto space-y-3",children:[M&&t("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!"}),$&&l("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[t("div",{children:"⚠️ Settings changed. Please restart CodeYam for changes to take effect:"}),t("code",{className:"ml-2 bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"})]}),(s==null?void 0:s.error)&&t("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 q=i.data;return typeof q.error=="string"?t("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:q.error}):null}return null})()]}),L&&t("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:l("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[t("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),t(oo,{mock:{entityName:"",filePath:"",content:""},onSave:H,onCancel:()=>_(!1)})]})})]})})}),zp=Object.freeze(Object.defineProperty({__proto__:null,action:Lp,default:Op,loader:Rp,meta:jp},Symbol.toStringTag,{value:"Module"}));async function Yp({params:e}){const r=e["*"];if(!r)return new Response("Static path is required",{status:400});const n=fe();if(!n)return new Response("Project root not found",{status:500});const o=ue.extname(r)!==""?r:`${r}.html`,s=ue.join(n,".codeyam","captures","static",o);try{await pe.access(s);let i=await pe.readFile(s);const c=ue.extname(s).toLowerCase();let d="application/octet-stream";if(c===".html"){d="text/html";let h=i.toString("utf-8");const u=h.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const p=u[1].match(/=\s*(\{[\s\S]*\})/);if(p){const f=JSON.parse(p[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const y=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;h=h.replace(u[0],y)}}catch(m){console.error("[Static] Failed to parse Remix context:",m)}i=Buffer.from(h,"utf-8")}else c===".js"||c===".mjs"?d="application/javascript":c===".css"?d="text/css":c===".json"?d="application/json":c===".png"?d="image/png":c===".jpg"||c===".jpeg"?d="image/jpeg":c===".svg"?d="image/svg+xml":c===".woff"?d="font/woff":c===".woff2"?d="font/woff2":c===".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 Bp=Object.freeze(Object.defineProperty({__proto__:null,loader:Yp},Symbol.toStringTag,{value:"Module"}));function Up(e,r,n=10){var d;const a=new Map,o=h=>h.entityType==="visual"||h.entityType==="library";for(const h of e)o(h)&&a.set(h.sha,{entity:h,depth:0});const s=new Map;for(const h of r){const u=(d=h.metadata)==null?void 0:d.importedBy;if(u)for(const m of Object.keys(u))for(const p of Object.keys(u[m])){const{shas:f}=u[m][p];for(const y of f)s.has(h.sha)||s.set(h.sha,new Set),s.get(h.sha).add(y)}}const i=[],c=new Set;for(const h of e)i.push({sha:h.sha,depth:0}),c.add(h.sha);for(;i.length>0;){const{sha:h,depth:u}=i.shift();if(u>=n)continue;const m=s.get(h);if(m)for(const p of m){if(c.has(p))continue;c.add(p);const f=r.find(y=>y.sha===p);if(f){if(o(f)){const y=u+1,g=a.get(p);(!g||y<g.depth)&&a.set(p,{entity:f,depth:y})}i.push({sha:p,depth:u+1})}}}return Array.from(a.values()).sort((h,u)=>h.depth!==u.depth?h.depth-u.depth:h.entity.name.localeCompare(u.entity.name))}function Ar(e){const r=new Map;for(const a of e)r.has(a.name)||r.set(a.name,[]),r.get(a.name).push(a);const n=[];for(const a of r.values())if(a.length===1)n.push(a[0]);else{const o=a.sort((s,i)=>{var h,u;const c=((h=s.metadata)==null?void 0:h.editedAt)||s.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(c)});n.push(o[0])}return n}function Ns(e,r){const n=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=r.filter(d=>d.filePath===o.path||o.status==="renamed"&&o.oldPath&&d.filePath===o.oldPath),i=s.filter(d=>{var h,u;return a.has(d.filePath)&&((h=d.metadata)==null?void 0:h.isUncommitted)&&!((u=d.metadata)!=null&&u.isSuperseded)}),c=Ar(i);n.set(o.path,{status:o,entities:s,editedEntities:c})}return n}function Wp(e,r,n){const a=new Map;if(!n){for(const s of e)if(s.status==="deleted")a.set(s.path,{status:s,entities:[]});else{const i=r.filter(d=>d.filePath===s.path||s.status==="renamed"&&s.oldPath&&d.filePath===s.oldPath),c=Ar(i);a.set(s.path,{status:s,entities:c})}return a}const o=new Map;for(const s of n.fileComparisons){const i=new Set;for(const c of s.newEntities)i.add(c.name);for(const c of s.modifiedEntities)i.add(c.name);for(const c of s.deletedEntities)i.add(c.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 c=i?r.filter(h=>(h.filePath===s.path||s.status==="renamed"&&s.oldPath&&h.filePath===s.oldPath)&&i.has(h.name)):[],d=Ar(c);a.set(s.path,{status:s,entities:d})}}return a}function Hp(e,r){const n=new Map,a=Ss(e,r);for(const o of a){const i=Up([o],r).filter(({depth:c})=>c>0);n.set(o.sha,i)}return n}function Ss(e,r){const n=new Set(e.map(o=>o.path));for(const o of e)o.status==="renamed"&&o.oldPath&&n.add(o.oldPath);const a=r.filter(o=>{var s,i;return n.has(o.filePath)&&((s=o.metadata)==null?void 0:s.isUncommitted)&&!((i=o.metadata)!=null&&i.isSuperseded)});return Ar(a)}function qp({recentSimulations:e}){const r=ne(()=>{const n=new Map;return e.forEach(a=>{const o=a.entitySha,s=n.get(o);s?s.push(a):n.set(o,[a])}),Array.from(n.entries()).map(([a,o])=>({entitySha:a,entityName:o[0].entityName,scenarios:o}))},[e]);return l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[t("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[t("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),t("p",{className:"text-sm text-gray-500 m-0",children:e.length>0?`Latest ${e.length} captured screenshot${e.length!==1?"s":""}`:"No simulations captured yet"})]})}),e.length>0?l(ce,{children:[t("div",{className:"space-y-6 mb-5",children:r.map(n=>l("div",{children:[l("div",{className:"mb-3 flex items-center gap-2",children:[t("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:t(Ht,{size:16,style:{color:"#8B5CF6"}})}),t(oe,{to:`/entity/${n.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:n.entityName})]}),t("div",{className:"grid grid-cols-4 gap-3",children:n.scenarios.map((a,o)=>t(oe,{to:a.scenarioId?`/entity/${a.entitySha}/scenarios/${a.scenarioId}`:`/entity/${a.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:s=>{s.currentTarget.style.borderColor="#005C75",s.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:s=>{s.currentTarget.style.borderColor="#E5E7EB",s.currentTarget.style.boxShadow="none"},title:a.scenarioName,children:t(De,{screenshotPath:a.screenshotPath,alt:a.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},a.scenarioId||`${a.entitySha}-${o}`))})]},n.entitySha))}),t(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:n=>n.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:n=>n.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):l("div",{className:"py-12 px-6 text-center rounded-lg w-full flex flex-col items-center justify-center min-h-50 border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[t("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:t(Ht,{size:24,style:{color:"#7A9BA5"},strokeWidth:1.5})}),t("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No simulations captured yet."}),l("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",t(oe,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",t(oe,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const Jp="/assets/codeyam-name-logo-CvKwUgHo.svg",Gp=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function Vp({request:e,context:r}){var n,a;try{const o=r.analysisQueue,s=o?o.getState():{paused:!1,jobs:[]},[i,c,d]=await Promise.all([er(),ze(),It()]),h=ds(),u=i?Ns(h,i):new Map,m=Array.from(u.entries()).sort((j,R)=>j[0].localeCompare(R[0])),p=(i==null?void 0:i.length)||0,f=(i==null?void 0:i.filter(j=>j.entityType==="visual").length)||0,y=(i==null?void 0:i.filter(j=>j.entityType==="library").length)||0,g=i?Ss(h,i):[],b=g.length,w=(i==null?void 0:i.filter(j=>(j.analyses??[]).filter(R=>R.scenarios&&R.scenarios.length>0).length>0).length)||0,x=(i==null?void 0:i.reduce((j,R)=>{var T,$,z;const M=((z=($=(T=R.analyses)==null?void 0:T[0])==null?void 0:$.scenarios)==null?void 0:z.length)||0;return j+M},0))||0,v=(i==null?void 0:i.reduce((j,R)=>{var $,z;const T=(((z=($=R.analyses)==null?void 0:$[0])==null?void 0:z.scenarios)||[]).filter(G=>{var U,B;return(B=(U=G.metadata)==null?void 0:U.screenshotPaths)==null?void 0:B[0]}).length;return j+T},0))||0,C=[];i==null||i.forEach(j=>{var M;const R=(M=j.analyses)==null?void 0:M[0];R!=null&&R.scenarios&&R.scenarios.filter($=>{var z;return!((z=$.metadata)!=null&&z.sameAsDefault)}).forEach($=>{var G,U;const z=(U=(G=$.metadata)==null?void 0:G.screenshotPaths)==null?void 0:U[0];z&&C.push({entitySha:j.sha,entityName:j.name,scenarioId:$.id,scenarioName:$.name,screenshotPath:z,createdAt:R.createdAt||""})})}),C.sort((j,R)=>new Date(R.createdAt).getTime()-new Date(j.createdAt).getTime());const k=C.slice(0,16),N=(i==null?void 0:i.filter(j=>j.entityType==="visual").filter(j=>{var T,$;const R=(T=j.analyses)==null?void 0:T[0];return!(($=R==null?void 0:R.scenarios)==null?void 0:$.some(z=>{var G,U;return(U=(G=z.metadata)==null?void 0:G.screenshotPaths)==null?void 0:U[0]}))}).slice(0,8))||[],E=(n=d==null?void 0:d.metadata)==null?void 0:n.currentRun,A=((a=E==null?void 0:E.currentEntityShas)==null?void 0:a.length)||0,I=s.jobs.length||0;return J({stats:{totalEntities:p,visualEntities:f,libraryEntities:y,uncommittedEntities:b,entitiesWithAnalyses:w,totalScenarios:x,capturedScreenshots:v,currentlyAnalyzing:A,filesOnQueue:I},uncommittedFiles:m,uncommittedEntitiesList:g,recentSimulations:k,visualEntitiesForSimulation:N,projectSlug:c,queueState:s,currentCommit:d})}catch(o){return console.error("Failed to load dashboard data:",o),J({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 Qp=Oe(function(){var D,L;const{stats:r,uncommittedFiles:n,uncommittedEntitiesList:a,recentSimulations:o,visualEntitiesForSimulation:s,projectSlug:i,queueState:c,currentCommit:d}=We(),h=Ae(),u=rt(),{showToast:m}=$n();mt({source:"dashboard"});const[p,f]=P(new Set),[y,g]=P(null),[b,w]=P(!1),[x,v]=P(!1),{lastLine:C,isCompleted:k}=pt(i,!!y),{simulatingEntity:N,scenarios:E,scenarioStatuses:A,allScenariosCaptured:I}=ne(()=>{var Y,W;const _={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!y)return _;const S=s==null?void 0:s.find(Q=>Q.sha===y);if(!S)return _;const F=(Y=S.analyses)==null?void 0:Y[0],O=(F==null?void 0:F.scenarios)||[],H=((W=F==null?void 0:F.status)==null?void 0:W.scenarios)||[],ae=H.filter(Q=>Q.screenshotFinishedAt).length,V=O.length>0&&ae===O.length;return{simulatingEntity:S,scenarios:O,scenarioStatuses:H,allScenariosCaptured:V}},[y,s]);te(()=>{(k||I)&&g(null)},[k,I]);const j=(D=d==null?void 0:d.metadata)==null?void 0:D.currentRun,R=new Set((j==null?void 0:j.currentEntityShas)||[]),M=new Set(c.jobs.flatMap(_=>_.entityShas||[])),T=new Set(((L=c.currentlyExecuting)==null?void 0:L.entityShas)||[]),$=a.filter(_=>_.entityType==="visual"||_.entityType==="library"),z=$.filter(_=>!R.has(_.sha)&&!M.has(_.sha)&&!T.has(_.sha)),G=()=>{if(z.length===0){m("All entities are already queued or analyzing","info",3e3);return}const _=z.map(S=>S.sha);v(!0),m(`Starting analysis for ${z.length} entities...`,"info",3e3),h.submit({entityShas:_.join(",")},{method:"post",action:"/api/analyze"})};te(()=>{if(h.state==="idle"&&h.data){const _=h.data;_.success?(console.log("[Analyze All] Success:",_.message),m(`Analysis started for ${_.entityCount} entities in ${_.fileCount} files. Watch the logs for progress.`,"success",6e3),v(!1)):_.error&&(console.error("[Analyze All] Error:",_.error),m(`Error: ${_.error}`,"error",8e3),v(!1))}},[h.state,h.data,m]);const U=_=>{f(S=>{const F=new Set(S);return F.has(_)?F.delete(_):F.add(_),F})},B=[{label:"Total Entities",value:r.totalEntities,iconType:"folder",link:"/files",color:"#005C75",tooltip:"In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested."},{label:"Analyzed Entities",value:r.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981",tooltip:"Entities that have been analyzed by CodeYam and have generated scenarios."},{label:"Visual Components",value:r.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6",tooltip:"React components and visual elements that can be rendered and captured as screenshots."},{label:"Library Functions",value:r.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9",tooltip:"Reusable functions and utilities that can be independently tested."}];return t("div",{className:"bg-cygray-10 min-h-screen",children:l("div",{className:"px-20 pt-8 pb-12",children:[l("header",{className:"mb-8 flex justify-between items-center",children:[l("div",{className:"flex items-center gap-4",children:[t("img",{src:Jp,alt:"CodeYam",className:"h-3.5"}),t("span",{className:"text-gray-400 text-sm",children:"|"}),t("h1",{className:"text-sm font-mono font-normal text-gray-400 m-0",children:i?i.replace(/-/g," ").replace(/\b\w/g,_=>_.toUpperCase()):"Project"})]}),u.state==="loading"&&t("div",{className:"text-blue-600 text-sm font-medium animate-pulse",children:"🔄 Updating..."})]}),t("div",{className:"flex items-center justify-between gap-3",children:B.map((_,S)=>t(oe,{to:_.link,className:"flex-1 bg-white rounded-xl border border-gray-200 overflow-hidden flex transition-all hover:shadow-lg no-underline cursor-pointer",style:{borderLeft:`4px solid ${_.color}`},children:l("div",{className:"px-6 py-6 flex flex-col gap-3 flex-1",children:[l("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[l("div",{className:"flex items-center gap-1.5 group relative",children:[t("span",{className:"text-xs text-gray-700 font-medium font-mono uppercase",children:_.label}),l("svg",{className:"w-3 h-3 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),t("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[_.tooltip,t("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),t("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 sm:hidden md:flex",style:{color:_.color},children:"View All →"})]}),l("div",{className:"flex flex-col gap-2",children:[l("div",{className:"flex items-center gap-3",children:[l("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${_.color}15`},children:[_.iconType==="folder"&&t(xi,{size:20,style:{color:_.color}}),_.iconType==="check"&&t(Nn,{size:20,style:{color:_.color}}),_.iconType==="image"&&t(Ht,{size:20,style:{color:_.color}}),_.iconType==="code-xml"&&t(bi,{size:20,style:{color:_.color}})]}),t("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:_.value.toLocaleString("en-US")})]}),t("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:_.color},children:"View All →"})]})]})},S))}),l("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[l("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[l("div",{className:"flex justify-between items-start mb-5",children:[l("div",{children:[t("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),t("p",{className:"text-sm text-gray-500 m-0",children:n.length>0?`${n.length} file${n.length!==1?"s":""} with ${a.length} uncommitted entit${a.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),$.length>0&&t("button",{onClick:G,disabled:h.state!=="idle"||x||z.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:h.state!=="idle"||x?"Starting analysis...":z.length===0?"All Queued":"Analyze All"})]}),n.length>0?t("div",{className:"flex flex-col gap-3",children:n.map(([_,S])=>{const F=p.has(_),O=S.editedEntities||[];return l("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#005C75"},children:[t("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>U(_),role:"button",tabIndex:0,children:l("div",{className:"flex items-center gap-3",children:[t("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:F?"▼":"▶"}),l("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[l("g",{clipPath:"url(#clip0_784_10666)",children:[t("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"}),t("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),t("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),t("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),t("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),t("defs",{children:t("clipPath",{id:"clip0_784_10666",children:t("rect",{width:"12",height:"16",fill:"white"})})})]}),l("div",{className:"flex-1 min-w-0",children:[t("span",{className:"font-normal text-gray-900 text-sm block truncate",children:_}),l("span",{className:"text-xs text-gray-500",children:[O.length," entit",O.length!==1?"ies":"y"]})]})]})}),F&&t("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:O.length>0?O.map(H=>{const ae=R.has(H.sha),V=M.has(H.sha)||T.has(H.sha);return l(oe,{to:`/entity/${H.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:Y=>Y.currentTarget.style.borderColor="#005C75",onMouseLeave:Y=>Y.currentTarget.style.borderColor="inherit",children:[l("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:H.entityType==="visual"?"#8B5CF615":H.entityType==="library"?"#6366F1":"#EC4899"},children:[H.entityType==="visual"&&t(Ht,{size:16,style:{color:"#8B5CF6"}}),H.entityType==="library"&&t(uo,{size:16,className:"text-white"}),H.entityType==="other"&&t(wi,{size:16,className:"text-white"})]}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-0.5",children:[t("div",{className:"font-semibold text-gray-900 text-sm",children:H.name}),H.entityType==="visual"&&t("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),H.entityType==="library"&&t("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),H.entityType==="other"&&t("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),H.description&&t("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:H.description})]}),l("div",{className:"flex items-center gap-2 shrink-0",children:[ae&&l("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[t(Ze,{size:14,className:"animate-spin"}),"Analyzing..."]}),!ae&&V&&t("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!ae&&!V&&t("button",{onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),m(`Starting analysis for ${H.name}...`,"info",3e3),h.submit({entityShas:H.sha},{method:"post",action:"/api/analyze"})},disabled:h.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:Y=>Y.currentTarget.style.backgroundColor="#004560",onMouseLeave:Y=>Y.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},H.sha)}):t("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},_)})}):l("div",{className:"py-12 px-6 text-center flex flex-col items-center rounded-lg min-h-50 justify-center border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[t("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:l("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#7A9BA5",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),t("polyline",{points:"14 2 14 8 20 8"}),t("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),t("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),t("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!y&&t(qp,{recentSimulations:o}),y&&l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[t("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[t("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),t("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"})]})}),y&&l("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[N&&t("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:l("div",{className:"flex items-center gap-3",children:[t("span",{className:"text-[32px] leading-none",children:t(Ue,{type:"visual"})}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",N.name]}),t("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:N.filePath})]})]})}),I?l("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[t("span",{className:"text-lg",children:"✅"}),l("span",{children:["Complete (",E.length," scenario",E.length!==1?"s":"",")"]})]}):C?l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[t(Ze,{size:18,className:"animate-spin shrink-0"}),t("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:C,children:C}),i&&t("button",{onClick:()=>w(!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"})]}):h.state!=="idle"?l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[t(Ze,{size:18,className:"animate-spin shrink-0"}),t("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[t(Ze,{size:18,className:"animate-spin shrink-0"}),t("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),E.length>0&&t("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:E.slice(0,8).map((_,S)=>{var W,Q,q;const F=(W=N==null?void 0:N.analyses)==null?void 0:W[0],O=Yr(_,F==null?void 0:F.status,void 0,y||void 0,void 0),H=(q=(Q=_.metadata)==null?void 0:Q.screenshotPaths)==null?void 0:q[0],ae=O.isCaptured,V=O.status==="capturing"||O.status==="starting",Y=O.hasError;return ae?t(oe,{to:`/entity/${y}`,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:t(De,{screenshotPath:H,alt:_.name,title:_.name,className:"max-w-full max-h-full object-contain object-center"})},S):Y?t("div",{className:"w-20 h-15 border-2 border-solid border-red-300 rounded bg-red-50 flex flex-col items-center justify-center text-lg",title:O.errorMessage||"Capture error",children:t("span",{className:"text-red-500",children:"⚠️"})},S):t("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:`${V?"Capturing":"Pending"} ${_.name}...`,children:t("span",{className:V?"animate-pulse":"text-gray-400",children:V?"⋯":"⏹️"})},S)})})]})]})]}),b&&i&&t(dt,{projectSlug:i,onClose:()=>w(!1)})]})})}),Kp=Object.freeze(Object.defineProperty({__proto__:null,default:Qp,loader:Vp,meta:Gp},Symbol.toStringTag,{value:"Module"}));function Es(e){const r={name:"root",path:"",memories:[],children:new Map};for(const n of e){const a=n.filePath.split("/");a.pop();let o=r,s="";for(const i of a)s=s?`${s}/${i}`:i,o.children.has(i)||o.children.set(i,{name:i,path:s,memories:[],children:new Map}),o=o.children.get(i);a.length===0?r.memories.push(n):o.memories.push(n)}return r}function As(e){let r=e.memories.length;for(const n of e.children.values())r+=As(n);return r}function Zp(e,r){var a;const n=e.match(/^#+ (.+)$/m);return n?n[1]:((a=r.split("/").pop())==null?void 0:a.replace(".md",""))||r}function Ut(e){return Math.round(e/3.5)}const Xp={architecture:"text-[#080096]",testing:"bg-green-100 text-green-800",faq:"text-[#080096]"},ks={architecture:"Architecture",testing:"Testing",faq:"FAQ"};function ef(e){switch(e){case"architecture":return"";case"testing":return"bg-green-100";case"faq":return"";default:return""}}function tf(e){return e==="faq"?{backgroundColor:"#D4D4FF"}:e==="architecture"?{backgroundColor:"#DBE9FF"}:{}}function rf(e){return e==="faq"?{backgroundColor:"#E7E7FC"}:e==="architecture"?{backgroundColor:"#DBE9FF"}:{}}function nf(e){switch(e){case"architecture":return"#3B82F6";case"testing":return"#10B981";case"faq":return"#080096";default:return"#080096"}}function af({category:e,size:r="sm"}){const n=r==="sm"?{width:11,height:11}:{width:20,height:20},a=r==="sm"?{width:8,height:11}:{width:13,height:20};switch(e){case"architecture":return l("svg",{width:n.width,height:n.height,viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"24",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"24",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"24",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"18",y:"6",width:"3",height:"3",transform:"rotate(90 18 6)",fill:"#080096"}),t("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#080096"}),t("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(90 3 6)",fill:"#080096"}),t("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(90 3 24)",fill:"#080096"}),t("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(90 21 6)",fill:"#080096"}),t("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#080096"}),t("rect",{x:"6",y:"6",width:"3",height:"3",transform:"rotate(90 6 6)",fill:"#080096"}),t("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#080096"}),t("rect",{x:"24",y:"6",width:"3",height:"3",transform:"rotate(90 24 6)",fill:"#080096"}),t("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#080096"}),t("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#080096"}),t("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#080096"}),t("rect",{x:"27",y:"6",width:"3",height:"3",transform:"rotate(90 27 6)",fill:"#080096"}),t("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(90 27 24)",fill:"#080096"}),t("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#080096"}),t("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#080096"}),t("rect",{x:"19",y:"3",width:"3",height:"3",transform:"rotate(90 19 3)",fill:"#080096"}),t("rect",{x:"11",y:"3",width:"3",height:"3",transform:"rotate(90 11 3)",fill:"#080096"})]});case"testing":return l("svg",{width:n.width,height:n.height,viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"24",y:"24",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"21",y:"21",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"18",y:"18",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"15",y:"15",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"12",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"9",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"21",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"18",y:"12",width:"3",height:"3",transform:"rotate(90 18 12)",fill:"#15803d"}),t("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#15803d"}),t("rect",{x:"21",y:"12",width:"3",height:"3",transform:"rotate(90 21 12)",fill:"#15803d"}),t("rect",{x:"6",y:"12",width:"3",height:"3",transform:"rotate(90 6 12)",fill:"#15803d"}),t("rect",{x:"24",y:"12",width:"3",height:"3",transform:"rotate(90 24 12)",fill:"#15803d"}),t("rect",{x:"9",y:"12",width:"3",height:"3",transform:"rotate(90 9 12)",fill:"#15803d"}),t("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#15803d"}),t("rect",{x:"12",y:"12",width:"3",height:"3",transform:"rotate(90 12 12)",fill:"#15803d"}),t("rect",{x:"12",y:"15",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"9",y:"9",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"6",y:"6",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"3",y:"3",width:"3",height:"3",fill:"#15803d"}),t("rect",{width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(90 3 24)",fill:"#15803d"}),t("rect",{x:"6",y:"21",width:"3",height:"3",transform:"rotate(90 6 21)",fill:"#15803d"}),t("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#15803d"}),t("rect",{x:"12",y:"15",width:"3",height:"3",transform:"rotate(90 12 15)",fill:"#15803d"}),t("rect",{x:"18",y:"9",width:"3",height:"3",transform:"rotate(90 18 9)",fill:"#15803d"}),t("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(90 21 6)",fill:"#15803d"}),t("rect",{x:"24",y:"3",width:"3",height:"3",transform:"rotate(90 24 3)",fill:"#15803d"}),t("rect",{x:"27",width:"3",height:"3",transform:"rotate(90 27 0)",fill:"#15803d"})]});case"faq":default:return l("svg",{width:a.width,height:a.height,viewBox:"0 0 18 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"6",y:"24",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"6",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"9",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"15",y:"9",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"9",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"15",y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"3",width:"3",height:"3",transform:"rotate(-90 12 3)",fill:"#080096"}),t("rect",{x:"15",y:"3",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(-90 9 3)",fill:"#080096"}),t("rect",{y:"3",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"6",y:"3",width:"3",height:"3",transform:"rotate(-90 6 3)",fill:"#080096"}),t("rect",{x:"3",y:"3",width:"3",height:"3",transform:"rotate(-90 3 3)",fill:"#080096"})]})}}function of({content:e,className:r}){const n=e.trim().replace(/^#+ .+$/m,"").trim();return t(Xi,{remarkPlugins:[el],components:{h1:({children:a})=>t("h1",{className:"text-lg font-bold text-gray-900 mb-3 mt-6 first:mt-0 pb-1 border-b border-gray-200",children:a}),h2:({children:a})=>t("h2",{className:"text-base font-semibold text-gray-900 mb-2 mt-5 first:mt-0",children:a}),h3:({children:a})=>t("h3",{className:"text-sm font-semibold text-gray-800 mb-2 mt-4 first:mt-0",children:a}),p:({children:a})=>t("p",{className:"text-sm text-gray-700 mb-3 leading-relaxed",children:a}),ul:({children:a})=>t("ul",{className:"list-disc ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:a}),ol:({children:a})=>t("ol",{className:"list-decimal ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:a}),li:({children:a})=>t("li",{className:"leading-relaxed",children:a}),code:({children:a,className:o})=>(o==null?void 0:o.includes("language-"))?t("pre",{className:"bg-gray-100 rounded p-3 text-xs font-mono overflow-x-auto mb-3",children:t("code",{children:a})}):t("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono text-gray-800",children:a}),pre:({children:a})=>t(ce,{children:a}),strong:({children:a})=>t("strong",{className:"font-semibold text-gray-900",children:a}),blockquote:({children:a})=>t("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic text-gray-600 mb-3",children:a}),table:({children:a})=>t("div",{className:"overflow-x-auto mb-3",children:t("table",{className:"min-w-full text-sm border-collapse border border-gray-200",children:a})}),thead:({children:a})=>t("thead",{className:"bg-gray-50",children:a}),th:({children:a})=>t("th",{className:"border border-gray-200 px-3 py-2 text-left font-semibold text-gray-900",children:a}),td:({children:a})=>t("td",{className:"border border-gray-200 px-3 py-2 text-gray-700",children:a}),a:({children:a,href:o})=>t("a",{href:o,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:a})},children:n})}function sf(e){const r=new Date(e),a=new Date().getTime()-r.getTime(),o=Math.floor(a/(1e3*60*60*24));return o===0?"Today":o===1?"Yesterday":o<7?`${o} days ago`:r.toLocaleDateString()}function Qn({rule:e,onEdit:r,onDelete:n,isReviewed:a,onToggleReviewed:o,changeType:s,isUncommitted:i,changeDate:c,diff:d,isFadingOut:h,showLeftBorder:u}){const[m,p]=P(!1),[f,y]=P(!1),g=e.frontmatter.category||"faq",b=ne(()=>Zp(e.body,e.filePath),[e.body,e.filePath]),w=Ut(e.body.length),x=u?nf(g):void 0,v=m?"#3e3e3e":i?"#d97706":"#c7c7c7",C=`rounded-lg border overflow-hidden transition-all ease-in-out ${i?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,k={...x&&{borderLeft:`2px solid ${x}`},...h&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return l("div",{className:C,style:k,children:[t("div",{className:`p-4 cursor-pointer ${i?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>p(!m),children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex items-center gap-3",children:[t("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:m?"rotate(90deg)":"none",transition:"transform 0.2s"},children:t("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:v})})}),t("div",{className:`w-10 h-10 rounded-lg ${ef(g)} flex items-center justify-center flex-shrink-0`,style:tf(g),children:t(af,{category:g})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[t("h3",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:i?"#78350f":"#000"},children:b}),t("span",{className:`px-2 py-0.5 rounded font-medium uppercase tracking-wider ${Xp[g]}`,style:{fontSize:"10px",...rf(g)},children:ks[g]}),s&&t("span",{className:`px-2 py-0.5 rounded uppercase font-medium tracking-wider ${s==="deleted"?"bg-red-100 text-red-700":""}`,style:{fontSize:"10px",...s==="added"&&{backgroundColor:"#CBF3FA",color:"#005C75"},...s==="modified"&&{backgroundColor:"#FFE8C1",color:"#C67E06"}},children:s}),i&&t("span",{className:"px-2 py-0.5 bg-amber-200 text-amber-800 rounded font-medium uppercase tracking-wider",style:{fontSize:"10px"},children:"Uncommitted"}),l("span",{className:"text-xs text-gray-400",children:["~",w.toLocaleString()," tokens"]})]}),t("div",{className:"flex items-center gap-2 text-xs text-gray-500 flex-wrap",children:e.frontmatter.paths&&e.frontmatter.paths.length>0&&l(ce,{children:[e.frontmatter.paths.slice(0,2).map((N,E)=>t("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:N},E)),e.frontmatter.paths.length>2&&l("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-2," more"]})]})})]})]}),l("div",{className:"flex items-center gap-3 flex-shrink-0",children:[c?t("span",{className:"text-xs text-gray-400",children:sf(c)}):e.frontmatter.timestamp&&l("span",{className:"text-xs text-gray-400",children:["Updated"," ",new Date(e.frontmatter.timestamp).toLocaleDateString()]}),o&&t("button",{onClick:N=>{N.stopPropagation(),o(e.filePath,e.lastModified,a??!1)},className:"w-6 h-6 rounded-full border-2 flex items-center justify-center cursor-pointer transition-colors",style:{borderColor:a?"#22c55e":"#d1d5db",backgroundColor:a?"#22c55e":"transparent"},title:a?"Mark as unreviewed":"Mark as reviewed",children:a&&t("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t("path",{d:"M11.5 4L5.5 10L2.5 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}),m&&l("div",{className:`border-t ${i?"border-amber-200":"border-gray-100"}`,children:[l("div",{className:`px-4 py-3 flex items-center justify-between ${i?"bg-amber-50":"bg-white"}`,children:[t("div",{className:"flex items-center gap-2",children:s==="modified"&&d&&l("button",{onClick:N=>{N.stopPropagation(),y(!f)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${f?i?"bg-amber-200 text-amber-900":"bg-gray-200 text-gray-900":i?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[t(mo,{className:"w-3 h-3"}),f?"Hide Diff":"Show Diff"]})}),s!=="deleted"&&l("div",{className:"flex items-center gap-2",children:[l("button",{onClick:N=>{N.stopPropagation(),r(e)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${i?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[t(vi,{className:"w-3 h-3"}),"Edit"]}),l("button",{onClick:N=>{N.stopPropagation(),n(e)},className:"flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer text-red-600 hover:text-red-800 hover:bg-red-100",children:[t(Ci,{className:"w-3 h-3"}),"Delete"]})]})]}),f&&d&&t("pre",{className:"mx-4 mb-4 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:d.split(`
|
|
246
|
+
`).map((N,E)=>{let A="";return N.startsWith("+")&&!N.startsWith("+++")?A="text-green-400":N.startsWith("-")&&!N.startsWith("---")?A="text-red-400":N.startsWith("@@")&&(A="text-cyan-400"),t("div",{className:A,children:N},E)})}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&l("div",{className:"mx-4 mb-3",children:[t("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Applies to paths:"}),t("div",{className:"flex flex-wrap gap-1.5",children:e.frontmatter.paths.map((N,E)=>t("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:N},E))})]}),!f&&t("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[500px] overflow-auto bg-white border-gray-200",children:t(of,{content:e.body})})]})]})}function lf(){return`---
|
|
247
|
+
paths:
|
|
248
|
+
- '**/*.ts'
|
|
249
|
+
category: faq
|
|
250
|
+
timestamp: ${new Date().toISOString().split(".")[0]+"Z"}
|
|
251
|
+
---
|
|
252
|
+
|
|
253
|
+
## Title
|
|
254
|
+
|
|
255
|
+
Description here.
|
|
256
|
+
|
|
257
|
+
**Learned:** ${new Date().toISOString().split("T")[0]} from [context]
|
|
258
|
+
`}function so({rule:e,onSave:r,onCancel:n}){const[a,o]=P((e==null?void 0:e.filePath)||""),[s,i]=P((e==null?void 0:e.content)||lf()),[c,d]=P(!!e),h=!e;return l("div",{className:"p-6",children:[l("div",{className:"flex items-center justify-between mb-4",children:[t("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),t("button",{onClick:n,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:t(po,{className:"w-5 h-5"})})]}),h&&l("div",{className:"mb-6",children:[t("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:l("div",{className:"flex items-start gap-3",children:[t(mo,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),l("div",{children:[t("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),t("p",{className:"text-sm text-[#0369a1] mb-2",children:"Run this command in Claude Code to create a properly formatted rule with the right file location and paths:"}),t("code",{className:"block bg-white px-3 py-2 rounded border border-[#bae6fd] font-mono text-sm text-[#0c4a6e]",children:"/codeyam:new-rule"})]})]})}),l("button",{onClick:()=>d(!c),className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer",children:[t("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:c?"rotate(90deg)":"none",transition:"transform 0.2s"},children:t("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:c?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(c||!h)&&l("div",{className:"space-y-4",children:[l("div",{children:[t("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),l("div",{className:"relative",children:[t("input",{type:"text",value:a,onChange:u=>o(u.target.value),placeholder:"e.g., src/webserver/architecture.md",className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm",disabled:!!e}),t("button",{onClick:()=>{navigator.clipboard.writeText(a)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy path",children:t(Sn,{className:"w-4 h-4"})})]})]}),l("div",{children:[t("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),t("textarea",{value:s,onChange:u=>i(u.target.value),rows:20,className:"w-full px-3 py-2 border border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm bg-gray-900 text-gray-100 [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-track]:bg-gray-800 [&::-webkit-scrollbar-thumb]:bg-gray-600 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:hover:bg-gray-500 [&::-webkit-resizer]:bg-gray-700"})]}),l("div",{className:"flex justify-end gap-2",children:[t("button",{onClick:n,className:"px-4 py-2 text-[#001f3f] hover:text-[#001530] rounded-md cursor-pointer font-mono uppercase text-xs font-semibold",children:"Cancel"}),t("button",{onClick:()=>r(a,s),disabled:!a.trim()||!s.trim(),className:"px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer font-mono uppercase text-xs font-semibold",children:"Save"})]})]})]})}function cf({memories:e,selectedPath:r,onSelectPath:n,expandedFolders:a,onToggleFolder:o}){const s=ne(()=>Es(e),[e]),i=(h,u,m)=>{if(h.target.closest(".chevron-toggle")){m&&o(u||"root");return}const f=u||null;n(r===f?null:f),m&&!a.has(u||"root")&&o(u||"root")},c=h=>{n(r===h?null:h)},d=(h,u=0)=>{const m=a.has(h.path||"root"),p=As(h),f=h.children.size>0,y=h.name==="root"?"(root)":h.name,g=h.memories.length>0||f,b=h.path||"",w=r===b||r===null&&b==="";return l("div",{children:[l("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${w?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${u*12+8}px`},onClick:x=>i(x,h.path,g),children:[g&&t("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:x=>{x.stopPropagation(),o(h.path||"root")},children:t(An,{className:`w-3 h-3 text-gray-500 transition-transform ${m?"rotate-90":""}`})}),!g&&t("div",{className:"w-3"}),t(fo,{className:"w-3.5 h-3.5 text-[#005C75]"}),t("span",{className:`text-xs font-mono font-semibold ${w?"text-[#005C75]":""}`,style:{color:"#005C75"},children:y}),l("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[p," rules"]})]}),m&&l("div",{className:"relative",children:[(h.memories.length>0||f)&&t("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${u*12+8+6}px`}}),h.memories.length>0&&t("div",{style:{paddingLeft:`${(u+1)*12+8}px`},children:h.memories.map(x=>{var C;const v=r===x.filePath;return t("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${v?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>c(x.filePath),children:t("span",{className:"text-xs",children:(C=x.filePath.split("/").pop())==null?void 0:C.replace(".md","")})},x.filePath)})}),f&&t("div",{children:Array.from(h.children.values()).sort((x,v)=>x.name.localeCompare(v.name)).map(x=>d(x,u+1))})]})]},h.path||"root")};return t("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:d(s)})}function df({memories:e,onEdit:r,onDelete:n,expandedFolders:a,onToggleFolder:o,reviewedStatus:s,onMarkReviewed:i,onMarkUnreviewed:c}){const[d,h]=P({});te(()=>{h({})},[s]);const u=ne(()=>({...s,...d}),[s,d]),m=ne(()=>Es(e),[e]),p=(y,g,b)=>{h(w=>({...w,[y]:!b})),b?c(y):i(y,g)},f=(y,g=0)=>{const b=a.has(y.path||"root"),w=y.children.size>0,x=y.name==="root"?"root":y.name,v=y.memories.length>0||w;return l("div",{children:[l("div",{className:"flex items-center gap-2 py-2 cursor-pointer hover:bg-gray-50 rounded px-2 mb-2",style:{backgroundColor:"rgba(224, 233, 236, 0.5)"},onClick:()=>v&&o(y.path||"root"),children:[v&&t(An,{className:`w-4 h-4 text-gray-500 transition-transform ${b?"rotate-90":""}`}),!v&&t("div",{className:"w-4"}),t(fo,{className:"w-4 h-4 text-[#005C75]"}),t("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:x})]}),b&&l("div",{className:"ml-10 space-y-4 relative",children:[(y.memories.length>0||w)&&t("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:"-24px"}}),y.memories.length>0&&t("div",{className:"space-y-2",children:y.memories.map(C=>t(Qn,{rule:C,onEdit:r,onDelete:n,isReviewed:u[C.filePath]??!1,onToggleReviewed:p},C.filePath))}),w&&t("div",{className:"space-y-4",children:Array.from(y.children.values()).sort((C,k)=>C.name.localeCompare(k.name)).map(C=>f(C,g+1))})]})]},y.path||"root")};return t("div",{children:f(m)})}function uf({changes:e,memories:r,onEditRule:n,onDeleteRule:a,reviewedStatus:o,onMarkReviewed:s,onMarkUnreviewed:i}){const[c,d]=P("unreviewed"),[h,u]=P({}),[m,p]=P(new Set);te(()=>{u({}),p(new Set)},[o]);const f=ne(()=>({...o,...h}),[o,h]),y=(k,N,E)=>{u(A=>({...A,[k]:!E})),p(E?A=>{const I=new Set(A);return I.delete(k),I}:A=>new Set(A).add(k)),E?i(k):s(k,N)},g=ne(()=>{const k=new Map;for(const N of e){const E=N.commitHash==="uncommitted";for(const A of N.files){if(k.has(A.filePath))continue;const I=r.find(j=>j.filePath===A.filePath);I&&k.set(A.filePath,{rule:I,changeType:A.changeType,date:N.date,isUncommitted:E,diff:A.diff,isReviewed:f[A.filePath]??!1})}}return Array.from(k.values()).sort((N,E)=>N.isUncommitted&&!E.isUncommitted?-1:!N.isUncommitted&&E.isUncommitted?1:new Date(E.date).getTime()-new Date(N.date).getTime())},[e,r,f]);ne(()=>g.filter(k=>!k.isReviewed).length,[g]);const b=ne(()=>c==="unreviewed"?g.filter(k=>!k.isReviewed||m.has(k.rule.filePath)):g,[g,c,m]),[w,x]=P(!1),v=3,C=w?b:b.slice(0,v);return g.length===0?null:l("div",{className:"mb-8",children:[l("div",{className:"flex items-center gap-6 border-b border-[#e1e1e1]",children:[t("h2",{className:"text-xl leading-6 py-3 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"Recently Changed Rules"}),t("button",{onClick:()=>d("unreviewed"),className:`px-0 py-3 border-b-2 -mb-px transition-colors bg-transparent cursor-pointer ${c==="unreviewed"?"border-[#232323] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:t("span",{className:"text-base leading-6",style:{fontFamily:"Sora",fontWeight:c==="unreviewed"?600:400},children:"Unreviewed"})}),t("button",{onClick:()=>d("all"),className:`px-0 py-3 border-b-2 -mb-px transition-colors bg-transparent cursor-pointer ${c==="all"?"border-[#232323] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:t("span",{className:"text-base leading-6",style:{fontFamily:"Sora",fontWeight:c==="all"?600:400},children:"All"})})]}),l("div",{className:"flex items-center justify-between mt-4 mb-3",children:[l("div",{className:"flex items-center gap-2",children:[l("span",{className:"text-xs text-gray-500 font-mono uppercase tracking-wider",children:["Showing"," ",Math.min(C.length,b.length)," ","of ",b.length,"."]}),b.length>v&&t("button",{onClick:()=>x(!w),className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase tracking-wider font-semibold",children:w?"Show Less":"View All"})]}),t("span",{className:"text-xs text-gray-500 font-mono uppercase tracking-wider",children:"Reviewed"})]}),t("div",{className:"space-y-2",children:C.map(k=>{const{rule:N,changeType:E,date:A,isUncommitted:I,diff:j}=k,R=m.has(N.filePath);return t(Qn,{rule:N,onEdit:n,onDelete:a,isReviewed:k.isReviewed,onToggleReviewed:y,changeType:E,isUncommitted:I,changeDate:A,diff:j,isFadingOut:R,showLeftBorder:!0},N.filePath)})})]})}function hf({onEditRule:e,onDeleteRule:r,refreshKey:n,reviewedStatus:a,onMarkReviewed:o,onMarkUnreviewed:s}){const[i,c]=P(""),[d,h]=P(null),[u,m]=P(!1),[p,f]=P(null),[y,g]=P(0),[b,w]=P(!1),[x,v]=P("unreviewed"),[C,k]=P({});te(()=>{k({})},[a]);const N=ne(()=>({...a,...C}),[a,C]),E=(F,O,H)=>{k(ae=>({...ae,[F]:!H})),H?s(F):o(F,O)},[A,I]=P({topPaths:[],totalFilesWithCoverage:0}),[j,R]=P([]),[M,T]=P(!0);te(()=>{(async()=>{try{const H=await(await fetch("/api/memory?action=source-files")).json();R(H.files||[])}catch(O){console.error("Failed to load source files:",O)}})()},[]),te(()=>{(async()=>{T(!0);try{const H=await(await fetch("/api/memory?action=audit")).json();I({topPaths:H.topPaths||[],totalFilesWithCoverage:H.totalFilesWithCoverage||0})}catch(O){console.error("Failed to load audit data:",O)}finally{T(!1)}})()},[n]),te(()=>{d&&n>0&&(async()=>{w(!0);try{const H=await(await fetch(`/api/memory?action=rules-for-path&path=${encodeURIComponent(d)}`)).json();f(H.rules||[]),g(H.totalTextLength||0)}catch{f([]),g(0)}finally{w(!1)}})()},[n,d]);const $=ne(()=>{if(!i.trim())return[];const F=i.toLowerCase();return j.filter(O=>O.toLowerCase().includes(F)).slice(0,10)},[i,j]),z=ne(()=>x==="all"?A.topPaths:A.topPaths.filter(F=>F.matchingRules.some(O=>!N[O.filePath])),[A.topPaths,x,N]),G=ne(()=>p?x==="all"?p:p.filter(F=>!N[F.filePath]):null,[p,x,N]),U=ne(()=>G?G.reduce((F,O)=>F+O.body.length,0):0,[G]);ne(()=>A.topPaths.filter(F=>F.matchingRules.some(O=>!N[O.filePath])).length,[A.topPaths,N]);const B=async F=>{w(!0);try{const H=await(await fetch(`/api/memory?action=rules-for-path&path=${encodeURIComponent(F)}`)).json();f(H.rules||[]),g(H.totalTextLength||0)}catch{f([]),g(0)}finally{w(!1)}},D=F=>{h(F),c(F),m(!1),B(F)},L=()=>{h(null),c(""),f(null),g(0)};return l("div",{className:"mb-6",children:[l("div",{className:"flex items-center gap-6 border-b border-[#e1e1e1] mb-4",children:[t("h2",{className:"text-xl leading-6 py-3 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"Rules Audit"}),t("button",{onClick:()=>v("unreviewed"),className:`px-0 py-3 border-b-2 -mb-px transition-colors bg-transparent cursor-pointer ${x==="unreviewed"?"border-[#232323] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:t("span",{className:"text-base leading-6",style:{fontFamily:"Sora",fontWeight:x==="unreviewed"?600:400},children:"Unreviewed"})}),t("button",{onClick:()=>v("all"),className:`px-0 py-3 border-b-2 -mb-px transition-colors bg-transparent cursor-pointer ${x==="all"?"border-[#232323] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:t("span",{className:"text-base leading-6",style:{fontFamily:"Sora",fontWeight:x==="all"?600:400},children:"All"})}),t("div",{className:"flex-1"}),l("div",{className:"relative max-w-md w-80",children:[t(En,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),t("input",{type:"text",value:i,onChange:F=>{const O=F.target.value;c(O),m(O.length>0),d&&O!==d&&(h(null),f(null))},onFocus:()=>m(i.length>0),onKeyDown:F=>{F.key==="Enter"&&$.length>0&&D($[0])},placeholder:"Search for a file path...",className:"w-full pl-10 pr-10 py-2 border border-gray-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-xs"}),d&&t("button",{onClick:L,className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 cursor-pointer",children:t(po,{className:"w-4 h-4"})}),u&&$.length>0&&!d&&t("div",{className:"absolute z-10 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-y-auto",children:$.map((F,O)=>l("button",{onClick:()=>D(F),className:"w-full px-4 py-2 text-left text-sm font-mono hover:bg-gray-100 flex items-center gap-2 cursor-pointer",children:[t(ho,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}),t("span",{className:"truncate",children:F})]},O))})]})]}),t("p",{className:"text-sm text-gray-500 mb-4",children:x==="unreviewed"?"View files with unreviewed rules (rules that may be outdated based on recent code changes)":"View all rules that apply to any folder or file in this repo (displaying the files that have the most rules — by total token count — applied to them)"}),b&&t("div",{className:"bg-white rounded-lg border border-gray-200 p-6 text-center",children:t("div",{className:"text-gray-500",children:"Loading rules..."})}),d&&G!==null&&!b&&l("div",{children:[l("div",{className:"text-sm text-gray-600 mb-3",style:{fontFamily:"Sora"},children:["Showing ",x==="unreviewed"?"unreviewed ":"","rules for:"]}),l("div",{className:"flex items-stretch gap-3 mb-4",children:[t("button",{onClick:L,className:"flex-shrink-0 px-3 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors flex items-center justify-center","aria-label":"Back to all files",children:t(Ni,{className:"w-5 h-5 text-gray-600"})}),l("div",{className:"flex-1 bg-white rounded-lg border p-4",style:{borderColor:"#CBF3FA"},children:[l("div",{className:"flex items-center gap-3 mb-2",children:[t("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),t("div",{className:"font-mono text-sm font-semibold text-gray-900 break-all",children:d})]}),l("div",{className:"flex items-center gap-3",children:[l("div",{className:"flex items-center gap-1.5",children:[l("span",{className:"px-2 py-0.5 bg-amber-100 text-amber-800 rounded uppercase font-medium tracking-wider",style:{fontSize:"10px"},children:[(G==null?void 0:G.length)??0," UNREVIEWED"]}),l("span",{className:"px-2 py-0.5 bg-amber-100 text-amber-800 rounded uppercase font-medium tracking-wider",style:{fontSize:"10px"},children:["~",Ut(U).toLocaleString()," ","TOKENS"]})]}),t("span",{className:"text-gray-300",children:"|"}),l("div",{className:"flex items-center gap-1.5",children:[l("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-700 rounded uppercase font-medium tracking-wider",style:{fontSize:"10px"},children:[(p==null?void 0:p.length)??0," TOTAL"]}),l("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-700 rounded uppercase font-medium tracking-wider",style:{fontSize:"10px"},children:["~",Ut(y).toLocaleString()," ","TOKENS"]})]})]})]})]}),G.length===0?t("div",{className:"bg-white rounded-lg border border-gray-200 p-6 text-center text-gray-500 text-sm",children:x==="unreviewed"?"No unreviewed rules match this path":"No rules match this path"}):t("div",{className:"space-y-3",children:G.map(F=>t(Qn,{rule:F,onEdit:e,onDelete:r,isReviewed:N[F.filePath]??!1,onToggleReviewed:E},F.filePath))})]}),!d&&!b&&!M&&z.length>0&&l("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden",children:[l("div",{className:"px-4 py-3 bg-gray-50 border-b border-gray-200",children:[l("div",{className:"font-medium text-gray-900 text-sm",children:["File paths that consume the most"," ",x==="unreviewed"?"unreviewed ":"","rules (by total tokens)"]}),t("div",{className:"text-xs text-gray-500 mt-1",children:x==="unreviewed"?`${z.length} file${z.length!==1?"s":""} with unreviewed rules`:`${A.totalFilesWithCoverage} file${A.totalFilesWithCoverage!==1?"s":""} with rule coverage`})]}),t("div",{className:"divide-y divide-gray-100",children:z.slice(0,3).map((F,O)=>{const H=F.matchingRules.filter(W=>!N[W.filePath]),ae=H.reduce((W,Q)=>W+Q.bodyLength,0),V=F.matchingRules,Y=F.totalTextLength;return t("button",{onClick:()=>D(F.filePath),className:"w-full px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex items-center gap-2",children:[l("span",{className:"text-gray-400 font-medium w-5 text-sm",children:[O+1,"."]}),t("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),l("div",{children:[t("div",{className:"font-mono text-xs text-gray-900",children:F.filePath}),l("div",{className:"flex items-center gap-2 mt-1",children:[l("span",{className:"px-2 py-0.5 bg-amber-100 text-amber-800 text-[11px] rounded uppercase font-medium",children:[H.length," unreviewed"]}),l("span",{className:"px-2 py-0.5 bg-amber-100 text-amber-800 text-[11px] rounded uppercase font-medium",children:["~",Ut(ae).toLocaleString()," ","tokens"]}),t("span",{className:"text-gray-300 text-xs",children:"|"}),l("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-700 text-[11px] rounded uppercase font-medium",children:[V.length," total"]}),l("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-700 text-[11px] rounded uppercase font-medium",children:["~",Ut(Y).toLocaleString()," ","tokens"]})]})]})]}),t(An,{className:"w-4 h-4 text-gray-400 mt-1"})]})},O)})})]}),!d&&M&&t("div",{className:"bg-white rounded-lg border border-gray-200 p-6",children:l("div",{className:"animate-pulse space-y-3",children:[t("div",{className:"h-4 bg-gray-200 rounded w-3/4"}),t("div",{className:"h-3 bg-gray-100 rounded w-1/2"}),t("div",{className:"h-4 bg-gray-200 rounded w-2/3 mt-4"}),t("div",{className:"h-3 bg-gray-100 rounded w-1/3"})]})}),!d&&!b&&!M&&z.length===0&&t("div",{className:"bg-white rounded-lg border border-gray-200 p-6 text-center text-gray-500 text-sm",children:x==="unreviewed"?"No files have unreviewed rules":"No files have rule coverage yet"})]})}const mf=()=>[{title:"CodeYam - Memory"},{name:"description",content:"Manage Claude Memory documentation"}];async function pf({request:e}){try{const[r,n]=await Promise.all([fetch(new URL("/api/memory",e.url).toString()),fetch(new URL("/api/memory?action=recent-changes",e.url).toString())]),a=await r.json(),o=await n.json();return a.error?J({memories:[],recentChanges:[],reviewedStatus:{},error:a.error}):J({memories:a.memories||[],recentChanges:o.changes||[],reviewedStatus:o.reviewedStatus||{},error:null})}catch(r){return console.error("Failed to load memories:",r),J({memories:[],recentChanges:[],reviewedStatus:{},error:"Failed to load memories"})}}const ff=Oe(function(){const{memories:r,recentChanges:n,reviewedStatus:a,error:o}=We(),s=Ae(),i=rt(),[c,d]=P(null),[h,u]=P(""),[m,p]=P(null),[f,y]=P(new Set(["root"])),[g,b]=P(null),[w,x]=P(!1),[v,C]=P(null),[k,N]=P(0),E=D=>{y(L=>{const _=new Set(L);return _.has(D)?_.delete(D):_.add(D),_})};mt({source:"memory-page"});const A=Ee(s.state);te(()=>{const D=A.current==="loading"||A.current==="submitting",L=s.state==="idle";D&&L&&s.data&&(i.revalidate(),b(null),x(!1),N(_=>_+1)),A.current=s.state},[s.state,s.data,i]);const I=(D,L)=>{s.submit({action:"mark-reviewed",filePath:D,lastModified:L},{method:"POST",action:"/api/memory",encType:"application/json"})},j=D=>{s.submit({action:"mark-unreviewed",filePath:D},{method:"POST",action:"/api/memory",encType:"application/json"})},R=ne(()=>{let D=r;if(c&&(D=D.filter(L=>(L.frontmatter.category||"faq")===c)),h.trim()){const L=h.toLowerCase();D=D.filter(_=>{var F;return(((F=_.filePath.split("/").pop())==null?void 0:F.replace(".md",""))||"").toLowerCase().includes(L)||_.body.toLowerCase().includes(L)})}return D},[r,c,h]),M=ne(()=>m?R.some(L=>L.filePath===m)?R.filter(L=>L.filePath===m):R.filter(L=>L.filePath.startsWith(m+"/")||L.filePath===m):R,[R,m]),T=(D,L)=>{const _=g?"update":"create";s.submit({action:_,filePath:D,content:L},{method:"POST",action:"/api/memory",encType:"application/json"})},$=D=>{s.submit({action:"delete",filePath:D.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),C(null)},z=ne(()=>{const D={architecture:0,testing:0,faq:0};for(const L of r){const _=L.frontmatter.category||"faq";D[_]++}return D},[r]),G=ne(()=>{const D=new Set(["root"]);for(const L of R){const _=L.filePath.split("/");_.pop();let S="";for(const F of _)S=S?`${S}/${F}`:F,D.add(S)}return D},[R]),U=G.size===f.size&&[...G].every(D=>f.has(D)),B=()=>{y(U?new Set(["root"]):new Set(G))};return o?t("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[t("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),t("p",{className:"text-base text-gray-500",children:o})]})}):t("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[l("div",{className:"flex items-center justify-between mb-6",children:[l("div",{children:[l("div",{className:"flex items-center gap-3 mb-2",children:[t(gf,{}),t("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),t("p",{className:"text-[15px] text-gray-500",children:"Documentation that helps Claude understand your codebase patterns and conventions."})]}),l("button",{onClick:()=>x(!0),className:"flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer font-mono uppercase text-xs font-semibold",children:[t(ka,{className:"w-4 h-4"}),"New Rule"]})]}),l("div",{className:"grid grid-cols-4 gap-4",children:[t(mr,{category:null,count:r.length,isSelected:c===null,onClick:()=>d(null)}),t(mr,{category:"architecture",count:z.architecture,isSelected:c==="architecture",onClick:()=>d(c==="architecture"?null:"architecture")}),t(mr,{category:"testing",count:z.testing,isSelected:c==="testing",onClick:()=>d(c==="testing"?null:"testing")}),t(mr,{category:"faq",count:z.faq,isSelected:c==="faq",onClick:()=>d(c==="faq"?null:"faq")})]})]}),w&&t("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:()=>x(!1),children:t("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:D=>D.stopPropagation(),children:t(so,{rule:null,onSave:T,onCancel:()=>{x(!1)}})})}),g&&t("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:()=>b(null),children:t("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:D=>D.stopPropagation(),children:t(so,{rule:g,onSave:T,onCancel:()=>{b(null)}})})}),t(uf,{changes:n,memories:R,onEditRule:b,onDeleteRule:C,reviewedStatus:a,onMarkReviewed:I,onMarkUnreviewed:j}),t(hf,{onEditRule:b,onDeleteRule:C,refreshKey:k,reviewedStatus:a,onMarkReviewed:I,onMarkUnreviewed:j}),l("div",{className:"flex items-center justify-between mb-4",children:[t("h2",{className:"text-xl leading-6 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"All Rules"}),l("div",{className:"flex items-center gap-4",children:[l("div",{className:"relative",children:[l("select",{value:c||"all",onChange:D=>{const L=D.target.value;d(L==="all"?null:L)},className:"appearance-none bg-white border border-gray-200 rounded px-3 pr-8 text-sm h-9 cursor-pointer focus:outline-none focus:ring-2 focus:ring-[#005c75] hover:border-gray-300 transition-colors",children:[t("option",{value:"all",children:"All Types"}),t("option",{value:"architecture",children:"Architecture"}),t("option",{value:"testing",children:"Testing"}),t("option",{value:"faq",children:"FAQ"})]}),t(qt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 pointer-events-none"})]}),G.size>1&&t("button",{onClick:B,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:U?"Collapse All":"Expand All"})]})]}),l("div",{className:"flex gap-6",children:[t("div",{className:"w-80 flex-shrink-0",children:t(cf,{memories:R,selectedPath:m,onSelectPath:p,expandedFolders:f,onToggleFolder:E})}),t("div",{className:"flex-1 min-w-0",children:r.length===0?l("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[t(Si,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),t("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Rules Yet"}),l("p",{className:"text-gray-500 mb-4",children:["Run"," ",t("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam:power-memories"})," ","to generate initial memories for your codebase."]}),l("button",{onClick:()=>x(!0),className:"inline-flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer",children:[t(ka,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):l("div",{children:[(c||m)&&l("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:[t(Ei,{className:"w-4 h-4"}),c&&l(ce,{children:["Showing"," ",ks[c]," ","memories"]}),c&&m&&" in ",m&&t("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:m||"(root)"}),t("button",{onClick:()=>{d(null),p(null)},className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),t(df,{memories:M,onEdit:b,onDelete:C,expandedFolders:f,onToggleFolder:E,reviewedStatus:a,onMarkReviewed:I,onMarkUnreviewed:j})]})})]}),v&&t("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:l("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[t("h3",{className:"text-lg font-semibold mb-2",children:"Delete Memory?"}),l("p",{className:"text-gray-600 mb-4",children:["Are you sure you want to delete"," ",t("span",{className:"font-mono text-sm",children:v.filePath}),"? This cannot be undone."]}),l("div",{className:"flex justify-end gap-2",children:[t("button",{onClick:()=>C(null),className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),t("button",{onClick:()=>$(v),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})]})})});function gf(){return l("svg",{width:"24",height:"24",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#232323"}),t("rect",{x:"12",width:"3",height:"3",fill:"#232323"}),t("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#232323"}),t("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#232323"}),t("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#232323"}),t("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#232323"}),t("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#232323"}),t("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#232323"}),t("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#232323"}),t("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#232323"}),t("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#232323"}),t("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#232323"}),t("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#232323"}),t("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#232323"}),t("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#232323"}),t("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#232323"}),t("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#232323"}),t("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#232323"}),t("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#232323"}),t("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#232323"}),t("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#232323"}),t("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#232323"}),t("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#232323"}),t("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#232323"}),t("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#232323"}),t("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#232323"}),t("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#232323"}),t("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#232323"}),t("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#232323"}),t("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#232323"}),t("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#232323"}),t("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#232323"}),t("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#232323"}),t("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#232323"})]})}function mr({category:e,count:r,isSelected:n,onClick:a}){const o=yf(e);return t("div",{className:`rounded-lg p-4 cursor-pointer transition-colors ${n?`ring-1 ${o.ringColor}`:""}`,style:{backgroundColor:o.bgColor,border:"1px solid #EFEFEF"},onClick:a,children:l("div",{className:"flex items-start gap-3",children:[t("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:o.iconBgColor},children:o.icon}),l("div",{className:"flex-1",children:[t("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:o.textColor},children:r}),t("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:o.textColor},children:o.label})]})]})})}function yf(e){switch(e){case"architecture":return{bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#080096",ringColor:"ring-[#080096]",label:"Architecture",icon:t(bf,{})};case"testing":return{bgColor:"#EAFBEF",iconBgColor:void 0,textColor:void 0,ringColor:"ring-[#15803d]",label:"Testing",icon:t(wf,{})};case"faq":return{bgColor:"#E7E7FC",iconBgColor:"#D4D4FF",textColor:"#080096",ringColor:"ring-[#080096]",label:"FAQ",icon:t(vf,{})};default:return{bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75",ringColor:"ring-[#005C75]",label:"Total Rules",icon:t(xf,{})}}}function xf(){return l("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),t("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),t("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),t("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),t("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),t("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),t("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),t("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),t("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),t("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),t("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),t("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),t("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),t("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),t("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),t("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),t("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),t("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),t("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),t("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),t("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),t("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),t("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),t("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),t("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),t("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),t("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),t("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),t("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),t("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),t("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),t("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),t("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),t("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}function bf(){return l("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"24",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"24",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"24",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"18",y:"6",width:"3",height:"3",transform:"rotate(90 18 6)",fill:"#080096"}),t("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#080096"}),t("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(90 3 6)",fill:"#080096"}),t("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(90 3 24)",fill:"#080096"}),t("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(90 21 6)",fill:"#080096"}),t("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#080096"}),t("rect",{x:"6",y:"6",width:"3",height:"3",transform:"rotate(90 6 6)",fill:"#080096"}),t("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#080096"}),t("rect",{x:"24",y:"6",width:"3",height:"3",transform:"rotate(90 24 6)",fill:"#080096"}),t("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#080096"}),t("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#080096"}),t("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#080096"}),t("rect",{x:"27",y:"6",width:"3",height:"3",transform:"rotate(90 27 6)",fill:"#080096"}),t("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(90 27 24)",fill:"#080096"}),t("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#080096"}),t("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#080096"}),t("rect",{x:"19",y:"3",width:"3",height:"3",transform:"rotate(90 19 3)",fill:"#080096"}),t("rect",{x:"11",y:"3",width:"3",height:"3",transform:"rotate(90 11 3)",fill:"#080096"})]})}function wf(){return l("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"24",y:"24",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"21",y:"21",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"18",y:"18",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"15",y:"15",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"12",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"9",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"21",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"18",y:"12",width:"3",height:"3",transform:"rotate(90 18 12)",fill:"#15803d"}),t("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#15803d"}),t("rect",{x:"21",y:"12",width:"3",height:"3",transform:"rotate(90 21 12)",fill:"#15803d"}),t("rect",{x:"6",y:"12",width:"3",height:"3",transform:"rotate(90 6 12)",fill:"#15803d"}),t("rect",{x:"24",y:"12",width:"3",height:"3",transform:"rotate(90 24 12)",fill:"#15803d"}),t("rect",{x:"9",y:"12",width:"3",height:"3",transform:"rotate(90 9 12)",fill:"#15803d"}),t("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#15803d"}),t("rect",{x:"12",y:"12",width:"3",height:"3",transform:"rotate(90 12 12)",fill:"#15803d"}),t("rect",{x:"12",y:"15",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"9",y:"9",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"6",y:"6",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"3",y:"3",width:"3",height:"3",fill:"#15803d"}),t("rect",{width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(90 3 24)",fill:"#15803d"}),t("rect",{x:"6",y:"21",width:"3",height:"3",transform:"rotate(90 6 21)",fill:"#15803d"}),t("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#15803d"}),t("rect",{x:"12",y:"15",width:"3",height:"3",transform:"rotate(90 12 15)",fill:"#15803d"}),t("rect",{x:"18",y:"9",width:"3",height:"3",transform:"rotate(90 18 9)",fill:"#15803d"}),t("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(90 21 6)",fill:"#15803d"}),t("rect",{x:"24",y:"3",width:"3",height:"3",transform:"rotate(90 24 3)",fill:"#15803d"}),t("rect",{x:"27",width:"3",height:"3",transform:"rotate(90 27 0)",fill:"#15803d"})]})}function vf(){return l("svg",{width:"13",height:"20",viewBox:"0 0 18 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"6",y:"24",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"6",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"9",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"15",y:"9",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"9",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"15",y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"3",width:"3",height:"3",transform:"rotate(-90 12 3)",fill:"#080096"}),t("rect",{x:"15",y:"3",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(-90 9 3)",fill:"#080096"}),t("rect",{y:"3",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"6",y:"3",width:"3",height:"3",transform:"rotate(-90 6 3)",fill:"#080096"}),t("rect",{x:"3",y:"3",width:"3",height:"3",transform:"rotate(-90 3 3)",fill:"#080096"})]})}const Cf=Object.freeze(Object.defineProperty({__proto__:null,default:ff,loader:pf,meta:mf},Symbol.toStringTag,{value:"Module"}));function hn(e){return`${e.filePath||""}::${e.name}`}function Ps(e,r){const n=Ae(),{showToast:a}=$n(),[o,s]=P(new Map);te(()=>{if(n.state==="idle"&&n.data){const p=n.data;p!=null&&p.error&&a(`Error: ${p.error}`,"error",6e3)}},[n.state,n.data,a]),te(()=>{var f;if(o.size===0)return;const p=new Set;(f=r==null?void 0:r.jobs)==null||f.forEach(y=>{var g;(g=y.entityShas)==null||g.forEach(b=>{o.forEach((w,x)=>{w===b&&p.add(x)})})}),e==null||e.forEach(y=>{o.forEach((g,b)=>{g===y&&p.add(b)})}),p.size>0&&s(y=>{const g=new Map(y);return p.forEach(b=>g.delete(b)),g})},[r,e,o]);const i=se(p=>{console.log("Generate analysis clicked for entity:",p.sha,p.name);const f=hn(p);s(g=>new Map(g).set(f,p.sha));const y=new FormData;y.append("entitySha",p.sha),y.append("filePath",p.filePath||""),n.submit(y,{method:"post",action:"/api/analyze"})},[n]),c=se(p=>{const f=p.filter(b=>b.entityType==="visual"||b.entityType==="library");console.log("Generate analysis for all entities:",f.length),s(b=>{const w=new Map(b);return f.forEach(x=>w.set(hn(x),x.sha)),w});const y=f.map(b=>b.sha).join(","),g=new FormData;g.append("entityShas",y),n.submit(g,{method:"post",action:"/api/analyze"})},[n]),d=se(p=>(e==null?void 0:e.includes(p))??!1,[e]),h=se(p=>{const f=hn(p);return o.has(f)},[o]),u=se(p=>{var f;return((f=r==null?void 0:r.jobs)==null?void 0:f.some(y=>{var g;return(g=y.entityShas)==null?void 0:g.includes(p)}))??!1},[r]),m=ne(()=>Array.from(o.keys()),[o]);return{isAnalyzing:n.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:c,isEntityBeingAnalyzed:d,isEntityPending:h,isEntityInQueue:u,pendingEntityKeys:m}}function Kn({showActions:e=!1,sortOrder:r="desc",onSortChange:n,onAnalyzeAll:a,analyzeAllDisabled:o=!1,analyzeAllText:s="Analyze All"}){return t("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:l("div",{className:"flex justify-between items-center px-3 py-2",children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t("span",{className:"w-4"}),t("span",{children:"FILE"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[t("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:t("span",{children:"STATE"})}),t("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:t("span",{children:"SIMULATIONS"})}),l("div",{className:"flex gap-4 items-center",children:[t("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),l("div",{className:"flex items-center justify-center gap-1 cursor-pointer hover:text-[#232323] transition-colors",style:{width:"116px"},onClick:n,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),n==null||n())},children:[t("span",{children:"MODIFIED"}),t("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:r==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:t("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&t("div",{className:"text-center",style:{width:"127px"},children:a&&t("button",{onClick:a,disabled:o,className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap px-3 py-1.5 normal-case",title:o?s:"Analyze all entities",children:s})})]})]})]})})}function Nf({status:e,variant:r="compact"}){const n={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(r==="full"){const s=a[e]||{label:"UNKNOWN",textColor:"#6B7280"};return t("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:t("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:s.textColor},children:s.label})})}const o=n[e]||{label:"?",bgColor:"bg-gray-500"};return l("div",{className:"inline-flex items-center gap-1",children:[t("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&&t("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 Zn({filePath:e,isExpanded:r,onToggle:n,fileStatus:a,simulationPreviews:o,entityCount:s,state:i,lastModified:c,actionButton:d,uncommittedCount:h,children:u,isNotAnalyzable:m=!1,isUncommitted:p=!1}){return l("div",{className:"bg-white overflow-hidden",style:r?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[l("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${m?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:n,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),n())},children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:r?"rotate(90deg)":"none"},children:t("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:r?"#3e3e3e":"#c7c7c7"})})}),t("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),t(So,{filePath:e}),a&&t(Nf,{status:typeof a=="string"?a:a.status,variant:"full"}),p&&i==="out-of-date"&&t("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[t("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(p||i==="out-of-date")&&l("div",{className:"flex gap-1.5 items-center",children:[p&&t("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&!p&&t("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),t("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:o}),l("div",{className:"flex gap-4 items-center",children:[t("div",{className:"flex items-center justify-center",style:{width:"70px"},children:t("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:l("span",{className:"text-[13px] text-[#3e3e3e]",children:[s," ",s===1?"entity":"entities"]})})}),t("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:ys(c)}),t("div",{style:{width:"127px"},className:"flex justify-center",children:d})]})]})]}),r&&u&&t("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:u})]})}function Xn({entities:e,maxPreviews:r=3}){var a,o,s,i,c;const n=[];for(const d of e){if(n.length>=r)break;const h=((o=(a=d.analyses)==null?void 0:a[0])==null?void 0:o.scenarios)||[];if(d.entityType==="library"){const u=h.find(m=>{var p,f;return((p=m.metadata)==null?void 0:p.executionResult)||((f=m.metadata)==null?void 0:f.error)});u&&n.push({type:"library",scenario:u,entitySha:d.sha})}else if(d.entityType==="visual"){const u=h.find(m=>{var p,f;return(f=(p=m.metadata)==null?void 0:p.screenshotPaths)==null?void 0:f[0]});if(u){const m=(i=(s=u.metadata)==null?void 0:s.screenshotPaths)==null?void 0:i[0],p=!!((c=u.metadata)!=null&&c.error);m&&n.push({type:"screenshot",screenshot:m,hasError:p,scenario:u,entitySha:d.sha})}}}return n.length===0?t("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):t(ce,{children:n.map((d,h)=>{if(d.type==="screenshot"&&d.screenshot){const u=d.hasError?"border-red-400":"border-gray-200";return l(oe,{to:d.scenario?`/entity/${d.entitySha}/scenarios/${d.scenario.id}`:`/entity/${d.entitySha}`,className:`relative w-[50px] h-[38px] border ${u} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:m=>m.stopPropagation(),children:[t(De,{screenshotPath:d.screenshot,alt:`Preview ${h+1}`,className:"max-w-full max-h-full object-contain object-center"}),d.hasError&&t("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:t(mn,{size:12,color:"white"})})]},`screenshot-${h}`)}return d.type==="library"&&d.scenario&&d.entitySha?t(fs,{scenario:d.scenario,entitySha:d.entitySha,size:"small",showBorder:!0},`library-${h}`):null})})}function ea({entity:e,isActivelyAnalyzing:r,isQueued:n,onGenerateSimulation:a}){var u,m;const o=r||n?[{entityShas:[e.sha]}]:[],s=Ve(e,o,r),i=e.entityType==="visual"||e.entityType==="library",c=i&&(s==="not-analyzed"||s==="out-of-date")&&!r&&!n,h=(((m=(u=e.analyses)==null?void 0:u[0])==null?void 0:m.scenarios)||[]).filter(p=>{var f,y;return(y=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0]});return l("div",{className:"bg-white rounded-lg",children:[l(oe,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t("span",{className:"w-4 shrink-0"}),e.entityType==="type"?t("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:t("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:t(Ue,{type:"type"})})}):t(Ue,{type:e.entityType||"other"}),t("span",{className:`font-['IBM_Plex_Sans'] text-[14px] leading-[18px] text-black ${i?"font-medium":"font-normal"}`,children:e.name}),t(Hn,{type:e.entityType||"other"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[t("div",{style:{width:"160px"}}),l("div",{className:"flex gap-4 items-center",children:[t("div",{style:{width:"70px"}}),t("div",{style:{width:"116px"}}),t("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?s==="queued"?l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):s==="analyzing"?l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[t("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),t("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..."]}):s==="up-to-date"?t("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):s==="out-of-date"?t("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),a(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):c&&t("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),a(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):t("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"})})]})]})]}),h.length>0&&t("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:h.map((p,f)=>{var g,b;const y=(b=(g=p.metadata)==null?void 0:g.screenshotPaths)==null?void 0:b[0];return y?t(oe,{to:`/entity/${e.sha}?scenario=${p.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:w=>w.stopPropagation(),children:t(De,{screenshotPath:y,alt:p.name,className:"max-w-full max-h-full object-contain object-center"})},p.id):null})})]})}function Sf({entities:e,page:r,itemsPerPage:n=50,currentRun:a,filter:o,entityType:s,queueState:i,isEntityPending:c,pendingEntityKeys:d,onGenerateSimulation:h,onGenerateAllSimulations:u,totalFilesCount:m,totalEntitiesCount:p,uncommittedFilesCount:f,showOnlyUncommitted:y,onToggleUncommitted:g}){const[b,w]=Qt(),[x,v]=P(new Set),[C,k]=P(""),[N,E]=P(!1),[A,I]=P("all"),[j,R]=P("desc"),M=s||"all",T=ne(()=>{let S=e;return M!=="all"&&(S=S.filter(F=>F.entityType===M)),o==="analyzed"&&(S=S.filter(F=>F.analyses&&F.analyses.length>0)),S},[e,M,o]),$=ne(()=>{const S=new Map,F=new Map,O=new Map;T.forEach(Y=>{var q,Z;const W=`${Y.filePath}::${Y.name}`,Q=F.get(W);if(!Q)F.set(W,Y),O.set(W,[]);else{const de=((q=Q.metadata)==null?void 0:q.editedAt)||Q.createdAt||"",he=((Z=Y.metadata)==null?void 0:Z.editedAt)||Y.createdAt||"";let ye=!1;if(he>de)ye=!0;else if(he===de){const be=Q.createdAt||"";ye=(Y.createdAt||"")>be}ye?(O.get(W).push(Q),F.set(W,Y)):O.get(W).push(Y)}}),F.forEach((Y,W)=>{var q;if(!(Y.analyses&&Y.analyses.length>0)&&((q=Y.metadata)!=null&&q.previousVersionWithAnalyses)){const de=(O.get(W)||[]).find(he=>{var ye;return he.sha===((ye=Y.metadata)==null?void 0:ye.previousVersionWithAnalyses)});de&&de.analyses&&de.analyses.length>0&&(Y.analyses=de.analyses)}}),Array.from(F.values()).sort((Y,W)=>{var Z,de,he,ye;const Q=!((Z=Y.metadata)!=null&&Z.notExported)&&!((de=Y.metadata)!=null&&de.namedExport),q=!((he=W.metadata)!=null&&he.notExported)&&!((ye=W.metadata)!=null&&ye.namedExport);return Q&&!q?-1:!Q&&q?1:0}).forEach(Y=>{var de,he,ye,be,Ne;const W=Y.filePath??"No File Path";S.has(W)||S.set(W,{filePath:W,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const Q=S.get(W);Q.entities.push(Y),Q.totalCount++,(de=Y.metadata)!=null&&de.isUncommitted&&Q.uncommittedCount++;const q=((be=(ye=(he=Y.analyses)==null?void 0:he[0])==null?void 0:ye.scenarios)==null?void 0:be.length)||0;Q.simulationCount+=q;const Z=((Ne=Y.metadata)==null?void 0:Ne.editedAt)||Y.updatedAt;Z&&(!Q.lastUpdated||new Date(Z)>new Date(Q.lastUpdated))&&(Q.lastUpdated=Z)});const H=(i==null?void 0:i.jobs)||[],ae=Y=>{const W=`${Y.filePath||""}::${Y.name}`;return(d==null?void 0:d.includes(W))||!1};S.forEach(Y=>{const W=Y.entities.map(Q=>ae(Q)?"queued":Ve(Q,H));W.includes("analyzing")||W.includes("queued")?Y.state="analyzing":W.includes("incomplete")?Y.state="incomplete":W.includes("out-of-date")?Y.state="out-of-date":W.includes("not-analyzed")?Y.state="not-analyzed":Y.state="up-to-date"}),S.forEach(Y=>{var W,Q,q,Z,de;for(const he of Y.entities){if(Y.previewScreenshots.length+Y.previewLibraryScenarios.length>=3)break;const be=((Q=(W=he.analyses)==null?void 0:W[0])==null?void 0:Q.scenarios)||[];if(he.entityType==="library"){const Ne=be.find(we=>{var ke,Te;return((ke=we.metadata)==null?void 0:ke.executionResult)||((Te=we.metadata)==null?void 0:Te.error)});Ne&&Y.previewLibraryScenarios.push({scenario:Ne,entitySha:he.sha})}else{const Ne=be.find(we=>{var ke,Te;return(Te=(ke=we.metadata)==null?void 0:ke.screenshotPaths)==null?void 0:Te[0]});if(Ne){const we=(Z=(q=Ne.metadata)==null?void 0:q.screenshotPaths)==null?void 0:Z[0],ke=!!((de=Ne.metadata)!=null&&de.error);we&&!Y.previewScreenshots.includes(we)&&(Y.previewScreenshots.push(we),Y.previewScreenshotErrors.push(ke))}}}});const V=Array.from(S.values());return V.sort((Y,W)=>{if(o==="analyzed"){const Z=Math.max(...Y.entities.filter(he=>{var ye,be;return(be=(ye=he.analyses)==null?void 0:ye[0])==null?void 0:be.createdAt}).map(he=>new Date(he.analyses[0].createdAt).getTime()),0),de=Math.max(...W.entities.filter(he=>{var ye,be;return(be=(ye=he.analyses)==null?void 0:ye[0])==null?void 0:be.createdAt}).map(he=>new Date(he.analyses[0].createdAt).getTime()),0);return j==="desc"?de-Z:Z-de}if(Y.uncommittedCount>0&&W.uncommittedCount===0)return-1;if(Y.uncommittedCount===0&&W.uncommittedCount>0)return 1;const Q=Y.lastUpdated?new Date(Y.lastUpdated).getTime():0,q=W.lastUpdated?new Date(W.lastUpdated).getTime():0;return j==="desc"?q-Q:Q-q}),V},[T,o,j,i,d]),z=ne(()=>{let S=$;if(A!=="all"&&(S=S.filter(F=>F.state===A)),C.trim()){const F=C.toLowerCase();S=S.filter(O=>O.filePath.toLowerCase().includes(F))}return S},[$,C,A]),G=(r-1)*n,U=G+n,B=z.slice(G,U),D=Math.ceil(z.length/n),L=S=>{v(F=>{const O=new Set(F);return O.has(S)?O.delete(S):O.add(S),O})},_=()=>{R(S=>S==="desc"?"asc":"desc")};return l("div",{children:[l("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[t("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),l("div",{className:"flex gap-3",children:[l("div",{className:"relative w-[130px]",children:[l("select",{value:M,onChange:S=>{const F=S.target.value,O=new URLSearchParams(b);F==="all"?O.delete("entityType"):O.set("entityType",F),O.set("page","1"),w(O)},className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[t("option",{value:"all",children:"All Types"}),t("option",{value:"visual",children:"Visual"}),t("option",{value:"library",children:"Library"})]}),t(qt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"relative w-[130px]",children:[l("select",{value:A,onChange:S=>I(S.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[t("option",{value:"all",children:"All States"}),t("option",{value:"analyzing",children:"Analyzing..."}),t("option",{value:"up-to-date",children:"Up to date"}),t("option",{value:"incomplete",children:"Incomplete"}),t("option",{value:"out-of-date",children:"Out of date"}),t("option",{value:"not-analyzed",children:"Not analyzed"})]}),t(qt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"flex-1 relative",children:[t(En,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),t("input",{type:"text",placeholder:"Search component",value:C,onChange:S=>k(S.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),m!==void 0&&p!==void 0&&f!==void 0&&t("div",{className:"mb-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[t("span",{style:{color:"#000000"},children:z.length})," ",z.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[t("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),t("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",t("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),t("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[t("span",{style:{color:"#000000"},children:z.reduce((S,F)=>S+F.totalCount,0)})," ",z.reduce((S,F)=>S+F.totalCount,0)===1?"entity":"entities"]}),t("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),y?l("button",{onClick:g,className:"flex items-center gap-2 text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase cursor-pointer",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[z.filter(S=>S.uncommittedCount>0).length," ","uncommitted"," ",z.filter(S=>S.uncommittedCount>0).length===1?"file":"files",t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):l("button",{onClick:g,className:"text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[f," uncommitted"," ",f===1?"file":"files"]})]}),B.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:()=>{v(new Set(B.map(S=>S.filePath))),E(!0)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[t(go,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:()=>{v(new Set),E(!1)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[t(yo,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),t(Kn,{showActions:!0,sortOrder:j,onSortChange:_}),t("div",{className:"flex flex-col gap-[3px]",children:B.map(S=>{const F=x.has(S.filePath),H=S.entities.filter(W=>(W.entityType==="visual"||W.entityType==="library")&&(Ve(W,(i==null?void 0:i.jobs)||[])==="not-analyzed"||Ve(W,(i==null?void 0:i.jobs)||[])==="out-of-date"||Ve(W,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,ae=W=>{var Q;return((Q=a==null?void 0:a.currentEntityShas)==null?void 0:Q.includes(W))||!1},V=W=>{var Q;return c!=null&&c(W)?!0:((Q=i==null?void 0:i.jobs)==null?void 0:Q.some(q=>{var Z;return(Z=q.entityShas)==null?void 0:Z.includes(W.sha)}))||!1},Y=W=>{h==null||h(W)};return t(Zn,{filePath:S.filePath,isExpanded:F,onToggle:()=>L(S.filePath),simulationPreviews:t(Xn,{entities:S.entities,maxPreviews:1}),entityCount:S.totalCount,state:S.state,lastModified:S.lastUpdated,uncommittedCount:S.uncommittedCount,isUncommitted:S.uncommittedCount>0,actionButton:H?t("button",{onClick:W=>{W.stopPropagation();const Q=S.entities.filter(q=>(q.entityType==="visual"||q.entityType==="library")&&(Ve(q,(i==null?void 0:i.jobs)||[])==="not-analyzed"||Ve(q,(i==null?void 0:i.jobs)||[])==="out-of-date"||Ve(q,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(Q)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:S.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:S.entities.sort((W,Q)=>{var ye,be,Ne,we;const q=!((ye=W.metadata)!=null&&ye.notExported)&&!((be=W.metadata)!=null&&be.namedExport),Z=!((Ne=Q.metadata)!=null&&Ne.notExported)&&!((we=Q.metadata)!=null&&we.namedExport);if(q&&!Z)return-1;if(!q&&Z)return 1;const de=W.entityType==="visual"||W.entityType==="library",he=Q.entityType==="visual"||Q.entityType==="library";return de&&!he?-1:!de&&he?1:W.name.localeCompare(Q.name)}).map(W=>t(ea,{entity:W,isActivelyAnalyzing:ae(W.sha),isQueued:V(W),onGenerateSimulation:Y},W.sha))},S.filePath)})}),D>1&&l("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[r>1&&t("a",{href:`?${new URLSearchParams({...Object.fromEntries(b),page:String(r-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),l("span",{children:["Page ",r," of ",D]}),r<D&&t("a",{href:`?${new URLSearchParams({...Object.fromEntries(b),page:String(r+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const Ef=()=>[{title:"CodeYam - Files & Entities"},{name:"description",content:"Browse your codebase files and entities"}];async function Af({request:e,context:r}){try{const n=new URL(e.url),a=parseInt(n.searchParams.get("page")||"1"),o=n.searchParams.get("filter")||null,s=n.searchParams.get("entityType"),i=r.analysisQueue,c=i?i.getState():{paused:!1,jobs:[]},[d,h]=await Promise.all([er(),It()]);return J({entities:d,currentCommit:h,page:a,filter:o,entityType:s,queueState:c})}catch(n){return console.error("Failed to load entities:",n),J({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const kf=Oe(function(){var C,k,N;const{entities:r,currentCommit:n,page:a,filter:o,entityType:s,queueState:i,error:c}=We();rt();const[d,h]=Qt(),[u,m]=P(!1);mt({source:"files-page"});const{handleGenerateSimulation:p,handleGenerateAllSimulations:f,isEntityPending:y,pendingEntityKeys:g}=Ps((k=(C=n==null?void 0:n.metadata)==null?void 0:C.currentRun)==null?void 0:k.currentEntityShas,i),b=r||[],w=ne(()=>{const E=new Set([]);for(const A of b)E.add(A.filePath??"No File Path");return Array.from(E)},[b]),x=ne(()=>{let E=b;return u&&(E=E.filter(A=>{var I;return(I=A.metadata)==null?void 0:I.isUncommitted})),E.sort((A,I)=>{var j,R,M,T,$,z;return(j=A.metadata)!=null&&j.isUncommitted&&!((R=I.metadata)!=null&&R.isUncommitted)?-1:!((M=A.metadata)!=null&&M.isUncommitted)&&((T=I.metadata)!=null&&T.isUncommitted)?1:new Date((($=I.metadata)==null?void 0:$.editedAt)||0).getTime()-new Date(((z=A.metadata)==null?void 0:z.editedAt)||0).getTime()})},[b,u]),v=ne(()=>{var A;const E=new Set([]);for(const I of b)(A=I.metadata)!=null&&A.isUncommitted&&E.add(I.filePath??"No File Path");return Array.from(E)},[b]);return c?t("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[t("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),t("p",{className:"text-base text-gray-500",children:c})]})}):b.length===0?t("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[t("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),t("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),t("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:l("div",{className:"max-w-md mx-auto",children:[t("h2",{className:"text-xl font-semibold text-gray-900 mb-3",children:"No entities found"}),l("p",{className:"text-[15px] text-gray-600 mb-6",children:["Your project hasn't been analyzed yet. Run"," ",t("code",{className:"px-2 py-1 bg-gray-100 rounded text-sm font-mono",children:"codeyam analyze"})," ","to extract entities from your codebase."]}),t("p",{className:"text-sm text-gray-500",children:"Entities include React components, functions, and other analyzable code elements."})]})})]})}):t("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[t("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),t("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),t(Sf,{entities:x,page:a,itemsPerPage:50,currentRun:(N=n==null?void 0:n.metadata)==null?void 0:N.currentRun,filter:o,entityType:s,queueState:i,isEntityPending:y,pendingEntityKeys:g,onGenerateSimulation:p,onGenerateAllSimulations:f,totalFilesCount:w.length,totalEntitiesCount:b.length,uncommittedFilesCount:v.length,showOnlyUncommitted:u,onToggleUncommitted:()=>m(!u)})]})})}),Pf=Object.freeze(Object.defineProperty({__proto__:null,default:kf,loader:Af,meta:Ef},Symbol.toStringTag,{value:"Module"}));function Mf(e,r,n){const[a,o]=P(()=>new Set),[s,i]=P(()=>new Set),c=Ee([]),d=Ee([]);return te(()=>{(r.length!==c.current.length||r.some((g,b)=>g!==c.current[b]))&&(c.current=r,o(g=>{const b=new Set;return r.forEach(w=>{g.has(w)&&b.add(w)}),b}))},[r]),te(()=>{(n.length!==d.current.length||n.some((g,b)=>g!==d.current[b]))&&(d.current=n,i(g=>{const b=new Set;return n.forEach(w=>{g.has(w)&&b.add(w)}),b}))},[n]),{expandedUncommitted:a,expandedBranch:s,setExpandedUncommitted:o,setExpandedBranch:i,toggleFile:(y,g,b)=>{b(w=>{const x=new Set(w);return x.has(y)?x.delete(y):x.add(y),x})},expandAllUncommitted:()=>{o(new Set(r))},collapseAllUncommitted:()=>{o(new Set)},expandAllBranch:()=>{i(new Set(n))},collapseAllBranch:()=>{i(new Set)}}}function _f(e,r,n){const[a,o]=P(null),[s,i]=P(null),c=Ae();te(()=>{var m,p;((m=c.data)==null?void 0:m.oldContent)!==void 0&&((p=c.data)==null?void 0:p.newContent)!==void 0&&i({oldContent:c.data.oldContent,newContent:c.data.newContent,fileName:c.data.fileName})},[c.data]);const d=m=>{o({type:"file",path:m}),i(null);const p=new FormData;p.append("actionType","getDiff"),p.append("filePath",m),p.append("diffType","branch"),p.append("baseBranch",e),p.append("currentBranch",r||""),c.submit(p,{method:"post"})},h=(m,p)=>{o({type:"entity",path:m,entitySha:p}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",m),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",r||""),f.append("entitySha",p),c.submit(f,{method:"post"})},u=()=>{o(null),i(null)};return{diffView:a,diffContent:s,isLoading:c.state==="loading"||c.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:h,handleCloseDiff:u}}function Tf({diffView:e,diffContent:r,isLoading:n,entities:a,onClose:o}){var h;const[s,i]=P(!1),[c,d]=P(!1);return te(()=>{d(!0)},[]),t("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:l("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[l("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[l("div",{children:[t("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),t("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&l("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((h=a.find(u=>u.sha===e.entitySha))==null?void 0:h.name)||e.entitySha]})]}),l("div",{className:"flex items-center gap-3",children:[t("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"}),t("button",{onClick:o,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:t("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),t("div",{className:"flex-1 overflow-auto",children:n?t("div",{className:"p-6 text-center",children:t("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):r?t("div",{className:"diff-viewer-wrapper",children:c&&t(tl,{oldValue:r.oldContent,newValue:r.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"}}})}):t("div",{className:"p-6 text-center",children:t("div",{className:"text-[#8e8e8e]",children:"No diff available"})})}),t("div",{className:"p-6 border-t border-[#e1e1e1] flex justify-end gap-3",children:t("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 If({files:e,currentBranch:r,defaultBranch:n,baseBranch:a,allBranches:o,expandedFiles:s,isEntityBeingAnalyzed:i,isEntityQueued:c,sortOrder:d,onToggleFile:h,onBranchChange:u,onGenerateSimulation:m,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const b=e.flatMap(([v,{entities:C}])=>{const k=C.filter(N=>i(N.sha)||c(N)).map(N=>N.sha);return k.length>0?[{entityShas:k}]:[]}),w=v=>{const C=v.map(k=>Ve(k,b));return C.includes("analyzing")||C.includes("queued")?"analyzing":C.includes("out-of-date")?"out-of-date":C.includes("not-analyzed")?"not-analyzed":"up-to-date"},x=ne(()=>[...e].sort((v,C)=>{const k=v[1].entities.reduce((I,j)=>{var M;const R=((M=j.metadata)==null?void 0:M.editedAt)||j.updatedAt;return R?I?new Date(R)>new Date(I)?R:I:R:I},null),N=C[1].entities.reduce((I,j)=>{var M;const R=((M=j.metadata)==null?void 0:M.editedAt)||j.updatedAt;return R?I?new Date(R)>new Date(I)?R:I:R:I},null);if(!k&&!N)return 0;if(!k)return 1;if(!N)return-1;const E=new Date(k).getTime(),A=new Date(N).getTime();return d==="desc"?A-E:E-A}),[e,d]);return t("div",{children:e.length>0?l("div",{children:[t(Kn,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),t("div",{className:"flex flex-col gap-[3px]",children:x.map(([v,{status:C,entities:k,isUncommitted:N}])=>{const E=s.has(v),A=w(k),I=k.reduce((T,$)=>{var G;const z=((G=$.metadata)==null?void 0:G.editedAt)||$.updatedAt;return z?T?new Date(z)>new Date(T)?z:T:z:T},null),R=k.filter(T=>T.entityType==="visual"||T.entityType==="library").length===0;let M;return R?M=t("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):A==="analyzing"?M=l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[t("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),t("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..."]}):A==="up-to-date"?M=t("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):A==="out-of-date"?M=t("button",{onClick:T=>{T.stopPropagation(),k.filter($=>($.entityType==="visual"||$.entityType==="library")&&!i($.sha)&&!c($)).forEach($=>m($))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):A==="not-analyzed"&&(M=t("button",{onClick:T=>{T.stopPropagation(),k.filter($=>($.entityType==="visual"||$.entityType==="library")&&!i($.sha)&&!c($)).forEach($=>m($))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),t(Zn,{filePath:v,isExpanded:E,onToggle:()=>h(v),fileStatus:C,isUncommitted:N,simulationPreviews:t(Xn,{entities:k,maxPreviews:1}),entityCount:k.length,state:A,lastModified:I,isNotAnalyzable:R,actionButton:M,children:k.sort((T,$)=>{const z=T.entityType==="visual"||T.entityType==="library",G=$.entityType==="visual"||$.entityType==="library";return z&&!G?-1:!z&&G?1:0}).map(T=>t(ea,{entity:T,isActivelyAnalyzing:i(T.sha),isQueued:c(T),onGenerateSimulation:m},T.sha))},v)})})]}):l("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[t("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),t("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function $f({files:e,entityImpactMap:r,expandedFiles:n,isEntityBeingAnalyzed:a,isEntityQueued:o,projectSlug:s,baseBranch:i,currentBranch:c,sortOrder:d,onToggleFile:h,onShowFileDiff:u,onGenerateSimulation:m,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const b=ne(()=>{const v=[];return e.forEach(([C,{editedEntities:k}])=>{const N=k.filter(E=>a(E.sha)||o(E)).map(E=>E.sha);N.length>0&&v.push({entityShas:N})}),v},[e,a,o]),w=ne(()=>{const v=new Map;return e.forEach(([C,{editedEntities:k}])=>{const N=k.map(j=>Ve(j,b));let E;N.includes("analyzing")||N.includes("queued")?E="analyzing":N.includes("out-of-date")?E="out-of-date":N.includes("not-analyzed")?E="not-analyzed":E="up-to-date";const A=k.reduce((j,R)=>{var T;const M=((T=R.metadata)==null?void 0:T.editedAt)||R.updatedAt;return M&&(!j||new Date(M)>new Date(j))?M:j},null),I=k.filter(j=>j.entityType==="visual"||j.entityType==="library").length;v.set(C,{state:E,lastModified:A,analyzableCount:I})}),v},[e,b]),x=ne(()=>[...e].sort((v,C)=>{const k=w.get(v[0]),N=w.get(C[0]),E=k==null?void 0:k.lastModified,A=N==null?void 0:N.lastModified;if(!E&&!A)return 0;if(!E)return 1;if(!A)return-1;const I=new Date(E).getTime(),j=new Date(A).getTime();return d==="desc"?j-I:I-j}),[e,w,d]);return e.length===0?l("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[t("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),t("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."})]}):l("div",{children:[t(Kn,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),t("div",{className:"flex flex-col gap-[3px]",children:x.map(([v,{status:C,editedEntities:k}])=>{const N=n.has(v),E=w.get(v),{state:A,lastModified:I,analyzableCount:j}=E,R=j===0;let M;return R?M=t("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):A==="analyzing"?M=l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[t("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),t("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..."]}):A==="up-to-date"?M=t("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):A==="out-of-date"?M=t("button",{onClick:T=>{T.stopPropagation(),k.filter($=>($.entityType==="visual"||$.entityType==="library")&&!a($.sha)&&!o($)).forEach($=>m($))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):A==="not-analyzed"&&(M=t("button",{onClick:T=>{T.stopPropagation(),k.filter($=>($.entityType==="visual"||$.entityType==="library")&&!a($.sha)&&!o($)).forEach($=>m($))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),t(Zn,{filePath:v,isExpanded:N,onToggle:()=>h(v),fileStatus:C,simulationPreviews:t(Xn,{entities:k,maxPreviews:1}),entityCount:k.length,state:A,lastModified:I,isNotAnalyzable:R,isUncommitted:!0,actionButton:M,children:k.sort((T,$)=>{const z=T.entityType==="visual"||T.entityType==="library",G=$.entityType==="visual"||$.entityType==="library";return z&&!G?-1:!z&&G?1:0}).map(T=>t(ea,{entity:T,isActivelyAnalyzing:a(T.sha),isQueued:o(T),onGenerateSimulation:m},T.sha))},v)})})]})}function jf({activeTab:e,onTabChange:r,uncommittedCount:n,branchCount:a}){return t("div",{className:"border-b border-gray-200",children:l("nav",{className:"flex gap-8 items-center",children:[l("button",{onClick:()=>r("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[l("span",{className:"flex items-center gap-2",children:["Branch Changes",a>0&&t("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"&&t("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]}),l("button",{onClick:()=>r("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[l("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",n>0&&t("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:n})]}),e==="uncommitted"&&t("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const Rf=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function Df({request:e}){const r=await e.formData();if(r.get("actionType")==="getDiff"){const a=r.get("filePath"),o=r.get("diffType"),s=r.get("baseBranch"),i=r.get("currentBranch"),c=r.get("entitySha");let d;return o==="branch"?d=pr(a,s,i):d=hh(a),J({...d,entitySha:c})}return J({error:"Unknown action"},{status:400})}async function Lf({request:e,context:r}){try{const n=new URL(e.url),a=n.searchParams.get("compare"),o=n.searchParams.get("viewBranch"),s=r.analysisQueue,i=s?s.getState():{paused:!1,jobs:[]},[c,d,h]=await Promise.all([er(),It(),ze()]),u=ds(),m=ih(),p=lh(),f=ch(),y=o||m,g=a||p;let b=[];return y&&y!==g&&(b=us(g,y)),J({entities:c||[],gitStatus:u,currentBranch:y,actualCurrentBranch:m,defaultBranch:p,allBranches:f,baseBranch:g,branchDiff:b,currentCommit:d,projectSlug:h,queueState:i})}catch(n){return console.error("Failed to load git data:",n),J({entities:[],gitStatus:[],currentBranch:null,actualCurrentBranch:null,defaultBranch:"main",allBranches:[],baseBranch:"main",branchDiff:[],currentCommit:null,projectSlug:null,queueState:{paused:!1,jobs:[]},error:"Failed to load git data"})}}const Ff=Oe(function(){var Ce,nr;const{entities:r,gitStatus:n,currentBranch:a,actualCurrentBranch:o,defaultBranch:s,allBranches:i,baseBranch:c,branchDiff:d,currentCommit:h,projectSlug:u,queueState:m}=We();mt({source:"git-page"});const[p,f]=Qt(),[y,g]=P(null),[b,w]=P("desc"),[x,v]=P("branch"),C=p.get("expanded")==="true",k=()=>{w(le=>le==="desc"?"asc":"desc")},N=Ae(),E=N.data;te(()=>{a&&c&&a!==c&&N.state==="idle"&&!E&&N.load(`/api/branch-entity-diff?base=${encodeURIComponent(c)}&compare=${encodeURIComponent(a)}`)},[a,c,N,E]);const A=ne(()=>{const le=Ns(n,r);return Array.from(le.entries()).sort((qe,Je)=>qe[0].localeCompare(Je[0]))},[n,r]),I=ne(()=>{const le=Wp(d,r,E);return Array.from(le.entries()).sort((qe,Je)=>qe[0].localeCompare(Je[0]))},[d,r,E]),j=ne(()=>Hp(n,r),[n,r]),R=ne(()=>x==="uncommitted"?A:I,[x,A,I]),M=ne(()=>R.map(([le])=>le),[R]),{expandedUncommitted:T,setExpandedUncommitted:$,toggleFile:z,expandAllUncommitted:G,collapseAllUncommitted:U}=Mf(C,M,[]),{diffView:B,diffContent:D,isLoading:L,handleShowFileDiff:_,handleCloseDiff:S}=_f(c,a),F=(Ce=h==null?void 0:h.metadata)==null?void 0:Ce.currentRun,O=new Set((F==null?void 0:F.currentEntityShas)||[]),H=new Set(m.jobs.flatMap(le=>le.entityShas||[])),ae=new Set(((nr=m.currentlyExecuting)==null?void 0:nr.entityShas)||[]),{isAnalyzing:V,handleGenerateSimulation:Y,handleGenerateAllSimulations:W,isEntityBeingAnalyzed:Q,isEntityPending:q}=Ps(F==null?void 0:F.currentEntityShas,m),Z=le=>q(le)||H.has(le.sha)||ae.has(le.sha),de=le=>{le===(o||a)?p.delete("viewBranch"):p.set("viewBranch",le),f(p)},he=le=>{le===s?p.delete("compare"):p.set("compare",le),f(p)},ye=()=>{const qe=R.flatMap(([Je,Ur])=>Ur.editedEntities||Ur.entities||[]).filter(Je=>!O.has(Je.sha)&&!H.has(Je.sha)&&!ae.has(Je.sha)&&!q(Je));W(qe)},be=A.length,Ne=I.length,we=R.flatMap(([le,qe])=>qe.editedEntities||qe.entities||[]),ke=we.filter(le=>le.entityType==="visual"||le.entityType==="library"),Te=ke.length>0&&ke.every(le=>O.has(le.sha)),xe=ke.length>0&&!Te&&ke.every(le=>H.has(le.sha)||ae.has(le.sha)),je=V||Te||xe,Pe=Te?"Analyzing...":xe?"Queued...":V?"Analyzing...":"Analyze All";return t("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[t("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Git Changes"}),l("p",{className:"text-[15px] text-gray-500",children:["This is a list of all the files that are affected by your local changes. ",t("strong",{children:"Analyze a file to get simulations."})]})]}),t("div",{className:"mb-6",children:t(jf,{activeTab:x,onTabChange:v,uncommittedCount:be,branchCount:Ne})}),a&&x==="branch"&&t("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:a===s?l("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",t("span",{className:"text-cyblack-75",children:s}),"."]}):l("div",{className:"flex gap-6 items-center",children:[l("div",{className:"shrink-0",children:[t("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?l("div",{className:"relative w-50",children:[t("select",{value:a,onChange:le=>de(le.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-2.5 pr-6 text-[13px] h-9.75 w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.map(le=>t("option",{value:le,children:le},le))}),t("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}):t("span",{className:"text-gray-900 font-medium text-[12px]",children:a})]}),l("div",{className:"flex-shrink-0",children:[t("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),l("div",{className:"relative w-[200px]",children:[t("select",{value:c,onChange:le=>he(le.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.filter(le=>le!==a).map(le=>t("option",{value:le,children:le},le))}),t("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),t("div",{className:"flex-1 mt-6",children:l("div",{className:"relative flex items-center",children:[t("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),t("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),t("div",{className:"mb-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[t("span",{style:{color:"#000000"},children:R.length})," ","modified ",R.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[t("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),t("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",t("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),t("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[t("span",{style:{color:"#000000"},children:we.length})," ",we.length===1?"entity":"entities"]})]}),R.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:G,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[t(go,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:U,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[t(yo,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),l("div",{className:"overflow-hidden",children:[x==="branch"&&a&&t(If,{files:I,currentBranch:a,defaultBranch:s,baseBranch:c,allBranches:i,expandedFiles:T,isEntityBeingAnalyzed:Q,isEntityQueued:Z,sortOrder:b,onToggleFile:le=>z(le,T,$),onBranchChange:he,onGenerateSimulation:Y,onSortChange:k,onAnalyzeAll:ye,analyzeAllDisabled:je,analyzeAllText:Pe}),x==="uncommitted"&&t($f,{files:A,entityImpactMap:j,expandedFiles:T,isEntityBeingAnalyzed:Q,isEntityQueued:Z,projectSlug:u,baseBranch:c,currentBranch:a,sortOrder:b,onToggleFile:le=>z(le,T,$),onShowFileDiff:_,onGenerateSimulation:Y,onSortChange:k,onAnalyzeAll:ye,analyzeAllDisabled:je,analyzeAllText:Pe})]}),B&&t(Tf,{diffView:B,diffContent:D,isLoading:L,entities:r,onClose:S}),y&&u&&t(dt,{projectSlug:u,onClose:()=>g(null)})]})})}),Of=Object.freeze(Object.defineProperty({__proto__:null,action:Df,default:Ff,loader:Lf,meta:Rf},Symbol.toStringTag,{value:"Module"})),$g={entry:{module:"/assets/entry.client-CS2cb_eZ.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/index-B1h680n5.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-DTfSQARG.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/index-B1h680n5.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/ReportIssueModal-OApQuNyq.js","/assets/useReportContext-DYxHZQuP.js","/assets/loader-circle-B7B9V-bu.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/useToast-mBRpZPiu.js","/assets/useLastLogLine-aSv48UbS.js","/assets/LogViewer-xgeCVgSM.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/TruncatedFilePath-DyFZkK0l.js","/assets/chevron-down-Cx24_aWc.js","/assets/circle-check-BOARzkeR.js","/assets/triangle-alert-B6LgvRJg.js","/assets/copy-Bb-80kDT.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.fullscreen-DavjRmOY.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/useLastLogLine-aSv48UbS.js","/assets/useCustomSizes-C1v1PQzo.js","/assets/cy-logo-cli-DcX-ZS3p.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-CTBG2mmz.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/InteractivePreview-aht4aafF.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-aSv48UbS.js"],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-D1T4TGjf.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/InteractivePreview-aht4aafF.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-aSv48UbS.js"],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.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-profile-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.restart-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,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)-BwavGCpm.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/LogViewer-xgeCVgSM.js","/assets/useLastLogLine-aSv48UbS.js","/assets/useReportContext-DYxHZQuP.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/EntityTypeBadge-DLqD3qNt.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LoadingDots-B0GLXMsr.js","/assets/loader-circle-B7B9V-bu.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/file-code-Dhef1kWN.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._-BJUiQqZF.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useLastLogLine-aSv48UbS.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/InteractivePreview-aht4aafF.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LibraryFunctionPreview-CVtiBnY5.js","/assets/LoadingDots-B0GLXMsr.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-DzccYyI8.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/LogViewer-xgeCVgSM.js","/assets/useReportContext-DYxHZQuP.js","/assets/preload-helper-ckwbz45p.js","/assets/useCustomSizes-C1v1PQzo.js","/assets/ReportIssueModal-OApQuNyq.js","/assets/circle-check-BOARzkeR.js","/assets/triangle-alert-B6LgvRJg.js","/assets/copy-Bb-80kDT.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,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-DwFIBT09.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LoadingDots-B0GLXMsr.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/fileTableUtils-DMJ7zii9.js","/assets/chevron-down-Cx24_aWc.js","/assets/search-CxXUmBSd.js","/assets/loader-circle-B7B9V-bu.js","/assets/createLucideIcon-BdhJEx6B.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.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.health-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,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-BBnGWYga.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/ScenarioViewer-DzccYyI8.js","/assets/InteractivePreview-aht4aafF.js","/assets/useCustomSizes-C1v1PQzo.js","/assets/LogViewer-xgeCVgSM.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/useLastLogLine-aSv48UbS.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-OApQuNyq.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/circle-check-BOARzkeR.js","/assets/triangle-alert-B6LgvRJg.js","/assets/copy-Bb-80kDT.js","/assets/scenarioStatus-B_8jpV3e.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/settings-CS5f3WzT.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.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-BwqWJOgH.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useLastLogLine-aSv48UbS.js","/assets/useToast-mBRpZPiu.js","/assets/useReportContext-DYxHZQuP.js","/assets/LogViewer-xgeCVgSM.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/circle-check-BOARzkeR.js","/assets/loader-circle-B7B9V-bu.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/memory-DuTFSyJ2.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/copy-Bb-80kDT.js","/assets/search-CxXUmBSd.js","/assets/file-code-Dhef1kWN.js","/assets/chevron-down-Cx24_aWc.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-CJ6lTdTA.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.js","/assets/EntityItem-DsN1wKrm.js","/assets/fileTableUtils-DMJ7zii9.js","/assets/chevron-down-Cx24_aWc.js","/assets/search-CxXUmBSd.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/useToast-mBRpZPiu.js","/assets/TruncatedFilePath-DyFZkK0l.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LibraryFunctionPreview-CVtiBnY5.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-B6LgvRJg.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/EntityTypeBadge-DLqD3qNt.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-CPTZZ-JZ.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.js","/assets/EntityItem-DsN1wKrm.js","/assets/LogViewer-xgeCVgSM.js","/assets/fileTableUtils-DMJ7zii9.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/useToast-mBRpZPiu.js","/assets/TruncatedFilePath-DyFZkK0l.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LibraryFunctionPreview-CVtiBnY5.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-B6LgvRJg.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/EntityTypeBadge-DLqD3qNt.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-bba56ec1.js",version:"bba56ec1",sri:void 0},jg="build/client",Rg="/",Dg={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},Lg=!0,Fg=!1,Og=[],zg={mode:"lazy",manifestPath:"/__manifest"},Yg="/",Bg={module:nl},Ug={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:bd},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,module:Sd},"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:qd},"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:Xd},"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:Zu},"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:th},"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:wh},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:Ch},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:Ah},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:Mh},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:Ih},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:Rh},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:Lh},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:Vh},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:em},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:am},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:lm},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:dm},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:hm},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:pm},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:Nm},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:Am},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:Pm},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:Zm},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:tp},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:lp},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:dp},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:hp},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:kp},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:_p},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:$p},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:zp},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:Bp},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:Kp},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:Cf},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:Pf},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:Of}},Wg=!1;export{dc as A,lc as B,ve as C,jl as D,Rl as E,At as F,Nl as G,Ao as H,ko as I,Po as J,Pl as K,_l as L,jg as M,Rg as N,Dg as O,vl as P,Lg as Q,Fg as R,yr as S,Og as T,zg as U,Yg as V,Bg as W,Ug as X,Wg as Y,$g as Z,gl as a,Pt as b,St as c,nt as d,Zt as e,jn as f,Rn as g,Eo as h,pl as i,Hl as j,ql as k,ut as l,at as m,To as n,ec as o,br as p,ht as q,Io as r,$o as s,oc as t,ct as u,jo as v,Tt as w,sc as x,Ia as y,hc as z};
|