@codeyam/codeyam-cli 0.1.0-staging.ae0de75 → 0.1.0-staging.b8f4f94
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 +3 -3
- package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +13 -7
- package/analyzer-template/packages/analyze/src/lib/asts/index.ts +7 -2
- package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js +196 -0
- package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js.map +1 -0
- package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js +114 -0
- package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js.map +1 -0
- package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js +149 -0
- package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js.map +1 -0
- package/codeyam-cli/src/commands/default.js +3 -46
- package/codeyam-cli/src/commands/default.js.map +1 -1
- package/codeyam-cli/src/commands/editor.js +254 -66
- package/codeyam-cli/src/commands/editor.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/editorAudit.test.js +234 -0
- package/codeyam-cli/src/utils/__tests__/editorAudit.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/editorJournal.test.js +12 -1
- package/codeyam-cli/src/utils/__tests__/editorJournal.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js +29 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js +1217 -0
- package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js.map +1 -0
- package/codeyam-cli/src/utils/backgroundServer.js +2 -2
- package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
- package/codeyam-cli/src/utils/editorAudit.js +45 -5
- package/codeyam-cli/src/utils/editorAudit.js.map +1 -1
- package/codeyam-cli/src/utils/editorJournal.js +7 -0
- package/codeyam-cli/src/utils/editorJournal.js.map +1 -1
- package/codeyam-cli/src/utils/entityChangeStatus.js +255 -0
- package/codeyam-cli/src/utils/entityChangeStatus.js.map +1 -0
- package/codeyam-cli/src/utils/install-skills.js +1 -1
- package/codeyam-cli/src/utils/install-skills.js.map +1 -1
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +5 -1
- package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/Terminal-nZNBALox.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-diff-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/editor-DTwKl1Xu.js +10 -0
- package/codeyam-cli/src/webserver/build/client/assets/{entity._sha.scenarios._scenarioId.dev-D8ILZMR0.js → entity._sha.scenarios._scenarioId.dev-DjACbfdI.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/git-CdN8sCqs.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/globals-h1-1oFYI.css +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/index-yHOVb4rc.js +15 -0
- package/codeyam-cli/src/webserver/build/client/assets/manifest-9422aeab.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{memory-FweZHj5U.js → memory-Dg0mvYrI.js} +4 -1
- package/codeyam-cli/src/webserver/build/client/assets/{root-DUKqhFlb.js → root-BzQgN2ff.js} +1 -1
- package/codeyam-cli/src/webserver/build/server/assets/{index-BLhjL9Xi.js → index-Bh_pNxNA.js} +1 -1
- package/codeyam-cli/src/webserver/build/server/assets/server-build-Bqr22tlO.js +367 -0
- package/codeyam-cli/src/webserver/build/server/index.js +1 -1
- package/codeyam-cli/src/webserver/build-info.json +5 -5
- package/codeyam-cli/src/webserver/server.js +32 -6
- package/codeyam-cli/src/webserver/server.js.map +1 -1
- package/codeyam-cli/src/webserver/terminalServer.js +23 -4
- package/codeyam-cli/src/webserver/terminalServer.js.map +1 -1
- package/codeyam-cli/templates/editor-step-hook.py +53 -6
- package/codeyam-cli/templates/skills/codeyam-editor/SKILL.md +10 -5
- package/codeyam-cli/templates/skills/codeyam-memory/SKILL.md +10 -10
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/detect-deprecated-patterns.mjs +139 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/find-exports.mjs +52 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/read-json-field.mjs +61 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/ripgrep-fallback.mjs +155 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/cleanup.mjs +13 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/filter-session.mjs +95 -0
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/preprocess.mjs +160 -0
- package/package.json +10 -10
- package/packages/analyze/src/lib/ProjectAnalyzer.js +10 -4
- package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
- package/packages/analyze/src/lib/asts/index.js +4 -2
- package/packages/analyze/src/lib/asts/index.js.map +1 -1
- package/scripts/npm-post-install.cjs +22 -0
- package/codeyam-cli/src/webserver/build/client/assets/Terminal-wkqC0AQk.js +0 -41
- package/codeyam-cli/src/webserver/build/client/assets/editor-CdjF_fX6.js +0 -8
- package/codeyam-cli/src/webserver/build/client/assets/git-CFCTYk9I.js +0 -15
- package/codeyam-cli/src/webserver/build/client/assets/globals-B17TBSS6.css +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/manifest-b8fd6b07.js +0 -1
- package/codeyam-cli/src/webserver/build/server/assets/server-build-DyMuI5mU.js +0 -363
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/detect-deprecated-patterns.sh +0 -108
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/find-exports.sh +0 -69
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/cleanup.sh +0 -12
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/filter.jq +0 -45
- package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/preprocess.sh +0 -139
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
var Hl=Object.defineProperty;var Ja=e=>{throw TypeError(e)};var Vl=(e,t,r)=>t in e?Hl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Xn=(e,t,r)=>Vl(e,typeof t!="symbol"?t+"":t,r),ql=(e,t,r)=>t.has(e)||Ja("Cannot "+r);var Ha=(e,t,r)=>(ql(e,t,"read from private field"),r?r.call(e):t.get(e)),Va=(e,t,r)=>t.has(e)?Ja("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);import{jsx as n,jsxs as l,Fragment as ue}from"react/jsx-runtime";import{PassThrough as Gl}from"node:stream";import{createReadableStreamFromReadable as Kl}from"@react-router/node";import{ServerRouter as Ql,useFetcher as Le,useLocation as $r,useNavigate as St,Link as de,UNSAFE_withComponentProps as Je,Meta as Zl,Links as Xl,ScrollRestoration as ec,Scripts as tc,useLoaderData as Ve,useRevalidator as ft,Outlet as nc,data as K,useSearchParams as fn,useRouteLoaderData as rc,useParams as ni,useActionData as sc,redirect as qa}from"react-router";import{isbot as ac}from"isbot";import{renderToPipeableStream as oc}from"react-dom/server";import{useState as _,useEffect as te,useCallback as oe,createContext as Xs,useContext as Rr,useRef as be,useMemo as ne,forwardRef as ic,useImperativeHandle as lc}from"react";import{Settings as Ga,CheckCircle2 as ea,Bug as ri,AlertTriangle as gr,Check as gt,Copy as Nt,Loader2 as ht,PencilRuler as cc,HomeIcon as dc,GitCommitIcon as Ka,File as uc,RefreshCw as mc,BookOpen as yr,FlaskConical as hc,SettingsIcon as pc,PanelsTopLeftIcon as fc,ComponentIcon as gc,FileText as Qa,Code as Za,Box as yc,List as xc,BarChart3 as bc,Tag as vc,Image as In,Code2 as si,Activity as ms,ChevronDown as ct,CircleEqual as wc,ArrowLeft as Nc,Terminal as xr,Search as Fn,ChevronLeft as Cc,ChevronRight as Ft,Save as Sc,MessageSquare as kc,Pause as ai,ListTodo as Ec,PauseCircle as Ac,FileCode as br,GripVertical as Pc,Ban as _c,CheckCircle as jc,FolderOpen as Mc,CodeXml as Tc,Zap as $c,Pencil as Rc,Trash2 as Ic,X as zn,Folder as oi,Info as Ds,Plus as ta,Eye as Dc,FolderTree as Lc,ChevronsUpDown as ii,ChevronsDownUp as li}from"lucide-react";import"fetch-retry";import Oc from"better-sqlite3";import{Pool as Fc}from"pg";import*as G from"fs";import Ce,{existsSync as Rt,readdirSync as zc,rmSync as hs}from"fs";import*as O from"path";import ee,{join as Xa}from"path";import{OperationNodeTransformer as Bc,Kysely as ci,ParseJSONResultsPlugin as Yc,SqliteDialect as Uc,PostgresDialect as Wc,sql as it}from"kysely";import*as Jc from"kysely/helpers/sqlite";import*as Hc from"kysely/helpers/postgres";import Be from"typescript";import*as we from"fs/promises";import xe,{writeFile as jn,readFile as Ls,mkdir as Vc}from"fs/promises";import*as na from"os";import Os from"os";import qc from"prompts";import vr from"chalk";import*as Gc from"crypto";import Bn,{randomUUID as ra,createHmac as Kc}from"crypto";import{execSync as Pe,spawn as kt,exec as sa}from"child_process";import{fileURLToPath as Ir}from"url";import{promisify as aa}from"util";import Qc from"dotenv";import Zc,{EventEmitter as Dr}from"events";import{v4 as Xc}from"uuid";import oa from"http";import ed from"net";import{WebSocket as di}from"ws";import"node-pty";import td from"openai";import nd from"p-queue";import eo from"p-retry";import{DynamoDBClient as Lr,PutItemCommand as rd}from"@aws-sdk/client-dynamodb";import{LRUCache as ia}from"lru-cache";import"pluralize";import"piscina";import sd from"json5";import{marshall as ad}from"@aws-sdk/util-dynamodb";import od from"v8";import{Prism as id}from"react-syntax-highlighter";import{vscDarkPlus as ld}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as cd}from"node:crypto";import{minimatch as Fs}from"minimatch";import dd from"react-markdown";import ud from"remark-gfm";import md from"react-diff-viewer-continued";const ui=5e3;function hd(e,t,r,s,a){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let c=!1,d=e.headers.get("user-agent"),m=d&&ac(d)||s.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>p(),ui+1e3);const{pipe:h,abort:p}=oc(n(Ql,{context:s,url:e.url}),{[m](){c=!0;const f=new Gl({final(g){clearTimeout(u),u=void 0,g()}}),y=Kl(f);r.set("Content-Type","text/html"),h(f),o(new Response(y,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,c&&console.error(f)}})})}const pd=Object.freeze(Object.defineProperty({__proto__:null,default:hd,streamTimeout:ui},Symbol.toStringTag,{value:"Module"}));function fd({id:e,selected:t,onClick:r,icon:s,name:a}){const[o,i]=_(!1);te(()=>{i(!0)},[]);const c=oe(()=>{r==null||r(e)},[r,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
|
+
${t?"text-[#CBF3FA]":"text-[#568B94] hover:text-[#CBF3FA]"}
|
|
5
|
+
`,onClick:c,children:[n("div",{className:`${t?"bg-[#CBF3FA] text-[#022A35]":""} w-9 h-9 rounded-lg flex items-center justify-center transition-colors`,children:o&&s}),n("span",{className:`text-[10px] font-normal text-center leading-tight ${t?"text-[#CBF3FA]":""}`,style:t?{color:"#CBF3FA !important"}:void 0,children:a})]})}const Or="/assets/cy-logo-cli-CCKUIm0S.svg";function gd(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 yd({content:e,className:t=""}){const[r,s]=_(!1),a=oe(()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),2e3)}).catch(o=>{console.error("Failed to copy:",o)})},[e]);return n("button",{onClick:a,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?l(ue,{children:[n(gt,{size:14}),"Copied"]}):l(ue,{children:[n(Nt,{size:14}),"Copy"]})})}function mi({isOpen:e,onClose:t,context:r,defaultEmail:s="",screenshotDataUrl:a}){const[o,i]=_(""),[c,d]=_(s),[m,u]=_(!1),[h,p]=_(!1),[f,y]=_(null),[g,x]=_(null),v=Le(),b=v.state!=="idle",N=!!(r.scenarioId||r.analysisId),w=r.analysisId||r.scenarioId||"",S=()=>{const A=`/codeyam-diagnose ${w}`;return o.trim()?`${A} ${o.trim()}`:A};if(v.data&&!h&&!g){const A=v.data;A.success&&A.reportId?(p(!0),y(A.reportId)):A.error&&x(A.error)}const C=async()=>{x(null);const A=new FormData;if(A.append("issueType","other"),A.append("description",o),A.append("email",c),A.append("source",r.source),A.append("entitySha",r.entitySha||""),A.append("scenarioId",r.scenarioId||""),A.append("analysisId",r.analysisId||""),A.append("currentUrl",r.currentUrl),A.append("entityName",r.entityName||""),A.append("entityType",r.entityType||""),A.append("scenarioName",r.scenarioName||""),A.append("errorMessage",r.errorMessage||""),a)try{const j=await(await fetch(a)).blob();A.append("screenshot",j,"screenshot.jpg")}catch(I){console.error("Failed to convert screenshot:",I)}v.submit(A,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},k=()=>{i(""),u(!1),p(!1),y(null),x(null),t()},E=A=>{A.key==="Escape"&&k()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:E,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:[b?n("div",{className:"animate-spin",children:n(Ga,{size:24,style:{strokeWidth:1.5}})}):h?n(ea,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(ri,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:h?"Report Submitted":"Report Issue"})]}),n("button",{onClick:k,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),h?l("div",{children:[l("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[n("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),l("p",{className:"text-xs text-green-700",children:["Report ID:"," ",n("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),n("p",{className:"text-sm text-gray-600 mb-6",children:"The CodeYam team will investigate and may reach out if you provided an email address."}),n("div",{className:"flex justify-end",children:n("button",{onClick:k,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:[n("div",{className:"text-sm font-medium text-gray-900",title:`${r.source}${r.entitySha?` • Entity: ${r.entitySha}`:""}${r.scenarioId?` • Scenario: ${r.scenarioId}`:""}${r.analysisId?` • Analysis: ${r.analysisId}`:""}`,children:gd(r)}),n("button",{type:"button",onClick:()=>u(!m),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:m?"Hide":"Details"})]}),m&&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:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),l("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&l("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&l("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&l("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),a&&l("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:a,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:o,onChange:A=>i(A.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"})]}),N&&l(ue,{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:[n("span",{className:"text-lg",children:"🔧"}),n("h3",{className:"text-sm font-semibold text-purple-900",children:"Diagnose & Fix (Recommended)"})]}),n("p",{className:"text-xs text-purple-700 mb-3",children:"Run this command in Claude Code to investigate the issue locally and potentially fix it. A detailed report will also be uploaded."}),l("div",{className:"relative",children:[n("div",{className:"bg-gray-800 text-gray-50 px-3 py-2.5 pr-20 rounded-md text-xs font-mono overflow-x-auto whitespace-nowrap",children:S()}),n(yd,{content:S(),className:"absolute top-1.5 right-2 px-2 py-1 bg-purple-600 text-white border-none rounded text-[11px] font-medium hover:bg-purple-700 transition-colors"})]})]}),l("div",{className:"relative my-5",children:[n("div",{className:"absolute inset-0 flex items-center",children:n("div",{className:"w-full border-t border-gray-300"})}),n("div",{className:"relative flex justify-center",children:n("span",{className:"bg-white px-3 text-xs text-gray-500 uppercase",children:"or"})})]})]}),l("div",{className:N?"opacity-75":"",children:[N&&l("div",{className:"flex items-center gap-2 mb-3",children:[n("span",{className:"text-lg",children:"📤"}),n("h3",{className:"text-sm font-semibold text-gray-700",children:"Quick Report"}),n("span",{className:"text-xs text-gray-500",children:"(won't investigate locally)"})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),n("input",{id:"email",type:"email",value:c,onChange:A=>d(A.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:[n(gr,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),l("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),b&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:v.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:[n(gr,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),l("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:g})]})]}),l("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:k,disabled:b,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors disabled:opacity-50 cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>void C(),disabled:b,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:b?l(ue,{children:[n("div",{className:"animate-spin",children:n(Ga,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):g?"Try Again":"Submit Report"})]})]})]})]})}):null}const to={source:"navbar"},la=Xs(void 0);function xd({children:e}){const[t,r]=_(to),s=oe(o=>{r(o)},[]),a=oe(()=>{r(to)},[]);return n(la.Provider,{value:{contextData:t,setContextData:s,resetContextData:a},children:e})}function yt(e){const t=Rr(la),r=be(t);te(()=>{if(r.current)return r.current.setContextData(e),()=>{var s;(s=r.current)==null||s.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId,e.entityName,e.entityType,e.scenarioName,e.errorMessage])}function bd(){const e=Rr(la),t=$r();return e?{source:e.contextData.source,entitySha:e.contextData.entitySha,scenarioId:e.contextData.scenarioId,analysisId:e.contextData.analysisId,currentUrl:t.pathname,entityName:e.contextData.entityName,entityType:e.contextData.entityType,scenarioName:e.contextData.scenarioName,errorMessage:e.contextData.errorMessage}:{source:"navbar",currentUrl:t.pathname}}function vd({labs:e,isAdmin:t,editorMode:r}){var C;const s=$r(),a=St(),[o,i]=_(),[c,d]=_(!1),[m,u]=_(!1),[h,p]=_(null),f=Le();te(()=>{f.state==="idle"&&!f.data&&f.load("/api/generate-report")},[f]);const y=((C=f.data)==null?void 0:C.defaultEmail)||"",g={width:"20px",height:"20px",strokeWidth:1.5},x=(e==null?void 0:e.simulations)??!1,v=[{id:"editor",icon:n(cc,{style:g}),link:"/editor",name:"Editor",hidden:!r},{id:"dashboard",icon:n(dc,{style:g}),link:"/",name:"Dashboard",hidden:!x},{id:"simulations",icon:l("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:g,children:[n("path",{d:"M9 12.75V15.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 15.75H12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6.75 12.7498L11.325 8.17483C11.6067 7.89873 11.9858 7.7447 12.3803 7.7461C12.7747 7.74751 13.1528 7.90423 13.4325 8.18233L16.5 11.2498",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 8.25C6.82843 8.25 7.5 7.57843 7.5 6.75C7.5 5.92157 6.82843 5.25 6 5.25C5.17157 5.25 4.5 5.92157 4.5 6.75C4.5 7.57843 5.17157 8.25 6 8.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M15 2.25H3C2.17157 2.25 1.5 2.92157 1.5 3.75V11.25C1.5 12.0784 2.17157 12.75 3 12.75H15C15.8284 12.75 16.5 12.0784 16.5 11.25V3.75C16.5 2.92157 15.8284 2.25 15 2.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),link:"/simulations",name:"Simulations",hidden:!x},{id:"git",icon:n(Ka,{style:g}),link:"/git",name:"Git",hidden:!x},{id:"files",icon:n(uc,{style:g}),link:"/files",name:"Files",hidden:!x},{id:"activity",icon:n(mc,{style:g}),link:"/activity",name:"Activity",hidden:!x},{id:"memory",icon:n(yr,{style:g}),link:"/memory",name:"Memory"},{id:"labs",icon:n(hc,{style:g}),link:"/labs",name:"Labs"},{id:"settings",icon:n(pc,{style:g}),link:"/settings",name:"Settings"},{id:"commits",icon:n(Ka,{style:g}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(fc,{style:g}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(gc,{style:g}),link:"/components",name:"Components",hidden:!0}],b=oe(k=>{const E=v.find(A=>A.id===k);E!=null&&E.link&&a(E.link),i(A=>A===k?void 0:k)},[v,a]);te(()=>{const k={editor:["editor"],dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],memory:["memory","agent-transcripts"],files:["files"],labs:["labs"],settings:["settings"],pages:["pages"],components:["components"]};for(const[E,A]of Object.entries(k))if(A.some(I=>I==="/"?s.pathname==="/":s.pathname.includes(I))){i(E);return}i(void 0)},[s]);const N=async()=>{u(!0);try{const{default:k}=await import("html2canvas-pro"),A=(await k(document.body)).toDataURL("image/jpeg",.8);p(A),d(!0)}catch(k){console.error("Screenshot capture failed:",k),d(!0)}finally{u(!1)}},w=()=>{d(!1),p(null)},S=bd();return l(ue,{children:[l("div",{id:"sidebar",className:"sticky top-0 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:[n("div",{className:"py-3 mt-2 mb-4",children:n(de,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:Or,alt:"CodeYam",className:"h-6"})})}),v.filter(k=>!k.hidden).map(k=>n(fd,{id:k.id,selected:k.id===o,onClick:b,icon:k.icon,name:k.name},`sidebar-button-${k.id}`))]}),t&&n("div",{className:"w-full flex flex-col items-center pb-2",children:l("button",{onClick:()=>void N(),disabled:m,className:"w-full px-1.5 py-2 flex flex-col items-center justify-center gap-1 text-[#568B94] hover:text-[#CBF3FA] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait",children:[n("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center",children:m?n(ht,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n(ri,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:m?"Capturing...":`Report
|
|
6
|
+
Bug`})]})})]}),c&&n(mi,{isOpen:!0,onClose:w,context:S,defaultEmail:y,screenshotDataUrl:h??void 0})]})}const hi=Xs(void 0);function wd({children:e}){const[t,r]=_([]),s=oe((o,i="info",c=5e3)=>{const m={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:c};r(u=>[...u,m])},[]),a=oe(o=>{r(i=>i.filter(c=>c.id!==o))},[]);return n(hi.Provider,{value:{toasts:t,showToast:s,closeToast:a},children:e})}function ca(){const e=Rr(hi);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Nd({toast:e,onClose:t}){te(()=>{const a=e.duration||5e3;if(a>0){const o=setTimeout(()=>{t(e.id)},a);return()=>clearTimeout(o)}},[e.id,e.duration,t]);const r={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return 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:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function Cd({toasts:e,onClose:t}){return e.length===0?null:l("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
|
|
7
|
+
@keyframes slideIn {
|
|
8
|
+
from {
|
|
9
|
+
transform: translateX(400px);
|
|
10
|
+
opacity: 0;
|
|
11
|
+
}
|
|
12
|
+
to {
|
|
13
|
+
transform: translateX(0);
|
|
14
|
+
opacity: 1;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
`}),e.map(r=>n(Nd,{toast:r,onClose:t},r.id))]})}function Et(e,t){const[r,s]=_(""),[a,o]=_(!1),[i,c]=_(null),[d,m]=_(!1);te(()=>{t&&(m(!1),o(!1),c(null))},[t]),te(()=>{if(!e||!t){t||s("");return}const h=async()=>{if(!d)try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const g=(await f.text()).trim().split(`
|
|
18
|
+
`).filter(b=>b.length>0);if(g.length<3){o(!1),m(!1),c(null),s("");return}const x=g.filter(b=>b.includes("CodeYam Log Level 1"));if(x.length>0){const b=x[x.length-1];s(b.replace(/.*CodeYam Log Level 1: /,""))}const v=g.find(b=>b.includes("$$INTERACTIVE_SERVER_URL$$:"));if(v){const b=v.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();c(b),m(!0)}g.some(b=>b.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};h().catch(()=>{});const p=setInterval(()=>{h().catch(()=>{})},500);return()=>clearInterval(p)},[e,t,d]);const u=oe(()=>{s(""),o(!1),c(null),m(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:a,resetLogs:u}}function Dt({projectSlug:e,onClose:t}){const[r,s]=_("Loading logs..."),[a,o]=_(!0),[i,c]=_(!0),[d,m]=_("all"),u=be(null);return te(()=>{const h=async()=>{try{const p=await fetch(`/api/logs/${e}`);if(p.ok){const f=await p.text();if(d==="all")s(f);else{const y=f.trim().split(`
|
|
19
|
+
`).filter(g=>{if(g.length===0)return!1;const x=g.match(/^.*CodeYam Log Level (\d+):/);return!!x&&Number(x[1])<=d});s(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 s(`Error: ${p.status} - ${await p.text()}`)}catch(p){s(`Error fetching logs: ${p.message}`)}};if(h().catch(()=>{}),a){const p=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(p)}},[e,a,i,d]),te(()=>{const h=p=>{p.key==="Escape"&&t()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:l("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:h=>h.stopPropagation(),children:[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:[n("span",{children:"Log Level:"}),l("select",{value:d,onChange:h=>m(h.target.value==="all"?"all":Number(h.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:a,onChange:h=>o(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:h=>c(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:u,children:r})]})})}function tt({type:e,size:t="default"}){const r={visual:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},library:{iconColor:"#06b6d5",bgColor:"bg-[#e6fbff]",bgHex:"#e6fbff"},type:{iconColor:"#db2627",bgColor:"bg-[#ffe1e1]",bgHex:"#ffe1e1"},data:{iconColor:"#2563eb",bgColor:"bg-blue-100",bgHex:"#dbeafe"},index:{iconColor:"#ea580c",bgColor:"bg-orange-100",bgHex:"#ffedd5"},functionCall:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},class:{iconColor:"#059669",bgColor:"bg-emerald-100",bgHex:"#d1fae5"},method:{iconColor:"#0891b2",bgColor:"bg-cyan-100",bgHex:"#cffafe"},other:{iconColor:"#6b7280",bgColor:"bg-gray-100",bgHex:"#f3f4f6"}},s=r[e]||r.other,a=t==="large"?18:14,o=t==="large"?32:18,i=()=>{switch(e){case"library":return n(si,{size:a,color:s.iconColor});case"visual":return n(In,{size:a,color:s.iconColor});case"type":return n(vc,{size:a,color:s.iconColor});case"data":return n(bc,{size:a,color:s.iconColor});case"index":return n(xc,{size:a,color:s.iconColor});case"functionCall":return n(Za,{size:a,color:s.iconColor});case"class":return n(yc,{size:a,color:s.iconColor});case"method":return n(Za,{size:a,color:s.iconColor});case"other":return n(Qa,{size:a,color:s.iconColor});default:return n(Qa,{size:a,color:s.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${s.bgColor}`,style:{width:`${o}px`,height:`${o}px`},children:i()})}function pi({filePath:e,maxLength:t=60,className:r,style:s}){const o=((c,d)=>{if(c.length<=d)return c;const m="...",u=d-m.length,h=Math.ceil(u*.4),p=Math.floor(u*.6),f=c.slice(0,h),y=c.slice(-p),g=f.lastIndexOf("/"),x=y.indexOf("/"),v=g>h*.5?f.slice(0,g+1):f,b=x!==-1&&x<p*.5?y.slice(x):y;return`${v}${m}${b}`})(e,t),i=o!==e;return n("span",{className:r||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...s,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:o})}function ps({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:s=50,showScenarioCount:a=!1,scenarioCount:o=0,additionalContent:i}){return l("div",{className:"flex flex-col gap-1",children:[l("div",{className:"flex items-center gap-1",children:[n(tt,{type:e.entityType||"other"}),l(de,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:t,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,a&&o>0&&` (${o})`]}),n(pi,{filePath:e.filePath,maxLength:s,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const fs={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function Sd({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:s=!1,queuedJobCount:a=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:c=[]}){var q,Y,H;const[d,m]=_(!1),[u,h]=_(!1),[p,f]=_(null),[y,g]=_(new Set),[x,v]=_(new Set),[b,N]=_(!1),w=!!i||o.length>0,S=!!i,C=(i==null?void 0:i.entities)||r,k=!!(e!=null&&e.analysisCompletedAt),E=(e==null?void 0:e.readyToBeCaptured)??0,A=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||k&&(E===0||A>=E);const I=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,j=w,{lastLine:P}=Et(t,j),$=S||o.length>0,T=new Set(((q=i==null?void 0:i.entities)==null?void 0:q.map(B=>B.sha))||[]),R=c.filter(B=>!(B.currentEntityShas||[]).some(M=>T.has(M))),J=(()=>{const D=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&I){const M=e.analysisCompletedAt||e.createdAt;if(new Date(M).getTime()>D)return!0}if(R.length>0){const M=R[0],Q=M.analysisCompletedAt||M.archivedAt||M.createdAt;if(Q&&new Date(Q).getTime()>D)return!0}return!1})();return te(()=>{const B=(i==null?void 0:i.id)||null;w&&!u&&B!==p&&h(!0),!w&&p!==null&&f(null)},[w,i==null?void 0:i.id,u,p]),l(ue,{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:()=>{h(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[$?n(ht,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(ms,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:$?"Analyzing...":"Activity: No Activity Yet"}),$&&n("button",{onClick:B=>{B.stopPropagation(),m(!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:[$?n(ht,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(ms,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:$?"Analyzing...":"Activity"})]}),l("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>m(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{h(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:n(ct,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),l("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[$&&i&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(ms,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Current Activity"})]}),n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:C.length>0?l("div",{className:"space-y-1.5",children:[(b?C:C.slice(0,3)).map(B=>n(ps,{entity:B,nameSize:"11px",pathSize:"10px",pathMaxLength:150},B.sha)),C.length>3&&n("button",{onClick:()=>N(B=>!B),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:fs,"aria-label":b?"Show fewer entities":`Show ${C.length-3} more entities`,children:b?"Show less":`+${C.length-3} more`}),P&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:P})]}):l("div",{children:[i.entityNames&&i.entityNames.length>0?l("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((B,D)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:B},D)),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"," ",((Y=i.entityShas)==null?void 0:Y.length)||0," ",((H=i.entityShas)==null?void 0:H.length)===1?"entity":"entities","..."]}),P&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:P})]})})]}),o.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(wc,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Queued Activity"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:o.map(B=>{var Q,U;const D=y.has(B.id),M=D?B.entities:B.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:B.entities.length>0?l("div",{className:"space-y-1.5",children:[M.map(F=>n(ps,{entity:F,nameSize:"10px",pathSize:"9px",pathMaxLength:120},F.sha)),B.entities.length>3&&n("button",{onClick:()=>{g(F=>{const X=new Set(F);return X.has(B.id)?X.delete(B.id):X.add(B.id),X})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:fs,"aria-label":D?"Show fewer entities":`Show ${B.entities.length-3} more entities`,children:D?"Show less":`+${B.entities.length-3} more`})]}):l("div",{style:{fontSize:"10px",color:"#343434"},children:[B.type==="analysis"&&n(ue,{children:B.entityNames&&B.entityNames.length>0?l("div",{className:"space-y-0.5",children:[B.entityNames.slice(0,5).map((F,X)=>n("div",{children:F},X)),B.entityNames.length>5&&l("div",{className:"italic",children:["+",B.entityNames.length-5," more"]})]}):`Analyzing ${((Q=B.entityShas)==null?void 0:Q.length)||0} ${((U=B.entityShas)==null?void 0:U.length)===1?"entity":"entities"}`}),B.type==="recapture"&&"Recapturing scenario",B.type==="debug-setup"&&"Setting up debug environment"]})},B.id)})})]}),J&&R.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(ea,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Recently Completed"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:R.slice(0,3).map((B,D)=>{const M=B.entities||[],Q=B.analysisCompletedAt||B.archivedAt||B.createdAt||"",U=(()=>{if(!Q)return"";const L=Date.now()-new Date(Q).getTime(),W=Math.floor(L/6e4),V=Math.floor(L/36e5);return V>0?`${V}h ago`:W>0?`${W}m ago`:"just now"})(),F=x.has(D),z=(F?M:M.slice(0,3)).map(L=>{var W,V,Z;return{...L,scenarioCount:((Z=(V=(W=L.analyses)==null?void 0:W[0])==null?void 0:V.scenarios)==null?void 0:Z.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:M.length>0&&l("div",{className:"space-y-1.5",children:[z.map((L,W)=>l("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(ps,{entity:L,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:L.scenarioCount})}),W===0&&U&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:U})]},L.sha)),M.length>3&&n("button",{onClick:()=>{v(L=>{const W=new Set(L);return W.has(D)?W.delete(D):W.add(D),W})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:fs,"aria-label":F?"Show fewer entities":`Show ${M.length-3} more entities`,children:F?"Show less":`+${M.length-3} more`})]})},D)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(de,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&t&&n(Dt,{projectSlug:t,onClose:()=>m(!1)})]})}function nt(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function Yn(e){const{file_id:t,project_id:r,commit_id:s,file_path:a,entity_type:o,entity_branches:i,analyses:c,commit:d,created_at:m,updated_at:u,...h}=e,p=(i??[]).map(g=>g.branch_id),f=c?c.map(At):void 0,y=d?Qt(d):void 0;return nt({...h,fileId:t,projectId:r,commitId:s,filePath:a,entityType:o,commit:y,analyses:f,branchIds:p,createdAt:m,updatedAt:u})}function da(e){return nt({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 ua(e){const{branches:t,files:r,analyzed_at:s,content_changed_at:a,created_at:o,updated_at:i,github_token:c,configuration:d,team_id:m,...u}=e;return nt({...u,branches:t?t.map(mn):void 0,files:r?r.map(da):void 0,analyzedAt:s,contentChangedAt:a,createdAt:o,updatedAt:i})}function kd(e){const{id:t,project_id:r,user_id:s,scenario_id:a,thumbs_up:o,user:i}=e,c=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return nt({id:t,projectId:r,userId:s,scenarioId:a,thumbsUp:!!o,user:c})}function Ed(e){const{id:t,project_id:r,user_id:s,scenario_id:a,text:o,created_at:i,updated_at:c,user:d}=e,m=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return nt({id:t,projectId:r,userId:s,scenarioId:a,text:o,createdAt:i,updatedAt:c,user:m})}function fi(e){const{project_id:t,analysis_id:r,previous_version_id:s,analysis:a,user_scenarios:o,scenario_comments:i,approved:c,...d}=e,m=a?At(a):void 0,u=o?o.map(kd):void 0,h=i?i.map(Ed):void 0;return nt({...d,projectId:t,analysisId:r,previousVersionId:s,analysis:m,userScenarios:u,comments:h})}function Ad(e){return nt({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?At(e.analysis):void 0,entity:e.entity?Yn(e.entity):void 0,branch:e.branch?mn(e.branch):void 0,createdAt:e.created_at})}function At(e){const{project_id:t,commit_id:r,file_id:s,file_path:a,entity_sha:o,entity_type:i,entity_name:c,previous_analysis_id:d,file:m,entity:u,commit:h,project:p,scenarios:f,analysis_branches:y,dependency_analyzed_tree_sha:g,analyzed_tree_sha:x,branch_commit_sha:v,committed_at:b,completed_at:N,created_at:w,updated_at:S,indirect:C,...k}=e,E=u?Yn(u):void 0,A=m?da(m):void 0,I=p?ua(p):void 0,j=h?Qt(h):void 0,P=f?f.map(fi):void 0,$=y?y.map(Ad):void 0,T=$?$.map(R=>R.branch):void 0;return nt({...k,projectId:t,commitId:r,fileId:s,filePath:a,entitySha:o,entityType:i,entityName:c,previousAnalysisId:d,entity:E,file:A,commit:j,project:I,scenarios:P,analysisBranches:$,branches:T,dependencyAnalyzedTreeSha:g,analyzedTreeSha:x,branchCommitSha:v,committedAt:b,completedAt:N,createdAt:w,updatedAt:S,indirect:!!C})}function ma(e){return nt({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?Qt(e.commit):void 0,branch:e.branch?mn(e.branch):void 0})}function Pd(e){const{project_id:t,commit_id:r,created_at:s,updated_at:a,success:o,...i}=e;return nt({...i,projectId:t,commitId:r,createdAt:s,updatedAt:a,success:!!o})}function Qt(e){const{project_id:t,branch_id:r,branch:s,background_jobs:a,merged_branch_id:o,mergedBranch:i,ai_message:c,html_url:d,author:m,analyses:u,entities:h,commit_branches:p,committed_at:f,analyzed_at:y,...g}=e,x=s?mn(s):void 0,v=i?mn(i):void 0,b=(a==null?void 0:a.length)>0?Pd(a[a.length-1]):void 0,N=(u??[]).map(At),w=(h??[]).map(Yn),S=(p==null?void 0:p.length)>0?p.map(ma):void 0;return m&&(m.username=m.preferredUsername??m.username),nt({...g,projectId:t,branchId:r,branch:x,backgroundJob:b,mergedBranchId:o,mergedBranch:v,aiMessage:c,htmlUrl:d,author:m,analyses:N,entities:w,commitBranches:S,committedAt:f,analyzedAt:y})}function mn(e){const{project_id:t,content_changed_at:r,commits:s,analysis_branches:a,active_at:o,created_at:i,updated_at:c,primary:d,...m}=e,u=s?s.map(Qt):void 0,h=a?a.flatMap(p=>At(p.analysis)):void 0;return nt({...m,projectId:t,contentChangedAt:r,commits:u,analyses:h,activeAt:o,createdAt:i,updatedAt:c,primary:!!d})}var Mr;class _d{constructor(){Va(this,Mr,new jd)}transformQuery(t){return Ha(this,Mr).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}Mr=new WeakMap;class jd extends Bc{transformValue(t){return{...super.transformValue(t),value:typeof t.value=="boolean"?t.value?1:0:t.value}}transformPrimitiveValueList(t){return{...t,values:t.values.map(r=>typeof r=="boolean"?r?1:0:r)}}}const ie=()=>null,Md={analyzed_at:ie(),configuration:ie(),content_changed_at:ie(),created_at:ie(),description:ie(),github_token:ie(),id:ie(),metadata:ie(),name:ie(),path:ie(),slug:ie(),team_id:ie(),updated_at:ie()},Td=Object.keys(Md),$d={active:ie(),analysis_id:ie(),branch_id:ie(),created_at:ie(),entity_sha:ie(),id:ie()},Rd=Object.keys($d),Id={active_at:ie(),content_changed_at:ie(),created_at:ie(),id:ie(),metadata:ie(),name:ie(),primary:ie(),project_id:ie(),ref:ie(),sha:ie(),updated_at:ie()},gi=Object.keys(Id),Dd={ai_message:ie(),analyzed_at:ie(),author_github_username:ie(),branch_id:ie(),committed_at:ie(),created_at:ie(),files:ie(),html_url:ie(),id:ie(),merged_branch_id:ie(),message:ie(),metadata:ie(),project_id:ie(),sha:ie(),title:ie(),url:ie()},yi=Object.keys(Dd),Ld=yi.filter(e=>e!=="files"),Od={commit_id:ie(),created_at:ie(),description:ie(),documentation:ie(),entity_type:ie(),file_id:ie(),file_path:ie(),metadata:ie(),name:ie(),project_id:ie(),quality:ie(),sha:ie(),updated_at:ie()},xi=Object.keys(Od),Fd={active:ie(),branch_id:ie(),entity_sha:ie()},zd=Object.keys(Fd),Bd={created_at:ie(),deleted:ie(),id:ie(),metadata:ie(),name:ie(),path:ie(),project_id:ie(),updated_at:ie()},Yd=Object.keys(Bd),Ud={analysis_id:ie(),approved:ie(),created_at:ie(),description:ie(),id:ie(),metadata:ie(),name:ie(),previous_version_id:ie(),project_id:ie()},wr=Object.keys(Ud),Wd=!!Zt("ENABLE_QUERY_LOGGING"),Jd=!!Zt("ENABLE_QUERY_ERROR_LOGGING");Zt("USE_LOCAL_POSTGRESQL_FOR_TESTING");let er;function Te(){if(!er){const e=vi();if(e==="sqlite")er=Hd();else if(e==="postgresql")er=Vd();else throw new Error(`Unknown database type: ${e}`)}return er}function Hd(e){if(e||(e=Zt("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=G.existsSync(e),r=O.dirname(e);if(!G.existsSync(r))G.mkdirSync(r,{recursive:!0,mode:493});else try{G.chmodSync(r,493)}catch(a){console.warn(`Warning: Could not set permissions on database directory: ${a.message}`)}const s=new Oc(e,{readonly:!1,fileMustExist:!1});if(s.pragma("journal_mode = WAL"),s.pragma("busy_timeout = 5000"),s.pragma("synchronous = FULL"),!process.env.CLAUDE_CODE_MODE)try{const a=s.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();t&&a.count===0&&(console.error("CodeYam DB ERROR: Database file existed but projects table is missing!"),console.error("This likely means SQLite created a new empty database instead of opening the existing one."),console.error("Possible causes: corruption, WAL file issues, or file locking problems."))}catch(a){console.error("CodeYam DB ERROR: Failed to verify database schema:",a)}return new ci({dialect:new Uc({database:s}),plugins:[new Yc,new _d],log:bi})}function Vd(){const e=Gd();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new Fc({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,s)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new ci({dialect:new Wc({pool:t}),log:bi})}let gs=null;function en(){return gs||(gs=qd(vi())),gs}function bi(e){e.level==="error"?Jd&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):Wd&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function qd(e){if(e==="sqlite")return Jc;if(e==="postgresql")return Hc;throw new Error(`Unknown database type: ${e}`)}function vi(){if(Zt("SQLITE_PATH"))return"sqlite";if(Zt("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function Gd(){const e=Zt("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function Zt(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}var Ke=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(Ke||{});const Fr="Default Scenario";let Kd="<main>";function Qd(){return Kd}function no(e,...t){Me(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function Me(...e){const t=Qd(),r=e.map(a=>{if(a)return typeof a=="string"?a:a instanceof Error?`${a.name}: ${a.message}
|
|
21
|
+
${a.stack}`:typeof a=="object"?Zd(a):String(a)}).filter(Boolean).join(`
|
|
22
|
+
`),s=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(s+`
|
|
23
|
+
`);return}console.log(s.replace(/\n/g,"\r"))}function Zd(e,t=2){function r(s,a=new WeakMap){return s===null||typeof s!="object"?s:a.has(s)?`"[Circular: ${s.constructor.name}]"`:(a.set(s,!0),Array.isArray(s)?`[${s.map(c=>{const d=r(c,a);return typeof c=="string"?`"${d}"`:d}).join(",")}]`:`{${Object.entries(s).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=r(c,a):typeof c=="string"?d=`"${c.replace(/"/g,'\\"')}"`:d=JSON.stringify(c),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(s){const a=r(e);if(!t)return a;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(o){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:o,pureStringifyError:s,serialized:a}),a}}}function Nr(e,t){try{let r=function(o){var i,c;if(Be.isFunctionDeclaration(o)&&En(o)){const d=((i=o.name)==null?void 0:i.text)||"default",m=o.getText(s),u=ys(o);a.push({name:d,code:m,sha:Ut(t,d,m),entityType:"function",isDefault:u})}else if(Be.isClassDeclaration(o)&&En(o)){const d=((c=o.name)==null?void 0:c.text)||"default",m=o.getText(s),u=ys(o),h=m.includes("React.")||m.includes("jsx")||m.includes("tsx");a.push({name:d,code:m,sha:Ut(t,d,m),entityType:h?"component":"class",isDefault:u})}else if(Be.isInterfaceDeclaration(o)&&En(o)){const d=o.name.text,m=o.getText(s);a.push({name:d,code:m,sha:Ut(t,d,m),entityType:"interface",isDefault:!1})}else if(Be.isTypeAliasDeclaration(o)&&En(o)){const d=o.name.text,m=o.getText(s);a.push({name:d,code:m,sha:Ut(t,d,m),entityType:"type",isDefault:!1})}else if(Be.isVariableStatement(o)&&En(o)){const d=ys(o);o.declarationList.declarations.forEach(m=>{var u;if(Be.isIdentifier(m.name)){const h=m.name.text,p=o.getText(s),f=((u=m.initializer)==null?void 0:u.getText(s))||"",y=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));a.push({name:h,code:p,sha:Ut(t,h,p),entityType:y?"component":"variable",isDefault:d})}})}else if(Be.isExportAssignment(o)){const d=o.getText(s);a.push({name:"default",code:d,sha:Ut(t,"default",d),entityType:"unknown",isDefault:!0})}else if(Be.isExportDeclaration(o)&&o.exportClause&&Be.isNamedExports(o.exportClause)){const d=o.getText(s);for(const m of o.exportClause.elements){const u=m.name.text;a.push({name:u,code:d,sha:Ut(t,u,d),entityType:"unknown",isDefault:!1})}}Be.forEachChild(o,r)};const s=Be.createSourceFile(t,e,Be.ScriptTarget.Latest,!0),a=[];return r(s),a}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function En(e){if(!Be.canHaveModifiers(e))return!1;const t=Be.getModifiers(e);return t?t.some(r=>r.kind===Be.SyntaxKind.ExportKeyword):!1}function ys(e){if(!Be.canHaveModifiers(e))return!1;const t=Be.getModifiers(e);return t?t.some(r=>r.kind===Be.SyntaxKind.DefaultKeyword):!1}function Ut(e,t,r){const s=Bn.createHash("sha256");return s.update(`${e}:${t}:${r}`),s.digest("hex").substring(0,40)}function Xd(e){var m;const{webapp:t,port:r,environmentVariables:s,packageManager:a}=e,o=t==null?void 0:t.startCommand;if(!o)return`${a} ${a==="npm"?"run ":""}dev`;const i=((m=o.args)==null?void 0:m.map(u=>u.replace(/\$PORT/g,String(r))))??[],c=[];for(const u of s)if(u.key&&u.value!==void 0){const h=String(u.value).replace(/'/g,"'\\''");c.push(`${u.key}='${h}'`)}if(o.env)for(const[u,h]of Object.entries(o.env)){const f=String(h).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");c.push(`${u}='${f}'`)}const d=c.length>0?c.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${o.command} ${i.join(" ")}`}function eu(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=O.normalize(e),s=[...t].sort((a,o)=>{var i,c;return(((i=o.path)==null?void 0:i.length)??0)-(((c=a.path)==null?void 0:c.length)??0)});for(const a of s){const o=O.normalize(a.path??".");if(o==="."||r.startsWith(o+O.sep)||r===o)return a}return t[0]}function tu(e){const{filePath:t,webapps:r,environmentVariables:s,port:a,packageManager:o}=e;if(!r||r.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=eu(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const c=Xd({webapp:i,port:a,environmentVariables:s,packageManager:o});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??o,startCommand:c,url:`http://localhost:${a}/static/codeyam-sample`}}function zr(e,t,r=[]){const s=Array.isArray(t)?t:[t];return a=>a.columns(s).doUpdateSet(o=>{const i=Object.keys(e).filter(c=>c!==t&&!r.includes(c));return Object.fromEntries(i.map(c=>[c,o.ref(`excluded.${c}`)]))})}function nu(e){const{jsonObjectFrom:t}=en();return t(e.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",e.ref("commits.author_github_username")))}async function ru({ids:e,analysisId:t}){const r=Te();try{let s=r.deleteFrom("scenarios");if(e){if(e.length===0)return;s=s.where("id","in",e)}else if(t)s=s.where("analysis_id","=",t);else throw Me("CodeYam Error: No deletion criteria provided",null,{ids:e,analysisId:t}),new Error("No deletion criteria provided for scenarios");await s.execute()}catch(s){throw Me("CodeYam Error: Database error deleting scenarios",s,{ids:e,analysisId:t}),s}}function su(...e){try{const t=Bn.createHash("sha256");for(const r of e)t.update(r);return t.digest("hex")}catch(t){throw console.log("CodeYam Error: Error generating sha",e),t}}function xs(e,t){return t.map(r=>au(e,r))}function au(e,t){return it` ${it.ref(e)}.${it.ref(t)}`.as(t)}function ou(e,t,r){return t.map(s=>iu(e,s,r))}function iu(e,t,r){return it` ${it.ref(e)}.${it.ref(t)}`.as(`_cy_${r}:${t}`)}function lu(e,...t){const r={};for(const[s,a]of Object.entries(e)){const o=s.match(/^_cy_(.+?):(.+)$/);if(o){const[,i,c]=o;if(t.includes(i)){r[i]||(r[i]={}),r[i][c]=a;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${s}'`);continue}r[s]=a}return r}const cu=50;function du(e,t){return e.length<=t?[e]:Array.from({length:Math.ceil(e.length/t)},(r,s)=>e.slice(s*t,s*t+t))}function ro({projectId:e,ids:t,fileIds:r,entityName:s,entityShas:a,commitIds:o,branchCommitSha:i,limit:c,excludeMetadata:d}){const m=Te(),{jsonObjectFrom:u,jsonArrayFrom:h}=en();let p=d?m.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"]):m.selectFrom("analyses").selectAll("analyses");if(e&&(p=p.where("project_id","=",e)),t){if(t.length===0)return null;p=p.where("id","in",t)}if(r){if(r.length===0)return null;p=p.where("file_id","in",r)}if(o){if(o.length===0)return null;p=p.where("commit_id","in",o)}return s&&(p=p.where("entity_name","=",s)),a&&(p=p.where("entity_sha","in",a)),i&&(p=p.where("branch_commit_sha","=",i)),c&&(p=p.limit(c)),d?m.with("filtered_analyses",()=>p).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[h(f.selectFrom("scenarios").select(xs("scenarios",wr)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),h(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):m.with("filtered_analyses",()=>p).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select(xs("entities",xi)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),h(f.selectFrom("scenarios").select(xs("scenarios",wr)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),h(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function Lt(e){const{ids:t,fileIds:r,entityShas:s,commitIds:a}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:s,key:"entityShas"},commit_id:{arr:a,key:"commitIds"}}).find(([d,{arr:m}])=>(m==null?void 0:m.length)>0);let c=[];if(i){const[d,{arr:m,key:u}]=i,h=du(m,cu),p=[];for(let f=0;f<h.length;f++){const y=h[f],x=await ro({...e,[u]:y}).execute();x&&p.push(...x)}c=p}else{const m=await ro(e).execute();if(!m||m.length===0)return Me("CodeYam: No analyses found",null,e),null;c=m}return c.length===0?null:c.map(At)}catch(o){return Me("CodeYam Error: Database error in loadAnalyses",o,e),null}}function uu(e,t){const{jsonArrayFrom:r,jsonObjectFrom:s}=en();let a=e.selectFrom("analysis_branches").select(Rd).select(o=>s(o.selectFrom("branches").select(gi).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(a=t(a)),r(a)}async function Pt({id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}){const f=Te(),y=Date.now();try{let g=f.selectFrom("analyses").selectAll("analyses");e&&(g=g.where("id","=",e)),r&&(g=g.where("project_id","=",r)),i?g=g.where("dependency_analyzed_tree_sha","=",i):c?g=g.where("analyzed_tree_sha","=",c):s&&(g=g.where("file_id","=",s)),o&&(g=g.where("entity_name","=",o)),a?g=g.where("commit_id","=",a):g=g.orderBy("created_at","desc").limit(1),t&&(g=g.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:x,jsonArrayFrom:v}=en();g=g.select(w=>{const S=[];return S.push(x(w.selectFrom("entities").select(xi).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&S.push(x(w.selectFrom("files").select(Yd).whereRef("files.id","=","analyses.file_id")).as("file")),m&&S.push(x(w.selectFrom("projects").select(Td).whereRef("projects.id","=","analyses.project_id")).as("project")),h&&S.push(v(w.selectFrom("scenarios").select(wr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),p&&S.push(uu(w,C=>C.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&S.push(x(w.selectFrom("commits").select(yi).select(C=>nu(C).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),S});const b=await g.executeTakeFirst(),N=Date.now()-y;if(!b)return Me("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}),null;if(N>100&&u){const w=b.commit,S=w!=null&&w.files?JSON.stringify(w.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${N}ms (files: ${Math.round(S/1024)}KB)`,{id:b.id,entityName:b.entity_name})}return At(b)}catch(g){return Me("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}),null}}async function wi({projectId:e,ids:t,names:r,includeInactive:s}){const a=Te();try{let o=a.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];o=o.where("id","in",t)}if(r){if(r.length===0)return[];o=o.where("name","in",r)}return s||(o=o.where("active_at","is not",null)),(await o.execute()).map(mn)}catch(o){return Me("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:s}),[]}}async function mu({projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}){const o=Te();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(a,m=>m.select(ou("branches",gi,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),s!==void 0&&(i=i.where("commit_branches.active","=",s));const c=await i.execute();return!c||c.length===0?null:c.map(m=>lu(m,"branch")).map(ma)}catch(i){return Me("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}),null}}async function hu(e){if(e.length===0)return new Map;const t=Te();try{const r=await t.selectFrom("commits").select(["id","branch_id","merged_branch_id"]).where("id","in",e).execute(),s=new Set;if(r.forEach(o=>{o.branch_id&&s.add(o.branch_id),o.merged_branch_id&&s.add(o.merged_branch_id)}),s.size===0)return new Map;const a=await t.selectFrom("branches").selectAll().where("id","in",Array.from(s)).execute();return new Map(a.map(o=>[o.id,o]))}catch(r){return Me("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function pu(e){if(e.length===0)return new Map;const t=Te(),{jsonObjectFrom:r,jsonArrayFrom:s}=en();try{const a=await t.selectFrom("analyses").selectAll("analyses").select(i=>[r(i.selectFrom("files").select(["id","name","path"]).whereRef("files.id","=","analyses.file_id")).as("file"),s(i.selectFrom("scenarios").select(wr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),o=new Map;return a.forEach(i=>{const c=o.get(i.commit_id)||[];c.push(i),o.set(i.commit_id,c)}),o}catch(a){return Me("CodeYam Error: Loading analyses for commits",a,{commitIds:e}),new Map}}async function fu(e){if(e.length===0)return new Map;const t=Te();try{const r=await t.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),s=new Map;return r.forEach(a=>{const o=s.get(a.commit_id)||[];o.push(a),s.set(a.commit_id,o)}),s}catch(r){return Me("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function Cr({projectId:e,branchId:t,ids:r,shas:s,fileNames:a,limit:o=10,skipRelations:i=!1}){if(!e&&!r)throw new Error("Must provide projectId or ids");const c=Te(),{jsonObjectFrom:d}=en(),m=Date.now();try{let u;if(i){const b=Ld.map(N=>`commits.${N}`);u=c.selectFrom("commits").select(b)}else u=c.selectFrom("commits").selectAll("commits").select(b=>[d(b.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",b.ref("commits.author_github_username"))).as("author")]);if(e&&(u=u.where("project_id","=",e)),r){if(r.length===0)return[];u=u.where("id","in",r)}if(s){if(s.length===0)return[];u=u.where("sha","in",s)}if(a&&a.length>0){const b=it.join(a.map(N=>it`${N}`),it`, `);u=u.where(it`
|
|
24
|
+
EXISTS (
|
|
25
|
+
SELECT 1
|
|
26
|
+
FROM json_each(${it.ref("commits.files")}) AS f
|
|
27
|
+
WHERE json_extract(f.value, '$.fileName') IN (${b})
|
|
28
|
+
)
|
|
29
|
+
`)}t&&(u=u.where("branch_id","=",t));const h=await u.orderBy("committed_at","desc").limit(o).execute(),p=Date.now()-m;if(!h||h.length===0)return[];if(p>100){const b=h.reduce((N,w)=>N+(w.files?JSON.stringify(w.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${p}ms (${h.length} commits, totalFiles: ${Math.round(b/1024)}KB)`)}if(i)return h.map(N=>({...N,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(Qt);const f=h.map(b=>b.id),[y,g,x]=await Promise.all([hu(f),pu(f),fu(f)]);return h.map(b=>{const N=b.branch_id?y.get(b.branch_id):void 0,w=b.merged_branch_id?y.get(b.merged_branch_id):void 0,S=g.get(b.id)||[],C=x.get(b.id)||[];return{...b,branch:N,mergedBranch:w,analyses:S,entities:C}}).map(Qt)}catch(u){return Me("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:t,ids:r,shas:s,limit:o}),[]}}async function lt({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:o,excludeMetadata:i}){if(r&&r.length==0||s&&s.length==0||a&&a.length==0||o&&o.length==0)return[];if(o&&o.length>50){const d=[];for(let m=0;m<o.length;m+=50){const u=o.slice(m,m+50),h=await lt({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:u,excludeMetadata:i});h&&d.push(...h)}return d}const c=Te();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(!!t,h=>h.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,h=>h.where("entities.project_id","=",e)).$if(!!o,h=>h.where("entities.sha","in",o)).$if(!!s,h=>h.where("entities.file_path","in",s)).$if(!!a,h=>h.where("entities.name","in",a)).$if(!!r,h=>h.where("entities.file_id","in",r)).execute();return!u||u.length===0?(console.log("Load Entities: No entities found",{projectId:e,fileIds:r,filePaths:s,shas:o}),null):u.map(Yn)}catch(d){return console.log("Load Entities: Error occurred",d,{projectId:e,fileIds:r,filePaths:s,shas:o}),null}}function gu(e,t){const{jsonArrayFrom:r}=en();let s=e.selectFrom("entity_branches").select(zd);return t&&(s=t(s)),r(s)}async function Ni({projectId:e,sha:t}){const r=Te();try{const s=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(a=>gu(a,o=>o.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return s?Yn(s):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&Me("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:t}),null)}catch(s){return Me("CodeYam Error: Load Entity: Database error",s,{projectId:e,sha:t}),null}}const bs=1e3;async function Ci({projectId:e,filePaths:t,fileIds:r,fileNames:s}){if(t&&t.length>50){const c=[];for(let d=0;d<t.length;d+=50){const m=t.slice(d,d+50),u=await Ci({projectId:e,filePaths:m,fileIds:r,fileNames:s});u&&c.push(...u)}return c}const a=Te(),o=[];let i=0;try{for(;;){let c=a.selectFrom("files").selectAll().where("project_id","=",e).limit(bs).offset(i);if(t){if(t.length===0)return[];c=c.where("path","in",t)}if(r){if(r.length===0)return[];c=c.where("id","in",r)}if(s){if(s.length===0)return[];c=c.where("name","in",s)}const d=await c.execute();if(!d||d.length===0||(o.push(...d),d.length<bs))break;i+=bs}return o==null?void 0:o.map(da)}catch(c){return console.log("CodeYam Error: Error loading project files in loadFiles",c),null}}async function yu({id:e,slug:t,withBranches:r,withFiles:s,silent:a}){try{let i=Te().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(t)i=i.where("slug","=",t);else throw new Error("Either id or slug must be provided");const c=await i.executeTakeFirst();if(!c)return a||console.log("CodeYam Error: Error loading project",{id:e,slug:t,withBranches:r,withFiles:s}),null;const d=ua(c);return s&&(d.files=await Ci({projectId:d.id})),r&&(d.branches=await wi({projectId:d.id,includeInactive:!1})),d}catch(o){return a||console.log("CodeYam Error: Error loading project",o),null}}function Sr(e,t){const r={...e};for(const s in t){const a=t[s],o=e[s];a!=null&&typeof a=="object"&&!Array.isArray(a)&&o!==void 0&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[s]=Sr(o,a):a!==void 0&&(r[s]=a)}return r}async function It({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:s,archiveCurrentRun:a,updateCallback:o}){for(let d=0;d<=4;d++)try{return await Te().transaction().execute(async m=>{var f,y;const u=await m.selectFrom("commits").select(["id","metadata"]).$if(!!e,g=>g.where("id","=",e)).$if(!!t,g=>g.where("sha","=",t)).executeTakeFirst();if(!u)return Me(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const h=u.metadata||{};if(s)s.lastUpdatedAt??(s.lastUpdatedAt=new Date().toISOString()),s.currentEntityShas!==void 0&&(console.log("[updateCommitMetadata] Updating currentRun.currentEntityShas"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Previous entity SHAs:",(f=h.currentRun)==null?void 0:f.currentEntityShas),console.log("[updateCommitMetadata] New entity SHAs:",s.currentEntityShas),console.log("[updateCommitMetadata] Archive flag:",a)),r=Sr(r??{},{currentRun:s});else if(!r&&!o)return h;const p=r?Sr(h,r):h;if(a&&p.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Current run entity SHAs:",p.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${p.currentRun.analyzerPid}, capture=${p.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${p.currentRun.analysesCompleted}, captures=${p.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${((y=p.historicalRuns)==null?void 0:y.length)||0}`);const g={...p.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(g,null,2)),p.historicalRuns=[...p.historicalRuns||[],g],console.log(`[updateCommitMetadata] Historical runs after archiving: ${p.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(p.historicalRuns.map(x=>({entityShas:x.currentEntityShas,archivedAt:x.archivedAt,completed:{analyses:x.analysesCompleted,captures:x.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}o&&await o(p);try{return await m.updateTable("commits").set({metadata:JSON.stringify(p)}).where("id","=",u.id).returning(["id"]).executeTakeFirst()?p:(Me(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),h)}catch(g){return Me(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,g),h}})}catch(m){const u=m instanceof Error&&m.message.includes("database is locked");if(u&&d<4){const h=250*Math.pow(2,d);await new Promise(p=>setTimeout(p,h));continue}return Me(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}${u?` after ${d+1} attempts`:""}`,m),null}return null}async function Si(e,t,r="analysis"){try{return await Te().transaction().execute(async s=>{const a=await s.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!a)return Me(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=At(a);return t(o.metadata,o),await s.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(Me(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(s){return Me(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,s,{analysisId:e,source:r}),null}}async function gn(e,t,r="capture"){for(let o=0;o<=4;o++)try{return await Te().transaction().execute(async i=>{const c=await i.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!c)return Me(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const d=At(c);return t(d.status,d),await i.updateTable("analyses").set({status:JSON.stringify(d.status)}).where("id","=",e).returningAll().executeTakeFirst()?d.status:(Me(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(i){const c=i instanceof Error&&i.message.includes("database is locked");if(c&&o<4){const d=250*Math.pow(2,o);await new Promise(m=>setTimeout(m,d));continue}return Me(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})${c?` after ${o+1} attempts`:""}`,i,{analysisId:e,source:r}),null}return null}async function hn({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:s}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await Te().transaction().execute(async a=>{const o=await a.selectFrom("projects").selectAll().$if(!!e,d=>d.where("id","=",e)).$if(!!t,d=>d.where("slug","=",t)).executeTakeFirst();if(!o)return Me(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!s)return i;const c=r?Sr(i,r):i;s&&await s(c,ua(o));try{return await a.updateTable("projects").set({metadata:JSON.stringify(c)}).where("id","=",o.id).returningAll().executeTakeFirst()?c:(Me(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return Me(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(a){return Me(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,a),null}}const xu=()=>crypto.randomUUID();function bu(e){const{id:t,projectId:r,analysisId:s,previousVersionId:a,analysis:o,metadata:i,data:c,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:t??xu(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:s,previous_version_id:a}}async function vu(e){if(e.length===0)return[];const t=Te(),r=e.map(bu);try{return(await t.insertInto("scenarios").values(r).onConflict(zr(r[0],"id",["created_at"])).returningAll().execute()).map(fi)}catch(s){return Me("CodeYam Error: Database error upserting scenarios",s,{scenarioCount:e.length}),null}}const wu=()=>crypto.randomUUID();function Nu(e){const{id:t,commitId:r,branchId:s,...a}=e;return delete a.commit,delete a.branch,{...a,id:t??wu(),commit_id:r,branch_id:s}}async function so(e){if(e.length===0)return[];const t=Te(),r=e.map(Nu);try{return(await t.insertInto("commit_branches").values(r).onConflict(zr(r[0],"id",["created_at"])).returningAll().execute()).map(ma)}catch(s){return Me("CodeYam Error: Database error upserting commit branches",s,{commitBranchCount:e.length,commitBranchIds:e.map(a=>a.id)}),[]}}async function Cu(e,t){const r=Te(),s={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(s).onConflict(zr(s,"username",[])).returningAll().executeTakeFirst()||null}catch(a){return Me("CodeYam Error: Error upserting github user",a,{username:e,avatarUrl:t}),null}}const Su=()=>crypto.randomUUID();function ku(e,t){const{id:r,projectId:s,branchId:a,mergedBranchId:o,aiMessage:i,htmlUrl:c,analyzedAt:d,committedAt:m,author:u,metadata:h,files:p,...f}=e;return delete f.branch,delete f.mergedBranch,delete f.backgroundJob,delete f.analyses,delete f.parents,delete f.entities,delete f.commitBranches,{...f,id:r??Su(),project_id:s??String(t),metadata:h?JSON.stringify(h):void 0,files:p?JSON.stringify(p):void 0,branch_id:a,merged_branch_id:o,author_github_username:u==null?void 0:u.username,html_url:c,ai_message:i,analyzed_at:d,committed_at:m}}async function Eu({projectId:e,commits:t}){const r=Te();try{const s=t.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 s)await Cu(i,s[i]);const a=t.map(i=>ku(i,e));return(await r.insertInto("commits").values(a).onConflict(zr(a[0],"id",["created_at"])).returningAll().execute()).map(Qt)}catch(s){return Me("CodeYam Error: Error saving commits",s,{projectId:e,commitCount:t.length,commitIds:t.map(a=>a.id).filter(Boolean)}),[]}}const kr=O.join(na.homedir(),".codeyam","secrets.json"),Er=O.join(process.cwd(),".codeyam","secrets.json");async function zt(){let e={};try{if(G.existsSync(Er)){const o=await we.readFile(Er,"utf8");e=JSON.parse(o)}}catch{console.warn(vr.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(G.existsSync(kr)){const o=await we.readFile(kr,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(vr.yellow("⚠ Could not read home secrets file, falling back to environment variables"))}const t={},r=e.OPENAI_API_KEY||process.env.OPENAI_API_KEY;r&&(t.OPENAI_API_KEY=r);const s=e.ANTHROPIC_API_KEY||process.env.ANTHROPIC_API_KEY;s&&(t.ANTHROPIC_API_KEY=s);const a=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return a&&(t.GROQ_API_KEY=a),t}async function Au(e,t=!0){const r=t?kr:Er,s=O.dirname(r);await we.mkdir(s,{recursive:!0}),await we.writeFile(r,JSON.stringify(e,null,2)),await we.chmod(r,384)}function Pu(e=!0){return e?kr:Er}async function ao(){const e=await zt(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function _u(e){console.log(),console.log(vr.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const s=await qc({type:"password",name:"key",message:"OpenAI API Key",validate:a=>a&&!a.startsWith("sk-")?"OpenAI API key should start with sk-":!0});s.key&&(t.OPENAI_API_KEY=s.key);break}return t}async function ju(e=!0){const t=await ao();if(t.isValid)return t.secrets;const r=await _u(t.missing),a={...await zt(),...r};await Au(a,e);const o=Pu(e);return console.log(vr.green(`✓ Configuration saved to ${o}`)),(await ao()).secrets}function Mu(e){const t=O.resolve(e),r=O.parse(t).root;return t===r||t===O.resolve(na.homedir())}function ki(e=process.cwd()){let t=O.resolve(e);const r=O.parse(t).root;for(;t!==r;){if(Mu(t))return null;const s=O.join(t,".codeyam","config.json");if(G.existsSync(s))return t;t=O.dirname(t)}return null}let Ei=ki();function he(){return Ei}function Tu(e){Ei=e}function Ai(e){const t={...e};for(const r in e)if(r.includes(".")){const s=r.replace(/\./g,"");t[s]=e[r]}return t}const $u={"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>`};Ai($u);const Ru={"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>`};Ai(Ru);function Mn(e,t,r=new WeakSet){if(!t)return e;if(!e)return t;try{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference detected during deep merge");r.add(t)}if(Array.isArray(t)){const a=Array.isArray(e)?e:[],o=[];for(let i=0;i<t.length;i++){const c=t[i];c&&typeof c=="object"&&!Array.isArray(c)||Array.isArray(c)?o[i]=Mn(a[i],c,r):o[i]=c}return o}const s={...e};for(const a in t)if(t[a]===null)s[a]=null;else if(Array.isArray(t[a])){const o=Array.isArray(e[a])?e[a]:[];s[a]=[];for(let i=0;i<t[a].length;i++){const c=t[a][i];typeof c=="object"&&c!==null?s[a][i]=Mn(o[i],c,r):s[a][i]=c}}else typeof t[a]=="object"&&t[a]!==null?s[a]=Mn(s[a]??{},t[a],r):s[a]=t[a];return s}catch(s){throw console.log("CodeYam: Error merging data",e,t),s}}async function Iu({projectId:e,commit:t,branch:r}){var c,d,m,u,h,p,f;let s;const a={commitId:t.id,branchId:r.id,active:!0},o=await mu({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){s=(c=o.sort((g,x)=>{var v,b,N,w;return(((b=(v=g.branch.metadata)==null?void 0:v.permanent)==null?void 0:b.order)??999)-(((w=(N=x.branch.metadata)==null?void 0:N.permanent)==null?void 0:w.order)??999)})[0])==null?void 0:c.branch,s&&((m=(d=r.metadata)==null?void 0:d.permanent)==null?void 0:m.order)!==void 0&&(((h=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:h.order)<=((f=(p=s.metadata)==null?void 0:p.permanent)==null?void 0:f.order)?s=r:a.active=!1);const y=o.filter(g=>g.active&&g.branch.id!==s.id||!g.active&&g.branch.id===s.id);y.length>0&&await so(y.map(g=>({...g,active:g.branchId===s.id})))}(o==null?void 0:o.find(y=>y.branchId===a.branchId))||await so([a])}function Bt(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=he();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return ee.join(e,".codeyam","db.sqlite3")}async function Ye(){const e=await ju();process.env.SQLITE_PATH=Bt(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Ie(e){await Ye();const t=await yu({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await wi({projectId:t.id,names:["_local"]}),s=r==null?void 0:r[0];if(!s)throw new Error(`Local development branch not found for project "${e}". Please run "codeyam init" to set up local analysis.`);return{project:t,branch:s}}async function Du(e,t,r){await Ye();const s=he(),a=su(`${e.slug}-local-${Date.now()}-${Math.random()}`),o=r.map(d=>{let m="";if(s)try{if(m=Pe(`git diff HEAD -- "${d}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!m)try{const u=Pe(`cat "${d}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const h=u.split(`
|
|
30
|
+
`);m=`@@ -0,0 +1,${h.length} @@
|
|
31
|
+
${h.map(p=>`+${p}`).join(`
|
|
32
|
+
`)}`}}catch{}}catch{}return{fileName:d,status:"modified",patch:m}}),i={sha:a,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${a}`,htmlUrl:`local://codeyam/${e.slug}/${a}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:o,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},c=await Eu({projectId:e.id,commits:[i]});if(!c||c.length===0)throw new Error("Failed to create fake commit");return await Iu({projectId:e.id,commit:c[0],branch:t}),c[0]}async function tn(){await Ye();const e=await lt({excludeMetadata:!0});if(!e||e.length===0)return[];const t=new Map;for(const d of e){const m=`${d.name}::${d.filePath}`,u=t.get(m);(!u||d.createdAt&&u.createdAt&&d.createdAt>u.createdAt)&&t.set(m,d)}const r=[...t.values()],s=e.map(d=>d.sha),a=await Lt({entityShas:s,excludeMetadata:!0}),o=new Map;if(a)for(const d of a)o.has(d.entitySha)||o.set(d.entitySha,[]),o.get(d.entitySha).push(d);const i=new Map;for(const d of e){const m=`${d.name}::${d.filePath}`,u=i.get(m)||[];u.push(d.sha),i.set(m,u)}return r.map(d=>{const m=o.get(d.sha)||[];if(m.length>0)return{...d,analyses:m};const u=`${d.name}::${d.filePath}`,h=i.get(u)||[];for(const p of h){if(p===d.sha)continue;const f=o.get(p);if(f&&f.length>0)return{...d,analyses:f}}return{...d,analyses:[]}})}async function Br(e,t){await Ye();const r=await Lt({entityShas:[e],limit:1});if(r&&r.length>0&&t){const s=await Ni({projectId:r[0].projectId,sha:e});if(s)for(const a of r)a.entity=s}return r||[]}async function Yr(e){if(await Ye(),e.name&&e.projectId){const r=await Lt({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const s=r.filter(o=>{const i=o.scenarios&&o.scenarios.length>0,c=!e.filePath||o.filePath===e.filePath;return i&&c});if(s.length>0)return s.sort((o,i)=>{const c=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),s[0];const a=r.filter(o=>o.scenarios&&o.scenarios.length>0);if(a.length>0)return a.sort((o,i)=>{const c=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),a[0]}}const t=await Lt({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function Pi(e){await Ye();const t=await Lt({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function Xt(e){await Ye();const t=await $e();if(!t)return null;const{project:r}=await Ie(t);return await Ni({projectId:r.id,sha:e})}async function _i(e){var s,a,o,i,c,d,m,u;await Ye();const t=[],r=[];if((s=e.metadata)!=null&&s.importedExports&&e.metadata.importedExports.length>0){const h=e.metadata.importedExports;for(const p of h){if(!p.filePath||!p.name)continue;const f=p.resolvedFilePath??p.filePath,y=p.resolvedName??p.name;let g=await lt({projectId:e.projectId,filePaths:[f],names:[y]});if((!g||g.length===0)&&p.resolvedIsDefault&&(g=await lt({projectId:e.projectId,filePaths:[f],names:["default"]})),g&&g.length>0){const x=g[0],v=await Lt({entityShas:[x.sha],limit:1});let b,N,w;if(v&&v.length>0&&v[0].scenarios){const S=v[0],C=S.scenarios||[],k=C.length,E=C.find(I=>{var j,P;return(P=(j=I.metadata)==null?void 0:j.screenshotPaths)==null?void 0:P[0]});E&&(b=(o=(a=E.metadata)==null?void 0:a.screenshotPaths)==null?void 0:o[0],N=E.name),w={status:((i=x.metadata)==null?void 0:i.previousVersionWithAnalyses)||S.entitySha!==x.sha?"out_of_date":"up_to_date",scenarioCount:k,timestamp:S.createdAt?new Date(S.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else w={status:"not_analyzed"};t.push({...x,screenshotPath:b,scenarioName:N,analysisStatus:w})}}}if((c=e.metadata)!=null&&c.importedBy){const h=[];for(const p in e.metadata.importedBy)for(const f in e.metadata.importedBy[p]){const y=e.metadata.importedBy[p][f];y.shas&&h.push(...y.shas)}if(h.length>0){const p=await lt({projectId:e.projectId,shas:h});if(p)for(const f of p){const y=await Lt({entityShas:[f.sha],limit:1});let g,x,v;if(y&&y.length>0&&y[0].scenarios){const b=y[0],N=b.scenarios||[],w=N.length,S=N.find(k=>{var E,A;return(A=(E=k.metadata)==null?void 0:E.screenshotPaths)==null?void 0:A[0]});S&&(g=(m=(d=S.metadata)==null?void 0:d.screenshotPaths)==null?void 0:m[0],x=S.name),v={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||b.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:w,timestamp:b.createdAt?new Date(b.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else v={status:"not_analyzed"};r.push({...f,screenshotPath:g,scenarioName:x,analysisStatus:v})}}}return{importedEntities:t,importingEntities:r}}async function $e(){try{const e=he();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await xe.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function yn(){await Ye();try{const e=await $e();if(!e)return null;const{project:t,branch:r}=await Ie(e),s=await Cr({projectId:t.id,branchId:r.id,limit:1,skipRelations:!0});return s&&s.length>0?s[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function Ur(){try{const e=he();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await xe.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function ji(e){try{const t=he();if(!t)return console.error("[getEntityCodeFromFilesystem] No project root found"),null;if(!e.filePath)return console.error("[getEntityCodeFromFilesystem] Entity has no filePath"),null;const r=ee.join(t,e.filePath);return await xe.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function Mi(e){try{const t=he();if(!t||!e.filePath)return!1;const r=ee.join(t,e.filePath),a=(await xe.stat(r)).mtime.getTime(),o=e.updatedAt||e.createdAt;if(!o)return!1;const i=new Date(o).getTime();return a>i+1e3}catch{return!1}}async function Ti(e){if(await Ye(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await lt({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),s=await Lt({entityShas:r}),a=new Map;if(s)for(const i of s)a.has(i.entitySha)||a.set(i.entitySha,[]),a.get(i.entitySha).push(i);for(const[i,c]of a.entries())c.sort((d,m)=>{const u=new Date(d.createdAt||0).getTime();return new Date(m.createdAt||0).getTime()-u});const o=t.map(i=>({...i,analyses:a.get(i.sha)||[]}));return o.sort((i,c)=>{var u,h;const d=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",m=((h=c.analyses[0])==null?void 0:h.createdAt)||c.createdAt||"";return new Date(m).getTime()-new Date(d).getTime()}),o}async function $i(e){try{const t=he();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=ee.join(t,".codeyam","config.json"),s=await xe.readFile(r,"utf8"),a=JSON.parse(s),o={...a,...e},i=JSON.stringify(o,null,2);if(await xe.writeFile(r,i,"utf8"),a.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 hn({projectSlug:a.projectSlug,metadataUpdate:c})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const Lu=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:tn,getAnalysesForEntity:Br,getAnalysisForExactEntitySha:Pi,getCurrentCommit:yn,getEntityBySha:Xt,getEntityCodeFromFilesystem:ji,getEntityHistory:Ti,getLatestAnalysisForEntity:Yr,getProjectConfig:Ur,getProjectSlug:$e,getRelatedEntities:_i,hasFileBeenModifiedSinceEntity:Mi,requireBranchAndProject:Ie,updateProjectConfig:$i},Symbol.toStringTag,{value:"Module"})),Ri="secrets.json";function Ii(e){return ee.join(e,".codeyam",Ri)}function Di(){return ee.join(Os.homedir(),".codeyam",Ri)}async function Wr(e){let t={};try{const r=Di(),s=await xe.readFile(r,"utf-8");t=JSON.parse(s)}catch{}try{const r=Ii(e),s=await xe.readFile(r,"utf-8"),a=JSON.parse(s);t={...t,...a}}catch{}return t}async function Ou(e,t,r=!0){const s=r?Di():Ii(e),a=ee.dirname(s);await xe.mkdir(a,{recursive:!0}),await xe.writeFile(s,JSON.stringify(t,null,2)+`
|
|
33
|
+
`,"utf-8")}async function Fu(e){const t=await Wr(e);return!!(t.ANTHROPIC_API_KEY&&t.ANTHROPIC_API_KEY.length>0)||!!(t.OPENAI_API_KEY&&t.OPENAI_API_KEY.length>0)||!!(t.GROQ_API_KEY&&t.GROQ_API_KEY.length>0)||!!(t.OPENROUTER_API_KEY&&t.OPENROUTER_API_KEY.length>0)}const zu=3;let An=0;async function tr(e){if(!e||e.length===0)return[];if(An>=zu)return console.warn(`[Loader] Circuit breaker open (${An} consecutive timeouts), skipping entity fetch for ${e.length} entities`),[];const t=Math.min(Math.max(e.length*2e3,1e4),6e4);return new Promise(r=>{let s=!1;const a=setTimeout(()=>{s||(s=!0,An++,console.warn(`[Loader] Entity fetch timeout after ${t}ms for ${e.length} entities`),r([]))},t);lt({shas:e,excludeMetadata:!0}).then(o=>{s||(s=!0,clearTimeout(a),An=0,r(o||[]))}).catch(()=>{s||(s=!0,clearTimeout(a),An++,r([]))})})}function Bu({sourcePath:e,destinationPath:t,excludes:r,silent:s}){if(process.platform!=="darwin")return!1;if(Rt(t))try{if(zc(t).length>0)return!1;hs(t,{recursive:!0})}catch{return!1}try{Pe(`cp -c -R "${e}" "${t}"`,{stdio:"pipe",timeout:3e5});for(const a of r)if(a.includes("*"))try{Pe(`rm -rf "${Xa(t,a)}"`,{stdio:"pipe",shell:"/bin/sh"})}catch{}else{const o=Xa(t,a);Rt(o)&&hs(o,{recursive:!0,force:!0})}return s||console.log(`Directory cloned (APFS CoW) from ${e} to ${t}`),!0}catch{if(Rt(t))try{hs(t,{recursive:!0})}catch{}return!1}}async function Yu({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:s=!1,silent:a=!1,extraArgs:o=[]}){const i=Date.now();if(!s&&o.length===0&&Bu({sourcePath:e,destinationPath:t,excludes:r,silent:a})){if(!a){const d=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${d}s]`)}return}return new Promise((c,d)=>{const m=e.endsWith("/")?e:`${e}/`,u=t.endsWith("/")?t:`${t}/`,h=["-a","--no-specials"];s||h.push("--delete","--force"),h.push(...o);for(const f of r)h.push(`--exclude=${f}`);h.push(m,u);const p=kt("rsync",h);p.on("exit",f=>{if(f===0){if(!a){const y=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${y}s]`)}c()}else console.error(`CodeYam Error: rsync failed with code: ${f}`,JSON.stringify({rsyncArgs:h},null,2)),d(new Error(`rsync failed with exit code ${f}`))}),p.on("error",f=>{a||console.log("Error occurred:",f),d(f)})})}const Uu=aa(sa);async function Wu(e){return new Promise(t=>setTimeout(t,e))}function Ju(e){try{return process.kill(e,0),!0}catch{return!1}}async function Li(e){try{const{stdout:t}=await Uu(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
|
|
34
|
+
`).filter(a=>a.trim()).map(a=>parseInt(a.trim(),10)).filter(a=>!isNaN(a)),s=[...r];for(const a of r){const o=await Li(a);s.push(...o)}return s}catch{return[]}}function oo(e,t,r){try{process.kill(e,t)}catch(s){r==null||r(`Error sending ${t} to process ${e}: ${s}`)}}async function Hu(e,t,r){const s=await Li(e);for(const a of s.reverse())await oo(a,t,r);await oo(e,t,r)}async function Dn(e,t=console.log,r=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let s=0;async function a(o,i){await Hu(e,o,t);for(let c=0;c<i;c++)if(await Wu(1e3),s+=1e3,!await Ju(e))return t(`Process tree ${e} successfully killed with ${o} after ${s/1e3} seconds.`),!0;return t(`Process tree still running after ${o}...`),!1}if(await a("SIGINT",5)||await a("SIGTERM",5))return!0;for(let o=0;o<r;o++)if(await a("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${s/1e3} seconds.`),!1}function Vu(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:cd(),createdAt:t}}Qc.config({quiet:!0});var Oi=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(Oi||{});class qu extends Zc{constructor(){super(...arguments),this.processes=new Map}register(t){const r=Xc(),{process:s,type:a,name:o,metadata:i,parentId:c}=t,d={id:r,type:a,name:o,pid:s.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:c,children:[]};if(this.processes.set(r,{info:d,process:s}),c){const h=this.processes.get(c);h&&(h.info.children=h.info.children||[],h.info.children.push(r))}const m=(h,p)=>{this.handleProcessExit(r,h,p)},u=h=>{this.handleProcessError(r,h)};return s.on("exit",m),s.on("error",u),s.__cleanup=()=>{s.removeListener("exit",m),s.removeListener("error",u)},this.emit("processStarted",d),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const s=this.processes.get(t);if(!s)throw new Error(`Process not found: ${t}`);const{info:a,process:o}=s;if(a.state==="completed"||a.state==="failed"||a.state==="killed")return;if(r.shutdownChildren&&a.children&&a.children.length>0&&await Promise.all(a.children.map(c=>this.shutdown(c,r))),o.pid)try{await Dn(o.pid,c=>console.log(`[Process ${t}] ${c}`))}catch(c){console.warn(`Error killing process ${t}:`,c)}await new Promise(c=>setTimeout(c,100)),a.state==="running"&&(a.state="killed",a.endedAt=Date.now());const i=o.__cleanup;i&&i()}async shutdownByType(t,r={}){const s=this.listByType(t);await Promise.all(s.map(a=>this.shutdown(a.id,r)))}async shutdownAll(t={}){const r=this.listAll();await Promise.all(r.map(s=>this.shutdown(s.id,t)))}cleanupCompleted(t={}){const{retentionMs:r=6e4}=t,s=Date.now();for(const[a,o]of this.processes.entries()){const{info:i}=o;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&s-i.endedAt>r){const c=o.process.__cleanup;c&&c(),this.processes.delete(a)}}}handleProcessExit(t,r,s){const a=this.processes.get(t);if(!a)return;const{info:o}=a;o.endedAt=Date.now(),o.exitCode=r,o.signal=s,r===0?o.state="completed":s?o.state="killed":o.state="failed",this.emit("processExited",o)}handleProcessError(t,r){const s=this.processes.get(t);if(!s)return;const{info:a}=s;a.endedAt=Date.now(),a.state="failed",a.metadata={...a.metadata,error:r.message},this.emit("processExited",a)}}let vs=null;function Gu(){return vs||(vs=new qu),vs}const Ku={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function Qu({command:e,args:t,workingDir:r,outputOptions:s=Ku,processName:a,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${a}`},c=kt(e,t,{cwd:r,env:i});return Gu().register({process:c,type:Oi.Other,name:a,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const h=f=>{const y=ee.join(r,"log.txt");G.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(v=>v.trim()?`[${g}]${y} ${v}`:v).join(`
|
|
36
|
+
`)};c.stdout.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=p(y);s.stdoutToConsole&&console.log(g),s.stdoutToFile&&h(g+`
|
|
37
|
+
`),s.stdoutCallback&&s.stdoutCallback(y)}),c.stderr.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=p(y,"<STDERR>");s.stderrToConsole&&console.error(g),s.stderrToFile&&h(g+`
|
|
38
|
+
`),s.stderrCallback&&s.stderrCallback(y)}),c.on("exit",function(f){u(f)})}),process:c}}function Zu(e){const t=[];return Object.keys(e).forEach(r=>{const s=e[r];s!==void 0&&(typeof s=="boolean"?s&&t.push(`--${r}`):s!==null&&t.push(`--${r}`,String(s)))}),t}function Xu({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:s}){const a=Object.entries(t).map(([i,c])=>`${i}=${c}`).join(`
|
|
39
|
+
`);G.writeFileSync(`${e}/.env`,a);const o=Zu(r);return Qu({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:s,processName:"analyzer",env:t})}const em="/tmp/codeyam/local-dev";function Fi(e){return O.join(em,e)}function zi(e){return O.join(Fi(e),"codeyam")}function pt(e){return O.join(Fi(e),"project")}function Jr(e){return O.join(zi(e),"log.txt")}const tm=[".sync-metadata.json","__codeyamMocks__"];async function nm(e,t={}){const{port:r,silent:s=!0}=t,a=pt(e);if(r)try{Pe(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}try{Pe(`lsof +D "${a}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}await new Promise(o=>setTimeout(o,500))}async function rm(e,t={}){const{killProcesses:r=!0,port:s,silent:a=!0}=t,o=pt(e),i=[],c=[];if(!G.existsSync(o))return{removed:i,errors:c};r&&await nm(e,{port:s,silent:a});for(const d of tm){const m=O.join(o,d);if(G.existsSync(m))try{(await we.stat(m)).isDirectory()?await we.rm(m,{recursive:!0,force:!0}):await we.unlink(m),i.push(d)}catch(u){c.push(`${d}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:c}}const sm=O.dirname(Ir(import.meta.url));function am(e){let t=e;for(;t!==O.dirname(t);){const r=O.join(t,"package.json");if(G.existsSync(r))try{if(JSON.parse(G.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=O.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function Hr(){const e=am(sm);return O.join(e,"analyzer-template")}function xn(e){return zi(e)}function om(){const e=Hr();return G.existsSync(O.join(e,".finalized"))}async function io(e){const t=Hr(),r=xn(e);if(!G.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await we.mkdir(O.dirname(r),{recursive:!0}),await Yu({sourcePath:t,destinationPath:r,silent:!0})}function bn(e,t,r,s){const a=xn(e);if(!G.existsSync(a))throw new Error(`Analyzer not found at ${a}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const o=void 0;return Xu({absoluteCodeyamRootPath:a,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function im(e){const t=Hr(),r=xn(e),s=O.join(t,".build-info.json"),a=O.join(r,".build-info.json");if(!G.existsSync(s))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!G.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!G.existsSync(a))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(G.readFileSync(s,"utf8")),i=JSON.parse(G.readFileSync(a,"utf8"));return o.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${o.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(o){return{isFresh:!1,reason:`Error reading build markers: ${o.message}`}}}async function Un(e,t){const r=xn(e);if(!G.existsSync(r)){t.update("Creating analyzer..."),await io(e);return}const s=im(e);s.isFresh||(t.update(`Updating analyzer (${s.reason})...`),await io(e))}async function ha(e){await rm(e,{killProcesses:!1})}const lm=O.dirname(Ir(import.meta.url));function Vr(){let e=lm;for(;e!==O.dirname(e);){const t=O.join(e,"package.json");if(G.existsSync(t))try{if(JSON.parse(G.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=O.dirname(e)}return null}function un(e){if(!G.existsSync(e))return null;try{return JSON.parse(G.readFileSync(e,"utf8"))}catch{return null}}function cm(){const e=Vr();if(e){const t=[O.join(e,"src/webserver/build-info.json"),O.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const s=un(r);if(s!=null&&s.semanticVersion)return s.semanticVersion}}return"unknown"}function dm(){const e=Vr();if(e){const t=O.join(e,"package.json");try{const r=JSON.parse(G.readFileSync(t,"utf8"));if(r.version)return r.version}catch{}}return"unknown"}const pa=cm(),ws=dm();function fa(){if(ws!=="unknown"&&ws!=="0.1.0")return ws;const e=Vr();if(e)for(const t of[O.join(e,"src/webserver/build-info.json"),O.join(e,"codeyam-cli/src/webserver/build-info.json")]){const r=un(t);if(r!=null&&r.buildNumber)return`dev (build ${r.buildNumber})`}return"dev"}function Bi(e){const t=Vr();let r=null;if(t){const d=[O.join(t,"src/webserver/build-info.json"),O.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const m of d)if(r=un(m),r)break}const s=Hr(),a=O.join(s,".build-info.json"),o=un(a);let i=null;if(e){const d=xn(e),m=O.join(d,".build-info.json");i=un(m)}let c=!1;return o&&i?c=o.buildTime>i.buildTime:o&&!i&&e&&(c=!0),{cliVersion:pa,webserverVersion:r,templateVersion:o,cachedAnalyzerVersion:i,isCacheStale:c}}function qr(e){const t=xn(e),r=O.join(t,".build-info.json"),s=un(r);return(s==null?void 0:s.version)??null}function Yi(){const e=he();return e?O.join(e,".codeyam","server.json"):null}function Ui(){const e=Yi();if(!e||!G.existsSync(e))return null;try{const t=G.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function um(){const e=Yi();if(e)try{G.unlinkSync(e)}catch{}}const mm="/assets/globals-h1-1oFYI.css";function lo({text:e,subtext:t,linkText:r,linkTo:s}){const[a,o]=_(!1);return a?null:n("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:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),l("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(de,{to:s,className:"shrink-0 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 transition-colors",children:r})]}),n("button",{type:"button",onClick:()=>o(!0),className:"shrink-0 ml-4 p-1 rounded text-blue-600 hover:text-blue-800 hover:bg-blue-100 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}function hm({version:e}){return n("div",{className:"px-6 sm:px-12 pb-8 mt-auto pt-8",children:l("div",{className:"border-t border-cygray-30 pt-6 flex flex-wrap justify-between items-center gap-4",children:[l("div",{className:"flex items-center gap-3",children:[n("span",{className:"font-mono text-sm font-semibold tracking-widest text-cyblack-100",children:"CODEYAM"}),e&&n("span",{className:"font-mono text-xs text-gray-400",children:e})]}),l("div",{className:"flex items-center gap-4 font-mono text-xs uppercase tracking-widest",children:[n("a",{href:"https://blog.codeyam.com/",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Read the Blog"}),n("span",{className:"text-cygray-30",children:"|"}),n("a",{href:"https://discord.gg/x4uAgaRdwF",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Join Discord"})]})]})})}function pm({serverVersion:e}){const[t,r]=_("stale"),[s,a]=_(null),o=async()=>{r("restarting"),a(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let c=0;const d=30,m=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}c++,c<d?setTimeout(()=>void u(),m):(a("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void u(),500)}catch(i){a(i instanceof Error?i.message:"Failed to restart server"),r("stale")}};return n("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:n("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-amber-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),l("div",{className:"flex-1",children:[t==="stale"&&l(ue,{children:[n("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."]}),s&&n("p",{className:"text-xs text-red-600 mt-1",children:s})]}),t==="restarting"&&l(ue,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Restarting server..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Please wait while the server restarts."})]}),t==="reconnecting"&&l(ue,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Reconnecting..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Waiting for the server to come back online."})]})]}),t==="stale"&&n("button",{type:"button",onClick:()=>void o(),className:"shrink-0 px-4 py-2 bg-amber-600 text-white text-sm font-medium rounded hover:bg-amber-700 transition-colors cursor-pointer",children:"Restart Server"}),(t==="restarting"||t==="reconnecting")&&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:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t==="restarting"?"Stopping...":"Reconnecting..."]})]})})})}function _t({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:s="",duration:a=2e3,ariaLabel:o,icon:i=!1,iconSize:c=14}){const[d,m]=_(!1),u=oe(()=>{navigator.clipboard.writeText(e).then(()=>{m(!0),setTimeout(()=>m(!1),a)}).catch(h=>{console.error("Failed to copy:",h)})},[e,a]);return n("button",{onClick:u,className:`cursor-pointer ${s}`,disabled:d,"aria-label":o||(d?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?d?n(gt,{size:c,className:"text-green-500"}):n(Nt,{size:c}):d?r:t})}function fm({currentVersion:e,latestVersion:t}){const[r,s]=_(!1);if(r)return null;const a="npm install -g @codeyam/codeyam-cli@latest && codeyam stop && codeyam";return n("div",{className:"bg-emerald-100 border rounded border-emerald-700 shadow-sm mx-6 mt-6",children: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:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-emerald-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M7 11l5-5m0 0l5 5m-5-5v12"})})}),l("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-emerald-900",children:"A new version of CodeYam CLI is available"}),l("p",{className:"text-xs text-emerald-700 mt-0.5",children:["Current: ",e," → Latest: ",t]})]}),l("div",{className:"shrink-0 flex items-center gap-2",children:[n("code",{className:"text-xs bg-emerald-200 text-emerald-900 px-2 py-1.5 rounded font-mono",children:a}),n(_t,{content:a,label:"Copy",copiedLabel:"Copied!",className:"px-3 py-1.5 bg-emerald-600 text-white text-xs font-medium rounded hover:bg-emerald-700 transition-colors"})]})]}),n("button",{type:"button",onClick:()=>s(!0),className:"shrink-0 ml-4 p-1 rounded text-emerald-600 hover:text-emerald-800 hover:bg-emerald-200 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}let Pn=null,nr=0;const gm=3600*1e3;function ym(e,t){const r=e.split(".").map(Number),s=t.split(".").map(Number);for(let a=0;a<Math.max(r.length,s.length);a++){const o=r[a]??0,i=s[a]??0;if(isNaN(o)||isNaN(i))return!1;if(o>i)return!0;if(o<i)return!1}return!1}async function xm(){const e=fa();if(Pn&&Date.now()-nr<gm)return Pn;try{const t=new AbortController,r=setTimeout(()=>t.abort(),5e3),s=await fetch("https://registry.npmjs.org/@codeyam/codeyam-cli/latest",{signal:t.signal});if(clearTimeout(r),!s.ok){const c={updateAvailable:!1,latestVersion:null,currentVersion:e};return Pn=c,nr=Date.now(),c}const o=(await s.json()).version;if(!o){const c={updateAvailable:!1,latestVersion:null,currentVersion:e};return Pn=c,nr=Date.now(),c}const i={updateAvailable:ym(o,e),latestVersion:o,currentVersion:e};return Pn=i,nr=Date.now(),i}catch{return{updateAvailable:!1,latestVersion:null,currentVersion:e}}}function Ar(e){return O.join(e,".codeyam","queue.json")}function Tn(e){const t=Ar(e);if(!G.existsSync(t))return{paused:!1,jobs:[]};try{const r=G.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function bm(e,t){const r=Ar(e),s=O.dirname(r);G.existsSync(s)||G.mkdirSync(s,{recursive:!0});try{G.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(a){throw console.error("Failed to save queue state:",a),a}}const Tr=class Tr extends Dr{constructor(t){super(),this.watcher=null,this.debounceTimers=new Map,this.DEBOUNCE_MS=300,this.options=t}start(){try{this.watcher=Ce.watch(this.options.projectRootPath,{recursive:!0},(t,r)=>{if(!r||!/\.(ts|tsx|js|jsx|css|scss|json|svg|html)$/.test(r)||Tr.IGNORED_DIRS.some(a=>r.includes(a+"/")||r.includes(a+"\\")))return;const s=this.debounceTimers.get(r);s&&clearTimeout(s),this.debounceTimers.set(r,setTimeout(()=>{this.debounceTimers.delete(r),this.syncFile(r)},this.DEBOUNCE_MS))}),console.log(`[InteractiveSyncWatcher] Watching ${this.options.projectRootPath} for changes`)}catch(t){console.error("[InteractiveSyncWatcher] Failed to start:",t)}}syncFile(t){const r=ee.join(this.options.projectRootPath,t),s=ee.join(this.options.tmpProjectPath,t);try{if(!Ce.existsSync(r)){Ce.existsSync(s)&&(Ce.unlinkSync(s),console.log(`[InteractiveSyncWatcher] Removed: ${t}`));return}const a=ee.dirname(s);Ce.existsSync(a)||Ce.mkdirSync(a,{recursive:!0}),Ce.copyFileSync(r,s);const o=ee.basename(t);console.log(`[InteractiveSyncWatcher] Synced: ${t}`);const i={type:"file-synced",fileName:o,filePath:t,timestamp:Date.now()};this.emit("sync",i)}catch(a){console.error(`[InteractiveSyncWatcher] Error syncing ${t}:`,a);const o={type:"error",fileName:ee.basename(t),filePath:t,timestamp:Date.now()};this.emit("sync",o)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null);for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),console.log("[InteractiveSyncWatcher] Stopped")}};Tr.IGNORED_DIRS=["node_modules",".git",".codeyam","__codeyamMocks__",".next","dist","build",".turbo",".vercel","coverage",".cache"];let zs=Tr,vm=class extends Dr{constructor(){super(),this.setMaxListeners(20)}emitFileSynced(t,r){this.emit("event",{type:"file-synced",fileName:t,filePath:r,timestamp:Date.now()})}emitError(t,r){this.emit("event",{type:"sync-error",fileName:t,filePath:r,timestamp:Date.now()})}};const Bs="__codeyam_dev_mode_event_emitter__";globalThis[Bs]||(globalThis[Bs]=new vm);const co=globalThis[Bs],Ys=new Map;async function wm(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await Nm(e,t,r);else if(e.type==="baseline")await Cm(e,t,r);else if(e.type==="recapture")await Sm(e,t,r);else if(e.type==="capture-only")await km(e,t,r);else if(e.type==="debug-setup")await Em(e,t,r);else if(e.type==="interactive-start")await Am(e,t,r);else if(e.type==="interactive-stop")await Pm(e,t,r);else throw new Error(`Unknown job type: ${e.type}`);console.log(`[Queue] Job ${e.id} completed successfully`)}catch(s){throw console.error(`[Queue] Job ${e.id} failed:`,s),s}}async function Nm(e,t,r){var g,x,v,b;const{projectSlug:s,commitSha:a,entityShas:o}=e;if(!a)throw new Error("Analysis job missing commitSha");const i=o||[],{project:c}=await Ie(s);await ha(s),await Un(s,{update:N=>console.log(`[Queue] ${N}`)});const d=qr(s),m={...await zt(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Bt(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...d?{ANALYZER_VERSION:d}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},u=(x=(g=c.metadata)==null?void 0:g.webapps)==null?void 0:x[0];if(!u)throw new Error("No webapps found in project metadata");const h=e.onlyDataStructure,p={packageManager:((v=c.metadata)==null?void 0:v.packageManager)||"npm",absoluteProjectRootPath:pt(s),port:0,noServer:!0,framework:u.framework,...h?{}:{orchestrateCapture:"local-sequential"}},f=bn(s,m,p),y=N=>{try{return process.kill(N,0),!0}catch{return!1}};await It({commitSha:a,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((b=e.filePaths)==null?void 0:b.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:f.process.pid}}),r==null||r.notifyChange("commit");try{try{const N=new Promise((w,S)=>setTimeout(()=>S(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,N]),await It({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await It({commitSha:a,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(w=>setTimeout(w,2e3))}finally{if(f.process.pid)try{y(f.process.pid)&&await Dn(f.process.pid,()=>{})}catch{}}}catch(N){if(console.error(`[Queue] Analysis job ${e.id} failed:`,N),f.process.pid&&y(f.process.pid))try{await Dn(f.process.pid,()=>{})}catch{}try{await It({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:N instanceof Error?N.message:String(N)}}),r==null||r.notifyChange("commit")}catch(w){console.error("[Queue] Failed to update commit metadata after job failure:",w)}throw N}}async function Cm(e,t,r){var p,f,y;const{projectSlug:s,commitSha:a}=e;if(!a)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${s}`);const{project:o}=await Ie(s);await ha(s),await Un(s,{update:g=>console.log(`[Queue] ${g}`)});const i=qr(s),c={...await zt(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Bt(),...i?{ANALYZER_VERSION:i}:{}},d=(f=(p=o.metadata)==null?void 0:p.webapps)==null?void 0:f[0];if(!d)throw new Error("No webapps found in project metadata");const m={packageManager:((y=o.metadata)==null?void 0:y.packageManager)||"npm",absoluteProjectRootPath:pt(s),port:0,noServer:!0,framework:d.framework,orchestrateCapture:"local-sequential"},u=bn(s,c,m),h=g=>{try{return process.kill(g,0),!0}catch{return!1}};await It({commitSha:a,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:u.process.pid}}),r==null||r.notifyChange("commit");try{const g=new Promise((x,v)=>setTimeout(()=>v(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([u.promise,g]),await It({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${s}`),await new Promise(x=>setTimeout(x,2e3))}finally{if(u.process.pid)try{h(u.process.pid)&&await Dn(u.process.pid,()=>{})}catch{}}}async function Sm(e,t,r){var f,y,g,x;const{projectSlug:s,analysisId:a,scenarioId:o,defaultWidth:i}=e;if(!a)throw new Error("Recapture job missing analysisId");const c=await Pt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:v}=await import("./index-Bh_pNxNA.js"),b=v(),N=await b.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let w={};N!=null&&N.metadata&&(typeof N.metadata=="string"?w=JSON.parse(N.metadata):w=N.metadata),w.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(w)}).where("sha","=",c.entitySha).execute()}await gn(a,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete v.finishedAt});const{project:d}=await Ie(s);await Un(s,{update:v=>console.log(`[Queue] ${v}`)});const m=qr(s),u={...await zt(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Bt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...m?{ANALYZER_VERSION:m}:{}},h={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:pt(s),port:void 0,noServer:!0,framework:((x=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??Ke.Next,orchestrateCapture:"local-sequential"},p=bn(s,u,h);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function km(e,t,r){var f,y,g,x;const{projectSlug:s,analysisId:a,scenarioId:o,defaultWidth:i}=e;if(!a)throw new Error("Capture-only job missing analysisId");const c=await Pt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:v}=await import("./index-Bh_pNxNA.js"),b=v(),N=await b.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let w={};N!=null&&N.metadata&&(typeof N.metadata=="string"?w=JSON.parse(N.metadata):w=N.metadata),w.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(w)}).where("sha","=",c.entitySha).execute()}await gn(a,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete v.finishedAt});const{project:d}=await Ie(s);await Un(s,{update:v=>console.log(`[Queue] ${v}`)});const m=qr(s);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await zt(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Bt(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...m?{ANALYZER_VERSION:m}:{}},h={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:pt(s),port:void 0,noServer:!0,fast:!0,framework:((x=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??Ke.Next,orchestrateCapture:"local-sequential"},p=bn(s,u,h);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function Em(e,t,r){var p,f,y,g;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Debug setup job missing analysisId");const i=await Pt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:c}=await Ie(s);await ha(s),await Un(s,{update:x=>console.log(`[Queue] ${x}`)});const d={...await zt(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Bt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,PREP_ONLY:"true"};o&&(d.SCENARIO_IDS=o);const m={packageManager:((p=c.metadata)==null?void 0:p.packageManager)||"npm",absoluteProjectRootPath:pt(s),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)||Ke.Next},h=await bn(s,d,m).promise;if(h!==0)throw new Error(`Prep process exited with code ${h}`)}async function Am(e,t,r){var x,v,b,N;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Interactive start job missing analysisId");const i=await Pt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:c}=await Ie(s),d={...await zt(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Bt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,INTERACTIVE_MODE:"true"};o&&(d.SCENARIO_IDS=o);const m=pt(s),u=ee.join(m,".next","dev","lock");if(Ce.existsSync(u)){console.log("[Queue] Found stale .next/dev/lock, cleaning up old processes");try{const w=Pe(`pgrep -f ${JSON.stringify(m)} 2>/dev/null || true`,{encoding:"utf-8"}).trim();if(w)for(const S of w.split(`
|
|
40
|
+
`).filter(Boolean))try{process.kill(parseInt(S,10),"SIGTERM"),console.log(`[Queue] Killed stale process ${S}`)}catch{}}catch{}try{Ce.unlinkSync(u),console.log("[Queue] Removed stale lock file")}catch{}}const h=Ce.existsSync(m)&&Ce.existsSync(ee.join(m,"package.json")),p={packageManager:((x=c.metadata)==null?void 0:x.packageManager)||"npm",absoluteProjectRootPath:m,port:void 0,noServer:!1,fast:h,framework:((N=(b=(v=c.metadata)==null?void 0:v.webapps)==null?void 0:b[0])==null?void 0:N.framework)||Ke.Next};await gn(a,w=>{w.readyToBeCaptured=!0});const f=bn(s,d,p);await Si(a,w=>{w.interactiveMode={pid:f.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${a}, PID: ${f.process.pid}`);const y=pt(s),g=new zs({projectRootPath:t,tmpProjectPath:y});g.on("sync",w=>{w.type==="file-synced"?co.emitFileSynced(w.fileName,w.filePath):w.type==="error"&&co.emitError(w.fileName,w.filePath)}),g.start(),Ys.set(a,g),console.log(`[Queue] File sync watcher started for analysis ${a}`)}async function Pm(e,t,r){var m;const{projectSlug:s,analysisId:a}=e;if(!a)throw new Error("Interactive stop job missing analysisId");const o=await Pt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!o)throw new Error(`Analysis ${a} not found`);const i=(m=o.metadata)==null?void 0:m.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${a}`);return}const c=Ys.get(a);c&&(c.stop(),Ys.delete(a),console.log(`[Queue] File sync watcher stopped for analysis ${a}`));const d=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${a}, killing PID: ${d}`);try{try{process.kill(d,0)}catch{console.log(`[Queue] Process ${d} already exited`);return}await Dn(d,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${d}`)}catch(u){throw console.error(`[Queue] Failed to kill process ${d}:`,u),u}finally{await Si(a,u=>{u.interactiveMode=null})}}class _m{constructor(t,r){this.processing=!1,this.completionCallbacks=new Map,this.completedJobs=new Map,this.projectRoot=t,this.state={paused:!1,jobs:[]},r&&(typeof r=="function"?this.notifier={notifyChange:()=>r()}:this.notifier=r)}start(){this.state=Tn(this.projectRoot),this.state.currentlyExecuting&&(console.log(`[Queue] Clearing stale currentlyExecuting job from previous session: ${this.state.currentlyExecuting.id}`),this.state.currentlyExecuting=void 0,this.save()),this.state.jobs.length>0?(this.state.paused=!0,this.save(),console.log(`[Queue] Found ${this.state.jobs.length} queued jobs from previous session (paused)`)):this.state.paused=!1}enqueue(t){const r=t.commitSha||ra(),s={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(s),this.save(),console.log(`[Queue] Enqueued job ${r} (${s.type})`);const a=new Promise((o,i)=>{this.completionCallbacks.set(r,c=>{c?i(c):o()})});return this.state.paused||this.processNext().catch(o=>{console.error("[Queue] ERROR in processNext():",o)}),{jobId:r,completion:a}}resume(){console.log("[Queue] Resuming queue"),this.state.paused=!1,this.save(),this.processNext()}pause(){console.log("[Queue] Pausing queue"),this.state.paused=!0,this.save()}getState(){return{...this.state}}getJobResult(t){return this.completedJobs.get(t)}removeJob(t){const r=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(a=>a.id!==t);const s=this.state.jobs.length<r;if(s){console.log(`[Queue] Removed job ${t}`),this.save();const a=this.completionCallbacks.get(t);a&&(setImmediate(()=>a(new Error("Job cancelled by user"))),this.completionCallbacks.delete(t))}else console.log(`[Queue] Job ${t} not found in queue`);return s}clearQueue(){const t=this.state.jobs.length;return t===0?0:(this.state.jobs.forEach(r=>{const s=this.completionCallbacks.get(r.id);s&&(setImmediate(()=>s(new Error("Job cancelled by user"))),this.completionCallbacks.delete(r.id))}),this.state.jobs=[],console.log(`[Queue] Cleared ${t} jobs`),this.save(),t)}reorderJob(t,r){const s=this.state.jobs.findIndex(i=>i.id===t);if(s===-1)return console.log(`[Queue] Job ${t} not found in queue`),!1;const a=r==="up"?s-1:s+1;if(a<0||a>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const o=this.state.jobs[s];return this.state.jobs[s]=this.state.jobs[a],this.state.jobs[a]=o,console.log(`[Queue] Moved job ${t} ${r} (position ${s} -> ${a})`),this.save(),!0}async processNext(){if(this.state.paused||this.processing)return;if(this.state.jobs.length===0){console.log("[Queue] No jobs to process");return}this.processing=!0;const t=this.state.jobs[0];console.log(`[Queue] Starting job ${t.id} (${t.type})`);try{this.state.currentlyExecuting=this.state.jobs.shift(),this.save(),await wm(t,this.projectRoot,this.notifier),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"success",completedAt:new Date().toISOString()});const r=this.completionCallbacks.get(t.id);r&&(r(),this.completionCallbacks.delete(t.id)),console.log(`[Queue] Job ${t.id} completed successfully`)}catch(r){console.error(`[Queue] Job ${t.id} failed:`,r),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"error",error:(r==null?void 0:r.message)||"Unknown error",completedAt:new Date().toISOString()});const s=this.completionCallbacks.get(t.id);s&&(s(r),this.completionCallbacks.delete(t.id))}finally{this.processing=!1,!this.state.paused&&this.state.jobs.length>0&&setImmediate(()=>void this.processNext())}}save(){bm(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class jm{constructor(t,r,s=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=s}start(){const t=Ar(this.projectRoot);if(!G.existsSync(t)){console.log("[QueueFileWatcher] Queue file does not exist yet, will start watching when created"),this.watchDirectory();return}this.watchFile(t)}watchDirectory(){const t=Ar(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=G.watch(r,(s,a)=>{a==="queue.json"&&(this.stop(),this.watchFile(t),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(s){console.error("[QueueFileWatcher] Failed to watch directory:",s)}}watchFile(t){try{this.watcher=G.watch(t,r=>{r==="change"&&this.notifyChange()}),console.log("[QueueFileWatcher] Watching queue.json for changes")}catch(r){console.error("[QueueFileWatcher] Failed to watch queue file:",r)}}notifyChange(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.onChange(),this.debounceTimer=null},this.debounceMs)}stop(){this.watcher&&(this.watcher.close(),this.watcher=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}class Mm{constructor(t,r,s){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=s,this.cachedState=Tn(r)}start(){this.cachedState=Tn(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 jm(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,s;const a=new Promise((i,c)=>{r=i,s=c}),o=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),s(i)}),{jobId:o,completion:a}}async enqueueRemote(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to enqueue: ${r.status} ${s}`)}return r.json()}resume(){console.log("[ProxyQueue] Sending resume command to background server"),this.sendAction("resume").catch(t=>{console.error("[ProxyQueue] Failed to resume:",t)})}pause(){console.log("[ProxyQueue] Sending pause command to background server"),this.sendAction("pause").catch(t=>{console.error("[ProxyQueue] Failed to pause:",t)})}async sendAction(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to ${t}: ${r.status} ${s}`)}this.refreshState()}getState(){return this.cachedState=Tn(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=Tn(this.projectRoot),this.onStateChange&&this.onStateChange()}async isServerAlive(){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),s=await fetch(`${this.serverInfo.url}/api/health`,{signal:t.signal});return clearTimeout(r),s.ok}catch{return!1}}getServerInfo(){return{...this.serverInfo}}stop(){this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null)}}function Tm(e){const t=O.join(e,".codeyam","server.json");if(!G.existsSync(t))return null;try{const r=G.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function $m(e){try{return process.kill(e,0),!0}catch{return!1}}async function Rm(e){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),s=await fetch(`${e}/api/health`,{signal:t.signal});return clearTimeout(r),s.ok}catch{return!1}}async function Im(e){const t=Tm(e);return!t||!$m(t.pid)||!await Rm(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class Dm extends Dr{constructor(){super();Xn(this,"watcher",null);Xn(this,"dbPath",null);Xn(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=Bt();const{default:r}=await import("chokidar"),s=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=r.watch(s,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",a=>{const o=Date.now(),i=new Date(o).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${a}`),console.log(`[dbNotifier] Timestamp: ${i} (${o})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:o})}).on("error",a=>{console.error("Database watcher error:",a),this.emit("error",a)}),this.isWatching=!0}catch(r){console.error("Failed to start database watcher:",r),this.emit("error",r)}}notifyChange(r="unknown"){const s=Date.now(),a=new Date(s).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${r}`),console.log(`[dbNotifier] Timestamp: ${a} (${s})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:r,timestamp:s})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const Ct=new Dm;let Gt=null,$n=null;async function Lm(){if(!Gt){if($n){await $n;return}$n=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||ki()||process.cwd();if(Tu(e),console.log(`[GlobalQueue] Project root: ${e}`),await Ye(),process.env.NODE_ENV==="development")try{const r=ee.join(e,".codeyam","config.json"),a=JSON.parse(await Ce.promises.readFile(r,"utf8")).projectSlug;a&&(await hn({projectSlug:a,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),console.log("[GlobalQueue] Labs & Simulations auto-enabled for dev mode"))}catch(r){console.warn("[GlobalQueue] Could not auto-enable labs:",r)}const t=await Im(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new Mm(t,e,()=>{Ct.notifyChange("unknown")});await r.start(),Gt=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new _m(e,Ct);await r.start(),Gt=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await $n}}async function jt(){return Gt||await Lm(),Gt}function Om(){return Gt||($n&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const Fm=()=>[{rel:"stylesheet",href:mm},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}],zm={currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[],isServerOutOfDate:!1,serverVersion:"unknown",npmUpdate:null,labs:null,simulationsEnabled:!1,isSimulationsReady:!1,isAdmin:!1,editorMode:!1,displayVersion:fa()};async function Bm({request:e,context:t}){var r,s,a,o,i,c,d,m,u,h,p;try{const f=e.signal,y=()=>{if(f.aborted)throw new Response(null,{status:499})};y();const g=he()||process.cwd(),[x,v,b]=await Promise.all([$e(),Wr(g),xm().catch(()=>null)]);if(!x)throw new Error("Project slug not found");const{project:N,branch:w}=await Ie(x);y();const S=await Cr({projectId:N.id,branchId:w.id,limit:20,skipRelations:!0});y();const C=S.length>0?S[0]:null,k=t.analysisQueue||Om(),E=k==null?void 0:k.getState();y();const A=await Promise.all(((E==null?void 0:E.jobs)||[]).map(async V=>{var ce;const Z=await tr(V.entityShas||[]);return Z.length===0&&((ce=V.entityShas)!=null&&ce.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",V.id),{...V,entities:Z}}));let I=null;if(E!=null&&E.currentlyExecuting){const V=E.currentlyExecuting,Z=await tr(V.entityShas||[]);Z.length===0&&((r=V.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",V.id),I={...V,entities:Z}}const j=I?A.filter(V=>V.id!==I.id):A;let P=((a=(s=C==null?void 0:C.metadata)==null?void 0:s.currentRun)==null?void 0:a.currentEntityShas)||[];if(P.length===0){const V=((o=C==null?void 0:C.metadata)==null?void 0:o.historicalRuns)||[];if(V.length>0){const ce=[...V].sort((ve,ae)=>{const me=ve.archivedAt||ve.createdAt||"";return(ae.archivedAt||ae.createdAt||"").localeCompare(me)})[0];if(ce){const ve=ce.analysisCompletedAt||ce.createdAt;if(ve){const ae=new Date(ve).getTime(),Se=Date.now()-1440*60*1e3;ae>Se&&(P=ce.currentEntityShas||[])}}}}const $=await tr(P),T=[];v.ANTHROPIC_API_KEY&&T.push("ANTHROPIC_API_KEY"),v.GROQ_API_KEY&&T.push("GROQ_API_KEY"),v.OPENAI_API_KEY&&T.push("OPENAI_API_KEY"),v.OPENROUTER_API_KEY&&T.push("OPENROUTER_API_KEY"),y();const R=[];for(const V of S){const Z=((i=V.metadata)==null?void 0:i.historicalRuns)||[];for(const ce of Z)R.push(ce)}R.sort((V,Z)=>{const ce=V.archivedAt||V.analysisCompletedAt||V.createdAt||"";return(Z.archivedAt||Z.analysisCompletedAt||Z.createdAt||"").localeCompare(ce)});const J=new Set(((c=I==null?void 0:I.entities)==null?void 0:c.map(V=>V.sha))||[]),Y=R.filter(V=>!(V.currentEntityShas||[]).some(ce=>J.has(ce))).slice(0,3),H=new Set;for(const V of Y)for(const Z of V.currentEntityShas||[])H.add(Z);const B=await tr(Array.from(H)),D=new Map;for(const V of B)D.set(V.sha,V);const M=Y.map(V=>({...V,entities:(V.currentEntityShas||[]).map(Z=>D.get(Z)).filter(Z=>Z!=null)})),Q=Ui(),U=(Q==null?void 0:Q.cliVersion)??"unknown",F=U!=="unknown"&&U!==pa,X=((m=(d=N.metadata)==null?void 0:d.labs)==null?void 0:m.simulations)??!1,z=X?om():!1,L=((u=N.metadata)==null?void 0:u.editorMode)??!1,W={currentRun:(h=C==null?void 0:C.metadata)==null?void 0:h.currentRun,projectSlug:x,currentEntities:$,availableAPIKeys:T,queuedJobCount:j.length,queueJobs:j,currentlyExecuting:I,historicalRuns:M,isServerOutOfDate:F,serverVersion:U,npmUpdate:b!=null&&b.updateAvailable&&b.latestVersion?{latestVersion:b.latestVersion,currentVersion:b.currentVersion}:null,labs:((p=N.metadata)==null?void 0:p.labs)??null,simulationsEnabled:X,isSimulationsReady:z,isAdmin:!!process.env.CODEYAM_ADMIN,editorMode:L,displayVersion:fa()};return K(W)}catch(f){return f instanceof Response&&f.status===499||console.error("Failed to load root data:",f),K(zm)}}function Ym(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:s,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:c,isServerOutOfDate:d,serverVersion:m,npmUpdate:u,labs:h,simulationsEnabled:p,isSimulationsReady:f,isAdmin:y,editorMode:g,displayVersion:x}=Ve(),{toasts:v,closeToast:b}=ca(),N=ft(),w=be(N),S=$r();te(()=>{w.current=N},[N]);const C=S.pathname.startsWith("/entity/")&&S.pathname.includes("/edit/")||S.pathname.startsWith("/dev/")||S.pathname.startsWith("/editor"),k=S.pathname.includes("/fullscreen")||S.pathname.startsWith("/editor");return te(()=>{const E=new EventSource("/api/events");let A=null,I=0;const j=2e3;return E.addEventListener("message",P=>{const $=JSON.parse(P.data);if($.type==="queue")w.current.revalidate(),I=Date.now();else if($.type==="db-change"||$.type==="unknown"){const T=Date.now(),R=T-I;R<j?(A&&clearTimeout(A),A=setTimeout(()=>{w.current.revalidate(),I=Date.now(),A=null},j-R)):(w.current.revalidate(),I=T)}}),E.addEventListener("error",P=>{console.error("SSE connection error:",P)}),()=>{A&&clearTimeout(A),E.close()}},[]),l(ue,{children:[l("div",{className:`min-h-screen ${C?"":"grid"} bg-cygray-10`,style:C?void 0:{gridTemplateColumns:"65px minmax(0, 1fr)"},children:[!C&&n(vd,{labs:h,isAdmin:y,editorMode:g}),l("div",{className:"max-h-screen overflow-auto bg-cygray-10 flex flex-col min-h-screen",children:[d&&n(pm,{serverVersion:m}),u&&u.currentVersion&&n(fm,{currentVersion:u.currentVersion,latestVersion:u.latestVersion}),p&&s.length===0&&n(lo,{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"}),p&&!f&&n(lo,{text:"Simulations enabled but not yet configured",subtext:"Run /codeyam-setup in Claude Code to install the analyzer and configure your dev server",linkText:"View Labs",linkTo:"/labs"}),n("div",{className:"flex-1",children:n(nc,{})}),n(hm,{version:x})]})]}),n(Cd,{toasts:v,onClose:b}),!k&&p&&n(Sd,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:c})]})}const Um=Je(function(){return l("html",{lang:"en",children:[l("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(Zl,{}),n(Xl,{})]}),l("body",{children:[n(wd,{children:n(xd,{children:n(Ym,{})})}),n(ec,{}),n(tc,{})]})]})}),Wm=Object.freeze(Object.defineProperty({__proto__:null,default:Um,links:Fm,loader:Bm},Symbol.toStringTag,{value:"Module"}));function rr(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function nn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:o=!0,refreshTrigger:i=0}){const c=Le(),[d,m]=_(null),[u,h]=_(!1),[p,f]=_(!1),[y,g]=_(!1),x=be(!1),v=be(null),b=be(null),N=be(null),[w,S]=_(0),[C,k]=_(0),E=be(null),A=be(!1),{interactiveUrl:I,resetLogs:j}=Et(a,o),P=be(t),$=be(i);te(()=>{$.current!==i&&($.current=i,d&&(console.log("[useInteractiveMode] Manual refresh triggered"),f(!0),g(!1),S(0),k(R=>R+1),A.current=!1,E.current&&(clearTimeout(E.current),E.current=null)))},[i,d]),te(()=>{if(P.current!==t&&(P.current=t,v.current&&b.current&&r)){let R=v.current;if(N.current&&s){const Y=rr(N.current),H=rr(s);Y!==H&&(R=R.replace(Y,H),N.current=s)}const J=rr(b.current),q=rr(r);R=R.replace(J,q),b.current=r,m(R),f(!0),g(!1),S(0),k(Y=>Y+1),A.current=!1,E.current&&(clearTimeout(E.current),E.current=null);return}},[t,r,s]),te(()=>{if(I){const R=I+"?width=600px";v.current=R,r&&(b.current=r),s&&(N.current=s),m(R),h(!1),f(!0)}},[I]),te(()=>{const R=J=>{J.data.type==="codeyam-resize"&&(A.current||(A.current=!0,E.current&&(clearTimeout(E.current),E.current=null),S(0),g(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{f(!1)})})))};return window.addEventListener("message",R),()=>window.removeEventListener("message",R)},[]);const T=()=>{A.current=!1,E.current&&clearTimeout(E.current);const R=300*Math.pow(2,w);E.current=setTimeout(()=>{A.current||(w<2?(S(J=>J+1),k(J=>J+1),f(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),g(!0),f(!1)))},R)};return te(()=>{o&&!x.current&&t&&e&&(x.current=!0,h(!0),g(!1),m(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(J){console.error("[useInteractiveMode] Failed to clear log file:",J)}j(),c.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[o,t,e,j,a]),te(()=>{const R=e,J=()=>{if(x.current&&R){const Y=new URLSearchParams({action:"stop",analysisId:R});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const H=navigator.sendBeacon("/api/interactive-mode",Y);console.log("[useInteractiveMode] sendBeacon result:",H),H||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y,keepalive:!0}).catch(B=>console.error("Failed to stop interactive mode:",B)))}},q=()=>{J()};return window.addEventListener("beforeunload",q),()=>{window.removeEventListener("beforeunload",q),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:x.current,analysisId:R}),J()}},[e]),{interactiveServerUrl:d,isStarting:u,isLoading:p,showIframe:y,iframeKey:C,onIframeLoad:T}}const sr=10,Jm=1024;function Gr({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:s,onHoverChange:a,hideLabel:o=!1,lightMode:i=!1}){const[c,d]=_(null),m=be(null),u=ne(()=>[...s].sort((b,N)=>b.width-N.width),[s]),{fittingPresets:h,overflowPresets:p}=ne(()=>{const b=[],N=[];for(const w of u)w.width<=Jm?b.push(w):N.push(w);return N.sort((w,S)=>S.width-w.width),{fittingPresets:b,overflowPresets:N}},[u]),f=oe(b=>{if(!m.current)return null;const N=m.current.getBoundingClientRect(),w=b-N.left,S=N.width,C=S/2,E=(h.length>0?h[h.length-1].width:0)/2,A=C-E,I=C+E,j=p.length>0?(p.length-1)*sr:0;if(p.length>0){if(w<A){if(w<=j){const $=Math.min(Math.floor(w/sr),p.length-1);return p[$]}return p[p.length-1]}if(w>I){const $=S-w;if($<=j){const T=Math.min(Math.floor($/sr),p.length-1);return p[T]}return p[p.length-1]}}const P=Math.abs(w-C);for(let $=h.length-1;$>=0;$--){const T=h[$],R=h[$-1],J=T.width/2,q=R?R.width/2:0;if(P<=J&&P>=q)return T}return h[0]||p[p.length-1]||null},[h,p]),y=oe(b=>{const N=f(b.clientX);d(N),a==null||a(N)},[f,a]),g=oe(()=>{d(null),a==null||a(null)},[a]),x=oe(b=>{const N=f(b.clientX);N&&r(N)},[f,r]),v=c||{name:t,width:e};return l("div",{ref:m,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:y,onMouseLeave:g,onClick:x,children:[c&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${c.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:h.map(b=>{const N=b.width===e,w=(c==null?void 0:c.name)===b.name,S=b.width/2;return l("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${S}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${N||w?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${S}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${N||w?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:p.map((b,N)=>{const w=N*sr,S=b.width===e,C=(c==null?void 0:c.name)===b.name;return l("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${w}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${S||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{right:`${w}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${S||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),!o&&n("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:[v.name," - ",v.width,"px"]})})]})}function Kr({width:e,height:t,onSave:r,onCancel:s}){const[a,o]=_(""),[i,c]=_(""),d=()=>{const u=a.trim();if(!u){c("Please enter a name for this custom size");return}r(u)};return n("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:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),l("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),l("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),l("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:a,onChange:u=>{o(u.target.value),c("")},onKeyDown:u=>{u.key==="Enter"&&a.trim()&&d(),u.key==="Escape"&&s()},placeholder:"e.g., iPhone 15 Pro",className:`w-full px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] ${i?"border-red-300":"border-gray-300"}`,autoFocus:!0}),i&&n("p",{className:"mt-1 text-sm text-red-600",children:i})]}),l("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:s,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors cursor-pointer",children:"Cancel"}),n("button",{onClick:d,disabled:!a.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 Qr(e){const[t,r]=_([]),s=e?`codeyam-custom-sizes-${e}`:null;te(()=>{if(!s||typeof window>"u"){r([]);return}try{const c=localStorage.getItem(s);if(c){const d=JSON.parse(c);Array.isArray(d)&&r(d)}}catch(c){console.error("[useCustomSizes] Failed to load custom sizes:",c),r([])}},[s]);const a=oe(c=>{if(!(!s||typeof window>"u"))try{localStorage.setItem(s,JSON.stringify(c))}catch(d){console.error("[useCustomSizes] Failed to save custom sizes:",d)}},[s]),o=oe((c,d,m)=>{r(u=>{const h=u.findIndex(y=>y.name===c),p={name:c,width:d,height:m};let f;return h>=0?(f=[...u],f[h]=p):f=[...u,p],a(f),f})},[a]),i=oe(c=>{r(d=>{const m=d.filter(u=>u.name!==c);return a(m),m})},[a]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}function Ot(){return l("div",{className:"spinner-container",children:[n("span",{className:"loader"}),n("style",{children:`
|
|
41
|
+
.loader {
|
|
42
|
+
width: 48px;
|
|
43
|
+
height: 48px;
|
|
44
|
+
border: 3px solid rgba(0, 92, 117, 0.2);
|
|
45
|
+
border-radius: 50%;
|
|
46
|
+
display: inline-block;
|
|
47
|
+
position: relative;
|
|
48
|
+
box-sizing: border-box;
|
|
49
|
+
animation: rotation 1s linear infinite;
|
|
50
|
+
}
|
|
51
|
+
.loader::after {
|
|
52
|
+
content: '';
|
|
53
|
+
box-sizing: border-box;
|
|
54
|
+
position: absolute;
|
|
55
|
+
left: 50%;
|
|
56
|
+
top: 50%;
|
|
57
|
+
transform: translate(-50%, -50%);
|
|
58
|
+
width: 56px;
|
|
59
|
+
height: 56px;
|
|
60
|
+
border-radius: 50%;
|
|
61
|
+
border: 3px solid;
|
|
62
|
+
border-color: #005c75 transparent;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
@keyframes rotation {
|
|
66
|
+
0% {
|
|
67
|
+
transform: rotate(0deg);
|
|
68
|
+
}
|
|
69
|
+
100% {
|
|
70
|
+
transform: rotate(360deg);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
`})]})}const uo=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],Hm=80;function pn(){const[e,t]=_(0);return te(()=>{const r=setInterval(()=>{t(s=>(s+1)%uo.length)},Hm);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:uo[e]})}async function Vm({params:e}){var c;const{sha:t,scenarioId:r}=e;if(!t||!r)throw K("Invalid parameters",{status:400});const s=await Xt(t);if(!s)throw K("Entity not found",{status:404});const a=await Yr(s),o=((c=a==null?void 0:a.scenarios)==null?void 0:c.find(d=>d.id===r))||null;if(!o)throw K("Scenario not found",{status:404});const i=await $e();return K({entity:s,scenario:o,analysis:a,projectSlug:i})}const Ns=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],qm=Je(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=Ve(),o=St(),[i]=fn(),[c,d]=_(null),[m,u]=_(1440),[h,p]=_({name:"Desktop",width:1440,height:900}),[f,y]=_(!1),[g,x]=_(null),{customSizes:v,addCustomSize:b}=Qr(a),N=ne(()=>[...Ns,...v],[v]),{interactiveServerUrl:w,isStarting:S,isLoading:C,showIframe:k,iframeKey:E,onIframeLoad:A}=nn({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0}),{lastLine:I}=Et(a,S||C),j=()=>{o(`/entity/${t.sha}`)},P=(U,F)=>{u(U);const X=N.find(L=>L.width===U&&L.height===F);d(X||null),p({name:(X==null?void 0:X.name)||"Custom",width:U,height:F})},$=U=>{d(U),u(U.width),p({name:U.name,width:U.width,height:U.height})},T=U=>{b(U,h.width,h.height??900),y(!1),p(F=>({...F,name:U}))},R=((s==null?void 0:s.scenarios)||[]).filter(U=>{var F;return!((F=U.metadata)!=null&&F.sameAsDefault)}),J=R.findIndex(U=>U.id===(r==null?void 0:r.id)),q=J+1,Y=R.length,H=J>0,B=J<R.length-1,D=()=>{if(H){const U=R[J-1],F=encodeURIComponent(`/entity/${t.sha}/scenarios/${U.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${U.id}/fullscreen?from=${F}`)}},M=()=>{if(B){const U=R[J+1],F=encodeURIComponent(`/entity/${t.sha}/scenarios/${U.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${U.id}/fullscreen?from=${F}`)}},Q=S||C||!k;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:[n("img",{src:Or,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),l("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:D,disabled:!H,className:`${H?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),l("span",{className:"text-gray-400 text-sm",children:[q,"/",Y]}),n("button",{onClick:M,disabled:!B,className:`${B?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),l("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&l("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]})]}),n("button",{onClick:j,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),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:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Ns[Ns.length-1].width}px`,width:"100%"},children:n(Gr,{currentViewportWidth:m,currentPresetName:h.name,onDevicePresetClick:$,devicePresets:N,hideLabel:!0,onHoverChange:x,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:[n("span",{className:"leading-none",children:(g==null?void 0:g.name)||h.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l("select",{value:h.name,onChange:U=>{const F=N.find(X=>X.name===U.target.value);F&&$(F)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[N.map(U=>n("option",{value:U.name,children:U.name},U.name)),h.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:h.width,onChange:U=>{const F=parseInt(U.target.value,10);!isNaN(F)&&F>0&&P(F,h.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:h.height??900}),h.name==="Custom"&&n("button",{onClick:()=>y(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
|
|
74
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
75
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
76
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
77
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
78
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:w?l("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${h.width}px`,maxHeight:`${h.height}px`},children:[Q&&n("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:[n("div",{className:"mb-4",children:n(Ot,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),I&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(pn,{}),I]})]})]})}),n("iframe",{src:w,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:A,style:{opacity:k?1:0}},E)]}):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:[n("div",{className:"mb-4",children:n(Ot,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),I&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(pn,{}),I]})]})]})}),f&&n(Kr,{width:h.width,height:h.height??900,onSave:T,onCancel:()=>y(!1)})]})}),Gm=Object.freeze(Object.defineProperty({__proto__:null,default:qm,loader:Vm},Symbol.toStringTag,{value:"Module"}));function Wi({serverUrl:e,isStarting:t,projectSlug:r,devServerError:s,onStartServer:a}){const[o,i]=_(null),c=be(null);te(()=>{if(!r)return;const h=new EventSource("/api/dev-mode-events");return h.onmessage=p=>{try{const f=JSON.parse(p.data);f.type==="file-synced"&&(i(f.fileName),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{i(null)},5e3))}catch{}},()=>{h.close(),c.current&&clearTimeout(c.current)}},[r]);let d;s?d="error":t?d="starting":e?d="running":d="stopped";const m={starting:"bg-yellow-400",running:"bg-green-400",stopped:"bg-gray-400",error:"bg-red-400"},u={starting:"Starting...",running:e||"Running",stopped:"Stopped",error:"Error"};return l("div",{className:"bg-[#1e1e1e] border-t border-[#3d3d3d] h-7 flex items-center px-4 gap-4 shrink-0 text-xs font-mono",children:[l("div",{className:"flex items-center gap-2",children:[n("div",{className:`w-2 h-2 rounded-full ${m[d]}`}),l("span",{className:"text-gray-400",children:["Server:"," ",n("span",{className:"text-gray-300",children:u[d]})]}),(d==="stopped"||d==="error")&&a&&n("button",{onClick:a,className:"ml-1 px-2.5 py-0.5 bg-[#005c75] hover:bg-[#007a9a] text-white text-[11px] font-medium rounded transition-colors cursor-pointer border-none leading-tight",children:"Start Server"})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"}),o&&l(ue,{children:[l("div",{className:"flex items-center gap-1.5",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2",children:n("path",{d:"M20 6L9 17l-5-5"})}),l("span",{className:"text-green-400",children:["Synced: ",o]})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"})]}),n("div",{className:"flex-1"}),n("span",{className:"text-gray-500",children:"Claude edits auto-sync to preview via HMR"})]})}const Km=`
|
|
79
|
+
.xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
|
|
80
|
+
.xterm.focus, .xterm:focus { outline: none; }
|
|
81
|
+
.xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
|
|
82
|
+
.xterm .xterm-helper-textarea { padding: 0; border: 0; margin: 0; position: absolute; opacity: 0; left: -9999em; top: 0; width: 0; height: 0; z-index: -5; white-space: nowrap; overflow: hidden; resize: none; }
|
|
83
|
+
.xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
|
|
84
|
+
.xterm .composition-view.active { display: block; }
|
|
85
|
+
.xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
|
|
86
|
+
.xterm .xterm-screen { position: relative; }
|
|
87
|
+
.xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
|
|
88
|
+
.xterm .xterm-scroll-area { visibility: hidden; }
|
|
89
|
+
.xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
|
|
90
|
+
.xterm.enable-mouse-events { cursor: default; }
|
|
91
|
+
.xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
|
|
92
|
+
.xterm.column-select.focus { cursor: crosshair; }
|
|
93
|
+
.xterm .xterm-accessibility:not(.debug), .xterm .xterm-message { position: absolute; left: 0; top: 0; bottom: 0; right: 0; z-index: 10; color: transparent; pointer-events: none; }
|
|
94
|
+
.xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
|
|
95
|
+
.xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
|
|
96
|
+
.xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
|
|
97
|
+
.xterm-dim { opacity: 1 !important; }
|
|
98
|
+
.xterm-underline-1 { text-decoration: underline; }
|
|
99
|
+
.xterm-underline-2 { text-decoration: double underline; }
|
|
100
|
+
.xterm-underline-3 { text-decoration: wavy underline; }
|
|
101
|
+
.xterm-underline-4 { text-decoration: dotted underline; }
|
|
102
|
+
.xterm-underline-5 { text-decoration: dashed underline; }
|
|
103
|
+
.xterm-overline { text-decoration: overline; }
|
|
104
|
+
.xterm-strikethrough { text-decoration: line-through; }
|
|
105
|
+
.xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
|
|
106
|
+
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
|
|
107
|
+
.xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
|
|
108
|
+
.xterm-decoration-top { z-index: 2; position: relative; }
|
|
109
|
+
`;function Qm(){if(document.getElementById("xterm-css"))return;const e=document.createElement("style");e.id="xterm-css",e.textContent=Km,document.head.appendChild(e)}const Ji=ic(function({entityName:t,entityType:r,entitySha:s,entityFilePath:a,scenarioName:o,scenarioDescription:i,analysisId:c,projectSlug:d,onRefreshPreview:m,onShowResults:u,onHideResults:h,editorMode:p,onIdleChange:f,notificationsEnabled:y},g){const x=be(null),v=be(null),b=be(null),N=be(null),w=be(null),S=be(!1),C=be(0),k=be(!1),E=be(f);E.current=f;const A=be(y);A.current=y;const I=oe(()=>{var j;(j=b.current)==null||j.focus()},[]);return lc(g,()=>({sendInput(j){const P=N.current;P&&P.readyState===WebSocket.OPEN&&(P.send(JSON.stringify({type:"input",data:j})),setTimeout(()=>{P.readyState===WebSocket.OPEN&&P.send(JSON.stringify({type:"input",data:"\r"}))},100))},focus(){var j;(j=b.current)==null||j.focus()},scrollToBottom(){var P;const j=(P=x.current)==null?void 0:P.querySelector(".xterm-viewport");j&&(j.scrollTop=j.scrollHeight)}})),te(()=>{const j=x.current;if(!j)return;let P=!1;return Qm(),Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit"),import("@xterm/addon-web-links")]).then(([$,T,R])=>{if(P)return;const J=new $.Terminal({cursorBlink:!0,fontSize:13,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78"},linkHandler:{activate(U,F){try{const X=new URL(F),z=X.searchParams.get("scenario");if(z&&X.pathname==="/editor"){const L=new BroadcastChannel("codeyam-editor");L.postMessage({type:"switch-scenario",scenarioId:z}),L.close();return}}catch{}window.open(F,"_blank")}}}),q=new T.FitAddon;J.loadAddon(q),J.loadAddon(new R.WebLinksAddon),J.open(j),requestAnimationFrame(()=>{try{q.fit()}catch{}}),b.current=J,J.focus(),setTimeout(()=>J.focus(),100),setTimeout(()=>J.focus(),500);const Y=window.location.protocol==="https:"?"wss:":"ws:",H=window.location.host;function B(U){const F=new URLSearchParams;return F.set("entityName",t),r&&F.set("entityType",r),s&&F.set("entitySha",s),a&&F.set("entityFilePath",a),o&&F.set("scenarioName",o),i&&F.set("scenarioDescription",i),c&&F.set("analysisId",c),d&&F.set("projectSlug",d),p&&F.set("editorMode","true"),U&&F.set("reconnectId",U),`${Y}//${H}/ws/terminal?${F.toString()}`}function D(U){const F=B(U),X=new WebSocket(F);N.current=X,X.onopen=()=>{C.current=0,k.current=!1,X.send(JSON.stringify({type:"resize",cols:J.cols,rows:J.rows}))},X.onmessage=z=>{var L,W;try{const V=JSON.parse(z.data);if(V.type==="session-id"){w.current=V.sessionId;return}if(V.type==="refresh-preview"){m==null||m(V.path);return}if(V.type==="show-results"){u==null||u();return}if(V.type==="hide-results"){h==null||h();return}if(V.type==="claude-idle"){if(console.log("[Terminal] Received claude-idle, notifications:",A.current,"permission:",typeof Notification<"u"?Notification.permission:"N/A"),(L=E.current)==null||L.call(E,!0),A.current&&typeof Notification<"u"&&Notification.permission==="granted"){const Z=new Notification("Claude is ready for you",{body:"Claude has finished and is waiting for your input.",tag:"claude-idle"});Z.onclick=()=>{window.focus(),Z.close()}}return}V.type==="output"&&(J.write(V.data),(W=E.current)==null||W.call(E,!1))}catch{J.write(z.data)}},X.onclose=()=>{if(S.current){J.write(`\r
|
|
110
|
+
\x1B[90m[Terminal session ended]\x1B[0m\r
|
|
111
|
+
`);return}const z=C.current;if(z<5&&w.current){const L=1e3*Math.pow(2,Math.min(z,3));C.current=z+1,J.write(`\r
|
|
112
|
+
\x1B[33m[Reconnecting...]\x1B[0m\r
|
|
113
|
+
`),setTimeout(()=>{S.current||D(w.current)},L)}else k.current?J.write(`\r
|
|
114
|
+
\x1B[90m[Terminal session ended]\x1B[0m\r
|
|
115
|
+
`):(k.current=!0,J.write(`\r
|
|
116
|
+
\x1B[33m[Starting new session...]\x1B[0m\r
|
|
117
|
+
`),w.current=null,C.current=0,D())},X.onerror=()=>{}}D(),J.onData(U=>{const F=N.current;F&&F.readyState===WebSocket.OPEN&&F.send(JSON.stringify({type:"input",data:U}))});let M=null;const Q=new ResizeObserver(()=>{M&&clearTimeout(M),M=setTimeout(()=>{let U;try{U=q.proposeDimensions()}catch{return}if(!U||U.cols===J.cols&&U.rows===J.rows)return;const F=j.querySelector(".xterm-viewport");let X,z=!0;F&&(X=F.scrollTop,z=F.scrollTop+F.clientHeight>=F.scrollHeight-10),q.fit(),F&&X!==void 0&&(z?F.scrollTop=F.scrollHeight:F.scrollTop=X);const L=N.current;L&&L.readyState===WebSocket.OPEN&&L.send(JSON.stringify({type:"resize",cols:J.cols,rows:J.rows}))},150)});Q.observe(j),v.current=()=>{var U;M&&clearTimeout(M),Q.disconnect(),S.current=!0,(U=N.current)==null||U.close(),N.current=null,J.dispose(),b.current=null}}),()=>{var $;P=!0,($=v.current)==null||$.call(v),v.current=null}},[]),n("div",{ref:x,onClick:I,className:"w-full h-full",style:{padding:"4px 0 0 8px"}})});function qe({screenshotPath:e,cacheBuster:t,alt:r,className:s="",title:a}){const[o,i]=_("loading"),[c,d]=_(!1),m=be(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,h=()=>{i("success"),d(!0)},p=()=>{i("error"),d(!1)};return te(()=>{i("loading"),d(!1);const f=m.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:a,children:[n("img",{ref:m,src:u,alt:r,onLoad:h,onError:p,className:s||"max-w-full max-h-full object-contain",style:{visibility:c?"visible":"hidden",position:c?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&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:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:a,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}function Zm({scenarios:e,currentScenarioId:t,entitySha:r,cacheBuster:s}){const a=St();return e.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8",children:n("p",{className:"text-gray-500 text-sm",children:"No scenarios found"})}):n("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:e.map(o=>{var d,m;const i=o.id===t,c=(m=(d=o.metadata)==null?void 0:d.screenshotPaths)==null?void 0:m[0];return l("button",{onClick:()=>{a(`/entity/${r}/scenarios/${o.id}/dev`)},className:`w-full text-left rounded-lg overflow-hidden border transition-colors cursor-pointer flex ${i?"border-[#005c75] bg-[#1a3a44]":"border-[#3d3d3d] bg-[#252525] hover:border-[#555]"}`,children:[n("div",{className:"w-24 h-20 shrink-0 bg-[#1a1a1a]",children:n(qe,{screenshotPath:c,cacheBuster:s,alt:o.name,className:"w-full h-full object-cover object-top"})}),l("div",{className:"p-2.5 min-w-0 flex-1",children:[l("div",{className:"text-white text-sm font-medium truncate",children:[i&&n("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-[#005c75] mr-1.5 relative top-[-1px]"}),o.name]}),o.description&&n("div",{className:"text-gray-400 text-xs mt-1 line-clamp-2",children:o.description})]})]},o.id)})})}async function Xm({params:e}){var c;const{sha:t,scenarioId:r}=e;if(!t||!r)throw K("Invalid parameters",{status:400});const s=await Xt(t);if(!s)throw K("Entity not found",{status:404});const a=await Yr(s),o=((c=a==null?void 0:a.scenarios)==null?void 0:c.find(d=>d.id===r))||null;if(!o)throw K("Scenario not found",{status:404});const i=await $e();return K({entity:s,scenario:o,analysis:a,projectSlug:i})}const Cs=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],eh=Je(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=Ve(),o=St(),i=be(null),c=be(null),[d,m]=_(null),[u,h]=_(1440),[p,f]=_({name:"Desktop",width:1440,height:900}),[y,g]=_(!1),[x,v]=_(null),[b,N]=_("chat"),[w,S]=_(0),[C,k]=_(null),E=oe(ae=>{k(ae||null),S(me=>me+1)},[]),{customSizes:A,addCustomSize:I}=Qr(a),j=ne(()=>[...Cs,...A],[A]),{interactiveServerUrl:P,isStarting:$,isLoading:T,showIframe:R,iframeKey:J,onIframeLoad:q}=nn({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0,refreshTrigger:w}),Y=ne(()=>{if(!P)return null;if(!C)return P;try{const ae=new URL(P);return ae.pathname=C,ae.href}catch{return P}},[P,C]),{lastLine:H}=Et(a,$||T),B=()=>{o(`/entity/${t.sha}`)},D=(ae,me)=>{h(ae);const Se=j.find(Ae=>Ae.width===ae&&Ae.height===me);m(Se||null),f({name:(Se==null?void 0:Se.name)||"Custom",width:ae,height:me})},M=ae=>{m(ae),h(ae.width),f({name:ae.name,width:ae.width,height:ae.height})},Q=ae=>{I(ae,p.width,p.height??900),g(!1),f(me=>({...me,name:ae}))},U=()=>{var me;N("chat"),(me=c.current)==null||me.sendInput("Create a new scenario for this entity based on the work we've just done. Create a name and description that reflects what the live preview is showing. Use the scenario data you've changed to create a new scenario in the database. If the data structure was fixed in any way you need to update that in the database as well and backfill all existing scenarios, then save to the database and capture a screenshot. Remember the database is at `.codeyam/db.sqlite3`, the scenarios table has all scenarios and the analyses table contains the scenariosDataStructure is its metadata.")},F=((s==null?void 0:s.scenarios)||[]).filter(ae=>{var me;return!((me=ae.metadata)!=null&&me.sameAsDefault)}),X=F.findIndex(ae=>ae.id===(r==null?void 0:r.id)),z=X+1,L=F.length,W=X>0,V=X<F.length-1,Z=()=>{if(W){const ae=F[X-1];o(`/entity/${t.sha}/scenarios/${ae.id}/dev`)}},ce=()=>{if(V){const ae=F[X+1];o(`/entity/${t.sha}/scenarios/${ae.id}/dev`)}},ve=$||T||!R;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:[n("img",{src:Or,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),l("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:Z,disabled:!W,className:`${W?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),l("span",{className:"text-gray-400 text-sm",children:[z,"/",L]}),n("button",{onClick:ce,disabled:!V,className:`${V?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),l("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&l("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]}),n("span",{className:"bg-[#005c75] text-white text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wider ml-2",children:"Dev Mode"})]}),n("button",{onClick:B,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close dev mode",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),l("div",{className:"flex-1 flex min-h-0",children:[l("div",{className:"flex-1 flex flex-col min-w-0",children:[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:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Cs[Cs.length-1].width}px`,width:"100%"},children:n(Gr,{currentViewportWidth:u,currentPresetName:p.name,onDevicePresetClick:M,devicePresets:j,hideLabel:!0,onHoverChange:v,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:[n("span",{className:"leading-none",children:(x==null?void 0:x.name)||p.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l("select",{value:p.name,onChange:ae=>{const me=j.find(Se=>Se.name===ae.target.value);me&&M(me)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[j.map(ae=>n("option",{value:ae.name,children:ae.name},ae.name)),p.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:p.width,onChange:ae=>{const me=parseInt(ae.target.value,10);!isNaN(me)&&me>0&&D(me,p.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"x"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:p.height??900}),p.name==="Custom"&&n("button",{onClick:()=>g(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
|
|
118
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
119
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
120
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
121
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
122
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:P?l("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${p.width}px`,maxHeight:`${p.height}px`},children:[ve&&n("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:[n("div",{className:"mb-4",children:n(Ot,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the dev server to be ready"}),H&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(pn,{}),H]})]})]})}),n("iframe",{ref:i,src:Y||P,className:"w-full h-full border-none",title:`Dev mode preview: ${r==null?void 0:r.name}`,onLoad:q,style:{opacity:R?1:0}},J)]}):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:[n("div",{className:"mb-4",children:n(Ot,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Dev Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment with live preview"}),H&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(pn,{}),H]})]})]})})]}),l("aside",{className:"w-[50%] min-w-[400px] max-w-[800px] bg-[#1e1e1e] border-l border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden",children:[l("div",{className:"border-b border-[#3d3d3d] px-4 shrink-0 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-0",children:[l("button",{onClick:()=>N("chat"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${b==="chat"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Chat",b==="chat"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),l("button",{onClick:()=>N("scenarios"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${b==="scenarios"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Scenarios",b==="scenarios"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]})]}),b==="chat"&&n("button",{onClick:U,disabled:!P,className:"px-3 py-1 text-[11px] font-medium rounded bg-[#005c75] text-white hover:bg-[#004a5c] transition-colors disabled:bg-gray-600 disabled:text-gray-400 disabled:cursor-not-allowed cursor-pointer",children:"Save Scenario"})]}),n("div",{style:{display:b==="chat"?"flex":"none"},className:"flex-1 overflow-hidden flex-col",children:n(Ji,{ref:c,entityName:t.name,entityType:t.entityType,entitySha:t.sha,entityFilePath:t.filePath||t.localFilePath,scenarioName:r==null?void 0:r.name,scenarioDescription:r==null?void 0:r.description,analysisId:s==null?void 0:s.id,projectSlug:a,onRefreshPreview:E})}),b==="scenarios"&&n(Zm,{scenarios:F,currentScenarioId:r==null?void 0:r.id,entitySha:t.sha,cacheBuster:0})]})]}),n(Wi,{serverUrl:P,isStarting:$,projectSlug:a}),y&&n(Kr,{width:p.width,height:p.height??900,onSave:Q,onCancel:()=>g(!1)})]})}),th=Object.freeze(Object.defineProperty({__proto__:null,default:eh,loader:Xm},Symbol.toStringTag,{value:"Module"}));async function nh({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{url:r,filename:s,viewportWidth:a,viewportHeight:o}=t;if(!r||!s)return new Response(JSON.stringify({error:"url and filename are required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=process.env.CODEYAM_ROOT_PATH||process.cwd(),c=O.join(i,".codeyam","journal","screenshots");await we.mkdir(c,{recursive:!0});const d=s.replace(/[^a-zA-Z0-9_\-T]/g,"_"),m=O.join(c,`${d}.png`),u=O.dirname(new URL(import.meta.url).pathname);let h=u;for(let v=0;v<5;v++){const b=O.dirname(h);if(O.basename(b)==="webserver"||O.basename(h)==="webserver"){h=O.basename(h)==="webserver"?h:b;break}h=b}const p=[O.join(h,"scripts","journalCapture.ts"),O.join(h,"app","lib","journalCapture.ts"),O.join(i,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),O.resolve(u,"..","lib","journalCapture.ts")];let f="";for(const v of p)try{await we.access(v),f=v;break}catch{}f||(console.warn(`[editor-journal-screenshot] journalCapture.ts not found in any of: ${p.join(", ")}`),f=p[0]);const y=JSON.stringify({url:r,outputPath:m,viewportWidth:a,viewportHeight:o}),g=await new Promise(v=>{const b=kt("npx",["tsx",f,y],{cwd:i,env:{...process.env}});let N="",w="";b.stdout.on("data",S=>{N+=S.toString()}),b.stderr.on("data",S=>{w+=S.toString()}),b.on("close",S=>{v(S===0?{success:!0,output:N}:{success:!1,output:N,error:w||`Process exited with code ${S}`})}),b.on("error",S=>{v({success:!1,output:"",error:S.message})})});if(!g.success)return new Response(JSON.stringify({error:"Failed to capture screenshot",details:g.error}),{status:500,headers:{"Content-Type":"application/json"}});const x=`screenshots/${d}.png`;return new Response(JSON.stringify({success:!0,path:x}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-screenshot] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const rh=Object.freeze(Object.defineProperty({__proto__:null,action:nh},Symbol.toStringTag,{value:"Module"})),Hi=Xs({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),ga=()=>{const e=Rr(Hi);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},Zr=({children:e})=>{const[t,r]=_({height:720,width:1200}),[s,a]=_(1),[o,i]=_(1200),c=be(null),d=oe(({height:h,width:p})=>{r(f=>({height:h??f.height,width:p??f.width}))},[]),m=oe(h=>{a(h)},[]),u=oe(h=>{i(h)},[]);return n(Hi.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:c,scale:s,updateScale:m,maxWidth:o,updateMaxWidth:u},children:e})},sh=typeof window<"u";function ah(){const[e,t]=_(null);return te(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const oh=1200,ih=720,mo=30,lh=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:s=1440,defaultHeight:a=900,onDataOverride:o,onIframeLoad:i,onScaleChange:c,onDimensionChange:d})=>{const m=ah(),[u,h]=_(!1),[p,f]=_(!1),[y,g]=_(oh),[x,v]=_(ih),[b,N]=_(null),[w,S]=_(null),{dimensions:C,updateDimensions:k,iframeRef:E,updateScale:A,updateMaxWidth:I}=ga(),j=ne(()=>Math.min(1,y/C.width),[y,C.width]),P=w!==null?w:j;te(()=>{u||(A(P),c==null||c(P))},[P,A,c,u]),te(()=>{I(y)},[y,I]);const $=oe(()=>{h(!0),S(j)},[j]),T=oe(()=>{h(!1),S(null)},[]),R=oe((B,D)=>{const M=w!==null?w:1,Q=Math.round(D.size.width/M);k({width:Q}),d==null||d(Q,C.height)},[k,w,d,C.height]),J=oe(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);te(()=>{const B=D=>{if(D.data.type==="codeyam-resize"){if(t&&D.data.name!==t||C.height===D.data.height||D.data.height===0)return;k({height:D.data.height})}};return window.addEventListener("message",B),()=>{window.removeEventListener("message",B)}},[E,t,s,C,k]),te(()=>{p&&o&&o(E.current)},[p,o,E]),te(()=>{if(!t)return;const B=setInterval(()=>{var D,M;(M=(D=E==null?void 0:E.current)==null?void 0:D.contentWindow)==null||M.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(B)},[t,E]),te(()=>{const B=()=>{const D=document.getElementById("scenario-container");if(!D)return;const M=D.getBoundingClientRect(),Q=D.clientWidth-mo*2,U=window.innerHeight-M.top-mo*2,F=Math.max(U,400),X=window.innerHeight-M.top;g(Q),v(F),N(X)};return B(),window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[]),te(()=>{k({width:s,height:a})},[s,a,k]);const q=ne(()=>C.width*P,[C.width,P]),Y=ne(()=>{const B=C.height,D=B*P;return B&&B!==720&&B!==900&&D<x?D:x},[C.height,x,P]),H=oe(()=>{window.history.back()},[]);return!sh||!m?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):l("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:b?{height:`${b}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
|
|
123
|
+
.react-resizable-handle-e {
|
|
124
|
+
display: flex !important;
|
|
125
|
+
align-items: center !important;
|
|
126
|
+
justify-content: center !important;
|
|
127
|
+
width: 6px !important;
|
|
128
|
+
height: 48px !important;
|
|
129
|
+
right: -8px !important;
|
|
130
|
+
top: 50% !important;
|
|
131
|
+
transform: translateY(-50%) !important;
|
|
132
|
+
cursor: ew-resize !important;
|
|
133
|
+
background: #d1d5db !important;
|
|
134
|
+
border-radius: 3px !important;
|
|
135
|
+
opacity: 0 !important;
|
|
136
|
+
transition: all 0.2s ease !important;
|
|
137
|
+
}
|
|
138
|
+
.react-resizable-handle-e:hover {
|
|
139
|
+
opacity: 0.8 !important;
|
|
140
|
+
background: #9ca3af !important;
|
|
141
|
+
}
|
|
142
|
+
.react-resizable:hover .react-resizable-handle-e {
|
|
143
|
+
opacity: 0.4 !important;
|
|
144
|
+
}
|
|
145
|
+
`}),n(m,{width:q,height:Y,minConstraints:[300,200],maxConstraints:[y,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:$,onResizeStop:T,onResize:R,children:n("div",{className:"overflow-auto",style:{width:`${q}px`,height:`${Y}px`},children:n("div",{style:{width:`${C.width}px`,height:`${C.height}px`,transform:`scale(${P})`,transformOrigin:"top left"},children:r?n("iframe",{ref:E,className:"w-full h-full rounded-lg",src:r,onLoad:J,sandbox:"allow-scripts allow-same-origin"}):l("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[n("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),n("span",{className:"text-blue-600 cursor-pointer",onClick:H,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function ch({presets:e,customSizes:t,currentWidth:r,currentHeight:s,scale:a,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:c,className:d=""}){const[m,u]=_(!1),[h,p]=_(String(r)),[f,y]=_(String(s)),[g,x]=_(!1),[v,b]=_(!1),N=be(null);te(()=>{g||p(String(r))},[r,g]),te(()=>{v||y(String(s))},[s,v]),te(()=>{const P=$=>{N.current&&!N.current.contains($.target)&&u(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[]);const w=ne(()=>{const P=e.find(T=>T.width===r&&T.height===s);if(P)return P.name;const $=t.find(T=>T.width===r&&T.height===s);return $?$.name:"Custom"},[e,t,r,s]),S=w==="Custom",C=P=>{o(P.width,P.height),u(!1)},k=P=>{const $=P.target.value;p($);const T=parseInt($,10);!isNaN(T)&&T>0&&o(T,s)},E=P=>{const $=P.target.value;y($);const T=parseInt($,10);!isNaN(T)&&T>0&&o(r,T)},A=()=>{x(!1);const P=parseInt(h,10);(isNaN(P)||P<=0)&&p(String(r))},I=()=>{b(!1);const P=parseInt(f,10);(isNaN(P)||P<=0)&&y(String(s))},j=P=>{(P.key==="Enter"||P.key==="Escape")&&P.target.blur()};return l("div",{className:`flex items-center gap-3 ${d}`,children:[l("div",{className:"relative",ref:N,children:[l("button",{onClick:()=>u(!m),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:w}),n("svg",{className:`w-4 h-4 transition-transform ${m?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),m&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:l("div",{className:"py-1",children:[e.length>0&&l(ue,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(P=>l("button",{onClick:()=>C(P),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${w===P.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:P.name}),l("span",{className:"text-xs text-gray-500",children:[P.width," x ",P.height]})]},P.name))]}),t.length>0&&l(ue,{children:[n("div",{className:"border-t border-gray-100 my-1"}),n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Custom"}),[...t].sort((P,$)=>P.width-$.width).map(P=>l("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${w===P.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[l("button",{onClick:()=>C(P),className:"flex-1 text-left px-3 py-2 text-sm flex justify-between items-center gap-4 whitespace-nowrap cursor-pointer",children:[n("span",{children:P.name}),l("span",{className:"text-xs text-gray-500",children:[P.width," x ",P.height]})]}),c&&n("button",{onClick:$=>{$.stopPropagation(),w===P.name&&e.length>0&&o(e[0].width,e[0].height),c(P.name)},className:"p-1.5 mr-1 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded cursor-pointer transition-colors",title:"Remove custom size",children:n("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},P.name))]})]})})]}),l("div",{className:"flex items-center gap-1 text-sm",children:[l("div",{className:"flex items-center",children:[n("input",{type:"text",value:h,onChange:k,onFocus:()=>x(!0),onBlur:A,onKeyDown:j,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),l("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:E,onFocus:()=>b(!0),onBlur:I,onKeyDown:j,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),a!==void 0&&a<1&&l("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(a*100),"%)"]})]}),S&&n("button",{onClick:i,className:"px-3 py-1.5 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors",children:"Save Custom Size"})]})}function Ss(e,t,r){if(Array.isArray(e)){if(!isNaN(parseInt(t)))return e[parseInt(t)];for(const s of e)if(s.name===t||s.title===t||s.id===t)return s}return e[t]}function Us(e){return e&&(typeof e=="object"||Array.isArray(e))}function dh(e){return Array.isArray(e)?e.length:void 0}function uh(e){const{data:t,structure:r}=e;if(!(!t&&!r)){if(Array.isArray(r))return Array.isArray(t)?t.map((s,a)=>a.toString()):[];if(typeof r=="object")return[...new Set([...Object.keys(t),...Object.keys(r)])].sort((a,o)=>{const i=Us(t[a]),c=Us(t[o]);return i&&!c?1:!i&&c?-1:a.localeCompare(o)});if(typeof t=="object")return Object.keys(t).sort((a,o)=>a.localeCompare(o))}}function mh({scenarioFormData:e,handleInputChange:t}){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:[n("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),n("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),l("div",{className:"grid w-full gap-1.5 pt-2",children:[n("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),n("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[100px]"})]}),n("button",{type:"submit",className:"mt-3 w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium",children:"Save Name & Description"})]})}function hh({path:e,namedPath:t,isArray:r,count:s,onClick:a}){const o=oe(()=>{a&&a(e)},[a,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:o,children:[l("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),l("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],s!==void 0&&` (${s})`]})]}),l("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var Vi=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Vi||{});const ph=({name:e,value:t,options:r,onChange:s})=>{const a=oe(o=>{s({target:{name:e,value:o.target.value}})},[e,s]);return n("select",{name:e,value:t,onChange:a,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",children:r.map((o,i)=>n("option",{value:o.trim(),children:o.trim()},i))})},fh=({name:e,value:t,onChange:r})=>{const s=oe(a=>{const o=a.target.checked;r({target:{name:e,value:o}})},[e,r]);return n("label",{className:"flex items-center gap-2 cursor-pointer",children:n("input",{type:"checkbox",name:e,checked:t,onChange:s,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
|
|
146
|
+
bg-gray-300 checked:bg-blue-600
|
|
147
|
+
after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
|
|
148
|
+
after:bg-white after:rounded-full after:transition-transform
|
|
149
|
+
checked:after:translate-x-4`})})};function gh({dataType:e,path:t,value:r,onChange:s}){const a=ne(()=>t[t.length-1],[t]),o=ne(()=>t.join("-"),[t]),i=oe(d=>{s(t,d.target.value)},[s,t]),c=oe(d=>{s(t,d.target.value)},[s,t]);return l("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:o,className:"capitalize text-sm font-medium text-gray-700",children:a==="~~codeyam-code~~"?"Dynamic Field":a}),e.includes("|")?n(ph,{name:o,value:r,options:e.split("|"),onChange:i}):e===Vi.BOOLEAN?n(fh,{name:o,value:r??!1,onChange:c}):n("input",{id:o,name:o,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${o}`)]})}function yh({analysis:e,scenarioName:t,dataItem:r,onResult:s,onGenerateData:a}){const[o,i]=_(!1),[c,d]=_(""),m=oe(async()=>{if(!a){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const h=e.scenarios.find(x=>x.name===t);if(!h)throw new Error("Scenario not found");const p=e.scenarios.find(x=>x.name===Fr),f=await a(c,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const y=(x,v)=>{const b=Object.assign({},x);return g(x)&&g(v)&&Object.keys(v).forEach(N=>{g(v[N])?N in x?b[N]=y(x[N],v[N]):Object.assign(b,{[N]:v[N]}):Object.assign(b,{[N]:v[N]})}),b},g=x=>x&&typeof x=="object"&&!Array.isArray(x);h.metadata.data=y(y((p==null?void 0:p.metadata.data)||{},h.metadata.data),f.data||{}),s(h),i(!1),d("")}catch(h){console.error("Error generating AI data:",h),i(!1)}},[e,c,r,t,s,a]),u=oe(h=>{d(h.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:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:c}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${c.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void m(),children:o?l(ue,{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:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Please wait"]}):"Generate Data"})]})}function xh({namedPath:e,path:t,last:r,onClick:s}){const a=oe(()=>s(r?t.slice(0,-1):t),[r,t,s]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:a,children:e[e.length-1]})}function bh({dataItem:e,onClick:t}){const r=oe(()=>t([]),[t]),s=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:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&l("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(s).map((a,o)=>l("div",{className:"flex items-center gap-1",children:[n(xh,{namedPath:e.namedPath.slice(0,o+s+1),path:e.path.slice(0,o+s+1),last:o+s===e.namedPath.length-1,onClick:t}),o+s<e.namedPath.length-1&&n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},`path-${a}-${o+s}`))]})}function ho({analysis:e,scenarioName:t,dataItem:r,onClick:s,onChange:a,onAIResult:o,onGenerateData:i,saveFeedback:c}){const d=ne(()=>r.data,[r]),m=ne(()=>uh(r),[r]);return l("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(bh,{dataItem:r,onClick:s}),l("div",{className:"flex flex-col gap-3",children:[n(yh,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),m==null?void 0:m.map((u,h)=>{var f;if(Us(d[u])){let y=u;isNaN(Number(u))||(y=d[u].name??d[u].title??d[u].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const g=[...r.path,u],x=[...r.namedPath,y];return n(hh,{path:g,namedPath:x,isArray:Array.isArray(d),count:dh(d[u]),onClick:s},`data-${u}-${h}`)}if(u==="id")return null;const p=[...r.path,u];return n(gh,{dataType:((f=r.structure)==null?void 0:f[u])??"string",path:p,value:d[u],onChange:a},`InputField-${p.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),l("div",{className:"flex gap-2",children:[n("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"}),n("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)&&n("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 po({title:e,children:t,defaultOpen:r=!1,borderT:s=!1,borderB:a=!1}){const[o,i]=_(r),c=[];return s&&c.push("border-t"),a&&c.push("border-b"),l("div",{className:`${c.join(" ")} border-gray-300`,children:[l("button",{type:"button",onClick:()=>i(!o),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${o?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),o&&n("div",{className:"px-4 py-3",children:t})]})}const vh=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:s,shouldCreateNewScenario:a,onSave:o,onNavigate:i,iframeRef:c,onGenerateData:d,saveFeedback:m})=>{const u=oe((k,E)=>{const A=Object.assign({},k),I=j=>j&&typeof j=="object"&&!Array.isArray(j);return I(k)&&I(E)&&Object.keys(E).forEach(j=>{I(E[j])?j in k?A[j]=u(k[j],E[j]):Object.assign(A,{[j]:E[j]}):Object.assign(A,{[j]:E[j]})}),A},[]),[h,p]=_({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,y]=_(null),g=ne(()=>({...h.data}),[h]),x=ne(()=>({...g.mockData?{"Retrieved Data":g.mockData}:{},...g.argumentsData?{"Function Arguments":g.argumentsData}:{}}),[g]),v=ne(()=>{const k={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(k).reduce((E,A)=>{if(A.includes(".")){const[I,j]=A.split(".");E[I]||(E[I]={}),E[I][j]=k[A]}else E[A]=k[A];return E},{})},[r]),b=oe(async k=>{k.preventDefault();const E=k.target.querySelector('input[name="recapture"]'),A=(E==null?void 0:E.value)==="true",I={mockData:h.data.mockData??{},argumentsData:h.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:h.name,shouldRecapture:A,dataToSave:I,rawFormData:h.data,iframePayload:{arguments:g.argumentsData??[],...g.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(I,null,2).substring(0,1e3));const j=s==null?void 0:s.scenarios.map(P=>!a&&P.name===e.name?{...P,name:h.name,description:h.description,metadata:{...P.metadata,data:I}}:P);a&&j.push({name:h.name,description:h.description,metadata:{data:I,interactiveExamplePath:s==null?void 0:s.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",j),o&&await o(j,{recapture:A}),i&&i(h.name)},[s,e.name,h,g,a,o,i]),N=oe(k=>{p(E=>({...E,[k.target.name]:k.target.value}))},[]),w=oe(k=>{y(E=>{if(!E)return null;for(const A of[{arguments:k.metadata.data.argumentsData},k.metadata.data.mockData]){let I=A;for(const j of E.path)if(I=Ss(I,j),!I)break;I&&(E.data=I)}return{...E}}),p({name:k.name,description:k.description,data:k.metadata.data})},[]),S=oe((k,E)=>{p(A=>{for(const I of[{"Function Arguments":A.data.argumentsData},{"Retrieved Data":A.data.mockData}]){let j=I;for(const P of k.slice(0,-1))if(j=Ss(j,P),!j)break;if(j){const P=j[k[k.length-1]];y($=>$?($.namedPath[$.namedPath.length-1]===P&&($.namedPath[$.namedPath.length-1]=E.toString()),$.data[k[k.length-1]]=E,{...$}):null),j[k[k.length-1]]=E}}return{...A}})},[]),C=oe(k=>{var j,P,$;if(k.length===0){y(null);return}let E=x;const A=[];let I=v;for(const T of k){if(A.push(isNaN(parseInt(T))?T:((j=E[T])==null?void 0:j.name)??((P=E[T])==null?void 0:P.title)??(($=E[T])==null?void 0:$.id)??T),E=Ss(E,T),!E){console.log("Data not found",E,T),y(null);return}Array.isArray(I)?I=I[0]:I=I[T]}y({path:k,namedPath:A,data:E,structure:I})},[x,v]);return te(()=>{const k=E=>{var A;E.data.type==="codeyam-log"&&((A=E.data.data)!=null&&A.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",E.data.data)};return window.addEventListener("message",k),()=>window.removeEventListener("message",k)},[]),te(()=>{var k;if((k=c==null?void 0:c.current)!=null&&k.contentWindow){const E={arguments:g.argumentsData??[],...g.mockData??{}},A={type:"codeyam-override-data",name:e.name,data:JSON.stringify(E)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:A.type,name:A.name,dataPreview:JSON.stringify(E).substring(0,200)+"...",fullData:E}),c.current.contentWindow.postMessage(A,"*")}},[g,e,c]),n("form",{method:"post",onSubmit:k=>void b(k),children:f?n(ho,{analysis:s,scenarioName:h.name,dataItem:f,onClick:C,onChange:S,onAIResult:w,onGenerateData:d,saveFeedback:m}):l(ue,{children:[n(po,{title:"Edit Name and Description",borderT:!0,children:n(mh,{scenarioFormData:h,handleInputChange:N})}),e.metadata.data&&n(po,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(ho,{analysis:s,scenarioName:h.name,dataItem:{path:[],namedPath:[],data:x,structure:v},onClick:C,onChange:S,onAIResult:w,onGenerateData:d,saveFeedback:m})})]})})};function Xr({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:s,isLoading:a,showIframe:o,iframeKey:i,onIframeLoad:c,onScaleChange:d,onDimensionChange:m,projectSlug:u,defaultWidth:h=1440,defaultHeight:p=900,retryCount:f=0}){const{lastLine:y}=Et(u??null,s||a);return r?l("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:o?1:0,background:"transparent"},children:n(lh,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:h,defaultHeight:p,onIframeLoad:c,onScaleChange:d,onDimensionChange:m},i)}),!o&&(s||a)&&n("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:[n("div",{className:"mb-4",children:n(Ot,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(pn,{}),y]})]})]})})]}):n("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:[n("div",{className:"mb-4",children:n(Ot,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(pn,{}),y]})]})]})})}const wh=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Nh({params:e}){var d,m;const{sha:t,scenarioId:r}=e;if(!t)throw new Response("Entity SHA is required",{status:400});if(!r)throw new Response("Scenario ID is required",{status:400});const s=await Br(t,!0),a=s&&s.length>0?s[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const o=(d=a.scenarios)==null?void 0:d.find(u=>u.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=(m=a.scenarios)==null?void 0:m.find(u=>u.name===Fr),c=await $e();return K({analysis:a,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:c})}function Ch(){var T,R,J;const e=Ve(),t=e.analysis,r=e.scenario,s=e.defaultScenario,a=e.entitySha,o=e.projectSlug,i=St(),{iframeRef:c}=ga(),[d,m]=_(!1),[u,h]=_(null),[p,f]=_(null),[y,g]=_(!1),[x,v]=_(!1),[b,N]=_(null),{interactiveServerUrl:w,isStarting:S,isLoading:C,showIframe:k,iframeKey:E,onIframeLoad:A}=nn({analysisId:t==null?void 0:t.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0}),I=oe(async(q,Y)=>{m(!0),h(null),f(null),console.log("[EditScenario] Starting save with options:",Y),console.log("[EditScenario] Scenarios to save:",q);try{const H={analysis:t,scenarios:q};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:q.length,scenarioNames:q.map(M=>M.name)});const B=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)}),D=await B.json();if(console.log("[EditScenario] API response:",D),!B.ok||!D.success)throw new Error(D.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),Y!=null&&Y.recapture&&r.id&&w){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:w}),h("Changes saved. Capturing screenshot...");const M={serverUrl:w,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",M);const Q=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});console.log("[EditScenario] Capture response status:",Q.status);const U=await Q.json();if(console.log("[EditScenario] Capture response body:",U),!Q.ok||!U.success)throw console.error("[EditScenario] Capture failed:",U),new Error(U.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",U),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),h("Recapture successful")}else if(Y!=null&&Y.recapture&&!w){console.log("[EditScenario] No running server, using queued recapture");const M=new FormData;M.append("analysisId",t.id||""),M.append("scenarioId",r.id||"");const Q=await fetch("/api/recapture-scenario",{method:"POST",body:M}),U=await Q.json();if(!Q.ok||!U.success)throw new Error(U.error||"Failed to trigger recapture");console.log("Recapture queued:",U),f(U.jobId),h("Changes saved. Screenshot recapture queued.")}else h("Changes saved successfully.")}catch(H){console.error("Error saving scenarios:",H),h(`Error: ${H instanceof Error?H.message:String(H)}`)}finally{m(!1)}},[t,r.id,w]),j=oe(q=>{},[]),P=oe(async(q,Y)=>{var D;const H=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:q,existingScenarios:t.scenarios,scenariosDataStructure:(D=t.metadata)==null?void 0:D.scenariosDataStructure,editingMockName:r.name,editingMockData:Y==null?void 0:Y.data})}),B=await H.json();if(!H.ok||!B.success)throw new Error(B.error||"Failed to generate scenario data");return B.data},[t,r.name]),$=oe(async()=>{var q;if(!r.id){N("Cannot delete scenario without ID");return}g(!0),N(null);try{const Y=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((q=r.metadata)==null?void 0:q.screenshotPaths)||[]})}),H=await Y.json();if(!Y.ok||!H.success)throw new Error(H.error||"Failed to delete scenario");i(`/entity/${a}`)}catch(Y){console.error("[EditScenario] Error deleting scenario:",Y),N(Y instanceof Error?Y.message:"Failed to delete scenario"),v(!1)}finally{g(!1)}},[r.id,(T=r.metadata)==null?void 0:T.screenshotPaths,a,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:[n("div",{className:"mb-4",children:l(de,{to:`/entity/${a}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(R=t.entity)==null?void 0:R.name]})}),l("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",r.name]}),r.description&&n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:r.description})]}),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:[n(vh,{currentScenario:r,defaultScenario:s,dataStructure:((J=t.metadata)==null?void 0:J.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:I,onNavigate:j,iframeRef:c,onGenerateData:P,saveFeedback:{isSaving:d,message:u,isError:(u==null?void 0:u.startsWith("Error"))??!1}}),u==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(de,{to:`/entity/${a}`,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:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),x?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 "',r.name,'"?']}),l("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void $(),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"}),n("button",{onClick:()=>v(!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"})]})]}):n("button",{onClick:()=>v(!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"}),b&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:b})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(Xr,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:w,isStarting:S,isLoading:C,showIframe:k,iframeKey:E,onIframeLoad:A,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const Sh=Je(function(){return n(Zr,{children:n(Ch,{})})}),kh=Object.freeze(Object.defineProperty({__proto__:null,default:Sh,loader:Nh,meta:wh},Symbol.toStringTag,{value:"Module"}));function Eh(e){return Bn.createHash("sha256").update(JSON.stringify(e)).digest("hex")}function Ah(e){const t=e.match(/^(GET|POST|PUT|DELETE|PATCH)\s+(\/\S+)$/);return t?{method:t[1],pathPattern:t[2]}:{method:null,pathPattern:e}}function Ph(e){const t=[],r=e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(s,a)=>(t.push(a),"([^/]+)"));return{regex:new RegExp(`^${r}$`),paramNames:t}}function _h(e,t){if(t.includes(e))return e;const r=e.lastIndexOf("/");if(r>0){const s=e.substring(0,r);if(t.includes(s))return s}return null}function jh(){let e=[],t={},r=null,s=null,a=!1,o=null;function i(m){const u=[],h=m.routes;if(h&&typeof h=="object")for(const[p,f]of Object.entries(h)){const{method:y,pathPattern:g}=Ah(p),{regex:x,paramNames:v}=Ph(g),b=typeof f=="object"&&f!==null?f:{body:f};u.push({method:y,pathPattern:g,pathRegex:x,paramNames:v,response:{body:b.body,status:typeof b.status=="number"?b.status:200}})}return u}function c(m){const u=m.state;if(u&&typeof u=="object"){a=!0,t={};for(const[h,p]of Object.entries(u))t[h]=Array.isArray(p)?JSON.parse(JSON.stringify(p)):[];r=JSON.stringify(u)}else a=!1,t={},r=null}return{loadScenario(m){const u=Eh(m);s&&u===s||(s=u,o=m,e=i(m),c(m))},matchRequest(m,u,h){if(!o&&e.length===0&&!a)return null;const p=Object.keys(t);if(a){const y=_h(u,p);if(y&&m==="GET"&&y===u)return{body:t[y],status:200};if(y){const g=d(m,u);if(m==="POST"&&y===u&&g){const x=t[y],v=typeof h=="object"&&h!==null?{...h}:{};if(!("id"in v)){const b=x.reduce((N,w)=>{const S=typeof w.id=="number"?w.id:0;return Math.max(N,S)},0);v.id=b+1}return x.push(v),{body:v,status:g.response.status}}if(m==="DELETE"&&g&&g.params){const x=g.params.id,v=t[y],b=v.findIndex(N=>String(N.id)===String(x));return b===-1?{body:{error:"Not found"},status:404}:(v.splice(b,1),{body:null,status:g.response.status})}if(m==="PUT"&&g&&g.params){const x=g.params.id,v=t[y],b=v.findIndex(w=>String(w.id)===String(x));if(b===-1)return{body:{error:"Not found"},status:404};const N=typeof h=="object"&&h!==null?{...h}:v[b];return v[b]=N,{body:N,status:g.response.status}}}}const f=d(m,u);if(f)return{body:f.response.body??null,status:f.response.status,params:f.params};if(o&&m==="GET"){const y=u.match(/^\/api\/(.+)$/);if(y){const g=y[1];if(g in o&&g!=="routes"&&g!=="state")return{body:o[g],status:200}}}return null},resetState(){if(r){const m=JSON.parse(r);t={};for(const[u,h]of Object.entries(m))t[u]=Array.isArray(h)?JSON.parse(JSON.stringify(h)):[]}},getState(){return{...t}}};function d(m,u){for(const h of e)if(h.method!==null&&h.method===m&&h.paramNames.length===0&&h.pathRegex.exec(u))return{response:h.response};if(m==="GET"){for(const h of e)if(h.method===null&&h.paramNames.length===0&&h.pathRegex.exec(u))return{response:h.response}}for(const h of e)if(h.paramNames.length>0){if((h.method??"GET")!==m)continue;const f=h.pathRegex.exec(u);if(f){const y={};for(let g=0;g<h.paramNames.length;g++)y[h.paramNames[g]]=f[g+1];return{response:h.response,params:y}}}return null}}const qi="__codeyam_editor_proxy__",Mh=500;let wt={data:null,timestamp:0};const fo=10*1024*1024;function Gi(){return globalThis[qi]??null}function Ki(e){globalThis[qi]=e}function Qi(){const e="__codeyam_mock_state__";return globalThis[e]||(globalThis[e]=jh()),globalThis[e]}function Zi(){const e=Gi();return e?`http://localhost:${e.port}`:null}function Th(){const e=Date.now();if(wt.data!==null&&e-wt.timestamp<Mh)return wt.data;const t=he()||process.env.CODEYAM_ROOT_PATH||process.cwd(),r=ee.join(t,".codeyam","active-scenario.json");try{if(!Ce.existsSync(r))return wt={data:null,timestamp:e},null;const a=JSON.parse(Ce.readFileSync(r,"utf-8")).scenarioId;if(!a)return wt={data:null,timestamp:e},null;const o=ee.join(t,".codeyam","editor-scenarios",`${a}.json`);if(!Ce.existsSync(o))return console.log(`[editorProxy] Scenario data file not found: ${o}`),wt={data:null,timestamp:e},null;const i=JSON.parse(Ce.readFileSync(o,"utf-8"));return wt={data:i,timestamp:e},Qi().loadScenario(i),i}catch(s){return console.warn("[editorProxy] Error reading scenario data:",s),wt={data:null,timestamp:e},null}}function $h(e){return new Promise(t=>{const r=[];let s=0;e.on("data",a=>{s+=a.length,s>fo?(t(null),e.resume()):r.push(a)}),e.on("end",()=>{s>fo||t(Buffer.concat(r))}),e.on("error",()=>{t(null)})})}function go(e,t,r,s){const a=new URL(r),o={...e.headers,host:`${a.hostname}:${a.port}`};s&&(o["content-length"]=String(s.length));const i={hostname:a.hostname,port:a.port,path:e.url,method:e.method,headers:o},c=oa.request(i,d=>{t.writeHead(d.statusCode||200,d.headers),d.pipe(t,{end:!0})});c.on("error",d=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${d.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),s&&s.length>0?c.end(s):c.end()}function Rh(e,t,r){const s=new URL(r),a={hostname:s.hostname,port:s.port,path:e.url,method:e.method,headers:{...e.headers,host:`${s.hostname}:${s.port}`}},o=oa.request(a,i=>{t.writeHead(i.statusCode||200,i.headers),i.pipe(t,{end:!0})});o.on("error",i=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${i.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),e.pipe(o,{end:!0})}function Ih(e,t,r,s){const a=new URL(s),o=parseInt(a.port,10)||80;console.log(`[editorProxy] WebSocket upgrade: ${e.url} → ${a.hostname}:${o}`);const i=ed.connect(o,a.hostname,()=>{const c=`${e.method} ${e.url} HTTP/${e.httpVersion}\r
|
|
150
|
+
`,d=Object.entries(e.headers).filter(([,m])=>m!=null).map(([m,u])=>`${m}: ${Array.isArray(u)?u.join(", "):u}`).join(`\r
|
|
151
|
+
`);i.write(c+d+`\r
|
|
152
|
+
\r
|
|
153
|
+
`),r.length>0&&i.write(r),i.pipe(t,{end:!0}),t.pipe(i,{end:!0})});i.on("error",c=>{console.warn(`[editorProxy] WebSocket proxy error: ${c.message}`),t.destroy()}),t.on("error",()=>{i.destroy()})}function Dh(e,t){const r=he()||process.env.CODEYAM_ROOT_PATH||process.cwd(),s=ee.join(r,".codeyam","proxy-config.json");try{Ce.mkdirSync(ee.dirname(s),{recursive:!0}),Ce.writeFileSync(s,JSON.stringify({proxyUrl:`http://localhost:${e}`,devServerUrl:t}),"utf-8"),console.log(`[editorProxy] Wrote proxy config to ${s}`)}catch(a){console.warn("[editorProxy] Failed to write proxy-config.json:",a)}}function Lh(){const e=he()||process.env.CODEYAM_ROOT_PATH||process.cwd(),t=ee.join(e,".codeyam","proxy-config.json");try{Ce.existsSync(t)&&Ce.unlinkSync(t)}catch{}}async function Xi(e){await el();const{targetUrl:t}=e;let r=e.port;console.log(`[editorProxy] Starting proxy (requested port ${r}, target ${t})`);const s=Qi(),a=oa.createServer((i,c)=>{(async()=>{const m=new URL(i.url||"/",`http://localhost:${r}`).pathname,u=i.method||"GET";if(u==="OPTIONS"){c.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Max-Age":"86400"}),c.end();return}if(Th(),u==="POST"||u==="PUT"||u==="DELETE"||u==="PATCH"){const f=await $h(i);if(f===null){go(i,c,t,null);return}let y;if(f.length>0)try{y=JSON.parse(f.toString("utf-8"))}catch{}const g=s.matchRequest(u,m,y);if(g){console.log(`[editorProxy] Intercepted ${u} ${m} → mock response (status ${g.status})`),c.writeHead(g.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data"}),c.end(g.body!=null?JSON.stringify(g.body):"");return}go(i,c,t,f);return}const p=s.matchRequest(u,m);if(p){console.log(`[editorProxy] Intercepted ${u} ${m} → mock response (status ${p.status})`),c.writeHead(p.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data"}),c.end(p.body!=null?JSON.stringify(p.body):"");return}Rh(i,c,t)})()});a.on("upgrade",(i,c,d)=>{Ih(i,c,d,t)});const o=10;for(let i=0;i<o;i++){const c=r+i;try{return await new Promise((m,u)=>{a.once("error",u),a.listen(c,"0.0.0.0",()=>{a.removeListener("error",u),m()})}),r=c,Ki({server:a,port:r,targetUrl:t}),Dh(r,t),console.log(`[editorProxy] Proxy started on port ${r}, forwarding to ${t}`),{port:r}}catch(d){if((d==null?void 0:d.code)==="EADDRINUSE"&&i<o-1){console.log(`[editorProxy] Port ${c} in use, trying ${c+1}`);continue}return console.error("[editorProxy] Failed to start proxy:",d),null}}return null}async function el(){const e=Gi();if(e)return console.log(`[editorProxy] Stopping proxy on port ${e.port}`),Lh(),new Promise(t=>{e.server.close(()=>{console.log("[editorProxy] Proxy stopped"),t()}),Ki(null),setTimeout(t,2e3)})}function tl(){wt={data:null,timestamp:0}}async function nl(){const e=Zi();if(e)return console.log(`[editorProxy] Proxy already running at ${e}`),e;const t=globalThis.__codeyam_editor_dev_server__;if(!t||t.status!=="running"||!t.url)return console.log("[editorProxy] Cannot start proxy — dev server not running"),null;const r=parseInt(process.env.CODEYAM_PORT||"3111",10);console.log(`[editorProxy] Proxy not running, starting on-demand (port ${r+1}, target ${t.url})`);const s=await Xi({port:r+1,targetUrl:t.url});if(s){const a=`http://localhost:${s.port}`;return console.log(`[editorProxy] On-demand proxy started at ${a}`),a}return console.error("[editorProxy] Failed to start on-demand proxy"),null}function rl(e){const t=[];for(const r of e.split(`
|
|
154
|
+
`))r.includes("[JournalCapture] Page console.error:")?t.push(r.replace(/.*\[JournalCapture\] Page console\.error:\s*/,"")):r.includes("[JournalCapture] Network failed:")&&t.push(r.replace(/.*\[JournalCapture\] /,""));return t}async function sl(e,t,r,s){const a=O.join(e,".codeyam","editor-scenarios","client-errors.json");let o={};try{const i=await we.readFile(a,"utf8");o=JSON.parse(i)}catch{}o[t]={scenarioName:r,capturedAt:new Date().toISOString(),errors:s},await we.mkdir(O.dirname(a),{recursive:!0}),await we.writeFile(a,JSON.stringify(o,null,2),"utf8")}async function Oh(e){const t=O.join(e,".codeyam","editor-scenarios","client-errors.json");try{const r=await we.readFile(t,"utf8");return JSON.parse(r)}catch{return{}}}function es(e,t){const r=new Map;for(const s of e)r.set(t(s),s);return[...r.values()]}function Vt(e){return e.replace(/[^a-zA-Z0-9_]+/g,"_")}function Pr(e){return e.replace("T"," ").replace(/\.\d{3}Z$/,"")}function al(e,t,r){const s=e&&e.startsWith("/");return s&&t?`${t}${e}`:e&&!s?e:t||r||null}async function Fh(e,t,r){const s=O.join(e,".codeyam","journal"),a=O.join(s,"index.json");O.join(s,"screenshots");let o;try{const c=await we.readFile(a,"utf8");o=JSON.parse(c)}catch{return}let i=!1;for(const c of o.entries)if(!c.commitSha&&c.scenarioScreenshots)for(let d=0;d<c.scenarioScreenshots.length;d++){const m=c.scenarioScreenshots[d];if(m.name!==t)continue;const u=O.join(s,m.path);try{await we.copyFile(r,u),i=!0,console.log(`[editor-register-scenario] Updated journal screenshot for "${t}" in entry "${c.title}"`)}catch(h){console.warn(`[editor-register-scenario] Failed to update journal screenshot: ${h instanceof Error?h.message:h}`)}}i&&Ct.notifyChange("journal")}function zh(){const e=globalThis.__codeyam_editor_dev_server__;return e&&e.status==="running"&&e.url?e.url:null}async function Bh(e){const t=O.dirname(new URL(import.meta.url).pathname);let r=t;for(let a=0;a<5;a++){const o=O.dirname(r);if(O.basename(o)==="webserver"||O.basename(r)==="webserver"){r=O.basename(r)==="webserver"?r:o;break}r=o}const s=[O.join(r,"scripts","journalCapture.ts"),O.join(r,"app","lib","journalCapture.ts"),O.join(e,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),O.resolve(t,"..","lib","journalCapture.ts")];for(const a of s)try{return await we.access(a),a}catch{}return console.warn(`[editor-register-scenario] journalCapture.ts not found in any of: ${s.join(", ")}`),s[0]}function Yh(e,t,r){return new Promise(s=>{const a=kt("npx",["tsx",e,t],{cwd:r,env:{...process.env}});let o="",i="";a.stdout.on("data",c=>{o+=c.toString()}),a.stderr.on("data",c=>{i+=c.toString()}),a.on("close",c=>{s(c===0?{success:!0,output:o}:{success:!1,output:o,error:i||`Process exited with code ${c}`})}),a.on("error",c=>{s({success:!1,output:"",error:c.message})})})}async function Uh({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{name:r,description:s,componentName:a,componentPath:o}=t;if(!r)return new Response(JSON.stringify({error:"name is required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=await $e();if(!i)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:c}=await Ie(i),d=Te(),m=ra();try{await d.schema.alterTable("editor_scenarios").addColumn("url","varchar").execute()}catch{}await d.insertInto("editor_scenarios").values({id:m,project_id:c.id,name:r,description:s||null,component_name:a||null,component_path:o||null,url:t.url||null}).execute();const u=process.env.CODEYAM_ROOT_PATH||process.cwd();if(t.mockData){const b=O.join(u,".codeyam","editor-scenarios");await we.mkdir(b,{recursive:!0}),await we.writeFile(O.join(b,`${m}.json`),JSON.stringify(t.mockData,null,2))}Ct.notifyChange("scenario"),console.log(`[editor-register-scenario] Starting auto-capture for scenario "${r}" (id: ${m})`);const h=t.url&&t.url.startsWith("/"),p=!t.url||h?await nl():null,f=zh(),y=al(t.url||null,p,f);console.log(`[editor-register-scenario] Capture URL resolution: explicit=${t.url||"none"}, isPath=${h}, proxy=${p||"none"}, devServer=${f||"none"} → using ${y||"none"}`);let g=null,x=null,v=[];if(y){const b=Vt(r),N=O.join(u,".codeyam","active-scenario.json");await we.writeFile(N,JSON.stringify({scenarioId:m,scenarioSlug:b,timestamp:new Date().toISOString()})),tl(),console.log(`[editor-register-scenario] Active scenario set to "${b}" (${m}), cache invalidated`),await new Promise(j=>setTimeout(j,500));const w=O.join(u,".codeyam","editor-scenarios","screenshots");await we.mkdir(w,{recursive:!0});const S=O.join(w,`${m}.png`),C=await Bh(u);console.log(`[editor-register-scenario] Capture script: ${C}`);const k=JSON.stringify({url:y,outputPath:S,viewportWidth:1280,viewportHeight:720,...a?{selector:"#codeyam-capture"}:{}});console.log(`[editor-register-scenario] Running Playwright capture: url=${y}, output=${S}`);const E=Date.now(),A=await Yh(C,k,u),I=Date.now()-E;if(console.log(`[editor-register-scenario] Capture ${A.success?"succeeded":"FAILED"} in ${I}ms`),A.success||(console.warn(`[editor-register-scenario] Capture stdout: ${A.output.slice(0,500)}`),console.warn(`[editor-register-scenario] Capture stderr: ${(A.error||"").slice(0,500)}`)),v=rl(A.output),await sl(u,m,r,v),v.length>0&&console.warn(`[editor-register-scenario] ${v.length} client-side error(s) detected:`,v),A.success){g=`screenshots/${m}.png`;try{await d.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}await d.updateTable("editor_scenarios").set({screenshot_path:g}).where("id","=",m).execute(),Ct.notifyChange("scenario"),await Fh(u,r,S)}else x=A.error||"Unknown capture error",console.warn(`[editor-register-scenario] Screenshot capture failed (non-blocking): ${x}`)}else console.log("[editor-register-scenario] Skipping screenshot — no capture URL available (dev server not running?)");return console.log(`[editor-register-scenario] Done: scenario="${r}", screenshot=${g?"captured":"skipped"}`),new Response(JSON.stringify({success:!0,scenario:{id:m,name:r,description:s,componentName:a||null,componentPath:o||null,screenshotPath:g,url:t.url||null},screenshotCaptured:g!==null,captureError:x,clientErrors:v}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-register-scenario] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Wh=Object.freeze(Object.defineProperty({__proto__:null,action:Uh},Symbol.toStringTag,{value:"Module"}));function Jh({executionFlows:e,selections:t,onChange:r,disabled:s=!1}){const a=oe(i=>t.some(c=>c.flowId===i),[t]),o=oe(i=>{a(i.id)?r(t.filter(c=>c.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,a]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const c=a(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:[n("input",{type:"checkbox",checked:c,onChange:()=>o(i),disabled:s,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:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!d&&n("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&n("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&n("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),c&&i.requiredValues.length>0&&l("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[n("span",{className:"text-gray-700 font-medium",children:"Required values:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((m,u)=>l("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:m.attributePath})," ",n("span",{className:"text-gray-400",children:m.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:m.value})]},u))})]})]},i.id)})})}function ya(e,t){const r=(e||[]).map(d=>({...d,usedInScenarios:[]})),s=new Map;r.forEach(d=>{s.set(d.id,d)});const a=[];t.forEach(d=>{var u;const m=((u=d.metadata)==null?void 0:u.coveredFlows)||[];m.forEach(h=>{const p=s.get(h);p&&p.usedInScenarios.push({id:d.id||"",name:d.name})}),a.push({scenario:d,coveredFlowIds:m})});const o=r.length,i=r.filter(d=>d.usedInScenarios.length>0).length,c=o>0?i/o*100:0;return{executionFlows:r,totalFlows:o,coveredFlows:i,coveragePercentage:c,scenariosWithFlows:a}}function Hh(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const Vh=({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 qh({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await Br(t,!0),s=r&&r.length>0?r[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const a=(i=s.scenarios)==null?void 0:i.find(c=>c.name===Fr);if(!a)throw new Response("Default scenario not found",{status:404});const o=await $e();return K({analysis:s,defaultScenario:a,entity:s.entity,entitySha:t,projectSlug:o})}function Gh(){var H;const{analysis:e,defaultScenario:t,entity:r,entitySha:s,projectSlug:a}=Ve(),o=St(),{iframeRef:i}=ga(),[c,d]=_(""),[m,u]=_(400),[h,p]=_(!1),[f,y]=_(!1),[g,x]=_(!1),[v,b]=_(null),[N,w]=_(null),[S,C]=_([]),k=ne(()=>{var D;return!((D=e==null?void 0:e.metadata)!=null&&D.executionFlows)||!(e!=null&&e.scenarios)?[]:ya(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:E,isStarting:A,isLoading:I,showIframe:j,iframeKey:P,onIframeLoad:$}=nn({analysisId:e==null?void 0:e.id,scenarioId:t==null?void 0:t.id,scenarioName:t==null?void 0:t.name,projectSlug:a,enabled:!0}),T=oe(async()=>{var B,D,M,Q;if(!c.trim()&&S.length===0){b("Please describe how you want to change the scenario or select execution flows");return}y(!0),b(null),w("Generating scenario with AI...");try{const U=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:c,existingScenarios:e.scenarios,scenariosDataStructure:(B=e.metadata)==null?void 0:B.scenariosDataStructure,flowSelections:S.length>0?S:void 0})}),F=await U.json();if(!U.ok||!F.success)throw new Error(F.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",F.data);const X=F.data;if(!X.name||!X.data)throw new Error("AI response missing required fields (name or data)");w("Saving new scenario..."),x(!0);const z={name:X.name,description:X.description||c,metadata:{data:X.data,interactiveExamplePath:(D=t.metadata)==null?void 0:D.interactiveExamplePath}},L=[...e.scenarios||[],z],W=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:L})}),V=await W.json();if(!W.ok||!V.success)throw new Error(V.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",V);const Z=(Q=(M=V.analysis)==null?void 0:M.scenarios)==null?void 0:Q.find(ce=>ce.name===X.name);if(!(Z!=null&&Z.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),w("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${s}`),1e3);return}if(E){w("Capturing screenshot...");const ce=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:E,scenarioId:Z.id,projectId:e.projectId,viewportWidth:1440})}),ve=await ce.json();!ce.ok||!ve.success?(console.error("[CreateScenario] Capture failed:",ve),w("Scenario created! (Screenshot capture failed)")):w("Scenario created and captured!")}else w("Scenario created!");setTimeout(()=>{o(`/entity/${s}/scenarios/${Z.id}`)},1e3)}catch(U){console.error("[CreateScenario] Error:",U),b(U instanceof Error?U.message:String(U)),w(null)}finally{y(!1),x(!1)}},[c,S,e,t,s,E,o]),R=f||g,J=oe(()=>{p(!0)},[]),q=oe(B=>{if(!h)return;const D=B.clientX;D>=250&&D<=600&&u(D)},[h]),Y=oe(()=>{p(!1)},[]);return te(()=>(h?(document.addEventListener("mousemove",q),document.addEventListener("mouseup",Y)):(document.removeEventListener("mousemove",q),document.removeEventListener("mouseup",Y)),()=>{document.removeEventListener("mousemove",q),document.removeEventListener("mouseup",Y)}),[h,q,Y]),l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children: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:[n("button",{onClick:()=>void o(`/entity/${s}`),className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:r==null?void 0:r.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:r==null?void 0:r.filePath,children:r==null?void 0:r.filePath})]}),l("div",{className:"flex items-end gap-8 shrink-0",children:[n(de,{to:`/entity/${s}/scenarios`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-medium border-b-2",style:{color:"#005C75",borderColor:"#005C75"},children:l("span",{className:"flex items-center gap-2",children:["Scenarios",n("span",{className:"inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full bg-[#cbf3fa] text-[#005c75]",children:((H=e==null?void 0:e.scenarios)==null?void 0:H.length)||0})]})}),n(de,{to:`/entity/${s}/related`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Related Entities"}),n(de,{to:`/entity/${s}/code`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Code"}),n(de,{to:`/entity/${s}/data`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Data Structure"}),n(de,{to:`/entity/${s}/history`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"History"})]})]})}),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:`${m}px`},children:[l("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select execution flows and/or describe how you'd like to change it."})]}),k.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"," ",S.length>0&&l("span",{className:"text-blue-600",children:["(",S.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(Jh,{executionFlows:k,selections:S,onChange:C,disabled:R})})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"Describe your scenario"}),n("textarea",{id:"prompt",value:c,onChange:B=>d(B.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:R})]}),l("div",{className:"space-y-2",children:[n("button",{onClick:()=>void T(),disabled:R||!c.trim()&&S.length===0,className:"w-full px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium cursor-pointer transition-colors hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed",children:R?"Creating...":"Create Scenario"}),N&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:N}),v&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:v})]})]}),l("div",{onMouseDown:J,style:{width:"20px",position:"absolute",top:0,left:`${m-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[n("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:h?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),n("div",{style:{position:"absolute",top:"50%",left:"10px",transform:"translate(-50%, -50%)",width:"8px",height:"40px",background:"#fff",border:"1px solid rgba(0,0,0,0.15)",borderRadius:"4px",cursor:"col-resize"}})]}),n("main",{className:"flex-1 overflow-auto flex items-center justify-center min-w-0",style:{backgroundImage:`
|
|
155
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
156
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
157
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
158
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
159
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:n(Xr,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:E,isStarting:A,isLoading:I,showIframe:j,iframeKey:P,onIframeLoad:$,projectSlug:a,defaultWidth:1440,defaultHeight:900})})]})]})}const Kh=Je(function(){return n(Zr,{children:n(Gh,{})})}),Qh=Object.freeze(Object.defineProperty({__proto__:null,default:Kh,loader:qh,meta:Vh},Symbol.toStringTag,{value:"Module"}));function Zh(){const e=globalThis.__codeyam_editor_dev_server__;return e&&e.status==="running"&&e.url?e.url:null}async function Xh({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioId:r,url:s,viewportWidth:a,viewportHeight:o}=t;if(!r)return new Response(JSON.stringify({error:"scenarioId is required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=await $e();if(!i)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:c}=await Ie(i),d=Te(),m=await d.selectFrom("editor_scenarios").selectAll().where("id","=",r).where("project_id","=",c.id).executeTakeFirst();if(!m)return new Response(JSON.stringify({error:"Scenario not found"}),{status:404,headers:{"Content-Type":"application/json"}});const u=s??m.url??null,h=u&&u.startsWith("/"),p=!u||h?await nl():null,f=Zh(),y=al(u,p,f);if(console.log(`[editor-capture-scenario] URL resolution: explicit=${s||"none"}, db=${m.url||"none"}, proxy=${p||"none"}, devServer=${f||"none"} → captureUrl=${y||"none"}`),!y)return new Response(JSON.stringify({error:"Cannot determine capture URL — no proxy or dev server running"}),{status:400,headers:{"Content-Type":"application/json"}});console.log(`[editor-capture-scenario] Starting capture for scenario "${m.name}" (id: ${r}), url: ${y}`);const g=process.env.CODEYAM_ROOT_PATH||process.cwd(),x=Vt(m.name),v=O.join(g,".codeyam","active-scenario.json");await we.writeFile(v,JSON.stringify({scenarioId:r,scenarioSlug:x,timestamp:new Date().toISOString()})),tl(),console.log(`[editor-capture-scenario] Active scenario set to "${x}", cache invalidated`),await new Promise(T=>setTimeout(T,500));const b=O.join(g,".codeyam","editor-scenarios","screenshots");await we.mkdir(b,{recursive:!0});const N=O.join(b,`${r}.png`),w=O.dirname(new URL(import.meta.url).pathname);let S=w;for(let T=0;T<5;T++){const R=O.dirname(S);if(O.basename(R)==="webserver"||O.basename(S)==="webserver"){S=O.basename(S)==="webserver"?S:R;break}S=R}const C=[O.join(S,"scripts","journalCapture.ts"),O.join(S,"app","lib","journalCapture.ts"),O.join(g,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),O.resolve(w,"..","lib","journalCapture.ts")];let k="";for(const T of C)try{await we.access(T),k=T;break}catch{}k||(console.warn(`[editor-capture-scenario] journalCapture.ts not found in any of: ${C.join(", ")}`),k=C[0]),console.log(`[editor-capture-scenario] Capture script: ${k}`);const E=JSON.stringify({url:y,outputPath:N,viewportWidth:a||1280,viewportHeight:o||720,...m.component_name?{selector:"#codeyam-capture"}:{}});console.log(`[editor-capture-scenario] Running Playwright capture: url=${y}, output=${N}`);const A=Date.now(),I=await new Promise(T=>{const R=kt("npx",["tsx",k,E],{cwd:g,env:{...process.env}});let J="",q="";R.stdout.on("data",Y=>{J+=Y.toString()}),R.stderr.on("data",Y=>{q+=Y.toString()}),R.on("close",Y=>{T(Y===0?{success:!0,output:J}:{success:!1,output:J,error:q||`Process exited with code ${Y}`})}),R.on("error",Y=>{T({success:!1,output:"",error:Y.message})})}),j=Date.now()-A;if(console.log(`[editor-capture-scenario] Capture ${I.success?"succeeded":"FAILED"} in ${j}ms`),!I.success)return console.warn(`[editor-capture-scenario] Capture stdout: ${I.output.slice(0,500)}`),console.warn(`[editor-capture-scenario] Capture stderr: ${(I.error||"").slice(0,500)}`),new Response(JSON.stringify({error:"Failed to capture screenshot",details:I.error}),{status:500,headers:{"Content-Type":"application/json"}});const P=`screenshots/${r}.png`;try{await d.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}await d.updateTable("editor_scenarios").set({screenshot_path:P}).where("id","=",r).execute();const $=rl(I.output);return await sl(g,r,m.name,$),$.length>0&&console.warn(`[editor-capture-scenario] ${$.length} client-side error(s) detected:`,$),Ct.notifyChange("scenario"),new Response(JSON.stringify({success:!0,screenshotPath:P,clientErrors:$}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-capture-scenario] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const ep=Object.freeze(Object.defineProperty({__proto__:null,action:Xh},Symbol.toStringTag,{value:"Module"}));async function tp({params:e}){const t=e["*"];if(!t)return new Response("Image path is required",{status:400});const r=process.env.CODEYAM_ROOT_PATH||process.cwd(),s=ee.join(r,".codeyam","editor-scenarios","screenshots",t),a=ee.resolve(s),o=ee.resolve(ee.join(r,".codeyam","editor-scenarios","screenshots"));if(!a.startsWith(o))return new Response("Invalid path",{status:403});try{await xe.access(s);const i=await xe.readFile(s),c=ee.extname(s).toLowerCase(),d=c===".png"?"image/png":c===".jpg"||c===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Image not found",{status:404})}}const np=Object.freeze(Object.defineProperty({__proto__:null,loader:tp},Symbol.toStringTag,{value:"Module"}));async function rp({params:e,request:t}){const r=e["*"];if(!r)return new Response("Image path is required",{status:400});const s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=ee.join(s,".codeyam","journal","screenshots",r),o=ee.resolve(a),i=ee.resolve(ee.join(s,".codeyam","journal","screenshots"));if(!o.startsWith(i))return new Response("Invalid path",{status:403});try{const c=await xe.stat(a),d=`"${c.mtimeMs.toString(36)}-${c.size.toString(36)}"`;if(t.headers.get("if-none-match")===d)return new Response(null,{status:304,headers:{ETag:d}});const u=await xe.readFile(a),h=ee.extname(a).toLowerCase(),p=h===".png"?"image/png":h===".jpg"||h===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(u,{status:200,headers:{"Content-Type":p,"Cache-Control":"public, max-age=0, must-revalidate",ETag:d}})}catch{return new Response("Image not found",{status:404})}}const sp=Object.freeze(Object.defineProperty({__proto__:null,loader:rp},Symbol.toStringTag,{value:"Module"})),ol=globalThis.__codeyamTerminalSessions??(globalThis.__codeyamTerminalSessions=new Set);globalThis.__codeyamDetachedPtys??(globalThis.__codeyamDetachedPtys=new Map);function il(e){const t=JSON.stringify({type:"refresh-preview",...e});let r=0;for(const s of ol)try{s.ws.readyState===di.OPEN&&(s.ws.send(t),r++)}catch{}return r}function ap(){const e=JSON.stringify({type:"hide-results"});let t=0;for(const r of ol)try{r.ws.readyState===di.OPEN&&(r.ws.send(e),t++)}catch{}return t}const op=Object.freeze(Object.defineProperty({__proto__:null,broadcastHideResults:ap,broadcastPreviewRefresh:il},Symbol.toStringTag,{value:"Module"}));async function ip({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioSlug:r,scenarioId:s,scenarioName:a}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({error:"scenarioSlug is required"}),{status:400,headers:{"Content-Type":"application/json"}});const o=he()||process.cwd(),i=ee.join(o,".codeyam"),c=ee.join(i,"active-scenario.json");Ce.mkdirSync(i,{recursive:!0}),Ce.writeFileSync(c,JSON.stringify({scenarioSlug:r,scenarioName:a||null,scenarioId:s||null,dataFile:s?`.codeyam/editor-scenarios/${s}.json`:null,switchedAt:new Date().toISOString()},null,2));const d=il();return new Response(JSON.stringify({success:!0,scenarioSlug:r,refreshedClients:d}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const lp=Object.freeze(Object.defineProperty({__proto__:null,action:ip},Symbol.toStringTag,{value:"Module"}));var ge;(e=>{(t=>{t.OPENAI_GPT5_1="openai/gpt-5.1",t.OPENAI_GPT5="openai/gpt-5",t.OPENAI_GPT5_MINI="openai/gpt-5-mini",t.OPENAI_GPT5_NANO="openai/gpt-5-nano",t.OPENAI_GPT4_1="openai/gpt-4.1",t.OPENAI_GPT4_1_MINI="openai/gpt-4.1-mini",t.OPENAI_GPT4_O="openai/gpt-4o",t.OPENAI_GPT4_O_MINI="openai/gpt-4o-mini",t.OPENAI_GPT_OSS_120B_GROQ="openai/gpt-oss-120b-groq",t.OPENAI_GPT_OSS_120B_DEEPINFRA="openai/gpt-oss-120b-deepinfra",t.QWEN3_235B_INSTRUCT_DEEPINFRA="qwen/qwen3-235b-instruct-deepinfra",t.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA="qwen/qwen3-coder-480b-instruct-deepinfra",t.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA="google/gemini-2.5-pro-deepinfra",t.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA="google/gemini-2.5-flash-deepinfra",t.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER="google/gemini-2.5-flash-lite-openrouter",t.META_LLAMA_4_MAVERICK_OPENROUTER="meta-llama/llama-4-maverick-openrouter",t.DEEPSEEK_V3_1_TERMINUS_OPENROUTER="deepseek/v3.1-terminus-openrouter",t.ANTHROPIC_CLAUDE_4_5_HAIKU="anthropic/claude-4.5-haiku",t.ANTHROPIC_CLAUDE_4_5_SONNET="anthropic/claude-4.5-sonnet",t.ANTHROPIC_CLAUDE_4_5_OPUS="anthropic/claude-4.5-opus",t.PHIND_CODELLAMA="phind/codellama",t.GOOGLE_GEMINI_PRO="google/gemini-pro",t.GOOGLE_PALM_2_CODE_CHAT_32K="google/palm-2-code-chat-32k",t.META_CODELLAMA_34B_INSTRUCT="meta-llama/codellama-34b-instruct",t.OPENAI_GPT4_PREVIEW="openai/gpt-4-preview"})(e.Model||(e.Model={}))})(ge||(ge={}));function ll(e,t){return e?Object.values(ge.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const cl=ll(process.env.DEFAULT_SMALLER_MODEL,ge.Model.OPENAI_GPT4_1_MINI),cp=ll(process.env.DEFAULT_LARGER_MODEL,ge.Model.OPENAI_GPT4_1),mt={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},ks={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},dp={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},Es={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},Mt={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},up={[ge.Model.OPENAI_GPT5_1]:{id:ge.Model.OPENAI_GPT5_1,provider:mt,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[ge.Model.OPENAI_GPT5]:{id:ge.Model.OPENAI_GPT5,provider:mt,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[ge.Model.OPENAI_GPT5_MINI]:{id:ge.Model.OPENAI_GPT5_MINI,provider:mt,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[ge.Model.OPENAI_GPT5_NANO]:{id:ge.Model.OPENAI_GPT5_NANO,provider:mt,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[ge.Model.OPENAI_GPT4_1]:{id:ge.Model.OPENAI_GPT4_1,provider:mt,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[ge.Model.OPENAI_GPT4_1_MINI]:{id:ge.Model.OPENAI_GPT4_1_MINI,provider:mt,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ge.Model.OPENAI_GPT4_O]:{id:ge.Model.OPENAI_GPT4_O,provider:mt,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[ge.Model.OPENAI_GPT4_O_MINI]:{id:ge.Model.OPENAI_GPT4_O_MINI,provider:mt,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[ge.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:ge.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:ks,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[ge.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:ge.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:ks,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[ge.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:ge.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:ks,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[ge.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:ge.Model.OPENAI_GPT_OSS_120B_GROQ,provider:dp,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[ge.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:ge.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:Mt,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[ge.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:ge.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:Mt,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[ge.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:ge.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:Mt,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ge.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:ge.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:Mt,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[ge.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:ge.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:Mt,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[ge.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:ge.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:Es,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[ge.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:ge.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:Es,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[ge.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:ge.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:Es,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[ge.Model.PHIND_CODELLAMA]:{id:ge.Model.PHIND_CODELLAMA,provider:mt,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ge.Model.GOOGLE_GEMINI_PRO]:{id:ge.Model.GOOGLE_GEMINI_PRO,provider:Mt,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ge.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:ge.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:Mt,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ge.Model.META_CODELLAMA_34B_INSTRUCT]:{id:ge.Model.META_CODELLAMA_34B_INSTRUCT,provider:Mt,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ge.Model.OPENAI_GPT4_PREVIEW]:{id:ge.Model.OPENAI_GPT4_PREVIEW,provider:mt,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function ts(e){const t=up[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function mp(e){return ts(e).maxCompletionTokens}function hp(e){return ts(e).pricing}const yo=1e6;function pp({model:e,usage:t}){const r=hp(e);return r?t.prompt_tokens*(r.input/yo)+t.completion_tokens*(r.output/yo):null}function fp({chatRequest:e,chatCompletion:t,model:r}){if("error"in t&&t.error)return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),error:JSON.stringify(t.error)};const s=t.usage||{prompt_tokens:0,completion_tokens:0},a=pp({model:r,usage:s});return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,cost:a?Math.round(a*1e5)/1e5:void 0}}function gp({messages:{system:e,prompt:t},model:r,responseType:s,jsonSchema:a}){const o=r??cl,i=ts(o);mp(o);const c=[];return e&&c.push({role:"system",content:e}),c.push({role:"user",content:[{type:"text",text:t}]}),{messages:c,model:i.apiModelName,response_format:s==="json_schema"&&a?{type:"json_schema",json_schema:{name:a.name,schema:a.schema,strict:a.strict!==!1}}:{type:s&&s=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}const Ws="/tmp/codeyam-e2e-tracking";let As,Ps;function yp(){return As===void 0&&(As=process.env.CODEYAM_E2E_TRACK_DATA==="true"),As}function xp(){return Ps===void 0&&(Ps=!process.env.CODEYAM_LLM_FIXTURES_DIR),Ps}function bp(){G.existsSync(Ws)||G.mkdirSync(Ws,{recursive:!0})}function vp(e){const t=JSON.stringify(e,null,0);return Gc.createHash("md5").update(t).digest("hex")}function wp(e,t,r){return[e].join("_")+".json"}function dl(e,t,r,s){if(!yp())return;bp();const a=wp(e),o=O.join(Ws,a),i=vp(t);if(xp()){const c={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:s,dataHash:i,data:t};G.writeFileSync(o,JSON.stringify(c,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(G.existsSync(o)){const c=JSON.parse(G.readFileSync(o,"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=Js(c.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${c.dataHash}`),console.log(` Second run hash: ${i}`);const m=o.replace(".json","_DIFF.json");G.writeFileSync(m,JSON.stringify({checkpoint:e,entityName:r,scenarioName:s,firstRun:c.data,secondRun:t,differences:d.differences},null,2)),console.log(` Diff saved to: ${m}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function Js(e,t,r=""){const s=[];if(typeof e!=typeof t)return s.push(`${r||"root"}: type mismatch (${typeof e} vs ${typeof t})`),s;if(e===null||t===null)return e!==t&&s.push(`${r||"root"}: ${JSON.stringify(e)} vs ${JSON.stringify(t)}`),s;if(Array.isArray(e)&&Array.isArray(t)){e.length!==t.length&&s.push(`${r||"root"}: array length ${e.length} vs ${t.length}`);const a=Math.max(e.length,t.length);for(let o=0;o<a;o++)s.push(...Js(e[o],t[o],`${r}[${o}]`));return s}if(typeof e=="object"&&typeof t=="object"){const a=Object.keys(e),o=Object.keys(t),i=Array.from(new Set([...a,...o]));for(const c of i){const d=e[c],m=t[c];c in e?c in t?s.push(...Js(d,m,`${r?r+".":""}${c}`)):s.push(`${r?r+".":""}${c}: missing in second run`):s.push(`${r?r+".":""}${c}: missing in first run`)}return s}if(e!==t){const a=JSON.stringify(e),o=JSON.stringify(t);a.length<100&&o.length<100?s.push(`${r||"root"}: ${a} vs ${o}`):s.push(`${r||"root"}: values differ (${a.length} chars vs ${o.length} chars)`)}return s}aa(sa);const ar=new nd({concurrency:100,timeout:1200*1e3,autoStart:!0}),xo={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},Tt={};async function Hs({type:e,systemMessage:t,prompt:r,jsonResponse:s=!0,jsonSchema:a,model:o=cl,attempts:i=0}){var k,E,A,I,j,P,$;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await Np(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${ar.size}, running=${ar.pending}]`);const c=Date.now();let d,m=0;const u=ts(o),h=process.env[u.provider.apiKeyEnvVar];if(!h)throw new Error(`API key not found for provider ${u.provider.name}. Please set ${u.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${u.provider.name} for AI request`);const p=new td({apiKey:h,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:a?"json_schema":s?"json_object":"text",jsonSchema:a},y=gp(f),g=await ar.add(()=>(d=Date.now(),eo(async()=>{const T=Date.now(),R=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],J=setInterval(()=>{const q=Math.floor((Date.now()-T)/1e3),Y=Math.floor(q/10)%R.length;no(1,`${R[Y]} [type=${e}, model=${o}, elapsed=${q}s]`)},1e4);try{return await p.chat.completions.create(y,{timeout:300*1e3})}finally{clearInterval(J)}},{...xo,onFailedAttempt:T=>{m++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:T,prompt:r,systemMessage:t,attempts:i,retryCount:m})}})));if(!g)throw new Error("Completion call returned no result");const x=g,v=Date.now(),b=fp({chatRequest:f,chatCompletion:x,model:o});if(!b)throw new Error("Failed to get LLM call stats");b.retries=m,b.wait_ms=d-c,b.duration_ms=v-c;const N=(k=x.choices)==null?void 0:k[0];let w=null;if(N){if(!N.finish_reason)throw console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({chatCompletion:x,chatRequest:f},null,2)),new Error("completionCall(): missing finish_reason in LLM response");w=(E=N.message)==null?void 0:E.content}let S=w;w&&(S=w.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const C=s?S&&(((A=S.match(/\{[\s\S]*\}/))==null?void 0:A[0])??S):S;if(!C){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:C,rawCompletion:w,chatCompletion:x,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await Hs({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(C.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:w,prompt:r,systemMessage:t}),new Error("Empty completion");if(s)try{JSON.parse(C)}catch(T){if(console.log("CodeYam Error: Invalid JSON in completion",{error:T.message,model:o,completion:C.substring(0,500),rawCompletion:w==null?void 0:w.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:T.message});const R=`Your previous response contained invalid JSON with the following error:
|
|
160
|
+
|
|
161
|
+
${T.message}
|
|
162
|
+
|
|
163
|
+
Here was your previous response:
|
|
164
|
+
\`\`\`
|
|
165
|
+
${C}
|
|
166
|
+
\`\`\`
|
|
167
|
+
|
|
168
|
+
Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,J=await ar.add(()=>eo(async()=>{const D=Date.now(),M=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],Q=setInterval(()=>{const U=Math.floor((Date.now()-D)/1e3),F=Math.floor(U/10)%M.length;no(1,`${M[F]} [type=${e}, model=${o}, elapsed=${U}s]`)},1e4);try{return await p.chat.completions.create({...y,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:C},{role:"user",content:R}]},{timeout:300*1e3})}finally{clearInterval(Q)}},{...xo,onFailedAttempt:D=>{console.log("CodeYam Error: Correction call failed",{error:D,attempts:i})}}));if(!J)throw new Error("Correction call returned no result");const q=J,Y=(P=(j=(I=q.choices)==null?void 0:I[0])==null?void 0:j.message)==null?void 0:P.content;let H=Y;Y&&(H=Y.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const B=H&&((($=H.match(/\{[\s\S]*\}/))==null?void 0:$[0])??H);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 b.duration_ms=D-c,{finishReason:q.choices[0].finish_reason,completion:B,stats:b}}catch(D){return console.log("CodeYam Error: Corrected JSON still invalid",{error:D.message,correctedCompletion:B.substring(0,500)}),await Hs({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${T.message}`)}return dl(`completionCall_${e}`,{completion:C,finishReason:x.choices[0].finish_reason}),{finishReason:x.choices[0].finish_reason,completion:C,stats:b}}async function Np(e,t,r){var o,i,c,d,m;const s=await import("fs"),a=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!s.existsSync(t))throw console.log(`CodeYam Test: Fixtures directory does not exist yet: ${t}`),new Error(`No LLM fixture files found - directory does not exist: ${t}`);const u=s.readdirSync(t).filter(b=>b.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${t}`);const h={};for(const b of u)try{const N=s.readFileSync(a.join(t,b),"utf-8"),w=JSON.parse(N);h[w.prompt_type]||(h[w.prompt_type]=[]),h[w.prompt_type].push(w)}catch(N){console.warn(`Failed to parse LLM fixture file ${b}:`,N)}for(const b of Object.keys(h))h[b].sort((N,w)=>{const S=N.created_at??0,C=w.created_at??0;return S-C});const p=h[e];if(!p||p.length===0){const b=Object.keys(h).join(", ");return console.warn(`CodeYam Test: No captured LLM call found for type '${e}'. Available types: ${b}`),{finishReason:"stop",completion:"{}",stats:{model:"fixture-fallback",prompt_type:e,system_message:"",prompt_text:"",response:"{}",input_tokens:0,output_tokens:0,cost:0}}}let f;if(["generateEntityScenarioData","generateChunkMockData","generateMissingMockData"].includes(e)&&r){const b=r.match(/Scenario name must match exactly: "([^"]+)"/),N=b==null?void 0:b[1];if(N){const w={};for(const C of p)try{const E=((o=JSON.parse(C.props||"{}").scenario)==null?void 0:o.name)||"__NO_SCENARIO__";w[E]||(w[E]=[]),w[E].push(C)}catch{}const S=w[N];if(S&&S.length>0){const C=`${t}::${e}::${N}`;Tt[C]===void 0&&(Tt[C]=0);const k=Tt[C];Tt[C]=(k+1)%S.length,f=S[k],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${N}' [${k+1}/${S.length}]`)}else{const C=Object.keys(w).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${N}'. Available: [${C}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const b=`${t}::${e}`;Tt[b]===void 0&&(Tt[b]=0);const N=Tt[b];Tt[b]=(N+1)%p.length,f=p[N],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${N+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 x=g;g&&(x=g.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const v=x&&(((m=x.match(/\{[\s\S]*\}/))==null?void 0:m[0])??x);return dl(`completionCall_${e}`,{completion:v||"",finishReason:"stop"}),{finishReason:"stop",completion:v||"",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 bo(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function Cp(e){const{propsJson:t,...r}=e,s=JSON.stringify(t,null,2),a=ra(),o=Date.now(),i={...r,id:a,created_at:o,props:s};let c;const d=`${i.object_id}_${a}.json`;if(process.env.DYNAMODB_PATH?c=O.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(c=O.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),c)try{const u=O.dirname(c);return await we.mkdir(u,{recursive:!0}),await we.writeFile(c,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${c}`),{id:a}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const m=bo();if(!m)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,h]of Object.entries(i))typeof h>"u"&&console.log(`CodeYam Warning: LLM call ${a} property ${u} with explicit value 'undefined'`);try{return await new Lr().send(new rd({TableName:bo(),Item:ad(i,{removeUndefinedValues:!0})})),{id:a}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${m}`,u),{id:"-1"}}}new Lr({});new Lr({});new Lr({});const Sp=3,kp=2,xa=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+Sp*String(t).length*(1+kp)});new ia(xa());new ia(xa());new ia(xa());class Ep{constructor(){this.byMethodName=new Map,this.byClassAndMethod=new Map}register(t,r,s){this.byMethodName.has(t)||this.byMethodName.set(t,[]),this.byMethodName.get(t).push(r),s&&(this.byClassAndMethod.has(s)||this.byClassAndMethod.set(s,new Map),this.byClassAndMethod.get(s).set(t,r))}getByMethodName(t){return this.byMethodName.get(t)}getByClassAndMethod(t,r){var s;return(s=this.byClassAndMethod.get(t))==null?void 0:s.get(r)}}class Ap{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Pp{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class _p{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class jp{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Mp{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];if(s.addType(o,"function"),s.addEquivalence(o.withParameter(1),r.withElement("*")),a.args.length>1){const i=a.args[1];s.addEquivalence(o.withParameter(0),i)}}}isComplete(){return!0}}class Tp{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.getLastFunctionCallSegment();a&&a.args.forEach(o=>{s.addEquivalence(t,o)}),s.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class $p{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.withReturnValues();s.addType(a,"unknown")}isComplete(){return!0}}class Rp{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>2)for(let o=2;o<a.args.length;o++){const i=a.args[o];s.addEquivalence(r.withElement("*"),i)}}isComplete(){return!0}}class Ip{getReturnType(){return"number"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0)for(let o=0;o<a.args.length;o++)s.addEquivalence(r.withElement("*"),t.withParameter(o))}isComplete(){return!0}}class Dp{getReturnType(){return"string"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}class Lp{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Op{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Fp{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown"),s.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class zp{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Bp{getReturnType(){return"object"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"array")}}isComplete(){return!0}}class Yp{getReturnType(){return"string[]"}addEquivalences(t,r,s){s.addType(r,"string"),s.addType(t,"string[]"),s.addEquivalence(t.withReturnValues().withElement("*"),r)}isComplete(){return!0}}class Up{getReturnType(){return"unknown"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r),s.addEquivalence(t.withProperty("functionCallReturnValue"),o.withProperty("returnValue"))}}isComplete(){return!0}}class Wp{getReturnType(){return"unknown"}addEquivalences(t,r,s){t.getLastFunctionCallSegment()}isComplete(){return!0}}class Jp{getReturnType(){return"array"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(s.addType(t.withParameter(1),"function"),a&&a.args.length>0){const o=a.args[0];s.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}function Hp(){const e=new Ep;return e.register("filter",new Ap,"Array"),e.register("map",new Lp,"Array"),e.register("flatMap",new Op,"Array"),e.register("join",new Dp,"Array"),e.register("find",new jp,"Array"),e.register("findLast",new zp,"Array"),e.register("at",new Fp,"Array"),e.register("reduce",new Mp,"Array"),e.register("concat",new Tp,"Array"),e.register("slice",new $p,"Array"),e.register("splice",new Rp,"Array"),e.register("push",new Ip,"Array"),e.register("some",new Pp,"Array"),e.register("every",new _p,"Array"),e.register("fromEntries",new Bp,"Object"),e.register("split",new Yp,"String"),e.register("then",new Up,"Promise"),e.register("useState",new Jp,"React"),e.register("useMemo",new Wp,"React"),e}Hp();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 Vp=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),qp=new Set(["find","findLast","at","pop","shift"]),Gp=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),Kp=new Set([...Vp,...qp,...Gp]),Qp=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Zp=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Xp=new Set([...Qp,...Zp]);[...Kp,...Xp];class ef{constructor(t){this.depth=0,this.traceCount=0,this.defaultOutput=(r,s)=>{const a=" ".repeat(this.depth),o=this.timestamps?`[${Date.now()}] `:"";s?console.info(`${o}${a}${r}`,JSON.stringify(s)):console.info(`${o}${a}${r}`)},this.enabled=t.enabled,this.pathPatterns=t.pathPatterns??[],this.scopePatterns=t.scopePatterns??[],this.maxDepth=t.maxDepth??50,this.output=t.output??this.defaultOutput,this.timestamps=t.timestamps??!1}shouldTrace(t){return!this.enabled||this.depth>=this.maxDepth?!1:!!(this.pathPatterns.length===0&&this.scopePatterns.length===0||t.path&&this.pathPatterns.length>0&&this.pathPatterns.some(r=>r.test(t.path))||t.scope&&this.scopePatterns.length>0&&this.scopePatterns.some(r=>r.test(t.scope)))}trace(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[TRACE] ${t}`,r))}traceEnter(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[ENTER] ${t}`,r),this.depth++)}traceExit(t,r={}){this.depth>0&&this.depth--,this.shouldTrace(r)&&this.output(`[EXIT] ${t}`,r)}traceWarn(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[WARN] ${t}`,r))}enable(){this.enabled=!0}disable(){this.enabled=!1}resetDepth(){this.depth=0}getStats(){return{traceCount:this.traceCount,currentDepth:this.depth,enabled:this.enabled}}reset(){this.depth=0,this.traceCount=0}}new ef({enabled:!1});function Wt(e,t){const r={added:{},removed:{},changed:{}},s=new Set(Object.keys(e??{})),a=new Set(Object.keys(t??{}));for(const o of a)s.has(o)||(r.added[o]=t[o]);for(const o of s)a.has(o)||(r.removed[o]=e[o]);for(const o of s)a.has(o)&&e[o]!==t[o]&&(r.changed[o]={from:e[o],to:t[o]});return r}function tf(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function or(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let nf=0;class ba{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++nf,this.enabled=(t==null?void 0:t.enabled)??!1,this.outputPath=(t==null?void 0:t.outputPath)??"/tmp/codeyam/transform-trace.json",this.enabled&&console.log(`[Tracer] Initialized (id=${this.tracerId}, output=${this.outputPath})`)}log(t){this.isEnabled()&&console.log(`[Tracer] ${t}`)}isEnabled(){const t=process.env.CODEYAM_TRACE_TRANSFORMS;return t==="1"||t==="true"?!0:this.enabled}enable(){this.enabled=!0}disable(){this.enabled=!1}setOutputPath(t){this.outputPath=t}setProjectSlug(t){this.projectSlug=t}startEntity(t){if(!this.isEnabled())return;this.currentEntity=t.name;const r=this.traces.get(t.name);if(r){this.log(`startEntity: ${t.name} already exists, preserving ${r.stages.length} stages`);return}this.log(`startEntity: ${t.name}`),this.traces.set(t.name,{entityName:t.name,entityType:t.entityType,filePath:t.filePath,stages:[],operations:[]})}snapshot(t,r,s){var d,m,u,h;if(!this.isEnabled())return;const a=this.traces.get(t);if(!a)return this.log(`snapshot: no trace for ${t}, creating one`),this.startEntity({name:t,entityType:"unknown",filePath:"unknown"}),this.snapshot(t,r,s);this.log(`snapshot: ${t} → ${r}`),this.currentStage=r;const o=JSON.parse(JSON.stringify(s)),i={stage:r,timestamp:Date.now(),data:o},c=a.stages[a.stages.length-1];if(c&&(i.diffFromPrevious={signatureSchema:Wt(c.data.signatureSchema,o.signatureSchema),returnValueSchema:Wt(c.data.returnValueSchema,o.returnValueSchema)},o.dependencySchemas||c.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const p=new Set([...Object.keys(o.dependencySchemas??{}),...Object.keys(c.data.dependencySchemas??{})]);for(const f of p){const y=(d=c.data.dependencySchemas)==null?void 0:d[f],g=(m=o.dependencySchemas)==null?void 0:m[f];for(const x of new Set([...Object.keys(y??{}),...Object.keys(g??{})])){const v=`${f}::${x}`,b=(u=y==null?void 0:y[x])==null?void 0:u.returnValueSchema,N=(h=g==null?void 0:g[x])==null?void 0:h.returnValueSchema,w=Wt(b,N);tf(w)&&(i.diffFromPrevious.dependencySchemas[v]=w)}}}a.stages.push(i)}operation(t,r){if(!this.isEnabled())return;const s=this.traces.get(t);s&&s.operations.push({...r,stage:r.stage??this.currentStage??void 0,timestamp:Date.now()})}computeFlushSummary(){var a;const t={},r=new Map;for(const[o,i]of this.traces){let c=0;for(const d of i.stages){if(!d.diffFromPrevious)continue;const u=`${((a=i.stages[i.stages.indexOf(d)-1])==null?void 0:a.stage)??"start"}→${d.stage}`;if(t[u]||(t[u]={added:0,removed:0,changed:0}),d.diffFromPrevious.signatureSchema){const h=d.diffFromPrevious.signatureSchema;t[u].added+=Object.keys(h.added).length,t[u].removed+=Object.keys(h.removed).length,t[u].changed+=Object.keys(h.changed).length,c+=or(h)}if(d.diffFromPrevious.returnValueSchema){const h=d.diffFromPrevious.returnValueSchema;t[u].added+=Object.keys(h.added).length,t[u].removed+=Object.keys(h.removed).length,t[u].changed+=Object.keys(h.changed).length,c+=or(h)}}r.set(o,c)}const s=[...r.entries()].sort((o,i)=>i[1]-o[1]).slice(0,10).map(([o])=>o);return{stageChangeCounts:t,entitiesWithMostChanges:s}}flush(){if(!this.isEnabled())return;if(this.traces.size===0){this.log("flush: no traces to write");return}const t=Array.from(this.traces.keys()),r=t.map(m=>`${m}(${this.traces.get(m).stages.length})`).join(", ");this.log(`flush: writing ${t.length} entities: ${r}`);const{stageChangeCounts:s,entitiesWithMostChanges:a}=this.computeFlushSummary(),o={timestamp:new Date().toISOString(),projectSlug:this.projectSlug,entityCount:this.traces.size},i={stageChangeCounts:s,entitiesWithMostChanges:a},c=O.dirname(this.outputPath);G.existsSync(c)||G.mkdirSync(c,{recursive:!0});const d=G.openSync(this.outputPath,"w");try{G.writeSync(d,`{
|
|
169
|
+
"meta": `),G.writeSync(d,JSON.stringify(o,null,2)),G.writeSync(d,`,
|
|
170
|
+
"summary": `),G.writeSync(d,JSON.stringify(i,null,2)),G.writeSync(d,`,
|
|
171
|
+
"entities": {`);let m=!0;for(const[u,h]of this.traces)m||G.writeSync(d,","),G.writeSync(d,`
|
|
172
|
+
${JSON.stringify(u)}: `),G.writeSync(d,JSON.stringify(h,null,2)),m=!1;G.writeSync(d,`
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
`),this.log(`flush: wrote trace to ${this.outputPath}`)}finally{G.closeSync(d)}}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=G.readFileSync(t,"utf-8"),s=JSON.parse(r),a=new ba({enabled:!1});a.projectSlug=s.meta.projectSlug;for(const[o,i]of Object.entries(s.entities))a.traces.set(o,i);return a}getSummary(){var a,o,i;const t={},r=new Map;for(const[c,d]of this.traces){let m=0;for(let u=1;u<d.stages.length;u++){const h=d.stages[u],f=`${((a=d.stages[u-1])==null?void 0:a.stage)??"start"}→${h.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(o=h.diffFromPrevious)!=null&&o.signatureSchema){const y=h.diffFromPrevious.signatureSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,m+=or(y)}if((i=h.diffFromPrevious)!=null&&i.returnValueSchema){const y=h.diffFromPrevious.returnValueSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,m+=or(y)}}r.set(c,m)}const s=[...r.entries()].sort((c,d)=>d[1]-c[1]).slice(0,10).map(([c,d])=>({name:c,totalChanges:d}));return{entityCount:this.traces.size,stageChangeCounts:t,entitiesWithMostChanges:s}}getEntitySummary(t){const r=this.traces.get(t);return r?{entityName:t,stages:r.stages.map(s=>({stage:s.stage,diffFromPrevious:s.diffFromPrevious?{signatureSchema:s.diffFromPrevious.signatureSchema,returnValueSchema:s.diffFromPrevious.returnValueSchema}:void 0}))}:null}getOperations(t,r){const s=this.traces.get(t);return s?r?s.operations.filter(a=>a.path&&r.test(a.path)):s.operations:[]}tracePath(t,r){var o,i;const s=this.traces.get(t),a=[];if(!s)return{entityName:t,path:r,history:a};for(const c of s.stages){const d=(o=c.data.signatureSchema)==null?void 0:o[r],m=(i=c.data.returnValueSchema)==null?void 0:i[r],u=d??m;u!==void 0&&a.push({stage:c.stage,value:u})}for(const c of s.operations)c.path===r&&a.push({operation:c.operation,stage:c.stage,value:c.after??c.before,context:c.context});return{entityName:t,path:r,history:a}}getEntityTrace(t){return this.traces.get(t)}getEntityNames(){return[...this.traces.keys()]}findProperty(t,r){const s=this.traces.get(t);if(!s)return[];const a=[],o=new RegExp(`(^|\\.)${r}(\\.|\\[|$)`);for(const i of s.stages){for(const[c,d]of Object.entries(i.data.signatureSchema??{}))o.test(c)&&a.push({stage:i.stage,path:c,type:d,schemaType:"signature"});for(const[c,d]of Object.entries(i.data.returnValueSchema??{}))o.test(c)&&a.push({stage:i.stage,path:c,type:d,schemaType:"returnValue"});for(const[c,d]of Object.entries(i.data.dependencySchemas??{}))for(const[m,u]of Object.entries(d))for(const[h,p]of Object.entries(u.returnValueSchema??{}))o.test(h)&&a.push({stage:i.stage,path:`${c}/${m}::${h}`,type:p,schemaType:"dependency"})}return a}findTypeInconsistencies(t){const r=this.traces.get(t);if(!r)return[];let s=r.stages[r.stages.length-1];for(let d=r.stages.length-1;d>=0;d--)if(Object.keys(r.stages[d].data.dependencySchemas??{}).length>0){s=r.stages[d];break}if(!s)return[];const a=new Set(["length","toString","valueOf","constructor"]),o=new Map,i=(d,m)=>{const u=d.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!u)return;const h=u[1],p=u[2]==="[]";if(a.has(h))return;const f=h+(p?"[]":"");o.has(f)||o.set(f,[]),o.get(f).push({path:d,type:m})};for(const[,d]of Object.entries(s.data.dependencySchemas??{}))for(const[,m]of Object.entries(d))for(const[u,h]of Object.entries(m.returnValueSchema??{}))i(u,h);const c=[];for(const[d,m]of o)new Set(m.map(h=>h.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&c.push({propertyName:d,paths:m.map(h=>({...h,stage:s.stage}))});return c.sort((d,m)=>{const u=new Set(d.paths.map(p=>p.type)).size;return new Set(m.paths.map(p=>p.type)).size-u}),c}getStageDiffSummary(t,r,s){const a=this.traces.get(t);if(!a)return null;const o=a.stages.find(p=>p.stage===r),i=a.stages.find(p=>p.stage===s);if(!o||!i)return null;const c={added:[],removed:[],typeChanged:[]},d=o.data.returnValueSchema??{},m=i.data.returnValueSchema??{},u=new Set(Object.keys(d)),h=new Set(Object.keys(m));for(const p of h)u.has(p)?d[p]!==m[p]&&c.typeChanged.push({path:p,from:d[p],to:m[p]}):c.added.push(`${p}: ${m[p]}`);for(const p of u)h.has(p)||c.removed.push(`${p}: ${d[p]}`);return c}traceSchemaTransform(t,r,s,a,o){if(!this.enabled)return a(s),s;const i={...s};a(s);const c=Wt(i,s);for(const[d,m]of Object.entries(c.added))this.operation(t,{operation:r,path:d,before:void 0,after:m,context:{...o,changeType:"added"}});for(const[d,m]of Object.entries(c.removed))this.operation(t,{operation:r,path:d,before:m,after:void 0,context:{...o,changeType:"removed"}});for(const[d,{from:m,to:u}]of Object.entries(c.changed))this.operation(t,{operation:r,path:d,before:m,after:u,context:{...o,changeType:"changed"}});return s}traceSchemaTransformResult(t,r,s,a,o){if(!this.enabled)return;const i=Wt(s,a);for(const[c,d]of Object.entries(i.added))this.operation(t,{operation:r,path:c,before:void 0,after:d,context:{...o,changeType:"added"}});for(const[c,d]of Object.entries(i.removed))this.operation(t,{operation:r,path:c,before:d,after:void 0,context:{...o,changeType:"removed"}});for(const[c,{from:d,to:m}]of Object.entries(i.changed))this.operation(t,{operation:r,path:c,before:d,after:m,context:{...o,changeType:"changed"}})}traceDependencySchemaTransform(t,r,s,a,o="both"){if(!this.enabled){for(const i in s)for(const c in s[i]){const d=s[i][c];(o==="signature"||o==="both")&&d.signatureSchema&&a(d.signatureSchema),(o==="returnValue"||o==="both")&&d.returnValueSchema&&a(d.returnValueSchema)}return}for(const i in s)for(const c in s[i]){const d=s[i][c],m={filePath:i,dependencyName:c};(o==="signature"||o==="both")&&d.signatureSchema&&this.traceSchemaTransform(t,r,d.signatureSchema,a,{...m,schemaType:"signature"}),(o==="returnValue"||o==="both")&&d.returnValueSchema&&this.traceSchemaTransform(t,r,d.returnValueSchema,a,{...m,schemaType:"returnValue"})}}traceDependencySchemaChanges(t,r,s,a){var i;if(!this.enabled){a();return}const o={};for(const c in s){o[c]={};for(const d in s[c]){const m=s[c][d];o[c][d]={sig:{...m.signatureSchema||{}},rv:{...m.returnValueSchema||{}}}}}a();for(const c in s)for(const d in s[c]){const m=s[c][d],u=(i=o[c])==null?void 0:i[d],h={filePath:c,dependencyName:d};if(m.signatureSchema){const p=(u==null?void 0:u.sig)||{},f=Wt(p,m.signatureSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...h,schemaType:"signature",changeType:"added"}});for(const[y,{from:g,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:y,before:g,after:x,context:{...h,schemaType:"signature",changeType:"changed"}})}if(m.returnValueSchema){const p=(u==null?void 0:u.rv)||{},f=Wt(p,m.returnValueSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...h,schemaType:"returnValue",changeType:"added"}});for(const[y,{from:g,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:y,before:g,after:x,context:{...h,schemaType:"returnValue",changeType:"changed"}})}}}}function rf(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const vo=new ba({enabled:rf(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{vo.isEnabled()&&vo.flush()});function ul(e){if(e==null)return null;const t=e.match(/```json\s*([\s\S]*?)\s*```/);t&&(e=t[1]),e=e.replace(/"[^"]+"\s*:\s*undefined\s*,?\s*/g,""),e=e.replace(/,(\s*[}\]])/g,"$1");try{return sd.parse(e)}catch(r){const a=r.message.match(/invalid character .* at (\d+):(\d+)/);if(a){const o=parseInt(a[2],10);if(e.substring(o-2,o-1)==='"')return e=e.substring(0,o-2)+"\\"+e.substring(o-2),ul(e)}return null}}function sf({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:s}){let a="";return s&&s.length>0&&(a=`
|
|
176
|
+
User-selected Execution Flow Values:
|
|
177
|
+
The user has specifically requested these values be used in the scenario:
|
|
178
|
+
${s.map(o=>` - ${o.path}: ${o.value}${o.isCustom?" (custom value)":""}`).join(`
|
|
179
|
+
`)}
|
|
180
|
+
|
|
181
|
+
IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
|
|
182
|
+
`),`Mock Scenario Data Structure:
|
|
183
|
+
\`\`\`
|
|
184
|
+
${JSON.stringify(r,null,2)}
|
|
185
|
+
\`\`\`
|
|
186
|
+
Existing Mock Scenario Data:
|
|
187
|
+
\`\`\`
|
|
188
|
+
${JSON.stringify(t,null,2)}
|
|
189
|
+
\`\`\`
|
|
190
|
+
${a}
|
|
191
|
+
New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
|
|
192
|
+
`}function af({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}){const o=s.find(i=>i.name===Fr);return`Mock Scenario Data Structure:
|
|
193
|
+
\`\`\`
|
|
194
|
+
${JSON.stringify({props:a.arguments,dataVariables:a.dataForMocks},null,2)}
|
|
195
|
+
\`\`\`
|
|
196
|
+
|
|
197
|
+
Existing Mock Scenario Data:
|
|
198
|
+
\`\`\`
|
|
199
|
+
${JSON.stringify(s.map(i=>({name:i.name,data:Mn(o.metadata.data,i.metadata.data)})),null,2)}
|
|
200
|
+
\`\`\`
|
|
201
|
+
|
|
202
|
+
Mock Scenario that should be edited: "${t}"
|
|
203
|
+
${r?`The portion of the data that should be edited:
|
|
204
|
+
\`\`\`
|
|
205
|
+
${JSON.stringify(r,null,2)}
|
|
206
|
+
\`\`\``:""}
|
|
207
|
+
|
|
208
|
+
How this data should be changed: "${e}"
|
|
209
|
+
`}async function of({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,flowSelections:o,model:i}){const c=t?af({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}):sf({description:e,existingScenarios:s,scenariosDataStructure:a,flowSelections:o}),d=await Hs({type:"guessScenarioDataFromDescription",systemMessage:t?cf(r):lf,prompt:c,model:i??cp});await Cp({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,model:i},...d.stats});const{completion:m}=d;return m?ul(m):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const lf=`
|
|
210
|
+
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.
|
|
211
|
+
|
|
212
|
+
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.
|
|
213
|
+
|
|
214
|
+
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.
|
|
215
|
+
|
|
216
|
+
You must respond with valid JSON following this format of this TS type definition:
|
|
217
|
+
\`\`\`
|
|
218
|
+
export type ScenarioData = {
|
|
219
|
+
name: string;
|
|
220
|
+
description: string;
|
|
221
|
+
data: {
|
|
222
|
+
mockData: { [key: string]: unknown };
|
|
223
|
+
argumentsData: { [key: string]: unknown };
|
|
224
|
+
};
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
\`\`\`
|
|
228
|
+
`,cf=e=>`
|
|
229
|
+
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.
|
|
230
|
+
|
|
231
|
+
Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
|
|
232
|
+
${e?`
|
|
233
|
+
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.`:""}
|
|
234
|
+
|
|
235
|
+
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.
|
|
236
|
+
|
|
237
|
+
You must respond with valid JSON following this type definition:
|
|
238
|
+
\`\`\`
|
|
239
|
+
{
|
|
240
|
+
data: {
|
|
241
|
+
mockData: { [key: string]: unknown };
|
|
242
|
+
argumentsData: { [key: string]: unknown };
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
\`\`\`
|
|
246
|
+
`;async function df({request:e}){if(e.method!=="POST")return K({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:s,scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:c}=t;if(!r&&(!c||c.length===0))return K({error:"Missing required field: description or flowSelections"},{status:400});const d=await of({description:r||"",existingScenarios:s??[],scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:c}),m=(d==null?void 0:d.data)||d;return K({success:!0,data:m})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),K({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const uf=Object.freeze(Object.defineProperty({__proto__:null,action:df},Symbol.toStringTag,{value:"Module"}));function mf(e){const t=new Map;for(const r of[...e].reverse()){const s=t.get(r.date)||[];s.push(r),t.set(r.date,s)}return t}function hf(e){const t=new Map;for(const r of e){const s=r.name.indexOf(" - "),a=s!==-1?r.name.slice(0,s):"App",o=t.get(a)||[];o.push(r),t.set(a,o)}return[...t.entries()].sort(([r],[s])=>r==="App"?-1:s==="App"?1:r.localeCompare(s))}function pf(e,t){const r=e.replace(/[^a-zA-Z0-9_\-]/g,"_");return`${t.toISOString().replace(/:/g,"-").replace(/\.\d+Z$/,"")}_${r}.png`}function ff(e){const{title:t,timeStr:r,type:s,description:a,allScenarioNames:o,screenshot:i,scenarioScreenshots:c,commitSha:d,commitMessage:m}=e,u=["","---","",`### ${t}`,`**Time:** ${r}`,`**Type:** ${s}`];if(o.length>0&&u.push(`**Scenarios:** ${o.join(", ")}`),u.push(""),u.push(a),i&&(u.push(""),u.push(``)),c.length>0){u.push(""),u.push("**Scenario Screenshots:**");for(const h of c)u.push(""),u.push(``)}return d&&m&&(u.push(""),u.push(`**Commit:** \`${d}\` — ${m}`)),u.push(""),u.join(`
|
|
247
|
+
`)}function gf(e,t){return e.findIndex(r=>r.time===t)}function yf(e){return!!e.commitSha}function xf(e,t){return t.commitSha!==void 0&&(e.commitSha=t.commitSha),t.commitMessage!==void 0&&(e.commitMessage=t.commitMessage),t.description!==void 0&&(e.description=t.description),t.scenarios!==void 0&&(e.scenarios=t.scenarios),t.scenarioScreenshots!==void 0&&(e.scenarioScreenshots=t.scenarioScreenshots),e}function bf(e,t,r,s){const a=`
|
|
248
|
+
**Commit:** \`${r}\` — ${s||"no message"}
|
|
249
|
+
`,o=`### ${t}`,i=e.lastIndexOf(o);if(i===-1)return null;const c=e.indexOf(`
|
|
250
|
+
---
|
|
251
|
+
`,i+1),d=c!==-1?c:e.length;return e.slice(0,d)+a+e.slice(d)}async function vf(e){console.log(`[editorScenarioLookup] Looking up screenshots for ${e.length} scenarios: ${e.join(", ")}`);try{const t=await $e();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up scenarios"),[];const{project:r}=await Ie(t),a=await Te().selectFrom("editor_scenarios").select(["name","screenshot_path","id"]).where("project_id","=",r.id).where("name","in",e).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] DB query returned ${a.length} matching scenarios:`,a.map(d=>({name:d.name,screenshot_path:d.screenshot_path,id:d.id})));const o=a.filter(d=>!d.screenshot_path);o.length>0&&console.warn(`[editorScenarioLookup] ${o.length} scenarios have no screenshot_path:`,o.map(d=>d.name));const i=a.filter(d=>d.screenshot_path),c=es(i,d=>d.name).map(d=>({name:d.name,screenshotPath:d.screenshot_path,scenarioId:d.id}));return console.log(`[editorScenarioLookup] Found ${c.length} scenarios with screenshots`),c}catch(t){return console.error("[editorScenarioLookup] Failed to look up scenario screenshots:",t),[]}}async function ml(){console.log("[editorScenarioLookup] Looking up all scenario screenshots for the current session");try{const e=await $e();if(!e)return console.warn("[editorScenarioLookup] No project slug found — cannot look up session scenarios"),[];const{project:t}=await Ie(e),r=Te(),s=he()||process.cwd();let a=null;const o=O.join(s,".codeyam","editor-step.json");try{const u=G.readFileSync(o,"utf8");a=JSON.parse(u).featureStartedAt||null}catch{return console.warn("[editorScenarioLookup] No editor-step.json found — cannot determine session start"),[]}if(!a)return console.warn("[editorScenarioLookup] No featureStartedAt found in editor-step.json"),[];const i=Pr(a),c=await r.selectFrom("editor_scenarios").select(["name","screenshot_path","id"]).where("project_id","=",t.id).where("created_at",">=",i).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] Query returned ${c.length} scenarios since ${a}`);const d=c.filter(u=>u.screenshot_path),m=es(d,u=>u.name).map(u=>({name:u.name,screenshotPath:u.screenshot_path,scenarioId:u.id}));return console.log(`[editorScenarioLookup] Found ${m.length} session scenarios with screenshots`),m}catch(e){return console.error("[editorScenarioLookup] Failed to look up session scenario screenshots:",e),[]}}async function hl(e,t,r){const s=O.join(t,".codeyam","journal","screenshots");await we.mkdir(s,{recursive:!0});const a=[];for(const o of e){const i=O.join(t,".codeyam","editor-scenarios",o.screenshotPath),c=pf(o.name,r),d=O.join(s,c);console.log(`[editorScenarioLookup] Copying scenario screenshot: "${o.name}" from ${i} → ${d}`);try{await we.access(i),await we.copyFile(i,d),a.push({name:o.name,path:`screenshots/${c}`}),console.log(`[editorScenarioLookup] Successfully copied screenshot for "${o.name}"`)}catch(m){console.warn(`[editorScenarioLookup] Scenario screenshot not found: ${i}`,m instanceof Error?m.message:m)}}return console.log(`[editorScenarioLookup] Scenario screenshot summary: ${a.length} scenarios have screenshots embedded`),a}async function wf({request:e}){if(e.method!=="PATCH")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{time:r,commitSha:s,commitMessage:a,description:o,includeSessionScenarios:i}=t;if(!r)return new Response(JSON.stringify({error:"time is required to identify the entry"}),{status:400,headers:{"Content-Type":"application/json"}});const c=process.env.CODEYAM_ROOT_PATH||process.cwd(),d=O.join(c,".codeyam","journal"),m=O.join(d,"index.json");console.log(`[editor-journal-update] Updating entry with time="${r}"`);let u={entries:[]};try{const g=await we.readFile(m,"utf8");u=JSON.parse(g)}catch{return new Response(JSON.stringify({error:"No journal index found"}),{status:404,headers:{"Content-Type":"application/json"}})}const h=gf(u.entries,r);if(h===-1)return new Response(JSON.stringify({error:`No journal entry found with time "${r}"`}),{status:404,headers:{"Content-Type":"application/json"}});const p=u.entries[h];if(yf(p))return console.log(`[editor-journal-update] Rejected: entry "${p.title}" already committed (${p.commitSha}). Create a new entry instead.`),new Response(JSON.stringify({error:`Journal entry already committed (${p.commitSha}). Create a new entry via POST /api/editor-journal-entry instead of updating.`}),{status:409,headers:{"Content-Type":"application/json"}});let f,y;if(i){const g=await ml();g.length>0&&(f=g.map(x=>x.name),y=await hl(g,c,new Date))}if(xf(p,{commitSha:s,commitMessage:a,description:o,scenarios:f,scenarioScreenshots:y}),u.entries[h]=p,await we.writeFile(m,JSON.stringify(u,null,2),"utf8"),console.log("[editor-journal-update] Updated index.json"),s)try{const g=p.date,x=O.join(d,`${g}.md`);let v="";try{v=await we.readFile(x,"utf8")}catch{}if(v){const b=bf(v,p.title,s,a||null);b&&(await we.writeFile(x,b,"utf8"),console.log(`[editor-journal-update] Appended commit line to ${x}`))}}catch(g){console.warn("[editor-journal-update] Failed to update markdown:",g)}return Ct.notifyChange("journal"),console.log(`[editor-journal-update] Done: updated entry "${p.title}"`),new Response(JSON.stringify({success:!0,entry:p}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-update] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Nf=Object.freeze(Object.defineProperty({__proto__:null,action:wf},Symbol.toStringTag,{value:"Module"}));async function Cf({request:e}){try{const t=process.env.CODEYAM_ROOT_PATH||process.cwd(),r=await Oh(t);let s=0;const a={};for(const[o,i]of Object.entries(r))i.errors.length>0&&(a[o]=i,s+=i.errors.length);return new Response(JSON.stringify({hasErrors:s>0,totalErrors:s,scenarios:a}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-client-errors] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Sf=Object.freeze(Object.defineProperty({__proto__:null,loader:Cf},Symbol.toStringTag,{value:"Module"}));async function kf({request:e}){try{const r=(await tn()||[]).filter(i=>i.analyses&&i.analyses.length>0).map(i=>{var y;const c=i.analyses[0],d=c.scenarios||[],m=!((y=c.status)!=null&&y.finishedAt),u=i.entityType||"visual",p=u==="library"||u==="functionCall"?d.some(g=>{var x;return!!((x=g.metadata)!=null&&x.executionResult)}):d.some(g=>{var x,v,b,N;return((v=(x=g.metadata)==null?void 0:x.screenshotPaths)==null?void 0:v[0])&&!((b=g.metadata)!=null&&b.noScreenshotSaved)&&!((N=g.metadata)!=null&&N.sameAsDefault)}),f=d.length;return{name:i.name,entityType:u,filePath:i.filePath||"",hasScreenshot:p,isAnalyzing:m,scenarioCount:f}}),s=r.filter(i=>i.hasScreenshot),a=r.filter(i=>!i.hasScreenshot&&!i.isAnalyzing).map(i=>i.name),o=r.filter(i=>i.isAnalyzing).length;return new Response(JSON.stringify({entities:r,summary:{total:r.length,withScreenshots:s.length,missingScreenshots:a,analyzing:o}}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-entity-status] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Ef=Object.freeze(Object.defineProperty({__proto__:null,loader:kf},Symbol.toStringTag,{value:"Module"}));function Af(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=Pe("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return Pf(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function Pf(e){const t=e.trim().split(`
|
|
252
|
+
`).filter(s=>s.length>0),r=[];for(const s of t){const a=s[0],o=s[1];let i=s.slice(2).replace(/^[ \t]+/,""),c,d=!1,m;if(a==="A"||o==="A")c="added",d=a==="A";else if(a==="M"||o==="M")c="modified",d=a==="M";else if(a==="D"||o==="D")c="deleted",d=a==="D";else if(a==="R"||o==="R"){c="renamed",d=a==="R";const u=i.indexOf(" -> ");u!==-1&&(m=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(c="untracked",d=!1):(c="modified",d=a!==" "&&a!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=ee.join(u,i);try{const p=(y,g)=>{const x=Ce.readdirSync(y,{withFileTypes:!0}),v=[];for(const b of x){const N=ee.join(y,b.name),w=ee.relative(u,N);b.isDirectory()?v.push(...p(N,g)):b.isFile()&&v.push(w)}return v},f=p(h,u);for(const y of f)r.push({path:y,status:c,staged:d,...m&&{oldPath:m}})}catch(p){console.error(`Failed to expand directory ${i}:`,p)}}else r.push({path:i,status:c,staged:d,...m&&{oldPath:m}})}return r}function _f(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Pe("git branch --show-current",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch(r){return console.error("Failed to get current branch:",r),null}}function jf(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const s=Pe('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().match(/refs\/remotes\/origin\/(.+)/);if(s)return s[1];try{return Pe("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return Pe("git show-ref --verify --quiet refs/heads/master",{cwd:t,stdio:["pipe","pipe","ignore"]}),"master"}catch{return"main"}}}catch(r){return console.error("Failed to get default branch:",r),"main"}}function Mf(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Pe('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
253
|
+
`).filter(s=>s.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function ns(){const e=he();return e?Af(e):[]}function Tf(){const e=he();return e?_f(e):null}function $f(){const e=he();return e?jf(e):"main"}function Rf(){const e=he();return e?Mf(e):[]}function pl(e,t){const r=he();return r?If(e,t,r):[]}function If(e,t,r){const s=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Pe(`git diff --name-status ${e}...${t}`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
254
|
+
`).filter(i=>i.length>0).map(i=>{const c=i.split(" "),d=c[0];let m=c[1],u,h;return d==="A"?h="added":d==="M"?h="modified":d==="D"?h="deleted":d.startsWith("R")?(h="renamed",u=c[1],m=c[2]):h="modified",{path:m,status:h,...u&&{oldPath:u}}})}catch(a){return console.error("Failed to get branch diff:",a),[]}}function fl(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=Pe(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let a="";try{a=Ce.readFileSync(ee.join(r,e),"utf8")}catch(o){console.error(`Failed to read current file ${e}:`,o),a=""}return{oldContent:s,newContent:a,fileName:e}}catch(s){return console.error(`Failed to get diff for ${e}:`,s),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Df(e){const t=he();return t?fl(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Lf(e,t,r,s){const a=s||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=Pe(`git show ${t}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=Pe(`git show ${r}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:o,newContent:i,fileName:e}}catch(o){return console.error(`Failed to get branch diff for ${e}:`,o),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function mr(e,t,r){const s=he();return s?Lf(e,t,r,s):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function gl(e,t){const r=new Map;for(const s of e)s.status!=="deleted"&&(t||s.status==="added"||s.status==="untracked"?r.set(s.path,"new"):s.status==="modified"&&r.set(s.path,"edited"));return r}function Wn(e){if(!e||e==="/")return"Home";const r=e.split("?")[0].replace(/^\//,"").split("/")[0];return r.charAt(0).toUpperCase()+r.slice(1)}function yl(e,t,r){var o;const s=[],a=new Set;for(const i of e){let c=null,d=null;if(i.componentName&&i.componentPath)c=i.componentName,d=i.componentPath;else if(!i.componentName&&i.url!==void 0){const m=Wn(i.url);t[m]&&(c=m,d=t[m])}if(c&&d&&!a.has(c)){a.add(c);const m=r.find(u=>u.name===c);s.push({name:c,filePath:d,importedBy:(o=m==null?void 0:m.metadata)==null?void 0:o.importedBy})}}return s}function Vs(e,t){return!t||Object.keys(t).length===0?e:e.filter(([r])=>t[r])}function Of(e){const t=new Map;for(const r of e){const s=r.importedBy;if(!s||typeof s!="object")continue;const a=new Set;for(const o of Object.keys(s))for(const i of Object.keys(s[o]))a.add(i);a.size>0&&t.set(r.name,a)}return t}function Ff(e,t){const r=new Map;for(const s of t){const a=e.get(s.filePath);a&&r.set(s.name,a)}return r}const zf=20;function xl(e,t,r=zf){const s={};if(t.length===0||e.size===0)return s;const a=new Map;for(const m of t)a.set(m.name,m);const o=Of(t),i=Ff(e,t);for(const[m,u]of i)s[m]={status:u};const c=new Map;for(const[m]of i)c.set(m,new Set([m]));const d=[];for(const[m]of i)d.push({name:m,depth:0});for(;d.length>0;){const{name:m,depth:u}=d.shift();if(u>=r)continue;const h=c.get(m)||new Set,p=o.get(m);if(p)for(const f of p){if(!a.has(f))continue;c.has(f)||c.set(f,new Set);const y=c.get(f);let g=!1;for(const x of h)y.has(x)||(y.add(x),g=!0);g&&d.push({name:f,depth:u+1})}}for(const[m,u]of c){if(i.has(m))continue;const h=[];for(const p of u){const f=a.get(p),y=i.get(p);f&&y&&h.push({name:p,filePath:f.filePath,changeType:y})}h.sort((p,f)=>p.name.localeCompare(f.name)),s[m]={status:"impacted",impactedBy:h.length>0?h:void 0}}return s}async function Bf({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{title:r,type:s,description:a,scenarios:o,includeSessionScenarios:i,screenshot:c,commitSha:d,commitMessage:m}=t;if(console.log(`[editor-journal-entry] Creating journal entry: title="${r}", type="${s}", scenarios=${JSON.stringify(o||[])}, includeSessionScenarios=${!!i}, screenshot=${c||"none"}`),!r||!s||!a)return console.warn("[editor-journal-entry] Missing required fields:",{title:!!r,type:!!s,description:!!a}),new Response(JSON.stringify({error:"title, type, and description are required"}),{status:400,headers:{"Content-Type":"application/json"}});const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=O.join(u,".codeyam","journal");await we.mkdir(h,{recursive:!0});const p=new Date,f=p.toISOString().split("T")[0],y=p.toISOString();let g=o||[];const x=i?await ml():o&&o.length>0?await vf(o):[];i&&x.length>0&&(g=x.map(A=>A.name));const v=await hl(x,u,p),b=O.join(h,`${f}.md`);let N="";try{N=await we.readFile(b,"utf8")}catch{N=`# Development Journal — ${f}
|
|
255
|
+
`}const w=ff({title:r,timeStr:y,type:s,description:a,allScenarioNames:g,screenshot:c||null,scenarioScreenshots:v,commitSha:d||null,commitMessage:m||null});await we.writeFile(b,N+w,"utf8"),console.log(`[editor-journal-entry] Written daily markdown: ${b}`);const S=O.join(h,"index.json");let C={entries:[]};try{const A=await we.readFile(S,"utf8");C=JSON.parse(A)}catch{}let k;try{const A=he()||process.cwd();let I=!1;try{const P=Pe("git rev-list --count HEAD",{cwd:A,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();I=parseInt(P,10)<=1}catch{I=!0}const j=ns();if(j.length>0){const P=gl(j,I);try{const $=await $e();if($){const{project:T}=await Ie($);let J=Te().selectFrom("editor_scenarios").select(["name","component_name","component_path","url"]).where("project_id","=",T.id);const q=O.join(A,".codeyam","editor-step.json");try{const X=G.readFileSync(q,"utf8"),z=JSON.parse(X);z.featureStartedAt&&(J=J.where("created_at",">=",Pr(z.featureStartedAt)))}catch{}const Y=await J.orderBy("created_at","asc").execute(),B=es(Y,X=>`${X.name}::${X.url||"/"}`).map(X=>({componentName:X.component_name||null,componentPath:X.component_path||null,url:X.url??null})),D={},M=O.join(A,"app");if(G.existsSync(M)){const X=(z,L)=>{for(const W of G.readdirSync(z,{withFileTypes:!0}))if(W.name!=="codeyam-isolate"){if(W.isDirectory())X(O.join(z,W.name),L?`${L}/${W.name}`:W.name);else if(W.name==="page.tsx"||W.name==="page.js"){const V=L?`app/${L}/${W.name}`:`app/${W.name}`,Z=Wn(L?`/${L}`:"/");D[Z]=V}}};X(M,"")}let Q=[];try{await Ye(),Q=await lt({})||[]}catch{}const U=yl(B,D,Q),F=xl(P,U);Object.keys(F).length>0&&(k=F)}}catch{}}}catch{}const E={date:f,time:y,title:r,type:s,description:a,scenarios:g,screenshot:c||null,scenarioScreenshots:v,commitSha:d||null,commitMessage:m||null,entityChangeStatus:k};return C.entries.push(E),await we.writeFile(S,JSON.stringify(C,null,2),"utf8"),console.log(`[editor-journal-entry] Updated index.json (now ${C.entries.length} entries)`),Ct.notifyChange("journal"),console.log(`[editor-journal-entry] Done: title="${r}", scenarioScreenshotsEmbedded=${v.length}`),new Response(JSON.stringify({success:!0,entry:E,scenarioScreenshotsFound:v.length}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-entry] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Yf=Object.freeze(Object.defineProperty({__proto__:null,action:Bf},Symbol.toStringTag,{value:"Module"}));function Uf({request:e}){const t={"Content-Type":"application/json","Access-Control-Allow-Origin":"*"};try{const r=he()||process.cwd();let o=new URL(e.url).searchParams.get("scenarioId");if(!o){const d=O.join(r,".codeyam","active-scenario.json");if(!G.existsSync(d))return new Response(JSON.stringify({}),{headers:t});o=JSON.parse(G.readFileSync(d,"utf-8")).scenarioId||null}if(!o)return new Response(JSON.stringify({}),{headers:t});const i=O.join(r,".codeyam","editor-scenarios",`${o}.json`);if(!G.existsSync(i))return new Response(JSON.stringify({}),{headers:t});const c=G.readFileSync(i,"utf-8");return new Response(c,{headers:t})}catch{return new Response(JSON.stringify({}),{headers:t})}}const Wf=Object.freeze(Object.defineProperty({__proto__:null,loader:Uf},Symbol.toStringTag,{value:"Module"}));async function Jf(e,t){const r=he();if(!r)return{entityCalls:[],analysisCalls:[]};const s=O.join(r,".codeyam","llm-calls");try{await we.access(s)}catch{return{entityCalls:[],analysisCalls:[]}}const a=[],o=[];try{const c=(await we.readdir(s)).filter(v=>v.endsWith(".json")),d=`${e}_`,m=t?`${t}_`:null,u=[],h=[];for(const v of c)v.startsWith(d)||m&&v.startsWith(m)?u.push(v):h.push(v);const p=u.map(async v=>{try{const b=O.join(s,v),N=await we.readFile(b,"utf-8");return JSON.parse(N)}catch{return null}}),f=h.map(async v=>{try{const b=O.join(s,v),N=await we.readFile(b,"utf-8"),w=JSON.parse(N);return w.object_id===e||t&&w.object_id===t?w:null}catch{return null}}),[y,g]=await Promise.all([Promise.all(p),Promise.all(f)]),x=[...y,...g].filter(v=>v!==null);for(const v of x)v.object_id===e?a.push(v):t&&v.object_id===t&&o.push(v);a.sort((v,b)=>b.created_at-v.created_at),o.sort((v,b)=>b.created_at-v.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:a,analysisCalls:o}}async function Hf({params:e,request:t}){const{entitySha:r}=e;if(!r)return K({error:"Entity SHA is required"},{status:400});const a=new URL(t.url).searchParams.get("analysisId")||void 0,o=await Jf(r,a);return K(o)}const Vf=Object.freeze(Object.defineProperty({__proto__:null,loader:Hf},Symbol.toStringTag,{value:"Module"}));function qf(e){try{const t=O.join(e,"package.json"),r=JSON.parse(G.readFileSync(t,"utf8")),s={...r.dependencies,...r.devDependencies};return s.vitest?"vitest":s.jest?"jest":null}catch{return null}}function Gf(e,t){var i;const s=JSON.parse(t).testResults||[],a=[];for(const c of s)for(const d of c.assertionResults||[]){const m=d.ancestorTitles||[],u=d.title||d.fullName||"unknown",h=m.length>0?`${m.join(" > ")} > ${u}`:u;a.push({title:u,fullName:h,status:d.status==="passed"?"passed":d.status==="failed"?"failed":"skipped",duration:d.duration,failureMessages:(i=d.failureMessages)!=null&&i.length?d.failureMessages:void 0})}const o=a.some(c=>c.status==="failed");return{testFilePath:e,status:o?"failed":"passed",testCases:a}}async function bl(e,t){const r=qf(e);if(!r)return{testFilePath:t,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};const s=O.isAbsolute(t)?t:O.join(e,t);if(!G.existsSync(s))return{testFilePath:t,status:"error",testCases:[],errorMessage:"Test file not found"};const a=O.join(na.tmpdir(),`codeyam-test-result-${Date.now()}.json`);return new Promise(o=>{var h;let i,c;r==="vitest"?(c="node",i=["./node_modules/.bin/vitest","run","--reporter=json","--outputFile",a,t]):(c="./node_modules/.bin/jest",i=["--json","--outputFile",a,"--testPathPatterns",t]);const d=kt(c,i,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let m="";(h=d.stderr)==null||h.on("data",p=>{m+=p.toString()});const u=setTimeout(()=>{d.kill("SIGTERM"),o({testFilePath:t,status:"error",testCases:[],errorMessage:"Test timed out after 30 seconds"})},3e4);d.on("close",()=>{clearTimeout(u);try{const p=G.readFileSync(a,"utf8");G.unlinkSync(a),o(Gf(t,p))}catch{o({testFilePath:t,status:"error",testCases:[],errorMessage:m.trim().slice(0,500)||"Test runner failed to produce output"})}}),d.on("error",p=>{clearTimeout(u),o({testFilePath:t,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${p.message}`})})})}async function Kf({request:e}){const r=new URL(e.url).searchParams.get("testFile");if(!r)return new Response(JSON.stringify({status:"error",errorMessage:"Missing testFile parameter",testCases:[],testFilePath:""}),{headers:{"Content-Type":"application/json"}});const s=he()||process.cwd();try{const a=await bl(s,r);return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}catch(a){const o=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({testFilePath:r,status:"error",testCases:[],errorMessage:o}),{status:500,headers:{"Content-Type":"application/json"}})}}const Qf=Object.freeze(Object.defineProperty({__proto__:null,loader:Kf},Symbol.toStringTag,{value:"Module"}));function wo(e,t){var r,s;try{return((s=(r=Pe(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:r.toString())==null?void 0:s.trim())??null}catch(a){return console.error(`Failed to get commit SHA for ${e}:`,a),""}}function Zf(e,t,r,s){const a=Bn.createHash("sha256");return a.update(`${e}:${t}:${r}:${s}`),a.digest("hex").substring(0,16)}function vl(){const e=he();if(!e)throw new Error("No project root found");const t=ee.join(e,".codeyam","cache","branch-entity-diff");return Ce.existsSync(t)||Ce.mkdirSync(t,{recursive:!0}),t}function Xf(e){try{const t=vl(),r=ee.join(t,`${e}.json`);if(!Ce.existsSync(r))return null;const s=Ce.readFileSync(r,"utf8");return JSON.parse(s)}catch(t){return console.error("Failed to read cache:",t),null}}function eg(e,t){try{const r=vl(),s=ee.join(r,`${e}.json`);Ce.writeFileSync(s,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function tg(e,t,r){const s=Nr(t,e),a=Nr(r,e),o=new Map(s.map(u=>[u.name,u])),i=new Map(a.map(u=>[u.name,u])),c=[],d=[],m=[];for(const[u,h]of i){const p=o.get(u);p?p.sha!==h.sha&&d.push({name:u,baseSha:p.sha,compareSha:h.sha,entityType:h.entityType}):c.push(h)}for(const[u,h]of o)i.has(u)||m.push(h);return{filePath:e,newEntities:c,modifiedEntities:d,deletedEntities:m}}function ng(e,t){const r=he();if(!r)throw new Error("No project root found");const s=wo(e,r),a=wo(t,r);if(!s||!a)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=Zf(e,t,s,a),i=Xf(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const c=pl(e,t),d=[];for(const u of c)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const h=mr(u.path,e,t),p=Nr(h.oldContent,u.path);d.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:p})}else if(u.status==="added"){const h=mr(u.path,e,t),p=Nr(h.newContent,u.path);d.push({filePath:u.path,newEntities:p,modifiedEntities:[],deletedEntities:[]})}else{const h=mr(u.path,e,t),p=tg(u.path,h.oldContent,h.newContent);(p.newEntities.length>0||p.modifiedEntities.length>0||p.deletedEntities.length>0)&&d.push(p)}const m={baseBranch:e,compareBranch:t,baseCommitSha:s,compareCommitSha:a,fileComparisons:d,cacheKey:o,computedAt:new Date().toISOString()};return eg(o,m),m}function rg({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),s=t.searchParams.get("compare");if(!r||!s)return K({error:"Missing required parameters: base and compare"},{status:400});const a=ng(r,s);return K(a)}catch(t){return console.error("Failed to compute branch entity diff:",t),K({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const sg=Object.freeze(Object.defineProperty({__proto__:null,loader:rg},Symbol.toStringTag,{value:"Module"}));async function ag({request:e}){if(e.method!=="POST")return K({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:s,projectId:a,viewportWidth:o=1440}=t;if(!r||!s||!a)return K({error:"Missing required fields: serverUrl, scenarioId, and projectId"},{status:400});console.log(`[Capture] URL to capture: ${r}`),console.log(`[Capture] Scenario ID from request: ${s}`);const i=he();if(!i)return K({error:"Project root not found"},{status:500});const c=O.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:r,scenarioId:s,projectId:a,projectRoot:i,viewportWidth:o}),m=await new Promise(p=>{const f=O.join(i,".codeyam","db.sqlite3"),y=kt("npx",["tsx",c,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let g="",x="";y.stdout.on("data",v=>{const b=v.toString();g+=b;const N=b.trim().split(`
|
|
256
|
+
`);for(const w of N)w.includes("[Capture]")&&console.log(w)}),y.stderr.on("data",v=>{const b=v.toString();x+=b,console.error("[Capture:Error]",b.trim())}),y.on("close",v=>{p(v===0?{success:!0,output:g}:{success:!1,output:g,error:x||`Process exited with code ${v}`})}),y.on("error",v=>{console.error("[Capture] Failed to spawn child process:",v),p({success:!1,output:"",error:v.message})})});if(!m.success)return K({error:"Failed to capture screenshot",details:m.error},{status:500});const u=m.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return K({error:"Failed to parse capture result"},{status:500});const h=JSON.parse(u[1]);return K(h)}catch(t){return console.error("[Capture] Error:",t),K({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const og=Object.freeze(Object.defineProperty({__proto__:null,action:ag},Symbol.toStringTag,{value:"Module"}));function ig(e){const t=e||process.cwd();try{return Pe("git rev-parse HEAD",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch(r){throw new Error(`Failed to get HEAD SHA: ${r}`)}}function lg(e){const t=e||process.cwd();try{return Pe("git rev-parse --git-dir",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),!0}catch{return!1}}function cg(e){if(lg(e))return!1;Pe("git init",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]});try{Pe('git config user.email "codeyam@local"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Pe('git config user.name "CodeYam"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}catch{}return!0}function dg(e){Pe("git add -A",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}function ug(e,t){return Pe(`git commit -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),ig(e)}function mg(e){return/^[0-9a-f]{7,40}$/i.test(e)}function hg(e,t){try{return Pe(`git cat-file -t ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"}),!0}catch{return!1}}function pg(e,t){try{return{stashed:!Pe(`git stash push -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:"pipe"}).includes("No local changes")}}catch{return{stashed:!1}}}function fg(e,t){Pe(`git checkout ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"})}async function gg({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{commitSha:r}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({success:!1,error:"commitSha is required"}),{status:400,headers:{"Content-Type":"application/json"}});if(!mg(r))return new Response(JSON.stringify({success:!1,error:"Invalid commit SHA format"}),{status:400,headers:{"Content-Type":"application/json"}});const s=process.env.CODEYAM_ROOT_PATH||process.cwd();if(console.log(`[editor-load-commit] Loading commit ${r} in ${s}`),!hg(s,r))return new Response(JSON.stringify({success:!1,error:`Commit ${r} not found`}),{status:400,headers:{"Content-Type":"application/json"}});const{stashed:a}=pg(s,"codeyam: auto-stash before time travel");a&&console.log("[editor-load-commit] Stashed uncommitted changes");try{fg(s,r),console.log(`[editor-load-commit] Checked out ${r}`)}catch(o){const i=o instanceof Error?o.message:String(o);return console.error("[editor-load-commit] Checkout failed:",i),new Response(JSON.stringify({success:!1,error:`Checkout failed: ${i}`}),{status:500,headers:{"Content-Type":"application/json"}})}try{const i=await(await fetch(`http://localhost:${process.env.CODEYAM_PORT||"3111"}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})})).json();console.log("[editor-load-commit] Dev server restart:",i)}catch(o){console.warn("[editor-load-commit] Dev server restart warning:",o)}return new Response(JSON.stringify({success:!0,stashed:a}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-load-commit] Error:",t),new Response(JSON.stringify({success:!1,error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const yg=Object.freeze(Object.defineProperty({__proto__:null,action:gg},Symbol.toStringTag,{value:"Module"}));async function xg(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await Ye();const s=await Pt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const a=Te(),o=s.entitySha,i=await a.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let c={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?c=JSON.parse(i.metadata):c=i.metadata),c.defaultWidth=t,await a.updateTable("entities").set({metadata:JSON.stringify(c)}).where("sha","=",o).execute(),console.log(`[recapture] Updated defaultWidth for entity ${o} to ${t}`),!s.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=s.scenarios)==null?void 0:f.length)||0} scenarios`),await gn(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=he();if(!d)throw new Error("Project root not found");const m=O.join(d,".codeyam","config.json"),u=JSON.parse(G.readFileSync(m,"utf8")),{projectSlug:h}=u;if(!h)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:h,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${p}`),{jobId:p}}async function bg(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await Ye();const s=await Pt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const a=(u=s.scenarios)==null?void 0:u.find(h=>h.id===t);if(!a)throw console.log(`[recapture] Scenario ${t} not found in analysis ${e}`),new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${a.name}`),await gn(e,h=>{if(h&&(h.readyToBeCaptured=!0,delete h.finishedAt,h.scenarios)){const p=h.scenarios.find(f=>f.name===a.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 ${a.name} for recapture`);const o=he();if(!o)throw new Error("Project root not found");const i=O.join(o,".codeyam","config.json"),c=JSON.parse(G.readFileSync(i,"utf8")),{projectSlug:d}=c;if(!d)throw new Error("Project slug not found in config");const{jobId:m}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:d,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${m}`),{jobId:m}}async function vg({request:e,context:t}){if(e.method!=="POST")return K({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await jt()),!r)return K({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a||!o)return K({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${a}, scenario ${o}`);const i=await bg(a,o,r);return console.log("[API] Scenario recapture queued",i),K({success:!0,message:"Scenario recapture queued",...i})}catch(s){return console.log("[API] Error during scenario recapture:",s),K({error:"Failed to recapture scenario",details:s instanceof Error?s.message:String(s)},{status:500})}}const wg=Object.freeze(Object.defineProperty({__proto__:null,action:vg},Symbol.toStringTag,{value:"Module"}));async function qs(e){try{return await xe.stat(e),!0}catch{return!1}}async function wl(){try{const e=he();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await xe.readFile(t,"utf-8")).projectSlug||null}catch{return null}}function Ng(){return`/private/tmp/claude-501/-${(he()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const hr="/tmp/claude-rule-markers",Cg=/<system-reminder>[\s\S]*?<\/system-reminder>/g,No=2e3;function Sg(e,t){if(e==="Read"||e==="Write"||e==="Edit")return String(t.file_path||"");if(e==="Glob")return String(t.pattern||"");if(e==="Grep"){const r=String(t.pattern||""),s=String(t.path||"");return s?`"${r}" in ${s}`:`"${r}"`}if(e==="Bash"){const r=String(t.command||"");return r.length>100?r.slice(0,100)+"...":r}if(e==="Task")return String(t.description||String(t.prompt||"").slice(0,80));for(const r of Object.values(t))if(typeof r=="string"&&r)return r.slice(0,80);return""}const kg=["no,","no ","that's not","thats not","that is not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","dont do","shouldn't","should not","try again","let me clarify","to clarify","that broke","that failed","error","bug"];function Eg(e){const t=[],r=new Set;for(const s of e)if(!(s.type!=="tool_call"||!s.name||!s.input)){if(s.name==="Write"||s.name==="Edit"){const a=String(s.input.file_path||"");if(a.includes(".claude/rules/")){const o=a.replace(/^.*?(\.claude\/rules\/)/,"$1"),i=`${s.name}:${o}`;r.has(i)||(r.add(i),s.name==="Write"?t.push({action:"created",filePath:o,content:String(s.input.content||"")}):t.push({action:"modified",filePath:o,oldString:String(s.input.old_string||""),newString:String(s.input.new_string||"")}))}}else if(s.name==="Bash"){const a=String(s.input.command||"");if(a.includes("codeyam memory touch")){const o=`touch:${a}`;r.has(o)||(r.add(o),t.push({action:"touched",filePath:a}))}}}return t}function Ag(e){if(!e)return;const t="### Session transcript",r=e.indexOf(t);if(r===-1)return;let s=e.slice(r+t.length).trim();const a=s.indexOf(`
|
|
257
|
+
###`);return a!==-1&&(s=s.slice(0,a).trim()),s||void 0}function Pg(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const s of kg)if(r.includes(s))return!0}return!1}function _g(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type==="assistant"){const a=(s.message||{}).model;if(typeof a=="string"&&a)return a}}catch{continue}}}function jg(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type!=="result")continue;const a={subtype:String(s.subtype||"unknown"),is_error:!!s.is_error};if(typeof s.duration_ms=="number"&&(a.duration_ms=s.duration_ms),typeof s.duration_api_ms=="number"&&(a.duration_api_ms=s.duration_api_ms),typeof s.num_turns=="number"&&(a.num_turns=s.num_turns),typeof s.total_cost_usd=="number"&&(a.total_cost_usd=s.total_cost_usd),s.usage&&typeof s.usage=="object"){a.usage={};for(const o of["input_tokens","output_tokens","cache_read_input_tokens","cache_creation_input_tokens"])typeof s.usage[o]=="number"&&(a.usage[o]=s.usage[o])}return Array.isArray(s.errors)&&s.errors.length>0&&(a.errors=s.errors.map(String)),a}catch{continue}}}function Mg(e){const t=[],r={};for(const s of e){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}const i=o.type;if(i==="progress"||i==="system"||i==="result")continue;const d=(o.message||{}).content,m=o.timestamp||"";if(i==="user"){if(typeof d=="string")t.push({type:"user_prompt",text:d,timestamp:m,agent_id:String(o.agentId||o.session_id||"unknown"),slug:String(o.slug||"")});else if(Array.isArray(d)){for(const u of d)if(typeof u=="object"&&u!==null&&u.type==="tool_result"){const h=u,p=String(h.tool_use_id||"");let f=h.content;const y=!!h.is_error;typeof f=="string"&&(f=f.replace(Cg,"").trim()),t.push({type:"tool_result",tool_use_id:p,tool_name:r[p]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:y,timestamp:m})}}}else if(i==="assistant"&&Array.isArray(d))for(const u of d){if(typeof u!="object"||u===null)continue;const h=u;if(h.type==="text"){const p=String(h.text||"").trim();p&&t.push({type:"assistant_text",text:p,timestamp:m})}else if(h.type==="tool_use"){const p=String(h.id||""),f=String(h.name||"unknown"),y=h.input||{};r[p]=f,t.push({type:"tool_call",tool_use_id:p,name:f,input:y,timestamp:m})}}}return t}function Tg(e,t){return e.type==="user_prompt"||e.type==="assistant_text"?(e.text||"").toLowerCase().includes(t):e.type==="tool_call"?(e.name||"").toLowerCase().includes(t)?!0:JSON.stringify(e.input||{}).toLowerCase().includes(t):e.type==="tool_result"?(e.content||"").toLowerCase().includes(t):!1}const ln=20;async function Co(e){const r=(await xe.readFile(e.filePath,"utf-8")).split(`
|
|
258
|
+
`),s=Mg(r);if(s.length===0)return null;const a=s.find(N=>N.type==="user_prompt"),o=e.stem,i=_g(r);let c=(a==null?void 0:a.slug)||"",d=(a==null?void 0:a.timestamp)||"";d||(d=new Date(e.mtime).toISOString());let m;if(e.filePath.endsWith(".log")){e.stem.endsWith("-stale")?c=c||"rule-reflection/stale":e.stem.endsWith("-conversation")?c=c||"rule-reflection/conversation":e.stem.endsWith("-interruption")?c=c||"rule-reflection/interruption":c=c||"rule-reflection";const N=e.filePath.replace(/\.log$/,".context");if(await qs(N))try{m=await xe.readFile(N,"utf-8")}catch{}}const u=s.filter(N=>N.type==="tool_call").length,h=s.filter(N=>N.type==="assistant_text").length,p=s.filter(N=>N.type==="tool_result"&&N.is_error&&N.content!=="Sibling tool call errored"),f=p.length,y=p.map(N=>{const w=N.content||"Unknown error";return w.length>150?w.slice(0,150)+"...":w});for(const N of s)N.type==="tool_call"&&N.name&&N.input&&(N.summary=Sg(N.name,N.input));for(const N of s)N.type==="tool_result"&&N.content&&N.content.length>No&&(N.truncated=!0,N.fullLength=N.content.length,N.content=N.content.slice(0,No));const g=Eg(s),x=Pg(s),v=Ag(m),b=jg(r);return{id:o,slug:c,timestamp:d,model:i,sourceFile:e.filePath,stats:{toolCalls:u,textBlocks:h,errors:f,errorMessages:y},entries:s,context:m,conversationSnippet:v,ruleChanges:g,hasConfusion:x,sessionResult:b}}async function $g(){const e=Ng(),t=hr,r=[];if(await qs(e)){const i=await xe.readdir(e);for(const c of i)if(c.endsWith(".output")){const d=ee.join(e,c),m=await xe.stat(d);r.push({filePath:d,stem:c.replace(".output",""),mtime:m.mtimeMs})}}const s=new Set,a=await wl(),o=[];a&&o.push(ee.join(t,a)),o.push(t);for(const i of o){if(!await qs(i))continue;const c=await xe.readdir(i);for(const d of c){if(!d.endsWith(".log")||s.has(d))continue;s.add(d);const m=ee.join(i,d),u=await xe.stat(m);r.push({filePath:m,stem:d.replace(".log",""),mtime:u.mtimeMs})}}return r.sort((i,c)=>c.mtime-i.mtime),r}async function Rg({request:e}){var t;try{const r=new URL(e.url),s=((t=r.searchParams.get("search"))==null?void 0:t.toLowerCase())||"",a=Math.max(1,parseInt(r.searchParams.get("page")||"1",10)),o=await $g();if(!s){const u=o.length,h=(a-1)*ln,p=o.slice(h,h+ln),f=[];for(const y of p){const g=await Co(y);g&&f.push(g)}return Response.json({agents:f,total:u,page:a,pageSize:ln})}const i=[];for(const u of o){const h=await Co(u);if(!h)continue;(h.id.toLowerCase().includes(s)||h.slug.toLowerCase().includes(s)||h.entries.some(f=>Tg(f,s)))&&i.push(h)}const c=i.length,d=(a-1)*ln,m=i.slice(d,d+ln);return Response.json({agents:m,total:c,page:a,pageSize:ln})}catch(r){return console.error("[api.agent-transcripts] Error:",r),Response.json({error:"Failed to load agent transcripts",details:r instanceof Error?r.message:String(r)},{status:500})}}const Ig=Object.freeze(Object.defineProperty({__proto__:null,loader:Rg},Symbol.toStringTag,{value:"Module"}));function Dg(e){var a,o;const t=ee.join(e,"package.json");if(!Ce.existsSync(t))return{error:"No package.json found."};let r="npm",s=["run","dev"];try{const i=JSON.parse(Ce.readFileSync(t,"utf8"));if(Ce.existsSync(ee.join(e,"pnpm-lock.yaml"))?r="pnpm":Ce.existsSync(ee.join(e,"yarn.lock"))?r="yarn":Ce.existsSync(ee.join(e,"bun.lockb"))&&(r="bun"),!((a=i.scripts)!=null&&a.dev))if((o=i.scripts)!=null&&o.start)s=["run","start"];else return{error:'No "dev" or "start" script found in package.json.'}}catch{}return{command:r,args:s}}const Lg=[/Local:\s+(https?:\/\/[^\s]+)/,/Ready on\s+(https?:\/\/[^\s]+)/i,/started at\s+(https?:\/\/[^\s]+)/i,/listening on\s+(https?:\/\/[^\s]+)/i,/http:\/\/localhost:\d+/];function Og(e){for(const t of Lg){const r=e.match(t);if(r){const s=r[1]||r[0];return Fg(s).trim()}}return null}function Fg(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function zg(e){const{exitCode:t,uptime:r,retryCount:s}=e,a=r<1e4;return t!==0&&t!==null&&a&&s===0?{action:"retry"}:t!==0&&t!==null?{action:"error"}:{action:"stopped"}}const Nl="__codeyam_editor_dev_server__",So=30;function va(){return globalThis[Nl]??null}function Cl(e){globalThis[Nl]=e}function _s(e,t){const r=[ee.join(e,".next","dev","lock"),ee.join(e,"node_modules",".vite","deps","_lock")];for(const s of r)try{Ce.existsSync(s)&&(Ce.unlinkSync(s),console.log(`[editor-dev-server] Removed stale lock file: ${s}`))}catch(a){console.warn(`[editor-dev-server] Failed to remove lock file ${s}:`,a)}if(t)try{const s=Pe(`lsof -ti:${t}`,{encoding:"utf8"}).trim();s&&(Pe(`lsof -ti:${t} | xargs kill`),console.log(`[editor-dev-server] Killed orphaned process(es) on port ${t}: ${s}`))}catch{}}function Bg({request:e}){const t=va();return t?new Response(JSON.stringify({status:t.status,url:t.url,proxyUrl:Zi(),pid:t.pid,errorMessage:t.status==="error"?t.errorMessage:null}),{headers:{"Content-Type":"application/json"}}):new Response(JSON.stringify({status:"stopped",url:null,proxyUrl:null}),{headers:{"Content-Type":"application/json"}})}async function Yg({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{action:r}=t;return r==="start"?Gs():r==="stop"?ko():r==="restart"?(ko(),await new Promise(s=>setTimeout(s,1e3)),Gs()):new Response(JSON.stringify({error:'Invalid action. Use "start", "stop", or "restart".'}),{status:400,headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}function Ug(){let t=ee.dirname(new URL(import.meta.url).pathname);for(let s=0;s<5;s++){const a=ee.dirname(t);if(ee.basename(a)==="webserver"||ee.basename(t)==="webserver"){t=ee.basename(t)==="webserver"?t:a;break}t=a}const r=[ee.join(t,"scripts","codeyam-preload.mjs"),ee.join(t,"scripts","codeyam-preload.mjs")];for(const s of r)if(Ce.existsSync(s))return s;return console.warn("[editor-dev-server] codeyam-preload.mjs not found, SSR fetch interception disabled"),null}function Gs(e=!1){var g,x;const t=va();if(t&&t.status!=="stopped"&&t.status!=="error")return new Response(JSON.stringify({status:t.status,url:t.url,message:"Dev server is already running"}),{headers:{"Content-Type":"application/json"}});const r=he()||process.cwd(),s=Dg(r);if("error"in s)return new Response(JSON.stringify({error:s.error}),{status:400,headers:{"Content-Type":"application/json"}});const{command:a,args:o}=s;_s(r,3e3),_s(r,3001),_s(r,5173),console.log(`[editor-dev-server] Starting: ${a} ${o.join(" ")} in ${r}`);const c=parseInt(process.env.CODEYAM_PORT||"3111",10)+1,d=Ug(),m=process.env.NODE_OPTIONS||"",u=d?`${m} --import ${d}`.trim():m,h=kt(a,o,{cwd:r,stdio:["ignore","pipe","pipe"],env:{...process.env,FORCE_COLOR:"1",...u?{NODE_OPTIONS:u}:{},CODEYAM_PROXY_URL:`http://localhost:${c}`},detached:!0});h.unref();const p=e?((t==null?void 0:t.retryCount)??0)+1:0,f={process:h,url:null,status:"starting",errorMessage:null,stderrBuffer:[],pid:h.pid||0,startedAt:Date.now(),retryCount:p};Cl(f);const y=(v,b)=>{const N=v.toString();if(b){const w=N.split(`
|
|
259
|
+
`).filter(S=>S.trim());f.stderrBuffer.push(...w),f.stderrBuffer.length>So&&(f.stderrBuffer=f.stderrBuffer.slice(-So))}if(f.status==="starting"){const w=Og(N);if(w){f.url=w,f.status="running",console.log(`[editor-dev-server] URL detected: ${f.url}`);const S=parseInt(process.env.CODEYAM_PORT||"3111",10);Xi({port:S+1,targetUrl:f.url})}}};return(g=h.stdout)==null||g.on("data",v=>y(v,!1)),(x=h.stderr)==null||x.on("data",v=>y(v,!0)),h.on("exit",v=>{console.log(`[editor-dev-server] Process exited with code ${v}`);const b=Date.now()-f.startedAt,N=zg({exitCode:v??null,uptime:b,retryCount:f.retryCount});N.action==="retry"?(console.log(`[editor-dev-server] Quick failure (${b}ms), auto-retrying...`),f.status="stopped",Gs(!0)):N.action==="error"?(f.status="error",f.errorMessage=f.stderrBuffer.length>0?f.stderrBuffer.join(`
|
|
260
|
+
`):`Dev server exited with code ${v}`,console.error(`[editor-dev-server] Server failed: ${f.errorMessage}`)):f.status="stopped"}),h.on("error",v=>{console.error("[editor-dev-server] Process error:",v),f.status="error",f.errorMessage=v.message}),new Response(JSON.stringify({status:"starting",pid:h.pid,message:`Starting ${a} ${o.join(" ")}`}),{headers:{"Content-Type":"application/json"}})}function ko(){const e=va();if(!e||e.status==="stopped")return new Response(JSON.stringify({status:"stopped",message:"No server to stop"}),{headers:{"Content-Type":"application/json"}});el();try{e.process.pid&&process.kill(-e.process.pid,"SIGTERM")}catch{try{e.process.kill("SIGTERM")}catch{}}return e.status="stopped",Cl(null),new Response(JSON.stringify({status:"stopped",message:"Dev server stopped"}),{headers:{"Content-Type":"application/json"}})}const Wg=Object.freeze(Object.defineProperty({__proto__:null,action:Yg,loader:Bg},Symbol.toStringTag,{value:"Module"}));async function Jg({params:e,request:t}){const{projectSlug:r}=e;if(!r)return new Response("Project slug is required",{status:400});if(t.method!=="DELETE")return new Response("Method not allowed",{status:405});const s=Jr(r);try{return await jn(s,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(a){console.error("[api.logs] Error clearing log file:",a);const o=a instanceof Error?a.message:String(a);return new Response(`Error clearing log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function Hg({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=Jr(t);try{if(!Rt(r))return new Response("No logs available yet. Analysis may not have started.",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});const s=await Ls(r,"utf-8");return!s||s.trim().length===0?new Response("Log file is empty. Waiting for analysis to start...",{headers:{"Content-Type":"text/plain; charset=utf-8"}}):new Response(s,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(s){console.error("[api.logs] Error reading log file:",s);const a=s instanceof Error?s.message:String(s);return new Response(`Error reading log file: ${a}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const Vg=Object.freeze(Object.defineProperty({__proto__:null,action:Jg,loader:Hg},Symbol.toStringTag,{value:"Module"}));function qg({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return Response.json({error:"Missing path parameter"},{status:400});const s=he()||process.cwd(),a=O.resolve(s,r);if(!a.startsWith(s+O.sep)&&a!==s)return Response.json({error:"Path outside project root"},{status:403});const o=fl(r,s);return Response.json(o)}const Gg=Object.freeze(Object.defineProperty({__proto__:null,loader:qg},Symbol.toStringTag,{value:"Module"}));async function Kg(){const e=await $e();if(!e)return Response.json({error:"No project configured"},{status:400});const{project:t}=await Ie(e),r=Te(),s=process.env.CODEYAM_PORT||"3111",a=he()||process.cwd(),o=O.join(a,".codeyam","editor-step.json");let i=null;try{const u=G.readFileSync(o,"utf8");i=JSON.parse(u).featureStartedAt||null}catch{}let c=r.selectFrom("editor_scenarios").select(["id","name","component_name","component_path"]).where("project_id","=",t.id);if(i){const u=i.replace("T"," ").replace(/\.\d{3}Z$/,"");c=c.where("created_at",">=",u)}const m=(await c.orderBy("created_at","asc").execute()).map(u=>({id:u.id,name:u.name,componentName:u.component_name||null,link:`http://localhost:${s}/editor?scenario=${u.id}&ref=link`}));return Response.json({scenarios:m})}const Qg=Object.freeze(Object.defineProperty({__proto__:null,loader:Kg},Symbol.toStringTag,{value:"Module"}));async function Zg(e,t){var o,i,c,d,m,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await Ye();const r=await Pt({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const s=(o=r.scenarios)==null?void 0:o.find(h=>h.id===t);if(!s)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${s.name}`);const a={returnValue:{status:"success",data:((d=(c=(i=s.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 ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(m=s.metadata)==null?void 0:m.data)==null?void 0:u.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),a}async function Xg({request:e}){if(e.method!=="POST")return K({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),s=t.get("scenarioId");if(!r||!s)return K({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${s}`);const a=await Zg(r,s);return console.log("[API] Function execution completed successfully"),K({success:!0,result:a})}catch(t){return console.log("[API] Error during function execution:",t),K({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const e0=Object.freeze(Object.defineProperty({__proto__:null,action:Xg},Symbol.toStringTag,{value:"Module"}));function t0({request:e}){return K({status:"ok"})}async function n0({request:e,context:t}){if(e.method!=="POST")return K({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await jt()),!r)return console.error("[Interactive Mode API] Queue not initialized"),K({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("action"),o=s.get("analysisId"),i=s.get("scenarioId");if(!a||!o)return K({error:"Missing required fields: action and analysisId"},{status:400});if(a!=="start"&&a!=="stop")return K({error:'Invalid action. Must be "start" or "stop"'},{status:400});const c=await $e();if(console.log("[Interactive Mode API] projectSlug:",c),!c)return K({error:"Project not initialized"},{status:500});if(a==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:c});return K({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:c});return K({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:d})}}catch(s){console.error("[Interactive Mode API] Error:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Interactive Mode API] Error stack:",o),K({error:"Failed to control interactive mode",details:a},{status:500})}}const r0=Object.freeze(Object.defineProperty({__proto__:null,action:n0,loader:t0},Symbol.toStringTag,{value:"Module"}));async function s0({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,screenshotPaths:s}=t;if(!r)return Response.json({error:"Missing required field: scenarioId"},{status:400});if(console.log(`[API] Deleting scenario ${r}`),s&&s.length>0){const a=he();if(a)for(const o of s){const i=ee.join(a,".codeyam","captures","screenshots",o);try{await xe.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 ru({ids:[r]}),console.log(`[API] Scenario ${r} deleted successfully`),Response.json({success:!0,message:"Scenario deleted successfully"})}catch(t){return console.error("[API] Error deleting scenario:",t),Response.json({error:"Failed to delete scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const a0=Object.freeze(Object.defineProperty({__proto__:null,action:s0},Symbol.toStringTag,{value:"Module"}));class o0 extends Dr{emitFileSynced(t,r){this.emit("event",{type:"file-synced",fileName:t,filePath:r,timestamp:Date.now()})}emitError(t,r){this.emit("event",{type:"sync-error",fileName:t,filePath:r,timestamp:Date.now()})}emitRefreshPreview(){this.emit("event",{type:"refresh-preview",timestamp:Date.now()})}}const Ks="__codeyam_dev_mode_event_emitter__";if(!globalThis[Ks]){const e=new o0;e.setMaxListeners(20),globalThis[Ks]=e}const Eo=globalThis[Ks];function i0({request:e}){const t=new ReadableStream({start(r){const s=new TextEncoder;r.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
261
|
+
|
|
262
|
+
`));let a=!1;const o=()=>{if(!a){a=!0,Eo.off("event",i),clearInterval(c);try{r.close()}catch{}}},i=d=>{try{r.enqueue(s.encode(`data: ${JSON.stringify(d)}
|
|
263
|
+
|
|
264
|
+
`))}catch{o()}};Eo.on("event",i);const c=setInterval(()=>{try{r.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
265
|
+
|
|
266
|
+
`))}catch{o()}},3e4);e.signal.addEventListener("abort",o)}});return new Response(t,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const l0=Object.freeze(Object.defineProperty({__proto__:null,loader:i0},Symbol.toStringTag,{value:"Module"})),Ln="/tmp/codeyam",Qs=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",Sl=500,c0=Sl*1024*1024;function qt(e,t){try{return Pe(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function pr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function kl(e){return qt("config user.email",e)}function d0(e){const t=O.join(e,".codeyam","debug-report.md");if(!G.existsSync(t))return null;try{return G.readFileSync(t,"utf8")}catch{return null}}function u0(e,t=20){const r=O.join(Ln,"local-dev",e,"codeyam","log.txt");if(!G.existsSync(r))return[];try{return G.readFileSync(r,"utf8").split(`
|
|
267
|
+
`).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function m0(e){try{const t=await fetch(`${Qs}/api/reports/check-base`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseSha:e})});if(!t.ok)return!1;const{hasBase:r}=await t.json();return r}catch{return!1}}function h0(e,t){try{Pe(`git archive HEAD | gzip > "${t}"`,{cwd:e,stdio:"pipe",shell:"/bin/bash"})}catch(r){throw new Error(`Failed to create base archive: ${r.message}`)}}function p0(e){const{projectRoot:t,projectSlug:r,outputPath:s,metadata:a,screenshot:o,onProgress:i}=e,c=i||(()=>{}),d=Date.now(),m=O.join(Ln,`delta-staging-${d}`),u=O.join(m,"delta");G.mkdirSync(u,{recursive:!0});try{const h=qt("diff --binary HEAD",t)||"";G.writeFileSync(O.join(u,"tracked.patch"),h?h+`
|
|
268
|
+
`:"");const p=qt("ls-files --others --exclude-standard",t);if(p){const x=O.join(u,"untracked");G.mkdirSync(x,{recursive:!0});for(const v of p.split(`
|
|
269
|
+
`).filter(Boolean)){const b=O.join(t,v),N=O.join(x,v);if(G.existsSync(b)){const w=O.dirname(N);G.mkdirSync(w,{recursive:!0}),G.statSync(b).isFile()&&G.copyFileSync(b,N)}}}const f=O.join(t,".codeyam");if(G.existsSync(f)){const x=O.join(u,"codeyam");G.cpSync(f,x,{recursive:!0})}G.writeFileSync(O.join(u,"meta.json"),JSON.stringify(a,null,2));const y=O.join(Ln,"local-dev",r,"codeyam","log.txt");G.existsSync(y)?G.copyFileSync(y,O.join(u,"codeyam-log.txt")):G.writeFileSync(O.join(u,"codeyam-log.txt"),`# Log file not found
|
|
270
|
+
`);const g=O.join(t,".codeyam","debug-report.md");G.existsSync(g)&&(G.copyFileSync(g,O.join(u,"debug-report.md")),c("Debug report included")),o&&o.length>0&&(G.writeFileSync(O.join(u,"screenshot.jpg"),o),c(`Screenshot included (${pr(o.length)})`));try{Pe(`tar -czf "${s}" -C "${m}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{G.rmSync(m,{recursive:!0,force:!0})}}async function f0(e){const{projectRoot:t,projectSlug:r,feedback:s,screenshot:a,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const c=qt("rev-parse HEAD",t);if(!c)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const d=qt("rev-parse --abbrev-ref HEAD",t)||"unknown",m=qt("status --porcelain",t),u=qt("remote get-url origin",t),h=m!==null&&m.length>0,p=Bi(r),f=d0(t);let y=s;f&&(y={...s||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /codeyam-diagnose workflow"));const g={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:c,branch:d,isDirty:h,remoteUrl:u},versions:{cli:p.cliVersion,webserver:p.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:y},x=Date.now(),v=O.join(Ln,`base-${c}-${x}.tar.gz`),b=O.join(Ln,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const N=await m0(c);let w=null;N?i("Server already has base, skipping..."):(i("Generating base archive..."),h0(t,v),w=G.statSync(v).size,i(`Base archive: ${pr(w)}`)),i("Generating delta archive..."),p0({projectRoot:t,projectSlug:r,outputPath:b,metadata:g,screenshot:a,onProgress:o});const C=G.statSync(b).size;i(`Delta archive: ${pr(C)}`);const k=(w||0)+C;if(k>c0)throw G.existsSync(v)&&G.unlinkSync(v),G.unlinkSync(b),new Error(`Bundle too large: ${pr(k)} (max: ${Sl} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:N?null:v,deltaPath:b,metadata:g,baseSha:c,baseSize:w,deltaSize:C}}async function g0(e){const{basePath:t,deltaPath:r,projectSlug:s,metadata:a,baseSha:o,deltaSize:i,onProgress:c}=e,d=c||(()=>{}),m=G.statSync(r),u=t?G.statSync(t):null,h=m.size+((u==null?void 0:u.size)||0);d("Requesting upload URLs...");const p=await fetch(`${Qs}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:s,fileSizeBytes:h,baseSha:o,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:a.timestamp,git:a.git,versions:a.versions,system:a.system,feedback:a.feedback}})});if(!p.ok){const N=await p.json();throw new Error(N.error||`Server returned ${p.status}`)}const{reportId:f,deltaUploadUrl:y,baseUploadUrl:g}=await p.json(),x=[];if(t&&g){d("Uploading base...");const N=G.readFileSync(t);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:N}).then(w=>{if(!w.ok)throw new Error(`Base upload failed: ${w.status}`)}))}d("Uploading delta...");const v=G.readFileSync(r);x.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:v}).then(N=>{if(!N.ok)throw new Error(`Delta upload failed: ${N.status}`)})),await Promise.all(x),d("Confirming upload...");const b=await fetch(`${Qs}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!b.ok){const N=await b.json();throw new Error(N.error||`Confirm failed: ${b.status}`)}return t&&G.existsSync(t)&&G.unlinkSync(t),G.unlinkSync(r),{bundleId:f}}async function y0({request:e}){if(e.method!=="POST")return K({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),s=t.get("description"),a=t.get("email"),o=t.get("source"),i=t.get("entitySha"),c=t.get("scenarioId"),d=t.get("analysisId"),m=t.get("currentUrl"),u=t.get("entityName"),h=t.get("entityType"),p=t.get("scenarioName"),f=t.get("errorMessage"),y=t.get("screenshot");let g=s||void 0;!g&&u&&(p?g=`Issue on ${u} scenario "${p}"`:g=`Issue on ${u}`);let x;if(y&&y.size>0){const k=await y.arrayBuffer();x=Buffer.from(k),console.log(`[Bundle] Screenshot received: ${y.size} bytes`)}const v=he();if(!v)return K({error:"Project root not found"},{status:500});const b=await $e();if(!b)return K({error:"Project slug not found"},{status:500});const N={issueType:r||"other",description:g,email:a||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:c||void 0,analysisId:d||void 0,currentUrl:m||void 0,recentActivity:u0(b,20),entityName:u||void 0,entityType:h||void 0,scenarioName:p||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${b}...`),console.log(`[Bundle] Context: ${N.source}, issue: ${N.issueType}`);const w=await f0({projectRoot:v,projectSlug:b,feedback:N,screenshot:x,onProgress:k=>{console.log(`[Bundle] ${k}`)}}),S=(w.baseSize||0)+w.deltaSize;console.log(`[Bundle] Archives created: delta=${w.deltaSize} bytes${w.basePath?`, base=${w.baseSize} bytes`:" (base reused)"}`);const C=await g0({basePath:w.basePath,deltaPath:w.deltaPath,projectSlug:b,metadata:w.metadata,baseSha:w.baseSha,deltaSize:w.deltaSize,onProgress:k=>{console.log(`[Bundle] ${k}`)}});return console.log(`[Bundle] Upload complete: ${C.bundleId}`),K({success:!0,reportId:C.bundleId,size:S})}catch(t){return console.error("[Bundle] Error:",t),K({error:t.message||"Failed to generate bundle"},{status:500})}}function x0(){const e=he(),t=e?kl(e):null;return K({defaultEmail:t})}const b0=Object.freeze(Object.defineProperty({__proto__:null,action:y0,loader:x0},Symbol.toStringTag,{value:"Module"}));async function v0({request:e}){try{const r=new URL(e.url).searchParams.get("date"),s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=O.join(s,".codeyam","journal","index.json");let o={entries:[]};try{const c=await we.readFile(a,"utf8");o=JSON.parse(c)}catch{}let i=o.entries;return r&&(i=i.filter(c=>c.date===r)),new Response(JSON.stringify({entries:i}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const w0=Object.freeze(Object.defineProperty({__proto__:null,loader:v0},Symbol.toStringTag,{value:"Module"}));function El(e){if(!G.existsSync(e))return Ke.Unknown;try{const t=JSON.parse(G.readFileSync(e,"utf8")),r={...t.dependencies,...t.devDependencies};return r.next?Ke.Next:r["@remix-run/node"]||r["@remix-run/react"]||r["react-router"]?Ke.Remix:r["react-scripts"]?Ke.CRA:Ke.Unknown}catch{return Ke.Unknown}}function N0(e,t){let r=e;const s=O.resolve(t);for(;;){const a=O.resolve(r);if(G.existsSync(O.join(a,"pnpm-lock.yaml")))return"pnpm";if(G.existsSync(O.join(a,"yarn.lock")))return"yarn";if(G.existsSync(O.join(a,"package-lock.json")))return"npm";if(a===s)break;const o=O.dirname(a);if(o===a)break;r=o}throw new Error(`Could not detect package manager in ${e} or any parent directory up to ${t}`)}function C0(e){const t=/cd\s+([^\s;&|]+)\s*(?:&&|;)/,r=e.match(t);return r?r[1]:null}function S0(e){const t=O.join(e,"package.json");if(!G.existsSync(t))return{isWebApp:!1};if(El(t)===Ke.Unknown)return{isWebApp:!1};try{const a=JSON.parse(G.readFileSync(t,"utf8")).scripts||{},o=["remix","react-router","next dev","vite","react-scripts","webpack-dev-server","parcel"],c=Object.keys(a).filter(d=>["dev","start","serve","build"].some(m=>d.includes(m))).filter(d=>o.some(m=>a[d].includes(m)));if(c.length===0)return{isWebApp:!1};for(const d of c){const m=a[d],u=C0(m);if(u){const h=O.join(e,u);if(G.existsSync(h)&&G.statSync(h).isDirectory())return{isWebApp:!0,actualPath:h}}}return{isWebApp:!0}}catch{return{isWebApp:!1}}}function Al(e,t=e,r=0,s=3){if(r>s)return[];const a=[],o=S0(t);if(o.isWebApp){const c=o.actualPath||t,d=O.relative(e,c);return a.push(d||"."),a}const i=["node_modules",".git",".next","dist","build",".cache","coverage",".codeyam"];try{const c=G.readdirSync(t,{withFileTypes:!0});for(const d of c)if(d.isDirectory()&&!i.includes(d.name)){const m=O.join(t,d.name);a.push(...Al(e,m,r+1,s))}}catch{}return a}function k0(e){const t=Al(e);return t.length===0?[]:t.map(s=>{const a=O.join(e,s),o=O.join(a,"package.json"),i=El(o),c=N0(a,e);let d;if(i===Ke.Remix||i===Ke.Next){const h=O.join(a,"app");G.existsSync(h)&&G.statSync(h).isDirectory()&&(d="app")}const m=E0(s,e),u=m?{command:"sh",args:["-c",`${c} run ${m} -- --port $PORT`]}:void 0;return{path:s,framework:i,packageManager:c,appDirectory:d,startCommand:u}})}function E0(e,t){const r=O.join(t,e),s=O.join(r,"package.json");if(!G.existsSync(s))return null;try{const o=JSON.parse(G.readFileSync(s,"utf8")).scripts||{},i=["dev","start","serve"];for(const c of i)if(o[c])return c;return null}catch{return null}}async function A0({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=he()||process.cwd(),r=ee.join(t,".codeyam","config.json");let s=[];try{s=k0(t)}catch{}if(Ce.existsSync(r)){const i=JSON.parse(Ce.readFileSync(r,"utf8"));i.webapps=s,Ce.writeFileSync(r,JSON.stringify(i,null,2))}const a=await $e();if(a)try{await hn({projectSlug:a,metadataUpdate:{webapps:s}})}catch{}let o=!1;if(s.length>0)try{const i=process.env.CODEYAM_PORT||"3111",d=await(await fetch(`http://localhost:${i}/api/editor-dev-server`)).json();(d.status==="stopped"||d.status===void 0)&&(await fetch(`http://localhost:${i}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}),o=!0)}catch{}return new Response(JSON.stringify({success:!0,webapps:s,devServerStarted:o,message:`Detected ${s.length} webapp(s)`}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const P0=Object.freeze(Object.defineProperty({__proto__:null,action:A0},Symbol.toStringTag,{value:"Module"}));function Kt(){const e=process.memoryUsage(),t=od.getHeapStatistics();return{process:{rss:Math.round(e.rss/1024/1024),heapTotal:Math.round(e.heapTotal/1024/1024),heapUsed:Math.round(e.heapUsed/1024/1024),external:Math.round(e.external/1024/1024),arrayBuffers:Math.round(e.arrayBuffers/1024/1024)},heap:{totalHeapSize:Math.round(t.total_heap_size/1024/1024),totalHeapSizeExecutable:Math.round(t.total_heap_size_executable/1024/1024),totalPhysicalSize:Math.round(t.total_physical_size/1024/1024),totalAvailableSize:Math.round(t.total_available_size/1024/1024),usedHeapSize:Math.round(t.used_heap_size/1024/1024),heapSizeLimit:Math.round(t.heap_size_limit/1024/1024),mallocedMemory:Math.round(t.malloced_memory/1024/1024),peakMallocedMemory:Math.round(t.peak_malloced_memory/1024/1024)},system:{totalMemory:Math.round(Os.totalmem()/1024/1024),freeMemory:Math.round(Os.freemem()/1024/1024)}}}function _0(){const e=Kt();console.log(`
|
|
271
|
+
[Memory Profiler] Detailed Statistics:`),console.log(" Process Memory:"),console.log(` RSS: ${e.process.rss} MB (total memory used by process)`),console.log(` Heap Used: ${e.process.heapUsed} MB / ${e.process.heapTotal} MB`),console.log(` External: ${e.process.external} MB (C++ objects)`),console.log(` ArrayBuffers: ${e.process.arrayBuffers} MB`),console.log(" V8 Heap:"),console.log(` Used: ${e.heap.usedHeapSize} MB / ${e.heap.totalHeapSize} MB`),console.log(` Physical: ${e.heap.totalPhysicalSize} MB`),console.log(` Limit: ${e.heap.heapSizeLimit} MB`),console.log(` Malloced: ${e.heap.mallocedMemory} MB (peak: ${e.heap.peakMallocedMemory} MB)`),console.log(" System:"),console.log(` Total: ${e.system.totalMemory} MB`),console.log(` Free: ${e.system.freeMemory} MB`);const t=(e.heap.usedHeapSize/e.heap.heapSizeLimit*100).toFixed(1);return console.log(` Heap Usage: ${t}% of limit`),e}function j0(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=Kt();global.gc();const t=Kt(),r=e.process.heapUsed-t.process.heapUsed;return console.log(`[Memory Profiler] GC freed ${r} MB`),console.log(`[Memory Profiler] Heap: ${t.process.heapUsed} MB (was ${e.process.heapUsed} MB)`),!0}else return console.log("[Memory Profiler] GC not available. Start Node with --expose-gc to enable."),!1}function M0(){const e=Kt(),t=e.heap.usedHeapSize/e.heap.heapSizeLimit*100,r={highHeapUsage:t>80,highExternalMemory:e.process.external>200,highArrayBuffers:e.process.arrayBuffers>100,nearHeapLimit:e.heap.totalAvailableSize<100},s=[];return r.highHeapUsage&&s.push(`High heap usage: ${t.toFixed(1)}% of limit`),r.highExternalMemory&&s.push(`High external memory: ${e.process.external} MB`),r.highArrayBuffers&&s.push(`High ArrayBuffer usage: ${e.process.arrayBuffers} MB`),r.nearHeapLimit&&s.push(`Near heap limit: only ${e.heap.totalAvailableSize} MB available`),{indicators:r,warnings:s,hasIssues:s.length>0}}function T0({request:e}){const r=new URL(e.url).searchParams.get("action");try{switch(r){case"snapshot":return Response.json({success:!1,error:"Heap snapshots are disabled because they block the server for several minutes. Use action=leaks instead."},{status:400});case"gc":{const s=j0(),a=Kt();return Response.json({success:s,message:s?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:a})}case"detailed":{const s=_0();return Response.json({success:!0,stats:s})}case"leaks":{const s=M0(),a=Kt();return Response.json({success:!0,leakCheck:s,stats:a})}default:{const s=Kt();return Response.json({success:!0,stats:s,actions:{gc:"/api/memory-profile?action=gc - Force garbage collection (requires --expose-gc)",detailed:"/api/memory-profile?action=detailed - Log detailed stats to console",leaks:"/api/memory-profile?action=leaks - Check for memory leak indicators"}})}}}catch(s){return console.error("[Memory API] Error:",s),Response.json({success:!1,error:s.message},{status:500})}}const $0=Object.freeze(Object.defineProperty({__proto__:null,loader:T0},Symbol.toStringTag,{value:"Module"})),ir=aa(sa);async function R0({request:e}){const r=new URL(e.url).searchParams.get("pids");if(!r)return Response.json({error:"Missing pids parameter"},{status:400});const s=r.split(",").map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o));if(s.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const a=await Promise.all(s.map(async o=>{const i=I0(o),c=i?await D0(o):null;return{pid:o,isRunning:i,processName:c}}));return Response.json({processes:a})}function I0(e){try{return process.kill(e,0),!0}catch{return!1}}async function D0(e){if(process.platform==="win32")try{const{stdout:r}=await ir(`tasklist /FI "PID eq ${e}" /FO CSV /NH`),s=r.match(/"([^"]+)"/);if(!s)return null;const a=s[1];if(a.toLowerCase()==="node.exe")try{const{stdout:o}=await ir(`wmic process where "ProcessId=${e}" get CommandLine /FORMAT:LIST`),i=o.match(/codeyam-(\w+)/);if(i)return`codeyam-${i[1]}`}catch{}return a}catch{return null}try{const{stdout:r}=await ir(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:s}=await ir(`ps -p ${e} -o args=`),a=s.trim(),o=a.match(/codeyam-(\w+)/);return o?`codeyam-${o[1]}`:a.split(" ")[0]||null}catch{return null}}}const L0=Object.freeze(Object.defineProperty({__proto__:null,loader:R0},Symbol.toStringTag,{value:"Module"})),O0=Ir(import.meta.url),F0=O.dirname(O0);function z0({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ui(),r=he()||(t==null?void 0:t.projectRoot);if(!r)throw new Error("Could not determine project root");const s=(t==null?void 0:t.port)||3111,a=O.join(F0,"..","..","..","..","webserver","bootstrap.js"),o=O.join(r,".codeyam","logs");G.existsSync(o)||G.mkdirSync(o,{recursive:!0});const i=G.openSync(O.join(o,"background-server.log"),"a"),c=G.openSync(O.join(o,"background-server-error.log"),"a"),d=new Date().toISOString();G.appendFileSync(O.join(o,"background-server.log"),`
|
|
272
|
+
[${d}] Server restart requested via dashboard
|
|
273
|
+
`),um();const m=kt("node",[a],{detached:!0,stdio:["ignore",i,c],env:{...process.env,CODEYAM_PORT:s.toString(),CODEYAM_ROOT_PATH:r,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});m.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${m.pid})`);const u=new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}});return setTimeout(()=>{console.log("[api.restart-server] Exiting old server process"),process.exit(0)},100),u}catch(t){return console.error("[api.restart-server] Error restarting server:",t),new Response(JSON.stringify({success:!1,error:t instanceof Error?t.message:"Unknown error"}),{status:500,headers:{"Content-Type":"application/json"}})}}const B0=Object.freeze(Object.defineProperty({__proto__:null,action:z0},Symbol.toStringTag,{value:"Module"}));async function Y0({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:s}=t;if(!r||!s)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${r.id}`),console.log(`[API] Received ${s.length} scenarios to save`),s.forEach((c,d)=>{var h,p,f,y,g;const m=(p=(h=c.metadata)==null?void 0:h.data)==null?void 0:p.argumentsData,u=Array.isArray(m)&&m.length>0?JSON.stringify(m[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(m)?m.length:"not-array",argumentsDataPreview:u})});const a=s.map(c=>({...c,projectId:c.projectId||r.projectId,analysisId:c.analysisId||r.id})),o=await vu(a);if(!o||o.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${o.length} scenarios to database`),o.forEach((c,d)=>{var u,h;const m=(h=(u=c.metadata)==null?void 0:u.data)==null?void 0:h.argumentsData;console.log(`[API] Saved scenario ${d}: ${c.name}`,{id:c.id,argumentsDataLength:Array.isArray(m)?m.length:"not-array"})});const i={...r,scenarios:o};return Response.json({success:!0,analysis:i})}catch(t){return console.error("[API] Error saving scenarios:",t),Response.json({error:"Failed to save scenarios",details:t instanceof Error?t.message:String(t)},{status:500})}}const U0=Object.freeze(Object.defineProperty({__proto__:null,action:Y0},Symbol.toStringTag,{value:"Module"})),W0=()=>[{title:"Agent Transcripts - CodeYam"},{name:"description",content:"View background agent transcripts and tool call history"}];async function J0({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("search")||"",s=t.searchParams.get("page")||"1",a=new URLSearchParams;r&&a.set("search",r),s!=="1"&&a.set("page",s);const o=a.toString(),i=new URL(`/api/agent-transcripts${o?`?${o}`:""}`,e.url),d=await(await fetch(i.toString())).json();if(d.error)return K({agents:[],error:d.error,search:r,page:1,totalPages:1});const m=d.total??(d.agents||[]).length,u=d.pageSize??20;return K({agents:d.agents||[],error:null,search:r,page:d.page??parseInt(s,10),totalPages:Math.max(1,Math.ceil(m/u))})}catch(t){return console.error("Failed to load agent transcripts:",t),K({agents:[],error:"Failed to load agent transcripts",search:"",page:1,totalPages:1})}}function H0(e){if(!e)return"";try{return new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}catch{return e}}function V0(e){if(!e)return"";try{return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}catch{return e}}function q0(e){return e.includes("opus")?"Opus":e.includes("sonnet")?"Sonnet":e.includes("haiku")?"Haiku":e}function fr({type:e,toolName:t}){const r={user_prompt:"bg-[#00b4d8] text-black",assistant_text:"bg-[#a8dadc] text-black",tool_call:"bg-[#f4a261] text-black",tool_result:"bg-[#2a9d8f] text-black",context:"bg-[#7c3aed] text-white"},s={user_prompt:"USER",assistant_text:"ASSISTANT",tool_call:t||"TOOL",tool_result:"RESULT",context:"CONTEXT"};return n("span",{className:`inline-block px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wide ${r[e]||"bg-gray-300 text-black"}`,children:s[e]||e})}function G0({input:e}){return n("div",{className:"text-xs font-mono space-y-1",children:Object.entries(e).map(([t,r])=>{let s=typeof r=="string"?r:JSON.stringify(r);return s.length>500&&(s=s.slice(0,500)+"..."),l("div",{children:[l("span",{className:"text-[#f4a261] font-bold",children:[t,":"]})," ",n("span",{className:"text-gray-700",children:s})]},t)})})}function K0({content:e,truncated:t,fullLength:r}){const[s,a]=_(!1);return l("div",{children:[l("pre",{className:"whitespace-pre-wrap break-words text-xs max-h-96 overflow-y-auto text-gray-700",children:[e,t&&!s&&"..."]}),t&&n("button",{onClick:()=>a(!s),className:"text-[11px] text-gray-500 hover:text-gray-700 mt-1 font-mono cursor-pointer",children:s?"Show less":`Show more (${(r||0)-e.length} more chars)`})]})}function Q0({entry:e,pairedResult:t}){const[r,s]=_(!1),a=H0(e.timestamp||"");return e.type==="user_prompt"?l("div",{className:"my-2",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(fr,{type:"user_prompt"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:a})]}),n("pre",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#00b4d8] max-h-72 overflow-y-auto text-gray-800",children:e.text})]}):e.type==="assistant_text"?l("div",{className:"my-2",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(fr,{type:"assistant_text"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:a})]}),n("div",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-sm border-l-[3px] border-l-[#a8dadc] text-gray-800",children:e.text})]}):e.type==="tool_call"?l("div",{className:"my-2",children:[l("button",{onClick:()=>s(!r),className:"flex items-center gap-2 w-full text-left bg-white border border-gray-200 rounded-md px-3 py-2 hover:bg-gray-50 cursor-pointer",children:[r?n(ct,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n(Ft,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n(fr,{type:"tool_call",toolName:e.name}),n("span",{className:"text-xs text-gray-500 font-mono truncate flex-1",children:e.summary||""}),n("span",{className:"text-[11px] text-gray-400 font-mono flex-shrink-0",children:a})]}),r&&l("div",{className:"bg-white border border-t-0 border-gray-200 rounded-b-md px-3 py-2 border-l-[3px] border-l-[#f4a261]",children:[n(G0,{input:e.input||{}}),t&&l("div",{className:"mt-3 pt-3 border-t border-gray-200",children:[l("div",{className:"text-[11px] font-bold uppercase tracking-wide text-[#2a9d8f] mb-1",children:["Result",t.is_error?" (Error)":"",":"]}),n(K0,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function Z0({context:e}){const[t,r]=_(!1);return l("div",{className:"my-2",children:[l("button",{onClick:()=>r(!t),className:"flex items-center gap-2 mb-1 cursor-pointer hover:opacity-80",children:[t?n(ct,{className:"w-3 h-3 text-gray-400"}):n(Ft,{className:"w-3 h-3 text-gray-400"}),n(fr,{type:"context"}),n("span",{className:"text-xs text-gray-500",children:"Full prompt context"})]}),t&&n("pre",{className:"bg-gray-50 border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#7c3aed] max-h-96 overflow-y-auto text-gray-700",children:e})]})}function X0({snippet:e}){const[t,r]=_(!1),s=e.split(`
|
|
274
|
+
`).filter(c=>c.trim()),a=s.slice(0,4),o=s.length>4,i=t?s:a;return l("div",{className:"my-2 bg-blue-50 border border-blue-200 rounded-md p-3",children:[l("div",{className:"flex items-center gap-2 mb-2",children:[n(kc,{className:"w-3.5 h-3.5 text-blue-600"}),n("span",{className:"text-xs font-bold text-blue-800",children:"Source Conversation"}),l("span",{className:"text-[10px] text-blue-500",children:[s.length," message",s.length!==1?"s":""]})]}),n("div",{className:"space-y-1",children:i.map((c,d)=>{const m=c.match(/^\[(\w+)\]:\s*(.*)/);if(!m)return null;const[,u,h]=m,p=u==="user";return l("div",{className:"text-xs",children:[l("span",{className:`font-bold ${p?"text-blue-700":"text-gray-500"}`,children:[p?"User":"Assistant",":"]})," ",n("span",{className:"text-gray-700",children:h.length>200?h.slice(0,200)+"...":h})]},d)})}),o&&n("button",{onClick:()=>r(!t),className:"text-[11px] text-blue-600 hover:text-blue-800 mt-2 font-mono cursor-pointer",children:t?"Show less":`Show all ${s.length} messages`})]})}function ey({change:e}){const[t,r]=_(!1),s=e.action==="created"?!!e.content:e.action==="modified"?!!(e.oldString||e.newString):!1;return l("li",{children:[n("button",{onClick:()=>s&&r(!t),className:`text-left w-full ${s?"hover:text-green-900 cursor-pointer":""}`,children:l("span",{className:"inline-flex items-center gap-1",children:[s&&(t?n(ct,{className:"w-3 h-3 inline flex-shrink-0"}):n(Ft,{className:"w-3 h-3 inline flex-shrink-0"})),e.action==="created"?"Created":"Modified"," ",e.filePath]})}),t&&e.action==="created"&&e.content&&n("pre",{className:"mt-1 mb-2 ml-4 p-2 bg-white border border-green-200 rounded text-[11px] text-gray-700 whitespace-pre-wrap break-words max-h-64 overflow-y-auto",children:e.content}),t&&e.action==="modified"&&l("div",{className:"mt-1 mb-2 ml-4 space-y-1",children:[e.oldString&&l("pre",{className:"p-2 bg-red-50 border border-red-200 rounded text-[11px] text-red-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["- ",e.oldString]}),e.newString&&l("pre",{className:"p-2 bg-green-50 border border-green-300 rounded text-[11px] text-green-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["+ ",e.newString]})]})]})}function ty({changes:e}){const t=e.filter(i=>i.action==="touched"),r=e.filter(i=>i.action!=="touched"),s=r.some(i=>i.action==="created"),a=r.some(i=>i.action==="modified");return l("div",{className:`my-2 border rounded-md p-3 ${s?"bg-green-50 border-green-200 text-green-800 [&_ul]:text-green-700":a?"bg-amber-50 border-amber-200 text-amber-800 [&_ul]:text-amber-700":"bg-gray-50 border-gray-200 text-gray-600 [&_ul]:text-gray-500"}`,children:[n("div",{className:"text-xs font-bold mb-1",children:"Rule Changes:"}),l("ul",{className:"text-xs space-y-0.5 font-mono",children:[r.map((i,c)=>n(ey,{change:i},c)),t.length>0&&l("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function ny({result:e}){const t=e.is_error,r=t?"bg-red-50 border-red-200":"bg-green-50 border-green-200",s=t?"text-red-800":"text-green-800",a=t?"text-red-700":"text-green-700",o=e.subtype.replace(/^error_/,"").replace(/_/g," "),i=d=>d>=6e4?`${(d/6e4).toFixed(1)}m`:`${(d/1e3).toFixed(1)}s`,c=d=>d>=1e3?`${(d/1e3).toFixed(1)}k`:String(d);return l("div",{className:`my-2 border rounded-md p-3 ${r}`,children:[l("div",{className:`text-xs font-bold mb-1 ${s}`,children:["Session Result: ",o]}),l("div",{className:`text-xs ${a} font-mono space-y-0.5`,children:[l("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5",children:[e.duration_ms!=null&&l("span",{children:["Duration: ",i(e.duration_ms)]}),e.duration_api_ms!=null&&l("span",{children:["API time: ",i(e.duration_api_ms)]}),e.num_turns!=null&&l("span",{children:["Turns: ",e.num_turns]}),e.total_cost_usd!=null&&l("span",{children:["Cost: $",e.total_cost_usd.toFixed(4)]})]}),e.usage&&l("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5 mt-1",children:[e.usage.input_tokens!=null&&l("span",{children:["Input: ",c(e.usage.input_tokens)]}),e.usage.output_tokens!=null&&l("span",{children:["Output: ",c(e.usage.output_tokens)]}),e.usage.cache_read_input_tokens!=null&&l("span",{children:["Cache read: ",c(e.usage.cache_read_input_tokens)]}),e.usage.cache_creation_input_tokens!=null&&l("span",{children:["Cache write:"," ",c(e.usage.cache_creation_input_tokens)]})]}),e.errors&&e.errors.length>0&&n("div",{className:"mt-1",children:e.errors.map((d,m)=>n("div",{className:"text-red-700 break-words",children:d},m))})]})]})}function ry({agent:e,defaultOpen:t,isAdmin:r}){var S,C,k;const[s,a]=_(t),[o,i]=_(!1),[c,d]=_(null),[m,u]=_(!1),h=ne(()=>{const E={};for(const A of e.entries)A.type==="tool_result"&&A.tool_use_id&&(E[A.tool_use_id]=A);return E},[e.entries]),p=ne(()=>{const E=new Set;for(const A of e.entries)A.type==="tool_call"&&A.tool_use_id&&h[A.tool_use_id]&&E.add(A.tool_use_id);return E},[e.entries,h]),f=E=>{E.stopPropagation(),i(!0),d(null),fetch("/api/save-fixture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e.id})}).then(A=>A.json()).then(A=>{A.success?d(`Saved to ${A.fixturePath}`):d(`Error: ${A.error}`)}).catch(A=>{d(`Error: ${A instanceof Error?A.message:String(A)}`)}).finally(()=>{i(!1)})},y=(e.ruleChanges||[]).filter(E=>E.action!=="touched"),g=y.filter(E=>E.action==="created"),x=y.filter(E=>E.action==="modified"),v=(e.ruleChanges||[]).filter(E=>E.action==="touched"),b=y.length>0,N=v.length>0,w=b||N;return l("div",{className:`bg-white border rounded-lg overflow-hidden mb-4 ${e.stats.errors>0?"border-red-300":g.length>0?"border-green-300":x.length>0?"border-amber-300":"border-gray-200"}`,children:[l("button",{onClick:()=>a(!s),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:[s?n(ct,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n(Ft,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm font-bold text-[#005C75] font-mono",children:e.id.slice(0,8)}),e.slug&&n("span",{className:"text-xs text-gray-500",children:e.slug}),e.model&&n("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold bg-purple-100 text-purple-700",title:e.model,children:q0(e.model)}),g.length>0&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-green-100 text-green-800",children:[n(yr,{className:"w-3 h-3"}),g.length," rule",g.length!==1?"s":""," ","created"]}),x.length>0&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-100 text-amber-800",children:[n(yr,{className:"w-3 h-3"}),x.length," rule",x.length!==1?"s":""," ","modified"]}),!b&&N&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-gray-100 text-gray-500",children:[v.length," timestamp",v.length!==1?"s":""," ","touched"]}),e.stats.errors>0&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-red-100 text-red-800",children:[n(gr,{className:"w-3 h-3 flex-shrink-0"}),e.stats.errors," ",e.stats.errors===1?"Error":"Errors"]}),l("span",{className:"text-[11px] text-gray-400 font-mono",children:[e.stats.toolCalls," tool calls, ",e.stats.textBlocks," text blocks",((S=e.sessionResult)==null?void 0:S.duration_ms)!=null&&l(ue,{children:[" · ",e.sessionResult.duration_ms>=6e4?`${(e.sessionResult.duration_ms/6e4).toFixed(1)}m`:`${(e.sessionResult.duration_ms/1e3).toFixed(1)}s`]}),((C=e.sessionResult)==null?void 0:C.total_cost_usd)!=null&&l(ue,{children:[" · ","$",e.sessionResult.total_cost_usd.toFixed(2)]})]}),l("span",{className:"text-[11px] text-gray-400 font-mono ml-auto flex items-center gap-2",children:[V0(e.timestamp),r&&b&&l("button",{onClick:f,disabled:o,className:"inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] font-bold bg-gray-100 text-gray-600 hover:bg-gray-200 disabled:opacity-50 cursor-pointer",title:"Save as test fixture",children:[n(Sc,{className:"w-3 h-3"}),o?"Saving...":"Save Fixture"]})]})]}),c&&n("div",{className:`px-4 py-2 text-xs font-mono ${c.startsWith("Error")?"bg-red-50 text-red-700":"bg-green-50 text-green-700"}`,children:c}),s&&l("div",{className:"px-4 pb-4 border-t border-gray-100",children:[e.sourceFile&&l("div",{className:"flex items-center gap-2 py-2 text-xs text-gray-500 font-mono",children:[n("span",{className:"text-gray-400",children:"FILE:"}),n("span",{className:"truncate",children:e.sourceFile}),n("button",{onClick:E=>{E.stopPropagation(),navigator.clipboard.writeText(e.sourceFile),u(!0),setTimeout(()=>u(!1),2e3)},className:"p-0.5 rounded text-gray-400 hover:text-gray-600 cursor-pointer transition-colors flex-shrink-0",title:"Copy file path",children:m?n(gt,{className:"w-3.5 h-3.5 text-green-500"}):n(Nt,{className:"w-3.5 h-3.5"})})]}),e.sessionResult&&n(ny,{result:e.sessionResult}),e.stats.errors>0&&((k=e.stats.errorMessages)==null?void 0:k.length)>0&&l("div",{className:"my-2 bg-red-50 border border-red-200 rounded-md p-3",children:[l("div",{className:"text-xs font-bold text-red-800 mb-1",children:[e.stats.errors," Error",e.stats.errors!==1?"s":"",":"]}),n("ul",{className:"text-xs text-red-700 space-y-1 font-mono",children:e.stats.errorMessages.map((E,A)=>n("li",{className:"break-words",children:E},A))})]}),e.conversationSnippet&&n(X0,{snippet:e.conversationSnippet}),w&&n(ty,{changes:e.ruleChanges}),e.context&&n(Z0,{context:e.context}),e.entries.map((E,A)=>{if(E.type==="tool_result"&&E.tool_use_id&&p.has(E.tool_use_id))return null;const I=E.type==="tool_call"&&E.tool_use_id?h[E.tool_use_id]:void 0;return n(Q0,{entry:E,pairedResult:I},`${e.id}-${A}`)})]})]})}function js(e,t){const r=new URLSearchParams;t&&r.set("search",t),e>1&&r.set("page",String(e));const s=r.toString();return`/agent-transcripts${s?`?${s}`:""}`}const sy=Je(function(){const{agents:t,error:r,search:s,page:a,totalPages:o}=Ve(),i=St(),c=rc("root"),d=(c==null?void 0:c.isAdmin)??!1,[m,u]=_(s),[h,p]=_(!1),[f,y]=_(0);yt({source:"agent-transcripts-page"});const g=v=>{v.preventDefault(),window.location.href=js(1,m)},x=()=>{p(!h),y(v=>v+1)};return r?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:r})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[l("div",{className:"flex items-center gap-3 mb-1",children:[n("button",{onClick:()=>{i("/memory")},className:"text-gray-600 hover:text-[#005C75] transition-colors cursor-pointer",title:"Back to Memory","aria-label":"Back to Memory",children:n(Nc,{className:"w-5 h-5"})}),n(xr,{className:"w-6 h-6 text-[#232323]"}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Agent Transcripts"})]}),n("p",{className:"text-[15px] text-gray-500 ml-14",children:"View background agent transcripts and tool call history"})]}),l("div",{className:"flex items-center gap-4 mb-6",children:[l("form",{onSubmit:g,className:"relative flex-1 max-w-md",children:[n(Fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:m,onChange:v=>u(v.target.value),placeholder:"Search transcripts...",className:"w-full pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),n("button",{onClick:x,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:h?"Collapse All":"Expand All"})]}),l("div",{className:"text-sm text-gray-500 mb-4",children:["Page ",a," of ",o,s&&l("span",{children:[" ","matching “",s,"”",n(de,{to:"/agent-transcripts",className:"text-[#005C75] hover:underline ml-2",children:"Clear"})]})]}),t.length===0?l("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(xr,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Agent Transcripts Found"}),n("p",{className:"text-gray-500",children:"Background agent output files will appear here when available."})]}):n("div",{children:t.map(v=>n(ry,{agent:v,defaultOpen:h,isAdmin:d},v.id))},f),o>1&&l("div",{className:"flex items-center justify-center gap-3 mt-8",children:[l("a",{href:a>1?js(a-1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${a>1?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:[n(Cc,{className:"w-4 h-4"}),"Prev"]}),l("span",{className:"text-sm text-gray-500 font-mono",children:[a," / ",o]}),l("a",{href:a<o?js(a+1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${a<o?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:["Next",n(Ft,{className:"w-4 h-4"})]})]})]})})}),ay=Object.freeze(Object.defineProperty({__proto__:null,default:sy,loader:J0,meta:W0},Symbol.toStringTag,{value:"Module"}));async function oy({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{message:r}=t;if(!r)return new Response(JSON.stringify({error:"message is required"}),{status:400,headers:{"Content-Type":"application/json"}});const s=process.env.CODEYAM_ROOT_PATH||process.cwd();console.log(`[editor-commit] Committing with message: "${r}" in ${s}`);const a=cg(s);a&&console.log("[editor-commit] Initialized new git repository"),dg(s),console.log("[editor-commit] Staged all changes");const o=ug(s,r);console.log(`[editor-commit] Created commit: ${o}`);try{const{broadcastHideResults:i}=await Promise.resolve().then(()=>op);i()}catch{}return new Response(JSON.stringify({success:!0,commitSha:o,initialized:a}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-commit] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const iy=Object.freeze(Object.defineProperty({__proto__:null,action:oy},Symbol.toStringTag,{value:"Module"})),ly=["JSX","React","Element","ReactNode"];function cy(e){return e.returnType?ly.some(t=>e.returnType.includes(t)):!1}function dy(e){const t=[],r=[];for(const s of e)cy(s)?t.push(s):r.push(s);return{components:t,functions:r}}function uy({components:e,functions:t,scenarioCounts:r,testFileExistence:s,testResults:a}){const o=e.map(f=>{const y=r[f.name]||0;return{name:f.name,filePath:f.filePath,scenarioCount:y,status:y>0?"ok":"missing"}}),i=t.map(f=>{if(!(f.testFile?s[f.testFile]??!1:!1))return{name:f.name,filePath:f.filePath,testFile:f.testFile,testFileExists:!1,status:"missing"};const g=f.testFile&&a?a[f.testFile]:void 0;if(!g)return{name:f.name,filePath:f.filePath,testFile:f.testFile,testFileExists:!0,status:"ok"};let x;return g.passing?g.hasEntityNameDescribe?x="ok":x="name_mismatch":x="failing",{name:f.name,filePath:f.filePath,testFile:f.testFile,testFileExists:!0,testsPassing:g.passing,testsVisibleInUi:g.hasEntityNameDescribe,status:x}}),c=o.filter(f=>f.status==="ok").length,d=o.length-c,m=i.filter(f=>f.status==="ok").length,u=i.filter(f=>f.status==="failing").length,h=i.filter(f=>f.status==="name_mismatch").length,p=i.filter(f=>f.status==="missing").length;return{components:o,functions:i,summary:{totalComponents:o.length,componentsOk:c,componentsMissing:d,totalFunctions:i.length,functionsOk:m,functionsMissing:p,functionsFailing:u,functionsNameMismatch:h,allPassing:d===0&&u===0&&h===0&&p===0}}}async function my(){const e=he()||process.cwd(),t=O.join(e,".codeyam","glossary.json");let r;try{const p=G.readFileSync(t,"utf8");r=JSON.parse(p),Array.isArray(r)||(r=[])}catch{return Response.json({components:[],functions:[],summary:{totalComponents:0,componentsOk:0,componentsMissing:0,totalFunctions:0,functionsOk:0,functionsMissing:0,functionsFailing:0,functionsNameMismatch:0,allPassing:!0}})}if(r.length===0)return Response.json({components:[],functions:[],summary:{totalComponents:0,componentsOk:0,componentsMissing:0,totalFunctions:0,functionsOk:0,functionsMissing:0,functionsFailing:0,functionsNameMismatch:0,allPassing:!0}});const s=O.join(e,".codeyam","editor-step.json");let a=null;try{const p=G.readFileSync(s,"utf8");a=JSON.parse(p).featureStartedAt||null}catch{}const{components:o,functions:i}=dy(r),c={},d=await $e();if(d)try{const{project:p}=await Ie(d),f=Te();let y=f.selectFrom("editor_scenarios").select(["component_name"]).select(f.fn.count("id").as("count")).where("project_id","=",p.id).where("component_name","is not",null).groupBy("component_name");if(a){const x=a.replace("T"," ").replace(/\.\d{3}Z$/,"");y=y.where("created_at",">=",x)}const g=await y.execute();for(const x of g)x.component_name&&(c[x.component_name]=Number(x.count))}catch{}const m={};for(const p of i)p.testFile&&(m[p.testFile]=G.existsSync(O.join(e,p.testFile)));const u={};for(const p of i)if(!(!p.testFile||!m[p.testFile]))try{const f=await bl(e,p.testFile),y=f.status==="passed",g=f.testCases.some(x=>x.fullName.startsWith(p.name));u[p.testFile]={passing:y,hasEntityNameDescribe:g}}catch{u[p.testFile]={passing:!1,hasEntityNameDescribe:!1}}const h=uy({components:o,functions:i,scenarioCounts:c,testFileExistence:m,testResults:u});return Response.json(h)}const hy=Object.freeze(Object.defineProperty({__proto__:null,loader:my},Symbol.toStringTag,{value:"Module"}));async function py({request:e}){try{const t=await e.json(),{pid:r,signal:s="SIGTERM",commitSha:a}=t;if(!r||typeof r!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!Ao(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,s)}catch(u){return Response.json({error:"Failed to kill process",pid:r,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,c=500,d=Date.now();let m=!0;for(;m&&Date.now()-d<i;)await new Promise(u=>setTimeout(u,c)),m=Ao(r);if(m){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${r}:`,u)}}if(a)try{await It({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(u){console.error("Failed to update database after killing process:",u)}return Response.json({success:!0,pid:r,signal:s,message:`Process ${r} killed successfully`,waitedMs:Date.now()-d})}catch(t){return console.error("Error in kill-process API:",t),Response.json({error:"Internal server error",details:t instanceof Error?t.message:String(t)},{status:500})}}function Ao(e){try{return process.kill(e,0),!0}catch{return!1}}const fy=Object.freeze(Object.defineProperty({__proto__:null,action:py},Symbol.toStringTag,{value:"Module"})),gy=Ir(import.meta.url),yy=ee.dirname(gy),xy=ee.resolve(yy,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function by(e){const t=[],r=new Set;for(const s of e.split(`
|
|
275
|
+
`)){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}if(o.type!=="assistant")continue;const i=o.message;if(!(!i||!Array.isArray(i.content)))for(const c of i.content){if(typeof c!="object"||c===null)continue;const d=c;if(d.type!=="tool_use")continue;const m=String(d.name||""),u=d.input||{};if(m==="Write"||m==="Edit"){const h=String(u.file_path||"");if(h.includes(".claude/rules/")){const p=h.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${m}:${p}`;r.has(f)||(r.add(f),t.push({action:m==="Write"?"created":"modified",filePath:p}))}}else if(m==="Bash"){const h=String(u.command||"");if(h.includes("codeyam memory touch")){const p=`touch:${h}`;r.has(p)||(r.add(p),t.push({action:"touched",filePath:h}))}}}}return t}async function vy({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{sessionId:r}=t;if(!r)return Response.json({error:"Missing required field: sessionId"},{status:400});const s=await wl(),a=s?ee.join(hr,s):null;let o=a?ee.join(a,`${r}.log`):"";if((!o||!Rt(o))&&(o=ee.join(hr,`${r}.log`)),!Rt(o))return Response.json({error:`Log file not found: ${r}.log`},{status:404});const i=await Ls(o,"utf-8");let c=a?ee.join(a,`${r}.context`):"";(!c||!Rt(c))&&(c=ee.join(hr,`${r}.context`));let d=null;if(Rt(c))try{d=await Ls(c,"utf-8")}catch{}const m=by(i),h=d?["no,","no ","that's not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","shouldn't","try again","that broke","that failed","error","bug"].some(x=>d.toLowerCase().includes(x)):!1,p=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":r.endsWith("-interruption")?"-int":"",f=r.slice(0,8)+p,y=ee.join(xy,f);await Vc(y,{recursive:!0}),await jn(ee.join(y,"agent-log.jsonl"),i),d&&await jn(ee.join(y,"context.md"),d),await jn(ee.join(y,"rule-changes.json"),JSON.stringify(m,null,2)),await jn(ee.join(y,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:h,ruleChangeCount:m.length},null,2));const g=ee.relative(process.cwd(),y);return console.log(`[api.save-fixture] Saved fixture to ${g}`),Response.json({success:!0,fixturePath:g})}catch(t){return console.error("[api.save-fixture] Error:",t),Response.json({error:"Failed to save fixture",details:t instanceof Error?t.message:String(t)},{status:500})}}const wy=Object.freeze(Object.defineProperty({__proto__:null,action:vy},Symbol.toStringTag,{value:"Module"}));async function Ny({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=he();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const s=ee.join(r,".codeyam","captures","screenshots",t);try{await xe.access(s);const a=await xe.readFile(s),o=ee.extname(s).toLowerCase(),i=o===".png"?"image/png":o===".jpg"||o===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(a,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const Cy=Object.freeze(Object.defineProperty({__proto__:null,loader:Ny},Symbol.toStringTag,{value:"Module"})),Po={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 wa({type:e,className:t=""}){const r=Po[e]||Po.other;return n("div",{className:`inline-flex items-center justify-center px-[4px] rounded-[4px] ${t}`,style:{backgroundColor:r.bgColor,color:r.textColor,height:"15px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-semibold leading-[15px] uppercase",children:r.label})})}const Sy={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 lr({variant:e,pid:t,label:r,className:s=""}){const a=Sy[e],o=r||(e==="analyzer"&&t?`Analyzer: ${t}`:e==="capture"&&t?`Capture: ${t}`:e==="running"?"Running":e==="error"?"Error":"");return n("div",{className:`inline-flex items-center justify-center px-[8px] rounded-[4px] ${s}`,style:{backgroundColor:a.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:a.borderColor,height:"20px"},children:n("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:a.textColor},children:o})})}let _o=!1;function ky(){if(_o)return;const e=document.createElement("style");e.textContent=`
|
|
276
|
+
@keyframes strongPulse {
|
|
277
|
+
0%, 100% { opacity: 0.2; }
|
|
278
|
+
50% { opacity: 1; }
|
|
279
|
+
}
|
|
280
|
+
`,document.head.appendChild(e),_o=!0}function Na({size:e="medium",className:t=""}){typeof document<"u"&&ky();const r={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:s,centerDotSize:a,gap:o}=r[e];return l("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${o}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}const Ey=()=>[{title:"Activity - CodeYam"},{name:"description",content:"View analysis activity and queue status"}];async function Ay({request:e,context:t,params:r}){var H,B,D,M,Q,U,F,X;let s=t.analysisQueue;s||(s=await jt());const a=new URL(e.url),o=parseInt(a.searchParams.get("page")||"1",10),i=20,c=r.tab||"current";if(!s)return K({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:c,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const d=s.getState(),m=await $e();let u=null;if(m&&((H=d==null?void 0:d.currentlyExecuting)!=null&&H.commitSha)){const{project:z,branch:L}=await Ie(m),W=await Cr({projectId:z.id,branchId:L.id,shas:[d.currentlyExecuting.commitSha]});u=W&&W.length>0?W[0]:null}else u=await yn();const h=async z=>{const L=await Xt(z);if(!L)return null;const{getAnalysesForEntity:W}=await Promise.resolve().then(()=>Lu),V=await W(z,!1);return{...L,analyses:V||[]}},p=await Promise.all(((d==null?void 0:d.jobs)||[]).map(async z=>{const L=[];if(z.entityShas&&z.entityShas.length>0){const W=z.entityShas.map(Z=>h(Z)),V=await Promise.all(W);L.push(...V.filter(Z=>Z!==null))}return{...z,entities:L}}));let f=null;if(d!=null&&d.currentlyExecuting){const z=d.currentlyExecuting,L=[];if(z.entityShas&&z.entityShas.length>0){const W=z.entityShas.map(Z=>h(Z)),V=await Promise.all(W);L.push(...V.filter(Z=>Z!==null))}f={...z,entities:L}}const y=f?p.filter(z=>z.id!==f.id):p,g=((D=(B=u==null?void 0:u.metadata)==null?void 0:B.currentRun)==null?void 0:D.currentEntityShas)||[],v=(await Promise.all(g.map(z=>h(z)))).filter(z=>z!==null),b=[];if(m)try{const{project:z,branch:L}=await Ie(m),W=await Cr({projectId:z.id,branchId:L.id,limit:100});for(const V of W){const Z=((M=V.metadata)==null?void 0:M.historicalRuns)||[];b.push(...Z)}}catch(z){console.error("[activity.tsx] Failed to load historical runs from commits:",z)}const N=[...b].sort((z,L)=>{const W=z.lastCaptureAt||z.analysisCompletedAt||z.archivedAt||z.createdAt||"";return(L.lastCaptureAt||L.analysisCompletedAt||L.archivedAt||L.createdAt||"").localeCompare(W)}),w=(o-1)*i,S=w+i,C=N.slice(w,S),k=Math.ceil(N.length/i),E=await Promise.all(C.map(async z=>{const L=z.currentEntityShas||[];if(L.length===0)return{...z,entities:[]};const W=await Promise.all(L.map(V=>h(V)));return{...z,entities:W.filter(V=>V!==null)}})),A=!!f,I=y.length,j=N.filter(z=>{const L=!!z.failedAt,W=z.readyToBeCaptured,V=z.capturesCompleted??0,Z=W===void 0?!0:W===0||V>=W;return!L&&!!z.analysisCompletedAt&&Z}),P=new Set(((Q=f==null?void 0:f.entities)==null?void 0:Q.map(z=>z.sha))||[]),$=j.filter(z=>!(z.currentEntityShas||[]).some(W=>P.has(W))),R=(await Promise.all($.slice(0,3).map(async z=>{const L=z.currentEntityShas||[];if(L.length===0)return{run:z,entities:[]};const W=await Promise.all(L.map(V=>h(V)));return{run:z,entities:W.filter(V=>V!==null)}}))).flatMap(({run:z,entities:L})=>L.map(W=>({...W,runId:z.id,completedAt:z.lastCaptureAt||z.analysisCompletedAt||z.archivedAt||z.createdAt})));let J=[],q=null,Y=null;if((F=(U=u==null?void 0:u.metadata)==null?void 0:U.currentRun)!=null&&F.analysisCompletedAt&&v.length>0){const z=v[0].sha;q=v[0];const L=await Br(z);L&&L.length>0&&L[0].scenarios&&(J=L[0].scenarios,Y=L[0].status)}return K({state:{...d,jobs:y,currentlyExecuting:f},currentRun:(X=u==null?void 0:u.metadata)==null?void 0:X.currentRun,historicalRuns:E,totalHistoricalRuns:N.length,currentPage:o,totalPages:k,projectSlug:m,commitSha:u==null?void 0:u.sha,queueJobs:y,currentlyExecuting:f,currentEntities:v,tab:c,hasCurrentActivity:A,queuedCount:I,recentCompletedEntities:R,hasMoreCompletedRuns:$.length>3,currentEntityScenarios:J,currentEntityForScenarios:q,currentAnalysisStatus:Y})}function Py({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:s}){const a=[{id:"current",label:"Current Activity",hasContent:t,count:t?1:null},{id:"queued",label:"Queued Activity",hasContent:r>0,count:r},{id:"historic",label:"Historic Activity",hasContent:s>0,count:s}];return n("div",{className:"border-b border-gray-200 mb-6",children:n("nav",{className:"flex gap-8",children:a.map(o=>{const i=e===o.id;return n(de,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
|
|
281
|
+
relative pb-4 px-2 text-sm transition-colors cursor-pointer
|
|
282
|
+
${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
|
|
283
|
+
`,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[o.label,o.count!==null&&o.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
|
|
284
|
+
inline-block w-2 h-2 rounded-full
|
|
285
|
+
${i?"":"bg-gray-400"}
|
|
286
|
+
`,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function _y({currentlyExecuting:e,currentRun:t,state:r,projectSlug:s,commitSha:a,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:c,currentEntityScenarios:d,currentEntityForScenarios:m,currentAnalysisStatus:u}){var T,R,J,q;const[h,p]=_({}),[f,y]=_({isKilling:!1,current:0,total:0}),g=ft(),x=!!e,v=(e==null?void 0:e.entities)||[],b=!!(t!=null&&t.analysisCompletedAt),N=b&&!!(t!=null&&t.capturePid),w=!b,S=x,C=d||[],{lastLine:k}=Et(s,S);te(()=>{if(!t)return;const Y=[t.analyzerPid,t.capturePid].filter(M=>!!M);if(Y.length===0)return;let H=!0;const B=async()=>{try{const Q=await(await fetch(`/api/process-status?pids=${Y.join(",")}`)).json();if(Q.processes&&H){const U={};Q.processes.forEach(F=>{U[F.pid]={isRunning:F.isRunning,processName:F.processName}}),p(U)}}catch(M){H&&console.error("Failed to fetch process statuses:",M)}};B();const D=setInterval(()=>void B(),5e3);return()=>{H=!1,clearInterval(D)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[E,A]=_(!1),[I,j]=_(!1);te(()=>{v.length<=3&&E&&A(!1)},[v.length,E]),te(()=>{i.length<=3&&I&&j(!1)},[i.length,I]);const P=E?v:v.slice(0,3),$=v.length>3;return l("div",{className:"flex flex-col gap-[45px]",children:[S?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:[n(ht,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:N?"Capturing...":"Analyzing..."})]}),P.map(Y=>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:[n("div",{children:n(tt,{type:Y.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col gap-[1px]",children:[l("div",{className:"flex items-center gap-[14px]",children:[n(de,{to:`/entity/${Y.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:Y.name}),Y.entityType&&n(wa,{type:Y.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:Y.filePath,children:Y.filePath})]})]}),n("button",{onClick:o,className:"px-[10px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},children:"View Logs"})]},Y.sha)),$&&!E&&l("button",{onClick:()=>A(!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:["+",v.length-3," more"," ",v.length-3===1?"entity":"entities"]}),E&&$&&n("button",{onClick:()=>A(!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"}),N&&C&&C.length>0&&m&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:C.map(Y=>{var F,X,z,L;if(!Y.id)return null;const H=(X=(F=Y.metadata)==null?void 0:F.screenshotPaths)==null?void 0:X[0],B=(z=Y.metadata)==null?void 0:z.noScreenshotSaved,D=H&&!B,M=(L=u==null?void 0:u.scenarios)==null?void 0:L.find(W=>W.name===Y.name),U=M&&M.screenshotStartedAt&&!M.screenshotFinishedAt||!D&&!B;return n(de,{to:`/entity/${m.sha}/scenarios/${Y.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:U?"#f9f9f9":void 0,borderColor:U?"#efefef":"#ccc"},children:D?n(qe,{screenshotPath:H,alt:Y.name,className:"w-full h-full object-contain bg-gray-100"}):U?n("div",{className:"w-full h-full flex items-center justify-center",children:n(Na,{size:"medium"})}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},Y.id)})}),k&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:k}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.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:"," "]}),(t==null?void 0:t.analyzerPid)&&n(lr,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(w||((T=h[t.analyzerPid])==null?void 0:T.isRunning))&&n(lr,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(lr,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(N||((R=h[t.capturePid])==null?void 0:R.isRunning))&&n(lr,{variant:"running"})]}),(((J=h[t==null?void 0:t.analyzerPid])==null?void 0:J.isRunning)||((q=h[t==null?void 0:t.capturePid])==null?void 0:q.isRunning))&&n("button",{onClick:()=>{const Y=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(D=>{var M;return!!D&&((M=h[D])==null?void 0:M.isRunning)});if(Y.length===0)return;const H=Y.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${H})?`))return;y({isKilling:!0,current:1,total:Y.length}),(async()=>{for(let D=0;D<Y.length;D++){const M=Y[D];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:M,commitSha:a||""})})}catch(Q){console.error(`Failed to kill process ${M}:`,Q)}D<Y.length-1&&y({isKilling:!0,current:D+2,total:Y.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:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(ai,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("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"," ",n(de,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(de,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),l(de,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]}),i&&i.length>0&&l("div",{children:[n("h3",{className:"font-mono uppercase",style:{fontSize:"12px",lineHeight:"18px",color:"#8e8e8e",marginBottom:"16px",fontWeight:500,letterSpacing:"0.05em"},children:"Recently Completed Analyses"}),l("div",{className:"flex flex-col gap-4",children:[(I?i:i.slice(0,3)).map(Y=>{var D;const H=(D=Y.analyses)==null?void 0:D[0],B=(H==null?void 0:H.scenarios)||[];return H==null||H.status,n("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:[n("div",{className:"flex-shrink-0",children:n(tt,{type:Y.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:[n(de,{to:`/entity/${Y.sha}`,className:"hover:underline cursor-pointer",title:Y.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:Y.name}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:"#e8ffe6",color:"#00925d",fontSize:"12px",lineHeight:"16px",fontWeight:400},children:Y.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:Y.filePath,children:Y.filePath})]}),n("div",{className:"flex-1"}),n("div",{className:"flex-shrink-0",children:n("button",{onClick:o,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:M=>{M.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:M=>{M.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),B.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:B.map(M=>{var X,z,L;if(!M.id)return null;const Q=(z=(X=M.metadata)==null?void 0:X.screenshotPaths)==null?void 0:z[0],U=(L=M.metadata)==null?void 0:L.noScreenshotSaved,F=Q&&!U;return l("div",{className:"shrink-0 flex flex-col gap-2",children:[n(de,{to:`/entity/${Y.sha}/scenarios/${M.id}`,className:"block cursor-pointer",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{backgroundColor:F?"#f3f4f6":"#FAFAFA",borderColor:F?"#d1d5db":"#BCCDD3",borderStyle:F?"solid":"dashed"},onMouseEnter:W=>{F&&(W.currentTarget.style.borderColor="#005C75",W.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:W=>{W.currentTarget.style.borderColor=F?"#d1d5db":"#BCCDD3",W.currentTarget.style.boxShadow="none"},children:F?n(qe,{screenshotPath:Q,alt:M.name,className:"max-w-full max-h-full object-contain"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})})}),n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M.name})]},M.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},Y.sha)}),i.length>3&&!I&&l("button",{onClick:()=>j(!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"]}),I&&i.length>3&&n("button",{onClick:()=>j(!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 jy({queueJobs:e,state:t,currentRun:r}){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:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Ec,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Queued Jobs"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Analysis jobs will appear here when they are queued but not yet started."})]})]}),l(de,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[s,a]=_(null),[o,i]=_(null),[c,d]=_(null),[m,u]=_(!1),[h,p]=_(!1),[f,y]=_(new Set),g=ft();te(()=>{e.length<=3&&h&&p(!1)},[e.length,h]);const x=C=>{a(C)},v=(C,k)=>{C.preventDefault(),i(k)},b=async(C,k)=>{if(C.preventDefault(),!s){i(null);return}const E=e.findIndex(j=>j.id===s);if(E===-1){a(null),i(null);return}if(E===k){a(null),i(null);return}const A=E<k?"down":"up",I=Math.abs(k-E);u(!0);try{for(let j=0;j<I;j++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:s,direction:A})});g.revalidate()}catch(j){console.error("Failed to reorder job:",j)}finally{u(!1),a(null),i(null)}},N=()=>{m||(a(null),i(null))},w=async C=>{if(confirm("Are you sure you want to cancel this job?"))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"remove",jobId:C})}),window.location.reload()}catch(k){console.error("Failed to cancel job:",k)}},S=async()=>{if(confirm(`Are you sure you want to cancel all ${e.length} queued jobs?`))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}),window.location.reload()}catch(C){console.error("Failed to cancel jobs:",C)}};return 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&&n("button",{onClick:()=>void S(),className:"px-[10px] py-0 rounded transition-colors cursor-pointer hover:bg-red-300",style:{backgroundColor:"#ffdcd9",color:"#ef4444",fontSize:"12px",fontWeight:500,height:"29px"},children:"Cancel All"})]}),l("div",{className:"flex flex-col gap-3",children:[(h?e:e.slice(0,3)).map(C=>{var $,T,R,J;const k=e.findIndex(q=>q.id===C.id),E=c===k,A=s===C.id,I=o===k,j=f.has(C.id),P=(($=C.entities)==null?void 0:$.length)>0?j?C.entities:C.entities.slice(0,3):[];return l("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:A||m?.5:1,transform:I&&s!==null&&!A?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:m?"not-allowed":A?"grabbing":"grab"},onMouseEnter:()=>d(k),onMouseLeave:()=>d(null),draggable:!m,onDragStart:q=>{x(C.id),q.dataTransfer.effectAllowed="move"},onDragOver:q=>v(q,k),onDrop:q=>void b(q,k),onDragEnd:N,children:[l("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(Ac,{size:16,style:{color:"#005C75"}}),l("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",k+1]})]}),l("div",{className:"flex flex-col gap-2 mt-8",children:[P.length>0?l(ue,{children:[P.map(q=>n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(tt,{type:q.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(de,{to:`/entity/${q.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:q.name}),q.entityType&&n(wa,{type:q.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:q.filePath})]})]})})},q.sha)),((T=C.entities)==null?void 0:T.length)>3&&n("button",{onClick:()=>{y(q=>{const Y=new Set(q);return Y.has(C.id)?Y.delete(C.id):Y.add(C.id),Y})},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:j?"Show less":`+${C.entities.length-3} more ${C.entities.length-3===1?"entity":"entities"}`})]}):n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(br,{size:18,style:{color:"#8e8e8e"}})}),l("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((R=C.entityNames)==null?void 0:R[0])||(C.type==="analysis"?"Analysis Job":C.type==="recapture"?"Recapture Job":C.type==="debug-setup"?"Debug Setup":C.type.charAt(0).toUpperCase()+C.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((J=C.filePaths)==null?void 0:J[0])||(C.filePaths&&C.filePaths.length>1?`${C.filePaths.length} files`:C.entityShas&&C.entityShas.length>0?`${C.entityShas.length} ${C.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),l("div",{className:"flex items-center justify-end gap-2 mt-1",children:[E&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(Pc,{size:20})}),n("button",{onClick:()=>void w(C.id),className:"transition-colors cursor-pointer hover:bg-red-100 rounded flex items-center justify-center",style:{fontSize:"10px",fontWeight:600,lineHeight:"22px",color:"#ef4444",backgroundColor:"#fef6f6",padding:"0 10px",height:"22px"},children:"Cancel"})]})]})]},C.id)}),e.length>3&&!h&&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"]}),h&&e.length>3&&n("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 My({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:s,tab:a,onShowLogs:o}){if(t===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:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(_c,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Historic Activity"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Completed analyses will appear here for historical reference."})]})]}),l(de,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[i,c]=_(!1),d=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(h=>{d.push({...h,runCreatedAt:u.createdAt})})});const m=i?d:d.slice(0,3);return l("div",{className:"flex flex-col gap-4",children:[m.map(u=>{var y;const h=(y=u.analyses)==null?void 0:y[0],p=(h==null?void 0:h.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:[n("div",{children:n(tt,{type:u.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(de,{to:`/entity/${u.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:u.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:f?"#e8ffe6":"#fef3cd",color:f?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:f?"Up to date":"Out of date"})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},title:u.filePath,children:u.filePath})]})]}),n("button",{onClick:o,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),p.length>0&&l("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[p.slice(0,8).map(g=>{var N,w,S;if(!g.id)return null;const x=(w=(N=g.metadata)==null?void 0:N.screenshotPaths)==null?void 0:w[0],v=(S=g.metadata)==null?void 0:S.noScreenshotSaved,b=x&&!v;return n(de,{to:`/entity/${u.sha}/scenarios/${g.id}`,className:"border rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px",borderColor:b?"#ccc":"#BCCDD3",borderStyle:b?"solid":"dashed"},children:b?n(qe,{screenshotPath:x,alt:g.name,className:"w-full h-full object-cover bg-gray-100"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},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&&n("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 Ty=Je(function(){const t=Ve(),r=ni(),[s,a]=_(!1);yt({source:"activity-page"});const o=r.tab||"current";return t?l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-[15px] text-gray-500",children:"View queued, current, and historical analysis activity."})]}),n(Py,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(_y,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>a(!0),recentCompletedEntities:t.recentCompletedEntities||[],hasMoreCompletedRuns:t.hasMoreCompletedRuns||!1,currentEntityScenarios:t.currentEntityScenarios||[],currentEntityForScenarios:t.currentEntityForScenarios,currentAnalysisStatus:t.currentAnalysisStatus}),o==="queued"&&n(jy,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(My,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>a(!0)}),s&&t.projectSlug&&n(Dt,{projectSlug:t.projectSlug,onClose:()=>a(!1)})]}):n("div",{className:"px-20 py-12",children:n("div",{className:"text-center",children:n("p",{className:"text-gray-600",children:"Loading..."})})})}),$y=Object.freeze(Object.defineProperty({__proto__:null,default:Ty,loader:Ay,meta:Ey},Symbol.toStringTag,{value:"Module"}));async function Pl(e,t,r){var w,S;await Ye();const s=await Pt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const a=he();if(!a)throw new Error("Project root not found");const o=O.join(a,".codeyam","config.json"),i=JSON.parse(G.readFileSync(o,"utf8")),{projectSlug:c}=i;if(!c)throw new Error("Project slug not found in config");const d=Jr(c);try{G.writeFileSync(d,"","utf8")}catch{}const{project:m}=await Ie(c),u=((w=m.metadata)==null?void 0:w.packageManager)||"npm",h=3112,p=pt(c),f=((S=m.metadata)==null?void 0:S.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${c}`);const y=i.environmentVariables||[],g=tu({filePath:s.filePath,webapps:f,environmentVariables:y,port:h,packageManager:u});await gn(e,C=>{if(C&&(C.readyToBeCaptured=!0,C.scenarios))for(const k of C.scenarios)(!t||k.name===t)&&(delete k.screenshotStartedAt,delete k.screenshotFinishedAt,delete k.interactiveStartedAt,delete k.interactiveFinishedAt,delete k.error,delete k.errorStack)});const{jobId:x}=r.enqueue({type:"debug-setup",commitSha:s.commit.sha,projectSlug:c,analysisId:e,scenarioId:t,prepOnly:!0}),v=g.startCommand,b={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:v,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${h}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:p,projectSlug:c,port:h,packageManager:u,framework:g.framework,instructions:b}}async function Ry({request:e,context:t}){const r=new URL(e.url),s=r.searchParams.get("analysisId"),a=r.searchParams.get("scenarioId")||void 0;if(!s)return K({error:"Missing analysisId parameter",usage:"GET /api/debug-setup?analysisId=<uuid>&scenarioId=<uuid>",example:'curl "http://localhost:3111/api/debug-setup?analysisId=f35509cb-b8f1-4d86-998e-fc24201ae2c7"'},{status:400});let o=t.analysisQueue;if(o||(o=await jt()),!o)return K({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:s,scenarioId:a});try{const i=await Pl(s,a,o);return K({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),K({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function Iy({request:e,context:t}){if(e.method!=="POST")return K({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await jt()),!r)return K({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a)return K({error:"Missing required field: analysisId"},{status:400});const i=await Pl(a,o,r);return K({...i,success:!0,message:"Debug setup queued"})}catch(s){console.error("[Debug Setup API] Error during debug setup:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Debug Setup API] Error stack:",o),K({error:"Failed to setup debug environment",details:a},{status:500})}}const Dy=Object.freeze(Object.defineProperty({__proto__:null,action:Iy,loader:Ry},Symbol.toStringTag,{value:"Module"}));function Ly({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return new Response("Missing path parameter",{status:400});const s=he()||process.cwd(),a=O.resolve(s,r);if(!a.startsWith(s+O.sep)&&a!==s)return new Response("Path outside project root",{status:403});try{const o=G.readFileSync(a,"utf8");return new Response(o,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch{return new Response("File not found",{status:404})}}const Oy=Object.freeze(Object.defineProperty({__proto__:null,loader:Ly},Symbol.toStringTag,{value:"Module"})),Fy=process.env.LABS_UNLOCK_SALT||"codeyam-labs-default-salt";function _l(e){const t=Kc("sha256",Fy);return t.update(e),`CY-${t.digest("hex").slice(0,16)}`}function zy(e,t){return t===_l(e)}async function By({request:e}){if(e.method!=="POST")return K({error:"Method not allowed"},{status:405});try{const r=(await e.formData()).get("unlockCode");if(!r)return K({success:!1,error:"Unlock code is required"},{status:400});const s=await $e();return s?zy(s,r)?(await hn({projectSlug:s,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),K({success:!0})):K({success:!1,error:"Invalid unlock code"},{status:400}):K({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("[Labs Unlock] Error:",t),K({success:!1,error:"Failed to validate unlock code. Please try again."},{status:500})}}const Yy=Object.freeze(Object.defineProperty({__proto__:null,action:By},Symbol.toStringTag,{value:"Module"}));async function Uy({request:e,context:t}){if(e.method!=="POST")return K({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await jt()),!r)return K({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("defaultWidth");if(!a||!o)return K({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return K({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${a} with width ${i}`);const c=await xg(a,i,r);return console.log("[API] Recapture queued",c),K({success:!0,message:"Recapture queued",...c})}catch(s){return console.log("[API] Error during recapture:",s),K({error:"Failed to recapture screenshots",details:s instanceof Error?s.message:String(s)},{status:500})}}const Wy=Object.freeze(Object.defineProperty({__proto__:null,action:Uy},Symbol.toStringTag,{value:"Module"}));function Jy(e){if(e.length===0)throw new Error("paths array must not be empty");return e.map(Hy).map(a=>a===""?[]:a.split("/")).reduce((a,o)=>{const i=[];for(let c=0;c<Math.min(a.length,o.length)&&a[c]===o[c];c++)i.push(a[c]);return i}).join("/")}function Hy(e){const r=e.replace(/\/+$/,"").split("/");for(;r.length>0;){const s=r[r.length-1];if(Vy(s))r.pop();else break}return r.join("/")}function Vy(e){return!!(e.includes("*")||/\.\w+$/.test(e))}function qy({request:e}){const r=new URL(e.url).searchParams.getAll("paths");if(r.length===0)return Response.json({error:"Missing required query parameter: paths"},{status:400});const s=Jy(r),a=s?`.claude/rules/${s}/`:".claude/rules/";return Response.json({result:a})}const Gy=Object.freeze(Object.defineProperty({__proto__:null,loader:qy},Symbol.toStringTag,{value:"Module"}));function Ky(e,t){var i,c,d,m,u;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,s=e.analyses&&e.analyses.length>0&&e.analyses.some(h=>h.scenarios&&h.scenarios.length>0);if(!r){const h=!!((c=e.metadata)!=null&&c.previousVersionWithAnalyses),p=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return h||p?s?{state:"committed_no_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Committed - Simulations Outdated",color:"text-orange-700",bgColor:"bg-orange-50",borderColor:"border-orange-300",icon:"⚠"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Yet Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}:s?{state:"committed_with_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up to date",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"✓"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}const a=!!((d=e.metadata)!=null&&d.previousCommittedSha);if(!!((m=e.metadata)!=null&&m.previousVersionWithAnalyses)||a){const h=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return s&&!h?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:s?{state:"uncommitted_outdated_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Edited - Simulations Outdated",color:"text-amber-700",bgColor:"bg-amber-50",borderColor:"border-amber-300",icon:"⚠"}}:{state:"uncommitted_outdated_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}else return s?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:{state:"uncommitted_no_previous_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"New",color:"text-purple-700",bgColor:"bg-purple-50",borderColor:"border-purple-200",icon:"+"}}}function Qy(e){return Ky(e).hasOutdatedSimulations}function rs(e,t,r,s,a){var q,Y,H,B,D,M,Q,U;const o=(q=t==null?void 0:t.scenarios)==null?void 0:q.find(F=>F.name===e.name),i=!!(o!=null&&o.startedAt),c=!!(o!=null&&o.screenshotStartedAt),d=!!(o!=null&&o.screenshotFinishedAt),m=!!(o!=null&&o.finishedAt),u=1800*1e3,h=c&&!d&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,p=!!((H=(Y=e.metadata)==null?void 0:Y.screenshotPaths)!=null&&H[0])||!!((B=e.metadata)!=null&&B.executionResult),f=c&&!d,y=o==null?void 0:o.error,g=(M=(D=e.metadata)==null?void 0:D.executionResult)==null?void 0:M.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const F of t.errors)x.push({source:`${F.phase} phase`,message:F.message});if(t!=null&&t.steps)for(const F of t.steps)F.error&&x.push({source:F.name,message:F.error});const v=!p&&!y&&!g&&x.length>0,b=!!(y||g||h||v),N=h?"Capture timed out after 30 minutes":(typeof y=="string"?y:null)||(g==null?void 0:g.message)||(v?`Analysis error: ${x[0].message}`:null),w=h?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(o==null?void 0:o.errorStack)||(g==null?void 0:g.stack)||null,C=(s&&a?a.jobs.some(F=>{var X;return((X=F.entityShas)==null?void 0:X.includes(s))||F.type==="analysis"&&F.entityShas&&F.entityShas.length===0})||((U=(Q=a.currentlyExecuting)==null?void 0:Q.entityShas)==null?void 0:U.includes(s)):!1)&&!i&&!b||!!(o!=null&&o.analyzing)&&!i&&!b,k=i&&!c&&!m&&!b,E=(C||k||f)&&!b,A=(C||k)&&r===!1&&!p;let I;A?I="crashed":b?I="error":p||m?I="completed":f?I="capturing":k?I="starting":C?I="queued":I="pending";let j="📷",P="pending",$=!1,T=`Not captured: ${e.name}`;const R="border-gray-300",J=b||A?"bg-red-50":"bg-white";return b||A?(j="⚠️",P="error",T=`Error: ${A?"Analysis process crashed":N||"Unknown error"}`):C?(j="⋯",P="queued",T=`Queued: ${e.name}`):k?(j="⋯",P="starting",$=!0,T=`Starting server for ${e.name}...`):f&&!b?(j="⋯",P="capturing",$=!0,T=`Capturing ${e.name}...`):p&&(j="✓",P="completed",T=e.name),{hasError:b||A,errorMessage:A?"Analysis process crashed":N,errorStack:A?"Process terminated unexpectedly before completing analysis":w,isCapturing:f,isCaptured:p,hasCrashed:A,isAnalyzing:E,isQueued:C,isServerStarting:k,status:I,icon:j,iconType:P,shouldSpin:$,title:T,borderColor:R,bgColor:J}}function jl({scenario:e,entitySha:t,size:r="medium",showBorder:s=!0,isOutdated:a=!1}){var w,S,C,k,E,A;const o=rs(e,void 0,void 0,t,void 0),i=(w=e.metadata)==null?void 0:w.executionResult,c=!!i,m=(((C=(S=e.metadata)==null?void 0:S.data)==null?void 0:C.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,h=((E=(k=i==null?void 0:i.sideEffects)==null?void 0:k.consoleOutput)==null?void 0:E.length)||0,p=((A=i==null?void 0:i.timing)==null?void 0:A.duration)||0;let f=0;m>0&&f++,m>2&&f++,u&&f++,h>0&&f++,f=Math.min(3,f);const y=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},x=o.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:c?a?{border:"border-amber-500",bg:"bg-amber-50",icon:"text-amber-700",badge:"bg-amber-100 text-amber-700"}:{border:"border-blue-400",bg:"bg-blue-50",icon:"text-blue-600",badge:"bg-blue-100 text-blue-700"}:{border:"border-gray-300 border-dashed",bg:"bg-gray-50",icon:"text-gray-400",badge:"bg-gray-100 text-gray-600"},v=s?`border-2 ${x.border}`:"",b=Array.from({length:3},(I,j)=>n("div",{className:`w-1 h-1 rounded-full ${j<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},j)),N=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:c?`${e.name}
|
|
287
|
+
${m} args → ${u?"value":"void"}${h>0?` (${h} logs)`:""}
|
|
288
|
+
${p}ms`:`Not executed: ${e.name}`;return l(de,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${y.width} ${y.height} ${v} rounded ${x.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:N,onClick:I=>I.stopPropagation(),children:[n("div",{className:`${x.icon} ${y.iconSize} font-mono font-bold`,children:o.hasError?"⚠":c?"ƒ":"○"}),c&&!o.hasError&&l("div",{className:`flex items-center gap-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:[n("span",{children:m}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),c&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:b}),c&&!o.hasError&&p>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:p>1e3?`${Math.round(p/1e3)}s`:`${p}ms`}),c&&!o.hasError&&h>0&&r==="medium"&&l("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",h]})]})}function Zs({size:e=24,className:t=""}){return l("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:[n("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),n("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),n("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function jo({scenario:e,entity:t,analysisStatus:r,queueState:s,processIsRunning:a,size:o="medium",cacheBuster:i,className:c="",viewMode:d}){var g,x;if(t.entityType==="library")return n(jl,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=rs(e,r,a,t.sha,s),h=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},p=`relative ${h.containerClass} ${c}`,f=()=>{const v=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${v}/${d}`:v};if(u.isCaptured){const v=(x=(g=e.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return n(de,{to:f(),className:`${p} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(qe,{screenshotPath:v,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const y=()=>{const v={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},b=n(Na,{size:o});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return b;switch(u.iconType){case"starting":case"capturing":return b;case"error":return l("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(Zs,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(jc,{...v});default:return b}};return n(de,{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:n("div",{className:h.iconSize,children:y()})})}const cn=70;function Zy({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:s,entitySha:a,cacheBuster:o,activeTab:i,entityType:c,entity:d,queueState:m,processIsRunning:u,isEntityAnalyzing:h,areScenariosStale:p,viewMode:f,setViewMode:y,isBreakdownView:g}){var $,T,R,J,q,Y;const x=be(null),[v,b]=_(new Set),[N,w]=_(!1);te(()=>{x.current&&i==="scenarios"&&x.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[s==null?void 0:s.id,i]);const S=H=>`/entity/${a}/scenarios/${H}`,C=H=>{b(B=>{const D=new Set(B);return D.has(H)?D.delete(H):D.add(H),D})},k=(H,B=2)=>{const M=H.split(`
|
|
289
|
+
`).slice(0,B).join(" ").trim();return M.length>cn?M.substring(0,cn-3):(H.split(`
|
|
290
|
+
`).length>B||H.length>M.length,M)},E=ne(()=>{var B;if(!((B=r==null?void 0:r.metadata)!=null&&B.executionFlows)||!(r!=null&&r.scenarios))return null;const H=r.scenarios.filter(D=>{var M;return!((M=D.metadata)!=null&&M.sameAsDefault)});return ya(r.metadata.executionFlows,H)},[r]),A=(E==null?void 0:E.totalFlows)||0,I=(E==null?void 0:E.coveredFlows)||0,j=(E==null?void 0:E.coveragePercentage)||0;($=d==null?void 0:d.metadata)!=null&&$.defaultWidth||(T=r==null?void 0:r.metadata)!=null&&T.defaultWidth;const P=(R=r==null?void 0:r.status)!=null&&R.finishedAt?new Date(r.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:[r&&e.length>0&&l("div",{className:"flex flex-col gap-2",children:[n("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),l("div",{className:"grid grid-cols-2 gap-2",children:[l(de,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((J=e[0])==null?void 0:J.id)}`:`/entity/${a}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[l("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(j),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),l(de,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((q=e[0])==null?void 0:q.id)}`:`/entity/${a}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[l("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[I,"/",A]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),l(de,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((Y=e[0])==null?void 0:Y.id)}`:`/entity/${a}/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:[n("div",{className:"text-[11px] text-[#005c75] font-normal uppercase font-mono underline",children:"EXECUTION FLOWS"}),g?n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M3 3L9 9M9 3L3 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),d&&d.filePath&&n("div",{children:n(de,{to:`/entity/${a}/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"]}),P&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:P})]}),h&&(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:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}),n("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):e.length===0?n("div",{className:"",children:n("p",{className:"text-[#8e8e8e] text-xs font-medium m-0 text-left leading-5",children:"No Scenarios"})}):n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"flex flex-col gap-[11.6px]",children:e.map((H,B)=>{const D=!g&&(s==null?void 0:s.id)===H.id,M=v.has(H.id||"");return H.id?l(de,{to:S(H.id),ref:D?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${D?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[n("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:n(jo,{scenario:H,entity:{sha:a,entityType:c},analysisStatus:r==null?void 0:r.status,queueState:m,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),l("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${M?"":"line-clamp-1"}`,children:H.name}),H.description&&n("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[M?H.description:k(H.description),!M&&H.description.length>cn&&l(ue,{children:["...",n("button",{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),C(H.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),M&&H.description.length>cn&&n("button",{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),C(H.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},B):null})})}),t.length>0&&!(h&&p)&&l("div",{className:"border-t border-[#e1e1e1] pt-3",children:[l("button",{onClick:()=>w(!N),className:"flex items-center gap-1 text-[10px] text-[#626262] font-medium cursor-pointer bg-transparent border-none p-0 hover:text-[#005c75] transition-colors w-full",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`transition-transform ${N?"rotate-90":""}`,children:n("path",{d:"M3.5 2L6.5 5L3.5 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"Hidden Scenarios (",t.length,")"]}),N&&l("div",{className:"mt-2",children:[n("p",{className:"text-[10px] text-[#8e8e8e] leading-[14px] mb-3",children:"These scenarios were hidden because the screenshots did not differ from the Default Scenario."}),n("div",{className:"flex flex-col gap-[11.6px]",children:t.map((H,B)=>{const D=!g&&(s==null?void 0:s.id)===H.id,M=v.has(H.id||"");return H.id?l(de,{to:`/entity/${a}/scenarios/${H.id}`,ref:D?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${D?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[n("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:n(jo,{scenario:H,entity:{sha:a,entityType:c},analysisStatus:r==null?void 0:r.status,queueState:m,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),l("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${M?"":"line-clamp-1"}`,children:H.name}),H.description&&n("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[M?H.description:k(H.description),!M&&H.description.length>cn&&l(ue,{children:["...",n("button",{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),C(H.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),M&&H.description.length>cn&&n("button",{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),C(H.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},B):null})})]})]})]})}function Xy({scenario:e,entitySha:t,onApply:r,onSave:s,onEditMockData:a,onDelete:o,isApplying:i=!1,isSaving:c=!1,saveMessage:d=null,showDeleteConfirm:m=!1,onShowDeleteConfirm:u,isDeleting:h=!1,deleteError:p=null}){const[f,y]=_(""),g=async()=>{await r(f)},x=async v=>{await s(f,v),v||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:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(de,{to:`/entity/${t}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),n("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),l("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[l("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange:v=>y(v.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:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),i?"Applying...":"Apply"]})]}),n("div",{className:"border-t border-[#e1e1e1] my-1"}),l("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick:a,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),d&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${d.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:d}),d==="Recapture successful"&&n("div",{children:n(de,{to:`/entity/${t}`,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:[n("button",{onClick:()=>void x(!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"}),n("button",{onClick:()=>void x(!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"}),o&&l(ue,{children:[m?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:[n("button",{onClick:()=>void o(),disabled:h,className:"flex-1 h-[22px] bg-red-600 text-white rounded text-[10px] font-normal hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors flex items-center justify-center cursor-pointer",children:h?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>u==null?void 0:u(!1),disabled:h,className:"flex-1 h-[22px] bg-gray-100 text-gray-700 border border-gray-300 rounded text-[10px] font-normal hover:bg-gray-200 disabled:opacity-50 transition-colors flex items-center justify-center cursor-pointer",children:"Cancel"})]})]}):n("button",{onClick:()=>u==null?void 0:u(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),p&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:p})]})]})]})}function ex({scenario:e,analysis:t,entity:r}){var i,c,d;const s=((i=e.metadata)==null?void 0:i.executionResult)||null,a=((d=(c=e.metadata)==null?void 0:c.data)==null?void 0:d.argumentsData)||[],o=m=>{var y,g,x;if(!m)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const u=[],h=((y=m.sideEffects)==null?void 0:y.consoleOutput)||[];h.length>0&&(u.push(`Console Output: ${h.length} log ${h.length===1?"entry":"entries"} captured`),h.forEach(v=>{u.push(` [${v.level.toUpperCase()}] ${v.args.join(" ")}`)}));const p=((g=m.sideEffects)==null?void 0:g.fileWrites)||[];p.length>0&&(u.push(`
|
|
291
|
+
File System Operations: ${p.length} ${p.length===1?"operation":"operations"} detected`),p.forEach(v=>{u.push(` ${v.operation}: ${v.path}${v.size?` (${v.size} bytes)`:""}`)}));const f=((x=m.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(u.push(`
|
|
292
|
+
API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(v=>{u.push(` ${v.method} ${v.url}${v.status?` → ${v.status}`:""}${v.duration?` (${v.duration}ms)`:""}`)})),m.error&&u.push(`
|
|
293
|
+
Error: ${m.error.name||"Error"}: ${m.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
|
|
294
|
+
`)};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:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(a,null,2)})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:s?n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:s.returnValue!==void 0?JSON.stringify(s.returnValue,null,2):"undefined"}):n("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:o(s)})})]})]})}const Jt={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function cr({scenarioId:e,analysisId:t}){const[r,s]=_(!1),[a,o]=_(!1),[i,c]=_(null),[d,m]=_(!1),u=e||t;if(!u)return null;const h=`/codeyam-diagnose ${u}`,p=async()=>{o(!0);try{const{default:y}=await import("html2canvas-pro"),x=(await y(document.body,{scale:.5})).toDataURL("image/jpeg",.8);c(x),s(!0)}catch(y){console.error("Screenshot capture failed:",y),s(!0)}finally{o(!1)}},f=()=>{s(!1),c(null)};return l(ue,{children:[l("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[n("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:Jt.heading},children:"Claude can help debug this error."}),n("p",{className:"m-0 mb-4 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"18px",color:Jt.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:Jt.commandBoxBg,borderColor:Jt.commandBoxBorder,maxWidth:"505px",height:"35px",paddingLeft:"13px",paddingRight:"13px",paddingTop:"6px",paddingBottom:"6px"},children:[n("code",{className:"font-mono font-['IBM_Plex_Mono'] flex-1 text-left",style:{fontSize:"12px",lineHeight:"20px",color:Jt.commandBoxText},children:h}),n("button",{onClick:y=>{y.stopPropagation(),navigator.clipboard.writeText(h),m(!0),setTimeout(()=>m(!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":Jt.commandBoxText},title:d?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:d?n(gt,{size:14}):n(Nt,{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,"," ",n("button",{onClick:()=>void p(),disabled:a,className:"underline cursor-pointer bg-transparent border-none p-0 font-normal hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:Jt.link},children:a?"capturing...":"please do so here"}),"."]})]}),n(mi,{isOpen:r,onClose:f,context:{source:e?"scenario-page":"entity-page",entitySha:void 0,scenarioId:e,analysisId:t,currentUrl:typeof window<"u"?window.location.pathname:"/"},screenshotDataUrl:i??void 0})]})}const Mo=1440,dr=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],vt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function Ml({selectedScenario:e,analysis:t,entity:r,viewMode:s,cacheBuster:a,hasScenarios:o,isAnalyzing:i=!1,projectSlug:c,hasAnApiKey:d=!0,processIsRunning:m,queueState:u}){var V,Z,ce,ve,ae,me,Se,Ne,Ae,De,Oe;const h=Le(),[p,f]=_(!1),[y,g]=_(!1),[x,v]=_({name:"Desktop",width:Mo,height:900}),[b,N]=_(Mo),[w,S]=_(1),{customSizes:C,addCustomSize:k,removeCustomSize:E}=Qr(c),A=ne(()=>[...dr,...C],[C]),I=(Ee,re)=>{N(Ee);const ye=A.find(ke=>ke.width===Ee&&ke.height===re);v({name:(ye==null?void 0:ye.name)||"Custom",width:Ee,height:re})},j=Ee=>{N(Ee.width),v({name:Ee.name,width:Ee.width,height:Ee.height})},P=Ee=>{k(Ee,x.width,x.height??900),g(!1),v(re=>({...re,name:Ee}))},$=(Ee,re)=>{N(Ee);const ye=A.find(ke=>ke.width===Ee&&ke.height===re);v(ke=>({name:(ye==null?void 0:ye.name)||"Custom",width:Ee,height:ke.height}))},T=(Z=(V=e==null?void 0:e.metadata)==null?void 0:V.screenshotPaths)==null?void 0:Z[0],R=ne(()=>e?rs(e,t==null?void 0:t.status,m,r==null?void 0:r.sha,u):null,[e,t==null?void 0:t.status,m,r==null?void 0:r.sha,u]),J=ne(()=>{var re,ye;const Ee=[];if((re=t==null?void 0:t.status)!=null&&re.errors&&t.status.errors.length>0)for(const ke of t.status.errors)Ee.push({source:`${ke.phase} phase`,message:ke.message,stack:ke.stack});if((ye=t==null?void 0:t.status)!=null&&ye.steps)for(const ke of t.status.steps)ke.error&&Ee.push({source:ke.name,message:ke.error,stack:ke.errorStack});return Ee},[(ce=t==null?void 0:t.status)==null?void 0:ce.errors,(ve=t==null?void 0:t.status)==null?void 0:ve.steps]),q=(R==null?void 0:R.errorMessage)||null,Y=(R==null?void 0:R.errorStack)||null,{interactiveServerUrl:H,isStarting:B,isLoading:D,showIframe:M,iframeKey:Q,onIframeLoad:U}=nn({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:c,enabled:s==="interactive"}),F=ne(()=>H||null,[H]),X=!i&&o&&e&&!((me=(ae=e.metadata)==null?void 0:ae.screenshotPaths)!=null&&me[0])&&((Ne=(Se=t==null?void 0:t.status)==null?void 0:Se.scenarios)==null?void 0:Ne.some(Ee=>Ee.name===e.name&&Ee.screenshotStartedAt&&!Ee.screenshotFinishedAt)),{lastLine:z}=Et(c,i||s==="interactive"||X||!1);if(!e){if(i&&r)return l(ue,{children:[n("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:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:X?"Capturing screenshots...":"Analyzing..."}),n("p",{className:"text-xs text-[#8e8e8e] text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:"This may take a few minutes."}),z&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:z}),c&&n("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})}),p&&c&&n(Dt,{projectSlug:c,onClose:()=>f(!1)})]});if(!o&&r&&!i){if(J.length>0){const Ee=J.length===1?((Ae=J[0])==null?void 0:Ae.message)||"An error occurred during analysis.":`${J.length} errors occurred during analysis.`;return l(ue,{children:[n("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:[n("div",{className:"p-4 rounded",style:{backgroundColor:vt.background,border:`2px solid ${vt.border}`},role:"alert",children:l("div",{className:"flex items-center gap-3",children:[n(Zs,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:l("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:vt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",Ee," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:vt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(cr,{analysisId:t==null?void 0:t.id})})]})}),p&&c&&n(Dt,{projectSlug:c,onClose:()=>f(!1)})]})}return n("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:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{h.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:h.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:h.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return l(ue,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
|
|
295
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
296
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
297
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
298
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
299
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||X&&!T)&&!q&&s==="screenshot"?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-linear-to-br from-blue-50 to-indigo-50",children:l("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[l("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:X?`Capturing ${r==null?void 0:r.name}`:`Analyzing ${r==null?void 0:r.name}`}),n("p",{className:"text-base text-gray-600 leading-relaxed m-0 mb-2",children:X?`Taking screenshots for ${((De=t==null?void 0:t.scenarios)==null?void 0:De.length)||0} scenario${((Oe=t==null?void 0:t.scenarios)==null?void 0:Oe.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&l("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),z&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:l("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),l("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:z,children:z})]})]})}),c&&n("button",{onClick:()=>f(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),n("p",{className:"text-xs text-gray-500 mt-8 m-0",children:"Screenshots will appear here as they are captured. This may take a few minutes."})]})}):s==="screenshot"&&(T||q)||s==="interactive"&&(F||B)||s==="data"?l(ue,{children:[q&&!T&&n("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:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:vt.background,border:`2px solid ${vt.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:vt.text},children:[n(Zs,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),l("div",{className:"text-center",children:[n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:vt.link},children:"See logs"})," ","for details."]}),n("div",{className:"flex-1 min-w-0",children:n("div",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:vt.text},children:q})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(cr,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),s==="interactive"?l("div",{className:"flex-1 flex flex-col min-h-0",children:[F&&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:[n(ch,{presets:[...dr],customSizes:C,currentWidth:x.width,currentHeight:x.height??900,scale:w,onSizeChange:I,onSaveCustomSize:()=>g(!0),onRemoveCustomSize:E}),e&&r&&l(de,{to:`/entity/${r.sha}/scenarios/${e.id}/fullscreen?from=${encodeURIComponent(`/entity/${r.sha}/scenarios/${e.id}/interactive`)}`,className:"flex items-center gap-2 px-4 py-2 bg-[#005c75] text-white rounded hover:bg-[#004a5c] transition-colors text-sm font-medium no-underline",title:"Open in fullscreen",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:n("path",{d:"M2 5V2H5M11 2H14V5M14 11V14H11M5 14H2V11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Fullscreen"]})]}),F&&n("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${dr[dr.length-1].width}px`,width:"100%"},children:n(Gr,{currentViewportWidth:b,currentPresetName:x.name,onDevicePresetClick:j,devicePresets:A})})}),n(Xr,{scenarioId:e.id,scenarioName:e.name,iframeUrl:F,isStarting:B,isLoading:D,showIframe:M,iframeKey:Q,onIframeLoad:U,onScaleChange:S,onDimensionChange:$,projectSlug:c,defaultWidth:x.width,defaultHeight:x.height})]}):s==="data"?n("div",{className:"flex-1 min-h-0",children:n(ex,{scenario:e,analysis:t,entity:r})}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 p-6 flex items-center justify-center",children:n("div",{className:"transition-all duration-300",style:{maxWidth:`${b}px`},children:(T||!q)&&n(qe,{screenshotPath:T,cacheBuster:a,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!T?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),l("div",{className:"flex-1",children:[n("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"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),z&&l("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:z})]}),c&&n("button",{onClick:()=>f(!0),className:"mt-4 px-4 py-2 bg-[#005c75] text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-[#004a5e]",children:"📋 View Full Logs"})]})]})})}):q?l("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!d&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:l("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[l("div",{className:"flex items-start gap-4",children:[n("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),l("div",{className:"bg-white border border-blue-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-blue-900 m-0 mb-2 uppercase tracking-wide",children:"CodeYam requires an AI API key for reliable analysis."}),l("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[n("li",{children:"You can use API keys for a variety of models"}),n("li",{children:"Faster analysis processing"}),n("li",{children:"Better handling of complex code structures"}),n("li",{children:"Improved scenario generation quality"})]})]}),n(de,{to:"/settings",className:"inline-block px-4 py-2 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700",children:"🔐 Configure API Keys"})]})}),n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),l("div",{className:"bg-white border border-red-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),n("div",{className:"max-h-[300px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:q})})]}),Y&&l("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:Y})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(cr,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):J.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:J,title:"Analysis Error",description:J.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${J.length} errors occurred during analysis. Screenshot capture was not completed.`}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(cr,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):l("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),p&&c&&n(Dt,{projectSlug:c,onClose:()=>f(!1)}),y&&n(Kr,{width:x.width,height:x.height??900,onSave:P,onCancel:()=>g(!1)})]})}function tx({analysis:e,entitySha:t}){ft();const[r,s]=_(e);te(()=>{s(e)},[e]);const[a,o]=_(null),i=ne(()=>{var h;if(!((h=r==null?void 0:r.metadata)!=null&&h.executionFlows)||!(r!=null&&r.scenarios))return null;const u=r.scenarios.filter(p=>{var f;return!((f=p.metadata)!=null&&f.sameAsDefault)});return ya(r.metadata.executionFlows,u)},[r]),c=ne(()=>i?Hh(i):[],[i]),d=ne(()=>r!=null&&r.scenarios?r.scenarios.filter(u=>{var h;return!((h=u.metadata)!=null&&h.sameAsDefault)}):[],[r]),m=u=>{var p;const h=((p=u.metadata)==null?void 0:p.coveredFlows)||[];return i?i.executionFlows.filter(f=>h.includes(f.id)):[]};return r?!i||i.executionFlows.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:l("div",{className:"p-6 space-y-6",children:[l("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),l("div",{className:"grid grid-cols-4 gap-4 text-center",children:[l("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:d.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:i.executionFlows.length}),n("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]}),n("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),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),l("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:l("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",d.length,")"]})}),n("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."," ",n(de,{to:`/entity/${t}/create-scenario`,className:"text-blue-600 hover:underline",children:"Create one"})]}):d.map(u=>{var f,y,g;const h=(y=(f=u.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0],p=m(u);return l("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(qe,{screenshotPath:h,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:[n("div",{className:"flex items-start justify-between gap-2",children:l("div",{children:[n(de,{to:`/entity/${t}/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)&&n("span",{className:"ml-2 text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"Error"})]})}),n("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:u.description}),p.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:p.map(x=>n("span",{className:`text-xs px-1.5 py-0.5 rounded ${x.isError?"bg-red-50 text-red-700":x.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:x.name},x.id))})]})]},u.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:l(de,{to:`/entity/${t}/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:[n("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:[n("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,")"]})}),n("div",{className:"divide-y divide-gray-100",children:i.executionFlows.map(u=>{const h=a===u.id,p=u.usedInScenarios.length>0;return l("div",{children:[n("button",{onClick:()=>o(h?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:[n("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:h?"▼":"▶"}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-medium text-sm text-gray-900",children:u.name}),p?n("span",{className:"text-xs px-2 py-0.5 rounded bg-green-100 text-green-700",children:"Covered"}):n("span",{className:"text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700",children:"Uncovered"}),u.blocksOtherFlows&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),u.impact==="high"&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),u.isError&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),u.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:u.description})]})]})}),h&&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:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),n("div",{className:"space-y-1",children:u.requiredValues.map((f,y)=>l("div",{className:"flex items-center gap-2 text-xs",children:[n("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children:f.attributePath}),n("span",{className:"text-gray-400",children:f.comparison}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:f.value})]},y))})]}),p&&l("div",{children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),n("div",{className:"flex flex-wrap gap-1",children:u.usedInScenarios.map(f=>n("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:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:u.codeSnippet})})]})]})]},u.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function To({hasIndirectBadge:e,onAnalyze:t}){return l(ue,{children:[n("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&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:"0 scenarios"})]})}),l("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[n("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),n("button",{className:"px-[15px] py-0 h-[23px] bg-[#005c75] text-white rounded text-xs font-medium leading-5 border-none cursor-pointer hover:bg-[#004a5e] transition-colors flex items-center justify-center",onClick:t,children:"Analyze"})]})]})}function nx({entity:e,history:t}){const[r,s]=_("entity"),[a,o]=_(new Set),i=t.filter(u=>u.analyses.length>0).length,c=ne(()=>{const u=new Map;return t.forEach(h=>{h.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:h,analysis:p,scenario:y})})})}),Array.from(u.entries()).map(([h,p])=>{var f;return{name:h,description:((f=p[0])==null?void 0:f.scenario.description)||"",versions:p.sort((y,g)=>{const x=new Date(y.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-x})}})},[t]),d=c.length,m=u=>{o(h=>{const p=new Set(h);return p.has(u)?p.delete(u):p.add(u),p})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:l("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:l("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[l("button",{onClick:()=>s("entity"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="entity"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-semibold leading-6",children:"Entity History"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="entity"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:i})]}),l("button",{onClick:()=>s("scenarios"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="scenarios"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-normal leading-6",children:"Scenario Changes"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="scenarios"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:d})]})]})}),t.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):r==="entity"?l("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((u,h)=>l("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children: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)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),l(de,{to:`/entity/${u.sha}/scenarios`,className:"text-xs font-mono text-[#646464] leading-5 hover:text-[#005c75] transition-colors",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:u.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:u.createdAt&&new Date(u.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),u.analyses.length>0?n("div",{children:u.analyses.map((p,f)=>{var g;const y=(p.scenarios??[]).filter(x=>{var v;return!((v=x.metadata)!=null&&v.sameAsDefault)});return n("div",{children:y.length===0?n(To,{hasIndirectBadge:p.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):l(ue,{children:[n("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&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),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)&&n("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&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:y.map((x,v)=>{var w,S;const b=(S=(w=x.metadata)==null?void 0:w.screenshotPaths)==null?void 0:S[0],N=`${x.name}-${v}`;return l(de,{to:`/entity/${u.sha}/scenarios/${x.id}`,className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden hover:border-[#005c75] hover:shadow-sm transition-all",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:b?n(qe,{screenshotPath:b,alt:x.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:x.name})})]},N)})})})]})},p.id||f)})}):n(To,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:c.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):c.map((u,h)=>{const p=a.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:[n("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:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),l("div",{className:"p-5 bg-white",children:[f.map((x,v)=>{var k,E;const{version:b,analysis:N,scenario:w}=x,S=(E=(k=w.metadata)==null?void 0:k.screenshotPaths)==null?void 0:E[0],C=v===0;return l("div",{className:`flex gap-5 items-start ${C?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(de,{to:`/entity/${b.sha}/scenarios/${w.id}`,className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0 hover:border-[#005c75] hover:shadow-sm transition-all",children:S?n(qe,{screenshotPath:S,alt:w.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),l("div",{className:"flex-1 flex flex-col gap-2",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[b.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),C&&u.versions.length>1&&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(de,{to:`/entity/${b.sha}/scenarios`,className:"text-xs font-mono text-[#646464] m-0 leading-5 hover:text-[#005c75] transition-colors w-fit",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:b.sha.substring(0,8)})]}),N.createdAt&&l("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(N.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),N.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${b.sha}-${v}`)}),y>0&&l("button",{onClick:()=>m(u.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${p?"rotate-180":""}`,children:n("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 $o({entity:e,analysisInfo:t,from:r}){const s=Le(),a=s.state!=="idle",o=e.entityType==="visual"||e.entityType==="library",i=c=>{c.preventDefault(),c.stopPropagation(),o&&s.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(de,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,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?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(qe,{screenshotPath:e.screenshotPath,alt:e.name,className:"max-w-full max-h-full object-contain"})}):n("div",{className:"w-[125px] h-full bg-[#efefef] flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n("span",{className:"text-[40px]",children:n(tt,{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:[n(tt,{type:e.entityType}),n("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),n("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),t.hasScenarios&&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:[t.scenarioCount," scenarios"]}),n("span",{className:"text-xs text-[#8e8e8e]",children:t.timestamp})]})]}),n("div",{className:"shrink-0 ml-4",children:t.status==="not_analyzed"?l(ue,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:a,children:a?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):l(ue,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:a,children:a?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const Ro=e=>{var a,o,i;const t=((a=e.analysisStatus)==null?void 0:a.status)||"not_analyzed",r=((o=e.analysisStatus)==null?void 0:o.scenarioCount)||0,s=(i=e.analysisStatus)==null?void 0:i.timestamp;return t==="not_analyzed"?{status:"not_analyzed",label:"Not analyzed",color:"gray"}:t==="up_to_date"?{status:"up_to_date",label:"Up to date",color:"green",hasScenarios:r>0,scenarioCount:r,timestamp:s}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:r>0,scenarioCount:r,timestamp:s}};function rx({importedEntities:e,importingEntities:t}){const[r]=fn(),s=r.get("from"),a=Le(),o=a.state!=="idle",i=e.length>0,c=t.length>0,d=p=>p.filter(f=>f.entityType==="visual"||f.entityType==="library"),m=p=>{const f=d(p);f.length!==0&&a.submit({entityShas:f.map(y=>y.sha).join(",")},{method:"post",action:"/api/analyze"})},u=d(e).length>0,h=d(t).length>0;return n("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:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&n("button",{onClick:()=>m(e),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(p=>n($o,{entity:p,analysisInfo:Ro(p),from:s},p.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),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:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),h&&n("button",{onClick:()=>m(t),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),c?n("div",{className:"p-6 space-y-4",children:t.map(p=>n($o,{entity:p,analysisInfo:Ro(p),from:s},p.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px] text-center",children:"Not imported by any entity."})})]})]})})}function sx({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(rx,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function ax({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(On,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function On({data:e,depth:t,defaultExpanded:r,maxDepth:s,objectKey:a,showInlineToggle:o=!1}){const[i,c]=_(r||t<2);if(te(()=>{c(r||t<2)},[r,t]),e===null)return n("span",{className:"text-gray-500",children:"null"});if(e===void 0)return n("span",{className:"text-gray-500",children:"undefined"});const d=typeof e;if(d==="string")return l("span",{className:"text-green-600",children:['"',e,'"']});if(d==="number")return n("span",{className:"text-blue-600",children:e});if(d==="boolean")return n("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?n("span",{className:"text-gray-600",children:"[]"}):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(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((m,u)=>n("div",{className:"py-0.5",children:n(On,{data:m,depth:t+1,defaultExpanded:r,maxDepth:s})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const m=Object.keys(e);if(m.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=p=>p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,h=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:[m.length,"}"]})]}),i?l(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:m.map(p=>{const f=e[p],y=u(f),g=h(f);return n("div",{className:"py-0.5",children:y?n(Ca,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:s}):g?n(Sa,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:s}):l(ue,{children:[l("span",{className:"text-orange-600",children:[p,": "]}),n(On,{data:f,depth:t+1,defaultExpanded:r,maxDepth:s})]})},p)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function Ca({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=_(s||r<2),c=Object.keys(t);return te(()=>{i(s||r<2)},[s,r]),l(ue,{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(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&l("span",{className:"text-gray-600",children:[c.length,"}"]})]}),o&&l(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:c.map(d=>{const m=t[d],u=m!==null&&typeof m=="object"&&!Array.isArray(m)&&Object.keys(m).length>0,h=Array.isArray(m)&&m.length>0;return n("div",{className:"py-0.5",children:u?n(Ca,{propertyKey:d,value:m,depth:r+1,defaultExpanded:s,maxDepth:a}):h?n(Sa,{propertyKey:d,value:m,depth:r+1,defaultExpanded:s,maxDepth:a}):l(ue,{children:[l("span",{className:"text-orange-600",children:[d,": "]}),n(On,{data:m,depth:r+2,defaultExpanded:s,maxDepth:a})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function Sa({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=_(s||r<2);return te(()=>{i(s||r<2)},[s,r]),l(ue,{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(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&l("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&l(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((c,d)=>{const m=c!==null&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,u=Array.isArray(c)&&c.length>0;return n("div",{className:"py-0.5",children:m?n(Ca,{propertyKey:d.toString(),value:c,depth:r+1,defaultExpanded:s,maxDepth:a}):u?n(Sa,{propertyKey:d.toString(),value:c,depth:r+1,defaultExpanded:s,maxDepth:a}):n(On,{data:c,depth:r+2,defaultExpanded:s,maxDepth:a})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function Ms({label:e,count:t,isActive:r,onClick:s,badgeColorActive:a,badgeTextActive:o}){return l("button",{onClick:s,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${a} ${o}`:"bg-gray-200 text-gray-700"}`,children:t}),r&&n("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function Io({label:e,isActive:t,onClick:r,disabled:s=!1}){return n("button",{onClick:r,className:`w-full text-left px-3 py-2.5 rounded-md transition-all text-sm cursor-pointer ${t?"bg-[#f6f9fc] text-[#005c75] font-medium border-l-2 border-[#005c75] pl-[10px]":"text-[#3e3e3e] hover:bg-gray-50"}`,disabled:s,children:e})}function Do({call:e,scenarioName:t}){const[r,s]=_(!1),[a,o]=_("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(" / ")},m=ne(()=>{var p,f,y,g,x;try{const v=JSON.parse(e.response);return(y=(f=(p=v.choices)==null?void 0:p[0])==null?void 0:f.message)!=null&&y.content?v.choices[0].message.content:(x=(g=v.content)==null?void 0:g[0])!=null&&x.text?v.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]),h=ne(()=>{var p;if(t)return t;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,t]);return l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>s(!r),children: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:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),h&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:h}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),l("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&n("span",{children:d(e.input_tokens,e.output_tokens)}),c(e.cost)&&n("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"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&l("div",{className:"border-t border-[#e1e1e1]",children:[l("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>o("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>o("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>o("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),a&&l("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[a==="system"&&n("div",{children:e.system_message?n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.system_message}):n("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),a==="prompt"&&n("div",{children:n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.prompt_text})}),a==="response"&&l("div",{children:[e.error&&l("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:m})]}),a==="props"&&n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),e.error&&!a&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:l("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const Lo=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function ox({entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a}){var N,w,S,C,k,E,A,I,j;const[o,i]=_("entity"),[c,d]=_("analysis"),[m,u]=_(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[h,p]=_("entity"),{entityLlmCalls:f,scenarioLlmCalls:y,totalLlmCalls:g}=ne(()=>{if(!a)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const P=[...a.entityCalls,...a.analysisCalls],$=P.filter(R=>R.object_type==="entity"||Lo.includes(R.prompt_type)),T=P.filter(R=>R.object_type!=="entity"&&!Lo.includes(R.prompt_type));return $.sort((R,J)=>J.created_at-R.created_at),T.sort((R,J)=>J.created_at-R.created_at),{entityLlmCalls:$,scenarioLlmCalls:T,totalLlmCalls:P.length}},[a]),x=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(N=e==null?void 0:e.metadata)==null?void 0:N.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(w=t==null?void 0:t.metadata)==null?void 0:w.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(C=(S=e==null?void 0:e.metadata)==null?void 0:S.isolatedDataStructure)==null?void 0:C.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(k=t==null?void 0:t.metadata)==null?void 0:k.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(E=e==null?void 0:e.metadata)==null?void 0:E.importedExports,"External Dependencies":(A=e==null?void 0:e.metadata)==null?void 0:A.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(I=t==null?void 0:t.metadata)==null?void 0:I.scenariosDataStructure,description:"Structure template used across all scenarios"}],v=x.filter(P=>P.data!==void 0&&P.data!==null).length;let b=null;if(o==="entity"){const P=x.find($=>$.id===c);P&&P.data!==void 0&&P.data!==null&&(b={title:P.title,description:P.description,data:P.data})}else if(o==="scenarios"&&m){const P=r.find($=>($.id||$.name)===m.scenarioId);P&&(b={title:P.name,description:P.description||"Scenario data and configuration",data:P.metadata})}return l("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:l("div",{className:"flex border-b border-gray-200 relative",children:[n(Ms,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(Ms,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(Ms,{label:"LLM Calls",count:g,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((j=t==null?void 0:t.metadata)==null?void 0:j.analyzerVersion)&&l("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?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 ${h==="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 ${h==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",y.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:h==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(P=>n(Do,{call:P},P.id)):y.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No scenario-level LLM calls found"})}):y.map(P=>n(Do,{call:P},P.id))})]}):l("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:o==="entity"?l(ue,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),v===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:x.map(P=>{const $=P.data!==void 0&&P.data!==null;return n(Io,{label:P.title,isActive:c===P.id,onClick:()=>d(P.id),disabled:!$},P.id)})})]}):l(ue,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"SCENARIOS"}),r.length===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No scenarios available."}):n("nav",{className:"space-y-1",children:r.map(P=>{const $=P.id||P.name,T=(m==null?void 0:m.scenarioId)===$;return n(Io,{label:P.name,isActive:T,onClick:()=>u({scenarioId:$})},$)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:b?n(ix,{title:b.title,description:b.description,data:b.data}):o==="scenarios"&&r.length===0?n(Oo,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:s}):o==="entity"?n(Oo,{title:"No Entity Data Yet",description:"Entity data structures will appear here after analysis is complete.",onAnalyze:s}):n("div",{className:"p-6 text-center py-12 text-gray-500",children:"Select a section to view data"})})]})]})}function Oo({title:e,description:t,onAnalyze:r}){return l("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[n("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),n("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:t}),r&&n("button",{onClick:r,className:"h-[54px] w-[183px] bg-[#005c75] text-white text-base font-medium rounded-lg border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]})}function ix({title:e,description:t,data:r}){const[s,a]=_(!0);return l(ue,{children:[l("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[n("h3",{className:"text-base font-semibold text-black m-0",children:e}),n("p",{className:"text-sm text-[#646464] mt-1 m-0",children:t})]}),l("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[l("div",{className:"flex gap-2",children:[n("button",{onClick:()=>a(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),n("button",{onClick:()=>a(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),n(_t,{content:JSON.stringify(r,null,2),label:"Copy JSON",copiedLabel:"Copied!",className:"px-4 h-8 bg-[#343434] hover:bg-[#232323] text-white text-sm font-medium rounded border-none transition-colors whitespace-nowrap"})]}),n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"p-6",children:r?n("div",{className:"bg-gray-50 rounded-lg p-3 overflow-x-auto",children:n(ax,{data:r,defaultExpanded:s,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function lx({entity:e,analysis:t,scenarios:r,onAnalyze:s}){const a=Le();return te(()=>{if(e!=null&&e.sha&&a.state==="idle"&&!a.data){const o=t!=null&&t.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;a.load(o)}},[e==null?void 0:e.sha,t==null?void 0:t.id,a.state,a.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(ox,{entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a.data})})}const cx={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},dx={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},ux=2e3,mx=e=>{var r;if(!e)return"typescript";switch((r=e.split(".").pop())==null?void 0:r.toLowerCase()){case"ts":case"tsx":return"typescript";case"js":case"jsx":return"javascript";case"json":return"json";case"css":return"css";default:return"typescript"}};function hx({entity:e,entityCode:t}){const r=$r(),s=be(null);return te(()=>{const a=r.hash;if(!a||!s.current)return;const o=a.match(/^#L(\d+)$/);if(!o)return;const i=parseInt(o[1],10);setTimeout(()=>{if(!s.current)return;const c=s.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)},[r.hash,t]),n("div",{ref:s,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:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),n("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e==null?void 0:e.filePath})]}),t&&n(_t,{content:t,label:"Copy Code",duration:ux,className:"px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] disabled:opacity-75 disabled:cursor-not-allowed"})]}),n("div",{className:"p-0",children:t?n("div",{className:"relative",children:n(id,{language:mx(e==null?void 0:e.filePath),style:ld,showLineNumbers:!0,customStyle:cx,lineNumberStyle:dx,wrapLines:!0,lineProps:a=>({"data-line-number":a,style:{display:"block"}}),children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const px=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function fx({currentParams:e,nextParams:t,currentUrl:r,nextUrl:s,formMethod:a,defaultShouldRevalidate:o}){return r.pathname===s.pathname&&r.search===s.search?o:!!(e.sha!==t.sha||a)}async function gx({params:e,request:t,context:r}){const{sha:s}=e;if(!s)throw new Response("Entity SHA is required",{status:400});const o=new URL(t.url).searchParams.get("from"),c=(e["*"]||"").split("/").filter(Boolean),d=c[0]||"scenarios",m=c[1]||null,u=c[2]||null,h=r.analysisQueue,p=h?h.getState():{paused:!1,jobs:[]},[f,y,g,x]=await Promise.all([Xt(s),$e(),yn(),Fu(he()||process.cwd())]),v=f?await Yr(f):null,b=f?await Pi(f.sha):null;let N={importedEntities:[],importingEntities:[]},w=null,S=[];f&&(N=await _i(f),w=await ji(f),S=await Ti(f));const C=!!(f&&S.length>0&&S[0].sha!==f.sha),k=S.length>0?S[0].sha:null,E=!!(S.length>0&&S[0].analyses&&S[0].analyses.length>0),A=f?await Mi(f):!1;return K({entity:f??void 0,analysis:v??void 0,currentEntityAnalysis:b??void 0,projectSlug:y,from:o,relatedEntities:N,entityCode:w??void 0,hasNewerVersion:C,newestEntitySha:k,newestVersionHasAnalysis:E,fileModifiedSinceEntity:A,history:S,tab:d,scenarioId:m,viewModeFromUrl:u,currentCommit:g,hasAnApiKey:x,queueState:p})}const yx=Je(function(){var Re,We,Yt,Qn,on,Ia,Da,La,Oa,Fa,za,Ba,Ya,Ua,Wa;const t=Ve(),a=(ni()["*"]||"").split("/").filter(Boolean),o=a[0]||"scenarios",i=a[1]||null,c=a[2]||null,d=t.entity,m=t.analysis,u=t.currentEntityAnalysis,h=u||m,p=t.projectSlug;t.from;const f=t.relatedEntities,y=t.entityCode,g=t.hasNewerVersion,x=t.newestEntitySha,v=t.newestVersionHasAnalysis,b=t.fileModifiedSinceEntity,N=t.history,w=t.currentCommit,S=t.hasAnApiKey,C=t.queueState;(Re=h==null?void 0:h.status)==null||Re.errors;const k=(h==null?void 0:h.scenarios)||[],E=k.filter(le=>{var je;return!((je=le.metadata)!=null&&je.sameAsDefault)}),A=k.filter(le=>{var je;return(je=le.metadata)==null?void 0:je.sameAsDefault}),I=St(),j=be(null);te(()=>{j.current===null&&(j.current=window.history.length)},[]);const P=()=>{if(typeof window>"u")return;const le=window.history.state;if(le===null||(le==null?void 0:le.idx)===void 0||(le==null?void 0:le.idx)===0)I("/");else{const je=window.history.length,et=j.current;if(et!==null&&je>et){const Fe=je-et+1;I(-Fe)}else I(-1)}},$=!!C.currentlyExecuting,T=o,R=(We=w==null?void 0:w.metadata)==null?void 0:We.currentRun,J=!!(R!=null&&R.createdAt)&&!(R!=null&&R.analysisCompletedAt),q=!!(d!=null&&d.sha&&((Yt=R==null?void 0:R.currentEntityShas)!=null&&Yt.includes(d.sha))),Y=!!(d!=null&&d.sha&&((on=(Qn=C.currentlyExecuting)==null?void 0:Qn.entityShas)!=null&&on.includes(d.sha))),H=!!(d!=null&&d.sha&&((Ia=C.jobs)!=null&&Ia.some(le=>{var je;return(je=le.entityShas)==null?void 0:je.includes(d.sha)}))),B=q||Y||H,D=B&&((Da=h==null?void 0:h.status)==null?void 0:Da.finishedAt)!=null&&E.length>0&&h.entitySha!==(d==null?void 0:d.sha),M=ne(()=>{if(T!=="scenarios")return null;if(i){const le=E.find(je=>je.id===i);if(le)return le}return E.length>0&&!B?E[0]:null},[T,i,E,B]),Q=((Fa=(Oa=(La=M==null?void 0:M.metadata)==null?void 0:La.executionResult)==null?void 0:Oa.error)==null?void 0:Fa.message)||((Ya=(Ba=(za=h==null?void 0:h.status)==null?void 0:za.errors)==null?void 0:Ba[0])==null?void 0:Ya.message);yt({source:M?"scenario-page":"entity-page",entitySha:d==null?void 0:d.sha,scenarioId:M==null?void 0:M.id,analysisId:h==null?void 0:h.id,entityName:d==null?void 0:d.name,entityType:d==null?void 0:d.entityType,scenarioName:M==null?void 0:M.name,errorMessage:Q});const[U,F]=_(()=>c&&c!=="edit"?c:(d==null?void 0:d.entityType)==="library"?"data":"screenshot");te(()=>{c&&c!==U&&c!=="edit"&&F(c)},[c]);const X=c==="edit",[z,L]=_(!1),[W,V]=_(!1),[Z,ce]=_(null),[ve,ae]=_(!1),[me,Se]=_(!1),[Ne,Ae]=_(null),[De,Oe]=_(null),[Ee,re]=_(0),{interactiveServerUrl:ye,isStarting:ke,isLoading:rt,showIframe:fe,iframeKey:He,onIframeLoad:Ue}=nn({analysisId:h==null?void 0:h.id,scenarioId:M==null?void 0:M.id,scenarioName:M==null?void 0:M.name,projectSlug:p,enabled:X&&!!M,refreshTrigger:Ee}),[Ze,Hn]=_(!1),[Ra,Vn]=_(""),[rn,Xe]=_(!1),[qn,xt]=_(Date.now()),[vn,sn]=_(!1),st=Le(),dt=Le(),Ge=Le(),ze=ft(),Gn=C.jobs.some(le=>{var je;return(d==null?void 0:d.sha)&&((je=le.entityShas)==null?void 0:je.includes(d.sha))||le.type==="analysis"&&le.commitSha===(w==null?void 0:w.sha)&&le.entityShas&&le.entityShas.length===0}),wn=B,an=((Ua=d==null?void 0:d.metadata)==null?void 0:Ua.defaultWidth)||((Wa=h==null?void 0:h.metadata)==null?void 0:Wa.defaultWidth)||1440,Nn=Math.round(an*(900/1440));st.state==="submitting"||st.state,ne(()=>{var le;return!!((le=M==null?void 0:M.metadata)!=null&&le.interactiveExamplePath)},[M]);const{isCompleted:Kn}=Et(p,rn);te(()=>{st.state==="idle"&&st.data&&(st.data.success?setTimeout(()=>{xt(Date.now()),ze.revalidate(),Xe(!1)},1500):st.data.error&&(Xe(!1),alert(`Recapture failed: ${st.data.error}`)))},[st.state,st.data,ze]),te(()=>{rn&&Kn&&setTimeout(()=>{xt(Date.now()),ze.revalidate(),Xe(!1)},1500)},[rn,Kn,ze]),te(()=>{dt.state==="idle"&&dt.data&&(dt.data.success?setTimeout(()=>{xt(Date.now()),ze.revalidate(),Xe(!1)},1500):dt.data.error&&(Xe(!1),alert(`Recapture failed: ${dt.data.error}`)))},[dt.state,dt.data,ze]);const Cn=()=>{d&&(g&&x&&x!==d.sha?(I(`/entity/${x}/scenarios`),setTimeout(()=>{Ge.submit({entitySha:x,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})},100)):Ge.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"}))};te(()=>{Ge.state==="idle"&&Ge.data&&(Ge.data.success?ze.revalidate():Ge.data.error&&alert(`Analysis failed: ${Ge.data.error}`))},[Ge.state,Ge.data,d==null?void 0:d.sha,ze]),te(()=>{const le=setTimeout(()=>{ze.revalidate()},500);return()=>clearTimeout(le)},[]),te(()=>{if(J||wn){const le=setInterval(()=>{ze.revalidate()},3e3);return()=>clearInterval(le)}},[J,wn,ze]);const os=(le,je)=>le==="scenarios"?`/entity/${d==null?void 0:d.sha}/scenarios`:`/entity/${d==null?void 0:d.sha}/${le}`,is=(le,je)=>`/entity/${d==null?void 0:d.sha}/scenarios/${le}/${je}`,ls=le=>{F(le),M!=null&&M.id&&(le==="interactive"?I(`/entity/${d==null?void 0:d.sha}/scenarios/${M.id}/fullscreen`,{replace:!0}):I(is(M.id,le),{replace:!0}))},cs=async le=>{var je,et;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:le,hasSelectedScenario:!!M,hasAnalysis:!!h}),!M||!h){const Fe="Error: No scenario or analysis available";console.error("[EntityDetail]",Fe),ce(Fe);return}L(!0),ce(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:le,scenarioId:M.id,scenarioName:M.name,currentData:M.data});try{const Fe=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:le,existingScenarios:h.scenarios,scenariosDataStructure:(je=h.metadata)==null?void 0:je.scenariosDataStructure,editingMockName:M.name,editingMockData:De||((et=M.metadata)==null?void 0:et.data)})}),bt=await Fe.json();if(!Fe.ok||!bt.success)throw new Error(bt.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",bt.data),Oe(bt.data);const Zn=(h.scenarios||[]).map(Qe=>Qe.id===M.id?{...Qe,metadata:{...Qe.metadata,data:bt.data}}:Qe),Sn=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:h,scenarios:Zn})}),at=await Sn.json();if(!Sn.ok||!at.success)throw console.error("[EntityDetail] Temp save failed:",at),new Error(at.error||"Failed to apply preview");if(ce("Generating preview. Capturing screenshot..."),ye){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:ye});const Qe=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:ye,scenarioId:M.id,projectId:h.projectId,viewportWidth:1440})}),kn=await Qe.json();!Qe.ok||!kn.success?(console.error("[EntityDetail] Direct capture failed:",kn),ce("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),ce('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Qe=new FormData;Qe.append("analysisId",h.id||""),Qe.append("scenarioId",M.id||"");const kn=await fetch("/api/recapture-scenario",{method:"POST",body:Qe}),us=await kn.json();!kn.ok||!us.success?(console.warn("[EntityDetail] Recapture failed:",us.error),ce("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",us.jobId),ce('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}re(Qe=>Qe+1),ze.revalidate()}catch(Fe){console.error("Error applying changes:",Fe),ce(`Error: ${Fe instanceof Error?Fe.message:String(Fe)}`)}finally{L(!1)}},ut=async(le,je)=>{var et;if(!M||!h){ce("Error: No scenario or analysis available");return}V(!0),ce(null),console.log("[EntityDetail] Saving scenario to database",{description:le,saveAsNew:je});try{const Fe=De||((et=M.metadata)==null?void 0:et.data);let bt;if(je){const at={...M,id:`${M.name}-${Date.now()}`,name:`${M.name} (Copy)`,metadata:{...M.metadata,data:Fe},description:le||M.description};bt=[...h.scenarios||[],at]}else bt=(h.scenarios||[]).map(at=>at.id===M.id?{...at,metadata:{...at.metadata,data:Fe},description:le||at.description}:at);const Zn=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:h,scenarios:bt})}),Sn=await Zn.json();if(!Zn.ok||!Sn.success)throw new Error(Sn.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),ce(je?"New scenario created successfully":"Scenario saved successfully"),Oe(null),ze.revalidate()}catch(Fe){console.error("Error saving scenario:",Fe),ce(`Error: ${Fe instanceof Error?Fe.message:String(Fe)}`)}finally{V(!1)}},ds=()=>{M!=null&&M.id&&(d!=null&&d.sha)&&I(`/entity/${d.sha}/scenarios/${M.id}/dev`)},se=async()=>{var le;if(!(M!=null&&M.id)){Ae("Cannot delete scenario without ID");return}ae(!0),Ae(null);try{const je=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:M.id,screenshotPaths:((le=M.metadata)==null?void 0:le.screenshotPaths)||[]})}),et=await je.json();if(!je.ok||!et.success)throw new Error(et.error||"Failed to delete scenario");I(`/entity/${d==null?void 0:d.sha}/scenarios`)}catch(je){console.error("[EntityDetail] Error deleting scenario:",je),Ae(je instanceof Error?je.message:"Failed to delete scenario"),Se(!1)}finally{ae(!1)}},pe=h&&d&&h.entitySha!==d.sha,_e=d?Qy(d):!1;return n(Zr,{children:l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children: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:[n("button",{onClick:P,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:d==null?void 0:d.name}),n("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})]}),n("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:E.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(le=>n(de,{to:os(le.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${T===le.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:T===le.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[le.label,le.count!==void 0&&le.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${T===le.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:le.count})]})},le.id))})]})}),(g||pe&&!u||b&&_e)&&!B&&!Gn&&n("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:[n("svg",{className:"w-4 h-4",style:{color:"#714A25"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),n("span",{className:"text-sm font-semibold",style:{color:"#714A25"},children:pe&&!g?"This entity version has not been analyzed yet.":"This entity has been recently changed."}),n("span",{className:"text-sm",style:{color:"#714A25"},children:g?"You are viewing an older version. A newer version is available.":pe?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),g&&x&&v?n(de,{to:`/entity/${x}/scenarios`,className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono cursor-pointer transition-colors no-underline",style:{backgroundColor:"#C69538"},onMouseEnter:le=>{le.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:le=>{le.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:Cn,disabled:Ge.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:le=>{Ge.state==="idle"&&(le.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:le=>{Ge.state==="idle"&&(le.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),l("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[T==="scenarios"&&l(ue,{children:[X&&M?n(Xy,{scenario:M,entitySha:(d==null?void 0:d.sha)||"",onApply:cs,onSave:ut,onEditMockData:ds,onDelete:se,isApplying:z,isSaving:W,saveMessage:Z,showDeleteConfirm:me,onShowDeleteConfirm:Se,isDeleting:ve,deleteError:Ne}):n(Zy,{scenarios:E,hiddenScenarios:A,analysis:h,selectedScenario:M,entitySha:(d==null?void 0:d.sha)||"",cacheBuster:qn,activeTab:T,entityType:d==null?void 0:d.entityType,entity:d,queueState:C,processIsRunning:$,isEntityAnalyzing:B,areScenariosStale:D,viewMode:U,setViewMode:ls,isBreakdownView:i==="breakdown"}),i==="breakdown"?n(tx,{analysis:h??null,entitySha:(d==null?void 0:d.sha)||""}):X&&M?n(Xr,{scenarioId:M.id||M.name,scenarioName:M.name,iframeUrl:ye,isStarting:ke,isLoading:rt,showIframe:fe,iframeKey:He,onIframeLoad:Ue,projectSlug:p,defaultWidth:1440,defaultHeight:900}):l("div",{className:"flex flex-col flex-1 min-h-0",children:[M&&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:[n("span",{className:"text-xs font-semibold text-[#343434]",children:M.name}),l("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[an," × ",Nn]})]}),l("div",{className:"flex items-center gap-2",children:[n(de,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${M.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:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"})}),"Download"]}),l(de,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${M.id}/dev`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Dev Mode - Live preview with data editor and code sync",children:[l("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n("polyline",{points:"16 18 22 12 16 6"}),n("polyline",{points:"8 6 2 12 8 18"})]}),"Dev Mode"]}),l(de,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${M.id}/fullscreen`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Interactive Mode",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:n("path",{d:"M8 5v14l11-7z"})}),"Interactive Mode"]})]})]}),n(Ml,{selectedScenario:M,analysis:h,entity:d,viewMode:U,cacheBuster:qn,hasScenarios:E.length>0,isAnalyzing:wn,projectSlug:p,hasAnApiKey:S,processIsRunning:$,queueState:C})]})]}),T==="related"&&n(sx,{relatedEntities:f}),T==="data"&&n(lx,{entity:d,analysis:h,scenarios:E,onAnalyze:Cn}),T==="code"&&n(hx,{entity:d,entityCode:y}),T==="history"&&n(nx,{entity:d,history:N})]}),vn&&p&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>sn(!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:le=>le.stopPropagation(),children:[l("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>sn(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(Dt,{projectSlug:p,onClose:()=>sn(!1)})})]})})]})})}),xx=Object.freeze(Object.defineProperty({__proto__:null,default:yx,loader:gx,meta:px,shouldRevalidate:fx},Symbol.toStringTag,{value:"Module"}));async function bx(e){const{entityShas:t,filePaths:r,context:s,scenarioCount:a,queue:o}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await Ye();const i=he();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const c=ee.join(i,".codeyam","config.json"),d=JSON.parse(await xe.readFile(c,"utf8")),{projectSlug:m,branchId:u}=d;if(!m||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${m}, Branch: ${u}`);const h=Jr(m);try{await xe.writeFile(h,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:p,branch:f}=await Ie(m);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const y=await lt({shas:t});if(!y||y.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);let g=r;if((!g||g.length===0)&&(g=[...new Set(y.map(b=>b.filePath).filter(b=>!!b))],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 x=await Du(p,f,g);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await It({commitSha:x.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:b=>{if(!b)return;const N=b.currentRun;if(N&&N.id&&N.archivedAt)return;N&&(N.analysesCompleted&&N.analysesCompleted>0||N.capturesCompleted&&N.capturesCompleted>0)&&Vu(b)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:v}=o.enqueue({type:"analysis",commitSha:x.sha,projectSlug:m,filePaths:g,entityShas:t,entityNames:y.map(b=>b.name),...s?{context:s}:{},...a?{scenarioCount:a}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${v} for ${t.length} entities`),{jobId:v}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function vx({request:e,context:t}){if(e.method!=="POST")return K({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await jt()),!r)return K({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("entitySha"),o=s.get("entityShas"),i=s.get("filePath"),c=s.get("context"),d=s.get("scenarioCount");let m;if(o)m=o.split(",").filter(Boolean);else if(a)m=[a];else return K({error:"Missing required field: entitySha or entityShas"},{status:400});if(m.length===0)return K({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${m.length} entity(ies)`);const u=await lt({shas:m}),p=[...new Set(u.map(y=>y.filePath).filter(y=>!!y))].length,{jobId:f}=await bx({entityShas:m,filePaths:i?[i]:void 0,context:c||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),K({success:!0,message:`Analysis queued for ${m.length} entity(ies)`,entityCount:m.length,fileCount:p,jobId:f})}catch(s){return console.error("[API] Error starting analysis:",s),K({error:"Failed to start analysis",details:s.message},{status:500})}}const wx=Object.freeze(Object.defineProperty({__proto__:null,action:vx},Symbol.toStringTag,{value:"Module"}));function Nx(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:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function Tl(e){if(!e)return"Never";const t=new Date(e),r=new Date;if(t.getDate()===r.getDate()&&t.getMonth()===r.getMonth()&&t.getFullYear()===r.getFullYear()){const a=t.getHours(),o=t.getMinutes(),i=a>=12?"pm":"am",c=a%12||12,d=o.toString().padStart(2,"0");return`Today, ${c}:${d} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function ot(e,t=[],r=!1){var u,h;if(t.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 r?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const a=e.analyses[0];if(!(((u=a.status)==null?void 0:u.scenarios)&&a.status.scenarios.length>0&&a.status.scenarios.some(p=>p.screenshotFinishedAt||p.finishedAt))||a.entitySha!==e.sha)return"not-analyzed";const i=a.createdAt?new Date(a.createdAt).getTime():0,c=(h=e.metadata)!=null&&h.editedAt?new Date(e.metadata.editedAt).getTime():0,d=a.scenarios||[],m=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&&m?d.every(f=>{var y,g,x;return((g=(y=f.metadata)==null?void 0:y.screenshotPaths)==null?void 0:g[0])||((x=f.metadata)==null?void 0:x.executionResult)})?"up-to-date":"incomplete":d.length>0?"incomplete":"not-analyzed":"out-of-date"}const Cx=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function Sx({request:e,context:t}){try{const r=t.analysisQueue,s=r?r.getState():{paused:!1,jobs:[]},a=await tn();return K({entities:a||[],queueState:s})}catch(r){return console.error("Failed to load simulations:",r),K({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const kx=Je(function(){const t=Ve(),r=t.entities,s=t.queueState;yt({source:"simulations-page"});const[a,o]=_(""),[i,c]=_("visual"),d=ne(()=>{const g=[];return r.forEach(x=>{var b;const v=(b=x.analyses)==null?void 0:b[0];if(v!=null&&v.scenarios){const N=v.scenarios.filter(w=>{var S;return!((S=w.metadata)!=null&&S.sameAsDefault)}).map(w=>{var j,P,$,T,R;const S=(P=(j=w.metadata)==null?void 0:j.screenshotPaths)==null?void 0:P[0],C=($=w.metadata)==null?void 0:$.noScreenshotSaved,k=S&&!C,E=(R=(T=v.status)==null?void 0:T.scenarios)==null?void 0:R.find(J=>J.name===w.name),A=E&&E.screenshotStartedAt&&!E.screenshotFinishedAt;let I;return k?I="completed":A?I="capturing":I="error",{scenarioName:w.name,scenarioDescription:w.description||"",screenshotPath:S||"",scenarioId:w.id,state:I}}).filter(w=>w.state==="completed"||w.state==="capturing");N.length>0&&g.push({entity:x,screenshots:N,createdAt:v.createdAt||""})}}),g.sort((x,v)=>new Date(v.createdAt).getTime()-new Date(x.createdAt).getTime()),g},[r]),m=ne(()=>r.filter(g=>{var b,N;const x=(b=g.analyses)==null?void 0:b[0];return!((N=x==null?void 0:x.scenarios)==null?void 0:N.some(w=>{var S,C;return(C=(S=w.metadata)==null?void 0:S.screenshotPaths)==null?void 0:C[0]}))}),[r]),u=ne(()=>d.filter(({entity:g})=>{const x=!a||g.name.toLowerCase().includes(a.toLowerCase()),v=i==="all"||g.entityType===i;return x&&v}),[d,a,i]),h=ne(()=>m.filter(g=>{const x=!a||g.name.toLowerCase().includes(a.toLowerCase()),v=i==="all"||g.entityType===i;return x&&v}),[m,a,i]),p=oe(g=>{o(g.target.value)},[]),f=oe(g=>{c(g.target.value)},[]),y=d.length>0;return n("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:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!y&&n("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."," ",n("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:[n("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:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(ct,{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:[n(Fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-3 text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:a,onChange:p})]})]})]}),y&&u.length>0&&n("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:[n("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:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children: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.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:u.reduce((g,{screenshots:x})=>g+x.length,0)})," ","scenarios"]})]})}),l("div",{className:"flex flex-col gap-3",children:[y&&(u.length===0?n("div",{className:"bg-white border border-gray-200 rounded-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):n(ue,{children:u.map(({entity:g,screenshots:x})=>n(Ex,{entity:g,screenshots:x,queueJobs:(s==null?void 0:s.jobs)||[]},g.sha))})),!y&&(h.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No components found matching your filters."}):h.map(g=>n(Ax,{entity:g},g.sha)))]})]})})});function Ex({entity:e,screenshots:t,queueJobs:r}){var f,y,g;const s=St(),a=Le(),[o,i]=_(!1),c=t.length||(((g=(y=(f=e.analyses)==null?void 0:f[0])==null?void 0:y.scenarios)==null?void 0:g.length)??0),d=x=>{s(`/entity/${e.sha}/scenarios/${x}?from=simulations`)},m=()=>{i(!0),a.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};te(()=>{a.state==="idle"&&o&&i(!1)},[a.state,o]);const u=ot(e,r),h=Nx(u),p=u==="out-of-date";return n("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:[n("div",{className:"flex-shrink-0",children:n(tt,{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(de,{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,")"]}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:h.bgColor,color:h.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:h.text})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),l("div",{className:"flex-shrink-0 flex items-center gap-2",children:[p&&n(ue,{children:o||a.state!=="idle"?l("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[n(ht,{size:14,className:"animate-spin",style:{color:"#be185d"}}),n("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):n("button",{onClick:m,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#005c75",color:"#ffffff",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#004d5e"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#005c75"},children:"Re-analyze"})}),n("button",{onClick:()=>void s(`/entity/${e.sha}/logs`),className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})]})]}),n("div",{className:"border-t border-gray-200"}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:t.length>0?t.map(x=>l("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>d(x.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:x.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:x.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:v=>{x.state==="completed"&&(v.currentTarget.style.borderColor="#005C75",v.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:v=>{v.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",v.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(qe,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(Na,{size:"medium"}):null})}),l("div",{className:"relative group",children:[n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.scenarioName}),n("div",{className:"fixed hidden group-hover:block pointer-events-none",style:{zIndex:1e4,transform:"translateY(8px)"},children: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:[x.scenarioName,x.scenarioDescription&&l(ue,{children:[": ",x.scenarioDescription]}),n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-100 border-l border-t border-gray-200 transform rotate-45"})]})})]})]},x.scenarioId)):n("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function Ax({entity:e}){const t=Le(),[r,s]=_(!1),a=()=>{s(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return te(()=>{t.state==="idle"&&r&&s(!1)},[t.state,r]),n("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:a,children: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:[n(tt,{type:e.entityType}),l("div",{className:"min-w-0",children:[l("div",{className:"flex items-center gap-3 mb-0.5",children:[n(de,{to:`/entity/${e.sha}`,className:"text-sm font-medium text-gray-900 no-underline",children:e.name}),n("span",{className:"text-[10px] font-semibold px-1 py-0.5 rounded",style:{color:e.entityType==="visual"?"#7c3aed":e.entityType==="library"?"#0DBFE9":e.entityType==="type"?"#dc2626":e.entityType==="data"?"#2563eb":e.entityType==="index"?"#ea580c":e.entityType==="functionCall"?"#7c3aed":e.entityType==="class"?"#059669":e.entityType==="method"?"#0891b2":"#6b7280",backgroundColor:e.entityType==="visual"?"#f3e8ff":e.entityType==="library"?"#cffafe":e.entityType==="type"?"#fee2e2":e.entityType==="data"?"#dbeafe":e.entityType==="index"?"#ffedd5":e.entityType==="functionCall"?"#f3e8ff":e.entityType==="class"?"#d1fae5":e.entityType==="method"?"#cffafe":"#f3f4f6"},children:e.entityType?e.entityType.toUpperCase():"UNKNOWN"})]}),n("div",{className:"text-xs text-gray-400 truncate",children:e.filePath})]})]}),n("div",{className:"w-32 flex justify-center",children:n("span",{className:"text-[10px] text-gray-500 bg-gray-100 px-2 py-1 rounded",children:"Not analyzed"})}),n("div",{className:"w-32 text-center text-[10px] text-gray-500",children:Tl(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.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:[n(ht,{size:14,className:"animate-spin"}),"Analyzing..."]}):n("button",{onClick:a,className:"bg-[#e0e9ec] text-[#005c75] px-4 py-1.5 rounded text-xs font-medium hover:bg-[#d0dde1] transition-colors cursor-pointer",children:"Analyze"})})]})})}const Px=Object.freeze(Object.defineProperty({__proto__:null,default:kx,loader:Sx,meta:Cx},Symbol.toStringTag,{value:"Module"}));function _x({request:e,context:t}){const r=t.dbNotifier||Ct;if(!r)return console.error("[SSE] ERROR: dbNotifier not found in context or global!"),new Response("Server configuration error",{status:500});r.start().catch(()=>{});const s=new ReadableStream({start(a){const o=new TextEncoder;a.enqueue(o.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
300
|
+
|
|
301
|
+
`)),Math.random().toString(36).substring(7);let i=!1;const c=()=>{if(!i){i=!0,r.off("change",d),clearInterval(m);try{a.close()}catch{}}},d=u=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
|
|
302
|
+
|
|
303
|
+
`))}catch{c()}};r.on("change",d);const m=setInterval(()=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
304
|
+
|
|
305
|
+
`))}catch{c()}},3e4);e.signal.addEventListener("abort",c)}});return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const jx=Object.freeze(Object.defineProperty({__proto__:null,loader:_x},Symbol.toStringTag,{value:"Module"}));function Mx(){return new Response(JSON.stringify({status:"ok",version:pa,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const Tx=Object.freeze(Object.defineProperty({__proto__:null,loader:Mx},Symbol.toStringTag,{value:"Module"}));function ka(e){const t=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,r=e.match(t);if(!r)return{frontmatter:{},body:e};const s=r[1],a=r[2],o={},i=s.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/),c=s.match(/paths:\s*\[([^\]]*)\]/);i&&i[1].trim()?o.paths=i[1].split(`
|
|
306
|
+
`).filter(m=>m.trim().startsWith("-")).map(m=>m.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean):c&&(o.paths=c[1].split(",").map(m=>m.replace(/['"]/g,"").trim()).filter(Boolean));const d=s.match(/^category:\s*(.+)$/m);return d&&(o.category=d[1].replace(/['"]/g,"").trim()),{frontmatter:o,body:a}}async function ss(e,t=""){const r=[];try{const s=await xe.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){const i=await ss(ee.join(e,a.name),o);r.push(...i)}else a.isFile()&&a.name.endsWith(".md")&&r.push(o)}}catch{}return r}async function Jn(e){const t=await ss(e),r=[];for(const s of t){const a=ee.join(e,s);try{const o=await xe.readFile(a,"utf-8"),{frontmatter:i,body:c}=ka(o);r.push({filePath:s,absolutePath:a,frontmatter:i,body:c})}catch{}}return r}function $l(e){const t=ee.posix.dirname(e.filePath);return!t||t==="."?null:`${t}/**`}function Rl(e,t){if(t.frontmatter.paths&&t.frontmatter.paths.length>0)return t.frontmatter.paths.some(s=>Fs(e,s,{matchBase:!0}));const r=$l(t);return r?Fs(e,r,{matchBase:!0}):!1}function $x(e,t){return(!e.frontmatter.paths||e.frontmatter.paths.length===0)&&!$l(e)?[]:t.filter(r=>Rl(r,e))}const Rx=new Set(["node_modules",".git","dist",".codeyam",".claude","build","coverage"]);async function Ea(e){const t=[];async function r(s,a){try{const o=await we.readdir(s,{withFileTypes:!0});for(const i of o){const c=O.join(s,i.name),d=a?`${a}/${i.name}`:i.name;i.isDirectory()&&Rx.has(i.name)||(i.isDirectory()?await r(c,d):i.isFile()&&t.push(d))}}catch{}}return await r(e,""),t}const Ix="codeyam-rule-state.json",Ts=1;function Il(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return Bn.createHash("sha256").update(t).digest("hex")}function Dl(e){return ee.join(e,".claude",Ix)}async function Ll(e){const t=Dl(e);try{const r=await xe.readFile(t,"utf-8"),s=JSON.parse(r);return s.version!==Ts?(console.warn(`[ruleState] Unknown version ${s.version}, using empty state`),{version:Ts,rules:{}}):s}catch{return{version:Ts,rules:{}}}}async function Ol(e,t){const r=Dl(e),s=ee.dirname(r);await xe.mkdir(s,{recursive:!0}),await xe.writeFile(r,JSON.stringify(t,null,2)+`
|
|
307
|
+
`,"utf-8")}async function Aa(e,t){const r=await Ll(e),s=new Set(t.map(a=>a.filePath));for(const a of Object.keys(r.rules))s.has(a)||delete r.rules[a];for(const a of t){const o=await xe.readFile(a.absolutePath,"utf-8"),i=Il(o),c=r.rules[a.filePath];c?c.contentHash!==i&&(r.rules[a.filePath]={...c,contentHash:i,reviewed:!1}):r.rules[a.filePath]={contentHash:i,reviewed:!1}}return await Ol(e,r),r}async function Fo(e,t,r,s){const a=await Ll(e);if(r){const o=ee.join(e,".claude","rules"),i=ee.join(o,t),c=await xe.readFile(i,"utf-8"),d=Il(c);a.rules[t]?(a.rules[t].reviewed=!0,a.rules[t].contentHash=d):a.rules[t]={contentHash:d,reviewed:!0}}else a.rules[t]&&(a.rules[t].reviewed=!1);await Ol(e,a)}function Pa(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function Fl(e,t=""){const r=[],s=await xe.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;a.isDirectory()?r.push(...await Fl(ee.join(e,a.name),o)):a.name.endsWith(".md")&&r.push(o)}return r}function _r(e){if(!e||e==="(diff not available)")return!1;const t=e.split(`
|
|
308
|
+
`).filter(s=>!(!s.startsWith("+")&&!s.startsWith("-")||s.startsWith("+++")||s.startsWith("---"))).map(s=>s.substring(1).trim());if(t.length===0)return!1;const r=/^(category:\s*\w+)$/;return t.every(s=>r.test(s))}async function Dx({request:e}){const t=he();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=new URL(e.url),s=r.searchParams.get("action"),a=ee.join(t,".claude","rules");if(s==="recent-changes")return Ox(t,a);if(s==="reviewed-status")return zx(t,a);if(s==="audit")return Bx(t,a);if(s==="source-files")return Yx(t);if(s==="rule-coverage")return Ux(t,a);if(s==="rule-diff"){const o=r.searchParams.get("filePath");return o?Fx(t,o):Response.json({error:"Missing required parameter: filePath"},{status:400})}if(s==="rules-for-path"){const o=r.searchParams.get("path");return o?Wx(a,o):Response.json({error:"Missing required parameter: path"},{status:400})}try{const o=await ss(a),i=[];for(const u of o){const h=ee.join(a,u);try{const p=await xe.readFile(h,"utf-8"),f=await xe.stat(h),{frontmatter:y,body:g}=ka(p);i.push({filePath:u,content:p,frontmatter:y,body:g,lastModified:f.mtime.toISOString()})}catch{}}i.sort((u,h)=>new Date(h.lastModified).getTime()-new Date(u.lastModified).getTime());let c=i.length>0;if(!c)try{await xe.access(ee.join(t,".claude","codeyam-rule-state.json")),c=!0}catch{}const d=await Jn(a),m={};if(d.length>0){const u=await Aa(t,d);for(const h of d)m[h.filePath]=Pa(u,h.filePath)}return Response.json({memories:i,memoryInitialized:c,reviewedStatus:m})}catch(o){return console.error("[API] Error loading memories:",o),Response.json({error:"Failed to load memories",details:o instanceof Error?o.message:String(o),memoryInitialized:!1},{status:500})}}async function Lx(e,t){const r=[];try{const s=t("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const a of s.split(`
|
|
309
|
+
`).filter(Boolean)){const o=a.substring(0,2);let i=a.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const c=o[0],d=o[1];let m=[i];if(i.endsWith("/")&&c==="?"){const u=ee.join(e,i);try{m=(await Fl(u)).map(p=>i+p)}catch{continue}}for(const u of m){if(u.endsWith("/"))continue;const h=u.replace(".claude/rules/","");let p="modified";c==="A"||c==="?"?p="added":c==="D"||d==="D"?p="deleted":(c==="M"||d==="M")&&(p="modified");let f="";try{if(p==="deleted")f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(p==="added"&&c==="?"){const y=`${e}/${u}`;try{const g=await xe.readFile(y,"utf-8");f=`diff --git a/${u} b/${u}
|
|
310
|
+
new file mode 100644
|
|
311
|
+
--- /dev/null
|
|
312
|
+
+++ b/${u}
|
|
313
|
+
@@ -0,0 +1,${g.split(`
|
|
314
|
+
`).length} @@
|
|
315
|
+
${g.split(`
|
|
316
|
+
`).map(x=>"+"+x).join(`
|
|
317
|
+
`)}`}catch{f="(content not available)"}}else f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});f.length>5e3&&(f=f.substring(0,5e3)+`
|
|
318
|
+
... (truncated)`)}catch{f="(diff not available)"}p==="modified"&&_r(f)||r.push({filePath:h,changeType:p,diff:f})}}}catch{}return r}async function Ox(e,t){try{const{execSync:r}=await import("child_process"),s=[],a=await Jn(t),o={};if(a.length>0){const u=await Aa(e,a);for(const h of a)o[h.filePath]=Pa(u,h.filePath)}const c=(await Lx(e,r)).filter(u=>!o[u.filePath]);c.length>0&&s.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:c});const m=r('git log --format="%H|%aI|%s" --since="60 days ago" -- .claude/rules/ 2>/dev/null || true',{cwd:e,encoding:"utf-8",maxBuffer:10*1024*1024}).split(`
|
|
319
|
+
`).filter(Boolean).slice(0,20);for(const u of m){const[h,p,...f]=u.split("|"),y=f.join("|");if(!h||!p)continue;const g=r(`git diff-tree --no-commit-id --name-status -r ${h} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),x=[];for(const v of g.split(`
|
|
320
|
+
`).filter(Boolean)){const[b,N]=v.split(" ");if(!N||!N.startsWith(".claude/rules/"))continue;const w=N.replace(".claude/rules/","");let S="modified";if(b==="A"?S="added":b==="D"&&(S="deleted"),o[w])continue;let C="";try{C=r(`git show ${h} --format="" -- "${N}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),C.length>5e3&&(C=C.substring(0,5e3)+`
|
|
321
|
+
... (truncated)`)}catch{C="(diff not available)"}S==="modified"&&_r(C)||x.push({filePath:w,changeType:S,diff:C})}x.length>0&&s.push({commitHash:h.substring(0,8),date:p,message:y,files:x})}return Response.json({changes:s,reviewedStatus:o})}catch(r){return console.error("[API] Error getting recent changes:",r),Response.json({changes:[],reviewedStatus:{}})}}async function Fx(e,t){try{const{execSync:r}=await import("child_process"),s=`.claude/rules/${t}`,a=r(`git rev-list --count HEAD -- "${s}" 2>/dev/null || echo 0`,{cwd:e,encoding:"utf-8"}),o=parseInt(a.trim(),10)||0,i=r(`git diff HEAD -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});if(i.trim()){if(_r(i))return Response.json({diff:null});const g=i.length>5e3?i.substring(0,5e3)+`
|
|
322
|
+
... (truncated)`:i;return Response.json({diff:{diff:g,commitMessage:"Uncommitted changes",date:new Date().toISOString(),isUncommitted:!0,commitCount:o}})}if(r(`git status --porcelain -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim().startsWith("?")){const g=ee.join(e,s);try{const x=await xe.readFile(g,"utf-8"),v=`diff --git a/${s} b/${s}
|
|
323
|
+
new file mode 100644
|
|
324
|
+
--- /dev/null
|
|
325
|
+
+++ b/${s}
|
|
326
|
+
@@ -0,0 +1,${x.split(`
|
|
327
|
+
`).length} @@
|
|
328
|
+
${x.split(`
|
|
329
|
+
`).map(b=>"+"+b).join(`
|
|
330
|
+
`)}`;return Response.json({diff:{diff:v.length>5e3?v.substring(0,5e3)+`
|
|
331
|
+
... (truncated)`:v,commitMessage:"New file (untracked)",date:new Date().toISOString(),isUncommitted:!0,commitCount:0}})}catch{}}const m=r(`git log -1 --format="%H|%aI|%s" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim();if(!m)return Response.json({diff:null});const[u,h,...p]=m.split("|"),f=p.join("|");if(!u||!h)return Response.json({diff:null});let y=r(`git show ${u} --format="" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});return y.trim()?_r(y)?Response.json({diff:null}):(y.length>5e3&&(y=y.substring(0,5e3)+`
|
|
332
|
+
... (truncated)`),Response.json({diff:{diff:y,commitMessage:f,date:h,isUncommitted:!1,commitCount:o}})):Response.json({diff:null})}catch(r){return console.error("[API] Error getting rule diff:",r),Response.json({diff:null})}}async function zx(e,t){try{const r=await Jn(t),s={};if(r.length>0){const a=await Aa(e,r);for(const o of r)s[o.filePath]=Pa(a,o.filePath)}return Response.json({reviewedStatus:s})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function Bx(e,t){try{const r=await Jn(t),s=await Ea(e),a=[];for(const o of s){const i=r.filter(c=>Rl(o,c));if(i.length>0){const c=i.reduce((d,m)=>d+m.body.length,0);a.push({filePath:o,matchingRules:i.map(d=>({filePath:d.filePath,patterns:d.frontmatter.paths||[],bodyLength:d.body.length})),totalTextLength:c})}}return a.sort((o,i)=>i.totalTextLength-o.totalTextLength),Response.json({topPaths:a,totalFilesWithCoverage:a.length,allSourceFiles:s})}catch(r){return console.error("[API] Error getting audit data:",r),Response.json({error:"Failed to get audit data",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Yx(e){try{const t=await Ea(e);return Response.json({files:t})}catch(t){return console.error("[API] Error getting source files:",t),Response.json({error:"Failed to get source files",details:t instanceof Error?t.message:String(t)},{status:500})}}async function Ux(e,t){try{const[r,s]=await Promise.all([Jn(t),Ea(e)]),a={};for(const o of r)a[o.filePath]=$x(o,s).length;return Response.json({coverage:a})}catch(r){return console.error("[API] Error getting rule coverage:",r),Response.json({error:"Failed to get rule coverage",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Wx(e,t){try{const r=await ss(e),s=[];for(const o of r){const i=ee.join(e,o);try{const c=await xe.readFile(i,"utf-8"),d=await xe.stat(i),{frontmatter:m,body:u}=ka(c);m.paths&&m.paths.some(h=>Fs(t,h,{matchBase:!0}))&&s.push({filePath:o,content:c,frontmatter:m,body:u,lastModified:d.mtime.toISOString()})}catch{}}const a=s.reduce((o,i)=>o+i.body.length,0);return Response.json({rules:s,totalTextLength:a})}catch(r){return console.error("[API] Error getting rules for path:",r),Response.json({error:"Failed to get rules for path",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Jx({request:e}){const t=he();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=ee.join(t,".claude","rules");try{const s=await e.json(),{action:a,filePath:o,content:i,lastModified:c}=s;if(!o)return Response.json({error:"Missing required field: filePath"},{status:400});if(a==="mark-reviewed")return await Fo(t,o,!0),console.log(`[API] Rule marked as reviewed: ${o}`),Response.json({success:!0,message:"Rule marked as reviewed",filePath:o});if(a==="mark-unreviewed")return await Fo(t,o,!1),console.log(`[API] Rule marked as unreviewed: ${o}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:o});const d=ee.normalize(o);if(d.includes("..")||ee.isAbsolute(d))return Response.json({error:"Invalid file path"},{status:400});const m=ee.join(r,d);switch(a){case"create":case"update":return i?(await xe.mkdir(ee.dirname(m),{recursive:!0}),await xe.writeFile(m,i,"utf-8"),console.log(`[API] Memory ${a}d: ${o}`),Response.json({success:!0,message:`Memory ${a}d successfully`,filePath:o})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await xe.unlink(m),console.log(`[API] Memory deleted: ${o}`);const u=ee.dirname(m);try{(await xe.readdir(u)).length===0&&u!==r&&await xe.rmdir(u)}catch{}return Response.json({success:!0,message:"Memory deleted successfully"})}catch(u){if(u.code==="ENOENT")return Response.json({error:"Memory not found"},{status:404});throw u}default:return Response.json({error:"Invalid action. Must be create, update, or delete"},{status:400})}}catch(s){return console.error("[API] Error managing memory:",s),Response.json({error:"Failed to manage memory",details:s instanceof Error?s.message:String(s)},{status:500})}}const Hx=Object.freeze(Object.defineProperty({__proto__:null,action:Jx,loader:Dx},Symbol.toStringTag,{value:"Module"}));async function Vx({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await jt()),!r)return K({error:"Queue not initialized"},{status:500});const s=new URL(e.url),a=s.searchParams.get("queryType");if(!a)return K({error:"Missing queryType parameter for GET request"},{status:400});if(a==="job"){const i=s.searchParams.get("jobId");if(!i)return K({error:"Missing jobId parameter for job query"},{status:400});const c=r.getState();if(((o=c.currentlyExecuting)==null?void 0:o.id)===i)return K({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 K({jobId:i,status:"queued",position:u,job:d})}const m=r.getJobResult(i);return m?K({jobId:i,status:m.status==="error"?"failed":"completed",error:m.error}):K({jobId:i,status:"completed"})}if(a==="full"){const i=r.getState(),c=await Promise.all(i.jobs.map(async m=>{const u=[];if(m.entityShas&&m.entityShas.length>0){const h=m.entityShas.map(f=>Xt(f)),p=await Promise.all(h);u.push(...p.filter(f=>f!==null))}return{id:m.id,type:m.type,commitSha:m.commitSha,projectSlug:m.projectSlug,queuedAt:m.queuedAt,entities:u,filePaths:m.filePaths}}));let d;if(i.currentlyExecuting){const m=i.currentlyExecuting,u=[];if(m.entityShas&&m.entityShas.length>0){const h=m.entityShas.map(f=>Xt(f)),p=await Promise.all(h);u.push(...p.filter(f=>f!==null))}d={id:m.id,type:m.type,commitSha:m.commitSha,projectSlug:m.projectSlug,queuedAt:m.queuedAt,entities:u,filePaths:m.filePaths}}return K({state:{...i,jobsWithEntities:c,currentlyExecutingWithEntities:d}})}return K({error:"Unknown queryType"},{status:400})}async function qx({request:e,context:t}){console.log("[Queue API] Received request"),console.log("[Queue API] Context keys:",Object.keys(t||{})),console.log("[Queue API] analysisQueue exists:",!!(t!=null&&t.analysisQueue));let r=t.analysisQueue;if(r||(r=await jt(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),K({error:"Queue not initialized"},{status:500});const s=await e.json(),{action:a,...o}=s;if(console.log("[Queue API] Action:",a,"Params:",Object.keys(o)),a==="enqueue"){const{jobId:i,completion:c}=r.enqueue(o);return c.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),K({jobId:i,status:"queued"})}if(a==="resume")return r.resume(),K({status:"resumed"});if(a==="pause")return r.pause(),K({status:"paused"});if(a==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?K({status:"removed",jobId:i}):K({error:"Job not found in queue"},{status:404}):K({error:"Missing jobId parameter"},{status:400})}if(a==="clear"){const i=r.clearQueue();return K({status:"cleared",count:i})}if(a==="reorder"){const{jobId:i,direction:c}=o;return!i||!c?K({error:"Missing jobId or direction parameter"},{status:400}):c!=="up"&&c!=="down"?K({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,c)?K({status:"reordered",jobId:i,direction:c}):K({error:"Could not reorder job (not found or at boundary)"},{status:400})}return K({error:"Unknown action"},{status:400})}const Gx=Object.freeze(Object.defineProperty({__proto__:null,action:qx,loader:Vx},Symbol.toStringTag,{value:"Module"})),Kx=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],Qx=Je(function(){return Le(),n(Zr,{children:l("div",{className:"h-screen bg-[#F8F7F6] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children: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:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),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:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),l("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children: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",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),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",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),l("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(Ml,{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})]})]})})}),Zx=Object.freeze(Object.defineProperty({__proto__:null,default:Qx,meta:Kx},Symbol.toStringTag,{value:"Module"})),Xx=()=>[{title:"Settings - CodeYam"},{name:"description",content:"Configure project settings"}];async function eb({request:e}){var t,r;try{const s=await Ur();if(!s)return K({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Project configuration not found"});let a=!1;try{const d=await $e();if(d){const{project:m}=await Ie(d);a=((r=(t=m.metadata)==null?void 0:t.labs)==null?void 0:r.simulations)===!0}}catch{}const o=he()||process.cwd(),i=await Wr(o),c=Bi(s.projectSlug);return K({config:s,secrets:{GROQ_API_KEY:i.GROQ_API_KEY||"",ANTHROPIC_API_KEY:i.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:i.OPENAI_API_KEY||""},versionInfo:c,simulationsEnabled:a,error:null})}catch(s){return console.error("Failed to load config:",s),K({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Failed to load configuration"})}}function tb(e){if(!e||!e.trim())return;const t=e.trim().split(/\s+/);if(t.length===0)return;const r=t[0],s=t.length>1?t.slice(1):void 0;return{command:r,args:s}}async function nb({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),s=t.get("startCommands"),a=t.get("groqApiKey"),o=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),c=t.get("pathsToIgnore"),d=t.get("memorySettings");let m;if(r)try{m=JSON.parse(r)}catch{return K({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let u;if(s)try{u=JSON.parse(s)}catch{return K({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let h;c&&(h=c.split(",").map(x=>x.trim()).map(x=>x.startsWith('"')&&x.endsWith('"')||x.startsWith("'")&&x.endsWith("'")?x.slice(1,-1):x).filter(x=>x.length>0));let p;if(d)try{p=JSON.parse(d)}catch{return K({success:!1,error:"Invalid memorySettings JSON format",requiresRestart:!1},{status:400})}let f;if(u){const x=await Ur();x!=null&&x.webapps&&(f=x.webapps.map((v,b)=>{if(u[b]!==void 0){const N=tb(u[b]);return{...v,startCommand:N}}return v}))}if(!await $i({universalMocks:m,pathsToIgnore:h,webapps:f,memory:p}))return K({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let g=!1;if(a!==void 0||o!==void 0||i!==void 0){const x=he()||process.cwd(),v=await Wr(x);g=a!==void 0&&a!==(v.GROQ_API_KEY||"")||o!==void 0&&o!==(v.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(v.OPENAI_API_KEY||""),await Ou(x,{...v,GROQ_API_KEY:a||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return K({success:!0,error:null,requiresRestart:g})}catch(t){return console.log("[Settings Action] Failed to save config:",t),K({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function zo(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Bo({mock:e,onSave:t,onCancel:r}){const[s,a]=_(e.entityName),[o,i]=_(e.filePath),[c,d]=_(e.content);return l("div",{className:"space-y-3",children:[l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:s,onChange:u=>a(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., determineDatabaseType"})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:o,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("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:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!s.trim()||!o.trim()||!c.trim()){alert("All fields are required");return}t({entityName:s,filePath:o,content:c})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function rb(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const sb=Je(function(){var Ne,Ae,De,Oe,Ee;const{config:t,secrets:r,versionInfo:s,simulationsEnabled:a,error:o}=Ve(),i=sc(),c=Le(),d=ft(),[m,u]=_(a?"project-metadata":"memory");yt({source:"settings-page"});const[h,p]=_((t==null?void 0:t.universalMocks)||[]),[f,y]=_(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,x]=_(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[v,b]=_((r==null?void 0:r.GROQ_API_KEY)||""),[N,w]=_((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[S,C]=_((r==null?void 0:r.OPENAI_API_KEY)||""),[k,E]=_(!1),[A,I]=_(!1),[j,P]=_(!1),[$,T]=_(!1),[R,J]=_(!1),[q,Y]=_(!1),[H,B]=_(null),[D,M]=_(!1),[Q,U]=_({}),[F,X]=_(((Ne=t==null?void 0:t.memory)==null?void 0:Ne.conversationReflection)??!0),[z,L]=_(((Ae=t==null?void 0:t.memory)==null?void 0:Ae.ruleMaintenance)??!0),[W,V]=_(((De=t==null?void 0:t.memory)==null?void 0:De.promptModel)??"haiku");te(()=>{var re,ye,ke,rt;if(t){p(t.universalMocks||[]);const fe=(t.pathsToIgnore||[]).join(", ");y(fe),x(fe);const He={};(re=t.webapps)==null||re.forEach((Ue,Ze)=>{Ue.startCommand&&(He[Ze]=zo(Ue.startCommand))}),U(He),X(((ye=t.memory)==null?void 0:ye.conversationReflection)??!0),L(((ke=t.memory)==null?void 0:ke.ruleMaintenance)??!0),V(((rt=t.memory)==null?void 0:rt.promptModel)??"haiku")}r&&(b(r.GROQ_API_KEY||""),w(r.ANTHROPIC_API_KEY||""),C(r.OPENAI_API_KEY||""))},[t,r]),te(()=>{if(i!=null&&i.success){T(!0);const re=setTimeout(()=>T(!1),3e3);return()=>clearTimeout(re)}},[i]),te(()=>{if(c.state==="idle"&&c.data&&!q){console.log("[Settings] Fetcher data:",c.data);const re=c.data;if(re.success){console.log("[Settings] Save successful, revalidating..."),T(!0),Y(!0),(f!==g||re.requiresRestart)&&J(!0),d.revalidate();const ye=setTimeout(()=>{T(!1),Y(!1)},3e3);return()=>clearTimeout(ye)}}},[c.state,c.data,q,d,f,g]);const Z=re=>{re.preventDefault();const ye=new FormData(re.currentTarget);ye.set("universalMocks",JSON.stringify(h)),ye.set("startCommands",JSON.stringify(Q)),ye.set("memorySettings",JSON.stringify({conversationReflection:F,ruleMaintenance:z,promptModel:W})),console.log("[Settings] Submitting form data:",{universalMocks:ye.get("universalMocks"),startCommands:ye.get("startCommands"),openAiApiKey:ye.get("openAiApiKey")?"***":"(empty)"}),c.submit(ye,{method:"post"})},ce=re=>{p([...h,re]),M(!1)},ve=(re,ye)=>{const ke=[...h];ke[re]=ye,p(ke),B(null)},ae=re=>{p(h.filter((ye,ke)=>ke!==re))};if(o)return l("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:o})})]});const me=[{id:"project-metadata",label:"Project Metadata"},{id:"ai-provider",label:"AI Provider Configuration"},{id:"commands",label:"Commands"},{id:"paths-to-ignore",label:"Paths To Ignore"},{id:"universal-mocks",label:"Universal Mocks"},{id:"memory",label:"Memory"},{id:"current-configuration",label:"Current Configuration"}],Se=a?me:me.filter(re=>re.id==="memory");return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 pt-8 pb-12 font-sans",children:[l("div",{className:"mb-8 flex justify-between items-start",children:[l("div",{children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Settings"}),n("p",{className:"text-[15px] text-gray-500",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:c.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:c.state==="submitting"?"Saving...":"Save Settings"})]}),($||R||(i==null?void 0:i.error)||c.data&&typeof c.data=="object"&&"error"in c.data)&&l("div",{className:"mb-4 space-y-3",children:[$&&n("div",{className:"text-emerald-600 text-sm font-medium bg-emerald-50 border border-emerald-200 rounded px-4 py-2",children:"Settings saved successfully!"}),R&&l("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[n("div",{children:"Settings changed. Please restart CodeYam for changes to take effect:"}),l("div",{className:"flex items-center gap-2 mt-1",children:[n("code",{className:"bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"}),n(_t,{content:"codeyam stop && codeyam",className:"px-2 py-1 text-xs bg-amber-200 hover:bg-amber-300 text-amber-800 rounded border-none transition-colors"})]})]}),(i==null?void 0:i.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:i.error}),(()=>{if(c.data&&typeof c.data=="object"&&"error"in c.data){const re=c.data;return typeof re.error=="string"?n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:re.error}):null}return null})()]}),l("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8 items-start",children:[n("nav",{className:"w-full lg:w-64 flex-shrink-0",children:n("ul",{className:"flex lg:flex-col overflow-x-auto gap-1",children:Se.map(re=>n("li",{children:n("button",{type:"button",onClick:()=>u(re.id),className:`w-full text-left px-3 lg:px-0 py-2.5 text-sm transition-colors cursor-pointer whitespace-nowrap ${m===re.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:re.label})},re.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:l("form",{id:"settings-form",onSubmit:Z,className:"space-y-6",children:[m==="project-metadata"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),l("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((re,ye)=>{var ke;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:re.path==="."?"Root":re.path})]}),re.appDirectory&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:re.appDirectory})]}),l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:re.framework})]}),re.startCommand&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",l("span",{className:"text-gray-900 font-mono text-xs",children:[re.startCommand.command," ",(ke=re.startCommand.args)==null?void 0:ke.join(" ")]})]})]})},ye)})}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"}),n("p",{className:"mt-2 text-sm text-gray-600",children:"Web applications are detected during initialization. To modify, edit `.codeyam/config.json` or re-run `codeyam init`."})]})]}),m==="ai-provider"&&l("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),l("div",{className:"space-y-6",children:[l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:k?"text":"password",id:"groqApiKey",name:"groqApiKey",value:v,onChange:re=>b(re.target.value),placeholder:"gsk_...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>E(!k),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:k?"Hide":"Show"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:A?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:N,onChange:re=>w(re.target.value),placeholder:"sk-ant-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>I(!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:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:j?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:S,onChange:re=>C(re.target.value),placeholder:"sk-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>P(!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"})]})]})]})]})]}),m==="commands"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((re,ye)=>l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[l("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:re.path==="."?"Root":re.path}),n("div",{className:"text-sm text-gray-600",children:re.framework})]}),l("div",{children:[n("label",{htmlFor:`startCommand-${ye}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${ye}`,name:`startCommand-${ye}`,value:Q[ye]||"",onChange:ke=>U({...Q,[ye]:ke.target.value}),placeholder:"e.g., pnpm dev --port $PORT",className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("p",{className:"mt-2 text-xs text-gray-500",children:"Use $PORT as a placeholder for the dynamic port number"})]})]},ye))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),m==="paths-to-ignore"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:f,onChange:re=>y(re.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:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),m==="universal-mocks"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),h.length===0?l("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>M(!0),className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}):n("div",{className:"space-y-3",children:h.map((re,ye)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:H===ye?n(Bo,{mock:re,onSave:ke=>ve(ye,ke),onCancel:()=>B(null)}):n(ue,{children:l("div",{className:"flex justify-between items-start mb-2",children:[l("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:re.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:re.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:re.content})]}),l("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>B(ye),className:"px-3 py-1 bg-teal-600 text-white border-none rounded text-sm cursor-pointer hover:bg-teal-700",children:"Edit"}),n("button",{type:"button",onClick:()=>ae(ye),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},ye))}),h.length>0&&n("button",{type:"button",onClick:()=>M(!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"})]}),m==="memory"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Memory"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure how CodeYam reflects on conversations and maintains rules between sessions."}),l("div",{className:"space-y-6",children:[n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Conversation Reflection"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent reviews the session for architectural decisions, tribal knowledge, confusion, or corrections that future sessions would benefit from knowing. It creates or updates Claude Rules based on what it learns."})]}),n("button",{type:"button",role:"switch","aria-checked":F,onClick:()=>X(!F),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${F?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${F?"translate-x-5":"translate-x-0"}`})})]})}),n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Rule Maintenance"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent checks if any existing Claude Rules have become stale based on recent code changes. It reviews the rule content against file diffs and updates rules that are out of date."})]}),n("button",{type:"button",role:"switch","aria-checked":z,onClick:()=>L(!z),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${z?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${z?"translate-x-5":"translate-x-0"}`})})]})}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Memory Prompt Model"}),n("p",{className:"text-sm text-gray-600 mb-4",children:"Choose the Claude model used for conversation reflection and rule maintenance tasks."}),n("div",{className:"space-y-3",children:[{value:"haiku",label:"Haiku",badge:"Default, Recommended",description:"Fastest and cheapest. Good for routine reflection tasks."},{value:"sonnet",label:"Sonnet",badge:null,description:"Balanced speed and quality. Better at nuanced rule writing."},{value:"opus",label:"Opus",badge:null,description:"Highest quality. Best for complex architectural decisions. Costs significantly more."}].map(re=>l("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${W===re.value?"border-[#005C75] bg-[#005C75]/5":"border-gray-200 hover:border-gray-300"}`,children:[n("input",{type:"radio",name:"promptModel",value:re.value,checked:W===re.value,onChange:()=>V(re.value),className:"mt-1 accent-[#005C75]"}),l("div",{children:[l("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-gray-900",children:re.label}),re.badge&&n("span",{className:"px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:re.badge})]}),n("p",{className:"text-sm text-gray-600 mt-0.5",children:re.description})]})]},re.value))})]})]})]}),m==="current-configuration"&&l("div",{className:"space-y-6",children:[t&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:l("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&l("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((re,ye)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:re.path==="."?"Root":re.path})]}),re.appDirectory&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:re.appDirectory})]}),l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:re.framework})]}),re.startCommand&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:zo(re.startCommand)})]})]})},ye))})]})]}),s&&l("div",{className:"mt-6",children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[s.webserverVersion&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",n("span",{className:"text-gray-900 font-mono",children:s.webserverVersion.version||"unknown"})]}),s.templateVersion&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",n("span",{className:"font-mono text-gray-900",children:s.templateVersion.version||((Oe=s.templateVersion.gitCommit)==null?void 0:Oe.slice(0,7))||"unknown"}),s.templateVersion.buildTimestamp&&l("span",{className:"text-gray-500 ml-2",children:["(built"," ",rb(s.templateVersion.buildTimestamp),")"]})]}),s.cachedAnalyzerVersion&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"font-mono text-gray-900",children:s.cachedAnalyzerVersion.version||((Ee=s.cachedAnalyzerVersion.gitCommit)==null?void 0:Ee.slice(0,7))||"unknown"}),s.isCacheStale?n("span",{className:"ml-2 px-2 py-0.5 bg-amber-100 text-amber-800 rounded text-xs",children:"Stale - will update on next analysis"}):n("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]}),!s.cachedAnalyzerVersion&&(t==null?void 0:t.projectSlug)&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),D&&n("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:[n("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),n(Bo,{mock:{entityName:"",filePath:"",content:""},onSave:ce,onCancel:()=>M(!1)})]})})]})})}),ab=Object.freeze(Object.defineProperty({__proto__:null,action:nb,default:sb,loader:eb,meta:Xx},Symbol.toStringTag,{value:"Module"}));async function ob({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=he();if(!r)return new Response("Project root not found",{status:500});const a=ee.extname(t)!==""?t:`${t}.html`,o=ee.join(r,".codeyam","captures","static",a);try{await xe.access(o);let i=await xe.readFile(o);const c=ee.extname(o).toLowerCase();let d="application/octet-stream";if(c===".html"){d="text/html";let m=i.toString("utf-8");const u=m.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>`;m=m.replace(u[0],y)}}catch(h){console.error("[Static] Failed to parse Remix context:",h)}i=Buffer.from(m,"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 ib=Object.freeze(Object.defineProperty({__proto__:null,loader:ob},Symbol.toStringTag,{value:"Module"}));function lb(e,t,r=10){var d;const s=new Map,a=m=>m.entityType==="visual"||m.entityType==="library";for(const m of e)a(m)&&s.set(m.sha,{entity:m,depth:0});const o=new Map;for(const m of t){const u=(d=m.metadata)==null?void 0:d.importedBy;if(u)for(const h of Object.keys(u))for(const p of Object.keys(u[h])){const{shas:f}=u[h][p];for(const y of f)o.has(m.sha)||o.set(m.sha,new Set),o.get(m.sha).add(y)}}const i=[],c=new Set;for(const m of e)i.push({sha:m.sha,depth:0}),c.add(m.sha);for(;i.length>0;){const{sha:m,depth:u}=i.shift();if(u>=r)continue;const h=o.get(m);if(h)for(const p of h){if(c.has(p))continue;c.add(p);const f=t.find(y=>y.sha===p);if(f){if(a(f)){const y=u+1,g=s.get(p);(!g||y<g.depth)&&s.set(p,{entity:f,depth:y})}i.push({sha:p,depth:u+1})}}}return Array.from(s.values()).sort((m,u)=>m.depth!==u.depth?m.depth-u.depth:m.entity.name.localeCompare(u.entity.name))}function jr(e){const t=new Map;for(const s of e)t.has(s.name)||t.set(s.name,[]),t.get(s.name).push(s);const r=[];for(const s of t.values())if(s.length===1)r.push(s[0]);else{const a=s.sort((o,i)=>{var m,u;const c=((m=o.metadata)==null?void 0:m.editedAt)||o.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(c)});r.push(a[0])}return r}function zl(e,t){const r=new Map,s=new Set(e.map(a=>a.path));for(const a of e)a.status==="renamed"&&a.oldPath&&s.add(a.oldPath);for(const a of e){const o=t.filter(d=>d.filePath===a.path||a.status==="renamed"&&a.oldPath&&d.filePath===a.oldPath),i=o.filter(d=>{var m,u;return s.has(d.filePath)&&((m=d.metadata)==null?void 0:m.isUncommitted)&&!((u=d.metadata)!=null&&u.isSuperseded)}),c=jr(i);r.set(a.path,{status:a,entities:o,editedEntities:c})}return r}function cb(e,t,r){const s=new Map;if(!r){for(const o of e)if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const i=t.filter(d=>d.filePath===o.path||o.status==="renamed"&&o.oldPath&&d.filePath===o.oldPath),c=jr(i);s.set(o.path,{status:o,entities:c})}return s}const a=new Map;for(const o of r.fileComparisons){const i=new Set;for(const c of o.newEntities)i.add(c.name);for(const c of o.modifiedEntities)i.add(c.name);for(const c of o.deletedEntities)i.add(c.name);i.size>0&&a.set(o.filePath,i)}for(const o of e){const i=a.get(o.path);if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const c=i?t.filter(m=>(m.filePath===o.path||o.status==="renamed"&&o.oldPath&&m.filePath===o.oldPath)&&i.has(m.name)):[],d=jr(c);s.set(o.path,{status:o,entities:d})}}return s}function db(e,t){const r=new Map,s=Bl(e,t);for(const a of s){const i=lb([a],t).filter(({depth:c})=>c>0);r.set(a.sha,i)}return r}function Bl(e,t){const r=new Set(e.map(a=>a.path));for(const a of e)a.status==="renamed"&&a.oldPath&&r.add(a.oldPath);const s=t.filter(a=>{var o,i;return r.has(a.filePath)&&((o=a.metadata)==null?void 0:o.isUncommitted)&&!((i=a.metadata)!=null&&i.isSuperseded)});return jr(s)}function ub({recentSimulations:e}){const t=ne(()=>{const r=new Map;return e.forEach(s=>{const a=s.entitySha,o=r.get(a);o?o.push(s):r.set(a,[s])}),Array.from(r.entries()).map(([s,a])=>({entitySha:s,entityName:a[0].entityName,scenarios:a}))},[e]);return l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:e.length>0?`Latest ${e.length} captured screenshot${e.length!==1?"s":""}`:"No simulations captured yet"})]})}),e.length>0?l(ue,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>l("div",{children:[l("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(In,{size:16,style:{color:"#8B5CF6"}})}),n(de,{to:`/entity/${r.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:r.entityName})]}),n("div",{className:"grid grid-cols-4 gap-3",children:r.scenarios.map((s,a)=>n(de,{to:s.scenarioId?`/entity/${s.entitySha}/scenarios/${s.scenarioId}`:`/entity/${s.entitySha}`,className:"aspect-4/3 border border-gray-200 rounded-lg overflow-hidden bg-gray-50 transition-all flex items-center justify-center hover:scale-105",onMouseEnter:o=>{o.currentTarget.style.borderColor="#005C75",o.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:o=>{o.currentTarget.style.borderColor="#E5E7EB",o.currentTarget.style.boxShadow="none"},title:s.scenarioName,children:n(qe,{screenshotPath:s.screenshotPath,alt:s.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},s.scenarioId||`${s.entitySha}-${a}`))})]},r.entitySha))}),n(de,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:r=>r.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:r=>r.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):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:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:n(In,{size:24,style:{color:"#7A9BA5"},strokeWidth:1.5})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No simulations captured yet."}),l("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",n(de,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(de,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const mb="/assets/codeyam-name-logo-CvKwUgHo.svg",hb=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function pb({request:e,context:t}){var r,s,a,o,i;try{const c=await $e();if(c){const{project:$}=await Ie(c);if(((r=$.metadata)==null?void 0:r.editorMode)??!1)return qa("/editor");if(!(((a=(s=$.metadata)==null?void 0:s.labs)==null?void 0:a.simulations)??!1))return qa("/memory")}const d=t.analysisQueue,m=d?d.getState():{paused:!1,jobs:[]},[u,h]=await Promise.all([tn(),yn()]),p=ns(),f=u?zl(p,u):new Map,y=Array.from(f.entries()).sort(($,T)=>$[0].localeCompare(T[0])),g=(u==null?void 0:u.length)||0,x=(u==null?void 0:u.filter($=>$.entityType==="visual").length)||0,v=(u==null?void 0:u.filter($=>$.entityType==="library").length)||0,b=u?Bl(p,u):[],N=b.length,w=(u==null?void 0:u.filter($=>($.analyses??[]).filter(T=>T.scenarios&&T.scenarios.length>0).length>0).length)||0,S=(u==null?void 0:u.reduce(($,T)=>{var J,q,Y;const R=((Y=(q=(J=T.analyses)==null?void 0:J[0])==null?void 0:q.scenarios)==null?void 0:Y.length)||0;return $+R},0))||0,C=(u==null?void 0:u.reduce(($,T)=>{var q,Y;const J=(((Y=(q=T.analyses)==null?void 0:q[0])==null?void 0:Y.scenarios)||[]).filter(H=>{var B,D;return(D=(B=H.metadata)==null?void 0:B.screenshotPaths)==null?void 0:D[0]}).length;return $+J},0))||0,k=[];u==null||u.forEach($=>{var R;const T=(R=$.analyses)==null?void 0:R[0];T!=null&&T.scenarios&&T.scenarios.filter(q=>{var Y;return!((Y=q.metadata)!=null&&Y.sameAsDefault)}).forEach(q=>{var H,B;const Y=(B=(H=q.metadata)==null?void 0:H.screenshotPaths)==null?void 0:B[0];Y&&k.push({entitySha:$.sha,entityName:$.name,scenarioId:q.id,scenarioName:q.name,screenshotPath:Y,createdAt:T.createdAt||""})})}),k.sort(($,T)=>new Date(T.createdAt).getTime()-new Date($.createdAt).getTime());const E=k.slice(0,16),A=(u==null?void 0:u.filter($=>$.entityType==="visual").filter($=>{var J,q;const T=(J=$.analyses)==null?void 0:J[0];return!((q=T==null?void 0:T.scenarios)==null?void 0:q.some(Y=>{var H,B;return(B=(H=Y.metadata)==null?void 0:H.screenshotPaths)==null?void 0:B[0]}))}).slice(0,8))||[],I=(o=h==null?void 0:h.metadata)==null?void 0:o.currentRun,j=((i=I==null?void 0:I.currentEntityShas)==null?void 0:i.length)||0,P=m.jobs.length||0;return K({stats:{totalEntities:g,visualEntities:x,libraryEntities:v,uncommittedEntities:N,entitiesWithAnalyses:w,totalScenarios:S,capturedScreenshots:C,currentlyAnalyzing:j,filesOnQueue:P},uncommittedFiles:y,uncommittedEntitiesList:b,recentSimulations:E,visualEntitiesForSimulation:A,projectSlug:c,queueState:m,currentCommit:h})}catch(c){return console.error("Failed to load dashboard data:",c),K({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 fb=Je(function(){var H,B;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:s,recentSimulations:a,visualEntitiesForSimulation:o,projectSlug:i,queueState:c,currentCommit:d}=Ve(),m=Le(),u=ft(),{showToast:h}=ca();yt({source:"dashboard"});const[p,f]=_(new Set),[y,g]=_(null),[x,v]=_(!1),[b,N]=_(!1),{lastLine:w,isCompleted:S}=Et(i,!!y),{simulatingEntity:C,scenarios:k,scenarioStatuses:E,allScenariosCaptured:A}=ne(()=>{var L,W;const D={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!y)return D;const M=o==null?void 0:o.find(V=>V.sha===y);if(!M)return D;const Q=(L=M.analyses)==null?void 0:L[0],U=(Q==null?void 0:Q.scenarios)||[],F=((W=Q==null?void 0:Q.status)==null?void 0:W.scenarios)||[],X=F.filter(V=>V.screenshotFinishedAt).length,z=U.length>0&&X===U.length;return{simulatingEntity:M,scenarios:U,scenarioStatuses:F,allScenariosCaptured:z}},[y,o]);te(()=>{(S||A)&&g(null)},[S,A]);const I=(H=d==null?void 0:d.metadata)==null?void 0:H.currentRun,j=new Set((I==null?void 0:I.currentEntityShas)||[]),P=new Set(c.jobs.flatMap(D=>D.entityShas||[])),$=new Set(((B=c.currentlyExecuting)==null?void 0:B.entityShas)||[]),T=s.filter(D=>D.entityType==="visual"||D.entityType==="library"),R=T.filter(D=>!j.has(D.sha)&&!P.has(D.sha)&&!$.has(D.sha)),J=()=>{if(R.length===0){h("All entities are already queued or analyzing","info",3e3);return}const D=R.map(M=>M.sha);N(!0),h(`Starting analysis for ${R.length} entities...`,"info",3e3),m.submit({entityShas:D.join(",")},{method:"post",action:"/api/analyze"})};te(()=>{if(m.state==="idle"&&m.data){const D=m.data;D.success?(console.log("[Analyze All] Success:",D.message),h(`Analysis started for ${D.entityCount} entities in ${D.fileCount} files. Watch the logs for progress.`,"success",6e3),N(!1)):D.error&&(console.error("[Analyze All] Error:",D.error),h(`Error: ${D.error}`,"error",8e3),N(!1))}},[m.state,m.data,h]);const q=D=>{f(M=>{const Q=new Set(M);return Q.has(D)?Q.delete(D):Q.add(D),Q})},Y=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#005C75",tooltip:"In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested."},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981",tooltip:"Entities that have been analyzed by CodeYam and have generated scenarios."},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6",tooltip:"React components and visual elements that can be rendered and captured as screenshots."},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9",tooltip:"Reusable functions and utilities that can be independently tested."}];return n("div",{className:"bg-cygray-10 min-h-screen",children: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:[n("img",{src:mb,alt:"CodeYam",className:"h-3.5"}),n("span",{className:"text-gray-400 text-sm",children:"|"}),n("h1",{className:"text-sm font-mono font-normal text-gray-400 m-0",children:i?i.replace(/-/g," ").replace(/\b\w/g,D=>D.toUpperCase()):"Project"})]}),u.state==="loading"&&n("div",{className:"text-blue-600 text-sm font-medium animate-pulse",children:"🔄 Updating..."})]}),n("div",{className:"flex items-center justify-between gap-3",children:Y.map((D,M)=>n(de,{to:D.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 ${D.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:[n("span",{className:"text-xs text-gray-700 font-medium font-mono uppercase",children:D.label}),l("svg",{className:"w-3 h-3 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[D.tooltip,n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 sm:hidden md:flex",style:{color:D.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:`${D.color}15`},children:[D.iconType==="folder"&&n(Mc,{size:20,style:{color:D.color}}),D.iconType==="check"&&n(ea,{size:20,style:{color:D.color}}),D.iconType==="image"&&n(In,{size:20,style:{color:D.color}}),D.iconType==="code-xml"&&n(Tc,{size:20,style:{color:D.color}})]}),n("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:D.value.toLocaleString("en-US")})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:D.color},children:"View All →"})]})]})},M))}),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:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),n("p",{className:"text-sm text-gray-500 m-0",children:r.length>0?`${r.length} file${r.length!==1?"s":""} with ${s.length} uncommitted entit${s.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),T.length>0&&n("button",{onClick:J,disabled:m.state!=="idle"||b||R.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:D=>D.currentTarget.style.backgroundColor="#004560",onMouseLeave:D=>D.currentTarget.style.backgroundColor="#005C75",children:m.state!=="idle"||b?"Starting analysis...":R.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([D,M])=>{const Q=p.has(D),U=M.editedEntities||[];return l("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#005C75"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>q(D),role:"button",tabIndex:0,children:l("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:Q?"▼":"▶"}),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:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),l("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:D}),l("span",{className:"text-xs text-gray-500",children:[U.length," entit",U.length!==1?"ies":"y"]})]})]})}),Q&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:U.length>0?U.map(F=>{const X=j.has(F.sha),z=P.has(F.sha)||$.has(F.sha);return l(de,{to:`/entity/${F.sha}`,className:"flex items-center gap-4 p-4 bg-white border border-gray-200 rounded-lg no-underline transition-all hover:shadow-md hover:-translate-y-0.5",style:{borderColor:"inherit"},onMouseEnter:L=>L.currentTarget.style.borderColor="#005C75",onMouseLeave:L=>L.currentTarget.style.borderColor="inherit",children:[l("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:F.entityType==="visual"?"#8B5CF615":F.entityType==="library"?"#6366F1":"#EC4899"},children:[F.entityType==="visual"&&n(In,{size:16,style:{color:"#8B5CF6"}}),F.entityType==="library"&&n(si,{size:16,className:"text-white"}),F.entityType==="other"&&n($c,{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:[n("div",{className:"font-semibold text-gray-900 text-sm",children:F.name}),F.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),F.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),F.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),F.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:F.description})]}),l("div",{className:"flex items-center gap-2 shrink-0",children:[X&&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:[n(ht,{size:14,className:"animate-spin"}),"Analyzing..."]}),!X&&z&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!X&&!z&&n("button",{onClick:L=>{L.preventDefault(),L.stopPropagation(),h(`Starting analysis for ${F.name}...`,"info",3e3),m.submit({entityShas:F.sha},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:L=>L.currentTarget.style.backgroundColor="#004560",onMouseLeave:L=>L.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},F.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},D)})}):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:[n("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:[n("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n("polyline",{points:"14 2 14 8 20 8"}),n("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),n("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!y&&n(ub,{recentSimulations:a}),y&&l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:a.length>0?`Latest ${a.length} captured screenshot${a.length!==1?"s":""}`:"No simulations captured yet"})]})}),y&&l("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[C&&n("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:l("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(tt,{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 ",C.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:C.filePath})]})]})}),A?l("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[n("span",{className:"text-lg",children:"✅"}),l("span",{children:["Complete (",k.length," scenario",k.length!==1?"s":"",")"]})]}):w?l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(ht,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:w,children:w}),i&&n("button",{onClick:()=>v(!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"})]}):m.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:[n(ht,{size:18,className:"animate-spin shrink-0"}),n("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:[n(ht,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),k.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:k.slice(0,8).map((D,M)=>{var W,V,Z;const Q=(W=C==null?void 0:C.analyses)==null?void 0:W[0],U=rs(D,Q==null?void 0:Q.status,void 0,y||void 0,void 0),F=(Z=(V=D.metadata)==null?void 0:V.screenshotPaths)==null?void 0:Z[0],X=U.isCaptured,z=U.status==="capturing"||U.status==="starting",L=U.hasError;return X?n(de,{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:n(qe,{screenshotPath:F,alt:D.name,title:D.name,className:"max-w-full max-h-full object-contain object-center"})},M):L?n("div",{className:"w-20 h-15 border-2 border-solid border-red-300 rounded bg-red-50 flex flex-col items-center justify-center text-lg",title:U.errorMessage||"Capture error",children:n("span",{className:"text-red-500",children:"⚠️"})},M):n("div",{className:"w-20 h-15 border-2 border-dashed border-gray-300 rounded bg-gray-50 flex items-center justify-center text-2xl",title:`${z?"Capturing":"Pending"} ${D.name}...`,children:n("span",{className:z?"animate-pulse":"text-gray-400",children:z?"⋯":"⏹️"})},M)})})]})]})]}),x&&i&&n(Dt,{projectSlug:i,onClose:()=>v(!1)})]})})}),gb=Object.freeze(Object.defineProperty({__proto__:null,default:fb,loader:pb,meta:hb},Symbol.toStringTag,{value:"Module"}));function _a(e){const[t,r]=_(null),[s,a]=_(!1),o=oe(()=>{e&&(a(!0),fetch(`/api/editor-test-results?testFile=${encodeURIComponent(e)}`).then(i=>i.json()).then(i=>{r(i),a(!1)}).catch(()=>{r({testFilePath:e,status:"error",testCases:[],errorMessage:"Failed to fetch test results"}),a(!1)}))},[e]);return te(()=>{e&&o()},[e,o]),{results:t,isRunning:s,runTests:o}}function _n({imgSrc:e,name:t,isActive:r,onSelect:s}){return l("button",{onClick:s,className:"flex flex-col items-center gap-1 cursor-pointer group",title:t,children:[n("div",{className:`w-32 h-32 rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] ${r?"border-[#005c75] ring-1 ring-[#005c75]":"border-transparent hover:border-[#4d4d4d]"}`,children:e?n("img",{src:e,alt:t,className:"w-full h-full object-contain",loading:"lazy"}):n("div",{className:"w-full h-full bg-[#1a1a1a] flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})})}),n("span",{className:`text-[10px] leading-tight text-center truncate w-32 ${r?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:t})]})}function $s({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=_a(e);if(s&&!r)return l("div",{className:"px-2 pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!r)return null;if(r.status==="error")return n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-red-400",children:r.errorMessage})});const o=t?r.testCases.filter(d=>d.fullName.startsWith(t)):r.testCases,i=o.length>0?o:r.testCases;if(i.length===0)return null;const c=t?`${t} > `:"";return l("div",{className:"px-2 pt-1 space-y-0.5",children:[i.map(d=>{var u;const m=c&&d.fullName.startsWith(c)?d.fullName.slice(c.length):d.fullName;return l("div",{children:[l("div",{className:"flex items-center gap-1.5",children:[d.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):d.status==="failed"?n("span",{className:"text-red-400 text-[10px]",children:"✗"}):n("span",{className:"text-gray-500 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${d.status==="passed"?"text-green-400":d.status==="failed"?"text-red-400":"text-gray-500"}`,children:m})]}),d.status==="failed"&&((u=d.failureMessages)==null?void 0:u.map((h,p)=>n("div",{className:"pl-4 text-[9px] text-red-300/70 truncate max-w-full",title:h,children:h.split(`
|
|
333
|
+
`)[0]},p)))]},d.fullName)}),n("button",{onClick:a,disabled:s,className:"mt-1 text-[10px] text-[#00a0c4] hover:text-[#00c4ee] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:s?"Running...":"Re-run"})]})}function Ht({filePath:e}){return e?l("div",{className:"flex items-center gap-1 px-2 mt-0.5",children:[l("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(_t,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function yb({scenarios:e,projectRoot:t,activeScenarioId:r,onScenarioSelect:s,zoomComponent:a,onZoomChange:o,analyzedEntities:i=[],glossaryFunctions:c=[],activeAnalyzedScenarioId:d,onAnalyzedScenarioSelect:m,entityImports:u,pageFilePaths:h={}}){const{pageGroups:p,componentGroups:f}=ne(()=>{const C=new Map,k=new Map;for(const A of e)if(A.componentName){const I=k.get(A.componentName)||[];I.push(A),k.set(A.componentName,I)}else{const I=Wn(A.url),j=C.get(I)||[];j.push(A),C.set(I,j)}const E=new Map([...k.entries()].sort(([A],[I])=>A.localeCompare(I)));return{pageGroups:C,componentGroups:E}},[e]),y=ne(()=>{const C=new Set((i||[]).filter(E=>E.entityType==="visual").map(E=>E.name)),k=new Map;for(const[E,A]of f)C.has(E)||k.set(E,A);return k},[f,i]),{visualEntities:g,libraryEntities:x}=ne(()=>{const C=i.filter(E=>E.entityType==="visual").sort((E,A)=>E.name.localeCompare(A.name)),k=i.filter(E=>E.entityType==="library"||E.entityType==="functionCall").sort((E,A)=>E.name.localeCompare(A.name));return{visualEntities:C,libraryEntities:k}},[i]),v=ne(()=>{const C=new Set(x.map(k=>k.name));return c.filter(k=>!C.has(k.name)).sort((k,E)=>k.name.localeCompare(E.name))},[c,x]),b=i.some(C=>C.isAnalyzing),N=be(null),w=be(0),S=oe(()=>{N.current&&(w.current=N.current.scrollTop)},[]);if(te(()=>{N.current&&w.current>0&&(N.current.scrollTop=w.current)}),e.length===0&&i.length===0&&v.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:l("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No scenarios yet"}),n("p",{className:"text-xs",children:"Scenarios will appear here as Claude creates them alongside your code. Each scenario represents a different state of your app's data."})]})});if(a){const C=f.get(a)||[],k=new Set((u==null?void 0:u[a])||[]),E=k.size>0,A=E?g.filter(j=>k.has(j.name)):[],I=E?x.filter(j=>k.has(j.name)):[];return n("div",{className:"flex-1 overflow-auto",children:l("div",{className:"p-3 space-y-1",children:[l("button",{onClick:()=>o(void 0),className:"w-full flex items-center gap-2 px-3 py-1.5 text-xs text-gray-400 hover:text-white transition-colors cursor-pointer",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M7.5 9L4.5 6L7.5 3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"All scenarios"]}),n("div",{className:"px-3 py-1.5",children:n("span",{className:"text-xs font-semibold text-white uppercase tracking-wider",children:a})}),n("div",{className:"flex flex-wrap gap-2 px-2",children:C.length===0?n("div",{className:"px-3 py-2 text-xs text-gray-500",children:"No scenarios for this component"}):C.map(j=>n(_n,{imgSrc:j.screenshotPath?`/api/editor-scenario-image/${j.id}.png`:null,name:j.name,isActive:j.id===r,onSelect:()=>s(j)},j.id))}),A.length>0&&l("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),A.map(j=>l("div",{className:"mt-2",children:[n("div",{className:"flex items-center gap-2 px-2 py-1",children:n("button",{onClick:()=>o(j.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:j.name})}),n(Ht,{filePath:j.filePath,projectRoot:t}),(j.scenarios.length>0||j.pendingScenarios.length>0)&&n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:j.scenarios.map(P=>n(_n,{imgSrc:P.screenshotPath?`/api/screenshot/${P.screenshotPath}`:null,name:P.name,isActive:P.id===d,onSelect:()=>m==null?void 0:m({analysisId:j.analysisId,scenarioId:P.id,scenarioName:P.name,entitySha:j.sha,entityName:j.name})},P.id))})]},j.sha))]}),I.length>0&&l("div",{className:"pt-2 mt-1",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),I.map(j=>l("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:j.name})}),n(Ht,{filePath:j.filePath,projectRoot:t}),j.testFile&&n($s,{testFile:j.testFile,entityName:j.name})]},j.sha))]})]})})}return n("div",{ref:N,onScroll:S,className:"flex-1 overflow-auto",children:l("div",{className:"p-3 space-y-3",children:[p.size>0&&l("div",{children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"})}),[...p.entries()].sort(([C],[k])=>C==="Home"?-1:k==="Home"?1:C.localeCompare(k)).map(([C,k])=>l("div",{className:"px-2 pt-1",children:[n("div",{className:"py-0.5",children:n("span",{className:"text-[11px] font-medium text-gray-400",children:C})}),h[C]&&n(Ht,{filePath:h[C],projectRoot:t}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:k.map(E=>n(_n,{imgSrc:E.screenshotPath?`/api/editor-scenario-image/${E.id}.png`:null,name:E.name,isActive:E.id===r&&!d,onSelect:()=>s(E)},E.id))})]},C))]}),y.size>0&&l("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),[...y.entries()].map(([C,k])=>{var E;return l("div",{className:"mt-2",children:[n("div",{className:"flex items-center justify-between px-2 py-1",children:n("button",{onClick:()=>o(C),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:C})}),((E=k[0])==null?void 0:E.componentPath)&&n(Ht,{filePath:k[0].componentPath,projectRoot:t}),n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:k.map(A=>n(_n,{imgSrc:A.screenshotPath?`/api/editor-scenario-image/${A.id}.png`:null,name:A.name,isActive:A.id===r&&!d,onSelect:()=>s(A)},A.id))})]},C)})]}),g.length>0&&l("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[l("div",{className:"px-2 py-1",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),b&&e.length===0&&i.every(C=>C.scenarioCount===0)&&n("span",{className:"ml-2 text-[10px] text-gray-500",children:"— Entities are being analyzed..."})]}),g.map(C=>l("div",{className:"mt-2",children:[l("div",{className:"flex items-center gap-2 px-2 py-1",children:[n("button",{onClick:()=>o(C.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:C.name}),C.isAnalyzing&&C.scenarioCount===0&&l("span",{className:"flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(Ht,{filePath:C.filePath,projectRoot:t}),(C.scenarios.length>0||C.pendingScenarios.length>0)&&l("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:[C.scenarios.map(k=>n(_n,{imgSrc:k.screenshotPath?`/api/screenshot/${k.screenshotPath}`:null,name:k.name,isActive:k.id===d,onSelect:()=>m==null?void 0:m({analysisId:C.analysisId,scenarioId:k.id,scenarioName:k.name,entitySha:C.sha,entityName:C.name})},k.id)),C.pendingScenarios.map(k=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:k,children:k},k))]})]},C.sha))]}),(x.length>0||v.length>0)&&l("div",{className:`pt-2 mt-1 ${g.length>0?"":"border-t border-[#3d3d3d]"}`,children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),x.map(C=>l("div",{className:"mt-2",children:[l("div",{className:"px-2 py-1",children:[n("span",{className:"text-[11px] font-medium text-gray-300",children:C.name}),C.isAnalyzing&&C.scenarioCount===0&&l("span",{className:"ml-2 inline-flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(Ht,{filePath:C.filePath,projectRoot:t}),C.testFile?n($s,{testFile:C.testFile,entityName:C.name}):n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},C.sha)),v.map(C=>l("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:C.name})}),n(Ht,{filePath:C.filePath,projectRoot:t}),n($s,{testFile:C.testFile,entityName:C.name})]},C.name))]})]})})}function Yo({status:e}){const t={new:{label:"New",bg:"bg-green-900/40",text:"text-green-400",border:"border-green-700/50"},edited:{label:"Edited",bg:"bg-blue-900/40",text:"text-blue-400",border:"border-blue-700/50"},impacted:{label:"Impacted",bg:"bg-amber-900/40",text:"text-amber-400",border:"border-amber-700/50"}}[e.status];return n("span",{className:`${t.bg} ${t.text} ${t.border} border text-[8px] font-bold px-1 py-0 rounded-full uppercase tracking-wider`,children:t.label})}function xb({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=_a(e);if(s&&!r)return l("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#00a0c4] animate-pulse"}),n("span",{className:"text-[10px] text-gray-500",children:"Running tests..."})]});if(!r)return null;if(r.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-400",children:r.errorMessage})});const o=t?r.testCases.filter(d=>d.fullName.startsWith(t)):r.testCases,i=o.length>0?o:r.testCases;if(i.length===0)return null;const c=t?`${t} > `:"";return l("div",{className:"pt-1 space-y-0.5",children:[i.map(d=>{var u;const m=c&&d.fullName.startsWith(c)?d.fullName.slice(c.length):d.fullName;return l("div",{children:[l("div",{className:"flex items-center gap-1.5",children:[d.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):d.status==="failed"?n("span",{className:"text-red-400 text-[10px]",children:"✗"}):n("span",{className:"text-gray-500 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${d.status==="passed"?"text-green-400":d.status==="failed"?"text-red-400":"text-gray-500"}`,children:m})]}),d.status==="failed"&&((u=d.failureMessages)==null?void 0:u.map((h,p)=>n("div",{className:"pl-4 text-[9px] text-red-400/70 truncate max-w-full",title:h,children:h.split(`
|
|
334
|
+
`)[0]},p)))]},d.fullName)}),n("button",{onClick:a,disabled:s,className:"mt-1 text-[10px] text-[#00a0c4] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:s?"Running...":"Re-run"})]})}const bb={feature:{label:"Feature",color:"bg-[#005c75]"},fix:{label:"Fix",color:"bg-amber-700"},refactor:{label:"Refactor",color:"bg-purple-700"},scaffold:{label:"Scaffold",color:"bg-green-700"},data:{label:"Data",color:"bg-blue-700"},milestone:{label:"Milestone",color:"bg-yellow-600"}};function vb(e){try{return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function wb(e){try{return new Date(e+"T00:00:00").toLocaleDateString([],{weekday:"long",month:"long",day:"numeric"})}catch{return e}}function Nb({isActive:e,onScreenshotClick:t,glossaryFunctions:r=[],pageNames:s=[]}){const[a,o]=_([]),[i,c]=_(!0),[d,m]=_(new Set),u=oe(f=>{m(y=>{const g=new Set(y);return g.has(f)?g.delete(f):g.add(f),g})},[]),h=oe(async()=>{try{const f=await fetch("/api/editor-journal");if(f.ok){const y=await f.json();o(y.entries||[])}}catch{}finally{c(!1)}},[]);if(te(()=>{h()},[h]),te(()=>{e&&h()},[e,h]),te(()=>{const f=new EventSource("/api/events");return f.addEventListener("message",y=>{try{const g=JSON.parse(y.data);g.type==="db-change"&&g.changeType==="journal"&&h()}catch{}}),()=>f.close()},[h]),i)return n("div",{className:"flex-1 flex items-center justify-center",children:n("span",{className:"text-gray-500 text-sm",children:"Loading journal..."})});if(a.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:l("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No journal entries yet"}),n("p",{className:"text-xs",children:"Journal entries will appear as you build. Claude records features, screenshots, and commits as the project evolves."})]})});const p=mf(a);return n("div",{className:"flex-1 overflow-auto",children:n("div",{className:"p-3 space-y-4",children:[...p.entries()].map(([f,y])=>l("div",{children:[n("div",{className:"px-3 py-1.5 sticky top-0 bg-[#1e1e1e] z-10",children:n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:wb(f)})}),n("div",{className:"space-y-2",children:y.map((g,x)=>{const v=bb[g.type]||{label:g.type,color:"bg-gray-600"},b=`${g.time}-${x}`,N=d.has(b);return l("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[l("div",{className:`p-3 space-y-2 ${N?"":"max-h-[300px] overflow-y-auto"}`,children:[n("div",{className:"flex items-start gap-2",children:l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-white truncate",children:g.title}),n("span",{className:`${v.color} text-white text-[9px] font-bold px-1.5 py-0.5 rounded uppercase tracking-wider shrink-0`,children:v.label})]}),n("span",{className:"text-[10px] text-gray-500",children:vb(g.time)})]})}),n("p",{className:"text-xs text-gray-400 leading-relaxed",children:g.description}),g.screenshot&&n("button",{type:"button",className:"rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] flex items-center justify-center p-1 cursor-pointer transition-colors w-full",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${g.screenshot.replace("screenshots/","")}`,commitSha:g.commitSha,commitMessage:g.commitMessage,scenarioName:g.title}),children:n("img",{src:`/api/editor-journal-image/${g.screenshot.replace("screenshots/","")}`,alt:g.title,className:"max-w-full max-h-full object-contain",loading:"lazy"})}),g.scenarioScreenshots&&g.scenarioScreenshots.length>0&&(()=>{const w=hf(g.scenarioScreenshots);new Set(s);const S=w.filter(([j])=>j==="App").flatMap(([,j])=>j),C=Vs(w.filter(([j])=>j!=="App"),g.entityChangeStatus),k=g.entityChangeStatus,A=k&&Object.keys(k).length>0?s.filter(j=>k[j]):s,I=j=>n("button",{type:"button",className:"w-[4.5rem] h-[4.5rem] rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] shrink-0 flex items-center justify-center cursor-pointer transition-colors",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${j.path.replace("screenshots/","")}`,commitSha:g.commitSha,commitMessage:g.commitMessage,scenarioName:j.name}),children:n("img",{src:`/api/editor-journal-image/${j.path.replace("screenshots/","")}`,alt:j.name,title:j.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})},j.path);return l("div",{className:"space-y-2",children:[(A.length>0||S.length>0)&&l("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),A.map(j=>l("div",{children:[l("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:j}),(k==null?void 0:k[j])&&n(Yo,{status:k[j]})]}),S.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:S.map(I)})]},j))]}),C.length>0&&l("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),C.map(([j,P])=>l("div",{children:[l("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:j}),(k==null?void 0:k[j])&&n(Yo,{status:k[j]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:P.map(I)})]},j))]})]})})(),r.length>0&&l("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"}),n("div",{className:"space-y-2",children:r.map(w=>l("div",{children:[n("span",{className:"text-[11px] font-medium text-gray-200",children:w.name}),n("span",{className:"text-[9px] text-gray-500 truncate block",children:w.filePath}),w.testFile?n(xb,{testFile:w.testFile,entityName:w.name}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},w.name))})]}),g.commitSha&&l("div",{className:"flex items-center gap-1.5 text-[10px]",children:[n("span",{className:"font-mono text-[#00a0c4] bg-[#00a0c4]/10 px-1.5 py-0.5 rounded",children:g.commitSha.slice(0,7)}),n("span",{className:"text-gray-500 truncate",children:g.commitMessage})]})]}),l("button",{onClick:()=>u(b),className:"w-full py-1.5 text-[10px] text-gray-500 hover:text-gray-300 border-t border-[#3d3d3d] transition-colors cursor-pointer",children:["——— ",N?"Collapse":"Expand"," ———"]})]},b)})})]},f))})})}function $t({imgSrc:e,name:t,isActive:r,onSelect:s}){return l("button",{onClick:s,className:"flex flex-col items-center gap-1 cursor-pointer group",title:t,children:[n("div",{className:`w-24 h-24 rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] ${r?"border-[#005c75] ring-1 ring-[#005c75]":"border-transparent hover:border-[#4d4d4d]"}`,children:e?n("img",{src:e,alt:t,className:"w-full h-full object-contain",loading:"lazy"}):n("div",{className:"w-full h-full bg-[#1a1a1a] flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})})}),n("span",{className:`text-[10px] leading-tight text-center truncate w-24 ${r?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:t})]})}function Uo({filePath:e}){return e?l("div",{className:"flex items-center gap-1 mt-0.5",children:[l("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(_t,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function Cb({hasProject:e,scenarios:t,analyzedEntities:r,glossaryFunctions:s=[],projectRoot:a,activeScenarioId:o,onScenarioSelect:i,onAnalyzedScenarioSelect:c,onSwitchToBuild:d,zoomComponent:m,onZoomChange:u,entityImports:h,pageFilePaths:p={}}){const{pageGroups:f,componentGroups:y}=ne(()=>{const w=new Map,S=new Map;for(const k of t)if(k.componentName){const E=S.get(k.componentName)||[];E.push(k),S.set(k.componentName,E)}else{const E=Wn(k.url),A=w.get(E)||[];A.push(k),w.set(E,A)}const C=new Map([...S.entries()].sort(([k],[E])=>k.localeCompare(E)));return{pageGroups:w,componentGroups:C}},[t]),g=be(null),x=be(0),v=oe(()=>{g.current&&(x.current=g.current.scrollTop)},[]);if(te(()=>{g.current&&x.current>0&&(g.current.scrollTop=x.current)}),!e)return n("div",{className:"flex-1 flex items-center justify-center",children:l("div",{className:"flex flex-col items-center gap-4",children:[n("h2",{className:"text-lg font-medium text-white font-['IBM_Plex_Sans'] m-0",children:"Ready to build something?"}),n("button",{onClick:d,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Start Building"})]})});const b=ne(()=>r.filter(w=>w.entityType==="visual").sort((w,S)=>w.name.localeCompare(S.name)),[r]);if(!(t.length>0||b.length>0))return n("div",{className:"flex-1 flex items-center justify-center",children:l("div",{className:"flex flex-col items-center gap-4 px-8 text-center",children:[n("h2",{className:"text-lg font-medium text-white font-['IBM_Plex_Sans'] m-0",children:"Your project is ready"}),n("p",{className:"text-sm text-gray-400 m-0 font-['IBM_Plex_Sans'] leading-relaxed max-w-[280px]",children:"Describe what you want to build in the Chat and your pages and components will appear here."}),n("button",{onClick:d,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Start Building"})]})});if(m){const w=f.get(m)||[],S=y.get(m)||[],C=b.find(P=>P.name===m),k=f.has(m),E=new Set((h==null?void 0:h[m])||[]),A=E.size>0,I=A?[...y.entries()].filter(([P])=>E.has(P)):[...y.entries()],j=A?b.filter(P=>E.has(P.name)):b;return n("div",{className:"flex-1 overflow-auto",children:l("div",{className:"p-4 space-y-3",children:[l("button",{onClick:()=>u(void 0),className:"flex items-center gap-2 text-xs text-gray-400 hover:text-white transition-colors cursor-pointer bg-transparent border-none p-0",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M7.5 9L4.5 6L7.5 3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"All"]}),n("h2",{className:"text-sm font-semibold text-white m-0 font-['IBM_Plex_Sans'] uppercase tracking-wider",children:m}),w.length>0&&n("div",{className:"flex flex-wrap gap-2",children:w.map(P=>n($t,{imgSrc:P.screenshotPath?`/api/editor-scenario-image/${P.id}.png`:null,name:P.name,isActive:P.id===o,onSelect:()=>i(P)},P.id))}),S.length>0&&n("div",{className:"flex flex-wrap gap-2",children:S.map(P=>n($t,{imgSrc:P.screenshotPath?`/api/editor-scenario-image/${P.id}.png`:null,name:P.name,isActive:P.id===o,onSelect:()=>i(P)},P.id))}),C&&(C.scenarios.length>0||C.pendingScenarios.length>0)&&l("div",{className:"flex flex-wrap gap-2",children:[C.scenarios.map(P=>n($t,{imgSrc:P.screenshotPath?`/api/screenshot/${P.screenshotPath}`:null,name:P.name,isActive:!1,onSelect:()=>c({analysisId:C.analysisId,scenarioId:P.id,scenarioName:P.name,entitySha:C.sha,entityName:C.name})},P.id)),C.pendingScenarios.map(P=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:P,children:P},P))]}),k&&I.length>0&&l("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),I.map(([P,$])=>l("div",{className:"mt-3",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(P),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:P})}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:$.map(T=>n($t,{imgSrc:T.screenshotPath?`/api/editor-scenario-image/${T.id}.png`:null,name:T.name,isActive:T.id===o,onSelect:()=>i(T)},T.id))})]},P))]}),k&&j.length>0&&l("div",{className:`${I.length===0?"pt-2 mt-1 border-t border-[#3d3d3d]":"mt-2"}`,children:[I.length===0&&n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),j.map(P=>l("div",{className:"mt-3",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(P.name),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:P.name})}),(P.scenarios.length>0||P.pendingScenarios.length>0)&&l("div",{className:"flex flex-wrap gap-2 pt-1",children:[P.scenarios.map($=>n($t,{imgSrc:$.screenshotPath?`/api/screenshot/${$.screenshotPath}`:null,name:$.name,isActive:!1,onSelect:()=>c({analysisId:P.analysisId,scenarioId:$.id,scenarioName:$.name,entitySha:P.sha,entityName:P.name})},$.id)),P.pendingScenarios.map($=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:$,children:$},$))]})]},P.sha))]}),w.length===0&&S.length===0&&!C&&n("div",{className:"text-xs text-gray-500",children:"No scenarios for this entity"})]})})}return n("div",{ref:g,onScroll:v,className:"flex-1 overflow-auto",children:l("div",{className:"p-4 space-y-4",children:[n("h2",{className:"text-sm font-medium text-gray-300 m-0 font-['IBM_Plex_Sans']",children:"What do you want to work on next?"}),n("button",{onClick:d,className:"w-full py-3 border-2 border-dashed border-[#4d4d4d] rounded-lg text-sm text-gray-400 hover:border-[#005c75] hover:text-white transition-colors cursor-pointer bg-transparent",children:"+ New Page"}),f.size>0&&l("div",{children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),[...f.entries()].sort(([w],[S])=>w==="Home"?-1:S==="Home"?1:w.localeCompare(S)).map(([w,S])=>l("div",{className:"mt-2",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(w),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:w})}),p[w]&&n(Uo,{filePath:p[w],projectRoot:a}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:S.map(C=>n($t,{imgSrc:C.screenshotPath?`/api/editor-scenario-image/${C.id}.png`:null,name:C.name,isActive:C.id===o,onSelect:()=>i(C)},C.id))})]},w))]}),y.size>0&&n("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),[...y.entries()].map(([w,S])=>l("div",{children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(w),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:w})}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:S.map(C=>n($t,{imgSrc:C.screenshotPath?`/api/editor-scenario-image/${C.id}.png`:null,name:C.name,isActive:C.id===o,onSelect:()=>i(C)},C.id))})]},w)),b.map(w=>l("div",{children:[l("div",{className:"flex items-center gap-2 py-1",children:[n("button",{onClick:()=>u(w.name),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:w.name}),w.isAnalyzing&&w.scenarioCount===0&&l("span",{className:"flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),(w.scenarios.length>0||w.pendingScenarios.length>0)&&l("div",{className:"flex flex-wrap gap-2 pt-1",children:[w.scenarios.map(S=>n($t,{imgSrc:S.screenshotPath?`/api/screenshot/${S.screenshotPath}`:null,name:S.name,isActive:!1,onSelect:()=>c({analysisId:w.analysisId,scenarioId:S.id,scenarioName:S.name,entitySha:w.sha,entityName:w.name})},S.id)),w.pendingScenarios.map(S=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:S,children:S},S))]})]},w.sha)),s.length>0&&l("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),s.map(w=>l("div",{className:"mt-2",children:[l("div",{className:"flex items-center gap-2 py-1",children:[n("span",{className:"text-[11px] font-medium text-gray-300",children:w.name}),w.testFile&&n("span",{className:"text-[9px] text-green-400 bg-green-400/10 px-1.5 py-0.5 rounded",children:"tested"})]}),w.description&&n("p",{className:"text-[10px] text-gray-500 mt-0 mb-0 leading-relaxed",children:w.description}),n(Uo,{filePath:w.filePath,projectRoot:a})]},w.name))]})]})})}function Sb({items:e,onNavigate:t}){return e.length===0?null:n("nav",{className:"flex items-center gap-1 text-xs",children:e.map((r,s)=>{const a=s===e.length-1;return l("span",{className:"flex items-center gap-1",children:[s>0&&n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"text-gray-500",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),a?n("span",{className:"text-white font-medium",children:r.name}):n("button",{onClick:()=>t(r.componentName),className:"text-gray-400 hover:text-white transition-colors cursor-pointer",children:r.name})]},r.componentName||"app")})})}const Wo={new:0,edited:1,impacted:2};function Jo({status:e,onClick:t}){const r={new:{label:"New",bg:"bg-green-100",text:"text-green-700",border:"border-green-200"},edited:{label:"Edited",bg:"bg-blue-100",text:"text-blue-700",border:"border-blue-200"},impacted:{label:"Impacted",bg:"bg-amber-100",text:"text-amber-700",border:"border-amber-200"}}[e.status],s=t&&(e.status==="edited"||e.status==="impacted");return n("button",{onClick:s?t:void 0,className:`${r.bg} ${r.text} ${r.border} border text-[9px] font-bold px-1.5 py-0.5 rounded-full uppercase tracking-wider shrink-0 ${s?"cursor-pointer hover:opacity-80 transition-opacity":"cursor-default"}`,children:r.label})}function Ho({filePath:e}){const[t,r]=_(null),[s,a]=_(!0),[o,i]=_(null);return te(()=>{import("react-diff-viewer-continued").then(c=>{i(()=>c.default)})},[]),te(()=>{a(!0),fetch(`/api/editor-file-diff?path=${encodeURIComponent(e)}`).then(c=>c.json()).then(c=>{r({oldContent:c.oldContent,newContent:c.newContent})}).catch(()=>{r(null)}).finally(()=>a(!1))},[e]),s?n("div",{className:"p-2 text-[10px] text-gray-400",children:"Loading diff..."}):!t||!o?n("div",{className:"p-2 text-[10px] text-gray-400",children:"Could not load diff"}):n("div",{className:"mt-2 border border-gray-200 rounded-lg overflow-hidden max-h-[300px] overflow-auto text-xs",children:n(o,{oldValue:t.oldContent,newValue:t.newContent,splitView:!1,useDarkTheme:!1,showDiffOnly:!0,styles:{contentText:{fontSize:"11px",lineHeight:"1.4"},line:{padding:"1px 8px",fontSize:"11px"}}})})}function Vo({impactedBy:e,changedEntities:t}){return n("div",{className:"mt-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5",children:e&&e.length>0?l(ue,{children:[n("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"Re-captured because these dependencies changed"}),n("ul",{className:"mt-1.5 space-y-1",children:e.map(r=>l("li",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold px-1 py-0 rounded-full uppercase tracking-wider border ${r.changeType==="new"?"bg-green-100 text-green-700 border-green-200":"bg-blue-100 text-blue-700 border-blue-200"}`,children:r.changeType==="new"?"New":"Edited"}),n("span",{className:"text-[11px] font-medium text-amber-800",children:r.name}),n("span",{className:"text-[9px] text-amber-500 truncate",children:r.filePath})]},r.filePath))})]}):t&&t.length>0?l(ue,{children:[n("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"Unchanged — these entities were modified in this session"}),n("ul",{className:"mt-1.5 space-y-1",children:t.map(r=>l("li",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold px-1 py-0 rounded-full uppercase tracking-wider border ${r.status==="new"?"bg-green-100 text-green-700 border-green-200":"bg-blue-100 text-blue-700 border-blue-200"}`,children:r.status==="new"?"New":"Edited"}),n("span",{className:"text-[11px] font-medium text-amber-800",children:r.name})]},r.name))})]}):n("span",{className:"text-[10px] text-amber-600",children:"This component was re-captured because a dependency changed"})})}function qo({scenarioId:e,name:t,isActive:r,onSelect:s}){const[a,o]=_(!1);return te(()=>{o(!1)},[e]),l("button",{onClick:s,className:"flex flex-col items-center gap-1.5 cursor-pointer group",title:t,children:[n("div",{className:`w-32 h-32 rounded-lg overflow-hidden border-2 transition-all ${r?"border-[#0ea5e9] ring-2 ring-[#0ea5e9]/40 shadow-lg shadow-[#0ea5e9]/20":"border-gray-200 hover:border-gray-400 shadow-sm"}`,children:a?n("div",{className:"w-full h-full bg-gray-100 flex items-center justify-center",children:n("span",{className:"text-[9px] text-gray-400",children:"No preview"})}):n("img",{src:`/api/editor-scenario-image/${e}.png`,alt:t,className:"w-full h-full object-contain bg-white",loading:"lazy",onError:()=>o(!0)})}),n("span",{className:`text-[11px] leading-tight text-center truncate w-32 font-medium ${r?"text-gray-900":"text-gray-600 group-hover:text-gray-900"}`,children:t})]})}function kb({filePath:e}){return e?l("div",{className:"flex items-center gap-1 mt-0.5",children:[l("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-400 hover:text-gray-600 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(_t,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-400 hover:text-gray-600 transition-colors"})]}):null}function Eb({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=_a(e);if(s&&!r)return l("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#0ea5e9] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!r)return null;if(r.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-500",children:r.errorMessage})});const o=t?r.testCases.filter(d=>d.fullName.startsWith(t)):r.testCases,i=o.length>0?o:r.testCases;if(i.length===0)return null;const c=t?`${t} > `:"";return l("div",{className:"pt-1 space-y-0.5",children:[i.map(d=>{var u;const m=c&&d.fullName.startsWith(c)?d.fullName.slice(c.length):d.fullName;return l("div",{children:[l("div",{className:"flex items-center gap-1.5",children:[d.status==="passed"?n("span",{className:"text-green-600 text-[10px]",children:"✓"}):d.status==="failed"?n("span",{className:"text-red-500 text-[10px]",children:"✗"}):n("span",{className:"text-gray-400 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${d.status==="passed"?"text-green-600":d.status==="failed"?"text-red-500":"text-gray-400"}`,children:m})]}),d.status==="failed"&&((u=d.failureMessages)==null?void 0:u.map((h,p)=>n("div",{className:"pl-4 text-[9px] text-red-400 truncate max-w-full",title:h,children:h.split(`
|
|
335
|
+
`)[0]},p)))]},d.fullName)}),n("button",{onClick:a,disabled:s,className:"mt-1 text-[10px] text-[#0ea5e9] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:s?"Running...":"Re-run"})]})}function Go(e){const t=e.indexOf(" - ");return t!==-1?e.slice(t+3):e}function Ko(e,t){return!t||Object.keys(t).length===0?e:[...e].sort(([r],[s])=>{var c,d;const a=((c=t[r])==null?void 0:c.status)||"impacted",o=((d=t[s])==null?void 0:d.status)||"impacted",i=(Wo[a]??2)-(Wo[o]??2);return i!==0?i:r.localeCompare(s)})}function Ab({scenarios:e,glossaryFunctions:t=[],projectRoot:r,activeScenarioId:s,onScenarioSelect:a,onClose:o,entityChangeStatus:i={}}){const c=ne(()=>Object.entries(i).filter(([,b])=>b.status==="new"||b.status==="edited").map(([b,N])=>({name:b,status:N.status})),[i]),[d,m]=_(null),u=oe(b=>{m(N=>N===b?null:b)},[]),{pageGroups:h,componentGroups:p}=ne(()=>{const b=new Map,N=new Map;for(const w of e)if(w.componentName){const S=N.get(w.componentName)||[];S.push(w),N.set(w.componentName,S)}else{const S=Wn(w.url),C=b.get(S)||[];C.push(w),b.set(S,C)}return{pageGroups:b,componentGroups:N}},[e]),f=ne(()=>Ko([...h.entries()],i),[h,i]),y=ne(()=>Ko([...p.entries()],i),[p,i]),g=ne(()=>Vs(f,i),[f,i]),x=ne(()=>Vs(y,i),[y,i]),v=t;return e.length===0&&t.length===0?l("div",{className:"h-full bg-white flex items-center justify-center relative",children:[n("button",{onClick:o,className:"absolute top-2 right-3 text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none",title:"Close results",children:"×"}),n("span",{className:"text-sm text-gray-400",children:"No scenarios registered yet"})]}):l("div",{className:"h-full bg-white flex flex-col overflow-hidden",children:[l("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-gray-200 shrink-0",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Working Session Results"}),n("button",{onClick:o,className:"text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none",title:"Close results",children:"×"})]}),n("div",{className:"flex-1 overflow-auto p-4",children:l("div",{className:"space-y-5",children:[g.length>0&&l("div",{children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"})}),n("div",{className:"space-y-3 pl-1",children:g.map(([b,N])=>{var k;const w=i[b],S=d===b,C=(k=N[0])==null?void 0:k.componentPath;return l("div",{children:[l("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:b}),w&&n(Jo,{status:w,onClick:()=>u(b)})]}),S&&(w==null?void 0:w.status)==="edited"&&C&&n(Ho,{filePath:C}),S&&(w==null?void 0:w.status)==="impacted"&&n(Vo,{impactedBy:w.impactedBy,changedEntities:c}),n("div",{className:"flex flex-wrap gap-3",children:N.map(E=>n(qo,{scenarioId:E.id,name:Go(E.name),isActive:E.id===s,onSelect:()=>a(E)},E.id))})]},b)})})]}),x.length>0&&l("div",{className:g.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),n("div",{className:"space-y-3 pl-1",children:x.map(([b,N])=>{var k;const w=i[b],S=d===b,C=(k=N[0])==null?void 0:k.componentPath;return l("div",{children:[l("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:b}),w&&n(Jo,{status:w,onClick:()=>u(b)})]}),S&&(w==null?void 0:w.status)==="edited"&&C&&n(Ho,{filePath:C}),S&&(w==null?void 0:w.status)==="impacted"&&n(Vo,{impactedBy:w.impactedBy,changedEntities:c}),n("div",{className:"flex flex-wrap gap-3",children:N.map(E=>n(qo,{scenarioId:E.id,name:Go(E.name),isActive:E.id===s,onSelect:()=>a(E)},E.id))})]},b)})})]}),v.length>0&&l("div",{className:g.length>0||x.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),n("div",{className:"space-y-2 pl-1",children:v.map(b=>l("div",{children:[n("div",{className:"flex items-center gap-2",children:n("span",{className:"text-[11px] font-medium text-gray-700",children:b.name})}),n(kb,{filePath:b.filePath,projectRoot:r}),b.testFile?n(Eb,{testFile:b.testFile,entityName:b.name}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-400",children:"No test file"})})]},b.name))})]})]})})]})}function Pb(e){const{activeAnalyzedScenario:t,analyzedPreviewUrl:r,activeScenarioId:s,scenarios:a,proxyUrl:o,devServerUrl:i,zoomComponent:c}=e;if(t&&r)return r;if(t&&!r)return null;if(s){const m=a.find(u=>u.id===s);if(m!=null&&m.url){const u=o||i;return u?m.url.startsWith("/")?`${u}${m.url}`:m.url:null}}const d=o||i;if(!d)return null;if(c&&s){const m=a.find(h=>h.id===s),u=m?Vt(m.name):"Default";return`${d}/__codeyam__/${c}/${u}`}return d}function _b(e,t){const r=t.width,s=t.height??900,a=e.width,o=e.height;return r<=a&&s<=o?1:Math.min(a/r,o/s)}const jb=()=>[{title:"Editor - CodeYam"},{name:"description",content:"CodeYam Code + Data Editor"}];async function Mb({request:e}){var p,f;const t=await $e();let r=!1,s=[];if(t){const{project:y}=await Ie(t);r=((p=y.metadata)==null?void 0:p.editorMode)??!1;try{const g=Te();for(const S of["component_name","component_path","screenshot_path","url"])try{await g.schema.alterTable("editor_scenarios").addColumn(S,"varchar").execute()}catch{}const x=he()||process.cwd(),v=O.join(x,".codeyam","editor-step.json");let b=null;try{const S=G.readFileSync(v,"utf8");b=JSON.parse(S).featureStartedAt||null}catch{}let N=g.selectFrom("editor_scenarios").selectAll().where("project_id","=",y.id);if(b){const S=Pr(b);N=N.where("created_at",">=",S)}const w=await N.orderBy("created_at","asc").execute();if(s=es(w,S=>`${S.name}::${S.url||"/"}`).map(S=>({id:S.id,name:S.name,description:S.description||"",componentName:S.component_name||null,componentPath:S.component_path||null,screenshotPath:S.screenshot_path||null,url:S.url||null})),b){const S=A=>!A||A==="/"?"/":"/"+A.split("?")[0].replace(/^\//,"").split("/")[0],C=new Set(s.filter(A=>!A.componentName).map(A=>S(A.url))),k=Pr(b),E=await g.selectFrom("editor_scenarios").selectAll().where("project_id","=",y.id).where("component_name","is",null).where("created_at","<",k).orderBy("created_at","desc").execute();for(const A of E){const I=S(A.url||null);C.has(I)||s.push({id:A.id,name:A.name,description:A.description||"",componentName:null,componentPath:null,screenshotPath:A.screenshot_path||null,url:A.url||null})}}}catch{}}const a=[...new Set(s.map(y=>y.componentName).filter(y=>y!==null))];let o=[];try{const y=he()||process.cwd(),g=O.join(y,".codeyam","glossary.json");if(G.existsSync(g)){const x=G.readFileSync(g,"utf8");o=JSON.parse(x)}}catch{}const i=o.filter(y=>y.testFile&&y.returnType!=="JSX.Element"&&y.returnType!=="React.ReactNode").map(y=>({name:y.name,filePath:y.filePath,description:y.description||"",testFile:y.testFile,feature:y.feature}));let c=[];try{c=(await tn()||[]).filter(g=>g.analyses&&g.analyses.length>0).map(g=>{var E;const x=g.analyses[0],v=x.scenarios||[],b=!((E=x.status)!=null&&E.finishedAt),N=g.entityType||"visual",w=N==="library"||N==="functionCall",S=v.filter(A=>{var I,j,P,$,T;return w?!!((I=A.metadata)!=null&&I.executionResult):((P=(j=A.metadata)==null?void 0:j.screenshotPaths)==null?void 0:P[0])&&!(($=A.metadata)!=null&&$.noScreenshotSaved)&&!((T=A.metadata)!=null&&T.sameAsDefault)}),C=v.filter(A=>{var I,j,P,$;return w?!((I=A.metadata)!=null&&I.executionResult):!((P=(j=A.metadata)==null?void 0:j.screenshotPaths)!=null&&P[0])||(($=A.metadata)==null?void 0:$.noScreenshotSaved)}),k=o.find(A=>A.filePath===(g.filePath||""));return{sha:g.sha,name:g.name,entityType:N,filePath:g.filePath||"",analysisId:x.id,isAnalyzing:b,scenarioCount:v.length,scenarios:S.map(A=>{var I,j;return{id:A.id,name:A.name,description:A.description||"",screenshotPath:((j=(I=A.metadata)==null?void 0:I.screenshotPaths)==null?void 0:j[0])||null}}),pendingScenarios:C.map(A=>A.name),testFile:k==null?void 0:k.testFile}})}catch{}let d=[];try{if(c.length>0){const y=c.map(g=>g.sha);await Ye(),d=await lt({shas:y})||[]}}catch{}const m={};try{if(d.length>0){const y=new Set([...c.map(g=>g.name),...a]);for(const g of d){const v=(((f=g.metadata)==null?void 0:f.importedExports)||[]).map(b=>b.name).filter(b=>y.has(b));v.length>0&&(m[g.name]=v)}}}catch{}const u={};try{const y=he()||process.cwd(),g=O.join(y,"app");if(G.existsSync(g)){const x=(v,b)=>{for(const N of G.readdirSync(v,{withFileTypes:!0}))if(N.name!=="codeyam-isolate"){if(N.isDirectory())x(O.join(v,N.name),b?`${b}/${N.name}`:N.name);else if(N.name==="page.tsx"||N.name==="page.js"){const w=b?`app/${b}/${N.name}`:`app/${N.name}`;let S;if(!b)S="Home";else{const C=b.split("/")[0];S=C.charAt(0).toUpperCase()+C.slice(1)}u[S]=w}}};x(g,"")}}catch{}let h={};try{let y=!1;try{const v=he()||process.cwd(),b=Pe("git rev-list --count HEAD",{cwd:v,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();y=parseInt(b,10)<=1}catch{y=!0}const g=gl(ns(),y),x=yl(s,u,d);h=xl(g,x)}catch{}return K({projectSlug:t,projectRoot:he(),hasProject:!!t,editorMode:r,devServerUrl:null,scenarios:s,components:a,analyzedEntities:c,glossaryFunctions:i,entityImports:m,pageFilePaths:u,entityChangeStatus:h})}const Rs=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}];function Tb({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,onStateChange:o}){const{interactiveServerUrl:i,isStarting:c,isLoading:d}=nn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:!0});return te(()=>{o(i,c||d)},[i,c,d,o]),null}const $b=Je(function(){const{projectSlug:t,projectRoot:r,hasProject:s,scenarios:a,analyzedEntities:o,glossaryFunctions:i,entityImports:c,pageFilePaths:d,entityChangeStatus:m}=Ve(),u=ft(),[h,p]=fn(),f=be(null),y=be(null),g=be(null),x=h.get("zoom")||void 0,v=h.get("scenario")||void 0;te(()=>{if(!v)return;const se=a.find(_e=>_e.id===v);if(!se)return;const pe=Vt(se.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:pe,scenarioId:se.id,scenarioName:se.name})}).catch(()=>{})},[v,a]),te(()=>{const se=new BroadcastChannel("codeyam-editor");return se.onmessage=pe=>{var _e;if(((_e=pe.data)==null?void 0:_e.type)==="switch-scenario"&&pe.data.scenarioId){const Re=pe.data.scenarioId,We=a.find(on=>on.id===Re);if(!We)return;const Yt=new URLSearchParams(h);Yt.set("scenario",Re),Yt.delete("zoom"),p(Yt),R(null),q(null),D(null);const Qn=Vt(We.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Qn,scenarioId:Re})}).then(()=>{xt(on=>on+1),j(!1)}).catch(()=>{})}},()=>se.close()},[h,p,a]),te(()=>{if(h.get("ref")!=="link"||!v)return;const se=new BroadcastChannel("codeyam-editor");se.postMessage({type:"switch-scenario",scenarioId:v}),se.close(),window.close()},[]);const[b,N]=_(null),[w,S]=_(null),[C,k]=_(!1),[E,A]=_(null),[I,j]=_(!1),[P,$]=_(!0),[T,R]=_(null),[J,q]=_(null),[Y,H]=_(!1),[B,D]=_(null),[M,Q]=_(!1),[U,F]=_(null),X=oe(se=>{D(se),F(null)},[]),z=oe((se,pe)=>{q(_e=>(se&&se!==_e&&j(!1),se)),!pe&&se&&j(!0),H(pe)},[]),L=oe(se=>{D(null),R(_e=>(_e&&_e.analysisId===se.analysisId||(q(null),xt(We=>We+1)),se)),H(!0),j(!1);const pe=new URLSearchParams(h);pe.delete("scenario"),pe.delete("zoom"),p(pe)},[h,p]),[W,V]=_(1440),[Z,ce]=_({name:"Desktop",width:1440,height:900}),[ve,ae]=_(!1),[me,Se]=_(null),[Ne,Ae]=_("app"),De=oe(()=>{Ae("build"),Ee(!0)},[]),[Oe,Ee]=_(!1),[re,ye]=_(!1),ke=oe(se=>{ye(se)},[]),[rt,fe]=_(!1),He=oe(()=>{fe(!0),Ae("build"),Ee(!0)},[]),Ue=oe(()=>{fe(!1)},[]),[Ze,Hn]=_(!1),Ra=oe(()=>{if(Ze){Hn(!1);return}typeof Notification<"u"&&Notification.permission==="default"?Notification.requestPermission().then(se=>{se==="granted"&&Hn(!0)}):Hn(!0)},[Ze]);te(()=>{if(Ne==="build"){ye(!1);const se=setTimeout(()=>{var pe,_e;(pe=f.current)==null||pe.scrollToBottom(),(_e=f.current)==null||_e.focus()},50);return()=>clearTimeout(se)}},[Ne]);const[Vn,rn]=_(null);te(()=>{const se=g.current;if(!se)return;const pe=new ResizeObserver(_e=>{const Re=_e[0];Re&&rn({width:Re.contentRect.width,height:Re.contentRect.height})});return pe.observe(se),()=>pe.disconnect()},[]);const Xe=ne(()=>Vn?_b(Vn,Z):1,[Vn,Z]),[qn,xt]=_(0),[vn,sn]=_(null),st=oe(se=>{sn(se||null),xt(pe=>pe+1)},[]),{customSizes:dt,addCustomSize:Ge}=Qr(t),ze=ne(()=>[...Rs,...dt],[dt]),Gn=be(!1);te(()=>{let se=!1,pe=null;const _e=async()=>{try{const Re=await fetch("/api/editor-dev-server");if(se)return;const We=await Re.json();if(We.status==="error")N(null),S(null),k(!1),A(We.errorMessage||"Dev server crashed");else if(We.url)N(We.url),S(We.proxyUrl||null),k(!1),A(null),$(!0);else if(We.status==="starting")k(!0),A(null),$(!0);else if(We.status==="stopped")if(b)N(null),k(!1);else if(Gn.current)k(!1);else{Gn.current=!0;try{(await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})})).ok?k(!0):$(!1)}catch{}}}catch{}};return _e(),pe=setInterval(()=>void _e(),2e3),()=>{se=!0,pe&&clearInterval(pe)}},[b]),te(()=>{const se=new EventSource("/api/events");let pe=null;return se.addEventListener("message",_e=>{try{const Re=JSON.parse(_e.data);(Re.type==="db-change"||Re.type==="unknown")&&(pe&&clearTimeout(pe),pe=setTimeout(()=>{u.revalidate()},2e3))}catch{}}),()=>{pe&&clearTimeout(pe),se.close()}},[u]);const wn=ne(()=>{const se=[{name:"App"}];return x&&se.push({name:x,componentName:x}),se},[x]),an=oe(se=>{const pe=new URLSearchParams(h);if(se){pe.set("zoom",se);const _e=a.find(Re=>Re.componentName===se||Re.componentName===null&&se==="Home");if(_e){pe.set("scenario",_e.id);const Re=Vt(_e.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Re,scenarioId:_e.id})}).catch(()=>{}),xt(We=>We+1),j(!1)}else pe.delete("scenario")}else pe.delete("zoom"),pe.delete("scenario");p(pe)},[h,p,a]),Nn=oe(se=>{R(null),q(null),D(null);const pe=new URLSearchParams(h);pe.set("scenario",se.id),p(pe);const _e=Vt(se.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:_e,scenarioId:se.id})}).catch(()=>{}),xt(Re=>Re+1),j(!1)},[h,p]),Kn=(se,pe)=>{V(se);const _e=ze.find(Re=>Re.width===se&&Re.height===pe);ce({name:(_e==null?void 0:_e.name)||"Custom",width:se,height:pe})},Cn=se=>{V(se.width),ce({name:se.name,width:se.width,height:se.height})},os=se=>{Ge(se,Z.width,Z.height??900),ae(!1),ce(pe=>({...pe,name:se}))},is=()=>{T||j(!0)},ls=oe(()=>{A(null),k(!0),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})}).catch(()=>{})},[]),cs=oe(()=>{A(null),k(!0),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}).catch(()=>{})},[]),ut=ne(()=>Pb({activeAnalyzedScenario:!!T,analyzedPreviewUrl:J,activeScenarioId:v||null,scenarios:a,proxyUrl:w,devServerUrl:b,zoomComponent:x||null}),[w,b,x,v,a,T,J]),ds=ne(()=>{if(!ut||!vn)return ut;try{const se=new URL(ut);return se.pathname=vn,se.href}catch{return ut}},[ut,vn]);return l("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[T&&n(Tb,{analysisId:T.analysisId,scenarioId:T.scenarioId,scenarioName:T.scenarioName,entityName:T.entityName,projectSlug:t,onStateChange:z},T.analysisId),n("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:[n("img",{src:Or,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:"Editor"}),x&&l(ue,{children:[n("div",{className:"w-px h-4 bg-gray-600"}),n(Sb,{items:wn,onNavigate:an})]}),n("span",{className:"bg-[#005c75] text-white text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wider ml-auto",children:"Code + Data"})]})}),l("div",{className:"flex-1 flex min-h-0",children:[l("div",{className:"flex-1 flex flex-col min-w-0",children:[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:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Rs[Rs.length-1].width}px`,width:"100%"},children:n(Gr,{currentViewportWidth:W,currentPresetName:Z.name,onDevicePresetClick:Cn,devicePresets:ze,hideLabel:!0,onHoverChange:Se,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:[n("span",{className:"leading-none",children:(me==null?void 0:me.name)||Z.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l("select",{value:Z.name,onChange:se=>{const pe=ze.find(_e=>_e.name===se.target.value);pe&&Cn(pe)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[ze.map(se=>n("option",{value:se.name,children:se.name},se.name)),Z.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:Z.width,onChange:se=>{const pe=parseInt(se.target.value,10);!isNaN(pe)&&pe>0&&Kn(pe,Z.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"x"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:Z.height??900}),Z.name==="Custom"&&n("button",{onClick:()=>ae(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{ref:g,className:"flex-1 flex items-center justify-center overflow-hidden p-8",style:{backgroundImage:`
|
|
336
|
+
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
337
|
+
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
338
|
+
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
339
|
+
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
340
|
+
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:B?l("div",{className:"flex flex-col items-center gap-6 max-w-[700px] w-full",children:[l("div",{className:"text-center",children:[n("h2",{className:"text-lg font-semibold text-[#333] m-0 font-['IBM_Plex_Sans']",children:"Journal Screenshot"}),n("p",{className:"text-sm text-[#888] mt-1 m-0 font-['IBM_Plex_Sans']",children:"This is a snapshot from a previous version — not a live preview"})]}),n("div",{className:"rounded-lg overflow-hidden border-2 border-[#ccc] shadow-md max-w-full w-fit",children:n("img",{src:B.screenshotUrl,alt:B.scenarioName,className:"max-w-full h-auto block"})}),l("div",{className:"flex items-center gap-2 text-sm text-[#666]",children:[B.commitSha&&n("span",{className:"font-mono text-xs text-[#00a0c4] bg-[#00a0c4]/15 px-2 py-0.5 rounded",children:B.commitSha.slice(0,7)}),l("span",{className:"truncate",children:[B.scenarioName,B.commitMessage&&` — ${B.commitMessage}`]})]}),l("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>D(null),className:"text-sm text-[#888] hover:text-[#333] transition-colors cursor-pointer px-3 py-1.5 rounded border border-[#ccc] hover:border-[#999] bg-white",children:"Back to live preview"}),B.commitSha&&n("button",{onClick:()=>{Q(!0),F(null),fetch("/api/editor-load-commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commitSha:B.commitSha})}).then(se=>se.json()).then(se=>{se.success?(D(null),k(!0),j(!1)):F(se.error||"Failed to load commit")}).catch(se=>{F(se instanceof Error?se.message:"Network error")}).finally(()=>{Q(!1)})},disabled:M,className:"bg-[#005c75] hover:bg-[#004d63] disabled:opacity-50 text-white text-sm font-medium px-4 py-1.5 rounded transition-colors cursor-pointer",children:M?"Loading...":"Load this version"})]}),U&&n("div",{className:"bg-red-50 border border-red-200 rounded px-4 py-2 text-sm text-red-600 w-full text-center",children:U})]}):ut?n("div",{style:{width:`${Z.width*Xe}px`,height:`${(Z.height??900)*Xe}px`},children:l("div",{className:"relative bg-white origin-top-left",style:{width:`${Z.width}px`,height:`${Z.height??900}px`,transform:Xe<1?`scale(${Xe})`:void 0},children:[!I&&n("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:[n("div",{className:"mb-4",children:n(Ot,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the app to render"})]})]})}),n("iframe",{ref:y,src:ds||ut,className:"w-full h-full border-none",title:"Editor preview",onLoad:is,style:{opacity:I?1:0}},qn)]})}):n("div",{className:"bg-white rounded-lg shadow-sm flex flex-col items-center justify-center",style:{width:`${Z.width*Xe}px`,height:`${(Z.height??900)*Xe}px`},children:E?l("div",{className:"flex flex-col gap-4 text-center px-8 max-w-[600px]",children:[n("h2",{className:"text-xl font-medium text-red-600 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Dev Server Failed"}),n("pre",{className:"text-xs text-left bg-gray-100 text-gray-800 p-4 rounded overflow-auto max-h-[300px] w-full font-mono whitespace-pre-wrap",children:E}),n("button",{onClick:ls,className:"mx-auto px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded hover:bg-[#004d63] transition-colors cursor-pointer",children:"Retry"})]}):C||Y?l(ue,{children:[n("div",{className:"mb-4",children:n(Ot,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:Y?"Starting Interactive Mode":"Starting Dev Server"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:Y?"Loading component preview...":"Your dev server is starting up..."})]})]}):l("div",{className:"flex flex-col gap-3 text-center px-8",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Code + Data Editor"}),n("p",{className:"text-sm text-[#888] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Describe what you want to build in the chat"})]})})})]}),l("aside",{className:"w-[50%] min-w-[400px] max-w-[800px] bg-[#1e1e1e] border-r border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden order-first",children:[l("div",{className:"border-b border-[#3d3d3d] px-4 shrink-0 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-0",children:[l("button",{onClick:()=>Ae("app"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${Ne==="app"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["App",Ne==="app"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),l("button",{onClick:()=>{Ae("build"),Ee(!0)},className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${Ne==="build"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Build",re&&Ne!=="build"&&n("span",{className:"ml-1.5 inline-block w-2 h-2 rounded-full bg-amber-400 animate-pulse"}),Ne==="build"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),l("button",{onClick:()=>Ae("data"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${Ne==="data"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Data",Ne==="data"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),l("button",{onClick:()=>Ae("journal"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${Ne==="journal"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Journal",Ne==="journal"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]})]}),typeof Notification<"u"&&n("button",{onClick:Ra,className:`px-2 py-1 text-[10px] rounded transition-colors cursor-pointer ${Ze?"text-green-400 hover:text-green-300":"text-gray-500 hover:text-gray-300"}`,title:Ze?"Click to turn off notifications":"Click to get notified when Claude finishes",children:Ze?"Notifications On":"Notifications Off"})]}),l("div",{className:"flex-1 overflow-hidden relative",children:[Oe&&l("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Ne==="build"?"visible":"hidden"},children:[n("div",{className:rt?"flex-1 min-h-0":"flex-1",style:rt?{flex:"1 1 50%"}:void 0,children:n(Ji,{ref:f,entityName:"Editor",projectSlug:t,entityFilePath:null,scenarioName:null,onRefreshPreview:st,onShowResults:He,onHideResults:Ue,editorMode:!0,onIdleChange:ke,notificationsEnabled:Ze})}),rt&&n("div",{style:{flex:"1 1 50%"},className:"min-h-0 border-t-2 border-gray-300",children:n(Ab,{scenarios:a,glossaryFunctions:i,projectRoot:r,activeScenarioId:v,onScenarioSelect:Nn,onClose:Ue,entityChangeStatus:m})})]}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Ne==="app"?"visible":"hidden"},children:n(Cb,{hasProject:s,scenarios:a,analyzedEntities:[],glossaryFunctions:i,projectRoot:r,activeScenarioId:v,onScenarioSelect:Nn,onAnalyzedScenarioSelect:L,onSwitchToBuild:De,zoomComponent:x,onZoomChange:an,entityImports:c,pageFilePaths:d})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Ne==="data"?"visible":"hidden"},children:n(yb,{scenarios:a,projectRoot:r,activeScenarioId:v,onScenarioSelect:Nn,zoomComponent:x,onZoomChange:an,analyzedEntities:[],glossaryFunctions:i,activeAnalyzedScenarioId:T==null?void 0:T.scenarioId,onAnalyzedScenarioSelect:L,entityImports:c,pageFilePaths:d})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Ne==="journal"?"visible":"hidden"},children:n(Nb,{isActive:Ne==="journal",onScreenshotClick:X,glossaryFunctions:i,pageNames:Object.keys(d)})})]})]})]}),n(Wi,{serverUrl:b,isStarting:C,projectSlug:t,devServerError:E,onStartServer:P?cs:void 0}),ve&&n(Kr,{width:Z.width,height:Z.height??900,onSave:os,onCancel:()=>ae(!1)})]})}),Rb=Object.freeze(Object.defineProperty({__proto__:null,default:$b,loader:Mb,meta:jb},Symbol.toStringTag,{value:"Module"}));function Yl({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(dd,{remarkPlugins:[ud],components:{h1:({children:s})=>n("h1",{className:"text-lg font-bold text-gray-900 mb-3 mt-6 first:mt-0 pb-1 border-b border-gray-200",children:s}),h2:({children:s})=>n("h2",{className:"text-base font-semibold text-gray-900 mb-2 mt-5 first:mt-0",children:s}),h3:({children:s})=>n("h3",{className:"text-sm font-semibold text-gray-800 mb-2 mt-4 first:mt-0",children:s}),p:({children:s})=>n("p",{className:"text-sm text-gray-700 mb-3 leading-relaxed",children:s}),ul:({children:s})=>n("ul",{className:"list-disc ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:s}),ol:({children:s})=>n("ol",{className:"list-decimal ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:s}),li:({children:s})=>n("li",{className:"leading-relaxed",children:s}),code:({children:s,className:a})=>(a==null?void 0:a.includes("language-"))?n("pre",{className:"bg-gray-100 rounded p-3 text-xs font-mono overflow-x-auto mb-3",children:n("code",{children:s})}):n("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono text-gray-800",children:s}),pre:({children:s})=>n(ue,{children:s}),strong:({children:s})=>n("strong",{className:"font-semibold text-gray-900",children:s}),blockquote:({children:s})=>n("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic text-gray-600 mb-3",children:s}),table:({children:s})=>n("div",{className:"overflow-x-auto mb-3",children:n("table",{className:"min-w-full text-sm border-collapse border border-gray-200",children:s})}),thead:({children:s})=>n("thead",{className:"bg-gray-50",children:s}),th:({children:s})=>n("th",{className:"border border-gray-200 px-3 py-2 text-left font-semibold text-gray-900",children:s}),td:({children:s})=>n("td",{className:"border border-gray-200 px-3 py-2 text-gray-700",children:s}),a:({children:s,href:a})=>n("a",{href:a,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:s})},children:r})}function Ul(e){const t={name:"root",path:"",memories:[],children:new Map};for(const r of e){const s=r.filePath.split("/");s.pop();let a=t,o="";for(const i of s)o=o?`${o}/${i}`:i,a.children.has(i)||a.children.set(i,{name:i,path:o,memories:[],children:new Map}),a=a.children.get(i);s.length===0?t.memories.push(r):a.memories.push(r)}return t}function Wl(e){let t=e.memories.length;for(const r of e.children.values())t+=Wl(r);return t}function as(e,t){var s;const r=e.match(/^#+ (.+)$/m);return r?r[1]:((s=t.split("/").pop())==null?void 0:s.replace(".md",""))||t}function Rn(e){return Math.round(e/3.5)}function dn(e){const t=new Date(e),r=new Date;if(t.toDateString()===r.toDateString()){const d=r.getTime()-t.getTime(),m=Math.floor(d/(1e3*60)),u=Math.floor(d/(1e3*60*60));return m<3?"Just now":m<60?`${m}min ago`:u===1?"1h ago":`${u}h ago`}const a=t.toLocaleDateString("en-US",{month:"short"}),o=t.getDate(),i=t.getFullYear(),c=r.getFullYear();return i===c?`${a} ${o}`:`${a} ${o}, ${i}`}function Ib({rule:e,onEdit:t,onDelete:r,onView:s,isReviewed:a,onToggleReviewed:o,changeType:i,isUncommitted:c,changeDate:d,diff:m,isFadingOut:u,showLeftBorder:h}){const[p,f]=_(!1),[y,g]=_(!1),x=ne(()=>as(e.body,e.filePath),[e.body,e.filePath]),v=Rn(e.body.length),b=p?"#3e3e3e":c?"#d97706":"#c7c7c7",N=`rounded-lg border overflow-hidden transition-all ease-in-out ${c?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,w={...u&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return l("div",{className:N,style:w,children:[n("div",{className:`p-4 cursor-pointer ${c?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>s?s(e):f(!p),children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:p?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:b})})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:c?"#78350f":"#000"},children:x}),i&&n("span",{className:`px-2 py-0.5 rounded uppercase font-medium tracking-wider ${i==="deleted"?"bg-red-100 text-red-700":""}`,style:{fontSize:"10px",...i==="added"&&{backgroundColor:"#CBF3FA",color:"#005C75"},...i==="modified"&&{backgroundColor:"#FFE8C1",color:"#C67E06"}},children:i}),c&&n("span",{className:"px-2 py-0.5 bg-amber-200 text-amber-800 rounded font-medium uppercase tracking-wider",style:{fontSize:"10px"},children:"Uncommitted"}),l("span",{className:"text-xs text-gray-400",children:["~",v.toLocaleString()," tokens"]})]}),n("div",{className:"flex items-center gap-2 text-xs text-gray-500 flex-wrap",children:e.frontmatter.paths&&e.frontmatter.paths.length>0&&l(ue,{children:[e.frontmatter.paths.slice(0,2).map((S,C)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:S},C)),e.frontmatter.paths.length>2&&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:[d&&n("span",{className:"text-xs text-gray-400",children:dn(d)}),o&&n("button",{onClick:S=>{S.stopPropagation(),o(e.filePath,e.lastModified,a??!1)},className:`w-5 h-5 rounded-full border-2 flex items-center justify-center cursor-pointer transition-colors ${a?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,title:a?"Mark as unreviewed":"Mark as reviewed",children:a&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}),p&&l("div",{className:`border-t ${c?"border-amber-200":"border-gray-100"}`,children:[l("div",{className:`px-4 py-3 flex items-center justify-between ${c?"bg-amber-50":"bg-white"}`,children:[n("div",{className:"flex items-center gap-2",children:i==="modified"&&m&&l("button",{onClick:S=>{S.stopPropagation(),g(!y)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${y?c?"bg-amber-200 text-amber-900":"bg-gray-200 text-gray-900":c?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(xr,{className:"w-3 h-3"}),y?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&l("div",{className:"flex items-center gap-2",children:[l("button",{onClick:S=>{S.stopPropagation(),t(e)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${c?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(Rc,{className:"w-3 h-3"}),"Edit"]}),l("button",{onClick:S=>{S.stopPropagation(),r(e)},className:"flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer text-red-600 hover:text-red-800 hover:bg-red-100",children:[n(Ic,{className:"w-3 h-3"}),"Delete"]})]})]}),y&&m&&n("pre",{className:"mx-4 mb-4 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:m.split(`
|
|
341
|
+
`).map((S,C)=>{let k="";return S.startsWith("+")&&!S.startsWith("+++")?k="text-green-400":S.startsWith("-")&&!S.startsWith("---")?k="text-red-400":S.startsWith("@@")&&(k="text-cyan-400"),n("div",{className:k,children:S},C)})}),l("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Edit with Claude:"}),l("div",{className:"flex items-center gap-2",children:[l("span",{className:"px-2 py-1 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:["Claude, can you help me edit this rule: `",e.filePath,"`"]}),n(_t,{content:`Claude, can you help me edit this rule: \`${e.filePath}\``,icon:!0,iconSize:14,className:"p-1 text-gray-400 hover:text-gray-600 rounded transition-colors"})]})]}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&l("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Applies to paths:"}),n("div",{className:"flex flex-wrap gap-1.5",children:e.frontmatter.paths.map((S,C)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:S},C))})]}),!y&&n("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[500px] overflow-auto bg-white border-gray-200",children:n(Yl,{content:e.body})})]})]})}function Db(){return new Date().toISOString().split(".")[0]+"",`---
|
|
342
|
+
paths:
|
|
343
|
+
- '**/*.ts'
|
|
344
|
+
---
|
|
345
|
+
|
|
346
|
+
## Title
|
|
347
|
+
|
|
348
|
+
Description here.
|
|
349
|
+
`}function Lb({rule:e,onSave:t,onCancel:r}){const[s,a]=_(e?`.claude/rules/${e.filePath}`:""),[o,i]=_((e==null?void 0:e.content)||Db()),[c,d]=_(!!e),[m,u]=_(!1),h=!e;return l("div",{className:"p-6",children:[l("div",{className:"flex items-center justify-between mb-4",children:[n("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),n("button",{onClick:r,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:n(zn,{className:"w-5 h-5"})})]}),h&&l("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:l("div",{className:"flex items-start gap-3",children:[n(xr,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),l("div",{children:[n("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),n("p",{className:"text-sm text-[#0369a1] mb-2",children:"Run this command in Claude Code to create a properly formatted rule with the right file location and paths:"}),l("div",{className:"relative",children:[n("code",{className:"block bg-white px-3 py-2 pr-9 rounded border border-[#bae6fd] font-mono text-sm text-[#0c4a6e]",children:"/codeyam-new-rule"}),n("button",{onClick:()=>{navigator.clipboard.writeText("/codeyam-new-rule"),u(!0),setTimeout(()=>u(!1),2e3)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[#0284c7] hover:text-[#0c4a6e] cursor-pointer transition-colors",title:"Copy command",children:m?n(gt,{className:"w-4 h-4 text-green-500"}):n(Nt,{className:"w-4 h-4"})})]})]})]})}),l("button",{onClick:()=>d(!c),className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:c?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:c?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(c||!h)&&l("div",{className:"space-y-4",children:[l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),l("div",{className:"relative",children:[n("input",{type:"text",value:s,onChange:p=>a(p.target.value),placeholder:"e.g., src/webserver/architecture.md",className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm",disabled:!!e}),n("button",{onClick:()=>{navigator.clipboard.writeText(s)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy path",children:n(Nt,{className:"w-4 h-4"})})]})]}),e&&l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ask Claude for help editing:"}),l("div",{className:"relative",children:[n("input",{type:"text",value:`Claude, can you help me edit the rule: \`${s}\``,readOnly:!0,className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md bg-gray-50 font-mono text-sm text-gray-600"}),n("button",{onClick:()=>{navigator.clipboard.writeText(`Claude, can you help me edit the rule: \`${s}\``)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy prompt",children:n(Nt,{className:"w-4 h-4"})})]})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:o,onChange:p=>i(p.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:[n("button",{onClick:r,className:"px-4 py-2 text-[#001f3f] hover:text-[#001530] rounded-md cursor-pointer font-mono uppercase text-xs font-semibold",children:"Cancel"}),n("button",{onClick:()=>t(s.replace(/^\.claude\/rules\//,""),o),disabled:!s.trim()||!o.trim(),className:"px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer font-mono uppercase text-xs font-semibold",children:"Save"})]})]})]})}function Ob({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:s,onToggleFolder:a}){const o=ne(()=>Ul(e),[e]),i=(m,u,h)=>{if(m.target.closest(".chevron-toggle")){h&&a(u||"root");return}const f=u||null;r(t===f?null:f),h&&!s.has(u||"root")&&a(u||"root")},c=m=>{r(t===m?null:m)},d=(m,u=0)=>{const h=s.has(m.path||"root"),p=Wl(m),f=m.children.size>0,y=m.name==="root"?"(root)":m.name,g=m.memories.length>0||f,x=m.path||"",v=t===x||t===null&&x==="";return l("div",{children:[l("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${v?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${u*12+8}px`},onClick:b=>i(b,m.path,g),children:[g&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:b=>{b.stopPropagation(),a(m.path||"root")},children:n(Ft,{className:`w-3 h-3 text-gray-500 transition-transform ${h?"rotate-90":""}`})}),!g&&n("div",{className:"w-3"}),n(oi,{className:"w-3.5 h-3.5 text-[#005C75]"}),n("span",{className:`text-xs font-mono font-semibold ${v?"text-[#005C75]":""}`,style:{color:"#005C75"},children:y}),l("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[p," rules"]})]}),h&&l("div",{className:"relative",children:[(m.memories.length>0||f)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${u*12+8+6}px`}}),m.memories.length>0&&n("div",{style:{paddingLeft:`${(u+1)*12+8}px`},children:m.memories.map(b=>{var w;const N=t===b.filePath;return n("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${N?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>c(b.filePath),children:n("span",{className:"text-xs",children:(w=b.filePath.split("/").pop())==null?void 0:w.replace(".md","")})},b.filePath)})}),f&&n("div",{children:Array.from(m.children.values()).sort((b,N)=>b.name.localeCompare(N.name)).map(b=>d(b,u+1))})]})]},m.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:d(o)})}function Fb({memories:e,onEdit:t,onDelete:r,expandedFolders:s,onToggleFolder:a,reviewedStatus:o,onMarkReviewed:i,onMarkUnreviewed:c,onViewRule:d}){const[m,u]=_({});te(()=>{u({})},[o]);const h=ne(()=>({...o,...m}),[o,m]),p=ne(()=>Ul(e),[e]),f=(g,x,v)=>{u(b=>({...b,[g]:!v})),v?c(g):i(g,x)},y=(g,x=0)=>{const v=s.has(g.path||"root"),b=g.children.size>0,N=g.name==="root"?"root":g.name,w=g.memories.length>0||b;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:()=>w&&a(g.path||"root"),children:[w&&n(Ft,{className:`w-4 h-4 text-gray-500 transition-transform ${v?"rotate-90":""}`}),!w&&n("div",{className:"w-4"}),n(oi,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:N})]}),v&&l("div",{className:"ml-10 space-y-4 relative",children:[(g.memories.length>0||b)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:"-24px"}}),g.memories.length>0&&n("div",{className:"space-y-2",children:g.memories.map(S=>n(Ib,{rule:S,onEdit:t,onDelete:r,onView:d,isReviewed:h[S.filePath]??!1,onToggleReviewed:f},S.filePath))}),b&&n("div",{className:"space-y-4",children:Array.from(g.children.values()).sort((S,C)=>S.name.localeCompare(C.name)).map(S=>y(S,x+1))})]})]},g.path||"root")};return n("div",{children:y(p)})}function zb({memories:e,reviewedStatus:t,onViewRule:r,refreshKey:s}){const[a,o]=_("unreviewed"),[i,c]=_("by-date"),[d,m]=_(null),[u,h]=_(!0),[p,f]=_(new Map),y=be(t),g=be([]);te(()=>()=>{g.current.forEach(clearTimeout)},[]),te(()=>{(async()=>{h(!0);try{const C=await(await fetch("/api/memory?action=rule-coverage")).json();m(C.coverage??null)}catch{m(null)}finally{h(!1)}})()},[s]),te(()=>{const w=y.current,S=[];for(const[C,k]of Object.entries(t))k&&!w[C]&&S.push(C);y.current=t,S.length!==0&&(f(C=>{const k=new Map(C);return S.forEach(E=>k.set(E,"approved")),k}),g.current.push(setTimeout(()=>{f(C=>{const k=new Map(C);return S.forEach(E=>k.set(E,"fading")),k})},1500)),g.current.push(setTimeout(()=>{f(C=>{const k=new Map(C);return S.forEach(E=>k.delete(E)),k})},2500)))},[t]);const x=ne(()=>{const w=[...e];return i==="by-impact"&&d!==null?w.sort((S,C)=>{const k=d[S.filePath]??0,E=d[C.filePath]??0;return E!==k?E-k:new Date(C.lastModified).getTime()-new Date(S.lastModified).getTime()}):w.sort((S,C)=>new Date(C.lastModified).getTime()-new Date(S.lastModified).getTime()),w},[e,i,d]),v=ne(()=>x.filter(w=>!t[w.filePath]).length,[x,t]),b=ne(()=>a==="unreviewed"?x.filter(w=>!t[w.filePath]||p.has(w.filePath)):x,[x,a,t,p]),N=!u&&d!==null;return l("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:[l("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Recently Changed Rules"})}),n("div",{className:"flex-1"}),l("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),l("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:["Unreviewed Rules (",v,")"]})]}),l("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),l("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:["All (",x.length,")"]})]})]}),l("div",{className:"grid grid-cols-[1fr_90px_80px_100px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Rule"}),l("button",{onClick:()=>N&&c("by-impact"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none p-0 ${N?"cursor-pointer hover:text-gray-600":"cursor-default"} ${i==="by-impact"?"text-[#005C75]":"text-gray-400"}`,children:["Src Files",i==="by-impact"&&n(ct,{className:"w-3 h-3"})]}),l("button",{onClick:()=>c("by-date"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none cursor-pointer p-0 hover:text-gray-600 ${i==="by-date"?"text-[#005C75]":"text-gray-400"}`,children:["Changed At",i==="by-date"&&n(ct,{className:"w-3 h-3"})]}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center flex items-center justify-center gap-1 whitespace-nowrap",children:["✓ Reviewed",l("span",{className:"relative group",children:[n(Ds,{className:"w-3 h-3 text-gray-300 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Showing which rules have been reviewed and approved. Click a rule to view it and approve it"})]})]})]}),n("div",{className:"flex-1 overflow-y-auto max-h-[400px]",children:b.map(w=>{const S=t[w.filePath]??!1,C=p.get(w.filePath),k=as(w.body,w.filePath),E=(d==null?void 0:d[w.filePath])??0;return n("div",{className:`border-b border-gray-50 transition-all ${C==="fading"?"duration-1000":"duration-300"}`,style:{opacity:C==="fading"?0:1},children:l("div",{className:`grid grid-cols-[1fr_90px_80px_100px] px-5 py-2.5 items-center cursor-pointer transition-colors duration-300 ${C==="approved"?"bg-[#f0fdf4]":"hover:bg-gray-50"}`,onClick:()=>r(w),children:[n("div",{className:"flex items-center gap-2 min-w-0",children:n("span",{className:"text-sm text-gray-900 truncate",children:k})}),n("span",{className:"text-xs text-center",children:u?n("span",{className:"inline-block w-6 h-3 bg-gray-100 rounded animate-pulse"}):d!==null?n("span",{className:E>0?"text-gray-700 font-medium":"text-gray-300",children:E}):n("span",{className:"text-gray-300",children:"—"})}),n("span",{className:"text-xs text-gray-500 text-center",children:dn(w.lastModified)}),n("div",{className:"flex justify-center",children:n("div",{className:`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors duration-300 ${S?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:S&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})})]})},w.filePath)})}),b.length===0&&a==="unreviewed"&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:"All rules have been reviewed"})]})}function Bb(e,t){const r=t.map(s=>`- \`${s}\``).join(`
|
|
350
|
+
`);return`Please audit the following Claude Rules that apply to the file \`${e}\`:
|
|
351
|
+
|
|
352
|
+
${r}
|
|
353
|
+
|
|
354
|
+
Please review these rules in conjunction with one another as they all apply to this file.
|
|
355
|
+
|
|
356
|
+
Review each rule with the other rules in mind:
|
|
357
|
+
- Necessary: Is this rule really necessary to avoid confusion in future work sessions?
|
|
358
|
+
- Efficiency: Are the rules concise and well-structured?
|
|
359
|
+
- Effectiveness: Does the rules provide clear, actionable guidance?
|
|
360
|
+
- Context window impact: Can the rules be shortened without losing important information?
|
|
361
|
+
- Overlap: Is there any redundant information across the rules that can be consolidated?
|
|
362
|
+
- Duplication: Are there any rules that are nearly identical that can be merged or removed?
|
|
363
|
+
|
|
364
|
+
Remember that documenting past confusion isn't helpul unless that confusion will likely happen again.
|
|
365
|
+
|
|
366
|
+
Note: Each rule may apply to multiple files, not just the file listed above. Consider this when suggesting changes — modifications should not negatively impact the rule's usefulness for other files it covers.`}function Yb({filePath:e,rulePaths:t,onClose:r}){const[s,a]=_(!1),o=Bb(e,t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:l("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:c=>c.stopPropagation(),children:[n("button",{onClick:r,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(zn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-1",children:"Audit Rules For File"}),n("p",{className:"font-mono text-sm text-gray-500 mb-4 truncate",title:e,children:e}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can audit these rules to try and make them as efficient and effective as possible, reducing the impact on the context window."}),n("textarea",{readOnly:!0,value:o,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-4",children:n("button",{onClick:()=>{navigator.clipboard.writeText(o),a(!0),setTimeout(()=>a(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:s?l(ue,{children:[n(gt,{className:"w-4 h-4"}),"Copied!"]}):l(ue,{children:[n(Nt,{className:"w-4 h-4"}),"Copy Prompt"]})})})]})})}function Ub({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:s}){const[a,o]=_("unreviewed"),[i,c]=_(null),[d,m]=_(""),[u,h]=_(0),[p,f]=_(!1),[y,g]=_(null),[x,v]=_(null),b=be(null),N=be(null),[w,S]=_({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[C,k]=_(!0);te(()=>{(async()=>{k(!0);try{const q=await(await fetch("/api/memory?action=audit")).json();S({topPaths:q.topPaths||[],totalFilesWithCoverage:q.totalFilesWithCoverage||0,allSourceFiles:q.allSourceFiles||[]})}catch(J){console.error("Failed to load audit data:",J)}finally{k(!1)}})()},[e]);const E=ne(()=>a==="all"?w.topPaths:w.topPaths.filter(R=>R.matchingRules.some(J=>!t[J.filePath])),[w.topPaths,a,t]);ne(()=>w.topPaths.filter(R=>R.matchingRules.some(J=>!t[J.filePath])).length,[w.topPaths,t]);const A=R=>R.split("/").pop()||R,I=ne(()=>{const R=new Map;for(const J of w.topPaths)R.set(J.filePath,J);return R},[w.topPaths]),j=ne(()=>{if(!d.trim())return[];const R=d.toLowerCase(),J=[],q=[];for(const Y of w.allSourceFiles){const H=Y.toLowerCase();if(!H.includes(R))continue;const B=I.get(Y)||{filePath:Y,matchingRules:[],totalTextLength:0};H.startsWith(R)?J.push(B):q.push(B)}return J.sort((Y,H)=>Y.filePath.localeCompare(H.filePath)),q.sort((Y,H)=>Y.filePath.localeCompare(H.filePath)),[...J,...q].slice(0,8)},[d,w.allSourceFiles,I]),P=oe(R=>{var J;g(R),c(R.filePath),m(R.filePath),f(!1),(J=b.current)==null||J.blur()},[]),$=oe(()=>{var R;m(""),g(null),c(null),(R=b.current)==null||R.focus()},[]),T=oe(R=>{var J;!p||j.length===0||(R.key==="ArrowDown"?(R.preventDefault(),h(q=>Math.min(q+1,j.length-1))):R.key==="ArrowUp"?(R.preventDefault(),h(q=>Math.max(q-1,0))):R.key==="Enter"?(R.preventDefault(),P(j[u])):R.key==="Escape"&&(f(!1),(J=b.current)==null||J.blur()))},[p,j,u,P]);return te(()=>{h(0)},[j]),l("div",{className:"bg-white rounded-lg border border-gray-200 flex flex-col",children:[l("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Rule Audit"})}),l("div",{className:"relative flex-1 max-w-[300px]",children:[n(Fn,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),n("input",{ref:b,type:"text",value:d,onChange:R=>{m(R.target.value),f(!0)},onFocus:()=>{d.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:T,placeholder:"Search files...",className:`w-full pl-8 ${d?"pr-7":"pr-3"} py-1 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-[#005C75] focus:border-[#005C75] bg-gray-50`}),d&&n("button",{type:"button",onMouseDown:R=>{R.preventDefault(),$()},className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center text-gray-400 hover:text-gray-600 cursor-pointer",children:n("svg",{viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"w-3 h-3",children:n("path",{d:"M1 1l12 12M13 1L1 13"})})}),p&&j.length>0&&n("div",{ref:N,className:"absolute left-0 top-full mt-0.5 bg-white border border-gray-200 rounded-md shadow-lg z-10 max-h-75 overflow-y-auto min-w-75 max-w-120",children:j.map((R,J)=>l("div",{onMouseDown:q=>{q.preventDefault(),P(R)},onMouseEnter:()=>h(J),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${J===u?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(br,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:R.filePath,children:(()=>{const q=R.filePath.toLowerCase().indexOf(d.toLowerCase());if(q===-1)return R.filePath;const Y=R.filePath.slice(0,q),H=R.filePath.slice(q,q+d.length),B=R.filePath.slice(q+d.length);return l(ue,{children:[Y,n("span",{className:"font-semibold text-[#005C75]",children:H}),B]})})()}),l("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[R.matchingRules.length," rule",R.matchingRules.length!==1?"s":""]})]},R.filePath))})]}),n("div",{className:"flex-1"}),l("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:"Unreviewed Rules"})]}),l("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:"All"})]})]}),l("div",{className:"grid grid-cols-[1fr_140px_150px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Source file"}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Rules",l("span",{className:"relative group",children:[n(Ds,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-48 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Number of rules not yet reviewed for this file / Total number of rules that apply to this file"})]})]}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Tokens",l("span",{className:"relative group",children:[n(Ds,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Estimated tokens from unreviewed rules / Total number of tokens from all rules that apply to this file"})]})]})]}),C&&n("div",{className:"px-5 py-6",children:l("div",{className:"animate-pulse space-y-3",children:[n("div",{className:"h-4 bg-gray-200 rounded w-3/4"}),n("div",{className:"h-3 bg-gray-100 rounded w-1/2"}),n("div",{className:"h-4 bg-gray-200 rounded w-2/3 mt-4"})]})}),!C&&(E.length>0||y)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(y?[y,...E.filter(J=>J.filePath!==y.filePath)].slice(0,8):E.slice(0,8)).map((R,J)=>{const q=R.matchingRules.length,Y=R.matchingRules.filter(U=>!t[U.filePath]),H=Y.length,B=Y.reduce((U,F)=>U+F.bodyLength,0),D=H>0,M=i===R.filePath,Q=(y==null?void 0:y.filePath)===R.filePath;return l("div",{children:[l("div",{onClick:()=>c(M?null:R.filePath),className:`grid grid-cols-[1fr_140px_150px] px-5 py-2.5 items-center border-b border-gray-50 cursor-pointer ${Q?"bg-[#f0f9ff] hover:bg-[#e0f2fe]":"hover:bg-gray-50"}`,children:[l("div",{className:"flex items-center gap-2 min-w-0",children:[M?n(ct,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n(Ft,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(br,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:R.filePath,children:Q?R.filePath:A(R.filePath)})]}),l("span",{className:"text-sm text-center",children:[n("span",{className:D?"font-semibold text-[#1A5276]":"text-gray-400",children:H}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:q})]}),l("span",{className:"text-sm text-center",children:[n("span",{className:D?"font-semibold text-[#1A5276]":"text-gray-400",children:Rn(B).toLocaleString()}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:Rn(R.totalTextLength).toLocaleString()})]})]}),M&&l("div",{className:"bg-gray-50 border-b border-gray-100",children:[R.matchingRules.map(U=>{const F=r.find(z=>z.filePath===U.filePath),X=t[U.filePath]??!1;return l("div",{onClick:z=>{z.stopPropagation(),F&&s(F)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(yr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-700 truncate flex-1",children:F?as(F.body,F.filePath):U.filePath}),l("span",{className:"text-xs text-gray-400 flex-shrink-0",children:[Rn(U.bodyLength).toLocaleString()," ","tokens"]}),n("div",{className:`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${X?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:X&&n("svg",{width:"8",height:"6",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]},U.filePath)}),l("div",{className:"flex items-center justify-center gap-3 px-5 py-2 border-t border-gray-200",children:[n("span",{className:"text-xs text-gray-400",children:"Have Claude audit these rules"}),n("button",{onClick:U=>{U.stopPropagation(),v({filePath:R.filePath,rulePaths:R.matchingRules.map(F=>F.filePath)})},className:"px-3 py-1 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer",children:"Prompt"})]})]})]},R.filePath)})}),!C&&E.length===0&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:a==="unreviewed"?"No files have unreviewed rules":"No files have rule coverage yet"}),x&&n(Yb,{filePath:x.filePath,rulePaths:x.rulePaths,onClose:()=>v(null)})]})}function Wb({rule:e,changeInfo:t,isReviewed:r,onApprove:s,onEdit:a,onDelete:o,onClose:i}){const c=as(e.body,e.filePath),d=Rn(e.body.length),m=e.frontmatter.category,u=`.claude/rules/${e.filePath}`,[h,p]=_(null),f=(t==null?void 0:t.changeType)==="added"||h!=null&&h.commitCount!=null&&h.commitCount<=1&&!(h.commitCount===1&&h.isUncommitted);return te(()=>{p(null),fetch(`/api/memory?action=rule-diff&filePath=${encodeURIComponent(e.filePath)}`).then(y=>y.json()).then(y=>{y.diff&&p(y.diff)}).catch(()=>{})},[e.filePath]),te(()=>{const y=g=>{g.key==="Escape"&&i()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[i]),n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:i,children:l("div",{className:"rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",style:{backgroundColor:"#F8F7F6"},onClick:y=>y.stopPropagation(),children:[n("div",{className:"px-6 pt-5 pb-4",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"min-w-0 flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[n("h2",{className:"text-[16px] font-bold text-gray-900",children:c}),t&&l(ue,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:dn(t.date)}),n("span",{className:`flex-shrink-0 text-[11px] uppercase font-semibold tracking-wider ${t.changeType==="added"?"text-green-600":t.changeType==="modified"?"text-orange-600":"text-red-600"}`,children:t.changeType})]})]}),m&&l("div",{className:"flex items-center gap-2 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"TYPE:"}),n("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase font-semibold tracking-wider bg-[#E0F2F1] text-[#00796B]",children:m})]}),l("div",{className:"flex items-center gap-1.5 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"FILE:"}),n("code",{className:"text-[11px] text-gray-600 font-mono",children:u}),n(_t,{content:u,icon:!0,iconSize:12,className:"p-0.5 rounded text-gray-400 hover:text-gray-600 transition-colors",ariaLabel:"Copy file path"})]}),l("div",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:["TOKENS: ~",d.toLocaleString()]})]}),l("div",{className:"flex items-center gap-2 flex-shrink-0 ml-4",children:[l("button",{onClick:s,className:`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer transition-colors ${r?"bg-green-600 text-white":"border border-green-600 text-green-700 hover:bg-green-50"}`,children:[n(gt,{className:"w-3.5 h-3.5"}),r?"Approved":"Approve"]}),n("button",{onClick:a,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors",children:"Edit"}),n("button",{onClick:o,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-red-300 text-red-600 hover:bg-red-50 transition-colors",children:"Delete"}),n("button",{onClick:i,className:"p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-200 cursor-pointer transition-colors ml-1",children:n(zn,{className:"w-5 h-5"})})]})]})}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&l("div",{className:"px-6 pb-4",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Applies to paths:"}),n("div",{className:"bg-white rounded-lg p-4 space-y-2.5",style:{border:"1px solid #E6E6E6"},children:e.frontmatter.paths.map((y,g)=>{const x=y.split("/"),v=x.pop()||y,b=x.length>0?x.join("/")+"/":"";return l("div",{className:"flex items-center gap-2 text-[13px] font-mono",children:[n(br,{className:"w-4 h-4 text-[#005C75] flex-shrink-0"}),l("span",{children:[b&&n("span",{className:"text-gray-500",children:b}),n("span",{className:"font-bold text-gray-900",children:v})]})]},g)})})]}),f?n("div",{className:"px-6 pb-4",children:l("div",{className:"text-[13px] text-gray-500",children:["Created"," ",t!=null&&t.date?dn(t.date):h!=null&&h.date?dn(h.date):"recently"]})}):h&&n("div",{className:"px-6 pb-4",children:l("details",{children:[l("summary",{className:"text-[13px] text-gray-700 font-semibold cursor-pointer",children:["Recent change: ",h.commitMessage," —"," ",dn(h.date)]}),n("pre",{className:"mt-2 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:h.diff.split(`
|
|
367
|
+
`).map((y,g)=>{let x="";return y.startsWith("+")&&!y.startsWith("+++")?x="text-green-400":y.startsWith("-")&&!y.startsWith("---")?x="text-red-400":y.startsWith("@@")&&(x="text-cyan-400"),n("div",{className:x,children:y},g)})})]})}),l("div",{className:"px-6 pb-6",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Rule Text:"}),n("div",{className:"bg-white rounded-lg p-6",style:{border:"1px solid #E6E6E6"},children:n(Yl,{content:e.body})})]})]})})}function Jb(){return l("svg",{width:"24",height:"24",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#232323"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#232323"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#232323"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#232323"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#232323"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#232323"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#232323"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#232323"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#232323"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#232323"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#232323"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#232323"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#232323"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#232323"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#232323"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#232323"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#232323"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#232323"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#232323"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#232323"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#232323"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#232323"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#232323"})]})}function Hb(){return l("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}function Vb(){return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans max-w-3xl mx-auto",children:[l("div",{className:"text-center mb-10",children:[n("h1",{className:"text-[22px] font-semibold mb-4",style:{fontFamily:"Sora",color:"#232323"},children:"Get Started with CodeYam Memory"}),n("p",{className:"text-[15px] text-gray-500 leading-relaxed max-w-2xl mx-auto",children:"CodeYam Memory generates path-scoped Claude Rules that load automatically when Claude works on matching files. These rules capture any confusion, architectural decisions, and tribal knowledge from your as you work with Claude, ensuring sessions become more efficient and aligned with your codebase over time."})]}),l("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"Setup Steps"}),l("ol",{className:"space-y-5",children:[l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"1"}),n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Open Claude Code in your project terminal"})]}),l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"2"}),l("div",{children:[l("div",{className:"flex items-center gap-2 pt-0.5",children:[n("span",{className:"text-[14px] font-medium text-gray-900",children:"Run"}),n(Qo,{value:"/codeyam-memory"}),n("span",{className:"text-[14px] font-medium text-gray-900",children:"in the Claude Code session"})]}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"This kicks off analysis of your git history to find confusion patterns."})]})]}),l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"3"}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Return to this dashboard page to review the new rules"}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"You can review, edit, and approve the rules Claude creates."})]})]})]})]}),l("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"What Gets Created"}),l("div",{className:"relative",children:[n("div",{className:"absolute left-[15px] top-8 bottom-4",style:{borderLeft:"2px dotted #B0BEC5"}}),l("div",{className:"space-y-6",children:[l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[l("p",{className:"text-[14px] font-medium text-gray-900",children:[n("code",{className:"bg-gray-200/60 px-1.5 py-0.5 rounded text-[13px]",children:".claude/rules/*.md"}),n("span",{className:"text-gray-400 mx-1.5",children:"—"}),"path-scoped guidance files"]}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"Markdown files with frontmatter specifying which file paths they apply to."})]})]}),l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Rules load automatically when Claude works on matching files"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"No manual steps needed — Claude picks up relevant rules based on the files it touches."})]})]}),l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Pre-commit hook to keep rules fresh and capture new patterns"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"A git hook runs automatically to update rules when related code changes and looks for any new patterns of confusion in work sessions."})]})]})]})]})]}),l("div",{className:"rounded-lg px-8 py-5 flex items-center justify-center gap-3",style:{backgroundColor:"#1A2332"},children:[n("span",{className:"text-white text-[15px] font-medium",children:"Run"}),n(Qo,{value:"/codeyam-memory"}),n("span",{className:"text-white text-[15px] font-medium",children:"in Claude Code to get started"})]})]})})}function Qo({value:e}){const[t,r]=_(!1);return l("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[13px] font-mono cursor-pointer border-0",style:{backgroundColor:"#2C3E50",color:"#E0E0E0"},title:"Copy to clipboard",children:[e,t?n(gt,{className:"w-3.5 h-3.5 text-green-400"}):l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-400",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})}function ur({label:e,count:t,icon:r,bgColor:s,iconBgColor:a,textColor:o}){return n("div",{className:"rounded-lg p-4",style:{backgroundColor:s,border:"1px solid #EFEFEF"},children:l("div",{className:"flex items-start gap-3",children:[n("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:a},children:r}),l("div",{className:"flex-1",children:[n("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:o},children:t}),n("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:o},children:e})]})]})})}function qb({searchFilter:e,onSearchChange:t,onCreateNew:r,onLearnMore:s,reviewCounts:a}){return l("div",{className:"mb-8",children:[l("div",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[l("div",{children:[l("div",{className:"flex items-center gap-3 mb-2",children:[n(Jb,{}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),l("p",{className:"text-[15px] text-gray-500",children:["Rules help Claude understand your codebase patterns and conventions."," ",n("button",{onClick:s,className:"text-[#005C75] underline cursor-pointer",children:"Learn more about rules."})]})]}),l("div",{className:"flex items-center gap-3",children:[l("div",{className:"relative",children:[n(Fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:e,onChange:o=>t(o.target.value),placeholder:"Search rules...",className:"w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),l("button",{onClick:r,className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(ta,{className:"w-4 h-4"}),"New Rule"]})]})]}),l("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[n(ur,{label:"Total Rules",count:a.total,icon:n(Hb,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(ur,{label:"Unreviewed",count:a.unreviewed,icon:n(Dc,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(ur,{label:"Reviewed",count:a.reviewed,icon:n(gt,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(ur,{label:"Stale",count:a.stale,icon:n(ai,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]})}function Gb({onClose:e,onCreateNew:t}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:l("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:r=>r.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(zn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-4",children:"What are Claude Rules?"}),n("h3",{className:"mb-4 font-semibold",children:"And how does CodeYam Memory work with Claude Rules?"}),l("div",{className:"text-gray-600 text-[15px] space-y-3 mb-6",children:[l("p",{children:["Claude Rules are a component of"," ",n("a",{href:"https://code.claude.com/docs/en/memory#modular-rules-with-claude%2Frules%2F",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 underline",children:"Memory Management in Claude Code"}),'. The text of each rule is passed into the context window when working on the specific files described in the "paths" frontmatter field of the rule.']}),n("p",{children:"This allows you to provide context that is surgically specific to certain files in your codebase. They are a powerful tool but are harder to write and maintain than CLAUDE.md files."}),n("p",{children:"CodeYam Memory helps write and maintain Claude Rules. Hooks ensure that rules are reviewed and added during Claude Code working sessions. The CodeYam CLI Dashboard provides a page dedicated to Memory where you can view, edit, create, delete, and review Claude Rules."})]}),n("div",{className:"flex justify-center",children:l("button",{onClick:t,className:"flex items-center gap-2 px-5 py-2.5 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(ta,{className:"w-4 h-4"}),"New Rule"]})})]})})}function Kb({rule:e,onConfirm:t,onCancel:r}){return n("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:[n("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"," ",n("span",{className:"font-mono text-sm",children:e.filePath}),"? This cannot be undone."]}),l("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>t(e),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})}const Zo="Can you help me perform an interactive rules audit? Please look at all of the rules in `.claude/rules`. Are they organized properly? Ideally they should be in a folder that is the best representation of the files they impact (e.g. if the rule impacts `folder1/folder2/file1` and `folder1/folder2/folder3/file2` then the rule should be in `.claude/rules/folder1/folder2`). Do they make sense? Are they oriented toward avoiding future confusion (vs documenting bug fixes or temporary workarounds, etc)? Please literally read each one to ensure you understand what it is saying and learn something useful from it. Are they concise and efficient in their communication? We want to be respectful of the context window so any information in a rule that does not make sense, is not particularly helpful, or is repetitive should be removed. All other information should be presented as directly as possible. Bullets and tables can help with this as opposed to paragraphs. Take into consideration how rules interact as any one file may have multiple rules applied to it. Please look at the impacted files as well to ensure that it is an appropriate rule for them and to ensure the rule is not just repeating information that can be ascertained from the code. We don't want Claude to have to read a large number of files (or a single very large file) to figure out how everything works, so architectural guidance can be quite valuable, but information that is specific to one file and can be ascertained by the code and comments in that file is unnecessary. Too often rules reflect past confusion that has been resolved and is unlikely to happen again. Content and rules like this should be removed. If you have any questions please ask!",Xo="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function ei({text:e}){const[t,r]=_(!1);return n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:t?l(ue,{children:[n(gt,{className:"w-4 h-4"}),"Copied!"]}):l(ue,{children:[n(Nt,{className:"w-4 h-4"}),"Copy Prompt"]})})}function Qb({onClose:e}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:l("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative max-h-[90vh] overflow-y-auto",onClick:t=>t.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(zn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-2",children:"Audit All Rules"}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can review all rules to look for information that is inconsistent, inappropriate, duplicative, inefficient, etc."}),n("textarea",{readOnly:!0,value:Zo,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(ei,{text:Zo})}),l("div",{className:"border-t border-gray-200 mt-6 pt-5",children:[n("p",{className:"text-gray-500 text-sm mb-3",children:"If you would like to avoid reviewing all of the changes Claude makes you can ask Claude to mark all rules as reviewed."}),n("textarea",{readOnly:!0,value:Xo,className:"w-full h-16 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(ei,{text:Xo})})]})]})})}function Zb(){const[e,t]=_(!1);return l(ue,{children:[l("div",{className:"border border-gray-200 rounded-lg px-5 py-4 mb-8 flex items-center gap-3",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit All Rules"}),n("p",{className:"text-sm text-gray-500",children:"Ask Claude to review, audit, and improve all rules."}),n("button",{onClick:()=>t(!0),className:"px-4 py-2 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer flex-shrink-0",children:"Get Prompt"})]}),e&&n(Qb,{onClose:()=>t(!1)})]})}const Xb=()=>[{title:"Memory - CodeYam"},{name:"description",content:"Manage Claude Memory documentation"}];async function ev({request:e}){try{const r=await(await fetch(new URL("/api/memory",e.url).toString())).json();return r.error?K({memories:[],reviewedStatus:{},memoryInitialized:r.memoryInitialized??!1,error:r.error}):r.memoryInitialized??!1?K({memories:r.memories||[],reviewedStatus:r.reviewedStatus||{},memoryInitialized:!0,error:null}):K({memories:[],reviewedStatus:{},memoryInitialized:!1,error:null})}catch(t){return console.error("Failed to load memories:",t),K({memories:[],reviewedStatus:{},memoryInitialized:!1,error:"Failed to load memories"})}}const tv=Je(function(){const{memories:t,reviewedStatus:r,memoryInitialized:s,error:a}=Ve(),o=Le(),i=ft(),[c,d]=_(""),[m,u]=_(null),[h,p]=_(new Set(["root"])),[f,y]=_(null),[g,x]=_(!1),[v,b]=_(null),[N,w]=_(0),[S,C]=_(!1),[k,E]=_(null),[A,I]=_(null),[j,P]=_({}),$=z=>{p(L=>{const W=new Set(L);return W.has(z)?W.delete(z):W.add(z),W})};yt({source:"memory-page"});const T=ne(()=>({...r,...j}),[r,j]),R=be(o.state);te(()=>{const z=R.current==="loading"||R.current==="submitting",L=o.state==="idle";z&&L&&o.data&&(i.revalidate(),y(null),x(!1),w(W=>W+1)),R.current=o.state},[o.state,o.data,i]),te(()=>{P(z=>{const L={};for(const[W,V]of Object.entries(z))r[W]!==V&&(L[W]=V);return Object.keys(L).length===Object.keys(z).length?z:L})},[r]);const J=(z,L)=>{P(W=>({...W,[z]:!0})),o.submit({action:"mark-reviewed",filePath:z,lastModified:L},{method:"POST",action:"/api/memory",encType:"application/json"})},q=z=>{P(L=>({...L,[z]:!1})),o.submit({action:"mark-unreviewed",filePath:z},{method:"POST",action:"/api/memory",encType:"application/json"})},Y=(z,L)=>{E(z),I(L??null)},H=ne(()=>{let z=t;if(c.trim()){const L=c.toLowerCase();z=z.filter(W=>{var Z;return(((Z=W.filePath.split("/").pop())==null?void 0:Z.replace(".md",""))||"").toLowerCase().includes(L)||W.body.toLowerCase().includes(L)})}return z},[t,c]),B=ne(()=>m?H.some(L=>L.filePath===m)?H.filter(L=>L.filePath===m):H.filter(L=>L.filePath.startsWith(m+"/")||L.filePath===m):H,[H,m]),D=(z,L)=>{const W=f?"update":"create";o.submit({action:W,filePath:z,content:L},{method:"POST",action:"/api/memory",encType:"application/json"})},M=z=>{o.submit({action:"delete",filePath:z.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),b(null)},Q=ne(()=>{const z=t.filter(L=>T[L.filePath]).length;return{total:t.length,reviewed:z,unreviewed:t.length-z,stale:0}},[t,T]),U=ne(()=>{const z=new Set(["root"]);for(const L of H){const W=L.filePath.split("/");W.pop();let V="";for(const Z of W)V=V?`${V}/${Z}`:Z,z.add(V)}return z},[H]),F=U.size===h.size&&[...U].every(z=>h.has(z)),X=()=>{p(F?new Set(["root"]):new Set(U))};return a?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:a})]})}):s?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans",children:[n(qb,{searchFilter:c,onSearchChange:d,onCreateNew:()=>x(!0),onLearnMore:()=>C(!0),reviewCounts:Q}),(g||f)&&n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:()=>{x(!1),y(null)},children:n("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:z=>z.stopPropagation(),children:n(Lb,{rule:f,onSave:D,onCancel:()=>{x(!1),y(null)}})})}),l("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(zb,{memories:H,reviewedStatus:T,onViewRule:Y,refreshKey:N}),n(Ub,{onEditRule:y,onDeleteRule:b,refreshKey:N,reviewedStatus:T,onMarkReviewed:J,onMarkUnreviewed:q,memories:t,onViewRule:Y})]}),n(Zb,{}),l("div",{className:"flex items-center justify-between mb-4",children:[n("h2",{className:"text-xl leading-6 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"All Rules"}),n("div",{className:"flex items-center gap-4",children:U.size>1&&n("button",{onClick:X,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:F?"Collapse All":"Expand All"})})]}),l("div",{className:"flex gap-6",children:[n("div",{className:"hidden lg:block w-80 flex-shrink-0",children:n(Ob,{memories:H,selectedPath:m,onSelectPath:u,expandedFolders:h,onToggleFolder:$})}),n("div",{className:"flex-1 min-w-0",children:t.length===0?l("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(Lc,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Rules Yet"}),l("p",{className:"text-gray-500 mb-4",children:["Run"," ",n("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam-memory"})," ","to generate initial memories for your codebase."]}),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:[n(ta,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):l("div",{children:[m&&l("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:["Showing rules in"," ",n("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:m||"(root)"}),n("button",{onClick:()=>u(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(Fb,{memories:B,onEdit:y,onDelete:b,expandedFolders:h,onToggleFolder:$,reviewedStatus:T,onMarkReviewed:J,onMarkUnreviewed:q,onViewRule:Y})]})})]}),n("div",{className:"mt-8 mb-8",children:n(de,{to:"/agent-transcripts",className:"block bg-white border border-gray-200 rounded-lg p-5 hover:border-[#005C75] hover:shadow-sm transition-all group",children:l("div",{className:"flex items-center gap-3",children:[n("div",{className:"w-10 h-10 rounded-lg bg-[#EDF1F3] flex items-center justify-center",children:l("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#005C75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("polyline",{points:"4 17 10 11 4 5"}),n("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),l("div",{children:[n("h3",{className:"text-sm font-semibold text-[#232323] group-hover:text-[#005C75]",style:{fontFamily:"Sora"},children:"Agent Transcripts"}),n("p",{className:"text-xs text-gray-500",children:"View background agent transcripts and tool call history"})]})]})})}),k&&!f&&(()=>{const z=t.find(L=>L.filePath===k.filePath)??k;return n(Wb,{rule:z,changeInfo:A??void 0,isReviewed:T[z.filePath]??!1,onApprove:()=>{T[z.filePath]??!1?q(z.filePath):J(z.filePath,z.lastModified),E(null)},onEdit:()=>{y(z)},onDelete:()=>{b(z),E(null)},onClose:()=>E(null)})})(),S&&n(Gb,{onClose:()=>C(!1),onCreateNew:()=>{C(!1),x(!0)}}),v&&n(Kb,{rule:v,onConfirm:M,onCancel:()=>b(null)})]})}):n(Vb,{})}),nv=Object.freeze(Object.defineProperty({__proto__:null,default:tv,loader:ev,meta:Xb},Symbol.toStringTag,{value:"Module"}));function Is(e){return`${e.filePath||""}::${e.name}`}function Jl(e,t){const r=Le(),{showToast:s}=ca(),[a,o]=_(new Map);te(()=>{if(r.state==="idle"&&r.data){const p=r.data;p!=null&&p.error&&s(`Error: ${p.error}`,"error",6e3)}},[r.state,r.data,s]),te(()=>{var f;if(a.size===0)return;const p=new Set;(f=t==null?void 0:t.jobs)==null||f.forEach(y=>{var g;(g=y.entityShas)==null||g.forEach(x=>{a.forEach((v,b)=>{v===x&&p.add(b)})})}),e==null||e.forEach(y=>{a.forEach((g,x)=>{g===y&&p.add(x)})}),p.size>0&&o(y=>{const g=new Map(y);return p.forEach(x=>g.delete(x)),g})},[t,e,a]);const i=oe(p=>{console.log("Generate analysis clicked for entity:",p.sha,p.name);const f=Is(p);o(g=>new Map(g).set(f,p.sha));const y=new FormData;y.append("entitySha",p.sha),y.append("filePath",p.filePath||""),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),c=oe(p=>{const f=p.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(x=>{const v=new Map(x);return f.forEach(b=>v.set(Is(b),b.sha)),v});const y=f.map(x=>x.sha).join(","),g=new FormData;g.append("entityShas",y),r.submit(g,{method:"post",action:"/api/analyze"})},[r]),d=oe(p=>(e==null?void 0:e.includes(p))??!1,[e]),m=oe(p=>{const f=Is(p);return a.has(f)},[a]),u=oe(p=>{var f;return((f=t==null?void 0:t.jobs)==null?void 0:f.some(y=>{var g;return(g=y.entityShas)==null?void 0:g.includes(p)}))??!1},[t]),h=ne(()=>Array.from(a.keys()),[a]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:c,isEntityBeingAnalyzed:d,isEntityPending:m,isEntityInQueue:u,pendingEntityKeys:h}}function ja({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:s,analyzeAllDisabled:a=!1,analyzeAllText:o="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children: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:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:n("span",{children:"STATE"})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:n("span",{children:"SIMULATIONS"})}),l("div",{className:"flex gap-4 items-center",children:[n("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:r,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r==null||r())},children:[n("span",{children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:t==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&n("div",{className:"text-center",style:{width:"127px"},children:s&&n("button",{onClick:s,disabled:a,className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap px-3 py-1.5 normal-case",title:a?o:"Analyze all entities",children:o})})]})]})]})})}function rv({status:e,variant:t="compact"}){const r={modified:{label:"M",bgColor:"bg-[#f59e0c]"},added:{label:"A",bgColor:"bg-emerald-500"},deleted:{label:"D",bgColor:"bg-red-500",showWarning:!0},renamed:{label:"R",bgColor:"bg-indigo-500"},untracked:{label:"U",bgColor:"bg-purple-500"}},s={modified:{label:"MODIFIED",textColor:"#BB6BD9"},added:{label:"ADDED",textColor:"#F2994A"},deleted:{label:"DELETED",textColor:"#EF4444"},renamed:{label:"RENAMED",textColor:"#3B82F6"},untracked:{label:"UNTRACKED",textColor:"#6B7280"}};if(t==="full"){const o=s[e]||{label:"UNKNOWN",textColor:"#6B7280"};return n("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:o.textColor},children:o.label})})}const a=r[e]||{label:"?",bgColor:"bg-gray-500"};return l("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${a.bgColor}`,title:e,children:a.label}),a.showWarning&&n("span",{className:"inline-flex items-center justify-center w-3 h-3 text-[10px] text-amber-600",title:"Warning: File will be deleted",children:"⚠"})]})}function Ma({filePath:e,isExpanded:t,onToggle:r,fileStatus:s,simulationPreviews:a,entityCount:o,state:i,lastModified:c,actionButton:d,uncommittedCount:m,children:u,isNotAnalyzable:h=!1,isUncommitted:p=!1}){return l("div",{className:"bg-white overflow-hidden",style:t?{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 ${h?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(pi,{filePath:e}),s&&n(rv,{status:typeof s=="string"?s:s.status,variant:"full"}),p&&i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("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&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&!p&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:a}),l("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:l("span",{className:"text-[13px] text-[#3e3e3e]",children:[o," ",o===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:Tl(c)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:d})]})]})]}),t&&u&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:u})]})}function Ta({entities:e,maxPreviews:t=3}){var s,a,o,i,c;const r=[];for(const d of e){if(r.length>=t)break;const m=((a=(s=d.analyses)==null?void 0:s[0])==null?void 0:a.scenarios)||[];if(d.entityType==="library"){const u=m.find(h=>{var p,f;return((p=h.metadata)==null?void 0:p.executionResult)||((f=h.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:d.sha})}else if(d.entityType==="visual"){const u=m.find(h=>{var p,f;return(f=(p=h.metadata)==null?void 0:p.screenshotPaths)==null?void 0:f[0]});if(u){const h=(i=(o=u.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],p=!!((c=u.metadata)!=null&&c.error);h&&r.push({type:"screenshot",screenshot:h,hasError:p,scenario:u,entitySha:d.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(ue,{children:r.map((d,m)=>{if(d.type==="screenshot"&&d.screenshot){const u=d.hasError?"border-red-400":"border-gray-200";return l(de,{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:h=>h.stopPropagation(),children:[n(qe,{screenshotPath:d.screenshot,alt:`Preview ${m+1}`,className:"max-w-full max-h-full object-contain object-center"}),d.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(gr,{size:12,color:"white"})})]},`screenshot-${m}`)}return d.type==="library"&&d.scenario&&d.entitySha?n(jl,{scenario:d.scenario,entitySha:d.entitySha,size:"small",showBorder:!0},`library-${m}`):null})})}function $a({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:s}){var u,h;const a=t||r?[{entityShas:[e.sha]}]:[],o=ot(e,a,t),i=e.entityType==="visual"||e.entityType==="library",c=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,m=(((h=(u=e.analyses)==null?void 0:u[0])==null?void 0:h.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(de,{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:[n("span",{className:"w-4 shrink-0"}),e.entityType==="type"?n("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:n("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:n(tt,{type:"type"})})}):n(tt,{type:e.entityType||"other"}),n("span",{className:`font-['IBM_Plex_Sans'] text-[14px] leading-[18px] text-black ${i?"font-medium":"font-normal"}`,children:e.name}),n(wa,{type:e.entityType||"other"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),l("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?o==="queued"?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:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):o==="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:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):o==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):o==="out-of-date"?n("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),s(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):c&&n("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),s(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"})})]})]})]}),m.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:m.map((p,f)=>{var g,x;const y=(x=(g=p.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return y?n(de,{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:v=>v.stopPropagation(),children:n(qe,{screenshotPath:y,alt:p.name,className:"max-w-full max-h-full object-contain object-center"})},p.id):null})})]})}function sv({entities:e,page:t,itemsPerPage:r=50,currentRun:s,filter:a,entityType:o,queueState:i,isEntityPending:c,pendingEntityKeys:d,onGenerateSimulation:m,onGenerateAllSimulations:u,totalFilesCount:h,totalEntitiesCount:p,uncommittedFilesCount:f,showOnlyUncommitted:y,onToggleUncommitted:g}){const[x,v]=fn(),[b,N]=_(new Set),[w,S]=_(""),[C,k]=_(!1),[E,A]=_("all"),[I,j]=_("desc"),P=o||"all",$=ne(()=>{let M=e;return P!=="all"&&(M=M.filter(Q=>Q.entityType===P)),a==="analyzed"&&(M=M.filter(Q=>Q.analyses&&Q.analyses.length>0)),M},[e,P,a]),T=ne(()=>{const M=new Map,Q=new Map,U=new Map;$.forEach(L=>{var Z,ce;const W=`${L.filePath}::${L.name}`,V=Q.get(W);if(!V)Q.set(W,L),U.set(W,[]);else{const ve=((Z=V.metadata)==null?void 0:Z.editedAt)||V.createdAt||"",ae=((ce=L.metadata)==null?void 0:ce.editedAt)||L.createdAt||"";let me=!1;if(ae>ve)me=!0;else if(ae===ve){const Se=V.createdAt||"";me=(L.createdAt||"")>Se}me?(U.get(W).push(V),Q.set(W,L)):U.get(W).push(L)}}),Q.forEach((L,W)=>{var Z;if(!(L.analyses&&L.analyses.length>0)&&((Z=L.metadata)!=null&&Z.previousVersionWithAnalyses)){const ve=(U.get(W)||[]).find(ae=>{var me;return ae.sha===((me=L.metadata)==null?void 0:me.previousVersionWithAnalyses)});ve&&ve.analyses&&ve.analyses.length>0&&(L.analyses=ve.analyses)}}),Array.from(Q.values()).sort((L,W)=>{var ce,ve,ae,me;const V=!((ce=L.metadata)!=null&&ce.notExported)&&!((ve=L.metadata)!=null&&ve.namedExport),Z=!((ae=W.metadata)!=null&&ae.notExported)&&!((me=W.metadata)!=null&&me.namedExport);return V&&!Z?-1:!V&&Z?1:0}).forEach(L=>{var ve,ae,me,Se,Ne;const W=L.filePath??"No File Path";M.has(W)||M.set(W,{filePath:W,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const V=M.get(W);V.entities.push(L),V.totalCount++,(ve=L.metadata)!=null&&ve.isUncommitted&&V.uncommittedCount++;const Z=((Se=(me=(ae=L.analyses)==null?void 0:ae[0])==null?void 0:me.scenarios)==null?void 0:Se.length)||0;V.simulationCount+=Z;const ce=((Ne=L.metadata)==null?void 0:Ne.editedAt)||L.updatedAt;ce&&(!V.lastUpdated||new Date(ce)>new Date(V.lastUpdated))&&(V.lastUpdated=ce)});const F=(i==null?void 0:i.jobs)||[],X=L=>{const W=`${L.filePath||""}::${L.name}`;return(d==null?void 0:d.includes(W))||!1};M.forEach(L=>{const W=L.entities.map(V=>X(V)?"queued":ot(V,F));W.includes("analyzing")||W.includes("queued")?L.state="analyzing":W.includes("incomplete")?L.state="incomplete":W.includes("out-of-date")?L.state="out-of-date":W.includes("not-analyzed")?L.state="not-analyzed":L.state="up-to-date"}),M.forEach(L=>{var W,V,Z,ce,ve;for(const ae of L.entities){if(L.previewScreenshots.length+L.previewLibraryScenarios.length>=3)break;const Se=((V=(W=ae.analyses)==null?void 0:W[0])==null?void 0:V.scenarios)||[];if(ae.entityType==="library"){const Ne=Se.find(Ae=>{var De,Oe;return((De=Ae.metadata)==null?void 0:De.executionResult)||((Oe=Ae.metadata)==null?void 0:Oe.error)});Ne&&L.previewLibraryScenarios.push({scenario:Ne,entitySha:ae.sha})}else{const Ne=Se.find(Ae=>{var De,Oe;return(Oe=(De=Ae.metadata)==null?void 0:De.screenshotPaths)==null?void 0:Oe[0]});if(Ne){const Ae=(ce=(Z=Ne.metadata)==null?void 0:Z.screenshotPaths)==null?void 0:ce[0],De=!!((ve=Ne.metadata)!=null&&ve.error);Ae&&!L.previewScreenshots.includes(Ae)&&(L.previewScreenshots.push(Ae),L.previewScreenshotErrors.push(De))}}}});const z=Array.from(M.values());return z.sort((L,W)=>{if(a==="analyzed"){const ce=Math.max(...L.entities.filter(ae=>{var me,Se;return(Se=(me=ae.analyses)==null?void 0:me[0])==null?void 0:Se.createdAt}).map(ae=>new Date(ae.analyses[0].createdAt).getTime()),0),ve=Math.max(...W.entities.filter(ae=>{var me,Se;return(Se=(me=ae.analyses)==null?void 0:me[0])==null?void 0:Se.createdAt}).map(ae=>new Date(ae.analyses[0].createdAt).getTime()),0);return I==="desc"?ve-ce:ce-ve}if(L.uncommittedCount>0&&W.uncommittedCount===0)return-1;if(L.uncommittedCount===0&&W.uncommittedCount>0)return 1;const V=L.lastUpdated?new Date(L.lastUpdated).getTime():0,Z=W.lastUpdated?new Date(W.lastUpdated).getTime():0;return I==="desc"?Z-V:V-Z}),z},[$,a,I,i,d]),R=ne(()=>{let M=T;if(E!=="all"&&(M=M.filter(Q=>Q.state===E)),w.trim()){const Q=w.toLowerCase();M=M.filter(U=>U.filePath.toLowerCase().includes(Q))}return M},[T,w,E]),J=(t-1)*r,q=J+r,Y=R.slice(J,q),H=Math.ceil(R.length/r),B=M=>{N(Q=>{const U=new Set(Q);return U.has(M)?U.delete(M):U.add(M),U})},D=()=>{j(M=>M==="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:[n("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:P,onChange:M=>{const Q=M.target.value,U=new URLSearchParams(x);Q==="all"?U.delete("entityType"):U.set("entityType",Q),U.set("page","1"),v(U)},className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(ct,{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:E,onChange:M=>A(M.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All States"}),n("option",{value:"analyzing",children:"Analyzing..."}),n("option",{value:"up-to-date",children:"Up to date"}),n("option",{value:"incomplete",children:"Incomplete"}),n("option",{value:"out-of-date",children:"Out of date"}),n("option",{value:"not-analyzed",children:"Not analyzed"})]}),n(ct,{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:[n(Fn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",value:w,onChange:M=>S(M.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),h!==void 0&&p!==void 0&&f!==void 0&&n("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:[n("span",{style:{color:"#000000"},children:R.length})," ",R.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children: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.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:R.reduce((M,Q)=>M+Q.totalCount,0)})," ",R.reduce((M,Q)=>M+Q.totalCount,0)===1?"entity":"entities"]}),n("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:[R.filter(M=>M.uncommittedCount>0).length," ","uncommitted"," ",R.filter(M=>M.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):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"]})]}),Y.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:()=>{N(new Set(Y.map(M=>M.filePath))),k(!0)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(ii,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:()=>{N(new Set),k(!1)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(li,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(ja,{showActions:!0,sortOrder:I,onSortChange:D}),n("div",{className:"flex flex-col gap-[3px]",children:Y.map(M=>{const Q=b.has(M.filePath),F=M.entities.filter(W=>(W.entityType==="visual"||W.entityType==="library")&&(ot(W,(i==null?void 0:i.jobs)||[])==="not-analyzed"||ot(W,(i==null?void 0:i.jobs)||[])==="out-of-date"||ot(W,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,X=W=>{var V;return((V=s==null?void 0:s.currentEntityShas)==null?void 0:V.includes(W))||!1},z=W=>{var V;return c!=null&&c(W)?!0:((V=i==null?void 0:i.jobs)==null?void 0:V.some(Z=>{var ce;return(ce=Z.entityShas)==null?void 0:ce.includes(W.sha)}))||!1},L=W=>{m==null||m(W)};return n(Ma,{filePath:M.filePath,isExpanded:Q,onToggle:()=>B(M.filePath),simulationPreviews:n(Ta,{entities:M.entities,maxPreviews:1}),entityCount:M.totalCount,state:M.state,lastModified:M.lastUpdated,uncommittedCount:M.uncommittedCount,isUncommitted:M.uncommittedCount>0,actionButton:F?n("button",{onClick:W=>{W.stopPropagation();const V=M.entities.filter(Z=>(Z.entityType==="visual"||Z.entityType==="library")&&(ot(Z,(i==null?void 0:i.jobs)||[])==="not-analyzed"||ot(Z,(i==null?void 0:i.jobs)||[])==="out-of-date"||ot(Z,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(V)},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:M.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:M.entities.sort((W,V)=>{var me,Se,Ne,Ae;const Z=!((me=W.metadata)!=null&&me.notExported)&&!((Se=W.metadata)!=null&&Se.namedExport),ce=!((Ne=V.metadata)!=null&&Ne.notExported)&&!((Ae=V.metadata)!=null&&Ae.namedExport);if(Z&&!ce)return-1;if(!Z&&ce)return 1;const ve=W.entityType==="visual"||W.entityType==="library",ae=V.entityType==="visual"||V.entityType==="library";return ve&&!ae?-1:!ve&&ae?1:W.name.localeCompare(V.name)}).map(W=>n($a,{entity:W,isActivelyAnalyzing:X(W.sha),isQueued:z(W),onGenerateSimulation:L},W.sha))},M.filePath)})}),H>1&&l("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),l("span",{children:["Page ",t," of ",H]}),t<H&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const av=()=>[{title:"Files & Entities - CodeYam"},{name:"description",content:"Browse your codebase files and entities"}];async function ov({request:e,context:t}){try{const r=new URL(e.url),s=parseInt(r.searchParams.get("page")||"1"),a=r.searchParams.get("filter")||null,o=r.searchParams.get("entityType"),i=t.analysisQueue,c=i?i.getState():{paused:!1,jobs:[]},[d,m]=await Promise.all([tn(),yn()]);return K({entities:d,currentCommit:m,page:s,filter:a,entityType:o,queueState:c})}catch(r){return console.error("Failed to load entities:",r),K({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const iv=Je(function(){var w,S,C;const{entities:t,currentCommit:r,page:s,filter:a,entityType:o,queueState:i,error:c}=Ve();ft();const[d,m]=fn(),[u,h]=_(!1);yt({source:"files-page"});const{handleGenerateSimulation:p,handleGenerateAllSimulations:f,isEntityPending:y,pendingEntityKeys:g}=Jl((S=(w=r==null?void 0:r.metadata)==null?void 0:w.currentRun)==null?void 0:S.currentEntityShas,i),x=t||[],v=ne(()=>{const k=new Set([]);for(const E of x)k.add(E.filePath??"No File Path");return Array.from(k)},[x]),b=ne(()=>{let k=x;return u&&(k=k.filter(E=>{var A;return(A=E.metadata)==null?void 0:A.isUncommitted})),k.sort((E,A)=>{var I,j,P,$,T,R;return(I=E.metadata)!=null&&I.isUncommitted&&!((j=A.metadata)!=null&&j.isUncommitted)?-1:!((P=E.metadata)!=null&&P.isUncommitted)&&(($=A.metadata)!=null&&$.isUncommitted)?1:new Date(((T=A.metadata)==null?void 0:T.editedAt)||0).getTime()-new Date(((R=E.metadata)==null?void 0:R.editedAt)||0).getTime()})},[x,u]),N=ne(()=>{var E;const k=new Set([]);for(const A of x)(E=A.metadata)!=null&&E.isUncommitted&&k.add(A.filePath??"No File Path");return Array.from(k)},[x]);return c?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:c})]})}):x.length===0?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:l("div",{className:"max-w-md mx-auto",children:[n("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"," ",n("code",{className:"px-2 py-1 bg-gray-100 rounded text-sm font-mono",children:"codeyam analyze"})," ","to extract entities from your codebase."]}),n("p",{className:"text-sm text-gray-500",children:"Entities include React components, functions, and other analyzable code elements."})]})})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n(sv,{entities:b,page:s,itemsPerPage:50,currentRun:(C=r==null?void 0:r.metadata)==null?void 0:C.currentRun,filter:a,entityType:o,queueState:i,isEntityPending:y,pendingEntityKeys:g,onGenerateSimulation:p,onGenerateAllSimulations:f,totalFilesCount:v.length,totalEntitiesCount:x.length,uncommittedFilesCount:N.length,showOnlyUncommitted:u,onToggleUncommitted:()=>h(!u)})]})})}),lv=Object.freeze(Object.defineProperty({__proto__:null,default:iv,loader:ov,meta:av},Symbol.toStringTag,{value:"Module"})),cv=()=>[{title:"Labs - CodeYam"},{name:"description",content:"Experimental features"}];async function dv({request:e}){var t;try{const r=await $e();if(!r)return K({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Project not found"});const{project:s}=await Ie(r),a=he()||process.cwd(),o=kl(a)||"";let i="";try{const d=await Ur();if(d!=null&&d.webapps&&Array.isArray(d.webapps)){const m=d.webapps.map(u=>u.framework).filter(Boolean);m.length>0&&(i=m.join(", "))}}catch{}const c=_l(r);return K({labs:((t=s.metadata)==null?void 0:t.labs)??null,projectSlug:r,defaultEmail:o,detectedTechStack:i,unlockCode:c,error:null})}catch(r){return console.error("Failed to load labs config:",r),K({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Failed to load labs configuration"})}}async function uv({request:e}){try{const t=await e.formData(),r=t.get("feature"),s=t.get("enabled")==="true";if(!r)return K({success:!1,error:"Missing feature name"},{status:400});const a=await $e();return a?(r==="clearAccess"?await hn({projectSlug:a,metadataUpdate:{labs:{accessGranted:!1,simulations:!1}}}):await hn({projectSlug:a,metadataUpdate:{labs:{[r]:s}}}),K({success:!0,error:null})):K({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),K({success:!1,error:"Failed to save labs configuration"},{status:500})}}const mv=[{id:"simulations",name:"Simulations",description:"Enable entity analysis, visual simulations, git impact analysis, file browsing, and activity monitoring. When disabled, only Memory, Labs, and Settings are accessible.",defaultEnabled:!0},{id:"enhancedClaudeTesting",name:"Enhanced Claude Testing",description:"Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!0},{id:"gitIntegration",name:"Git Integration Showing Impacted Files",description:"Lorem Ipsum Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!1}],ti="https://docs.google.com/forms/d/e/1FAIpQLSfopqQOQsjY9S4Ns0l3xDLzGl7iYNpKa2Wn2Xzmtxj8CR1sMA/viewform",hv=[{title:"CodeYam Simulations",status:"apply for early access",desc:"CodeYam Simulations are the core of the CodeYam development experience. They leverage static code analysis and AI to generate robust data scenarios that are used to hydrate code. This creates a whole new dimension to the software development experience"},{title:"The Full CodeYam Experience",status:"more to come",desc:"CodeYam is completely rethinking the software development experience in the AI era. Focused on navigating the challenges of iteration speed, complexity, and communication, CodeYam will provide a powerful software development experience."}];function pv({onClose:e}){const t=be(null),r=be(0);return te(()=>{const s=t.current;if(!s)return;const a=100,o=2e3,i=500;let c=null,d=!1;const m=()=>{r.current=Date.now(),!c&&!d&&(c=setInterval(()=>{const u=Date.now()-r.current,h=s.scrollTop>a,p=u>o;h&&p&&(s.scrollTo({top:0,behavior:"smooth"}),d=!0,c&&(clearInterval(c),c=null))},i))};return s.addEventListener("scroll",m,{passive:!0}),()=>{s.removeEventListener("scroll",m),c&&clearInterval(c)}},[]),l("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:s=>{s.target===s.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),l("div",{className:"relative bg-white rounded-xl max-w-3xl w-full mx-4 max-h-[90vh] overflow-hidden",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none z-10",children:"×"}),l("div",{ref:t,className:"overflow-y-auto max-h-[90vh] p-4 md:p-6",children:[l("div",{className:"mb-4",children:[n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Request Early Access"}),n("p",{className:"text-sm text-gray-500",children:"Complete the form below to join the waitlist for CodeYam Labs."})]}),n("div",{className:"bg-white rounded-lg overflow-hidden",children:n("iframe",{src:`${ti}?embedded=true`,width:"100%",height:"1400",style:{border:0,minHeight:"1400px"},title:"Labs Waitlist Form",loading:"eager",children:n("div",{className:"flex items-center justify-center p-8 text-gray-600",children:l("div",{className:"text-center",children:[n("div",{className:"mb-4",children:"Loading form..."}),l("div",{className:"text-sm",children:["If this takes too long,"," ",n("a",{href:ti,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"open the form directly"})]})]})})})})]})]})]})}function fv({onClose:e,unlockCodeInput:t,setUnlockCodeInput:r,unlockFetcher:s}){var i,c;const a=(i=s.data)==null?void 0:i.error,o=(c=s.data)==null?void 0:c.success;return l("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:d=>{d.target===d.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),l("div",{className:"relative bg-white rounded-xl p-8 max-w-md w-full mx-4",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none",children:"×"}),n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Have an unlock code?"}),n("p",{className:"text-sm text-cygray-50 mb-6",children:"If you've received an unlock code, paste it below to enable Simulations immediately."}),l(s.Form,{method:"post",action:"/api/labs-unlock",className:"space-y-4",children:[n("input",{type:"text",name:"unlockCode",value:t,onChange:d=>r(d.target.value),placeholder:"CY-...",className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-100 focus:border-transparent"}),n("button",{type:"submit",disabled:!t.trim()||s.state==="submitting",className:"w-full py-3 text-white border-none rounded-lg text-sm font-mono font-semibold uppercase tracking-wider cursor-pointer transition-all bg-primary-200 hover:bg-primary-100 disabled:bg-gray-400 disabled:cursor-not-allowed",children:s.state==="submitting"?"Validating...":"Unlock"}),a&&n("p",{className:"text-red-600 text-sm mt-2",children:a}),o&&n("p",{className:"text-emerald-600 text-sm mt-2",children:"Simulations enabled! Refresh the page to see all tabs."})]})]})]})}const gv=Je(function(){const{labs:t,unlockCode:r,error:s}=Ve(),a=Le(),o=Le(),i=Le(),[c,d]=_(""),[m,u]=_(!1),[h,p]=_(!1);yt({source:"labs-page"});const f=(t==null?void 0:t.accessGranted)===!0||(t==null?void 0:t.simulations)===!0;return s?n("div",{className:"bg-cygray-10 min-h-screen",children:l("div",{className:"px-20 pt-8 pb-12 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Labs"}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 mt-4",children:n("p",{className:"text-red-700",children:s})})]})}):f?l("div",{className:"bg-cygray-10 min-h-screen font-sans flex flex-col",children:[n("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"})}),l("div",{className:"px-6 sm:px-12 pt-8 pb-10",children:[n("h2",{className:"font-serif italic text-[32px] sm:text-[48px] text-primary-100 mb-3 font-normal leading-tight",children:"Congrats!"}),n("p",{className:"font-serif text-[18px] sm:text-[24px] text-cyblack-100 font-normal leading-snug max-w-2xl",children:"You were granted early access to software simulation and other experimental features."})]}),n("div",{className:"px-6 sm:px-12 space-y-6 flex-1",children:mv.map(y=>{var v;const g=(t==null?void 0:t[y.id])??y.defaultEnabled,x=o.state==="submitting"&&((v=o.formData)==null?void 0:v.get("feature"))===y.id;return n("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:l("div",{className:"flex items-center justify-between gap-4",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-3 mb-3",children:[n("h3",{className:"text-lg font-semibold text-cyblack-100 m-0",children:y.name}),n("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${g?"bg-primary-100/15 text-primary-100":"bg-cygray-20 text-cygray-50"}`,children:g?"Enabled":"Disabled"})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed m-0",children:y.description})]}),l(o.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:y.id}),n("input",{type:"hidden",name:"enabled",value:String(!g)}),n("button",{type:"submit",disabled:x,className:`relative inline-flex h-8 w-14 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none disabled:opacity-60 disabled:cursor-not-allowed ${g?"bg-primary-100":"bg-gray-300"}`,children:n("span",{className:`pointer-events-none inline-block h-7 w-7 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${g?"translate-x-6":"translate-x-0"}`})})]})]})},y.id)})}),r&&n("div",{className:"px-6 sm:px-12 pt-12",children:l("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:[n("h3",{className:"text-base font-semibold text-cyblack-100 mb-1",children:"Unlock Code"}),n("p",{className:"text-sm text-cygray-50 mb-3",children:"This code was used to enable Labs access. Clear it to revoke access and return to the landing page."}),l("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[n("code",{className:"sm:flex-1 px-4 py-2.5 bg-cygray-10 border border-cygray-30 rounded-lg text-sm font-mono text-cyblack-100 overflow-x-auto",children:r}),l(i.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:"clearAccess"}),n("input",{type:"hidden",name:"enabled",value:"false"}),n("button",{type:"submit",disabled:i.state==="submitting",className:"px-4 py-2.5 bg-red-50 border border-red-200 rounded-lg text-sm font-medium text-red-700 cursor-pointer transition-colors hover:bg-red-100 disabled:opacity-60 disabled:cursor-not-allowed",children:i.state==="submitting"?"Clearing...":"Clear"})]})]})]})})]}):l("div",{className:"bg-cygray-10 min-h-screen font-sans",children:[m&&n(pv,{onClose:()=>u(!1)}),h&&n(fv,{onClose:()=>p(!1),unlockCodeInput:c,setUnlockCodeInput:d,unlockFetcher:a}),l("div",{className:"flex flex-wrap justify-between items-center gap-3 px-6 sm:px-12 pt-8 pb-4",children:[n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"}),l("div",{className:"flex flex-wrap items-center gap-3",children:[n("button",{onClick:()=>p(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cygray-30 bg-transparent text-cygray-50 cursor-pointer transition-colors hover:border-cyblack-100 hover:text-cyblack-100",children:"Have a Code?"}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cyblack-100 bg-transparent text-cyblack-100 cursor-pointer transition-colors hover:bg-cyblack-100 hover:text-white",children:"Apply for Early Access"})]})]}),l("div",{className:"px-6 sm:px-12 pt-12 pb-8",children:[n("h2",{className:"font-serif text-[24px] sm:text-[32px] leading-snug text-cyblack-100 max-w-xl mb-4 font-normal",children:"Powerful tools for the AI coding era."}),l("p",{className:"text-base sm:text-lg text-cygray-50 leading-relaxed max-w-xl mb-8",children:["We're opening early access to"," ",n("strong",{className:"text-cyblack-100",children:"experimental features"})," to a small group of developers and teams."]}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded bg-primary-200 text-white border-none cursor-pointer transition-colors hover:bg-primary-100",children:"Apply for Early Access"})]}),n("div",{className:"px-6 sm:px-12 py-8",children:n("hr",{className:"border-t border-cygray-30 m-0"})}),l("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:[n("h3",{className:"font-serif text-[22px] sm:text-[28px] text-cyblack-100 mb-10 font-normal text-center",children:"In The Works"}),n("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5 max-w-4xl mx-auto",children:hv.map(y=>l("div",{className:"border border-cygray-30 bg-white p-5 sm:p-8 rounded-lg",children:[l("h4",{className:"text-base font-semibold text-cyblack-100 mb-1",children:[y.title," ",l("span",{className:"font-normal text-primary-100 font-serif italic",children:["(",y.status,")"]})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed mt-3 mb-0",children:y.desc})]},y.title))})]}),n("div",{className:"px-6 sm:px-12 py-16",children:l("div",{className:"rounded-lg p-6 sm:p-12 bg-primary-200",children:[n("h3",{className:"font-serif text-[20px] sm:text-[24px] text-white mb-4 font-semibold",children:"Request Early Access"}),n("p",{className:"text-sm text-white/80 leading-relaxed max-w-lg mb-10 font-mono",children:"We're onboarding a limited number of developers and teams. Tell us about how you build and we'll let you know when you can try simulations and other Labs features."}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded border border-white bg-white text-cyblack-100 cursor-pointer transition-colors hover:bg-white/90 mb-4",children:"Apply for Early Access"}),n("p",{className:"text-xs text-white/60 m-0",children:"Takes about 2 minutes. Your answers help us determine eligibility and prioritize access."})]})})]})}),yv=Object.freeze(Object.defineProperty({__proto__:null,action:uv,default:gv,loader:dv,meta:cv},Symbol.toStringTag,{value:"Module"}));function xv(e,t,r){const[s,a]=_(()=>new Set),[o,i]=_(()=>new Set),c=be([]),d=be([]);return te(()=>{(t.length!==c.current.length||t.some((g,x)=>g!==c.current[x]))&&(c.current=t,a(g=>{const x=new Set;return t.forEach(v=>{g.has(v)&&x.add(v)}),x}))},[t]),te(()=>{(r.length!==d.current.length||r.some((g,x)=>g!==d.current[x]))&&(d.current=r,i(g=>{const x=new Set;return r.forEach(v=>{g.has(v)&&x.add(v)}),x}))},[r]),{expandedUncommitted:s,expandedBranch:o,setExpandedUncommitted:a,setExpandedBranch:i,toggleFile:(y,g,x)=>{x(v=>{const b=new Set(v);return b.has(y)?b.delete(y):b.add(y),b})},expandAllUncommitted:()=>{a(new Set(t))},collapseAllUncommitted:()=>{a(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function bv(e,t,r){const[s,a]=_(null),[o,i]=_(null),c=Le();te(()=>{var h,p;((h=c.data)==null?void 0:h.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=h=>{a({type:"file",path:h}),i(null);const p=new FormData;p.append("actionType","getDiff"),p.append("filePath",h),p.append("diffType","branch"),p.append("baseBranch",e),p.append("currentBranch",t||""),c.submit(p,{method:"post"})},m=(h,p)=>{a({type:"entity",path:h,entitySha:p}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",h),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",p),c.submit(f,{method:"post"})},u=()=>{a(null),i(null)};return{diffView:s,diffContent:o,isLoading:c.state==="loading"||c.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:m,handleCloseDiff:u}}function vv({diffView:e,diffContent:t,isLoading:r,entities:s,onClose:a}){var m;const[o,i]=_(!1),[c,d]=_(!1);return te(()=>{d(!0)},[]),n("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:[n("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),n("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&l("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((m=s.find(u=>u.sha===e.entitySha))==null?void 0:m.name)||e.entitySha]})]}),l("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick:a,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:c&&n(md,{oldValue:t.oldContent,newValue:t.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!o,extraLinesSurroundingDiff:4,styles:{variables:{light:{diffViewerBackground:"#fff",diffViewerColor:"#212529",addedBackground:"#e6ffed",addedColor:"#24292e",removedBackground:"#ffeef0",removedColor:"#24292e",wordAddedBackground:"#acf2bd",wordRemovedBackground:"#fdb8c0",addedGutterBackground:"#cdffd8",removedGutterBackground:"#ffdce0",gutterBackground:"#f6f8fa",gutterBackgroundDark:"#f3f4f6",highlightBackground:"#fffbdd",highlightGutterBackground:"#fff5b1"}},contentText:{fontSize:"12px",lineHeight:"1.5"},line:{padding:"2px 10px",fontSize:"12px","&:hover":{background:"#f8f9fa"}},splitView:{display:"flex",width:"100%"},diffContainer:{width:"50%",overflowX:"auto"}}})}):n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"No diff available"})})}),n("div",{className:"p-6 border-t border-[#e1e1e1] flex justify-end gap-3",children:n("button",{onClick:a,className:"px-4 py-2 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",children:"Close"})})]})})}function wv({files:e,currentBranch:t,defaultBranch:r,baseBranch:s,allBranches:a,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:c,sortOrder:d,onToggleFile:m,onBranchChange:u,onGenerateSimulation:h,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=e.flatMap(([N,{entities:w}])=>{const S=w.filter(C=>i(C.sha)||c(C)).map(C=>C.sha);return S.length>0?[{entityShas:S}]:[]}),v=N=>{const w=N.map(S=>ot(S,x));return w.includes("analyzing")||w.includes("queued")?"analyzing":w.includes("out-of-date")?"out-of-date":w.includes("not-analyzed")?"not-analyzed":"up-to-date"},b=ne(()=>[...e].sort((N,w)=>{const S=N[1].entities.reduce((A,I)=>{var P;const j=((P=I.metadata)==null?void 0:P.editedAt)||I.updatedAt;return j?A?new Date(j)>new Date(A)?j:A:j:A},null),C=w[1].entities.reduce((A,I)=>{var P;const j=((P=I.metadata)==null?void 0:P.editedAt)||I.updatedAt;return j?A?new Date(j)>new Date(A)?j:A:j:A},null);if(!S&&!C)return 0;if(!S)return 1;if(!C)return-1;const k=new Date(S).getTime(),E=new Date(C).getTime();return d==="desc"?E-k:k-E}),[e,d]);return n("div",{children:e.length>0?l("div",{children:[n(ja,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([N,{status:w,entities:S,isUncommitted:C}])=>{const k=o.has(N),E=v(S),A=S.reduce(($,T)=>{var J;const R=((J=T.metadata)==null?void 0:J.editedAt)||T.updatedAt;return R?$?new Date(R)>new Date($)?R:$:R:$},null),j=S.filter($=>$.entityType==="visual"||$.entityType==="library").length===0;let P;return j?P=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):E==="analyzing"?P=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:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):E==="up-to-date"?P=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):E==="out-of-date"?P=n("button",{onClick:$=>{$.stopPropagation(),S.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!i(T.sha)&&!c(T)).forEach(T=>h(T))},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"}):E==="not-analyzed"&&(P=n("button",{onClick:$=>{$.stopPropagation(),S.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!i(T.sha)&&!c(T)).forEach(T=>h(T))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Ma,{filePath:N,isExpanded:k,onToggle:()=>m(N),fileStatus:w,isUncommitted:C,simulationPreviews:n(Ta,{entities:S,maxPreviews:1}),entityCount:S.length,state:E,lastModified:A,isNotAnalyzable:j,actionButton:P,children:S.sort(($,T)=>{const R=$.entityType==="visual"||$.entityType==="library",J=T.entityType==="visual"||T.entityType==="library";return R&&!J?-1:!R&&J?1:0}).map($=>n($a,{entity:$,isActivelyAnalyzing:i($.sha),isQueued:c($),onGenerateSimulation:h},$.sha))},N)})})]}):l("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function Nv({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:s,isEntityQueued:a,projectSlug:o,baseBranch:i,currentBranch:c,sortOrder:d,onToggleFile:m,onShowFileDiff:u,onGenerateSimulation:h,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=ne(()=>{const N=[];return e.forEach(([w,{editedEntities:S}])=>{const C=S.filter(k=>s(k.sha)||a(k)).map(k=>k.sha);C.length>0&&N.push({entityShas:C})}),N},[e,s,a]),v=ne(()=>{const N=new Map;return e.forEach(([w,{editedEntities:S}])=>{const C=S.map(I=>ot(I,x));let k;C.includes("analyzing")||C.includes("queued")?k="analyzing":C.includes("out-of-date")?k="out-of-date":C.includes("not-analyzed")?k="not-analyzed":k="up-to-date";const E=S.reduce((I,j)=>{var $;const P=(($=j.metadata)==null?void 0:$.editedAt)||j.updatedAt;return P&&(!I||new Date(P)>new Date(I))?P:I},null),A=S.filter(I=>I.entityType==="visual"||I.entityType==="library").length;N.set(w,{state:k,lastModified:E,analyzableCount:A})}),N},[e,x]),b=ne(()=>[...e].sort((N,w)=>{const S=v.get(N[0]),C=v.get(w[0]),k=S==null?void 0:S.lastModified,E=C==null?void 0:C.lastModified;if(!k&&!E)return 0;if(!k)return 1;if(!E)return-1;const A=new Date(k).getTime(),I=new Date(E).getTime();return d==="desc"?I-A:A-I}),[e,v,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:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"If you edit a file in your project, it will show up here."})]}):l("div",{children:[n(ja,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([N,{status:w,editedEntities:S}])=>{const C=r.has(N),k=v.get(N),{state:E,lastModified:A,analyzableCount:I}=k,j=I===0;let P;return j?P=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):E==="analyzing"?P=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:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):E==="up-to-date"?P=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):E==="out-of-date"?P=n("button",{onClick:$=>{$.stopPropagation(),S.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!s(T.sha)&&!a(T)).forEach(T=>h(T))},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"}):E==="not-analyzed"&&(P=n("button",{onClick:$=>{$.stopPropagation(),S.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!s(T.sha)&&!a(T)).forEach(T=>h(T))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Ma,{filePath:N,isExpanded:C,onToggle:()=>m(N),fileStatus:w,simulationPreviews:n(Ta,{entities:S,maxPreviews:1}),entityCount:S.length,state:E,lastModified:A,isNotAnalyzable:j,isUncommitted:!0,actionButton:P,children:S.sort(($,T)=>{const R=$.entityType==="visual"||$.entityType==="library",J=T.entityType==="visual"||T.entityType==="library";return R&&!J?-1:!R&&J?1:0}).map($=>n($a,{entity:$,isActivelyAnalyzing:s($.sha),isQueued:a($),onGenerateSimulation:h},$.sha))},N)})})]})}function Cv({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:s}){return n("div",{className:"border-b border-gray-200",children:l("nav",{className:"flex gap-8 items-center",children:[l("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[l("span",{className:"flex items-center gap-2",children:["Branch Changes",s>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="branch"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:s})]}),e==="branch"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]}),l("button",{onClick:()=>t("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[l("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:r})]}),e==="uncommitted"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const Sv=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function kv({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const s=t.get("filePath"),a=t.get("diffType"),o=t.get("baseBranch"),i=t.get("currentBranch"),c=t.get("entitySha");let d;return a==="branch"?d=mr(s,o,i):d=Df(s),K({...d,entitySha:c})}return K({error:"Unknown action"},{status:400})}async function Ev({request:e,context:t}){try{const r=new URL(e.url),s=r.searchParams.get("compare"),a=r.searchParams.get("viewBranch"),o=t.analysisQueue,i=o?o.getState():{paused:!1,jobs:[]},[c,d,m]=await Promise.all([tn(),yn(),$e()]),u=ns(),h=Tf(),p=$f(),f=Rf(),y=a||h,g=s||p;let x=[];return y&&y!==g&&(x=pl(g,y)),K({entities:c||[],gitStatus:u,currentBranch:y,actualCurrentBranch:h,defaultBranch:p,allBranches:f,baseBranch:g,branchDiff:x,currentCommit:d,projectSlug:m,queueState:i})}catch(r){return console.error("Failed to load git data:",r),K({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 Av=Je(function(){var ke,rt;const{entities:t,gitStatus:r,currentBranch:s,actualCurrentBranch:a,defaultBranch:o,allBranches:i,baseBranch:c,branchDiff:d,currentCommit:m,projectSlug:u,queueState:h}=Ve();yt({source:"git-page"});const[p,f]=fn(),[y,g]=_(null),[x,v]=_("desc"),[b,N]=_("branch"),w=p.get("expanded")==="true",S=()=>{v(fe=>fe==="desc"?"asc":"desc")},C=Le(),k=C.data;te(()=>{s&&c&&s!==c&&C.state==="idle"&&!k&&C.load(`/api/branch-entity-diff?base=${encodeURIComponent(c)}&compare=${encodeURIComponent(s)}`)},[s,c,C,k]);const E=ne(()=>{const fe=zl(r,t);return Array.from(fe.entries()).sort((He,Ue)=>He[0].localeCompare(Ue[0]))},[r,t]),A=ne(()=>{const fe=cb(d,t,k);return Array.from(fe.entries()).sort((He,Ue)=>He[0].localeCompare(Ue[0]))},[d,t,k]),I=ne(()=>db(r,t),[r,t]),j=ne(()=>b==="uncommitted"?E:A,[b,E,A]),P=ne(()=>j.map(([fe])=>fe),[j]),{expandedUncommitted:$,setExpandedUncommitted:T,toggleFile:R,expandAllUncommitted:J,collapseAllUncommitted:q}=xv(w,P,[]),{diffView:Y,diffContent:H,isLoading:B,handleShowFileDiff:D,handleCloseDiff:M}=bv(c,s),Q=(ke=m==null?void 0:m.metadata)==null?void 0:ke.currentRun,U=new Set((Q==null?void 0:Q.currentEntityShas)||[]),F=new Set(h.jobs.flatMap(fe=>fe.entityShas||[])),X=new Set(((rt=h.currentlyExecuting)==null?void 0:rt.entityShas)||[]),{isAnalyzing:z,handleGenerateSimulation:L,handleGenerateAllSimulations:W,isEntityBeingAnalyzed:V,isEntityPending:Z}=Jl(Q==null?void 0:Q.currentEntityShas,h),ce=fe=>Z(fe)||F.has(fe.sha)||X.has(fe.sha),ve=fe=>{fe===(a||s)?p.delete("viewBranch"):p.set("viewBranch",fe),f(p)},ae=fe=>{fe===o?p.delete("compare"):p.set("compare",fe),f(p)},me=()=>{const He=j.flatMap(([Ue,Ze])=>Ze.editedEntities||Ze.entities||[]).filter(Ue=>!U.has(Ue.sha)&&!F.has(Ue.sha)&&!X.has(Ue.sha)&&!Z(Ue));W(He)},Se=E.length,Ne=A.length,Ae=j.flatMap(([fe,He])=>He.editedEntities||He.entities||[]),De=Ae.filter(fe=>fe.entityType==="visual"||fe.entityType==="library"),Oe=De.length>0&&De.every(fe=>U.has(fe.sha)),Ee=De.length>0&&!Oe&&De.every(fe=>F.has(fe.sha)||X.has(fe.sha)),re=z||Oe||Ee,ye=Oe?"Analyzing...":Ee?"Queued...":z?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("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. ",n("strong",{children:"Analyze a file to get simulations."})]})]}),n("div",{className:"mb-6",children:n(Cv,{activeTab:b,onTabChange:N,uncommittedCount:Se,branchCount:Ne})}),s&&b==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:s===o?l("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:o}),"."]}):l("div",{className:"flex gap-6 items-center",children:[l("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?l("div",{className:"relative w-50",children:[n("select",{value:s,onChange:fe=>ve(fe.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(fe=>n("option",{value:fe,children:fe},fe))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}):n("span",{className:"text-gray-900 font-medium text-[12px]",children:s})]}),l("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),l("div",{className:"relative w-[200px]",children:[n("select",{value:c,onChange:fe=>ae(fe.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(fe=>fe!==s).map(fe=>n("option",{value:fe,children:fe},fe))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children:l("div",{className:"relative flex items-center",children:[n("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),n("div",{className:"mb-3",children: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:[n("span",{style:{color:"#000000"},children:j.length})," ","modified ",j.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children: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.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:Ae.length})," ",Ae.length===1?"entity":"entities"]})]}),j.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:J,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(ii,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:q,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(li,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),l("div",{className:"overflow-hidden",children:[b==="branch"&&s&&n(wv,{files:A,currentBranch:s,defaultBranch:o,baseBranch:c,allBranches:i,expandedFiles:$,isEntityBeingAnalyzed:V,isEntityQueued:ce,sortOrder:x,onToggleFile:fe=>R(fe,$,T),onBranchChange:ae,onGenerateSimulation:L,onSortChange:S,onAnalyzeAll:me,analyzeAllDisabled:re,analyzeAllText:ye}),b==="uncommitted"&&n(Nv,{files:E,entityImpactMap:I,expandedFiles:$,isEntityBeingAnalyzed:V,isEntityQueued:ce,projectSlug:u,baseBranch:c,currentBranch:s,sortOrder:x,onToggleFile:fe=>R(fe,$,T),onShowFileDiff:D,onGenerateSimulation:L,onSortChange:S,onAnalyzeAll:me,analyzeAllDisabled:re,analyzeAllText:ye})]}),Y&&n(vv,{diffView:Y,diffContent:H,isLoading:B,entities:t,onClose:M}),y&&u&&n(Dt,{projectSlug:u,onClose:()=>g(null)})]})})}),Pv=Object.freeze(Object.defineProperty({__proto__:null,action:kv,default:Av,loader:Ev,meta:Sv},Symbol.toStringTag,{value:"Module"})),Sw={entry:{module:"/assets/entry.client-DTvKq3TY.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/index-10oVnAAH.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-BzQgN2ff.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/index-10oVnAAH.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/ReportIssueModal-djPLI-WV.js","/assets/useReportContext-O-jkvSPx.js","/assets/loader-circle-BAXYRVEO.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/book-open-D_nMCFmP.js","/assets/useToast-9FIWuYfK.js","/assets/useLastLogLine-C14nCb1q.js","/assets/LogViewer-ceAyBX-H.js","/assets/EntityTypeIcon-CobE682z.js","/assets/TruncatedFilePath-C8OKAR5x.js","/assets/chevron-down-BH2h1Ea2.js","/assets/circle-check-DyIKORY6.js","/assets/CopyButton-DmJveP3T.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.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-C28BiQzt.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/Spinner-Bb5uFQ5V.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/InlineSpinner-Bu6c6aDe.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.dev":{id:"routes/entity.$sha.scenarios.$scenarioId.dev",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/dev",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.dev-DjACbfdI.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/Spinner-Bb5uFQ5V.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/InlineSpinner-Bu6c6aDe.js","/assets/Terminal-nZNBALox.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/preload-helper-ckwbz45p.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-screenshot":{id:"routes/api.editor-journal-screenshot",parentId:"root",path:"api/editor-journal-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/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-BMvVHNXU.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/Spinner-Bb5uFQ5V.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C14nCb1q.js","/assets/InlineSpinner-Bu6c6aDe.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-register-scenario":{id:"routes/api.editor-register-scenario",parentId:"root",path:"api/editor-register-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-register-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/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-p9hhkjJM.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/Spinner-Bb5uFQ5V.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C14nCb1q.js","/assets/InlineSpinner-Bu6c6aDe.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-capture-scenario":{id:"routes/api.editor-capture-scenario",parentId:"root",path:"api/editor-capture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-capture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-switch-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-update-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-client-errors-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-entity-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-entry-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.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.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-test-results-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,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.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-load-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.agent-transcripts-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-dev-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.logs._projectSlug-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-file-diff":{id:"routes/api.editor-file-diff",parentId:"root",path:"api/editor-file-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,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.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.dev-mode-events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-report-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-refresh-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.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/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/agent-transcripts-D9hemwl6.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/terminal-BG4heKCG.js","/assets/search-fKo7v0Zo.js","/assets/chevron-down-BH2h1Ea2.js","/assets/book-open-D_nMCFmP.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-audit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-fixture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,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)-BpKzcsJz.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/LogViewer-ceAyBX-H.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityTypeIcon-CobE682z.js","/assets/EntityTypeBadge-g3saevPb.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LoadingDots-BU_OAEMP.js","/assets/loader-circle-BAXYRVEO.js","/assets/pause-DTAcYxBt.js","/assets/createLucideIcon-CMT1jU2q.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.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.labs-unlock-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.rule-path-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha._-CrjR3zZW.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useLastLogLine-C14nCb1q.js","/assets/Spinner-Bb5uFQ5V.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LibraryFunctionPreview-DLeucoVX.js","/assets/LoadingDots-BU_OAEMP.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-B76aig_2.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-CobE682z.js","/assets/CopyButton-DmJveP3T.js","/assets/LogViewer-ceAyBX-H.js","/assets/useReportContext-O-jkvSPx.js","/assets/preload-helper-ckwbz45p.js","/assets/InlineSpinner-Bu6c6aDe.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/ReportIssueModal-djPLI-WV.js","/assets/circle-check-DyIKORY6.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.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-B3aOzpCZ.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LoadingDots-BU_OAEMP.js","/assets/EntityTypeIcon-CobE682z.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/chevron-down-BH2h1Ea2.js","/assets/search-fKo7v0Zo.js","/assets/loader-circle-BAXYRVEO.js","/assets/createLucideIcon-CMT1jU2q.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-BiM6z3Do.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/ScenarioViewer-B76aig_2.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/LogViewer-ceAyBX-H.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/useLastLogLine-C14nCb1q.js","/assets/Spinner-Bb5uFQ5V.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-djPLI-WV.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/circle-check-DyIKORY6.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/InlineSpinner-Bu6c6aDe.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-DfuTtcJP.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/CopyButton-DmJveP3T.js","/assets/copy-NDbZjXao.js","/assets/createLucideIcon-CMT1jU2q.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-C96V0n15.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useToast-9FIWuYfK.js","/assets/useReportContext-O-jkvSPx.js","/assets/LogViewer-ceAyBX-H.js","/assets/EntityTypeIcon-CobE682z.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/circle-check-DyIKORY6.js","/assets/loader-circle-BAXYRVEO.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/editor":{id:"routes/editor",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/editor-DTwKl1Xu.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/Terminal-nZNBALox.js","/assets/CopyButton-DmJveP3T.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/Spinner-Bb5uFQ5V.js","/assets/copy-NDbZjXao.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/useLastLogLine-C14nCb1q.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-Dg0mvYrI.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/terminal-BG4heKCG.js","/assets/copy-NDbZjXao.js","/assets/CopyButton-DmJveP3T.js","/assets/chevron-down-BH2h1Ea2.js","/assets/search-fKo7v0Zo.js","/assets/pause-DTAcYxBt.js","/assets/book-open-D_nMCFmP.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-DO4CZ16O.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityItem-C76mRRiF.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/chevron-down-BH2h1Ea2.js","/assets/search-fKo7v0Zo.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/useToast-9FIWuYfK.js","/assets/TruncatedFilePath-C8OKAR5x.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LibraryFunctionPreview-DLeucoVX.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-DtSmdtM4.js","/assets/EntityTypeIcon-CobE682z.js","/assets/EntityTypeBadge-g3saevPb.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/labs-Zk7ryIM1.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.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-CdN8sCqs.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityItem-C76mRRiF.js","/assets/LogViewer-ceAyBX-H.js","/assets/index-yHOVb4rc.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/useToast-9FIWuYfK.js","/assets/TruncatedFilePath-C8OKAR5x.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LibraryFunctionPreview-DLeucoVX.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-DtSmdtM4.js","/assets/EntityTypeIcon-CobE682z.js","/assets/EntityTypeBadge-g3saevPb.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-9422aeab.js",version:"9422aeab",sri:void 0},kw="build/client",Ew="/",Aw={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},Pw=!0,_w=!1,jw=[],Mw={mode:"lazy",manifestPath:"/__manifest"},Tw="/",$w={module:pd},Rw={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:Wm},"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:Gm},"routes/entity.$sha.scenarios.$scenarioId.dev":{id:"routes/entity.$sha.scenarios.$scenarioId.dev",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/dev",index:void 0,caseSensitive:void 0,module:th},"routes/api.editor-journal-screenshot":{id:"routes/api.editor-journal-screenshot",parentId:"root",path:"api/editor-journal-screenshot",index:void 0,caseSensitive:void 0,module:rh},"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:kh},"routes/api.editor-register-scenario":{id:"routes/api.editor-register-scenario",parentId:"root",path:"api/editor-register-scenario",index:void 0,caseSensitive:void 0,module:Wh},"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:Qh},"routes/api.editor-capture-scenario":{id:"routes/api.editor-capture-scenario",parentId:"root",path:"api/editor-capture-scenario",index:void 0,caseSensitive:void 0,module:ep},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,module:np},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,module:sp},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,module:lp},"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:uf},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,module:Nf},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,module:Sf},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,module:Ef},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,module:Yf},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,module:Wf},"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:Vf},"routes/api.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,module:Qf},"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:sg},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:og},"routes/api.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,module:yg},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:wg},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:Ig},"routes/api.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,module:Wg},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:Vg},"routes/api.editor-file-diff":{id:"routes/api.editor-file-diff",parentId:"root",path:"api/editor-file-diff",index:void 0,caseSensitive:void 0,module:Gg},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,module:Qg},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:e0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:r0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:a0},"routes/api.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,module:l0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:b0},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,module:w0},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,module:P0},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:$0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:L0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:B0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:U0},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:ay},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,module:iy},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,module:hy},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:fy},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:wy},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:Cy},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:$y},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:Dy},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,module:Oy},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,module:Yy},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:Wy},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,module:Gy},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:xx},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:wx},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:Px},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:jx},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:Tx},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:Hx},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:Gx},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:Zx},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:ab},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:ib},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:gb},"routes/editor":{id:"routes/editor",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,module:Rb},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:nv},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:lv},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:yv},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:Pv}},Iw=!1;export{Cu as A,vu as B,Te as C,Hd as D,Vd as E,en as F,Rd as G,gi as H,yi as I,Ld as J,xi as K,zd as L,Yd as M,kw as N,Ew as O,Td as P,Aw as Q,Pw as R,wr as S,_w as T,jw as U,Mw as V,Tw as W,$w as X,Rw as Y,Iw as Z,Sw as _,Ad as a,mn as b,Qt as c,At as d,Yn as e,da as f,ua as g,fi as h,kd as i,ru as j,su as k,Lt as l,Pt as m,wi as n,mu as o,Cr as p,lt as q,Ni as r,Ci as s,yu as t,It as u,Si as v,gn as w,hn as x,so as y,Eu as z};
|