@codeyam/codeyam-cli 0.1.0-staging.dbc742d → 0.1.0-staging.e057775
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 +6 -6
- package/analyzer-template/log.txt +3 -3
- package/codeyam-cli/src/commands/__tests__/editor.stepDispatch.test.js +45 -0
- package/codeyam-cli/src/commands/__tests__/editor.stepDispatch.test.js.map +1 -0
- package/codeyam-cli/src/commands/editor.js +177 -80
- package/codeyam-cli/src/commands/editor.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/analyzerFinalization.test.js +144 -0
- package/codeyam-cli/src/utils/__tests__/analyzerFinalization.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/editorAudit.test.js +221 -1
- package/codeyam-cli/src/utils/__tests__/editorAudit.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/editorPreview.test.js +51 -1
- package/codeyam-cli/src/utils/__tests__/editorPreview.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js +14 -0
- package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js.map +1 -1
- package/codeyam-cli/src/utils/analyzerFinalization.js +96 -0
- package/codeyam-cli/src/utils/analyzerFinalization.js.map +1 -0
- package/codeyam-cli/src/utils/editorAudit.js +17 -0
- package/codeyam-cli/src/utils/editorAudit.js.map +1 -1
- package/codeyam-cli/src/utils/editorPreview.js +26 -0
- package/codeyam-cli/src/utils/editorPreview.js.map +1 -1
- package/codeyam-cli/src/utils/editorScenarios.js +4 -0
- package/codeyam-cli/src/utils/editorScenarios.js.map +1 -1
- package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js +17 -0
- package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js.map +1 -1
- package/codeyam-cli/src/webserver/app/lib/git.js +3 -2
- package/codeyam-cli/src/webserver/app/lib/git.js.map +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{ScenarioViewer-0DY_NKil.js → ScenarioViewer-Bd-hxofb.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{dev.empty-Csi0_PMl.js → dev.empty-BsDh6TSF.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/editor-PBc_6L9R.js +10 -0
- package/codeyam-cli/src/webserver/build/client/assets/editorPreview-4FzHlcNn.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-BF4oLwaE.js → entity._sha._-BsDXNp45.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{entity._sha.scenarios._scenarioId.dev-C7YX6r3H.js → entity._sha.scenarios._scenarioId.dev-BgAqUtTZ.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-Bmshgrij.js +6 -0
- package/codeyam-cli/src/webserver/build/client/assets/globals-B8vTTNy2.css +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/manifest-65850841.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{root-CHOdrM6Y.js → root-BwX8YgFb.js} +8 -8
- package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-BE43Hjti.js +1 -0
- package/codeyam-cli/src/webserver/build/server/assets/{index-BWoRb5RY.js → index-DEEQf4pi.js} +1 -1
- package/codeyam-cli/src/webserver/build/server/assets/{init-DbChSUQP.js → init-CkWmyFY2.js} +1 -1
- package/codeyam-cli/src/webserver/build/server/assets/server-build-BHi-9O8W.js +439 -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/editorProxy.js +26 -4
- package/codeyam-cli/src/webserver/editorProxy.js.map +1 -1
- package/codeyam-cli/src/webserver/terminalServer.js +3 -3
- package/codeyam-cli/src/webserver/terminalServer.js.map +1 -1
- package/codeyam-cli/templates/editor-step-hook.py +11 -6
- package/package.json +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/editor-BBAGP_mE.js +0 -10
- package/codeyam-cli/src/webserver/build/client/assets/editorPreview-BLQMSKZa.js +0 -41
- package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-CF164ouH.js +0 -6
- package/codeyam-cli/src/webserver/build/client/assets/globals-COUSHTyZ.css +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/manifest-9c70d1f3.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-CrAK28Bc.js +0 -1
- package/codeyam-cli/src/webserver/build/server/assets/server-build-BtbLQkKd.js +0 -433
|
@@ -1,433 +0,0 @@
|
|
|
1
|
-
var Oc=Object.defineProperty;var bo=e=>{throw TypeError(e)};var Lc=(e,t,r)=>t in e?Oc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var zn=(e,t,r)=>Lc(e,typeof t!="symbol"?t+"":t,r),Fc=(e,t,r)=>t.has(e)||bo("Cannot "+r);var wo=(e,t,r)=>(Fc(e,t,"read from private field"),r?r.call(e):t.get(e)),vo=(e,t,r)=>t.has(e)?bo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);import{jsx as n,jsxs as d,Fragment as de}from"react/jsx-runtime";import{PassThrough as zc}from"node:stream";import{createReadableStreamFromReadable as Bc}from"@react-router/node";import{ServerRouter as Yc,useFetcher as Fe,useLocation as Hr,useNavigate as St,Link as me,UNSAFE_withComponentProps as Je,Meta as Uc,Links as Wc,ScrollRestoration as Hc,Scripts as Jc,useLoaderData as qe,useRevalidator as kt,Outlet as Vc,data as Q,useSearchParams as Cn,useRouteLoaderData as Gc,useParams as Fi,useActionData as Kc,redirect as No}from"react-router";import{isbot as qc}from"isbot";import{renderToPipeableStream as Qc}from"react-dom/server";import{useState as M,useEffect as ne,useCallback as ie,createContext as ya,useContext as Jr,useRef as ve,useMemo as ae,forwardRef as Zc,useImperativeHandle as Xc,Component as ed}from"react";import{Settings as Co,CheckCircle2 as xa,Bug as zi,AlertTriangle as Ar,Check as ut,Copy as ft,Loader2 as ht,PencilRuler as td,HomeIcon as nd,GitCommitIcon as So,File as rd,RefreshCw as sd,BookOpen as Pr,FlaskConical as ad,SettingsIcon as od,PanelsTopLeftIcon as id,ComponentIcon as ld,FileText as ko,Code as Eo,Box as cd,List as dd,BarChart3 as ud,Tag as md,Image as Zn,Code2 as Bi,Activity as _s,ChevronDown as dt,CircleEqual as pd,ArrowLeft as hd,Terminal as jr,Search as nr,ChevronLeft as fd,ChevronRight as Yt,Save as gd,MessageSquare as yd,Pause as Yi,ListTodo as xd,PauseCircle as bd,FileCode as Mr,GripVertical as wd,Ban as vd,CheckCircle as Nd,FolderOpen as Cd,CodeXml as Sd,Zap as kd,Pencil as Ed,Trash2 as _d,X as Sn,Folder as Ui,Info as Ks,Plus as ba,Eye as Ad,FolderTree as Pd,ChevronsUpDown as Wi,ChevronsDownUp as Hi}from"lucide-react";import"fetch-retry";import jd from"better-sqlite3";import{Pool as Md}from"pg";import*as K from"fs";import fe,{existsSync as Ot,readdirSync as Td,rmSync as As}from"fs";import*as F from"path";import Z,{join as _o}from"path";import{OperationNodeTransformer as $d,sql as rt,Kysely as Ji,ParseJSONResultsPlugin as Id,SqliteDialect as Rd,PostgresDialect as Dd}from"kysely";import*as Od from"kysely/helpers/sqlite";import*as Ld from"kysely/helpers/postgres";import Ue from"typescript";import*as we from"fs/promises";import Ne,{writeFile as Jn,readFile as qs,mkdir as Fd}from"fs/promises";import*as wa from"os";import Qs from"os";import zd from"prompts";import Tr from"chalk";import*as Bd from"crypto";import rr,{randomUUID as va,createHmac as Yd}from"crypto";import{execSync as Ee,spawn as Et,exec as Na}from"child_process";import{fileURLToPath as Vr}from"url";import{promisify as Ca}from"util";import Ud from"dotenv";import Wd,{EventEmitter as Gr}from"events";import{v4 as Hd}from"uuid";import Sa from"http";import Vi from"net";import{WebSocket as ka}from"ws";import"node-pty";import Jd from"openai";import Vd from"p-queue";import Ao from"p-retry";import{DynamoDBClient as Kr,PutItemCommand as Gd}from"@aws-sdk/client-dynamodb";import{LRUCache as Ea}from"lru-cache";import"pluralize";import"piscina";import Kd from"json5";import{marshall as qd}from"@aws-sdk/util-dynamodb";import Qd from"v8";import{Prism as Zd}from"react-syntax-highlighter";import{vscDarkPlus as Xd}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as eu}from"node:crypto";import{minimatch as Zs}from"minimatch";import tu from"react-markdown";import nu from"remark-gfm";import ru from"react-diff-viewer-continued";const Gi=5e3;function su(e,t,r,s,a){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let l=!1,c=e.headers.get("user-agent"),m=c&&qc(c)||s.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>h(),Gi+1e3);const{pipe:p,abort:h}=Qc(n(Yc,{context:s,url:e.url}),{[m](){l=!0;const f=new zc({final(g){clearTimeout(u),u=void 0,g()}}),y=Bc(f);r.set("Content-Type","text/html"),p(f),o(new Response(y,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const au=Object.freeze(Object.defineProperty({__proto__:null,default:su,streamTimeout:Gi},Symbol.toStringTag,{value:"Module"}));function ou({id:e,selected:t,onClick:r,icon:s,name:a}){const[o,i]=M(!1);ne(()=>{i(!0)},[]);const l=ie(()=>{r==null||r(e)},[r,e]);return d("button",{className:`
|
|
2
|
-
w-full px-1.5 py-2 cursor-pointer focus:outline-none
|
|
3
|
-
flex flex-col items-center justify-center gap-1 transition-colors
|
|
4
|
-
${t?"text-[#CBF3FA]":"text-[#568B94] hover:text-[#CBF3FA]"}
|
|
5
|
-
`,onClick:l,children:[n("div",{className:`${t?"bg-[#CBF3FA] text-[#022A35]":""} w-9 h-9 rounded-lg flex items-center justify-center transition-colors`,children:o&&s}),n("span",{className:`text-[10px] font-normal text-center leading-tight ${t?"text-[#CBF3FA]":""}`,style:t?{color:"#CBF3FA !important"}:void 0,children:a})]})}const qr="/assets/cy-logo-cli-CCKUIm0S.svg";function iu(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 lu({content:e,className:t=""}){const[r,s]=M(!1),a=ie(()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),2e3)}).catch(o=>{console.error("Failed to copy:",o)})},[e]);return n("button",{onClick:a,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?d(de,{children:[n(ut,{size:14}),"Copied"]}):d(de,{children:[n(ft,{size:14}),"Copy"]})})}function Ki({isOpen:e,onClose:t,context:r,defaultEmail:s="",screenshotDataUrl:a}){const[o,i]=M(""),[l,c]=M(s),[m,u]=M(!1),[p,h]=M(!1),[f,y]=M(null),[g,x]=M(null),b=Fe(),w=b.state!=="idle",v=!!(r.scenarioId||r.analysisId),C=r.analysisId||r.scenarioId||"",P=()=>{const _=`/codeyam-diagnose ${C}`;return o.trim()?`${_} ${o.trim()}`:_};if(b.data&&!p&&!g){const _=b.data;_.success&&_.reportId?(h(!0),y(_.reportId)):_.error&&x(_.error)}const N=async()=>{x(null);const _=new FormData;if(_.append("issueType","other"),_.append("description",o),_.append("email",l),_.append("source",r.source),_.append("entitySha",r.entitySha||""),_.append("scenarioId",r.scenarioId||""),_.append("analysisId",r.analysisId||""),_.append("currentUrl",r.currentUrl),_.append("entityName",r.entityName||""),_.append("entityType",r.entityType||""),_.append("scenarioName",r.scenarioName||""),_.append("errorMessage",r.errorMessage||""),a)try{const T=await(await fetch(a)).blob();_.append("screenshot",T,"screenshot.jpg")}catch(j){console.error("Failed to convert screenshot:",j)}b.submit(_,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},S=()=>{i(""),u(!1),h(!1),y(null),x(null),t()},k=_=>{_.key==="Escape"&&S()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:k,children:d("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl max-h-[90vh] overflow-y-auto",children:[d("div",{className:"flex items-center justify-between mb-6",children:[d("div",{className:"flex items-center gap-3",children:[w?n("div",{className:"animate-spin",children:n(Co,{size:24,style:{strokeWidth:1.5}})}):p?n(xa,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(zi,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:p?"Report Submitted":"Report Issue"})]}),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"})})})]}),p?d("div",{children:[d("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[n("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),d("p",{className:"text-xs text-green-700",children:["Report ID:"," ",n("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),n("p",{className:"text-sm text-gray-600 mb-6",children:"The CodeYam team will investigate and may reach out if you provided an email address."}),n("div",{className:"flex justify-end",children:n("button",{onClick:S,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):d("div",{children:[d("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[d("div",{className:"flex items-center justify-between",children:[n("div",{className:"text-sm font-medium text-gray-900",title:`${r.source}${r.entitySha?` • Entity: ${r.entitySha}`:""}${r.scenarioId?` • Scenario: ${r.scenarioId}`:""}${r.analysisId?` • Analysis: ${r.analysisId}`:""}`,children:iu(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&&d("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[d("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),d("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&d("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&d("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&d("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),a&&d("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:a,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),d("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:o,onChange:_=>i(_.target.value),placeholder:"Optional: Describe what you expected vs what happened...",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] resize-none"})]}),v&&d(de,{children:[d("div",{className:"mb-4 p-4 bg-purple-50 rounded-lg border border-purple-200",children:[d("div",{className:"flex items-center gap-2 mb-2",children:[n("span",{className:"text-lg",children:"🔧"}),n("h3",{className:"text-sm font-semibold text-purple-900",children:"Diagnose & Fix (Recommended)"})]}),n("p",{className:"text-xs text-purple-700 mb-3",children:"Run this command in Claude Code to investigate the issue locally and potentially fix it. A detailed report will also be uploaded."}),d("div",{className:"relative",children:[n("div",{className:"bg-gray-800 text-gray-50 px-3 py-2.5 pr-20 rounded-md text-xs font-mono overflow-x-auto whitespace-nowrap",children:P()}),n(lu,{content:P(),className:"absolute top-1.5 right-2 px-2 py-1 bg-purple-600 text-white border-none rounded text-[11px] font-medium hover:bg-purple-700 transition-colors"})]})]}),d("div",{className:"relative my-5",children:[n("div",{className:"absolute inset-0 flex items-center",children:n("div",{className:"w-full border-t border-gray-300"})}),n("div",{className:"relative flex justify-center",children:n("span",{className:"bg-white px-3 text-xs text-gray-500 uppercase",children:"or"})})]})]}),d("div",{className:v?"opacity-75":"",children:[v&&d("div",{className:"flex items-center gap-2 mb-3",children:[n("span",{className:"text-lg",children:"📤"}),n("h3",{className:"text-sm font-semibold text-gray-700",children:"Quick Report"}),n("span",{className:"text-xs text-gray-500",children:"(won't investigate locally)"})]}),d("div",{className:"mb-4",children:[n("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),n("input",{id:"email",type:"email",value:l,onChange:_=>c(_.target.value),placeholder:"you@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"})]}),d("div",{className:"mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(Ar,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),d("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),w&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:b.formData?"Uploading report...":"Creating archive..."})}),g&&d("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(Ar,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),d("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:g})]})]}),d("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:S,disabled:w,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors disabled:opacity-50 cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>void N(),disabled:w,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer",children:w?d(de,{children:[n("div",{className:"animate-spin",children:n(Co,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):g?"Try Again":"Submit Report"})]})]})]})]})}):null}const Po={source:"navbar"},_a=ya(void 0);function cu({children:e}){const[t,r]=M(Po),s=ie(o=>{r(o)},[]),a=ie(()=>{r(Po)},[]);return n(_a.Provider,{value:{contextData:t,setContextData:s,resetContextData:a},children:e})}function xt(e){const t=Jr(_a),r=ve(t);ne(()=>{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 du(){const e=Jr(_a),t=Hr();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 uu({labs:e,isAdmin:t,editorMode:r}){var N;const s=Hr(),a=St(),[o,i]=M(),[l,c]=M(!1),[m,u]=M(!1),[p,h]=M(null),f=Fe();ne(()=>{f.state==="idle"&&!f.data&&f.load("/api/generate-report")},[f]);const y=((N=f.data)==null?void 0:N.defaultEmail)||"",g={width:"20px",height:"20px",strokeWidth:1.5},x=(e==null?void 0:e.simulations)??!1,b=[{id:"editor",icon:n(td,{style:g}),link:"/editor",name:"Editor",hidden:!r},{id:"dashboard",icon:n(nd,{style:g}),link:"/",name:"Dashboard",hidden:!x},{id:"simulations",icon:d("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(So,{style:g}),link:"/git",name:"Git",hidden:!x},{id:"files",icon:n(rd,{style:g}),link:"/files",name:"Files",hidden:!x},{id:"activity",icon:n(sd,{style:g}),link:"/activity",name:"Activity",hidden:!x},{id:"memory",icon:n(Pr,{style:g}),link:"/memory",name:"Memory"},{id:"labs",icon:n(ad,{style:g}),link:"/labs",name:"Labs"},{id:"settings",icon:n(od,{style:g}),link:"/settings",name:"Settings"},{id:"commits",icon:n(So,{style:g}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(id,{style:g}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(ld,{style:g}),link:"/components",name:"Components",hidden:!0}],w=ie(S=>{const k=b.find(_=>_.id===S);k!=null&&k.link&&a(k.link),i(_=>_===S?void 0:S)},[b,a]);ne(()=>{const S={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[k,_]of Object.entries(S))if(_.some(j=>j==="/"?s.pathname==="/":s.pathname.includes(j))){i(k);return}i(void 0)},[s]);const v=async()=>{u(!0);try{const{default:S}=await import("html2canvas-pro"),_=(await S(document.body)).toDataURL("image/jpeg",.8);h(_),c(!0)}catch(S){console.error("Screenshot capture failed:",S),c(!0)}finally{u(!1)}},C=()=>{c(!1),h(null)},P=du();return d(de,{children:[d("div",{id:"sidebar",className:"sticky top-0 w-full h-screen bg-[#051C22] flex flex-col justify-between py-3",children:[d("div",{className:"w-full flex flex-col items-center",children:[n("div",{className:"py-3 mt-2 mb-4",children:n(me,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:qr,alt:"CodeYam",className:"h-6"})})}),b.filter(S=>!S.hidden).map(S=>n(ou,{id:S.id,selected:S.id===o,onClick:w,icon:S.icon,name:S.name},`sidebar-button-${S.id}`))]}),t&&n("div",{className:"w-full flex flex-col items-center pb-2",children:d("button",{onClick:()=>void v(),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(zi,{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`})]})})]}),l&&n(Ki,{isOpen:!0,onClose:C,context:P,defaultEmail:y,screenshotDataUrl:p??void 0})]})}const qi=ya(void 0);function mu({children:e}){const[t,r]=M([]),s=ie((o,i="info",l=5e3)=>{const m={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:l};r(u=>[...u,m])},[]),a=ie(o=>{r(i=>i.filter(l=>l.id!==o))},[]);return n(qi.Provider,{value:{toasts:t,showToast:s,closeToast:a},children:e})}function Aa(){const e=Jr(qi);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function pu({toast:e,onClose:t}){ne(()=>{const a=e.duration||5e3;if(a>0){const o=setTimeout(()=>{t(e.id)},a);return()=>clearTimeout(o)}},[e.id,e.duration,t]);const r={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return d("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg min-w-[320px] max-w-[500px] animate-[slideIn_0.3s_ease-out] ${{success:"bg-emerald-50 border-emerald-200 text-emerald-900",error:"bg-red-50 border-red-200 text-red-900",info:"bg-blue-50 border-blue-200 text-blue-900",warning:"bg-amber-50 border-amber-200 text-amber-900"}[e.type]}`,children:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function hu({toasts:e,onClose:t}){return e.length===0?null:d("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
|
|
7
|
-
@keyframes slideIn {
|
|
8
|
-
from {
|
|
9
|
-
transform: translateX(400px);
|
|
10
|
-
opacity: 0;
|
|
11
|
-
}
|
|
12
|
-
to {
|
|
13
|
-
transform: translateX(0);
|
|
14
|
-
opacity: 1;
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
`}),e.map(r=>n(pu,{toast:r,onClose:t},r.id))]})}function _t(e,t){const[r,s]=M(""),[a,o]=M(!1),[i,l]=M(null),[c,m]=M(!1);ne(()=>{t&&(m(!1),o(!1),l(null))},[t]),ne(()=>{if(!e||!t){t||s("");return}const p=async()=>{if(!c)try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const g=(await f.text()).trim().split(`
|
|
18
|
-
`).filter(w=>w.length>0);if(g.length<3){o(!1),m(!1),l(null),s("");return}const x=g.filter(w=>w.includes("CodeYam Log Level 1"));if(x.length>0){const w=x[x.length-1];s(w.replace(/.*CodeYam Log Level 1: /,""))}const b=g.find(w=>w.includes("$$INTERACTIVE_SERVER_URL$$:"));if(b){const w=b.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();l(w),m(!0)}g.some(w=>w.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};p().catch(()=>{});const h=setInterval(()=>{p().catch(()=>{})},500);return()=>clearInterval(h)},[e,t,c]);const u=ie(()=>{s(""),o(!1),l(null),m(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:a,resetLogs:u}}function Ft({projectSlug:e,onClose:t}){const[r,s]=M("Loading logs..."),[a,o]=M(!0),[i,l]=M(!0),[c,m]=M("all"),u=ve(null);return ne(()=>{const p=async()=>{try{const h=await fetch(`/api/logs/${e}`);if(h.ok){const f=await h.text();if(c==="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])<=c});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: ${h.status} - ${await h.text()}`)}catch(h){s(`Error fetching logs: ${h.message}`)}};if(p().catch(()=>{}),a){const h=setInterval(()=>{p().catch(()=>{})},2e3);return()=>clearInterval(h)}},[e,a,i,c]),ne(()=>{const p=h=>{h.key==="Escape"&&t()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:d("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:p=>p.stopPropagation(),children:[d("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[d("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),d("div",{className:"flex items-center gap-4",children:[d("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),d("select",{value:c,onChange:p=>m(p.target.value==="all"?"all":Number(p.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),d("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:a,onChange:p=>o(p.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),d("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:p=>l(p.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 at({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(Bi,{size:a,color:s.iconColor});case"visual":return n(Zn,{size:a,color:s.iconColor});case"type":return n(md,{size:a,color:s.iconColor});case"data":return n(ud,{size:a,color:s.iconColor});case"index":return n(dd,{size:a,color:s.iconColor});case"functionCall":return n(Eo,{size:a,color:s.iconColor});case"class":return n(cd,{size:a,color:s.iconColor});case"method":return n(Eo,{size:a,color:s.iconColor});case"other":return n(ko,{size:a,color:s.iconColor});default:return n(ko,{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 Qi({filePath:e,maxLength:t=60,className:r,style:s}){const o=((l,c)=>{if(l.length<=c)return l;const m="...",u=c-m.length,p=Math.ceil(u*.4),h=Math.floor(u*.6),f=l.slice(0,p),y=l.slice(-h),g=f.lastIndexOf("/"),x=y.indexOf("/"),b=g>p*.5?f.slice(0,g+1):f,w=x!==-1&&x<h*.5?y.slice(x):y;return`${b}${m}${w}`})(e,t),i=o!==e;return n("span",{className:r||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...s,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:o})}function Ps({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:s=50,showScenarioCount:a=!1,scenarioCount:o=0,additionalContent:i}){return d("div",{className:"flex flex-col gap-1",children:[d("div",{className:"flex items-center gap-1",children:[n(at,{type:e.entityType||"other"}),d(me,{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(Qi,{filePath:e.filePath,maxLength:s,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const js={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function fu({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:s=!1,queuedJobCount:a=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:l=[]}){var Y,U,B;const[c,m]=M(!1),[u,p]=M(!1),[h,f]=M(null),[y,g]=M(new Set),[x,b]=M(new Set),[w,v]=M(!1),C=!!i||o.length>0,P=!!i,N=(i==null?void 0:i.entities)||r,S=!!(e!=null&&e.analysisCompletedAt),k=(e==null?void 0:e.readyToBeCaptured)??0,_=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||S&&(k===0||_>=k);const j=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,T=C,{lastLine:E}=_t(t,T),$=P||o.length>0,R=new Set(((Y=i==null?void 0:i.entities)==null?void 0:Y.map(H=>H.sha))||[]),I=l.filter(H=>!(H.currentEntityShas||[]).some(A=>R.has(A))),W=(()=>{const D=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&j){const A=e.analysisCompletedAt||e.createdAt;if(new Date(A).getTime()>D)return!0}if(I.length>0){const A=I[0],J=A.analysisCompletedAt||A.archivedAt||A.createdAt;if(J&&new Date(J).getTime()>D)return!0}return!1})();return ne(()=>{const H=(i==null?void 0:i.id)||null;C&&!u&&H!==h&&p(!0),!C&&h!==null&&f(null)},[C,i==null?void 0:i.id,u,h]),d(de,{children:[d("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${u?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!u&&d("div",{onClick:()=>{p(!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(_s,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:$?"Analyzing...":"Activity: No Activity Yet"}),$&&n("button",{onClick:H=>{H.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&&d("div",{children:[d("div",{className:"flex items-center justify-between px-3 py-2",children:[d("div",{className:"flex items-center gap-2",children:[$?n(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(_s,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:$?"Analyzing...":"Activity"})]}),d("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>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:()=>{p(!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(dt,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),d("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[$&&i&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(_s,{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:N.length>0?d("div",{className:"space-y-1.5",children:[(w?N:N.slice(0,3)).map(H=>n(Ps,{entity:H,nameSize:"11px",pathSize:"10px",pathMaxLength:150},H.sha)),N.length>3&&n("button",{onClick:()=>v(H=>!H),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:js,"aria-label":w?"Show fewer entities":`Show ${N.length-3} more entities`,children:w?"Show less":`+${N.length-3} more`}),E&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:E})]}):d("div",{children:[i.entityNames&&i.entityNames.length>0?d("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((H,D)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:H},D)),i.entityNames.length>5&&d("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):d("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((U=i.entityShas)==null?void 0:U.length)||0," ",((B=i.entityShas)==null?void 0:B.length)===1?"entity":"entities","..."]}),E&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:E})]})})]}),o.length>0&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(pd,{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(H=>{var J,V;const D=y.has(H.id),A=D?H.entities:H.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:H.entities.length>0?d("div",{className:"space-y-1.5",children:[A.map(q=>n(Ps,{entity:q,nameSize:"10px",pathSize:"9px",pathMaxLength:120},q.sha)),H.entities.length>3&&n("button",{onClick:()=>{g(q=>{const X=new Set(q);return X.has(H.id)?X.delete(H.id):X.add(H.id),X})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:js,"aria-label":D?"Show fewer entities":`Show ${H.entities.length-3} more entities`,children:D?"Show less":`+${H.entities.length-3} more`})]}):d("div",{style:{fontSize:"10px",color:"#343434"},children:[H.type==="analysis"&&n(de,{children:H.entityNames&&H.entityNames.length>0?d("div",{className:"space-y-0.5",children:[H.entityNames.slice(0,5).map((q,X)=>n("div",{children:q},X)),H.entityNames.length>5&&d("div",{className:"italic",children:["+",H.entityNames.length-5," more"]})]}):`Analyzing ${((J=H.entityShas)==null?void 0:J.length)||0} ${((V=H.entityShas)==null?void 0:V.length)===1?"entity":"entities"}`}),H.type==="recapture"&&"Recapturing scenario",H.type==="debug-setup"&&"Setting up debug environment"]})},H.id)})})]}),W&&I.length>0&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(xa,{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:I.slice(0,3).map((H,D)=>{const A=H.entities||[],J=H.analysisCompletedAt||H.archivedAt||H.createdAt||"",V=(()=>{if(!J)return"";const O=Date.now()-new Date(J).getTime(),z=Math.floor(O/6e4),G=Math.floor(O/36e5);return G>0?`${G}h ago`:z>0?`${z}m ago`:"just now"})(),q=x.has(D),L=(q?A:A.slice(0,3)).map(O=>{var z,G,ee;return{...O,scenarioCount:((ee=(G=(z=O.analyses)==null?void 0:z[0])==null?void 0:G.scenarios)==null?void 0:ee.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:A.length>0&&d("div",{className:"space-y-1.5",children:[L.map((O,z)=>d("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(Ps,{entity:O,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:O.scenarioCount})}),z===0&&V&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:V})]},O.sha)),A.length>3&&n("button",{onClick:()=>{b(O=>{const z=new Set(O);return z.has(D)?z.delete(D):z.add(D),z})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:js,"aria-label":q?"Show fewer entities":`Show ${A.length-3} more entities`,children:q?"Show less":`+${A.length-3} more`})]})},D)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(me,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),c&&t&&n(Ft,{projectSlug:t,onClose:()=>m(!1)})]})}function ot(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function sr(e){const{file_id:t,project_id:r,commit_id:s,file_path:a,entity_type:o,entity_branches:i,analyses:l,commit:c,created_at:m,updated_at:u,...p}=e,h=(i??[]).map(g=>g.branch_id),f=l?l.map(At):void 0,y=c?on(c):void 0;return ot({...p,fileId:t,projectId:r,commitId:s,filePath:a,entityType:o,commit:y,analyses:f,branchIds:h,createdAt:m,updatedAt:u})}function Pa(e){return ot({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 Qr(e){const{branches:t,files:r,analyzed_at:s,content_changed_at:a,created_at:o,updated_at:i,github_token:l,configuration:c,team_id:m,...u}=e;return ot({...u,branches:t?t.map(ln):void 0,files:r?r.map(Pa):void 0,analyzedAt:s,contentChangedAt:a,createdAt:o,updatedAt:i})}function gu(e){const{id:t,project_id:r,user_id:s,scenario_id:a,thumbs_up:o,user:i}=e,l=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return ot({id:t,projectId:r,userId:s,scenarioId:a,thumbsUp:!!o,user:l})}function yu(e){const{id:t,project_id:r,user_id:s,scenario_id:a,text:o,created_at:i,updated_at:l,user:c}=e,m=c?{username:c.github_username,avatarUrl:c.github_user.avatar_url}:void 0;return ot({id:t,projectId:r,userId:s,scenarioId:a,text:o,createdAt:i,updatedAt:l,user:m})}function Zi(e){const{project_id:t,analysis_id:r,previous_version_id:s,analysis:a,user_scenarios:o,scenario_comments:i,approved:l,...c}=e,m=a?At(a):void 0,u=o?o.map(gu):void 0,p=i?i.map(yu):void 0;return ot({...c,projectId:t,analysisId:r,previousVersionId:s,analysis:m,userScenarios:u,comments:p})}function xu(e){return ot({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?sr(e.entity):void 0,branch:e.branch?ln(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:l,previous_analysis_id:c,file:m,entity:u,commit:p,project:h,scenarios:f,analysis_branches:y,dependency_analyzed_tree_sha:g,analyzed_tree_sha:x,branch_commit_sha:b,committed_at:w,completed_at:v,created_at:C,updated_at:P,indirect:N,...S}=e,k=u?sr(u):void 0,_=m?Pa(m):void 0,j=h?Qr(h):void 0,T=p?on(p):void 0,E=f?f.map(Zi):void 0,$=y?y.map(xu):void 0,R=$?$.map(I=>I.branch):void 0;return ot({...S,projectId:t,commitId:r,fileId:s,filePath:a,entitySha:o,entityType:i,entityName:l,previousAnalysisId:c,entity:k,file:_,commit:T,project:j,scenarios:E,analysisBranches:$,branches:R,dependencyAnalyzedTreeSha:g,analyzedTreeSha:x,branchCommitSha:b,committedAt:w,completedAt:v,createdAt:C,updatedAt:P,indirect:!!N})}function ja(e){return ot({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?on(e.commit):void 0,branch:e.branch?ln(e.branch):void 0})}function bu(e){const{project_id:t,commit_id:r,created_at:s,updated_at:a,success:o,...i}=e;return ot({...i,projectId:t,commitId:r,createdAt:s,updatedAt:a,success:!!o})}function on(e){const{project_id:t,branch_id:r,branch:s,background_jobs:a,merged_branch_id:o,mergedBranch:i,ai_message:l,html_url:c,author:m,analyses:u,entities:p,commit_branches:h,committed_at:f,analyzed_at:y,...g}=e,x=s?ln(s):void 0,b=i?ln(i):void 0,w=(a==null?void 0:a.length)>0?bu(a[a.length-1]):void 0,v=(u??[]).map(At),C=(p??[]).map(sr),P=(h==null?void 0:h.length)>0?h.map(ja):void 0;return m&&(m.username=m.preferredUsername??m.username),ot({...g,projectId:t,branchId:r,branch:x,backgroundJob:w,mergedBranchId:o,mergedBranch:b,aiMessage:l,htmlUrl:c,author:m,analyses:v,entities:C,commitBranches:P,committedAt:f,analyzedAt:y})}function ln(e){const{project_id:t,content_changed_at:r,commits:s,analysis_branches:a,active_at:o,created_at:i,updated_at:l,primary:c,...m}=e,u=s?s.map(on):void 0,p=a?a.flatMap(h=>At(h.analysis)):void 0;return ot({...m,projectId:t,contentChangedAt:r,commits:u,analyses:p,activeAt:o,createdAt:i,updatedAt:l,primary:!!c})}var Ur;class wu{constructor(){vo(this,Ur,new vu)}transformQuery(t){return wo(this,Ur).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}Ur=new WeakMap;class vu extends $d{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 le=()=>null;function $e(e=!1){return t=>(t=t.defaultTo(rt`CURRENT_TIMESTAMP`),e&&(t=t.notNull()),t)}const Nu={analyzed_at:le(),configuration:le(),content_changed_at:le(),created_at:le(),description:le(),github_token:le(),id:le(),metadata:le(),name:le(),path:le(),slug:le(),team_id:le(),updated_at:le()},Cu=Object.keys(Nu);async function Su(e){await e.schema.createTable("projects").addColumn("id","uuid",t=>t.primaryKey()).addColumn("name","text").addColumn("slug","text",t=>t.notNull()).addColumn("github_token","text").addColumn("description","text").addColumn("path","text").addColumn("configuration","text").addColumn("metadata","text").addColumn("content_changed_at","datetime").addColumn("analyzed_at","datetime").addColumn("created_at","datetime",$e(!0)).addColumn("updated_at","datetime",$e()).addColumn("team_id","integer").ifNotExists().execute()}async function ku(e){await e.schema.createTable("analyses").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("file_id","uuid").addColumn("commit_id","uuid").addColumn("entity_sha","varchar").addColumn("entity_name","varchar").addColumn("status","text").addColumn("metadata","text").addColumn("created_at","datetime",$e(!0)).addColumn("updated_at","datetime",$e(!0)).addColumn("tree_sha","text").addColumn("analyzed_tree_sha","text").addColumn("dependency_analyzed_tree_sha","text").addColumn("previous_analysis_id","uuid").addColumn("branch_commit_sha","varchar").addColumn("indirect","boolean").addColumn("committed_at","datetime").addColumn("completed_at","datetime").addColumn("file_path","varchar").addColumn("entity_type","varchar").ifNotExists().execute()}const Eu={active:le(),analysis_id:le(),branch_id:le(),created_at:le(),entity_sha:le(),id:le()},_u=Object.keys(Eu);async function Au(e){await e.schema.createTable("analysis_branches").addColumn("id","uuid",t=>t.primaryKey()).addColumn("analysis_id","uuid",t=>t.notNull()).addColumn("branch_id","uuid",t=>t.notNull()).addColumn("entity_sha","varchar",t=>t.notNull()).addColumn("active","boolean",t=>t.defaultTo(!0)).addColumn("created_at","datetime",$e()).ifNotExists().execute()}async function Pu(e){await e.schema.createTable("background_jobs").addColumn("commit_id","uuid",t=>t.notNull()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("progress","text").addColumn("success","boolean").addColumn("created_at","datetime",$e(!0)).addColumn("updated_at","datetime").addPrimaryKeyConstraint("background_jobs_pkey",["project_id","commit_id"]).ifNotExists().execute()}const ju={active_at:le(),content_changed_at:le(),created_at:le(),id:le(),metadata:le(),name:le(),primary:le(),project_id:le(),ref:le(),sha:le(),updated_at:le()},Xi=Object.keys(ju);async function Mu(e){await e.schema.createTable("branches").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("ref","text").addColumn("name","text").addColumn("sha","text").addColumn("primary","boolean",t=>t.notNull().defaultTo(!1)).addColumn("metadata","text").addColumn("content_changed_at","datetime",$e()).addColumn("active_at","datetime").addColumn("created_at","datetime",$e(!0)).addColumn("updated_at","datetime",$e()).ifNotExists().execute()}async function Tu(e){await e.schema.createTable("commit_branches").addColumn("id","uuid",t=>t.primaryKey()).addColumn("branch_id","uuid").addColumn("commit_id","uuid").addColumn("active","boolean").addColumn("created_at","datetime",$e(!0)).ifNotExists().execute()}const $u={ai_message:le(),analyzed_at:le(),author_github_username:le(),branch_id:le(),committed_at:le(),created_at:le(),files:le(),html_url:le(),id:le(),merged_branch_id:le(),message:le(),metadata:le(),project_id:le(),sha:le(),title:le(),url:le()},el=Object.keys($u),Iu=el.filter(e=>e!=="files");async function Ru(e){await e.schema.createTable("commits").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("branch_id","uuid").addColumn("merged_branch_id","uuid").addColumn("message","text").addColumn("ai_message","text").addColumn("title","varchar").addColumn("author_github_username","varchar").addColumn("url","varchar").addColumn("html_url","varchar").addColumn("sha","varchar",t=>t.notNull()).addColumn("files","text").addColumn("metadata","text").addColumn("committed_at","datetime").addColumn("analyzed_at","datetime").addColumn("created_at","datetime",$e(!0)).ifNotExists().execute()}async function Du(e){await e.schema.createTable("debug_reports").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_slug","varchar",t=>t.notNull()).addColumn("s3_key","varchar",t=>t.notNull()).addColumn("file_size_bytes","bigint").addColumn("metadata","text").addColumn("status","varchar").addColumn("created_at","datetime",$e(!0)).addColumn("uploaded_at","datetime").addColumn("base_sha","varchar").addColumn("delta_size_bytes","bigint").ifNotExists().execute()}async function Ou(e){await e.schema.createTable("labs_requests").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_slug","varchar",t=>t.notNull().unique()).addColumn("name","varchar",t=>t.notNull()).addColumn("email","varchar",t=>t.notNull()).addColumn("org_name","varchar").addColumn("org_size","varchar").addColumn("project_size","varchar").addColumn("tech_stack","varchar").addColumn("status","varchar").addColumn("unlock_code","varchar").addColumn("created_at","datetime",$e(!0)).addColumn("approved_at","datetime").ifNotExists().execute()}const Lu={commit_id:le(),created_at:le(),description:le(),documentation:le(),entity_type:le(),file_id:le(),file_path:le(),metadata:le(),name:le(),project_id:le(),quality:le(),sha:le(),updated_at:le()},tl=Object.keys(Lu);async function Fu(e){await e.schema.createTable("entities").addColumn("project_id","uuid",t=>t.notNull()).addColumn("file_id","uuid").addColumn("commit_id","uuid").addColumn("name","varchar").addColumn("sha","varchar",t=>t.primaryKey()).addColumn("entity_type","varchar").addColumn("file_path","varchar").addColumn("description","text").addColumn("documentation","text").addColumn("metadata","text").addColumn("quality","text").addColumn("created_at","datetime",$e(!0)).addColumn("updated_at","datetime").ifNotExists().execute()}const zu={active:le(),branch_id:le(),entity_sha:le()},Bu=Object.keys(zu);async function Yu(e){await e.schema.createTable("entity_branches").addColumn("branch_id","uuid",t=>t.notNull()).addColumn("entity_sha","varchar",t=>t.notNull()).addColumn("active","boolean",t=>t.defaultTo(!0)).addPrimaryKeyConstraint("entity_branches_pkey",["branch_id","entity_sha"]).ifNotExists().execute()}async function Uu(e){await e.schema.createTable("entity_statements").addColumn("id","integer",t=>t.autoIncrement().primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("entity_sha","varchar",t=>t.notNull()).addColumn("statement_sha","varchar",t=>t.notNull()).addColumn("created_at","datetime",$e(!0)).ifNotExists().execute()}const Wu={created_at:le(),deleted:le(),id:le(),metadata:le(),name:le(),path:le(),project_id:le(),updated_at:le()},Hu=Object.keys(Wu);async function Ju(e){await e.schema.createTable("files").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("name","varchar").addColumn("path","varchar",t=>t.notNull()).addColumn("deleted","boolean",t=>t.defaultTo(!1)).addColumn("created_at","datetime",$e(!0)).addColumn("updated_at","datetime",$e()).addColumn("metadata","text").ifNotExists().execute()}async function Vu(e){await e.schema.createTable("github_payloads").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("payload_type","varchar").addColumn("payload","text").addColumn("after","varchar").addColumn("commit_sha","varchar").addColumn("ref","varchar").addColumn("committed_at","datetime").addColumn("error","text").addColumn("created_at","datetime",$e(!0)).ifNotExists().execute()}async function Gu(e){await e.schema.createTable("github_users").addColumn("username","varchar",t=>t.primaryKey()).addColumn("preferred_username","varchar").addColumn("avatar_url","varchar").addColumn("created_at","datetime",$e(!0)).addColumn("updated_at","datetime",$e()).ifNotExists().execute()}async function Ku(e){await e.schema.createTable("scenario_comments").addColumn("id","serial",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("scenario_id","uuid").addColumn("user_id","uuid").addColumn("text","text").addColumn("metadata","text").addColumn("created_at","datetime",$e(!0)).addColumn("updated_at","datetime",$e(!0)).ifNotExists().execute()}async function qu(e){await e.schema.createTable("editor_scenarios").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("name","varchar",t=>t.notNull()).addColumn("description","text").addColumn("component_name","varchar").addColumn("component_path","varchar").addColumn("url","varchar").addColumn("type","varchar").addColumn("screenshot_path","varchar").addColumn("created_at","datetime",$e(!0)).addColumn("updated_at","datetime",$e(!0)).ifNotExists().execute();for(const t of["component_name","component_path","url","type","screenshot_path"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"varchar").execute()}catch{}for(const t of["viewport_width","viewport_height"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"integer").execute()}catch{}try{await e.schema.alterTable("editor_scenarios").addColumn("dimension","varchar").execute()}catch{}}const Qu={analysis_id:le(),approved:le(),created_at:le(),description:le(),id:le(),metadata:le(),name:le(),previous_version_id:le(),project_id:le()},$r=Object.keys(Qu);async function Zu(e){await e.schema.createTable("scenarios").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("analysis_id","uuid").addColumn("name","varchar").addColumn("description","text").addColumn("metadata","text").addColumn("approved","boolean").addColumn("previous_version_id","uuid").addColumn("created_at","datetime",$e(!0)).ifNotExists().execute()}async function Xu(e){await e.schema.createTable("statements").addColumn("sha","varchar",t=>t.primaryKey()).addColumn("text","text",t=>t.notNull()).addColumn("llm_call_id","varchar").addColumn("results","text").addColumn("issues","text").addColumn("created_at","datetime",$e(!0)).ifNotExists().execute()}async function em(e){await e.schema.createTable("teams").addColumn("id","serial",t=>t.primaryKey()).addColumn("name","varchar",t=>t.notNull()).addColumn("created_at","datetime",$e(!0)).ifNotExists().execute()}async function tm(e){await e.schema.createTable("user_scenarios").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("scenario_id","uuid",t=>t.notNull()).addColumn("user_id","uuid",t=>t.notNull()).addColumn("thumbs_up","boolean",t=>t.defaultTo(!1)).addColumn("created_at","datetime",$e(!0)).ifNotExists().execute()}async function nm(e){await e.schema.createTable("user_teams").addColumn("team_id","integer",t=>t.notNull()).addColumn("user_auth_id","uuid",t=>t.notNull()).addPrimaryKeyConstraint("user_teams_pkey",["team_id","user_auth_id"]).ifNotExists().execute()}async function rm(e){await e.schema.createTable("users").addColumn("auth_id","uuid",t=>t.primaryKey()).addColumn("email","varchar").addColumn("github_username","varchar").addColumn("github_token","varchar").addColumn("verified","boolean",t=>t.defaultTo(!1)).addColumn("created_at","datetime",$e(!0)).addColumn("updated_at","datetime",$e()).ifNotExists().execute()}const sm=!!cn("ENABLE_QUERY_LOGGING"),am=!!cn("ENABLE_QUERY_ERROR_LOGGING");cn("USE_LOCAL_POSTGRESQL_FOR_TESTING");let dr;function je(){if(!dr){const e=rl();if(e==="sqlite")dr=om();else if(e==="postgresql")dr=im();else throw new Error(`Unknown database type: ${e}`)}return dr}function om(e){if(e||(e=cn("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=K.existsSync(e),r=F.dirname(e);if(!K.existsSync(r))K.mkdirSync(r,{recursive:!0,mode:493});else try{K.chmodSync(r,493)}catch(a){console.warn(`Warning: Could not set permissions on database directory: ${a.message}`)}const s=new jd(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 Ji({dialect:new Rd({database:s}),plugins:[new Id,new wu],log:nl})}function im(){const e=cm();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new Md({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,s)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new Ji({dialect:new Dd({pool:t}),log:nl})}let Ms=null;function un(){return Ms||(Ms=lm(rl())),Ms}function nl(e){e.level==="error"?am&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):sm&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function lm(e){if(e==="sqlite")return Od;if(e==="postgresql")return Ld;throw new Error(`Unknown database type: ${e}`)}function rl(){if(cn("SQLITE_PATH"))return"sqlite";if(cn("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}async function zC(e){await Su(e),await ku(e),await Au(e),await Pu(e),await Mu(e),await Tu(e),await Ru(e),await Du(e),await qu(e),await Fu(e),await Yu(e),await Uu(e),await Ju(e),await Vu(e),await Gu(e),await Ou(e),await Ku(e),await Zu(e),await Xu(e),await em(e),await tm(e),await nm(e),await rm(e)}function cm(){const e=cn("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function cn(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}const dm=()=>crypto.randomUUID();function um(e){const{id:t,projectId:r,activeAt:s,contentChangedAt:a,metadata:o,...i}=e;return delete i.commits,delete i.files,delete i.analyses,delete i.createdAt,delete i.updatedAt,{...i,id:t??dm(),project_id:r,active_at:s,content_changed_at:a,metadata:o?JSON.stringify(o):null}}var Ke=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Vite="Vite",e.Expo="Expo",e.Unknown="Unknown",e))(Ke||{});const Zr="Default Scenario";let mm="<main>";function pm(){return mm}function jo(e,...t){Me(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function Me(...e){const t=pm(),r=e.map(a=>{if(a)return typeof a=="string"?a:a instanceof Error?`${a.name}: ${a.message}
|
|
21
|
-
${a.stack}`:typeof a=="object"?hm(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 hm(e,t=2){function r(s,a=new WeakMap){return s===null||typeof s!="object"?s:a.has(s)?`"[Circular: ${s.constructor.name}]"`:(a.set(s,!0),Array.isArray(s)?`[${s.map(l=>{const c=r(l,a);return typeof l=="string"?`"${c}"`:c}).join(",")}]`:`{${Object.entries(s).map(([i,l])=>{let c;return typeof l>"u"?null:(typeof l=="function"?c=`"(function: ${l.name||"anonymous"})"`:l instanceof Date?c=`"${l.toISOString()}"`:typeof l=="object"&&l!==null?c=r(l,a):typeof l=="string"?c=`"${l.replace(/"/g,'\\"')}"`:c=JSON.stringify(l),`"${i.replace(/"/g,'\\"')}":${c}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(s){const a=r(e);if(!t)return a;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(o){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:o,pureStringifyError:s,serialized:a}),a}}}function Ir(e,t){try{let r=function(o){var i,l;if(Ue.isFunctionDeclaration(o)&&Bn(o)){const c=((i=o.name)==null?void 0:i.text)||"default",m=o.getText(s),u=Ts(o);a.push({name:c,code:m,sha:qt(t,c,m),entityType:"function",isDefault:u})}else if(Ue.isClassDeclaration(o)&&Bn(o)){const c=((l=o.name)==null?void 0:l.text)||"default",m=o.getText(s),u=Ts(o),p=m.includes("React.")||m.includes("jsx")||m.includes("tsx");a.push({name:c,code:m,sha:qt(t,c,m),entityType:p?"component":"class",isDefault:u})}else if(Ue.isInterfaceDeclaration(o)&&Bn(o)){const c=o.name.text,m=o.getText(s);a.push({name:c,code:m,sha:qt(t,c,m),entityType:"interface",isDefault:!1})}else if(Ue.isTypeAliasDeclaration(o)&&Bn(o)){const c=o.name.text,m=o.getText(s);a.push({name:c,code:m,sha:qt(t,c,m),entityType:"type",isDefault:!1})}else if(Ue.isVariableStatement(o)&&Bn(o)){const c=Ts(o);o.declarationList.declarations.forEach(m=>{var u;if(Ue.isIdentifier(m.name)){const p=m.name.text,h=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:p,code:h,sha:qt(t,p,h),entityType:y?"component":"variable",isDefault:c})}})}else if(Ue.isExportAssignment(o)){const c=o.getText(s);a.push({name:"default",code:c,sha:qt(t,"default",c),entityType:"unknown",isDefault:!0})}else if(Ue.isExportDeclaration(o)&&o.exportClause&&Ue.isNamedExports(o.exportClause)){const c=o.getText(s);for(const m of o.exportClause.elements){const u=m.name.text;a.push({name:u,code:c,sha:qt(t,u,c),entityType:"unknown",isDefault:!1})}}Ue.forEachChild(o,r)};const s=Ue.createSourceFile(t,e,Ue.ScriptTarget.Latest,!0),a=[];return r(s),a}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function Bn(e){if(!Ue.canHaveModifiers(e))return!1;const t=Ue.getModifiers(e);return t?t.some(r=>r.kind===Ue.SyntaxKind.ExportKeyword):!1}function Ts(e){if(!Ue.canHaveModifiers(e))return!1;const t=Ue.getModifiers(e);return t?t.some(r=>r.kind===Ue.SyntaxKind.DefaultKeyword):!1}function qt(e,t,r){const s=rr.createHash("sha256");return s.update(`${e}:${t}:${r}`),s.digest("hex").substring(0,40)}function fm(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))))??[],l=[];for(const u of s)if(u.key&&u.value!==void 0){const p=String(u.value).replace(/'/g,"'\\''");l.push(`${u.key}='${p}'`)}if(o.env)for(const[u,p]of Object.entries(o.env)){const f=String(p).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");l.push(`${u}='${f}'`)}const c=l.length>0?l.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${c}sh -c "${i[1]}"`:`${c}${o.command} ${i.join(" ")}`}function gm(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=F.normalize(e),s=[...t].sort((a,o)=>{var i,l;return(((i=o.path)==null?void 0:i.length)??0)-(((l=a.path)==null?void 0:l.length)??0)});for(const a of s){const o=F.normalize(a.path??".");if(o==="."||r.startsWith(o+F.sep)||r===o)return a}return t[0]}function ym(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=gm(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const l=fm({webapp:i,port:a,environmentVariables:s,packageManager:o});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??o,startCommand:l,url:`http://localhost:${a}/static/codeyam-sample`}}function kn(e,t,r=[]){const s=Array.isArray(t)?t:[t];return a=>a.columns(s).doUpdateSet(o=>{const i=Object.keys(e).filter(l=>l!==t&&!r.includes(l));return Object.fromEntries(i.map(l=>[l,o.ref(`excluded.${l}`)]))})}async function xm(e){if(e.length===0)return[];const t=je(),r=e.map(um);try{return(await t.insertInto("branches").values(r).onConflict(kn(r[0],"id",["created_at"])).returningAll().execute()).map(ln)}catch(s){return Me("CodeYam Error: Database error upserting branches",s,{branchCount:e.length,branchIds:e.map(a=>a.id)}),[]}}function bm(e){const{jsonObjectFrom:t}=un();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 wm({ids:e,analysisId:t}){const r=je();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 vm(...e){try{const t=rr.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 $s(e,t){return t.map(r=>Nm(e,r))}function Nm(e,t){return rt` ${rt.ref(e)}.${rt.ref(t)}`.as(t)}function Cm(e,t,r){return t.map(s=>Sm(e,s,r))}function Sm(e,t,r){return rt` ${rt.ref(e)}.${rt.ref(t)}`.as(`_cy_${r}:${t}`)}function km(e,...t){const r={};for(const[s,a]of Object.entries(e)){const o=s.match(/^_cy_(.+?):(.+)$/);if(o){const[,i,l]=o;if(t.includes(i)){r[i]||(r[i]={}),r[i][l]=a;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${s}'`);continue}r[s]=a}return r}const Em=50;function _m(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 Mo({projectId:e,ids:t,fileIds:r,entityName:s,entityShas:a,commitIds:o,branchCommitSha:i,limit:l,excludeMetadata:c}){const m=je(),{jsonObjectFrom:u,jsonArrayFrom:p}=un();let h=c?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&&(h=h.where("project_id","=",e)),t){if(t.length===0)return null;h=h.where("id","in",t)}if(r){if(r.length===0)return null;h=h.where("file_id","in",r)}if(o){if(o.length===0)return null;h=h.where("commit_id","in",o)}return s&&(h=h.where("entity_name","=",s)),a&&(h=h.where("entity_sha","in",a)),i&&(h=h.where("branch_commit_sha","=",i)),l&&(h=h.limit(l)),c?m.with("filtered_analyses",()=>h).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[p(f.selectFrom("scenarios").select($s("scenarios",$r)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),p(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):m.with("filtered_analyses",()=>h).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select($s("entities",tl)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),p(f.selectFrom("scenarios").select($s("scenarios",$r)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),p(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function zt(e){const{ids:t,fileIds:r,entityShas:s,commitIds:a}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:s,key:"entityShas"},commit_id:{arr:a,key:"commitIds"}}).find(([c,{arr:m}])=>(m==null?void 0:m.length)>0);let l=[];if(i){const[c,{arr:m,key:u}]=i,p=_m(m,Em),h=[];for(let f=0;f<p.length;f++){const y=p[f],x=await Mo({...e,[u]:y}).execute();x&&h.push(...x)}l=h}else{const m=await Mo(e).execute();if(!m||m.length===0)return Me("CodeYam: No analyses found",null,e),null;l=m}return l.length===0?null:l.map(At)}catch(o){return Me("CodeYam Error: Database error in loadAnalyses",o,e),null}}function Am(e,t){const{jsonArrayFrom:r,jsonObjectFrom:s}=un();let a=e.selectFrom("analysis_branches").select(_u).select(o=>s(o.selectFrom("branches").select(Xi).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:l,includeFile:c,includeProject:m,includeCommitAndBranch:u,includeScenarios:p,includeBranches:h}){const f=je(),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):l?g=g.where("analyzed_tree_sha","=",l):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:b}=un();g=g.select(C=>{const P=[];return P.push(x(C.selectFrom("entities").select(tl).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),c&&P.push(x(C.selectFrom("files").select(Hu).whereRef("files.id","=","analyses.file_id")).as("file")),m&&P.push(x(C.selectFrom("projects").select(Cu).whereRef("projects.id","=","analyses.project_id")).as("project")),p&&P.push(b(C.selectFrom("scenarios").select($r).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),h&&P.push(Am(C,N=>N.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&P.push(x(C.selectFrom("commits").select(el).select(N=>bm(N).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),P});const w=await g.executeTakeFirst(),v=Date.now()-y;if(!w)return Me("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:c,includeProject:m,includeCommitAndBranch:u,includeScenarios:p,includeBranches:h}),null;if(v>100&&u){const C=w.commit,P=C!=null&&C.files?JSON.stringify(C.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${v}ms (files: ${Math.round(P/1024)}KB)`,{id:w.id,entityName:w.entity_name})}return At(w)}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:l,includeFile:c,includeProject:m,includeCommitAndBranch:u,includeScenarios:p,includeBranches:h}),null}}async function Ma({projectId:e,ids:t,names:r,includeInactive:s}){const a=je();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(ln)}catch(o){return Me("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:s}),[]}}async function Pm({projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}){const o=je();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(a,m=>m.select(Cm("branches",Xi,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),s!==void 0&&(i=i.where("commit_branches.active","=",s));const l=await i.execute();return!l||l.length===0?null:l.map(m=>km(m,"branch")).map(ja)}catch(i){return Me("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}),null}}async function jm(e){if(e.length===0)return new Map;const t=je();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 Mm(e){if(e.length===0)return new Map;const t=je(),{jsonObjectFrom:r,jsonArrayFrom:s}=un();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($r).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),o=new Map;return a.forEach(i=>{const l=o.get(i.commit_id)||[];l.push(i),o.set(i.commit_id,l)}),o}catch(a){return Me("CodeYam Error: Loading analyses for commits",a,{commitIds:e}),new Map}}async function Tm(e){if(e.length===0)return new Map;const t=je();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 Rr({projectId:e,branchId:t,ids:r,shas:s,fileNames:a,limit:o=10,skipRelations:i=!1}){if(!e&&!r)throw new Error("Must provide projectId or ids");const l=je(),{jsonObjectFrom:c}=un(),m=Date.now();try{let u;if(i){const w=Iu.map(v=>`commits.${v}`);u=l.selectFrom("commits").select(w)}else u=l.selectFrom("commits").selectAll("commits").select(w=>[c(w.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",w.ref("commits.author_github_username"))).as("author")]);if(e&&(u=u.where("project_id","=",e)),r){if(r.length===0)return[];u=u.where("id","in",r)}if(s){if(s.length===0)return[];u=u.where("sha","in",s)}if(a&&a.length>0){const w=rt.join(a.map(v=>rt`${v}`),rt`, `);u=u.where(rt`
|
|
24
|
-
EXISTS (
|
|
25
|
-
SELECT 1
|
|
26
|
-
FROM json_each(${rt.ref("commits.files")}) AS f
|
|
27
|
-
WHERE json_extract(f.value, '$.fileName') IN (${w})
|
|
28
|
-
)
|
|
29
|
-
`)}t&&(u=u.where("branch_id","=",t));const p=await u.orderBy("committed_at","desc").limit(o).execute(),h=Date.now()-m;if(!p||p.length===0)return[];if(h>100){const w=p.reduce((v,C)=>v+(C.files?JSON.stringify(C.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${h}ms (${p.length} commits, totalFiles: ${Math.round(w/1024)}KB)`)}if(i)return p.map(v=>({...v,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(on);const f=p.map(w=>w.id),[y,g,x]=await Promise.all([jm(f),Mm(f),Tm(f)]);return p.map(w=>{const v=w.branch_id?y.get(w.branch_id):void 0,C=w.merged_branch_id?y.get(w.merged_branch_id):void 0,P=g.get(w.id)||[],N=x.get(w.id)||[];return{...w,branch:v,mergedBranch:C,analyses:P,entities:N}}).map(on)}catch(u){return Me("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:t,ids:r,shas:s,limit:o}),[]}}async function st({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:o,excludeMetadata:i}){if(r&&r.length==0||s&&s.length==0||a&&a.length==0||o&&o.length==0)return[];if(o&&o.length>50){const c=[];for(let m=0;m<o.length;m+=50){const u=o.slice(m,m+50),p=await st({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:u,excludeMetadata:i});p&&c.push(...p)}return c}const l=je();try{const u=await(i?l.selectFrom("entities").select(["entities.project_id","entities.file_id","entities.commit_id","entities.name","entities.sha","entities.entity_type","entities.file_path","entities.description","entities.documentation","entities.quality","entities.created_at","entities.updated_at"]):l.selectFrom("entities").selectAll("entities")).$if(!!t,p=>p.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,p=>p.where("entities.project_id","=",e)).$if(!!o,p=>p.where("entities.sha","in",o)).$if(!!s,p=>p.where("entities.file_path","in",s)).$if(!!a,p=>p.where("entities.name","in",a)).$if(!!r,p=>p.where("entities.file_id","in",r)).execute();return!u||u.length===0?null:u.map(sr)}catch(c){return console.log("Load Entities: Error occurred",c,{projectId:e,fileIds:r,filePaths:s,shas:o}),null}}function $m(e,t){const{jsonArrayFrom:r}=un();let s=e.selectFrom("entity_branches").select(Bu);return t&&(s=t(s)),r(s)}async function sl({projectId:e,sha:t}){const r=je();try{const s=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(a=>$m(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?sr(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 Is=1e3;async function al({projectId:e,filePaths:t,fileIds:r,fileNames:s}){if(t&&t.length>50){const l=[];for(let c=0;c<t.length;c+=50){const m=t.slice(c,c+50),u=await al({projectId:e,filePaths:m,fileIds:r,fileNames:s});u&&l.push(...u)}return l}const a=je(),o=[];let i=0;try{for(;;){let l=a.selectFrom("files").selectAll().where("project_id","=",e).limit(Is).offset(i);if(t){if(t.length===0)return[];l=l.where("path","in",t)}if(r){if(r.length===0)return[];l=l.where("id","in",r)}if(s){if(s.length===0)return[];l=l.where("name","in",s)}const c=await l.execute();if(!c||c.length===0||(o.push(...c),c.length<Is))break;i+=Is}return o==null?void 0:o.map(Pa)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function Ta({id:e,slug:t,withBranches:r,withFiles:s,silent:a}){try{let i=je().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(t)i=i.where("slug","=",t);else throw new Error("Either id or slug must be provided");const l=await i.executeTakeFirst();if(!l)return null;const c=Qr(l);return s&&(c.files=await al({projectId:c.id})),r&&(c.branches=await Ma({projectId:c.id,includeInactive:!1})),c}catch{return null}}function Dr(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]=Dr(o,a):a!==void 0&&(r[s]=a)}return r}async function Lt({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:s,archiveCurrentRun:a,updateCallback:o}){for(let c=0;c<=4;c++)try{return await je().transaction().execute(async m=>{const u=await m.selectFrom("commits").select(["id","metadata"]).$if(!!e,f=>f.where("id","=",e)).$if(!!t,f=>f.where("sha","=",t)).executeTakeFirst();if(!u)return Me(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const p=u.metadata||{};if(s)s.lastUpdatedAt??(s.lastUpdatedAt=new Date().toISOString()),r=Dr(r??{},{currentRun:s});else if(!r&&!o)return p;const h=r?Dr(p,r):p;if(a&&h.currentRun){const f={...h.currentRun,archivedAt:new Date().toISOString()};h.historicalRuns=[...h.historicalRuns||[],f]}o&&await o(h);try{return await m.updateTable("commits").set({metadata:JSON.stringify(h)}).where("id","=",u.id).returning(["id"]).executeTakeFirst()?h:(Me(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),p)}catch(f){return Me(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,f),p}})}catch(m){const u=m instanceof Error&&m.message.includes("database is locked");if(u&&c<4){const p=250*Math.pow(2,c);await new Promise(h=>setTimeout(h,p));continue}return Me(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}${u?` after ${c+1} attempts`:""}`,m),null}return null}async function ol(e,t,r="analysis"){try{return await je().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 En(e,t,r="capture"){for(let o=0;o<=4;o++)try{return await je().transaction().execute(async i=>{const l=await i.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!l)return Me(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const c=At(l);return t(c.status,c),await i.updateTable("analyses").set({status:JSON.stringify(c.status)}).where("id","=",e).returningAll().executeTakeFirst()?c.status:(Me(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(i){const l=i instanceof Error&&i.message.includes("database is locked");if(l&&o<4){const c=250*Math.pow(2,o);await new Promise(m=>setTimeout(m,c));continue}return Me(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})${l?` after ${o+1} attempts`:""}`,i,{analysisId:e,source:r}),null}return null}async function vn({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:s}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await je().transaction().execute(async a=>{const o=await a.selectFrom("projects").selectAll().$if(!!e,c=>c.where("id","=",e)).$if(!!t,c=>c.where("slug","=",t)).executeTakeFirst();if(!o)return Me(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!s)return i;const l=r?Dr(i,r):i;s&&await s(l,Qr(o));try{return await a.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",o.id).returningAll().executeTakeFirst()?l:(Me(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(c){return Me(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,c),null}})}catch(a){return Me(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,a),null}}const Im=()=>crypto.randomUUID();function Rm(e){const{id:t,projectId:r,analysisId:s,previousVersionId:a,analysis:o,metadata:i,data:l,...c}=e;return delete c.userScenarios,delete c.comments,"created_at"in c&&delete c.created_at,{...c,id:t??Im(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:s,previous_version_id:a}}async function Dm(e){if(e.length===0)return[];const t=je(),r=e.map(Rm);try{return(await t.insertInto("scenarios").values(r).onConflict(kn(r[0],"id",["created_at"])).returningAll().execute()).map(Zi)}catch(s){return Me("CodeYam Error: Database error upserting scenarios",s,{scenarioCount:e.length}),null}}const Om=()=>crypto.randomUUID();function Lm(e){const{id:t,commitId:r,branchId:s,...a}=e;return delete a.commit,delete a.branch,{...a,id:t??Om(),commit_id:r,branch_id:s}}async function To(e){if(e.length===0)return[];const t=je(),r=e.map(Lm);try{return(await t.insertInto("commit_branches").values(r).onConflict(kn(r[0],"id",["created_at"])).returningAll().execute()).map(ja)}catch(s){return Me("CodeYam Error: Database error upserting commit branches",s,{commitBranchCount:e.length,commitBranchIds:e.map(a=>a.id)}),[]}}async function Fm(e,t){const r=je(),s={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(s).onConflict(kn(s,"username",[])).returningAll().executeTakeFirst()||null}catch(a){return Me("CodeYam Error: Error upserting github user",a,{username:e,avatarUrl:t}),null}}const zm=()=>crypto.randomUUID();function Bm(e,t){const{id:r,projectId:s,branchId:a,mergedBranchId:o,aiMessage:i,htmlUrl:l,analyzedAt:c,committedAt:m,author:u,metadata:p,files:h,...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??zm(),project_id:s??String(t),metadata:p?JSON.stringify(p):void 0,files:h?JSON.stringify(h):void 0,branch_id:a,merged_branch_id:o,author_github_username:u==null?void 0:u.username,html_url:l,ai_message:i,analyzed_at:c,committed_at:m}}async function Ym({projectId:e,commits:t}){const r=je();try{const s=t.reduce((i,l)=>{const{author:c}=l;return c!=null&&c.username&&(c!=null&&c.avatarUrl)&&(i[c.username]=c.avatarUrl),i},{});for(const i in s)await Fm(i,s[i]);const a=t.map(i=>Bm(i,e));return(await r.insertInto("commits").values(a).onConflict(kn(a[0],"id",["created_at"])).returningAll().execute()).map(on)}catch(s){return Me("CodeYam Error: Error saving commits",s,{projectId:e,commitCount:t.length,commitIds:t.map(a=>a.id).filter(Boolean)}),[]}}const Um=()=>crypto.randomUUID();function Wm(e){const{id:t,files:r,branches:s,team:a,analyzedAt:o,contentChangedAt:i,createdAt:l,updatedAt:c,metadata:m,...u}=e;return{...u,id:t??Um(),analyzed_at:o||null,content_changed_at:i||null,created_at:l||new Date().toISOString(),updated_at:c||null,metadata:m?JSON.stringify(m):null,github_token:null,configuration:null,team_id:null}}async function Hm(e){try{if(e.length===0)return null;const t=je(),r=e.map(o=>Wm(o)),s=await t.insertInto("projects").values(r).onConflict(kn(r[0],"id",["created_at"])).returningAll().execute(),a=s==null?void 0:s[0];return a?Qr(a):null}catch(t){return console.log("Error saving project",t),null}}const Or=F.join(wa.homedir(),".codeyam","secrets.json"),Lr=F.join(process.cwd(),".codeyam","secrets.json");async function Ut(){let e={};try{if(K.existsSync(Lr)){const o=await we.readFile(Lr,"utf8");e=JSON.parse(o)}}catch{console.warn(Tr.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(K.existsSync(Or)){const o=await we.readFile(Or,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(Tr.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 Jm(e,t=!0){const r=t?Or:Lr,s=F.dirname(r);await we.mkdir(s,{recursive:!0}),await we.writeFile(r,JSON.stringify(e,null,2)),await we.chmod(r,384)}function Vm(e=!0){return e?Or:Lr}async function $o(){const e=await Ut(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function Gm(e){console.log(),console.log(Tr.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const s=await zd({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 Km(e=!0){const t=await $o();if(t.isValid)return t.secrets;const r=await Gm(t.missing),a={...await Ut(),...r};await Jm(a,e);const o=Vm(e);return console.log(Tr.green(`✓ Configuration saved to ${o}`)),(await $o()).secrets}function qm(e){const t=F.resolve(e),r=F.parse(t).root;return t===r||t===F.resolve(wa.homedir())}function il(e=process.cwd()){let t=F.resolve(e);const r=F.parse(t).root;for(;t!==r;){if(qm(t))return null;const s=F.join(t,".codeyam","config.json");if(K.existsSync(s))return t;t=F.dirname(t)}return null}let ll=il();function he(){return ll}function Qm(e){ll=e}function cl(e){const t={...e};for(const r in e)if(r.includes(".")){const s=r.replace(/\./g,"");t[s]=e[r]}return t}const Zm={"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>`};cl(Zm);const Xm={"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>`};cl(Xm);function Vn(e,t,r=new WeakSet){if(!t)return e;if(!e)return t;try{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference detected during deep merge");r.add(t)}if(Array.isArray(t)){const a=Array.isArray(e)?e:[],o=[];for(let i=0;i<t.length;i++){const l=t[i];l&&typeof l=="object"&&!Array.isArray(l)||Array.isArray(l)?o[i]=Vn(a[i],l,r):o[i]=l}return o}const s={...e};for(const a in t)if(t[a]===null)s[a]=null;else if(Array.isArray(t[a])){const o=Array.isArray(e[a])?e[a]:[];s[a]=[];for(let i=0;i<t[a].length;i++){const l=t[a][i];typeof l=="object"&&l!==null?s[a][i]=Vn(o[i],l,r):s[a][i]=l}}else typeof t[a]=="object"&&t[a]!==null?s[a]=Vn(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 ep({projectId:e,commit:t,branch:r}){var l,c,m,u,p,h,f;let s;const a={commitId:t.id,branchId:r.id,active:!0},o=await Pm({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){s=(l=o.sort((g,x)=>{var b,w,v,C;return(((w=(b=g.branch.metadata)==null?void 0:b.permanent)==null?void 0:w.order)??999)-(((C=(v=x.branch.metadata)==null?void 0:v.permanent)==null?void 0:C.order)??999)})[0])==null?void 0:l.branch,s&&((m=(c=r.metadata)==null?void 0:c.permanent)==null?void 0:m.order)!==void 0&&(((p=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:p.order)<=((f=(h=s.metadata)==null?void 0:h.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 To(y.map(g=>({...g,active:g.branchId===s.id})))}(o==null?void 0:o.find(y=>y.branchId===a.branchId))||await To([a])}let Io=!1;function Wt(){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 Z.join(e,".codeyam","db.sqlite3")}async function ze(){if(!Io){Io=!0;const t=he();t&&await np(t)}const e=await Km();process.env.SQLITE_PATH=Wt(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function BC(){try{return await ze(),await Ta({slug:"__test_connection__",silent:!0}),!0}catch(e){return console.error("Database connection test failed:",e),!1}}async function Re(e){await ze();const t=await Ta({slug:e,silent:!0});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await Ma({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 YC(e){await ze();const t=await Ta({slug:e.slug,silent:!0});if(t)return{project:t,created:!1};const r={id:va(),name:e.slug,slug:e.slug,path:`local:${process.cwd()}`,metadata:{packageManager:e.packageManager,unapprovedPaths:e.unapprovedPaths,webapps:e.webapps}};try{return{project:await Hm([r]),created:!0}}catch(s){throw new Error(`Failed to create project: ${s.message}`)}}async function UC(e){await ze();const t=await Ma({projectId:e.id,names:["_local"]});if(t&&t.length>0)return{branch:t[0],created:!1};const r={projectId:e.id,name:"_local",ref:"_local",primary:!0,activeAt:new Date().toISOString(),contentChangedAt:new Date().toISOString(),metadata:{contributors:[{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"}],commits:{total:0,last7Days:[]},timeline:[{title:"Local branch created",date:new Date().toISOString(),authors:[{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"}],sha:"local-init"}]}},s=await xm([r]);if(!s||s.length===0)throw new Error("Failed to create _local branch");return{branch:s[0],created:!0}}async function tp(e,t,r){await ze();const s=he(),a=vm(`${e.slug}-local-${Date.now()}-${Math.random()}`),o=r.map(c=>{let m="";if(s)try{if(m=Ee(`git diff HEAD -- "${c}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!m)try{const u=Ee(`cat "${c}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const p=u.split(`
|
|
30
|
-
`);m=`@@ -0,0 +1,${p.length} @@
|
|
31
|
-
${p.map(h=>`+${h}`).join(`
|
|
32
|
-
`)}`}}catch{}}catch{}return{fileName:c,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()}},l=await Ym({projectId:e.id,commits:[i]});if(!l||l.length===0)throw new Error("Failed to create fake commit");return await ep({projectId:e.id,commit:l[0],branch:t}),l[0]}async function np(e){const t=Z.join(e,".codeyam","db.sqlite3"),r=Z.join(e,".codeyam","config.json");if(K.existsSync(t)||!K.existsSync(r))return!1;const{default:s}=await import("./init-DbChSUQP.js");return await s.handler({force:!0,autoInit:!0,$0:"",_:[]}),!0}async function mn(){await ze();const e=await st({excludeMetadata:!0});if(!e||e.length===0)return[];const t=new Map;for(const c of e){const m=`${c.name}::${c.filePath}`,u=t.get(m);(!u||c.createdAt&&u.createdAt&&c.createdAt>u.createdAt)&&t.set(m,c)}const r=[...t.values()],s=e.map(c=>c.sha),a=await zt({entityShas:s,excludeMetadata:!0}),o=new Map;if(a)for(const c of a)o.has(c.entitySha)||o.set(c.entitySha,[]),o.get(c.entitySha).push(c);const i=new Map;for(const c of e){const m=`${c.name}::${c.filePath}`,u=i.get(m)||[];u.push(c.sha),i.set(m,u)}return r.map(c=>{const m=o.get(c.sha)||[];if(m.length>0)return{...c,analyses:m};const u=`${c.name}::${c.filePath}`,p=i.get(u)||[];for(const h of p){if(h===c.sha)continue;const f=o.get(h);if(f&&f.length>0)return{...c,analyses:f}}return{...c,analyses:[]}})}async function Xr(e,t){await ze();const r=await zt({entityShas:[e],limit:1});if(r&&r.length>0&&t){const s=await sl({projectId:r[0].projectId,sha:e});if(s)for(const a of r)a.entity=s}return r||[]}async function es(e){if(await ze(),e.name&&e.projectId){const r=await zt({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const s=r.filter(o=>{const i=o.scenarios&&o.scenarios.length>0,l=!e.filePath||o.filePath===e.filePath;return i&&l});if(s.length>0)return s.sort((o,i)=>{const l=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),s[0];const a=r.filter(o=>o.scenarios&&o.scenarios.length>0);if(a.length>0)return a.sort((o,i)=>{const l=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),a[0]}}const t=await zt({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function dl(e){await ze();const t=await zt({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function dn(e){await ze();const t=await Ie();if(!t)return null;const{project:r}=await Re(t);return await sl({projectId:r.id,sha:e})}async function ul(e){var s,a,o,i,l,c,m,u;await ze();const t=[],r=[];if((s=e.metadata)!=null&&s.importedExports&&e.metadata.importedExports.length>0){const p=e.metadata.importedExports;for(const h of p){if(!h.filePath||!h.name)continue;const f=h.resolvedFilePath??h.filePath,y=h.resolvedName??h.name;let g=await st({projectId:e.projectId,filePaths:[f],names:[y]});if((!g||g.length===0)&&h.resolvedIsDefault&&(g=await st({projectId:e.projectId,filePaths:[f],names:["default"]})),g&&g.length>0){const x=g[0],b=await zt({entityShas:[x.sha],limit:1});let w,v,C;if(b&&b.length>0&&b[0].scenarios){const P=b[0],N=P.scenarios||[],S=N.length,k=N.find(j=>{var T,E;return(E=(T=j.metadata)==null?void 0:T.screenshotPaths)==null?void 0:E[0]});k&&(w=(o=(a=k.metadata)==null?void 0:a.screenshotPaths)==null?void 0:o[0],v=k.name),C={status:((i=x.metadata)==null?void 0:i.previousVersionWithAnalyses)||P.entitySha!==x.sha?"out_of_date":"up_to_date",scenarioCount:S,timestamp:P.createdAt?new Date(P.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else C={status:"not_analyzed"};t.push({...x,screenshotPath:w,scenarioName:v,analysisStatus:C})}}}if((l=e.metadata)!=null&&l.importedBy){const p=[];for(const h in e.metadata.importedBy)for(const f in e.metadata.importedBy[h]){const y=e.metadata.importedBy[h][f];y.shas&&p.push(...y.shas)}if(p.length>0){const h=await st({projectId:e.projectId,shas:p});if(h)for(const f of h){const y=await zt({entityShas:[f.sha],limit:1});let g,x,b;if(y&&y.length>0&&y[0].scenarios){const w=y[0],v=w.scenarios||[],C=v.length,P=v.find(S=>{var k,_;return(_=(k=S.metadata)==null?void 0:k.screenshotPaths)==null?void 0:_[0]});P&&(g=(m=(c=P.metadata)==null?void 0:c.screenshotPaths)==null?void 0:m[0],x=P.name),b={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||w.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:C,timestamp:w.createdAt?new Date(w.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else b={status:"not_analyzed"};r.push({...f,screenshotPath:g,scenarioName:x,analysisStatus:b})}}}return{importedEntities:t,importingEntities:r}}async function Ie(){try{const e=he();if(!e)return null;const t=Z.join(e,".codeyam","config.json");return JSON.parse(await Ne.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function _n(){await ze();try{const e=await Ie();if(!e)return null;const{project:t,branch:r}=await Re(e),s=await Rr({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 ts(){try{const e=he();if(!e)return null;const t=Z.join(e,".codeyam","config.json");return JSON.parse(await Ne.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function ml(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=Z.join(t,e.filePath);return await Ne.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function pl(e){try{const t=he();if(!t||!e.filePath)return!1;const r=Z.join(t,e.filePath),a=(await Ne.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 hl(e){if(await ze(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await st({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),s=await zt({entityShas:r}),a=new Map;if(s)for(const i of s)a.has(i.entitySha)||a.set(i.entitySha,[]),a.get(i.entitySha).push(i);for(const[i,l]of a.entries())l.sort((c,m)=>{const u=new Date(c.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,l)=>{var u,p;const c=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",m=((p=l.analyses[0])==null?void 0:p.createdAt)||l.createdAt||"";return new Date(m).getTime()-new Date(c).getTime()}),o}async function fl(e){try{const t=he();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=Z.join(t,".codeyam","config.json"),s=await Ne.readFile(r,"utf8"),a=JSON.parse(s),o={...a,...e},i=JSON.stringify(o,null,2);if(await Ne.writeFile(r,i,"utf8"),a.projectSlug){const l={};e.universalMocks!==void 0&&(l.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(l.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(l.webapps=e.webapps),await vn({projectSlug:a.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const rp=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:mn,getAnalysesForEntity:Xr,getAnalysisForExactEntitySha:dl,getCurrentCommit:_n,getEntityBySha:dn,getEntityCodeFromFilesystem:ml,getEntityHistory:hl,getLatestAnalysisForEntity:es,getProjectConfig:ts,getProjectSlug:Ie,getRelatedEntities:ul,hasFileBeenModifiedSinceEntity:pl,requireBranchAndProject:Re,updateProjectConfig:fl},Symbol.toStringTag,{value:"Module"})),gl="secrets.json";function yl(e){return Z.join(e,".codeyam",gl)}function xl(){return Z.join(Qs.homedir(),".codeyam",gl)}async function ns(e){let t={};try{const r=xl(),s=await Ne.readFile(r,"utf-8");t=JSON.parse(s)}catch{}try{const r=yl(e),s=await Ne.readFile(r,"utf-8"),a=JSON.parse(s);t={...t,...a}}catch{}return t}async function sp(e,t,r=!0){const s=r?xl():yl(e),a=Z.dirname(s);await Ne.mkdir(a,{recursive:!0}),await Ne.writeFile(s,JSON.stringify(t,null,2)+`
|
|
33
|
-
`,"utf-8")}async function ap(e){const t=await ns(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 op=3;let Yn=0;async function ur(e){if(!e||e.length===0)return[];if(Yn>=op)return console.warn(`[Loader] Circuit breaker open (${Yn} 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,Yn++,console.warn(`[Loader] Entity fetch timeout after ${t}ms for ${e.length} entities`),r([]))},t);st({shas:e,excludeMetadata:!0}).then(o=>{s||(s=!0,clearTimeout(a),Yn=0,r(o||[]))}).catch(()=>{s||(s=!0,clearTimeout(a),Yn++,r([]))})})}function ip({sourcePath:e,destinationPath:t,excludes:r,silent:s}){if(process.platform!=="darwin")return!1;if(Ot(t))try{if(Td(t).length>0)return!1;As(t,{recursive:!0})}catch{return!1}try{Ee(`cp -c -R "${e}" "${t}"`,{stdio:"pipe",timeout:3e5});for(const a of r)if(a.includes("*"))try{Ee(`rm -rf "${_o(t,a)}"`,{stdio:"pipe",shell:"/bin/sh"})}catch{}else{const o=_o(t,a);Ot(o)&&As(o,{recursive:!0,force:!0})}return s||console.log(`Directory cloned (APFS CoW) from ${e} to ${t}`),!0}catch{if(Ot(t))try{As(t,{recursive:!0})}catch{}return!1}}async function lp({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:s=!1,silent:a=!1,extraArgs:o=[]}){const i=Date.now();if(!s&&o.length===0&&ip({sourcePath:e,destinationPath:t,excludes:r,silent:a})){if(!a){const c=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${c}s]`)}return}return new Promise((l,c)=>{const m=e.endsWith("/")?e:`${e}/`,u=t.endsWith("/")?t:`${t}/`,p=["-a","--no-specials"];s||p.push("--delete","--force"),p.push(...o);for(const f of r)p.push(`--exclude=${f}`);p.push(m,u);const h=Et("rsync",p);h.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]`)}l()}else console.error(`CodeYam Error: rsync failed with code: ${f}`,JSON.stringify({rsyncArgs:p},null,2)),c(new Error(`rsync failed with exit code ${f}`))}),h.on("error",f=>{a||console.log("Error occurred:",f),c(f)})})}const cp=Ca(Na);async function dp(e){return new Promise(t=>setTimeout(t,e))}function up(e){try{return process.kill(e,0),!0}catch{return!1}}async function bl(e){try{const{stdout:t}=await cp(`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 bl(a);s.push(...o)}return s}catch{return[]}}function Ro(e,t,r){try{process.kill(e,t)}catch(s){r==null||r(`Error sending ${t} to process ${e}: ${s}`)}}async function mp(e,t,r){const s=await bl(e);for(const a of s.reverse())await Ro(a,t,r);await Ro(e,t,r)}async function Xn(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 mp(e,o,t);for(let l=0;l<i;l++)if(await dp(1e3),s+=1e3,!await up(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 pp(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:eu(),createdAt:t}}Ud.config({quiet:!0});var wl=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(wl||{});class hp extends Wd{constructor(){super(...arguments),this.processes=new Map}register(t){const r=Hd(),{process:s,type:a,name:o,metadata:i,parentId:l}=t,c={id:r,type:a,name:o,pid:s.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:l,children:[]};if(this.processes.set(r,{info:c,process:s}),l){const p=this.processes.get(l);p&&(p.info.children=p.info.children||[],p.info.children.push(r))}const m=(p,h)=>{this.handleProcessExit(r,p,h)},u=p=>{this.handleProcessError(r,p)};return s.on("exit",m),s.on("error",u),s.__cleanup=()=>{s.removeListener("exit",m),s.removeListener("error",u)},this.emit("processStarted",c),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const s=this.processes.get(t);if(!s)throw new Error(`Process not found: ${t}`);const{info:a,process:o}=s;if(a.state==="completed"||a.state==="failed"||a.state==="killed")return;if(r.shutdownChildren&&a.children&&a.children.length>0&&await Promise.all(a.children.map(l=>this.shutdown(l,r))),o.pid)try{await Xn(o.pid,l=>console.log(`[Process ${t}] ${l}`))}catch(l){console.warn(`Error killing process ${t}:`,l)}await new Promise(l=>setTimeout(l,100)),a.state==="running"&&(a.state="killed",a.endedAt=Date.now());const i=o.__cleanup;i&&i()}async shutdownByType(t,r={}){const s=this.listByType(t);await Promise.all(s.map(a=>this.shutdown(a.id,r)))}async shutdownAll(t={}){const r=this.listAll();await Promise.all(r.map(s=>this.shutdown(s.id,t)))}cleanupCompleted(t={}){const{retentionMs:r=6e4}=t,s=Date.now();for(const[a,o]of this.processes.entries()){const{info:i}=o;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&s-i.endedAt>r){const l=o.process.__cleanup;l&&l(),this.processes.delete(a)}}}handleProcessExit(t,r,s){const a=this.processes.get(t);if(!a)return;const{info:o}=a;o.endedAt=Date.now(),o.exitCode=r,o.signal=s,r===0?o.state="completed":s?o.state="killed":o.state="failed",this.emit("processExited",o)}handleProcessError(t,r){const s=this.processes.get(t);if(!s)return;const{info:a}=s;a.endedAt=Date.now(),a.state="failed",a.metadata={...a.metadata,error:r.message},this.emit("processExited",a)}}let Rs=null;function fp(){return Rs||(Rs=new hp),Rs}const gp={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function yp({command:e,args:t,workingDir:r,outputOptions:s=gp,processName:a,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${a}`},l=Et(e,t,{cwd:r,env:i});return fp().register({process:l,type:wl.Other,name:a,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const p=f=>{const y=Z.join(r,"log.txt");K.appendFile(y,f,g=>{g&&console.log("Error writing to log file:",g)})},h=(f,y="")=>{const g=new Date().toLocaleString();return f.split(`
|
|
35
|
-
`).map(b=>b.trim()?`[${g}]${y} ${b}`:b).join(`
|
|
36
|
-
`)};l.stdout.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=h(y);s.stdoutToConsole&&console.log(g),s.stdoutToFile&&p(g+`
|
|
37
|
-
`),s.stdoutCallback&&s.stdoutCallback(y)}),l.stderr.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=h(y,"<STDERR>");s.stderrToConsole&&console.error(g),s.stderrToFile&&p(g+`
|
|
38
|
-
`),s.stderrCallback&&s.stderrCallback(y)}),l.on("exit",function(f){u(f)})}),process:l}}function xp(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 bp({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:s}){const a=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
|
|
39
|
-
`);K.writeFileSync(`${e}/.env`,a);const o=xp(r);return yp({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:s,processName:"analyzer",env:t})}const wp="/tmp/codeyam/local-dev";function vl(e){return F.join(wp,e)}function Nl(e){return F.join(vl(e),"codeyam")}function gt(e){return F.join(vl(e),"project")}function rs(e){return F.join(Nl(e),"log.txt")}const vp=[".sync-metadata.json","__codeyamMocks__"];async function Np(e,t={}){const{port:r,silent:s=!0}=t,a=gt(e);if(r)try{Ee(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}try{Ee(`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 Cp(e,t={}){const{killProcesses:r=!0,port:s,silent:a=!0}=t,o=gt(e),i=[],l=[];if(!K.existsSync(o))return{removed:i,errors:l};r&&await Np(e,{port:s,silent:a});for(const c of vp){const m=F.join(o,c);if(K.existsSync(m))try{(await we.stat(m)).isDirectory()?await we.rm(m,{recursive:!0,force:!0}):await we.unlink(m),i.push(c)}catch(u){l.push(`${c}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:l}}const Sp=F.dirname(Vr(import.meta.url));function kp(e){let t=e;for(;t!==F.dirname(t);){const r=F.join(t,"package.json");if(K.existsSync(r))try{if(JSON.parse(K.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=F.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function ss(){const e=kp(Sp);return F.join(e,"analyzer-template")}function An(e){return Nl(e)}function Ep(){const e=ss();return K.existsSync(F.join(e,".finalized"))}async function Do(e){const t=ss(),r=An(e);if(!K.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await we.mkdir(F.dirname(r),{recursive:!0}),await lp({sourcePath:t,destinationPath:r,silent:!0}),K.existsSync(F.join(r,"dist"))||Ee("npm install --include=dev && npm run build",{cwd:r,stdio:"pipe",timeout:3e5})}function Pn(e,t,r,s){const a=An(e);if(!K.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 bp({absoluteCodeyamRootPath:a,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function _p(e){const t=ss(),r=An(e),s=F.join(t,".build-info.json"),a=F.join(r,".build-info.json");if(!K.existsSync(s))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!K.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!K.existsSync(a))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(K.readFileSync(s,"utf8")),i=JSON.parse(K.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 ar(e,t){const r=An(e);if(!K.existsSync(r)){t.update("Creating analyzer..."),await Do(e);return}const s=_p(e);s.isFresh||(t.update(`Updating analyzer (${s.reason})...`),await Do(e))}async function $a(e){await Cp(e,{killProcesses:!1})}const Ap=F.dirname(Vr(import.meta.url));function as(){let e=Ap;for(;e!==F.dirname(e);){const t=F.join(e,"package.json");if(K.existsSync(t))try{if(JSON.parse(K.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=F.dirname(e)}return null}function wn(e){if(!K.existsSync(e))return null;try{return JSON.parse(K.readFileSync(e,"utf8"))}catch{return null}}function Pp(){const e=as();if(e){const t=[F.join(e,"src/webserver/build-info.json"),F.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const s=wn(r);if(s!=null&&s.semanticVersion)return s.semanticVersion}}return"unknown"}function jp(){const e=as();if(e){const t=F.join(e,"package.json");try{const r=JSON.parse(K.readFileSync(t,"utf8"));if(r.version)return r.version}catch{}}return"unknown"}const Ia=Pp(),Ds=jp();function Ra(){if(Ds!=="unknown"&&Ds!=="0.1.0")return Ds;const e=as();if(e)for(const t of[F.join(e,"src/webserver/build-info.json"),F.join(e,"codeyam-cli/src/webserver/build-info.json")]){const r=wn(t);if(r!=null&&r.buildNumber)return`dev (build ${r.buildNumber})`}return"dev"}function Cl(e){const t=as();let r=null;if(t){const c=[F.join(t,"src/webserver/build-info.json"),F.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const m of c)if(r=wn(m),r)break}const s=ss(),a=F.join(s,".build-info.json"),o=wn(a);let i=null;if(e){const c=An(e),m=F.join(c,".build-info.json");i=wn(m)}let l=!1;return o&&i?l=o.buildTime>i.buildTime:o&&!i&&e&&(l=!0),{cliVersion:Ia,webserverVersion:r,templateVersion:o,cachedAnalyzerVersion:i,isCacheStale:l}}function os(e){const t=An(e),r=F.join(t,".build-info.json"),s=wn(r);return(s==null?void 0:s.version)??null}function Sl(){const e=he();return e?F.join(e,".codeyam","server.json"):null}function is(){const e=Sl();if(!e||!K.existsSync(e))return null;try{const t=K.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function Da(){const e=Sl();if(e)try{K.unlinkSync(e)}catch{}}function kl(e){try{return process.kill(e,0),!0}catch{return!1}}function El(){try{const e=process.platform==="win32",r=Ee(e?'tasklist /FI "IMAGENAME eq node.exe" /FO CSV /NH':"ps aux | grep codeyam-server | grep -v grep",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();if(!r)return[];const s=[];if(e)for(const a of r.split(`
|
|
40
|
-
`)){const o=a.match(/"[^"]*","(\d+)"/);if(o){const i=parseInt(o[1],10);if(!isNaN(i))try{Ee(`wmic process where "ProcessId=${i}" get CommandLine /FORMAT:LIST`,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).includes("codeyam-server")&&s.push(i)}catch{}}}else for(const a of r.split(`
|
|
41
|
-
`)){const o=a.trim().split(/\s+/);if(o.length>=2){const i=parseInt(o[1],10);isNaN(i)||s.push(i)}}return s}catch{return[]}}function WC(){const e=is();if(e)if(!kl(e.pid))Da();else return{running:!0,state:e};const t=El();return t.length>0?{running:!0,pids:t}:{running:!1}}function Mp(e,t=5e3){if(e.length===0)return!0;const r=Date.now()+t;for(;Date.now()<r;){if(!e.some(a=>kl(a)))return!0;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100)}return!1}function HC(){let e=!1;const t=[],r=is();if(r){try{process.kill(r.pid,"SIGTERM"),t.push(r.pid),e=!0}catch{}Da()}const s=El();for(const a of s)try{process.kill(a,"SIGTERM"),t.includes(a)||t.push(a),e=!0}catch{}return Mp(t),e}const Tp="/assets/globals-COUSHTyZ.css";function Oo({text:e,subtext:t,linkText:r,linkTo:s}){const[a,o]=M(!1);return a?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:d("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),d("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(me,{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 $p({version:e}){return n("div",{className:"px-6 sm:px-12 pb-8 mt-auto pt-8",children:d("div",{className:"border-t border-cygray-30 pt-6 flex flex-wrap justify-between items-center gap-4",children:[d("div",{className:"flex items-center gap-3",children:[n("span",{className:"font-mono text-sm font-semibold tracking-widest text-cyblack-100",children:"CODEYAM"}),e&&n("span",{className:"font-mono text-xs text-gray-400",children:e})]}),d("div",{className:"flex items-center gap-4 font-mono text-xs uppercase tracking-widest",children:[n("a",{href:"https://blog.codeyam.com/",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Read the Blog"}),n("span",{className:"text-cygray-30",children:"|"}),n("a",{href:"https://discord.gg/x4uAgaRdwF",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Join Discord"})]})]})})}function Ip({serverVersion:e}){const[t,r]=M("stale"),[s,a]=M(null),o=async()=>{r("restarting"),a(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let l=0;const c=30,m=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}l++,l<c?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:d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-amber-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),d("div",{className:"flex-1",children:[t==="stale"&&d(de,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Dashboard server is out of date"}),d("p",{className:"text-xs text-amber-700 mt-0.5",children:["Server version: ",e,". A newer version of CodeYam CLI is installed. Restart the server to get the latest features."]}),s&&n("p",{className:"text-xs text-red-600 mt-1",children:s})]}),t==="restarting"&&d(de,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Restarting server..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Please wait while the server restarts."})]}),t==="reconnecting"&&d(de,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Reconnecting..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Waiting for the server to come back online."})]})]}),t==="stale"&&n("button",{type:"button",onClick:()=>void o(),className:"shrink-0 px-4 py-2 bg-amber-600 text-white text-sm font-medium rounded hover:bg-amber-700 transition-colors cursor-pointer",children:"Restart Server"}),(t==="restarting"||t==="reconnecting")&&d("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 text-amber-700 text-sm",children:[d("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t==="restarting"?"Stopping...":"Reconnecting..."]})]})})})}function jt({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:s="",duration:a=2e3,ariaLabel:o,icon:i=!1,iconSize:l=14}){const[c,m]=M(!1),u=ie(()=>{navigator.clipboard.writeText(e).then(()=>{m(!0),setTimeout(()=>m(!1),a)}).catch(p=>{console.error("Failed to copy:",p)})},[e,a]);return n("button",{onClick:u,className:`cursor-pointer ${s}`,disabled:c,"aria-label":o||(c?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?c?n(ut,{size:l,className:"text-green-500"}):n(ft,{size:l}):c?r:t})}function Rp({currentVersion:e,latestVersion:t}){const[r,s]=M(!1);if(r)return null;const a="npm install -g @codeyam/codeyam-cli@latest && codeyam stop && codeyam";return n("div",{className:"bg-emerald-100 border rounded border-emerald-700 shadow-sm mx-6 mt-6",children:d("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-emerald-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M7 11l5-5m0 0l5 5m-5-5v12"})})}),d("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-emerald-900",children:"A new version of CodeYam CLI is available"}),d("p",{className:"text-xs text-emerald-700 mt-0.5",children:["Current: ",e," → Latest: ",t]})]}),d("div",{className:"shrink-0 flex items-center gap-2",children:[n("code",{className:"text-xs bg-emerald-200 text-emerald-900 px-2 py-1.5 rounded font-mono",children:a}),n(jt,{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 Un=null,mr=0;const Dp=3600*1e3;function Op(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 Lp(){const e=Ra();if(Un&&Date.now()-mr<Dp)return Un;try{const t=new AbortController,r=setTimeout(()=>t.abort(),5e3),s=await fetch("https://registry.npmjs.org/@codeyam/codeyam-cli/latest",{signal:t.signal});if(clearTimeout(r),!s.ok){const l={updateAvailable:!1,latestVersion:null,currentVersion:e};return Un=l,mr=Date.now(),l}const o=(await s.json()).version;if(!o){const l={updateAvailable:!1,latestVersion:null,currentVersion:e};return Un=l,mr=Date.now(),l}const i={updateAvailable:Op(o,e),latestVersion:o,currentVersion:e};return Un=i,mr=Date.now(),i}catch{return{updateAvailable:!1,latestVersion:null,currentVersion:e}}}function Fr(e){return F.join(e,".codeyam","queue.json")}function Gn(e){const t=Fr(e);if(!K.existsSync(t))return{paused:!1,jobs:[]};try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function Fp(e,t){const r=Fr(e),s=F.dirname(r);K.existsSync(s)||K.mkdirSync(s,{recursive:!0});try{K.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(a){throw console.error("Failed to save queue state:",a),a}}const Wr=class Wr extends Gr{constructor(t){super(),this.watcher=null,this.debounceTimers=new Map,this.DEBOUNCE_MS=300,this.options=t}start(){try{this.watcher=fe.watch(this.options.projectRootPath,{recursive:!0},(t,r)=>{if(!r||!/\.(ts|tsx|js|jsx|css|scss|json|svg|html)$/.test(r)||Wr.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=Z.join(this.options.projectRootPath,t),s=Z.join(this.options.tmpProjectPath,t);try{if(!fe.existsSync(r)){fe.existsSync(s)&&(fe.unlinkSync(s),console.log(`[InteractiveSyncWatcher] Removed: ${t}`));return}const a=Z.dirname(s);fe.existsSync(a)||fe.mkdirSync(a,{recursive:!0}),fe.copyFileSync(r,s);const o=Z.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:Z.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")}};Wr.IGNORED_DIRS=["node_modules",".git",".codeyam","__codeyamMocks__",".next","dist","build",".turbo",".vercel","coverage",".cache"];let Xs=Wr,zp=class extends Gr{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 ea="__codeyam_dev_mode_event_emitter__";globalThis[ea]||(globalThis[ea]=new zp);const Lo=globalThis[ea],ta=new Map;async function Bp(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await Yp(e,t,r);else if(e.type==="baseline")await Up(e,t,r);else if(e.type==="recapture")await Wp(e,t,r);else if(e.type==="capture-only")await Hp(e,t,r);else if(e.type==="debug-setup")await Jp(e,t,r);else if(e.type==="interactive-start")await Vp(e,t,r);else if(e.type==="interactive-stop")await Gp(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 Yp(e,t,r){var g,x,b,w;const{projectSlug:s,commitSha:a,entityShas:o}=e;if(!a)throw new Error("Analysis job missing commitSha");const i=o||[],{project:l}=await Re(s);await $a(s),await ar(s,{update:v=>console.log(`[Queue] ${v}`)});const c=os(s),m={...await Ut(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Wt(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...c?{ANALYZER_VERSION:c}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},u=(x=(g=l.metadata)==null?void 0:g.webapps)==null?void 0:x[0];if(!u)throw new Error("No webapps found in project metadata");const p=e.onlyDataStructure,h={packageManager:((b=l.metadata)==null?void 0:b.packageManager)||"npm",absoluteProjectRootPath:gt(s),port:0,noServer:!0,framework:u.framework,...p?{}:{orchestrateCapture:"local-sequential"}},f=Pn(s,m,h),y=v=>{try{return process.kill(v,0),!0}catch{return!1}};await Lt({commitSha:a,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((w=e.filePaths)==null?void 0:w.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:f.process.pid}}),r==null||r.notifyChange("commit");try{try{const v=new Promise((C,P)=>setTimeout(()=>P(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,v]),await Lt({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await Lt({commitSha:a,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(C=>setTimeout(C,2e3))}finally{if(f.process.pid)try{y(f.process.pid)&&await Xn(f.process.pid,()=>{})}catch{}}}catch(v){if(console.error(`[Queue] Analysis job ${e.id} failed:`,v),f.process.pid&&y(f.process.pid))try{await Xn(f.process.pid,()=>{})}catch{}try{await Lt({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:v instanceof Error?v.message:String(v)}}),r==null||r.notifyChange("commit")}catch(C){console.error("[Queue] Failed to update commit metadata after job failure:",C)}throw v}}async function Up(e,t,r){var h,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 Re(s);await $a(s),await ar(s,{update:g=>console.log(`[Queue] ${g}`)});const i=os(s),l={...await Ut(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Wt(),...i?{ANALYZER_VERSION:i}:{}},c=(f=(h=o.metadata)==null?void 0:h.webapps)==null?void 0:f[0];if(!c)throw new Error("No webapps found in project metadata");const m={packageManager:((y=o.metadata)==null?void 0:y.packageManager)||"npm",absoluteProjectRootPath:gt(s),port:0,noServer:!0,framework:c.framework,orchestrateCapture:"local-sequential"},u=Pn(s,l,m),p=g=>{try{return process.kill(g,0),!0}catch{return!1}};await Lt({commitSha:a,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:u.process.pid}}),r==null||r.notifyChange("commit");try{const g=new Promise((x,b)=>setTimeout(()=>b(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([u.promise,g]),await Lt({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{p(u.process.pid)&&await Xn(u.process.pid,()=>{})}catch{}}}async function Wp(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 l=await Pt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:b}=await import("./index-BWoRb5RY.js"),w=b(),v=await w.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let C={};v!=null&&v.metadata&&(typeof v.metadata=="string"?C=JSON.parse(v.metadata):C=v.metadata),C.defaultWidth=i,await w.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",l.entitySha).execute()}await En(a,b=>{if(b.readyToBeCaptured=!0,b.scenarios)for(const w of b.scenarios)(!o||w.name===o)&&(delete w.finishedAt,delete w.startedAt,delete w.screenshotStartedAt,delete w.screenshotFinishedAt,delete w.interactiveStartedAt,delete w.interactiveFinishedAt,delete w.error,delete w.errorStack);delete b.finishedAt});const{project:c}=await Re(s);await ar(s,{update:b=>console.log(`[Queue] ${b}`)});const m=os(s),u={...await Ut(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Wt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...m?{ANALYZER_VERSION:m}:{}},p={packageManager:((f=c.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:gt(s),port:void 0,noServer:!0,framework:((x=(g=(y=c.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??Ke.Next,orchestrateCapture:"local-sequential"},h=Pn(s,u,p);try{await h.promise}finally{try{h.process.kill("SIGTERM")}catch{}}}async function Hp(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 l=await Pt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:b}=await import("./index-BWoRb5RY.js"),w=b(),v=await w.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let C={};v!=null&&v.metadata&&(typeof v.metadata=="string"?C=JSON.parse(v.metadata):C=v.metadata),C.defaultWidth=i,await w.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",l.entitySha).execute()}await En(a,b=>{if(b.readyToBeCaptured=!0,b.scenarios)for(const w of b.scenarios)(!o||w.name===o)&&(delete w.finishedAt,delete w.startedAt,delete w.screenshotStartedAt,delete w.screenshotFinishedAt,delete w.interactiveStartedAt,delete w.interactiveFinishedAt,delete w.error,delete w.errorStack);delete b.finishedAt});const{project:c}=await Re(s);await ar(s,{update:b=>console.log(`[Queue] ${b}`)});const m=os(s);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await Ut(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Wt(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...m?{ANALYZER_VERSION:m}:{}},p={packageManager:((f=c.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:gt(s),port:void 0,noServer:!0,fast:!0,framework:((x=(g=(y=c.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??Ke.Next,orchestrateCapture:"local-sequential"},h=Pn(s,u,p);try{await h.promise}finally{try{h.process.kill("SIGTERM")}catch{}}}async function Jp(e,t,r){var h,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:l}=await Re(s);await $a(s),await ar(s,{update:x=>console.log(`[Queue] ${x}`)});const c={...await Ut(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Wt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,PREP_ONLY:"true"};o&&(c.SCENARIO_IDS=o);const m={packageManager:((h=l.metadata)==null?void 0:h.packageManager)||"npm",absoluteProjectRootPath:gt(s),port:void 0,noServer:!1,framework:((g=(y=(f=l.metadata)==null?void 0:f.webapps)==null?void 0:y[0])==null?void 0:g.framework)||Ke.Next},p=await Pn(s,c,m).promise;if(p!==0)throw new Error(`Prep process exited with code ${p}`)}async function Vp(e,t,r){var x,b,w,v;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Interactive start job missing analysisId");const i=await Pt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:l}=await Re(s),c={...await Ut(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:Wt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,INTERACTIVE_MODE:"true"};o&&(c.SCENARIO_IDS=o);const m=gt(s),u=Z.join(m,".next","dev","lock");if(fe.existsSync(u)){console.log("[Queue] Found stale .next/dev/lock, cleaning up old processes");try{const C=Ee(`pgrep -f ${JSON.stringify(m)} 2>/dev/null || true`,{encoding:"utf-8"}).trim();if(C)for(const P of C.split(`
|
|
42
|
-
`).filter(Boolean))try{process.kill(parseInt(P,10),"SIGTERM"),console.log(`[Queue] Killed stale process ${P}`)}catch{}}catch{}try{fe.unlinkSync(u),console.log("[Queue] Removed stale lock file")}catch{}}const p=fe.existsSync(m)&&fe.existsSync(Z.join(m,"package.json")),h={packageManager:((x=l.metadata)==null?void 0:x.packageManager)||"npm",absoluteProjectRootPath:m,port:void 0,noServer:!1,fast:p,framework:((v=(w=(b=l.metadata)==null?void 0:b.webapps)==null?void 0:w[0])==null?void 0:v.framework)||Ke.Next};await En(a,C=>{C.readyToBeCaptured=!0});const f=Pn(s,c,h);await ol(a,C=>{C.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=gt(s),g=new Xs({projectRootPath:t,tmpProjectPath:y});g.on("sync",C=>{C.type==="file-synced"?Lo.emitFileSynced(C.fileName,C.filePath):C.type==="error"&&Lo.emitError(C.fileName,C.filePath)}),g.start(),ta.set(a,g),console.log(`[Queue] File sync watcher started for analysis ${a}`)}async function Gp(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 l=ta.get(a);l&&(l.stop(),ta.delete(a),console.log(`[Queue] File sync watcher stopped for analysis ${a}`));const c=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${a}, killing PID: ${c}`);try{try{process.kill(c,0)}catch{console.log(`[Queue] Process ${c} already exited`);return}await Xn(c,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${c}`)}catch(u){throw console.error(`[Queue] Failed to kill process ${c}:`,u),u}finally{await ol(a,u=>{u.interactiveMode=null})}}class Kp{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=Gn(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||va(),s={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(s),this.save(),console.log(`[Queue] Enqueued job ${r} (${s.type})`);const a=new Promise((o,i)=>{this.completionCallbacks.set(r,l=>{l?i(l):o()})});return this.state.paused||this.processNext().catch(o=>{console.error("[Queue] ERROR in processNext():",o)}),{jobId:r,completion:a}}resume(){console.log("[Queue] Resuming queue"),this.state.paused=!1,this.save(),this.processNext()}pause(){console.log("[Queue] Pausing queue"),this.state.paused=!0,this.save()}getState(){return{...this.state}}getJobResult(t){return this.completedJobs.get(t)}removeJob(t){const r=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(a=>a.id!==t);const s=this.state.jobs.length<r;if(s){console.log(`[Queue] Removed job ${t}`),this.save();const a=this.completionCallbacks.get(t);a&&(setImmediate(()=>a(new Error("Job cancelled by user"))),this.completionCallbacks.delete(t))}else console.log(`[Queue] Job ${t} not found in queue`);return s}clearQueue(){const t=this.state.jobs.length;return t===0?0:(this.state.jobs.forEach(r=>{const s=this.completionCallbacks.get(r.id);s&&(setImmediate(()=>s(new Error("Job cancelled by user"))),this.completionCallbacks.delete(r.id))}),this.state.jobs=[],console.log(`[Queue] Cleared ${t} jobs`),this.save(),t)}reorderJob(t,r){const s=this.state.jobs.findIndex(i=>i.id===t);if(s===-1)return console.log(`[Queue] Job ${t} not found in queue`),!1;const a=r==="up"?s-1:s+1;if(a<0||a>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const o=this.state.jobs[s];return this.state.jobs[s]=this.state.jobs[a],this.state.jobs[a]=o,console.log(`[Queue] Moved job ${t} ${r} (position ${s} -> ${a})`),this.save(),!0}async processNext(){if(this.state.paused||this.processing)return;if(this.state.jobs.length===0){console.log("[Queue] No jobs to process");return}this.processing=!0;const t=this.state.jobs[0];console.log(`[Queue] Starting job ${t.id} (${t.type})`);try{this.state.currentlyExecuting=this.state.jobs.shift(),this.save(),await Bp(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(){Fp(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class qp{constructor(t,r,s=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=s}start(){const t=Fr(this.projectRoot);if(!K.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=Fr(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=K.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=K.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 Qp{constructor(t,r,s){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=s,this.cachedState=Gn(r)}start(){this.cachedState=Gn(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 qp(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,s;const a=new Promise((i,l)=>{r=i,s=l}),o=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),s(i)}),{jobId:o,completion:a}}async enqueueRemote(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to enqueue: ${r.status} ${s}`)}return r.json()}resume(){console.log("[ProxyQueue] Sending resume command to background server"),this.sendAction("resume").catch(t=>{console.error("[ProxyQueue] Failed to resume:",t)})}pause(){console.log("[ProxyQueue] Sending pause command to background server"),this.sendAction("pause").catch(t=>{console.error("[ProxyQueue] Failed to pause:",t)})}async sendAction(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to ${t}: ${r.status} ${s}`)}this.refreshState()}getState(){return this.cachedState=Gn(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=Gn(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 Zp(e){const t=F.join(e,".codeyam","server.json");if(!K.existsSync(t))return null;try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function Xp(e){try{return process.kill(e,0),!0}catch{return!1}}async function eh(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 th(e){const t=Zp(e);return!t||!Xp(t.pid)||!await eh(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class nh extends Gr{constructor(){super();zn(this,"watcher",null);zn(this,"dbPath",null);zn(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=Wt();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 nh;let sn=null,Kn=null;async function rh(){if(!sn){if(Kn){await Kn;return}Kn=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||il()||process.cwd();if(Qm(e),console.log(`[GlobalQueue] Project root: ${e}`),await ze(),process.env.NODE_ENV==="development")try{const r=Z.join(e,".codeyam","config.json"),a=JSON.parse(await fe.promises.readFile(r,"utf8")).projectSlug;a&&(await vn({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 th(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new Qp(t,e,()=>{ct.notifyChange("unknown")});await r.start(),sn=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new Kp(e,ct);await r.start(),sn=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Kn}}async function Mt(){return sn||await rh(),sn}function sh(){return sn||(Kn&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const ah=()=>[{rel:"stylesheet",href:Tp},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}],oh={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:Ra()};async function ih({request:e,context:t}){var r,s,a,o,i,l,c,m,u,p,h;try{const f=e.signal,y=()=>{if(f.aborted)throw new Response(null,{status:499})};y();const g=he()||process.cwd(),[x,b,w]=await Promise.all([Ie(),ns(g),Lp().catch(()=>null)]);if(!x)throw new Error("Project slug not found");const{project:v,branch:C}=await Re(x);y();const P=await Rr({projectId:v.id,branchId:C.id,limit:20,skipRelations:!0});y();const N=P.length>0?P[0]:null,S=t.analysisQueue||sh(),k=S==null?void 0:S.getState();y();const _=await Promise.all(((k==null?void 0:k.jobs)||[]).map(async G=>{var re;const ee=await ur(G.entityShas||[]);return ee.length===0&&((re=G.entityShas)!=null&&re.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",G.id),{...G,entities:ee}}));let j=null;if(k!=null&&k.currentlyExecuting){const G=k.currentlyExecuting,ee=await ur(G.entityShas||[]);ee.length===0&&((r=G.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",G.id),j={...G,entities:ee}}const T=j?_.filter(G=>G.id!==j.id):_;let E=((a=(s=N==null?void 0:N.metadata)==null?void 0:s.currentRun)==null?void 0:a.currentEntityShas)||[];if(E.length===0){const G=((o=N==null?void 0:N.metadata)==null?void 0:o.historicalRuns)||[];if(G.length>0){const re=[...G].sort((ue,se)=>{const pe=ue.archivedAt||ue.createdAt||"";return(se.archivedAt||se.createdAt||"").localeCompare(pe)})[0];if(re){const ue=re.analysisCompletedAt||re.createdAt;if(ue){const se=new Date(ue).getTime(),Ce=Date.now()-1440*60*1e3;se>Ce&&(E=re.currentEntityShas||[])}}}}const $=await ur(E),R=[];b.ANTHROPIC_API_KEY&&R.push("ANTHROPIC_API_KEY"),b.GROQ_API_KEY&&R.push("GROQ_API_KEY"),b.OPENAI_API_KEY&&R.push("OPENAI_API_KEY"),b.OPENROUTER_API_KEY&&R.push("OPENROUTER_API_KEY"),y();const I=[];for(const G of P){const ee=((i=G.metadata)==null?void 0:i.historicalRuns)||[];for(const re of ee)I.push(re)}I.sort((G,ee)=>{const re=G.archivedAt||G.analysisCompletedAt||G.createdAt||"";return(ee.archivedAt||ee.analysisCompletedAt||ee.createdAt||"").localeCompare(re)});const W=new Set(((l=j==null?void 0:j.entities)==null?void 0:l.map(G=>G.sha))||[]),U=I.filter(G=>!(G.currentEntityShas||[]).some(re=>W.has(re))).slice(0,3),B=new Set;for(const G of U)for(const ee of G.currentEntityShas||[])B.add(ee);const H=await ur(Array.from(B)),D=new Map;for(const G of H)D.set(G.sha,G);const A=U.map(G=>({...G,entities:(G.currentEntityShas||[]).map(ee=>D.get(ee)).filter(ee=>ee!=null)})),J=is(),V=(J==null?void 0:J.cliVersion)??"unknown",q=V!=="unknown"&&V!==Ia,X=((m=(c=v.metadata)==null?void 0:c.labs)==null?void 0:m.simulations)??!1,L=X?Ep():!1,O=((u=v.metadata)==null?void 0:u.editorMode)??!1,z={currentRun:(p=N==null?void 0:N.metadata)==null?void 0:p.currentRun,projectSlug:x,currentEntities:$,availableAPIKeys:R,queuedJobCount:T.length,queueJobs:T,currentlyExecuting:j,historicalRuns:A,isServerOutOfDate:q,serverVersion:V,npmUpdate:w!=null&&w.updateAvailable&&w.latestVersion?{latestVersion:w.latestVersion,currentVersion:w.currentVersion}:null,labs:((h=v.metadata)==null?void 0:h.labs)??null,simulationsEnabled:X,isSimulationsReady:L,isAdmin:!!process.env.CODEYAM_ADMIN,editorMode:O,displayVersion:Ra()};return Q(z)}catch(f){return f instanceof Response&&f.status===499||console.error("Failed to load root data:",f),Q(oh)}}function lh(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:s,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:l,isServerOutOfDate:c,serverVersion:m,npmUpdate:u,labs:p,simulationsEnabled:h,isSimulationsReady:f,isAdmin:y,editorMode:g,displayVersion:x}=qe(),{toasts:b,closeToast:w}=Aa(),v=kt(),C=ve(v),P=Hr();ne(()=>{C.current=v},[v]);const N=P.pathname.startsWith("/entity/")&&P.pathname.includes("/edit/")||P.pathname.startsWith("/dev/")||P.pathname.startsWith("/editor"),S=P.pathname.includes("/fullscreen")||P.pathname.startsWith("/editor");return ne(()=>{let k=null,_=null,j=0;const T=2e3;function E(){k||(k=new EventSource("/api/events"),k.addEventListener("message",I=>{const W=JSON.parse(I.data);if(W.type==="queue")C.current.revalidate(),j=Date.now();else if(W.type==="db-change"||W.type==="unknown"){const Y=Date.now(),U=Y-j;U<T?(_&&clearTimeout(_),_=setTimeout(()=>{C.current.revalidate(),j=Date.now(),_=null},T-U)):(C.current.revalidate(),j=Y)}}),k.addEventListener("error",()=>{}))}function $(){_&&(clearTimeout(_),_=null),k&&(k.close(),k=null)}function R(){document.hidden?$():(E(),C.current.revalidate())}return document.hidden||E(),document.addEventListener("visibilitychange",R),()=>{document.removeEventListener("visibilitychange",R),$()}},[]),d(de,{children:[d("div",{className:`min-h-screen ${N?"":"grid"} bg-cygray-10`,style:N?void 0:{gridTemplateColumns:"65px minmax(0, 1fr)"},children:[!N&&n(uu,{labs:p,isAdmin:y,editorMode:g}),d("div",{className:"max-h-screen overflow-auto bg-cygray-10 flex flex-col min-h-screen",children:[c&&n(Ip,{serverVersion:m}),u&&u.currentVersion&&n(Rp,{currentVersion:u.currentVersion,latestVersion:u.latestVersion}),h&&s.length===0&&n(Oo,{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"}),h&&!f&&n(Oo,{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(Vc,{})}),n($p,{version:x})]})]}),n(hu,{toasts:b,onClose:w}),!S&&h&&n(fu,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:l})]})}const ch=Je(function(){return d("html",{lang:"en",children:[d("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(Uc,{}),n(Wc,{})]}),d("body",{children:[n(mu,{children:n(cu,{children:n(lh,{})})}),n(Hc,{}),n(Jc,{})]})]})}),dh=Object.freeze(Object.defineProperty({__proto__:null,default:ch,links:ah,loader:ih},Symbol.toStringTag,{value:"Module"}));function pr(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function pn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:o=!0,refreshTrigger:i=0}){const l=Fe(),[c,m]=M(null),[u,p]=M(!1),[h,f]=M(!1),[y,g]=M(!1),x=ve(!1),b=ve(null),w=ve(null),v=ve(null),[C,P]=M(0),[N,S]=M(0),k=ve(null),_=ve(!1),{interactiveUrl:j,resetLogs:T}=_t(a,o),E=ve(t),$=ve(i);ne(()=>{$.current!==i&&($.current=i,c&&(console.log("[useInteractiveMode] Manual refresh triggered"),f(!0),g(!1),P(0),S(I=>I+1),_.current=!1,k.current&&(clearTimeout(k.current),k.current=null)))},[i,c]),ne(()=>{if(E.current!==t&&(E.current=t,b.current&&w.current&&r)){let I=b.current;if(v.current&&s){const U=pr(v.current),B=pr(s);U!==B&&(I=I.replace(U,B),v.current=s)}const W=pr(w.current),Y=pr(r);I=I.replace(W,Y),w.current=r,m(I),f(!0),g(!1),P(0),S(U=>U+1),_.current=!1,k.current&&(clearTimeout(k.current),k.current=null);return}},[t,r,s]),ne(()=>{if(j){const I=j+"?width=600px";b.current=I,r&&(w.current=r),s&&(v.current=s),m(I),p(!1),f(!0)}},[j]),ne(()=>{const I=W=>{W.data.type==="codeyam-resize"&&(_.current||(_.current=!0,k.current&&(clearTimeout(k.current),k.current=null),P(0),g(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{f(!1)})})))};return window.addEventListener("message",I),()=>window.removeEventListener("message",I)},[]);const R=()=>{_.current=!1,k.current&&clearTimeout(k.current);const I=300*Math.pow(2,C);k.current=setTimeout(()=>{_.current||(C<2?(P(W=>W+1),S(W=>W+1),f(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),g(!0),f(!1)))},I)};return ne(()=>{o&&!x.current&&t&&e&&(x.current=!0,p(!0),g(!1),m(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(W){console.error("[useInteractiveMode] Failed to clear log file:",W)}T(),l.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[o,t,e,T,a]),ne(()=>{const I=e,W=()=>{if(x.current&&I){const U=new URLSearchParams({action:"stop",analysisId:I});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const B=navigator.sendBeacon("/api/interactive-mode",U);console.log("[useInteractiveMode] sendBeacon result:",B),B||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:U,keepalive:!0}).catch(H=>console.error("Failed to stop interactive mode:",H)))}},Y=()=>{W()};return window.addEventListener("beforeunload",Y),()=>{window.removeEventListener("beforeunload",Y),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:x.current,analysisId:I}),W()}},[e]),{interactiveServerUrl:c,isStarting:u,isLoading:h,showIframe:y,iframeKey:N,onIframeLoad:R}}const hr=10,uh=1024;function Oa({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:s,onHoverChange:a,hideLabel:o=!1,lightMode:i=!1}){const[l,c]=M(null),m=ve(null),u=ae(()=>[...s].sort((w,v)=>w.width-v.width),[s]),{fittingPresets:p,overflowPresets:h}=ae(()=>{const w=[],v=[];for(const C of u)C.width<=uh?w.push(C):v.push(C);return v.sort((C,P)=>P.width-C.width),{fittingPresets:w,overflowPresets:v}},[u]),f=ie(w=>{if(!m.current)return null;const v=m.current.getBoundingClientRect(),C=w-v.left,P=v.width,N=P/2,k=(p.length>0?p[p.length-1].width:0)/2,_=N-k,j=N+k,T=h.length>0?(h.length-1)*hr:0;if(h.length>0){if(C<_){if(C<=T){const $=Math.min(Math.floor(C/hr),h.length-1);return h[$]}return h[h.length-1]}if(C>j){const $=P-C;if($<=T){const R=Math.min(Math.floor($/hr),h.length-1);return h[R]}return h[h.length-1]}}const E=Math.abs(C-N);for(let $=p.length-1;$>=0;$--){const R=p[$],I=p[$-1],W=R.width/2,Y=I?I.width/2:0;if(E<=W&&E>=Y)return R}return p[0]||h[h.length-1]||null},[p,h]),y=ie(w=>{const v=f(w.clientX);c(v),a==null||a(v)},[f,a]),g=ie(()=>{c(null),a==null||a(null)},[a]),x=ie(w=>{const v=f(w.clientX);v&&r(v)},[f,r]),b=l||{name:t,width:e};return d("div",{ref:m,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:y,onMouseLeave:g,onClick:x,children:[l&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${l.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:p.map(w=>{const v=w.width===e,C=(l==null?void 0:l.name)===w.name,P=w.width/2;return d("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${P}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${v||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${P}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${v||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},w.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:h.map((w,v)=>{const C=v*hr,P=w.width===e,N=(l==null?void 0:l.name)===w.name;return d("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${C}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${P||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{right:`${C}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${P||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},w.name)})}),!o&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:d("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${l?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[b.name," - ",b.width,"px"]})})]})}function ls({width:e,height:t,onSave:r,onCancel:s}){const[a,o]=M(""),[i,l]=M(""),c=()=>{const u=a.trim();if(!u){l("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:d("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[d("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),d("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),d("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),d("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:a,onChange:u=>{o(u.target.value),l("")},onKeyDown:u=>{u.key==="Enter"&&a.trim()&&c(),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})]}),d("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:s,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors cursor-pointer",children:"Cancel"}),n("button",{onClick:c,disabled:!a.trim(),className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] 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 cs(e){const[t,r]=M([]),s=e?`codeyam-custom-sizes-${e}`:null;ne(()=>{if(!s||typeof window>"u"){r([]);return}try{const l=localStorage.getItem(s);if(l){const c=JSON.parse(l);Array.isArray(c)&&r(c)}}catch(l){console.error("[useCustomSizes] Failed to load custom sizes:",l),r([])}},[s]);const a=ie(l=>{if(!(!s||typeof window>"u"))try{localStorage.setItem(s,JSON.stringify(l))}catch(c){console.error("[useCustomSizes] Failed to save custom sizes:",c)}},[s]),o=ie((l,c,m)=>{r(u=>{const p=u.findIndex(y=>y.name===l),h={name:l,width:c,height:m};let f;return p>=0?(f=[...u],f[p]=h):f=[...u,h],a(f),f})},[a]),i=ie(l=>{r(c=>{const m=c.filter(u=>u.name!==l);return a(m),m})},[a]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}function Bt(){return d("div",{className:"spinner-container",children:[n("span",{className:"loader"}),n("style",{children:`
|
|
43
|
-
.loader {
|
|
44
|
-
width: 48px;
|
|
45
|
-
height: 48px;
|
|
46
|
-
border: 3px solid rgba(0, 92, 117, 0.2);
|
|
47
|
-
border-radius: 50%;
|
|
48
|
-
display: inline-block;
|
|
49
|
-
position: relative;
|
|
50
|
-
box-sizing: border-box;
|
|
51
|
-
animation: rotation 1s linear infinite;
|
|
52
|
-
}
|
|
53
|
-
.loader::after {
|
|
54
|
-
content: '';
|
|
55
|
-
box-sizing: border-box;
|
|
56
|
-
position: absolute;
|
|
57
|
-
left: 50%;
|
|
58
|
-
top: 50%;
|
|
59
|
-
transform: translate(-50%, -50%);
|
|
60
|
-
width: 56px;
|
|
61
|
-
height: 56px;
|
|
62
|
-
border-radius: 50%;
|
|
63
|
-
border: 3px solid;
|
|
64
|
-
border-color: #005c75 transparent;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
@keyframes rotation {
|
|
68
|
-
0% {
|
|
69
|
-
transform: rotate(0deg);
|
|
70
|
-
}
|
|
71
|
-
100% {
|
|
72
|
-
transform: rotate(360deg);
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
`})]})}const Fo=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],mh=80;function Nn(){const[e,t]=M(0);return ne(()=>{const r=setInterval(()=>{t(s=>(s+1)%Fo.length)},mh);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:Fo[e]})}async function ph({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw Q("Invalid parameters",{status:400});const s=await dn(t);if(!s)throw Q("Entity not found",{status:404});const a=await es(s),o=((l=a==null?void 0:a.scenarios)==null?void 0:l.find(c=>c.id===r))||null;if(!o)throw Q("Scenario not found",{status:404});const i=await Ie();return Q({entity:s,scenario:o,analysis:a,projectSlug:i})}const Os=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],hh=Je(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=qe(),o=St(),[i]=Cn(),[l,c]=M(null),[m,u]=M(1440),[p,h]=M({name:"Desktop",width:1440,height:900}),[f,y]=M(!1),[g,x]=M(null),{customSizes:b,addCustomSize:w}=cs(a),v=ae(()=>[...Os,...b],[b]),{interactiveServerUrl:C,isStarting:P,isLoading:N,showIframe:S,iframeKey:k,onIframeLoad:_}=pn({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:j}=_t(a,P||N),T=()=>{o(`/entity/${t.sha}`)},E=(V,q)=>{u(V);const X=v.find(O=>O.width===V&&O.height===q);c(X||null),h({name:(X==null?void 0:X.name)||"Custom",width:V,height:q})},$=V=>{c(V),u(V.width),h({name:V.name,width:V.width,height:V.height})},R=V=>{w(V,p.width,p.height??900),y(!1),h(q=>({...q,name:V}))},I=((s==null?void 0:s.scenarios)||[]).filter(V=>{var q;return!((q=V.metadata)!=null&&q.sameAsDefault)}),W=I.findIndex(V=>V.id===(r==null?void 0:r.id)),Y=W+1,U=I.length,B=W>0,H=W<I.length-1,D=()=>{if(B){const V=I[W-1],q=encodeURIComponent(`/entity/${t.sha}/scenarios/${V.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${V.id}/fullscreen?from=${q}`)}},A=()=>{if(H){const V=I[W+1],q=encodeURIComponent(`/entity/${t.sha}/scenarios/${V.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${V.id}/fullscreen?from=${q}`)}},J=P||N||!S;return d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[d("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:qr,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),d("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:D,disabled:!B,className:`${B?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),d("span",{className:"text-gray-400 text-sm",children:[Y,"/",U]}),n("button",{onClick:A,disabled:!H,className:`${H?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),d("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&d("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]})]}),n("button",{onClick:T,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),d("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Os[Os.length-1].width}px`,width:"100%"},children:n(Oa,{currentViewportWidth:m,currentPresetName:p.name,onDevicePresetClick:$,devicePresets:v,hideLabel:!0,onHoverChange:x,lightMode:!0})})}),d("div",{className:"relative z-10 flex items-center gap-2",children:[d("div",{className:"relative w-28 h-5",children:[d("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(g==null?void 0:g.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"})})]}),d("select",{value:p.name,onChange:V=>{const q=v.find(X=>X.name===V.target.value);q&&$(q)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[v.map(V=>n("option",{value:V.name,children:V.name},V.name)),p.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:p.width,onChange:V=>{const q=parseInt(V.target.value,10);!isNaN(q)&&q>0&&E(q,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:"×"}),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:()=>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:`
|
|
76
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
77
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
78
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
79
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
80
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:C?d("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${p.width}px`,maxHeight:`${p.height}px`},children:[J&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),j&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Nn,{}),j]})]})]})}),n("iframe",{src:C,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:_,style:{opacity:S?1:0}},k)]}):d("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),j&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Nn,{}),j]})]})]})}),f&&n(ls,{width:p.width,height:p.height??900,onSave:R,onCancel:()=>y(!1)})]})}),fh=Object.freeze(Object.defineProperty({__proto__:null,default:hh,loader:ph},Symbol.toStringTag,{value:"Module"}));function _l({serverUrl:e,isStarting:t,projectSlug:r,devServerError:s,onStartServer:a,notificationsEnabled:o,onToggleNotifications:i}){const[l,c]=M(null),m=ve(null);ne(()=>{if(!r)return;const f=new EventSource("/api/dev-mode-events");return f.onmessage=y=>{try{const g=JSON.parse(y.data);g.type==="file-synced"&&(c(g.fileName),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{c(null)},5e3))}catch{}},()=>{f.close(),m.current&&clearTimeout(m.current)}},[r]);let u;s?u="error":t?u="starting":e?u="running":u="stopped";const p={starting:"bg-yellow-400",running:"bg-green-400",stopped:"bg-gray-400",error:"bg-red-400"},h={starting:"Starting...",running:e||"Running",stopped:"Stopped",error:"Error"};return d("div",{className:"bg-[#1e1e1e] border-t border-[#3d3d3d] h-7 flex items-center px-4 gap-4 shrink-0 text-xs font-mono",children:[d("div",{className:"flex items-center gap-2",children:[n("div",{className:`w-2 h-2 rounded-full ${p[u]}`}),d("span",{className:"text-gray-400",children:["Server:"," ",n("span",{className:"text-gray-300",children:h[u]})]}),(u==="stopped"||u==="error")&&a&&n("button",{onClick:a,className:"ml-1 px-2.5 py-0.5 bg-[#005c75] hover:bg-[#007a9a] text-white text-[11px] font-medium rounded transition-colors cursor-pointer border-none leading-tight",children:"Start Server"})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"}),l&&d(de,{children:[d("div",{className:"flex items-center gap-1.5",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2",children:n("path",{d:"M20 6L9 17l-5-5"})}),d("span",{className:"text-green-400",children:["Synced: ",l]})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"})]}),n("div",{className:"flex-1"}),i&&n("button",{onClick:i,className:`text-[11px] rounded transition-colors cursor-pointer ${o?"text-green-400 hover:text-green-300":"text-gray-500 hover:text-gray-300"}`,title:o?"Click to turn off notifications":"Click to get notified when Claude finishes",children:o?"Notifications On":"Notifications Off"})]})}async function gh(e,t){try{const{WebglAddon:s}=await import("@xterm/addon-webgl"),a=new s;return a.onContextLoss(()=>{t==null||t("webgl","canvas",new Error("WebGL context lost")),a.dispose(),zo(e).then(o=>{o||t==null||t("canvas","dom",new Error("Canvas fallback failed after context loss"))})}),e.loadAddon(a),{type:"webgl",dispose:()=>a.dispose()}}catch(s){t==null||t("webgl","canvas",s)}const r=await zo(e);return r||(t==null||t("canvas","dom",new Error("Canvas addon failed")),{type:"dom",dispose:()=>{}})}async function zo(e){try{const{CanvasAddon:t}=await import("@xterm/addon-canvas"),r=new t;return e.loadAddon(r),{type:"canvas",dispose:()=>r.dispose()}}catch{return null}}const yh=`
|
|
81
|
-
.xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
|
|
82
|
-
.xterm.focus, .xterm:focus { outline: none; }
|
|
83
|
-
.xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
|
|
84
|
-
.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; }
|
|
85
|
-
.xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
|
|
86
|
-
.xterm .composition-view.active { display: block; }
|
|
87
|
-
.xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
|
|
88
|
-
.xterm .xterm-screen { position: relative; }
|
|
89
|
-
.xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
|
|
90
|
-
.xterm .xterm-scroll-area { visibility: hidden; }
|
|
91
|
-
.xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
|
|
92
|
-
.xterm.enable-mouse-events { cursor: default; }
|
|
93
|
-
.xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
|
|
94
|
-
.xterm.column-select.focus { cursor: crosshair; }
|
|
95
|
-
.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; }
|
|
96
|
-
.xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
|
|
97
|
-
.xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
|
|
98
|
-
.xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
|
|
99
|
-
.xterm-dim { opacity: 1 !important; }
|
|
100
|
-
.xterm-underline-1 { text-decoration: underline; }
|
|
101
|
-
.xterm-underline-2 { text-decoration: double underline; }
|
|
102
|
-
.xterm-underline-3 { text-decoration: wavy underline; }
|
|
103
|
-
.xterm-underline-4 { text-decoration: dotted underline; }
|
|
104
|
-
.xterm-underline-5 { text-decoration: dashed underline; }
|
|
105
|
-
.xterm-overline { text-decoration: overline; }
|
|
106
|
-
.xterm-strikethrough { text-decoration: line-through; }
|
|
107
|
-
.xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
|
|
108
|
-
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
|
|
109
|
-
.xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
|
|
110
|
-
.xterm-decoration-top { z-index: 2; position: relative; }
|
|
111
|
-
`;function xh(){if(document.getElementById("xterm-css"))return;const e=document.createElement("style");e.id="xterm-css",e.textContent=yh,document.head.appendChild(e)}const Al=Zc(function({entityName:t,entityType:r,entitySha:s,entityFilePath:a,scenarioName:o,scenarioDescription:i,analysisId:l,projectSlug:c,onRefreshPreview:m,onShowResults:u,onHideResults:p,onSetViewport:h,editorMode:f,onIdleChange:y,notificationsEnabled:g},x){const b=ve(null),w=ve(null),v=ve(null),C=ve(null),P=ve(null),N=ve(!1),S=ve(0),k=ve(!1),_=ve(y);_.current=y;const j=ve(g);j.current=g;const T=ie(()=>{var E;(E=v.current)==null||E.focus()},[]);return Xc(x,()=>({sendInput(E){const $=C.current;$&&$.readyState===WebSocket.OPEN&&($.send(JSON.stringify({type:"input",data:E})),setTimeout(()=>{$.readyState===WebSocket.OPEN&&$.send(JSON.stringify({type:"input",data:"\r"}))},100))},focus(){var E;(E=v.current)==null||E.focus()},scrollToBottom(){var $;const E=($=b.current)==null?void 0:$.querySelector(".xterm-viewport");E&&(E.scrollTop=E.scrollHeight)}})),ne(()=>{const E=b.current;if(!E)return;let $=!1;return xh(),Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit"),import("@xterm/addon-web-links")]).then(([R,I,W])=>{if($)return;const Y=new R.Terminal({cursorBlink:!0,scrollback:5e3,fontSize:13,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78"},linkHandler:{activate(X,L){try{const O=new URL(L),z=O.searchParams.get("scenario");if(z&&O.pathname==="/editor"){const G=new BroadcastChannel("codeyam-editor");G.postMessage({type:"switch-scenario",scenarioId:z}),G.close();return}}catch{}window.open(L,"_blank")}}}),U=new I.FitAddon;Y.loadAddon(U),Y.loadAddon(new W.WebLinksAddon),Y.open(E);let B=null;gh(Y,(X,L,O)=>{console.warn(`[Terminal] Renderer fallback: ${X} → ${L}`,O)}).then(X=>{if($){X.dispose();return}console.log(`[Terminal] Using ${X.type} renderer`),B=X.dispose}),requestAnimationFrame(()=>{try{U.fit()}catch{}}),v.current=Y,Y.focus(),setTimeout(()=>Y.focus(),100),setTimeout(()=>Y.focus(),500);const H=window.location.protocol==="https:"?"wss:":"ws:",D=window.location.host;function A(X){const L=new URLSearchParams;return L.set("entityName",t),r&&L.set("entityType",r),s&&L.set("entitySha",s),a&&L.set("entityFilePath",a),o&&L.set("scenarioName",o),i&&L.set("scenarioDescription",i),l&&L.set("analysisId",l),c&&L.set("projectSlug",c),f&&L.set("editorMode","true"),X&&L.set("reconnectId",X),`${H}//${D}/ws/terminal?${L.toString()}`}function J(X){const L=A(X),O=new WebSocket(L);C.current=O,O.onopen=()=>{S.current=0,k.current=!1,O.send(JSON.stringify({type:"resize",cols:Y.cols,rows:Y.rows}))},O.onmessage=z=>{var G,ee;try{const re=JSON.parse(z.data);if(re.type==="session-id"){P.current=re.sessionId;return}if(re.type==="refresh-preview"){m==null||m(re.path,re.scenarioId);return}if(re.type==="show-results"){u==null||u();return}if(re.type==="hide-results"){p==null||p();return}if(re.type==="set-viewport"){h==null||h({name:re.name,width:re.width,height:re.height});return}if(re.type==="claude-idle"){if(console.log("[Terminal] Received claude-idle, notifications:",j.current,"permission:",typeof Notification<"u"?Notification.permission:"N/A"),(G=_.current)==null||G.call(_,!0),j.current&&typeof Notification<"u"&&Notification.permission==="granted"){const ue=new Notification("Claude is ready for you",{body:"Claude has finished and is waiting for your input.",tag:"claude-idle"});ue.onclick=()=>{window.focus(),ue.close()}}return}re.type==="output"&&(Y.write(re.data),(ee=_.current)==null||ee.call(_,!1))}catch{Y.write(z.data)}},O.onclose=()=>{if(N.current){Y.write(`\r
|
|
112
|
-
\x1B[90m[Terminal session ended]\x1B[0m\r
|
|
113
|
-
`);return}const z=S.current;if(z<5&&P.current){const G=1e3*Math.pow(2,Math.min(z,3));S.current=z+1,Y.write(`\r
|
|
114
|
-
\x1B[33m[Reconnecting...]\x1B[0m\r
|
|
115
|
-
`),setTimeout(()=>{N.current||J(P.current)},G)}else k.current?Y.write(`\r
|
|
116
|
-
\x1B[90m[Terminal session ended]\x1B[0m\r
|
|
117
|
-
`):(k.current=!0,Y.write(`\r
|
|
118
|
-
\x1B[33m[Starting new session...]\x1B[0m\r
|
|
119
|
-
`),P.current=null,S.current=0,J())},O.onerror=()=>{}}J(),Y.onData(X=>{const L=C.current;L&&L.readyState===WebSocket.OPEN&&L.send(JSON.stringify({type:"input",data:X}))});let V=null;const q=new ResizeObserver(()=>{V&&clearTimeout(V),V=setTimeout(()=>{let X;try{X=U.proposeDimensions()}catch{return}if(!X||X.cols===Y.cols&&X.rows===Y.rows)return;const L=E.querySelector(".xterm-viewport");let O,z=!0;L&&(O=L.scrollTop,z=L.scrollTop+L.clientHeight>=L.scrollHeight-10),U.fit(),L&&O!==void 0&&(z?L.scrollTop=L.scrollHeight:L.scrollTop=O);const G=C.current;G&&G.readyState===WebSocket.OPEN&&G.send(JSON.stringify({type:"resize",cols:Y.cols,rows:Y.rows}))},150)});q.observe(E),w.current=()=>{var X;V&&clearTimeout(V),q.disconnect(),N.current=!0,(X=C.current)==null||X.close(),C.current=null,B==null||B(),Y.dispose(),v.current=null}}),()=>{var R;$=!0,(R=w.current)==null||R.call(w),w.current=null}},[]),n("div",{ref:b,onClick:T,className:"w-full h-full",style:{padding:"4px 0 0 8px"}})});function Ze({screenshotPath:e,cacheBuster:t,alt:r,className:s="",title:a}){const[o,i]=M("loading"),[l,c]=M(!1),m=ve(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,p=()=>{i("success"),c(!0)},h=()=>{i("error"),c(!1)};return ne(()=>{i("loading"),c(!1);const f=m.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),c(!0)):(i("error"),c(!1)))},[u]),e?d("div",{className:"relative w-full h-full flex items-center justify-center",title:a,children:[n("img",{ref:m,src:u,alt:r,onLoad:p,onError:h,className:s||"max-w-full max-h-full object-contain",style:{visibility:l?"visible":"hidden",position:l?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&d("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:a,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}function bh({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 c,m;const i=o.id===t,l=(m=(c=o.metadata)==null?void 0:c.screenshotPaths)==null?void 0:m[0];return d("button",{onClick:()=>{a(`/entity/${r}/scenarios/${o.id}/dev`)},className:`w-full text-left rounded-lg overflow-hidden border transition-colors cursor-pointer flex ${i?"border-[#005c75] bg-[#1a3a44]":"border-[#3d3d3d] bg-[#252525] hover:border-[#555]"}`,children:[n("div",{className:"w-24 h-20 shrink-0 bg-[#1a1a1a]",children:n(Ze,{screenshotPath:l,cacheBuster:s,alt:o.name,className:"w-full h-full object-cover object-top"})}),d("div",{className:"p-2.5 min-w-0 flex-1",children:[d("div",{className:"text-white text-sm font-medium truncate",children:[i&&n("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-[#005c75] mr-1.5 relative top-[-1px]"}),o.name]}),o.description&&n("div",{className:"text-gray-400 text-xs mt-1 line-clamp-2",children:o.description})]})]},o.id)})})}function yt(e,t){const r=new Map;for(const s of e)r.set(t(s),s);return[...r.values()]}function Ct(e){return e.replace(/[^a-zA-Z0-9_]+/g,"_")}function La(e){return e.replace("T"," ").replace(/\.\d{3}Z$/,"")}const wh=["defaultScreenSize","screenSizes","projectTitle","projectDescription"];function VC(e){try{const t=JSON.parse(fe.readFileSync(e,"utf8")),r={};for(const s of wh)t[s]!==void 0&&(r[s]=t[s]);return r}catch{return{}}}function na(e,t,r){const s=e&&e.startsWith("/");return s&&t?`${t}${e}`:e&&!s?e:t||r||null}function vh(e){var t,r;try{const s=Z.join(e,".codeyam","config.json"),a=JSON.parse(fe.readFileSync(s,"utf8"));if((t=a.defaultScreenSize)!=null&&t.width&&((r=a.defaultScreenSize)!=null&&r.height))return{width:a.defaultScreenSize.width,height:a.defaultScreenSize.height}}catch{}return null}function Nh(e){try{const t=Z.join(e,".codeyam","config.json"),r=JSON.parse(fe.readFileSync(t,"utf8"));if(r.screenSizes&&typeof r.screenSizes=="object"&&!Array.isArray(r.screenSizes))return r.screenSizes}catch{}return{}}function Ch(e){var t,r;return{width:e.bodyWidth||((t=e.projectDefault)==null?void 0:t.width)||1280,height:e.bodyHeight||((r=e.projectDefault)==null?void 0:r.height)||720}}function zr(e){let t=null;if(e.dimension){const a=Nh(e.codeyamRoot)[e.dimension];a!=null&&a.width&&(a!=null&&a.height)&&(t={width:a.width,height:a.height})}const r=t||vh(e.codeyamRoot);return Ch({bodyWidth:e.bodyWidth,bodyHeight:e.bodyHeight,projectDefault:r})}async function Sh(e,t){const r=await e.selectFrom("editor_scenarios").selectAll().where("name","=",t.name).where("project_id","=",t.projectId).orderBy("created_at","desc").execute();if(r.length>0){const o=r[0].id;await e.updateTable("editor_scenarios").set({description:t.description,component_name:t.componentName,component_path:t.componentPath,url:t.url,type:t.type,viewport_width:t.viewportWidth,viewport_height:t.viewportHeight,dimension:t.dimension}).where("id","=",o).execute();const i=r.slice(1).map(l=>l.id);return i.length>0&&await e.deleteFrom("editor_scenarios").where("id","in",i).execute(),{scenarioId:o,isNew:!1,cleanedUpIds:i}}const s=globalThis.crypto.randomUUID();return await e.insertInto("editor_scenarios").values({id:s,project_id:t.projectId,name:t.name,description:t.description,component_name:t.componentName,component_path:t.componentPath,url:t.url,type:t.type,viewport_width:t.viewportWidth,viewport_height:t.viewportHeight,dimension:t.dimension}).execute(),{scenarioId:s,isNew:!0,cleanedUpIds:[]}}function kh(e,t){const r=Z.join(e,".codeyam","editor-scenarios");for(const s of t)for(const a of[`${s}.json`,`${s}.seed.json`,Z.join("screenshots",`${s}.png`)])try{fe.unlinkSync(Z.join(r,a))}catch{}}function Eh(e){const{activeAnalyzedScenario:t,analyzedPreviewUrl:r,activeScenarioId:s,scenarios:a,proxyUrl:o,devServerUrl:i,zoomComponent:l}=e;if(t&&r)return r;if(t&&!r)return null;if(s){const 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 c=o||i;if(!c)return null;if(l&&s){const m=a.find(p=>p.id===s),u=m?Ct(m.name):"Default";return`${c}/__codeyam__/${l}/${u}`}return c}function Pl(e,t){if(!e||!t)return e;try{const r=new URL(e),s=t.indexOf("?");return s>=0?(r.pathname=t.slice(0,s),r.search=t.slice(s)):(r.pathname=t,r.search=""),r.href}catch{return e}}function _h(e,t){return e?e!==t:!1}function Ah(e,t){const r=t.width,s=t.height??900,a=e.width,o=e.height;return r<=a&&s<=o?1:Math.min(a/r,o/s)}async function Ph({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw Q("Invalid parameters",{status:400});const s=await dn(t);if(!s)throw Q("Entity not found",{status:404});const a=await es(s),o=((l=a==null?void 0:a.scenarios)==null?void 0:l.find(c=>c.id===r))||null;if(!o)throw Q("Scenario not found",{status:404});const i=await Ie();return Q({entity:s,scenario:o,analysis:a,projectSlug:i})}const Ls=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],jh=Je(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=qe(),o=St(),i=ve(null),l=ve(null),[c,m]=M(null),[u,p]=M(1440),[h,f]=M({name:"Desktop",width:1440,height:900}),[y,g]=M(!1),[x,b]=M(null),[w,v]=M("chat"),[C,P]=M(0),[N,S]=M(null),k=ie(se=>{S(se||null),P(pe=>pe+1)},[]),{customSizes:_,addCustomSize:j}=cs(a),T=ae(()=>[...Ls,..._],[_]),{interactiveServerUrl:E,isStarting:$,isLoading:R,showIframe:I,iframeKey:W,onIframeLoad:Y}=pn({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:C}),U=ae(()=>Pl(E,N),[E,N]),{lastLine:B}=_t(a,$||R),H=()=>{o(`/entity/${t.sha}`)},D=(se,pe)=>{p(se);const Ce=T.find(Ae=>Ae.width===se&&Ae.height===pe);m(Ce||null),f({name:(Ce==null?void 0:Ce.name)||"Custom",width:se,height:pe})},A=se=>{m(se),p(se.width),f({name:se.name,width:se.width,height:se.height})},J=se=>{j(se,h.width,h.height??900),g(!1),f(pe=>({...pe,name:se}))},V=()=>{var pe;v("chat"),(pe=l.current)==null||pe.sendInput("Create a new scenario for this entity based on the work we've just done. Create a name and description that reflects what the live preview is showing. Use the scenario data you've changed to create a new scenario in the database. If the data structure was fixed in any way you need to update that in the database as well and backfill all existing scenarios, then save to the database and capture a screenshot. Remember the database is at `.codeyam/db.sqlite3`, the scenarios table has all scenarios and the analyses table contains the scenariosDataStructure is its metadata.")},q=((s==null?void 0:s.scenarios)||[]).filter(se=>{var pe;return!((pe=se.metadata)!=null&&pe.sameAsDefault)}),X=q.findIndex(se=>se.id===(r==null?void 0:r.id)),L=X+1,O=q.length,z=X>0,G=X<q.length-1,ee=()=>{if(z){const se=q[X-1];o(`/entity/${t.sha}/scenarios/${se.id}/dev`)}},re=()=>{if(G){const se=q[X+1];o(`/entity/${t.sha}/scenarios/${se.id}/dev`)}},ue=$||R||!I;return d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[d("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:qr,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),d("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:ee,disabled:!z,className:`${z?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),d("span",{className:"text-gray-400 text-sm",children:[L,"/",O]}),n("button",{onClick:re,disabled:!G,className:`${G?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),d("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&d("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]}),n("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:H,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close dev mode",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),d("div",{className:"flex-1 flex min-h-0",children:[d("div",{className:"flex-1 flex flex-col min-w-0",children:[d("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Ls[Ls.length-1].width}px`,width:"100%"},children:n(Oa,{currentViewportWidth:u,currentPresetName:h.name,onDevicePresetClick:A,devicePresets:T,hideLabel:!0,onHoverChange:b,lightMode:!0})})}),d("div",{className:"relative z-10 flex items-center gap-2",children:[d("div",{className:"relative w-28 h-5",children:[d("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(x==null?void 0:x.name)||h.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),d("select",{value:h.name,onChange:se=>{const pe=T.find(Ce=>Ce.name===se.target.value);pe&&A(pe)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[T.map(se=>n("option",{value:se.name,children:se.name},se.name)),h.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:h.width,onChange:se=>{const pe=parseInt(se.target.value,10);!isNaN(pe)&&pe>0&&D(pe,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:"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:h.height??900}),h.name==="Custom"&&n("button",{onClick:()=>g(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
|
|
120
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
121
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
122
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
123
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
124
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:E?d("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${h.width}px`,maxHeight:`${h.height}px`},children:[ue&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the dev server to be ready"}),B&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Nn,{}),B]})]})]})}),n("iframe",{ref:i,src:U||E,className:"w-full h-full border-none",title:`Dev mode preview: ${r==null?void 0:r.name}`,onLoad:Y,style:{opacity:I?1:0}},W)]}):d("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Dev Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment with live preview"}),B&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Nn,{}),B]})]})]})})]}),d("aside",{className:"w-[50%] min-w-[400px] max-w-[800px] bg-[#1e1e1e] border-l border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden",children:[d("div",{className:"border-b border-[#3d3d3d] px-4 shrink-0 flex items-center justify-between",children:[d("div",{className:"flex items-center gap-0",children:[d("button",{onClick:()=>v("chat"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${w==="chat"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Chat",w==="chat"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),d("button",{onClick:()=>v("scenarios"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${w==="scenarios"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Scenarios",w==="scenarios"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]})]}),w==="chat"&&n("button",{onClick:V,disabled:!E,className:"px-3 py-1 text-[11px] font-medium rounded bg-[#005c75] text-white hover:bg-[#004a5c] transition-colors disabled:bg-gray-600 disabled:text-gray-400 disabled:cursor-not-allowed cursor-pointer",children:"Save Scenario"})]}),n("div",{style:{display:w==="chat"?"flex":"none"},className:"flex-1 overflow-hidden flex-col",children:n(Al,{ref:l,entityName:t.name,entityType:t.entityType,entitySha:t.sha,entityFilePath:t.filePath||t.localFilePath,scenarioName:r==null?void 0:r.name,scenarioDescription:r==null?void 0:r.description,analysisId:s==null?void 0:s.id,projectSlug:a,onRefreshPreview:k})}),w==="scenarios"&&n(bh,{scenarios:q,currentScenarioId:r==null?void 0:r.id,entitySha:t.sha,cacheBuster:0})]})]}),n(_l,{serverUrl:E,isStarting:$,projectSlug:a}),y&&n(ls,{width:h.width,height:h.height??900,onSave:J,onCancel:()=>g(!1)})]})}),Mh=Object.freeze(Object.defineProperty({__proto__:null,default:jh,loader:Ph},Symbol.toStringTag,{value:"Module"}));async function Th({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{url:r,filename:s,viewportWidth:a,viewportHeight:o}=t;if(!r||!s)return new Response(JSON.stringify({error:"url and filename are required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=process.env.CODEYAM_ROOT_PATH||process.cwd(),l=F.join(i,".codeyam","journal","screenshots");await we.mkdir(l,{recursive:!0});const c=s.replace(/[^a-zA-Z0-9_\-T]/g,"_"),m=F.join(l,`${c}.png`),u=F.dirname(new URL(import.meta.url).pathname);let p=u;for(let w=0;w<5;w++){const v=F.dirname(p);if(F.basename(v)==="webserver"||F.basename(p)==="webserver"){p=F.basename(p)==="webserver"?p:v;break}p=v}const h=[F.join(p,"scripts","journalCapture.ts"),F.join(p,"app","lib","journalCapture.ts"),F.join(i,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),F.resolve(u,"..","lib","journalCapture.ts")];let f="";for(const w of h)try{await we.access(w),f=w;break}catch{}f||(console.warn(`[editor-journal-screenshot] journalCapture.ts not found in any of: ${h.join(", ")}`),f=h[0]);const y=zr({bodyWidth:a,bodyHeight:o,codeyamRoot:i}),g=JSON.stringify({url:r,outputPath:m,viewportWidth:y.width,viewportHeight:y.height}),x=await new Promise(w=>{const v=Et("npx",["tsx",f,g],{cwd:i,env:{...process.env}});let C="",P="";v.stdout.on("data",N=>{C+=N.toString()}),v.stderr.on("data",N=>{P+=N.toString()}),v.on("close",N=>{w(N===0?{success:!0,output:C}:{success:!1,output:C,error:P||`Process exited with code ${N}`})}),v.on("error",N=>{w({success:!1,output:"",error:N.message})})});if(!x.success)return new Response(JSON.stringify({error:"Failed to capture screenshot",details:x.error}),{status:500,headers:{"Content-Type":"application/json"}});const b=`screenshots/${c}.png`;return new Response(JSON.stringify({success:!0,path:b}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-screenshot] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const $h=Object.freeze(Object.defineProperty({__proto__:null,action:Th},Symbol.toStringTag,{value:"Module"})),jl=ya({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),Fa=()=>{const e=Jr(jl);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},ds=({children:e})=>{const[t,r]=M({height:720,width:1200}),[s,a]=M(1),[o,i]=M(1200),l=ve(null),c=ie(({height:p,width:h})=>{r(f=>({height:p??f.height,width:h??f.width}))},[]),m=ie(p=>{a(p)},[]),u=ie(p=>{i(p)},[]);return n(jl.Provider,{value:{dimensions:t,updateDimensions:c,iframeRef:l,scale:s,updateScale:m,maxWidth:o,updateMaxWidth:u},children:e})},Ih=typeof window<"u";function Rh(){const[e,t]=M(null);return ne(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const Dh=1200,Oh=720,Bo=30,Lh=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:s=1440,defaultHeight:a=900,onDataOverride:o,onIframeLoad:i,onScaleChange:l,onDimensionChange:c})=>{const m=Rh(),[u,p]=M(!1),[h,f]=M(!1),[y,g]=M(Dh),[x,b]=M(Oh),[w,v]=M(null),[C,P]=M(null),{dimensions:N,updateDimensions:S,iframeRef:k,updateScale:_,updateMaxWidth:j}=Fa(),T=ae(()=>Math.min(1,y/N.width),[y,N.width]),E=C!==null?C:T;ne(()=>{u||(_(E),l==null||l(E))},[E,_,l,u]),ne(()=>{j(y)},[y,j]);const $=ie(()=>{p(!0),P(T)},[T]),R=ie(()=>{p(!1),P(null)},[]),I=ie((H,D)=>{const A=C!==null?C:1,J=Math.round(D.size.width/A);S({width:J}),c==null||c(J,N.height)},[S,C,c,N.height]),W=ie(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);ne(()=>{const H=D=>{if(D.data.type==="codeyam-resize"){if(t&&D.data.name!==t||N.height===D.data.height||D.data.height===0)return;S({height:D.data.height})}};return window.addEventListener("message",H),()=>{window.removeEventListener("message",H)}},[k,t,s,N,S]),ne(()=>{h&&o&&o(k.current)},[h,o,k]),ne(()=>{if(!t)return;const H=setInterval(()=>{var D,A;(A=(D=k==null?void 0:k.current)==null?void 0:D.contentWindow)==null||A.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(H)},[t,k]),ne(()=>{const H=()=>{const D=document.getElementById("scenario-container");if(!D)return;const A=D.getBoundingClientRect(),J=D.clientWidth-Bo*2,V=window.innerHeight-A.top-Bo*2,q=Math.max(V,400),X=window.innerHeight-A.top;g(J),b(q),v(X)};return H(),window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[]),ne(()=>{S({width:s,height:a})},[s,a,S]);const Y=ae(()=>N.width*E,[N.width,E]),U=ae(()=>{const H=N.height,D=H*E;return H&&H!==720&&H!==900&&D<x?D:x},[N.height,x,E]),B=ie(()=>{window.history.back()},[]);return!Ih||!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..."})}):d("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:w?{height:`${w}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
|
|
125
|
-
.react-resizable-handle-e {
|
|
126
|
-
display: flex !important;
|
|
127
|
-
align-items: center !important;
|
|
128
|
-
justify-content: center !important;
|
|
129
|
-
width: 6px !important;
|
|
130
|
-
height: 48px !important;
|
|
131
|
-
right: -8px !important;
|
|
132
|
-
top: 50% !important;
|
|
133
|
-
transform: translateY(-50%) !important;
|
|
134
|
-
cursor: ew-resize !important;
|
|
135
|
-
background: #d1d5db !important;
|
|
136
|
-
border-radius: 3px !important;
|
|
137
|
-
opacity: 0 !important;
|
|
138
|
-
transition: all 0.2s ease !important;
|
|
139
|
-
}
|
|
140
|
-
.react-resizable-handle-e:hover {
|
|
141
|
-
opacity: 0.8 !important;
|
|
142
|
-
background: #9ca3af !important;
|
|
143
|
-
}
|
|
144
|
-
.react-resizable:hover .react-resizable-handle-e {
|
|
145
|
-
opacity: 0.4 !important;
|
|
146
|
-
}
|
|
147
|
-
`}),n(m,{width:Y,height:U,minConstraints:[300,200],maxConstraints:[y,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:$,onResizeStop:R,onResize:I,children:n("div",{className:"overflow-auto",style:{width:`${Y}px`,height:`${U}px`},children:n("div",{style:{width:`${N.width}px`,height:`${N.height}px`,transform:`scale(${E})`,transformOrigin:"top left"},children:r?n("iframe",{ref:k,className:"w-full h-full rounded-lg",src:r,onLoad:W,sandbox:"allow-scripts allow-same-origin"}):d("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[n("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),n("span",{className:"text-blue-600 cursor-pointer",onClick:B,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function Fh({presets:e,customSizes:t,currentWidth:r,currentHeight:s,scale:a,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:l,className:c=""}){const[m,u]=M(!1),[p,h]=M(String(r)),[f,y]=M(String(s)),[g,x]=M(!1),[b,w]=M(!1),v=ve(null);ne(()=>{g||h(String(r))},[r,g]),ne(()=>{b||y(String(s))},[s,b]),ne(()=>{const E=$=>{v.current&&!v.current.contains($.target)&&u(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[]);const C=ae(()=>{const E=e.find(R=>R.width===r&&R.height===s);if(E)return E.name;const $=t.find(R=>R.width===r&&R.height===s);return $?$.name:"Custom"},[e,t,r,s]),P=C==="Custom",N=E=>{o(E.width,E.height),u(!1)},S=E=>{const $=E.target.value;h($);const R=parseInt($,10);!isNaN(R)&&R>0&&o(R,s)},k=E=>{const $=E.target.value;y($);const R=parseInt($,10);!isNaN(R)&&R>0&&o(r,R)},_=()=>{x(!1);const E=parseInt(p,10);(isNaN(E)||E<=0)&&h(String(r))},j=()=>{w(!1);const E=parseInt(f,10);(isNaN(E)||E<=0)&&y(String(s))},T=E=>{(E.key==="Enter"||E.key==="Escape")&&E.target.blur()};return d("div",{className:`flex items-center gap-3 ${c}`,children:[d("div",{className:"relative",ref:v,children:[d("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:C}),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:d("div",{className:"py-1",children:[e.length>0&&d(de,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(E=>d("button",{onClick:()=>N(E),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${C===E.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:E.name}),d("span",{className:"text-xs text-gray-500",children:[E.width," x ",E.height]})]},E.name))]}),t.length>0&&d(de,{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((E,$)=>E.width-$.width).map(E=>d("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${C===E.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[d("button",{onClick:()=>N(E),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:E.name}),d("span",{className:"text-xs text-gray-500",children:[E.width," x ",E.height]})]}),l&&n("button",{onClick:$=>{$.stopPropagation(),C===E.name&&e.length>0&&o(e[0].width,e[0].height),l(E.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"})})})]},E.name))]})]})})]}),d("div",{className:"flex items-center gap-1 text-sm",children:[d("div",{className:"flex items-center",children:[n("input",{type:"text",value:p,onChange:S,onFocus:()=>x(!0),onBlur:_,onKeyDown:T,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),d("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:k,onFocus:()=>w(!0),onBlur:j,onKeyDown:T,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),a!==void 0&&a<1&&d("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(a*100),"%)"]})]}),P&&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 Fs(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 ra(e){return e&&(typeof e=="object"||Array.isArray(e))}function zh(e){return Array.isArray(e)?e.length:void 0}function Bh(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=ra(t[a]),l=ra(t[o]);return i&&!l?1:!i&&l?-1:a.localeCompare(o)});if(typeof t=="object")return Object.keys(t).sort((a,o)=>a.localeCompare(o))}}function Yh({scenarioFormData:e,handleInputChange:t}){return d("div",{className:"p-3 flex flex-col gap-3",children:[d("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),n("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),d("div",{className:"grid w-full gap-1.5 pt-2",children:[n("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),n("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[100px]"})]}),n("button",{type:"submit",className:"mt-3 w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium",children:"Save Name & Description"})]})}function Uh({path:e,namedPath:t,isArray:r,count:s,onClick:a}){const o=ie(()=>{a&&a(e)},[a,e]);return d("div",{className:"bg-blue-50 p-3 rounded-lg flex items-center justify-between cursor-pointer group hover:bg-blue-100 transition-colors border border-blue-200",onClick:o,children:[d("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),d("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],s!==void 0&&` (${s})`]})]}),d("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var Ml=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Ml||{});const Wh=({name:e,value:t,options:r,onChange:s})=>{const a=ie(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))})},Hh=({name:e,value:t,onChange:r})=>{const s=ie(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
|
|
148
|
-
bg-gray-300 checked:bg-blue-600
|
|
149
|
-
after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
|
|
150
|
-
after:bg-white after:rounded-full after:transition-transform
|
|
151
|
-
checked:after:translate-x-4`})})};function Jh({dataType:e,path:t,value:r,onChange:s}){const a=ae(()=>t[t.length-1],[t]),o=ae(()=>t.join("-"),[t]),i=ie(c=>{s(t,c.target.value)},[s,t]),l=ie(c=>{s(t,c.target.value)},[s,t]);return d("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:o,className:"capitalize text-sm font-medium text-gray-700",children:a==="~~codeyam-code~~"?"Dynamic Field":a}),e.includes("|")?n(Wh,{name:o,value:r,options:e.split("|"),onChange:i}):e===Ml.BOOLEAN?n(Hh,{name:o,value:r??!1,onChange:l}):n("input",{id:o,name:o,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${o}`)]})}function Vh({analysis:e,scenarioName:t,dataItem:r,onResult:s,onGenerateData:a}){const[o,i]=M(!1),[l,c]=M(""),m=ie(async()=>{if(!a){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const p=e.scenarios.find(x=>x.name===t);if(!p)throw new Error("Scenario not found");const h=e.scenarios.find(x=>x.name===Zr),f=await a(l,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const y=(x,b)=>{const w=Object.assign({},x);return g(x)&&g(b)&&Object.keys(b).forEach(v=>{g(b[v])?v in x?w[v]=y(x[v],b[v]):Object.assign(w,{[v]:b[v]}):Object.assign(w,{[v]:b[v]})}),w},g=x=>x&&typeof x=="object"&&!Array.isArray(x);p.metadata.data=y(y((h==null?void 0:h.metadata.data)||{},p.metadata.data),f.data||{}),s(p),i(!1),c("")}catch(p){console.error("Error generating AI data:",p),i(!1)}},[e,l,r,t,s,a]),u=ie(p=>{c(p.target.value)},[]);return d("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:l}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${l.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void m(),children:o?d(de,{children:[d("svg",{className:"animate-spin h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Please wait"]}):"Generate Data"})]})}function Gh({namedPath:e,path:t,last:r,onClick:s}){const a=ie(()=>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 Kh({dataItem:e,onClick:t}){const r=ie(()=>t([]),[t]),s=ae(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return d("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&d("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(s).map((a,o)=>d("div",{className:"flex items-center gap-1",children:[n(Gh,{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 Yo({analysis:e,scenarioName:t,dataItem:r,onClick:s,onChange:a,onAIResult:o,onGenerateData:i,saveFeedback:l}){const c=ae(()=>r.data,[r]),m=ae(()=>Bh(r),[r]);return d("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(Kh,{dataItem:r,onClick:s}),d("div",{className:"flex flex-col gap-3",children:[n(Vh,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),m==null?void 0:m.map((u,p)=>{var f;if(ra(c[u])){let y=u;isNaN(Number(u))||(y=c[u].name??c[u].title??c[u].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const g=[...r.path,u],x=[...r.namedPath,y];return n(Uh,{path:g,namedPath:x,isArray:Array.isArray(c),count:zh(c[u]),onClick:s},`data-${u}-${p}`)}if(u==="id")return null;const h=[...r.path,u];return n(Jh,{dataType:((f=r.structure)==null?void 0:f[u])??"string",path:h,value:c[u],onChange:a},`InputField-${h.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),d("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:l!=null&&l.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save & Recapture"})]}),(l==null?void 0:l.message)&&!(l!=null&&l.isSaving)&&n("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${l.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:l.message})]})}function Uo({title:e,children:t,defaultOpen:r=!1,borderT:s=!1,borderB:a=!1}){const[o,i]=M(r),l=[];return s&&l.push("border-t"),a&&l.push("border-b"),d("div",{className:`${l.join(" ")} border-gray-300`,children:[d("button",{type:"button",onClick:()=>i(!o),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${o?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),o&&n("div",{className:"px-4 py-3",children:t})]})}const qh=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:s,shouldCreateNewScenario:a,onSave:o,onNavigate:i,iframeRef:l,onGenerateData:c,saveFeedback:m})=>{const u=ie((S,k)=>{const _=Object.assign({},S),j=T=>T&&typeof T=="object"&&!Array.isArray(T);return j(S)&&j(k)&&Object.keys(k).forEach(T=>{j(k[T])?T in S?_[T]=u(S[T],k[T]):Object.assign(_,{[T]:k[T]}):Object.assign(_,{[T]:k[T]})}),_},[]),[p,h]=M({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,y]=M(null),g=ae(()=>({...p.data}),[p]),x=ae(()=>({...g.mockData?{"Retrieved Data":g.mockData}:{},...g.argumentsData?{"Function Arguments":g.argumentsData}:{}}),[g]),b=ae(()=>{const S={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(S).reduce((k,_)=>{if(_.includes(".")){const[j,T]=_.split(".");k[j]||(k[j]={}),k[j][T]=S[_]}else k[_]=S[_];return k},{})},[r]),w=ie(async S=>{S.preventDefault();const k=S.target.querySelector('input[name="recapture"]'),_=(k==null?void 0:k.value)==="true",j={mockData:p.data.mockData??{},argumentsData:p.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:p.name,shouldRecapture:_,dataToSave:j,rawFormData:p.data,iframePayload:{arguments:g.argumentsData??[],...g.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(j,null,2).substring(0,1e3));const T=s==null?void 0:s.scenarios.map(E=>!a&&E.name===e.name?{...E,name:p.name,description:p.description,metadata:{...E.metadata,data:j}}:E);a&&T.push({name:p.name,description:p.description,metadata:{data:j,interactiveExamplePath:s==null?void 0:s.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",T),o&&await o(T,{recapture:_}),i&&i(p.name)},[s,e.name,p,g,a,o,i]),v=ie(S=>{h(k=>({...k,[S.target.name]:S.target.value}))},[]),C=ie(S=>{y(k=>{if(!k)return null;for(const _ of[{arguments:S.metadata.data.argumentsData},S.metadata.data.mockData]){let j=_;for(const T of k.path)if(j=Fs(j,T),!j)break;j&&(k.data=j)}return{...k}}),h({name:S.name,description:S.description,data:S.metadata.data})},[]),P=ie((S,k)=>{h(_=>{for(const j of[{"Function Arguments":_.data.argumentsData},{"Retrieved Data":_.data.mockData}]){let T=j;for(const E of S.slice(0,-1))if(T=Fs(T,E),!T)break;if(T){const E=T[S[S.length-1]];y($=>$?($.namedPath[$.namedPath.length-1]===E&&($.namedPath[$.namedPath.length-1]=k.toString()),$.data[S[S.length-1]]=k,{...$}):null),T[S[S.length-1]]=k}}return{..._}})},[]),N=ie(S=>{var T,E,$;if(S.length===0){y(null);return}let k=x;const _=[];let j=b;for(const R of S){if(_.push(isNaN(parseInt(R))?R:((T=k[R])==null?void 0:T.name)??((E=k[R])==null?void 0:E.title)??(($=k[R])==null?void 0:$.id)??R),k=Fs(k,R),!k){console.log("Data not found",k,R),y(null);return}Array.isArray(j)?j=j[0]:j=j[R]}y({path:S,namedPath:_,data:k,structure:j})},[x,b]);return ne(()=>{const S=k=>{var _;k.data.type==="codeyam-log"&&((_=k.data.data)!=null&&_.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",k.data.data)};return window.addEventListener("message",S),()=>window.removeEventListener("message",S)},[]),ne(()=>{var S;if((S=l==null?void 0:l.current)!=null&&S.contentWindow){const k={arguments:g.argumentsData??[],...g.mockData??{}},_={type:"codeyam-override-data",name:e.name,data:JSON.stringify(k)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:_.type,name:_.name,dataPreview:JSON.stringify(k).substring(0,200)+"...",fullData:k}),l.current.contentWindow.postMessage(_,"*")}},[g,e,l]),n("form",{method:"post",onSubmit:S=>void w(S),children:f?n(Yo,{analysis:s,scenarioName:p.name,dataItem:f,onClick:N,onChange:P,onAIResult:C,onGenerateData:c,saveFeedback:m}):d(de,{children:[n(Uo,{title:"Edit Name and Description",borderT:!0,children:n(Yh,{scenarioFormData:p,handleInputChange:v})}),e.metadata.data&&n(Uo,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(Yo,{analysis:s,scenarioName:p.name,dataItem:{path:[],namedPath:[],data:x,structure:b},onClick:N,onChange:P,onAIResult:C,onGenerateData:c,saveFeedback:m})})]})})};function us({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:s,isLoading:a,showIframe:o,iframeKey:i,onIframeLoad:l,onScaleChange:c,onDimensionChange:m,projectSlug:u,defaultWidth:p=1440,defaultHeight:h=900,retryCount:f=0}){const{lastLine:y}=_t(u??null,s||a);return r?d("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:o?1:0,background:"transparent"},children:n(Lh,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:p,defaultHeight:h,onIframeLoad:l,onScaleChange:c,onDimensionChange:m},i)}),!o&&(s||a)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Nn,{}),y]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center",children:d("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Nn,{}),y]})]})]})})}const Qh=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Zh({params:e}){var c,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 Xr(t,!0),a=s&&s.length>0?s[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const o=(c=a.scenarios)==null?void 0:c.find(u=>u.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=(m=a.scenarios)==null?void 0:m.find(u=>u.name===Zr),l=await Ie();return Q({analysis:a,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:l})}function Xh(){var R,I,W;const e=qe(),t=e.analysis,r=e.scenario,s=e.defaultScenario,a=e.entitySha,o=e.projectSlug,i=St(),{iframeRef:l}=Fa(),[c,m]=M(!1),[u,p]=M(null),[h,f]=M(null),[y,g]=M(!1),[x,b]=M(!1),[w,v]=M(null),{interactiveServerUrl:C,isStarting:P,isLoading:N,showIframe:S,iframeKey:k,onIframeLoad:_}=pn({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}),j=ie(async(Y,U)=>{m(!0),p(null),f(null),console.log("[EditScenario] Starting save with options:",U),console.log("[EditScenario] Scenarios to save:",Y);try{const B={analysis:t,scenarios:Y};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:Y.length,scenarioNames:Y.map(A=>A.name)});const H=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)}),D=await H.json();if(console.log("[EditScenario] API response:",D),!H.ok||!D.success)throw new Error(D.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),U!=null&&U.recapture&&r.id&&C){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:C}),p("Changes saved. Capturing screenshot...");const A={serverUrl:C,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",A);const J=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});console.log("[EditScenario] Capture response status:",J.status);const V=await J.json();if(console.log("[EditScenario] Capture response body:",V),!J.ok||!V.success)throw console.error("[EditScenario] Capture failed:",V),new Error(V.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",V),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),p("Recapture successful")}else if(U!=null&&U.recapture&&!C){console.log("[EditScenario] No running server, using queued recapture");const A=new FormData;A.append("analysisId",t.id||""),A.append("scenarioId",r.id||"");const J=await fetch("/api/recapture-scenario",{method:"POST",body:A}),V=await J.json();if(!J.ok||!V.success)throw new Error(V.error||"Failed to trigger recapture");console.log("Recapture queued:",V),f(V.jobId),p("Changes saved. Screenshot recapture queued.")}else p("Changes saved successfully.")}catch(B){console.error("Error saving scenarios:",B),p(`Error: ${B instanceof Error?B.message:String(B)}`)}finally{m(!1)}},[t,r.id,C]),T=ie(Y=>{},[]),E=ie(async(Y,U)=>{var D;const B=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:Y,existingScenarios:t.scenarios,scenariosDataStructure:(D=t.metadata)==null?void 0:D.scenariosDataStructure,editingMockName:r.name,editingMockData:U==null?void 0:U.data})}),H=await B.json();if(!B.ok||!H.success)throw new Error(H.error||"Failed to generate scenario data");return H.data},[t,r.name]),$=ie(async()=>{var Y;if(!r.id){v("Cannot delete scenario without ID");return}g(!0),v(null);try{const U=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((Y=r.metadata)==null?void 0:Y.screenshotPaths)||[]})}),B=await U.json();if(!U.ok||!B.success)throw new Error(B.error||"Failed to delete scenario");i(`/entity/${a}`)}catch(U){console.error("[EditScenario] Error deleting scenario:",U),v(U instanceof Error?U.message:"Failed to delete scenario"),b(!1)}finally{g(!1)}},[r.id,(R=r.metadata)==null?void 0:R.screenshotPaths,a,i]);return d("div",{className:"h-screen bg-gray-50 flex flex-col",children:[d("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:d(me,{to:`/entity/${a}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(I=t.entity)==null?void 0:I.name]})}),d("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",r.name]}),r.description&&n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:r.description})]}),d("div",{className:"flex flex-1 gap-0 min-h-0",children:[d("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n(qh,{currentScenario:r,defaultScenario:s,dataStructure:((W=t.metadata)==null?void 0:W.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:j,onNavigate:T,iframeRef:l,onGenerateData:E,saveFeedback:{isSaving:c,message:u,isError:(u==null?void 0:u.startsWith("Error"))??!1}}),u==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(me,{to:`/entity/${a}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),d("div",{className:"border-t border-gray-200 p-4 mt-4",children:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),x?d("div",{className:"space-y-3",children:[d("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),d("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void $(),disabled: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:()=>b(!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:()=>b(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),w&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:w})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(us,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:C,isStarting:P,isLoading:N,showIframe:S,iframeKey:k,onIframeLoad:_,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const ef=Je(function(){return n(ds,{children:n(Xh,{})})}),tf=Object.freeze(Object.defineProperty({__proto__:null,default:ef,loader:Zh,meta:Qh},Symbol.toStringTag,{value:"Module"}));function nf(e){return rr.createHash("sha256").update(JSON.stringify(e)).digest("hex")}function rf(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 sf(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 af(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 of(){let e=[],t={},r=null,s=null,a=!1,o=null;function i(m){const u=[],p=m.routes;if(p&&typeof p=="object")for(const[h,f]of Object.entries(p)){const{method:y,pathPattern:g}=rf(h),{regex:x,paramNames:b}=sf(g),w=typeof f=="object"&&f!==null?f:{body:f};u.push({method:y,pathPattern:g,pathRegex:x,paramNames:b,response:{body:w.body,status:typeof w.status=="number"?w.status:200}})}return u}function l(m){const u=m.state;if(u&&typeof u=="object"){a=!0,t={};for(const[p,h]of Object.entries(u))t[p]=Array.isArray(h)?JSON.parse(JSON.stringify(h)):[];r=JSON.stringify(u)}else a=!1,t={},r=null}return{loadScenario(m){const u=nf(m);s&&u===s||(s=u,o=m,e=i(m),l(m))},matchRequest(m,u,p){if(!o&&e.length===0&&!a)return null;const h=Object.keys(t);if(a){const y=af(u,h);if(y&&m==="GET"&&y===u)return{body:t[y],status:200};if(y){const g=c(m,u);if(m==="POST"&&y===u&&g){const x=t[y],b=typeof p=="object"&&p!==null?{...p}:{};if(!("id"in b)){const w=x.reduce((v,C)=>{const P=typeof C.id=="number"?C.id:0;return Math.max(v,P)},0);b.id=w+1}return x.push(b),{body:b,status:g.response.status}}if(m==="DELETE"&&g&&g.params){const x=g.params.id,b=t[y],w=b.findIndex(v=>String(v.id)===String(x));return w===-1?{body:{error:"Not found"},status:404}:(b.splice(w,1),{body:null,status:g.response.status})}if(m==="PUT"&&g&&g.params){const x=g.params.id,b=t[y],w=b.findIndex(C=>String(C.id)===String(x));if(w===-1)return{body:{error:"Not found"},status:404};const v=typeof p=="object"&&p!==null?{...p}:b[w];return b[w]=v,{body:v,status:g.response.status}}}}const f=c(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,p]of Object.entries(m))t[u]=Array.isArray(p)?JSON.parse(JSON.stringify(p)):[]}},getState(){return{...t}}};function c(m,u){for(const p of e)if(p.method!==null&&p.method===m&&p.paramNames.length===0&&p.pathRegex.exec(u))return{response:p.response};if(m==="GET"){for(const p of e)if(p.method===null&&p.paramNames.length===0&&p.pathRegex.exec(u))return{response:p.response}}for(const p of e)if(p.paramNames.length>0){if((p.method??"GET")!==m)continue;const f=p.pathRegex.exec(u);if(f){const y={};for(let g=0;g<p.paramNames.length;g++)y[p.paramNames[g]]=f[g+1];return{response:p.response,params:y}}}return null}}function lf(e){var a,o;const t=Z.join(e,"package.json");if(!fe.existsSync(t))return{error:"No package.json found."};let r="npm",s=["run","dev"];try{const i=JSON.parse(fe.readFileSync(t,"utf8"));if(fe.existsSync(Z.join(e,"pnpm-lock.yaml"))?r="pnpm":fe.existsSync(Z.join(e,"yarn.lock"))?r="yarn":fe.existsSync(Z.join(e,"bun.lockb"))&&(r="bun"),!((a=i.scripts)!=null&&a.dev))if((o=i.scripts)!=null&&o.start)s=["run","start"];else return{error:'No "dev" or "start" script found in package.json.'}}catch{}return{command:r,args:s}}function cf(e,t){const r=t.toString(),s={PORT:r},a=Z.join(e,".codeyam","config.json");if(fe.existsSync(a))try{const c=(JSON.parse(fe.readFileSync(a,"utf8")).webapps||[])[0];if(c!=null&&c.startCommand){const{command:m,args:u,env:p}=c.startCommand,h=(u||[]).map(f=>f.includes("$PORT")?f.replace(/\$PORT/g,r):f);if(p)for(const[f,y]of Object.entries(p))typeof y=="string"&&y.includes("$PORT")?s[f]=y.replace(/\$PORT/g,r):typeof y=="string"&&(s[f]=y);return{command:m,args:h,env:s}}}catch{}const o=lf(e);return"error"in o?o:{command:o.command,args:o.args,env:s}}function Tl(e){return{proxyPort:e+1,devServerPort:e+2}}const df=[/Local:\s+(https?:\/\/[^\s]+)/,/Ready on\s+(https?:\/\/[^\s]+)/i,/started at\s+(https?:\/\/[^\s]+)/i,/listening on\s+(https?:\/\/[^\s]+)/i,/waiting on\s+(https?:\/\/[^\s]+)/i,/http:\/\/localhost:\d+/];function uf(e){for(const t of df){const r=e.match(t);if(r){const s=r[1]||r[0];return mf(s).trim()}}return null}function mf(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function $l(){const e=globalThis.__codeyam_editor_dev_server__;return e&&e.status==="running"&&e.url?e.url:null}async function pf(e,t={}){const{intervalMs:r=2e3,maxAttempts:s=15}=t,a=`http://localhost:${e}`;for(let o=0;o<s;o++){try{const i=await fetch(a,{method:"HEAD",signal:AbortSignal.timeout(2e3)});if(i.ok||i.status===304)return a}catch{}o<s-1&&await new Promise(i=>setTimeout(i,r))}return null}function hf(e){const{exitCode:t,uptime:r,retryCount:s,wasRunning:a}=e,o=r<1e4;return t!==0&&t!==null&&o&&s===0?{action:"retry"}:t!==0&&t!==null?{action:"error"}:a===!1?{action:"error"}:{action:"stopped"}}function ff(e){try{return new URL(e).toString().replace(/\/$/,"")}catch{return e}}async function gf(e){const t=["127.0.0.1","::1"];for(const r of t)try{if(await new Promise(a=>{const o=new Vi.Socket;o.setTimeout(1e3),o.once("connect",()=>{o.destroy(),a(!0)}),o.once("error",()=>{o.destroy(),a(!1)}),o.once("timeout",()=>{o.destroy(),a(!1)}),o.connect(e,r)}))return r}catch{}return null}const Il="__codeyam_editor_proxy__",Rl="__codeyam_preview_health__";function Dl(){return globalThis[Rl]??null}function Ol(e){globalThis[Rl]=e}function yf(){return Dl()}function Ll(){Ol(null)}const xf=`<script data-codeyam-health>
|
|
152
|
-
(function() {
|
|
153
|
-
var errors = [];
|
|
154
|
-
var reported = false;
|
|
155
|
-
function report(type, msg, stack) {
|
|
156
|
-
errors.push({ type: type, message: msg, stack: stack, timestamp: Date.now() });
|
|
157
|
-
if (!reported) {
|
|
158
|
-
reported = true;
|
|
159
|
-
setTimeout(function() { flush(); }, 500);
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
function flush() {
|
|
163
|
-
fetch('/__codeyam__/preview-health', {
|
|
164
|
-
method: 'POST',
|
|
165
|
-
headers: { 'Content-Type': 'application/json' },
|
|
166
|
-
body: JSON.stringify({ errors: errors, url: location.href })
|
|
167
|
-
}).catch(function(){});
|
|
168
|
-
reported = false;
|
|
169
|
-
errors = [];
|
|
170
|
-
}
|
|
171
|
-
window.addEventListener('error', function(e) {
|
|
172
|
-
report('error', e.message, e.error && e.error.stack);
|
|
173
|
-
});
|
|
174
|
-
window.addEventListener('unhandledrejection', function(e) {
|
|
175
|
-
report('unhandledrejection', String(e.reason), e.reason && e.reason.stack);
|
|
176
|
-
});
|
|
177
|
-
var origError = console.error;
|
|
178
|
-
console.error = function() {
|
|
179
|
-
report('console.error', Array.prototype.join.call(arguments, ' '));
|
|
180
|
-
origError.apply(console, arguments);
|
|
181
|
-
};
|
|
182
|
-
window.addEventListener('load', function() {
|
|
183
|
-
setTimeout(function() {
|
|
184
|
-
var hasContent = document.body && document.body.innerText.trim().length > 0;
|
|
185
|
-
fetch('/__codeyam__/preview-health', {
|
|
186
|
-
method: 'POST',
|
|
187
|
-
headers: { 'Content-Type': 'application/json' },
|
|
188
|
-
body: JSON.stringify({
|
|
189
|
-
loaded: true,
|
|
190
|
-
hasContent: hasContent,
|
|
191
|
-
url: location.href,
|
|
192
|
-
errorCount: errors.length
|
|
193
|
-
})
|
|
194
|
-
}).catch(function(){});
|
|
195
|
-
}, 1000);
|
|
196
|
-
});
|
|
197
|
-
})();
|
|
198
|
-
<\/script>`,bf=500;let Nt={data:null,timestamp:0},nn,ms=null,ps=null;const Wo=10*1024*1024;function hs(){return globalThis[Il]??null}function Fl(e){globalThis[Il]=e}function zl(){const e="__codeyam_mock_state__";return globalThis[e]||(globalThis[e]=of()),globalThis[e]}function Bl(){const e=hs();return e?`http://localhost:${e.port}`:null}function wf(){const e=Date.now();if(Nt.data!==null&&e-Nt.timestamp<bf)return Nt.data;const t=he()||process.env.CODEYAM_ROOT_PATH||process.cwd(),r=Z.join(t,".codeyam","active-scenario.json");try{if(!fe.existsSync(r))return Nt={data:null,timestamp:e},null;const s=JSON.parse(fe.readFileSync(r,"utf-8")),a=s.scenarioId;if(!a)return Nt={data:null,timestamp:e},null;const o=Z.join(t,".codeyam","editor-scenarios",`${a}.json`);if(!fe.existsSync(o))return console.log(`[editorProxy] Scenario data file not found: ${o}`),Nt={data:null,timestamp:e},null;const i=JSON.parse(fe.readFileSync(o,"utf-8"));nn=i.session||null,ms=i.localStorage||null,ps=a;const l=s.type||i.type||null;let c;return(l==="application"||l==="user")&&i.seed?i.externalApis&&typeof i.externalApis=="object"?c={routes:i.externalApis}:c={}:c=i,Nt={data:c,timestamp:e},zl().loadScenario(c),c}catch(s){return console.warn("[editorProxy] Error reading scenario data:",s),Nt={data:null,timestamp:e},null}}function vf(e){return new Promise(t=>{const r=[];let s=0;e.on("data",a=>{s+=a.length,s>Wo?(t(null),e.resume()):r.push(a)}),e.on("end",()=>{s>Wo||t(Buffer.concat(r))}),e.on("error",()=>{t(null)})})}function za(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function Ho(e,t,r,s){const a=new URL(r),o=za(a.hostname),i={...e.headers,host:`${a.hostname}:${a.port}`};delete i["accept-encoding"],s&&(i["content-length"]=String(s.length));const l={hostname:o,port:a.port,path:e.url,method:e.method,headers:i},c=Sa.request(l,m=>{const u=m.statusCode||200;u>=400&&console.warn(`[editorProxy] Target returned ${u} for ${e.method} ${e.url}`);const p={...m.headers};if(Yl(p),(m.headers["content-type"]||"").includes("text/html")){Ll();const f=[];m.on("data",y=>f.push(y)),m.on("end",()=>{const y=Buffer.concat(f).toString("utf-8"),g=Ul(ms,ps||""),x=Wl(y,g);delete p["content-length"],delete p["content-encoding"],p["cache-control"]="no-store, must-revalidate",t.writeHead(u,p),t.end(x)});return}t.writeHead(u,p),m.pipe(t,{end:!0})});c.on("error",m=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${m.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 Nf(e,t,r){const s=new URL(r),a=za(s.hostname),{"accept-encoding":o,...i}=e.headers,l={hostname:a,port:s.port,path:e.url,method:e.method,headers:{...i,host:`${s.hostname}:${s.port}`}},c=Sa.request(l,m=>{const u=m.statusCode||200;u>=400&&console.warn(`[editorProxy] Target returned ${u} for ${e.method} ${e.url}`);const p={...m.headers};if(Yl(p),(m.headers["content-type"]||"").includes("text/html")){Ll();const f=[];m.on("data",y=>f.push(y)),m.on("end",()=>{const y=Buffer.concat(f).toString("utf-8"),g=Ul(ms,ps||""),x=Wl(y,g);delete p["content-length"],delete p["content-encoding"],p["cache-control"]="no-store, must-revalidate",t.writeHead(u,p),t.end(x)});return}t.writeHead(u,p),m.pipe(t,{end:!0})});c.on("error",m=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${m.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),e.pipe(c,{end:!0})}function Yl(e){if(nn===void 0)return;let t;nn!=null&&nn.cookieValue?t=`session-token=${nn.cookieValue}; Path=/; SameSite=Lax`:t="session-token=; Path=/; Max-Age=0";const r=e["set-cookie"];r?e["set-cookie"]=[...Array.isArray(r)?r:[r],t]:e["set-cookie"]=[t]}function Ul(e,t){if(!e||typeof e!="object")return"";const r=Object.entries(e),s=r.map(([o])=>o),a=r.map(([o,i])=>{const l=typeof i=="string"?i:JSON.stringify(i);return`localStorage.setItem(${JSON.stringify(o)}, ${JSON.stringify(l)});`}).join(`
|
|
199
|
-
`);return`<script data-codeyam-ls>
|
|
200
|
-
(function() {
|
|
201
|
-
if (localStorage.getItem('__codeyam_ls_sid__') === ${JSON.stringify(t)}) return;
|
|
202
|
-
var prev = JSON.parse(localStorage.getItem('__codeyam_ls_keys__') || '[]');
|
|
203
|
-
for (var i = 0; i < prev.length; i++) localStorage.removeItem(prev[i]);
|
|
204
|
-
${a}
|
|
205
|
-
localStorage.setItem('__codeyam_ls_keys__', ${JSON.stringify(JSON.stringify(s))});
|
|
206
|
-
localStorage.setItem('__codeyam_ls_sid__', ${JSON.stringify(t)});
|
|
207
|
-
})();
|
|
208
|
-
<\/script>`}function Wl(e,t){const r=(t||"")+xf;return e.includes("</head>")?e.replace("</head>",r+"</head>"):e.includes("</body>")?e.replace("</body>",r+"</body>"):e+r}function Cf(e,t){const r=[];e.on("data",s=>r.push(s)),e.on("end",()=>{try{const s=JSON.parse(Buffer.concat(r).toString("utf-8")),a=Dl()||{errors:[],loaded:!1,hasContent:!1,url:"",lastUpdated:0};s.errors&&Array.isArray(s.errors)&&(a.errors=a.errors.concat(s.errors)),s.loaded!==void 0&&(a.loaded=s.loaded),s.hasContent!==void 0&&(a.hasContent=s.hasContent),s.url&&(a.url=s.url),a.lastUpdated=Date.now(),Ol(a)}catch{}t.writeHead(204),t.end()})}function Sf(e,t,r,s){const a=new URL(s),o=za(a.hostname),i=parseInt(a.port,10)||80;console.log(`[editorProxy] WebSocket upgrade: ${e.url} → ${o}:${i}`);const l=Vi.connect(i,o,()=>{const c=`${e.method} ${e.url} HTTP/${e.httpVersion}\r
|
|
209
|
-
`,m=Object.entries(e.headers).filter(([,u])=>u!=null).map(([u,p])=>`${u}: ${Array.isArray(p)?p.join(", "):p}`).join(`\r
|
|
210
|
-
`);l.write(c+m+`\r
|
|
211
|
-
\r
|
|
212
|
-
`),r.length>0&&l.write(r),l.pipe(t,{end:!0}),t.pipe(l,{end:!0})});l.on("error",c=>{console.warn(`[editorProxy] WebSocket proxy error: ${c.message}`),t.destroy()}),t.on("error",()=>{l.destroy()})}function kf(e,t){const r=he()||process.env.CODEYAM_ROOT_PATH||process.cwd(),s=Z.join(r,".codeyam","proxy-config.json");try{fe.mkdirSync(Z.dirname(s),{recursive:!0}),fe.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 Ef(){const e=he()||process.env.CODEYAM_ROOT_PATH||process.cwd(),t=Z.join(e,".codeyam","proxy-config.json");try{fe.existsSync(t)&&fe.unlinkSync(t)}catch{}}async function sa(e){const t=hs();if(t)return console.log(`[editorProxy] Proxy already running on port ${t.port} → ${t.targetUrl}`),{port:t.port};await Hl();let r=ff(e.targetUrl),s=e.port;try{const l=new URL(r);if(l.hostname==="localhost"){const c=parseInt(l.port||"80",10),m=await gf(c);m&&(l.hostname=m,r=l.toString().replace(/\/$/,""),console.log(`[editorProxy] Resolved localhost to ${m} for port ${c}`))}}catch{}console.log(`[editorProxy] Starting proxy (requested port ${s}, target ${r})`);const a=zl(),o=Sa.createServer((l,c)=>{(async()=>{const u=new URL(l.url||"/",`http://localhost:${s}`).pathname,p=l.method||"GET";if(p==="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(p==="POST"&&u==="/__codeyam__/preview-health"){Cf(l,c);return}if(wf(),p==="POST"||p==="PUT"||p==="DELETE"||p==="PATCH"){const y=await vf(l);if(y===null){Ho(l,c,r,null);return}let g;if(y.length>0)try{g=JSON.parse(y.toString("utf-8"))}catch{}const x=a.matchRequest(p,u,g);if(x){console.log(`[editorProxy] Intercepted ${p} ${u} → mock response (status ${x.status})`),c.writeHead(x.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data","Cache-Control":"no-store"}),c.end(x.body!=null?JSON.stringify(x.body):"");return}Ho(l,c,r,y);return}const f=a.matchRequest(p,u);if(f){console.log(`[editorProxy] Intercepted ${p} ${u} → mock response (status ${f.status})`),c.writeHead(f.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data","Cache-Control":"no-store"}),c.end(f.body!=null?JSON.stringify(f.body):"");return}Nf(l,c,r)})()});o.on("upgrade",(l,c,m)=>{Sf(l,c,m,r)});const i=10;for(let l=0;l<i;l++){const c=s+l;try{await new Promise((p,h)=>{o.once("error",h),o.listen(c,"0.0.0.0",()=>{o.removeListener("error",h),p()})});const m=o.address();return s=typeof m=="object"&&m!==null?m.port:c,Fl({server:o,port:s,targetUrl:r}),kf(s,r),console.log(`[editorProxy] Proxy started on port ${s}, forwarding to ${r}`),{port:s}}catch(m){if((m==null?void 0:m.code)==="EADDRINUSE"&&l<i-1){console.log(`[editorProxy] Port ${c} in use, trying ${c+1}`);continue}return console.error("[editorProxy] Failed to start proxy:",m),null}}return null}async function Hl(){const e=hs();if(e)return console.log(`[editorProxy] Stopping proxy on port ${e.port}`),Ef(),new Promise(t=>{e.server.close(()=>{console.log("[editorProxy] Proxy stopped"),t()}),Fl(null),setTimeout(t,2e3)})}function qn(){Nt={data:null,timestamp:0},nn=void 0,ms=null,ps=null}async function Jo(){const e=hs();if(!e)return console.warn("[editorProxy] Cannot verify — proxy is not running"),!1;try{const t=await fetch(`http://127.0.0.1:${e.port}/`,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return t.status===502?(console.warn("[editorProxy] Verification failed — proxy returned 502 (target unreachable)"),!1):(console.log(`[editorProxy] Verification passed — proxy forwarding to ${e.targetUrl} (status ${t.status})`),!0)}catch{return console.warn(`[editorProxy] Verification failed — could not reach proxy on port ${e.port}`),!1}}async function Jl(){const e=Bl();if(e)return console.log(`[editorProxy] Proxy already running at ${e}`),e;const t=globalThis.__codeyam_editor_dev_server__;if(!t||t.status!=="running"||!t.url)return console.log("[editorProxy] Cannot start proxy — dev server not running"),null;const r=parseInt(process.env.CODEYAM_PORT||"3111",10),{proxyPort:s}=Tl(r);console.log(`[editorProxy] Proxy not running, starting on-demand (port ${s}, target ${t.url})`);const a=await sa({port:s,targetUrl:t.url});if(a){const o=`http://localhost:${a.port}`;return console.log(`[editorProxy] On-demand proxy started at ${o}`),o}return console.error("[editorProxy] Failed to start on-demand proxy"),null}const _f=["/api/health","/__codeyam__/preview-health"];function Vl(e){const t=[];for(const r of e.split(`
|
|
213
|
-
`))if(r.includes("[JournalCapture] Page console.error:"))t.push(r.replace(/.*\[JournalCapture\] Page console\.error:\s*/,""));else if(r.includes("[JournalCapture] Network failed:")){if(_f.some(s=>r.includes(s)))continue;t.push(r.replace(/.*\[JournalCapture\] /,""))}return t}async function Gl(e,t,r,s){const a=F.join(e,".codeyam","editor-scenarios","client-errors.json");let o={};try{const i=await we.readFile(a,"utf8");o=JSON.parse(i)}catch{}for(const[i,l]of Object.entries(o))i!==t&&l.scenarioName===r&&delete o[i];o[t]={scenarioName:r,capturedAt:new Date().toISOString(),errors:s},await we.mkdir(F.dirname(a),{recursive:!0}),await we.writeFile(a,JSON.stringify(o,null,2),"utf8")}async function Kl(e){const t=F.join(e,".codeyam","editor-scenarios","client-errors.json");try{const r=await we.readFile(t,"utf8");return JSON.parse(r)}catch{return{}}}function aa(e){let r=F.dirname(new URL(e).pathname);for(let s=0;s<5;s++){const a=F.dirname(r);if(F.basename(a)==="webserver"||F.basename(r)==="webserver")return F.basename(r)==="webserver"?r:a;r=a}return r}async function oa(e,t){const r=[F.join(e,"scripts","journalCapture.ts"),F.join(e,"app","lib","journalCapture.ts"),F.join(t,"codeyam-cli","src","webserver","app","lib","journalCapture.ts")];for(const s of r)try{return await we.access(s),s}catch{}return r[0]}function ia(e,t,r){return new Promise(s=>{const a=e.endsWith(".ts"),l=Et(a?"npx":e,a?["tsx",e,t]:[t],{cwd:r,env:{...process.env}});let c="",m="";l.stdout.on("data",u=>{c+=u.toString()}),l.stderr.on("data",u=>{m+=u.toString()}),l.on("close",u=>{s(u===0?{success:!0,output:c}:{success:!1,output:c,error:m||`Process exited with code ${u}`})}),l.on("error",u=>{s({success:!1,output:"",error:u.message})})})}const Af=3e4;function Ba(e,t,r){const s=Af,a=F.basename(F.dirname(e))===".codeyam"?F.dirname(F.dirname(e)):F.dirname(e);return new Promise(o=>{const i=Date.now(),l=e.endsWith(".ts"),u=Et(l?"npx":e,l?["tsx",e,t]:[t],{cwd:a,env:{...process.env}});let p="",h="",f=!1;const y=setTimeout(()=>{f=!0,u.kill("SIGTERM")},s);u.stdout.on("data",g=>{p+=g.toString()}),u.stderr.on("data",g=>{h+=g.toString()}),u.on("close",g=>{clearTimeout(y);const x=Date.now()-i;o(f?{success:!1,output:p,error:`Seed adapter timeout after ${s}ms`,durationMs:x}:g===0?{success:!0,output:p,durationMs:x}:{success:!1,output:p,error:h||`Seed adapter exited with code ${g}`,durationMs:x})}),u.on("error",g=>{clearTimeout(y),o({success:!1,output:"",error:g.message,durationMs:Date.now()-i})})})}function Ya(e){const t=["seed-adapter.ts","seed-adapter.js"];for(const r of t){const s=F.join(e,".codeyam",r);try{return K.accessSync(s),s}catch{}}return null}function Pf(e,t){const r={};for(const[s,a]of Object.entries(e))r[s]=JSON.parse(JSON.stringify(a));for(const[s,a]of Object.entries(t))r[s]=JSON.parse(JSON.stringify(a));return r}function jf(e,t,r){const s=F.join(e,".codeyam","editor-scenarios",`${t}.json`);let a={};try{a=JSON.parse(K.readFileSync(s,"utf8"))}catch{return}a._metadata=r,K.writeFileSync(s,JSON.stringify(a,null,2),"utf8")}function Mf(e,t){const r=F.join(e,".codeyam","editor-scenarios");for(const s of[".json",".seed.json"]){const a=F.join(r,`${t}${s}`);try{K.unlinkSync(a)}catch{}}}const Ua=globalThis.__codeyamTerminalSessions??(globalThis.__codeyamTerminalSessions=new Set);globalThis.__codeyamDetachedPtys??(globalThis.__codeyamDetachedPtys=new Map);function Wa(e,t){const r=JSON.stringify({type:"refresh-preview",...e&&{path:e},...t&&{scenarioId:t}});let s=0;for(const a of Ua)try{a.ws.readyState===ka.OPEN&&(a.ws.send(r),s++)}catch{}return s}function Tf(){const e=JSON.stringify({type:"hide-results"});let t=0;for(const r of Ua)try{r.ws.readyState===ka.OPEN&&(r.ws.send(e),t++)}catch{}return t}function ql(e){const t=JSON.stringify({type:"set-viewport",...e});let r=0;for(const s of Ua)try{s.ws.readyState===ka.OPEN&&(s.ws.send(t),r++)}catch{}return r}const $f=Object.freeze(Object.defineProperty({__proto__:null,broadcastHideResults:Tf,broadcastPreviewRefresh:Wa,broadcastSetViewport:ql},Symbol.toStringTag,{value:"Module"}));let Qt=null;async function If(e){const{scenarioId:t,projectRoot:r}=e,s=Z.join(r,".codeyam"),a=Z.join(s,"editor-scenarios");let o=e.scenarioSlug||null;if(!o)try{const u=Z.join(a,`${t}.json`);fe.existsSync(u)?o=JSON.parse(fe.readFileSync(u,"utf-8")).name||t:o=t}catch{o=t}let i=e.scenarioType||null;if(!i)try{const u=Z.join(a,`${t}.json`);fe.existsSync(u)&&(i=JSON.parse(fe.readFileSync(u,"utf-8")).type||null)}catch{}const l=Z.join(s,"active-scenario.json");fe.mkdirSync(s,{recursive:!0}),fe.writeFileSync(l,JSON.stringify({scenarioSlug:o,scenarioName:e.scenarioName||o,scenarioId:t,type:i,dataFile:`.codeyam/editor-scenarios/${t}.json`,switchedAt:new Date().toISOString()},null,2));let c=null;const m=i==="application"||i==="user";if(m)if(Qt&&Qt.scenarioId===t)c=await Qt.promise;else{const u=Ya(r),p=Z.join(a,`${t}.seed.json`);if(u&&fe.existsSync(p)){const h=Ba(u,p).then(f=>({success:f.success,error:f.error}));Qt={scenarioId:t,promise:h};try{c=await h}finally{Qt&&Qt.scenarioId===t&&(Qt=null)}}else u||(c={success:!1,error:"No seed adapter found"})}return{success:!0,scenarioSlug:o,scenarioId:t,type:i,seeded:m,...c?{seedResult:c}:{}}}function Rf(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=Ee("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return Df(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function Df(e){const t=e.trim().split(`
|
|
214
|
-
`).filter(s=>s.length>0),r=[];for(const s of t){const a=s[0],o=s[1];let i=s.slice(2).replace(/^[ \t]+/,""),l,c=!1,m;if(a==="A"||o==="A")l="added",c=a==="A";else if(a==="M"||o==="M")l="modified",c=a==="M";else if(a==="D"||o==="D")l="deleted",c=a==="D";else if(a==="R"||o==="R"){l="renamed",c=a==="R";const u=i.indexOf(" -> ");u!==-1&&(m=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(l="untracked",c=!1):(l="modified",c=a!==" "&&a!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),p=Z.join(u,i);try{const h=(y,g)=>{const x=fe.readdirSync(y,{withFileTypes:!0}),b=[];for(const w of x){const v=Z.join(y,w.name),C=Z.relative(u,v);w.isDirectory()?b.push(...h(v,g)):w.isFile()&&b.push(C)}return b},f=h(p,u);for(const y of f)r.push({path:y,status:l,staged:c,...m&&{oldPath:m}})}catch(h){console.error(`Failed to expand directory ${i}:`,h)}}else r.push({path:i,status:l,staged:c,...m&&{oldPath:m}})}return r}function Of(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ee("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 Lf(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const s=Ee('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 Ee("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return Ee("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 Ff(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ee('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
215
|
-
`).filter(s=>s.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function jn(){const e=he();return e?Rf(e):[]}function zf(){const e=he();return e?Of(e):null}function Bf(){const e=he();return e?Lf(e):"main"}function Yf(){const e=he();return e?Ff(e):[]}function Ql(e,t){const r=he();return r?Uf(e,t,r):[]}function Uf(e,t,r){const s=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Ee(`git diff --name-status ${e}...${t}`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
216
|
-
`).filter(i=>i.length>0).map(i=>{const l=i.split(" "),c=l[0];let m=l[1],u,p;return c==="A"?p="added":c==="M"?p="modified":c==="D"?p="deleted":c.startsWith("R")?(p="renamed",u=l[1],m=l[2]):p="modified",{path:m,status:p,...u&&{oldPath:u}}})}catch(a){return console.error("Failed to get branch diff:",a),[]}}function Zl(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=Ee(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let a="";try{a=fe.readFileSync(Z.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 Wf(e){const t=he();return t?Zl(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Hf(e,t,r,s){const a=s||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=Ee(`git show ${t}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=Ee(`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 Sr(e,t,r){const s=he();return s?Hf(e,t,r,s):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Xl(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 Xe(e){if(!e||e==="/")return"Home";const t=e.split("?")[0].replace(/^\//,"");if(!t)return"Home";const r=t.split("/")[0];return r.charAt(0).toUpperCase()+r.slice(1)}function Ha(e){return e?e.includes("/isolated-components"):!1}function Ja(e){return e.componentName?e.componentName:Xe(e.url)}function ec(e,t,r){var o;const s=[],a=new Set;for(const i of e){let l=null,c=null;if(i.componentName&&i.componentPath)l=i.componentName,c=i.componentPath;else if(!i.componentName&&i.url!==void 0){const m=Xe(i.url);t[m]&&(l=m,c=t[m])}if(l&&c&&!a.has(l)){a.add(l);const m=r.find(u=>u.name===l);s.push({name:l,filePath:c,importedBy:(o=m==null?void 0:m.metadata)==null?void 0:o.importedBy})}}return s}function Jf(e,t){const r=[],s=new Set(t);for(const a of e)s.has(a.name)||(s.add(a.name),r.push({name:a.name,filePath:a.filePath}));return r}function Vf(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>t[r.name])}function Gf(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>{if("componentName"in r){const a=Ja(r);return!!t[a]}const s=r.name.indexOf(" - ");if(s!==-1){const a=r.name.slice(0,s);return!!t[a]}return!!t.Home})}function Kf(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 qf(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 Qf=20;function tc(e,t,r=Qf){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=Kf(t),i=qf(e,t);for(const[m,u]of i)s[m]={status:u};const l=new Map;for(const[m]of i)l.set(m,new Set([m]));const c=[];for(const[m]of i)c.push({name:m,depth:0});for(;c.length>0;){const{name:m,depth:u}=c.shift();if(u>=r)continue;const p=l.get(m)||new Set,h=o.get(m);if(h)for(const f of h){if(!a.has(f))continue;l.has(f)||l.set(f,new Set);const y=l.get(f);let g=!1;for(const x of p)y.has(x)||(y.add(x),g=!0);g&&c.push({name:f,depth:u+1})}}for(const[m,u]of l){if(i.has(m))continue;const p=[];for(const h of u){const f=a.get(h),y=i.get(h);f&&y&&p.push({name:h,filePath:f.filePath,changeType:y})}p.sort((h,f)=>h.name.localeCompare(f.name)),s[m]={status:"impacted",impactedBy:p.length>0?p:void 0}}return s}async function Zf(e,t,r){const s=F.join(e,".codeyam","journal"),a=F.join(s,"index.json");F.join(s,"screenshots");let o;try{const l=await we.readFile(a,"utf8");o=JSON.parse(l)}catch{return}let i=!1;for(const l of o.entries)if(!l.commitSha&&l.scenarioScreenshots)for(let c=0;c<l.scenarioScreenshots.length;c++){const m=l.scenarioScreenshots[c];if(m.name!==t)continue;const u=F.join(s,m.path);try{await we.copyFile(r,u),i=!0,console.log(`[editor-register-scenario] Updated journal screenshot for "${t}" in entry "${l.title}"`)}catch(p){console.warn(`[editor-register-scenario] Failed to update journal screenshot: ${p instanceof Error?p.message:p}`)}}i&&ct.notifyChange("journal")}const Vo=$l;async function Xf({request:e}){var t,r;if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const s=await e.json();s.url=s.url||s.path||void 0;const{name:a,description:o,componentName:i,componentPath:l}=s;if(!a)return new Response(JSON.stringify({error:"name is required"}),{status:400,headers:{"Content-Type":"application/json"}});const c=await Ie();if(!c)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:m}=await Re(c),u=je(),p=process.env.CODEYAM_ROOT_PATH||process.cwd();let h,f,y;if(!s.viewportWidth&&!s.viewportHeight&&!s.dimension){const E=await u.selectFrom("editor_scenarios").selectAll().where("name","=",a).where("project_id","=",m.id).orderBy("created_at","desc").executeTakeFirst();E&&(h=E.viewport_width||void 0,f=E.viewport_height||void 0,y=E.dimension||void 0)}const g=zr({bodyWidth:s.viewportWidth||h,bodyHeight:s.viewportHeight||f,dimension:s.dimension||y,codeyamRoot:p}),x=await Sh(u,{projectId:m.id,name:a,description:o||null,componentName:i||null,componentPath:l||null,url:s.url||null,type:s.type||null,viewportWidth:g.width,viewportHeight:g.height,dimension:s.dimension||y||null}),b=x.scenarioId;x.cleanedUpIds.length>0&&(kh(p,x.cleanedUpIds),console.log(`[editor-register-scenario] Cleaned up ${x.cleanedUpIds.length} duplicate(s) for "${a}"`));const w=s.type==="application"||s.type==="user";if(w&&s.seed){let E=s.seed;if(s.type==="user"&&s.baseScenario)try{const W=F.join(p,".codeyam","editor-scenarios",`${s.baseScenario}.json`),Y=await we.readFile(W,"utf-8"),U=JSON.parse(Y);U.seed&&(E=Pf(U.seed,s.seed),console.log(`[editor-register-scenario] Merged seed data from base scenario ${s.baseScenario}`))}catch(W){console.warn(`[editor-register-scenario] Could not read base scenario ${s.baseScenario}: ${W instanceof Error?W.message:W}`)}const $=F.join(p,".codeyam","editor-scenarios");await we.mkdir($,{recursive:!0});const R=new Date().toISOString(),I={name:a,description:o||null,componentName:i||null,componentPath:l||null,url:s.url||null,type:s.type||null,screenshotPath:null,viewportWidth:s.viewportWidth||null,viewportHeight:s.viewportHeight||null,createdAt:R,updatedAt:R};await we.writeFile(F.join($,`${b}.json`),JSON.stringify({_metadata:I,type:s.type,seed:E,...s.externalApis?{externalApis:s.externalApis}:{},...s.session?{session:s.session}:{},...s.localStorage?{localStorage:s.localStorage}:{}},null,2)),await we.writeFile(F.join($,`${b}.seed.json`),JSON.stringify(E,null,2))}else if(s.mockData||s.localStorage){const E=F.join(p,".codeyam","editor-scenarios");await we.mkdir(E,{recursive:!0});const $=new Date().toISOString(),I={_metadata:{name:a,description:o||null,componentName:i||null,componentPath:l||null,url:s.url||null,type:s.type||"component",screenshotPath:null,viewportWidth:s.viewportWidth||null,viewportHeight:s.viewportHeight||null,createdAt:$,updatedAt:$},...s.mockData||{},...s.localStorage?{localStorage:s.localStorage}:{}};await we.writeFile(F.join(E,`${b}.json`),JSON.stringify(I,null,2))}else{const E=F.join(p,".codeyam","editor-scenarios");await we.mkdir(E,{recursive:!0});const $=new Date().toISOString(),R={name:a,description:o||null,componentName:i||null,componentPath:l||null,url:s.url||null,type:s.type||"component",screenshotPath:null,viewportWidth:s.viewportWidth||null,viewportHeight:s.viewportHeight||null,createdAt:$,updatedAt:$};await we.writeFile(F.join(E,`${b}.json`),JSON.stringify({_metadata:R},null,2))}let v=null;if(w&&s.seed){const E=Ya(p);if(E){const $=F.join(p,".codeyam","editor-scenarios",`${b}.seed.json`);console.log(`[editor-register-scenario] Running seed adapter: ${E}`);const R=await Ba(E,$);v={success:R.success,error:R.error},R.success?console.log(`[editor-register-scenario] Seed adapter completed in ${R.durationMs}ms`):console.warn(`[editor-register-scenario] Seed adapter failed: ${R.error}`)}else console.warn(`[editor-register-scenario] No seed adapter found at ${p}/.codeyam/seed-adapter.ts`),v={success:!1,error:"No seed adapter found. Create .codeyam/seed-adapter.ts to use seed-based scenarios."}}ct.notifyChange("scenario"),console.log(`[editor-register-scenario] Starting auto-capture for scenario "${a}" (id: ${b})`);const C=s.url&&s.url.startsWith("/"),P=!s.url||C?await Jl():null,N=Vo(),S=na(s.url||null,P,N);console.log(`[editor-register-scenario] Capture URL resolution: explicit=${s.url||"none"}, isPath=${C}, proxy=${P||"none"}, devServer=${N||"none"} → using ${S||"none"}`);let k=null,_=null,j=[],T=null;if(S){const E=Ct(a),$=F.join(p,".codeyam","active-scenario.json");await we.writeFile($,JSON.stringify({scenarioId:b,scenarioSlug:E,type:s.type||null,timestamp:new Date().toISOString()})),qn(),console.log(`[editor-register-scenario] Active scenario set to "${E}" (${b}), cache invalidated`),await new Promise(J=>setTimeout(J,500));const R=(t=s.url)!=null&&t.startsWith("/")?`${Vo()||"http://localhost:3113"}${s.url}`:S;for(let J=0;J<5;J++){try{const V=await fetch(R,{method:"GET",signal:AbortSignal.timeout(3e3)});if(V.status<500)break;console.log(`[editor-register-scenario] Route returned ${V.status}, waiting for HMR (attempt ${J+1}/5)...`)}catch{console.log(`[editor-register-scenario] Route not reachable, waiting for HMR (attempt ${J+1}/5)...`)}await new Promise(V=>setTimeout(V,2e3))}const I=F.join(p,".codeyam","editor-scenarios","screenshots");await we.mkdir(I,{recursive:!0});const W=F.join(I,`${b}.png`),Y=aa(import.meta.url),U=await oa(Y,p);console.log(`[editor-register-scenario] Capture script: ${U}`),T=g;const B=JSON.stringify({url:S,outputPath:W,viewportWidth:g.width,viewportHeight:g.height,...i?{selector:"#codeyam-capture"}:{}});console.log(`[editor-register-scenario] Capture viewport: ${g.width}×${g.height} (body=${s.viewportWidth||"none"}×${s.viewportHeight||"none"})`),console.log(`[editor-register-scenario] Running Playwright capture: url=${S}, output=${W}`);const H=Date.now(),D=await ia(U,B,p),A=Date.now()-H;if(console.log(`[editor-register-scenario] Capture ${D.success?"succeeded":"FAILED"} in ${A}ms`),D.success||(console.warn(`[editor-register-scenario] Capture stdout: ${D.output.slice(0,500)}`),console.warn(`[editor-register-scenario] Capture stderr: ${(D.error||"").slice(0,500)}`)),j=Vl(D.output),await Gl(p,b,a,j),j.length>0&&console.warn(`[editor-register-scenario] ${j.length} client-side error(s) detected:`,j),D.success){k=`screenshots/${b}.png`;try{await u.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}await u.updateTable("editor_scenarios").set({screenshot_path:k}).where("id","=",b).execute(),ct.notifyChange("scenario"),await Zf(p,a,W)}else _=D.error||"Unknown capture error",console.warn(`[editor-register-scenario] Screenshot capture failed (non-blocking): ${_}`)}else console.log("[editor-register-scenario] Skipping screenshot — no capture URL available (dev server not running?)");if(console.log(`[editor-register-scenario] Done: scenario="${a}", screenshot=${k?"captured":"skipped"}`),S&&k)try{const E=he()||process.cwd(),$=F.join(E,".codeyam","editor-step.json");let R=null;try{const I=K.readFileSync($,"utf8");R=JSON.parse(I).featureStartedAt||null}catch{}if(R){const I=La(R),W=await u.selectFrom("editor_scenarios").selectAll().where("project_id","=",m.id).orderBy("created_at","asc").execute(),Y=yt(W,B=>`${B.name}::${B.url||"/"}`),U=jn();if(U.length>0){let B=!1;try{const{execSync:z}=await import("child_process"),G=z("git rev-list --count HEAD",{cwd:E,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();B=parseInt(G,10)<=1}catch{B=!0}const H=Xl(U,B),D={},A=F.join(E,"app");if(K.existsSync(A)){const z=(G,ee)=>{for(const re of K.readdirSync(G,{withFileTypes:!0}))if(re.name!=="isolated-components"){if(re.isDirectory())z(F.join(G,re.name),ee?`${ee}/${re.name}`:re.name);else if(re.name==="page.tsx"||re.name==="page.js"){const ue=Xe(ee?`/${ee}`:"/");D[ue]=ee?`app/${ee}/${re.name}`:`app/${re.name}`}}};z(A,"")}let J=[];try{await ze(),J=await st({})||[]}catch{}const V=Y.map(z=>({componentName:z.component_name||null,componentPath:z.component_path||null,url:z.url??null})),q=ec(V,D,J),X=tc(H,q),L=Y.filter(z=>z.created_at<I),O=new Map;for(const z of L){const G=z.component_name||Xe(z.url);((r=X[G])==null?void 0:r.status)==="impacted"&&O.set(G,z)}if(O.size>0){console.log(`[editor-register-scenario] Recapturing ${O.size} impacted older scenario(s): ${[...O.keys()].join(", ")}`);const z=aa(import.meta.url),G=await oa(z,p),ee=F.join(p,".codeyam","editor-scenarios","screenshots");for(const[ue,se]of O)try{const pe=Ct(se.name);await If({scenarioId:se.id,scenarioSlug:pe,projectRoot:p}),qn(),await new Promise(Se=>setTimeout(Se,300));const Ce=na(se.url||null,P,N);if(!Ce)continue;const _e=F.join(ee,`${se.id}.png`),Ae=zr({bodyWidth:se.viewport_width||void 0,bodyHeight:se.viewport_height||void 0,dimension:se.dimension||void 0,codeyamRoot:p}),De=JSON.stringify({url:Ce,outputPath:_e,viewportWidth:Ae.width,viewportHeight:Ae.height,...se.component_name?{selector:"#codeyam-capture"}:{}});console.log(`[editor-register-scenario] Recapturing "${se.name}" (entity: ${ue})`);const Le=await ia(G,De,p);Le.success?(await u.updateTable("editor_scenarios").set({screenshot_path:`screenshots/${se.id}.png`}).where("id","=",se.id).execute(),console.log(`[editor-register-scenario] Recapture succeeded for "${se.name}"`)):console.warn(`[editor-register-scenario] Recapture failed for "${se.name}": ${Le.error}`)}catch(pe){console.warn(`[editor-register-scenario] Recapture error for "${se.name}": ${pe instanceof Error?pe.message:pe}`)}const re=F.join(p,".codeyam","active-scenario.json");await we.writeFile(re,JSON.stringify({scenarioId:b,scenarioSlug:Ct(a),type:s.type||null,timestamp:new Date().toISOString()})),qn(),ct.notifyChange("scenario")}}}}catch(E){console.warn(`[editor-register-scenario] Recapture of impacted scenarios failed (non-blocking): ${E instanceof Error?E.message:E}`)}try{const E=new Date().toISOString();jf(p,b,{name:a,description:o||null,componentName:i||null,componentPath:l||null,url:s.url||null,type:s.type||null,screenshotPath:k||null,viewportWidth:s.viewportWidth||null,viewportHeight:s.viewportHeight||null,createdAt:E,updatedAt:E})}catch(E){console.warn(`[editor-register-scenario] Failed to update scenario metadata (non-blocking): ${E instanceof Error?E.message:E}`)}try{Wa(s.url||void 0,b)}catch{}return new Response(JSON.stringify({success:!0,scenario:{id:b,name:a,description:o,componentName:i||null,componentPath:l||null,screenshotPath:k,url:s.url||null,type:s.type||null,viewportWidth:g.width,viewportHeight:g.height,dimension:s.dimension||null},updated:!x.isNew,screenshotCaptured:k!==null,capturedViewport:T,captureError:_,clientErrors:j,...v?{seedResult:v}:{}}),{headers:{"Content-Type":"application/json"}})}catch(s){const a=s instanceof Error?s.message:String(s);return console.error("[editor-register-scenario] Error:",s),new Response(JSON.stringify({error:a}),{status:500,headers:{"Content-Type":"application/json"}})}}const eg=Object.freeze(Object.defineProperty({__proto__:null,action:Xf},Symbol.toStringTag,{value:"Module"}));function tg(e){const t={},r=F.join(e,"app");if(!K.existsSync(r))return t;const s=l=>l.split("/").filter(c=>!c.startsWith("(")).join("/"),a=new Set(["_layout.tsx","_layout.ts","_layout.js","layout.tsx","layout.ts","layout.js"]),o=new Set([".tsx",".ts",".jsx",".js"]),i=(l,c)=>{for(const m of K.readdirSync(l,{withFileTypes:!0}))if(m.name!=="isolated-components")if(m.isDirectory())i(F.join(l,m.name),c?`${c}/${m.name}`:m.name);else if(m.name==="page.tsx"||m.name==="page.js"){const u=c?`app/${c}/${m.name}`:`app/${m.name}`,p=s(c);t[Xe(p?`/${p}`:"/")]=u}else{if(a.has(m.name))continue;{const u=F.extname(m.name);if(!o.has(u))continue;const p=F.basename(m.name,u),h=c?`app/${c}/${m.name}`:`app/${m.name}`,f=s(c);let y;p==="index"?y=f?`/${f}`:"/":y=f?`/${f}/${p}`:`/${p}`;const g=Xe(y);t[g]||(t[g]=h)}}};return i(r,""),t}function ng(e){try{const t=Ee("git rev-list --count HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();return parseInt(t,10)<=1}catch{return!0}}function rg(e){try{const t=F.join(e,".codeyam","editor-step.json"),r=K.readFileSync(t,"utf8");return JSON.parse(r).featureStartedAt||null}catch{return null}}function nc(e){try{const t=F.join(e,".codeyam","editor-step.json"),r=K.readFileSync(t,"utf8");return JSON.parse(r).feature||null}catch{return null}}function rc(e){try{const t=F.join(e,".codeyam","editor-user-prompt.txt");return K.readFileSync(t,"utf8").trim()||null}catch{return null}}async function or(e){const{projectRoot:t,scenarioInputs:r,glossaryInputs:s}=e,a=tg(t),o=new Set(Object.keys(a)),i=jn();if(i.length===0)return{entityChangeStatus:{},pageEntityNames:o};const l=ng(t),c=Xl(i,l);let m=[];try{await ze(),m=await st({})||[]}catch{}const u=ec(r,a,m);let p=u;if(s&&s.length>0){const f=new Set(u.map(g=>g.name)),y=Jf(s,f);p=[...u,...y]}return{entityChangeStatus:tc(c,p),pageEntityNames:o}}function sg(e,t,r,s){const a=s?s.replace("T"," ").replace(/\.\d{3}Z$/,""):null,o=[],i=[],l=new Set;for(const u of e){let p=null;if(u.component_name?p=u.component_name:p=Xe(u.url),!p)continue;const h=t[p];if(!h||u.component_name)continue;const f=u.created_at||"";(a?f>=a:!0)?(i.push({name:u.name,url:u.url,entityName:p}),l.add(p)):o.push({name:u.name,url:u.url,entityName:p,changeStatus:h.status,lastCaptured:f})}const c=[];for(const[u,p]of Object.entries(t)){if(!r.has(u)||l.has(u))continue;o.some(f=>f.entityName===u)||c.push({entityName:u,changeStatus:p.status})}const m=o.length===0&&c.length===0;return{staleScenarios:o,freshScenarios:i,uncoveredPages:c,pass:m}}async function ag(){const e=he()||process.cwd(),t=await Ie();if(!t)return Response.json({error:"No project configured"},{status:400});const r=F.join(e,".codeyam","editor-step.json");let s=null;try{const f=K.readFileSync(r,"utf8");s=JSON.parse(f).featureStartedAt||null}catch{}const{project:a}=await Re(t),i=await je().selectFrom("editor_scenarios").select(["id","name","component_name","component_path","url","type","created_at"]).where("project_id","=",a.id).orderBy("created_at","asc").execute(),l=yt(i,f=>`${f.name}::${f.url||"/"}`),c=l.map(f=>({componentName:f.component_name||null,componentPath:f.component_path||null,url:f.url??null}));let m={},u=new Set;try{const f=await or({projectRoot:e,scenarioInputs:c});m=f.entityChangeStatus,u=f.pageEntityNames}catch{}if(Object.keys(m).length===0)return Response.json({staleScenarios:[],uncoveredPages:[],freshScenarios:[],pass:!0,note:"No entity change data available — cannot determine coverage."});const p=l.map(f=>({name:f.name,component_name:f.component_name,url:f.url??null,created_at:f.created_at||""})),h=sg(p,m,u,s);return Response.json(h)}const og=Object.freeze(Object.defineProperty({__proto__:null,loader:ag},Symbol.toStringTag,{value:"Module"}));function ig({executionFlows:e,selections:t,onChange:r,disabled:s=!1}){const a=ie(i=>t.some(l=>l.flowId===i),[t]),o=ie(i=>{a(i.id)?r(t.filter(l=>l.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,a]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const l=a(i.id),c=i.usedInScenarios.length>0;return d("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[d("label",{className:"flex items-start gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:l,onChange:()=>o(i),disabled:s,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!c&&n("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&n("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&n("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),l&&i.requiredValues.length>0&&d("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[n("span",{className:"text-gray-700 font-medium",children:"Required values:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((m,u)=>d("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 Va(e,t){const r=(e||[]).map(c=>({...c,usedInScenarios:[]})),s=new Map;r.forEach(c=>{s.set(c.id,c)});const a=[];t.forEach(c=>{var u;const m=((u=c.metadata)==null?void 0:u.coveredFlows)||[];m.forEach(p=>{const h=s.get(p);h&&h.usedInScenarios.push({id:c.id||"",name:c.name})}),a.push({scenario:c,coveredFlowIds:m})});const o=r.length,i=r.filter(c=>c.usedInScenarios.length>0).length,l=o>0?i/o*100:0;return{executionFlows:r,totalFlows:o,coveredFlows:i,coveragePercentage:l,scenariosWithFlows:a}}function lg(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const cg=({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 dg({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await Xr(t,!0),s=r&&r.length>0?r[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const a=(i=s.scenarios)==null?void 0:i.find(l=>l.name===Zr);if(!a)throw new Response("Default scenario not found",{status:404});const o=await Ie();return Q({analysis:s,defaultScenario:a,entity:s.entity,entitySha:t,projectSlug:o})}function ug(){var B;const{analysis:e,defaultScenario:t,entity:r,entitySha:s,projectSlug:a}=qe(),o=St(),{iframeRef:i}=Fa(),[l,c]=M(""),[m,u]=M(400),[p,h]=M(!1),[f,y]=M(!1),[g,x]=M(!1),[b,w]=M(null),[v,C]=M(null),[P,N]=M([]),S=ae(()=>{var D;return!((D=e==null?void 0:e.metadata)!=null&&D.executionFlows)||!(e!=null&&e.scenarios)?[]:Va(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:k,isStarting:_,isLoading:j,showIframe:T,iframeKey:E,onIframeLoad:$}=pn({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}),R=ie(async()=>{var H,D,A,J;if(!l.trim()&&P.length===0){w("Please describe how you want to change the scenario or select execution flows");return}y(!0),w(null),C("Generating scenario with AI...");try{const V=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,existingScenarios:e.scenarios,scenariosDataStructure:(H=e.metadata)==null?void 0:H.scenariosDataStructure,flowSelections:P.length>0?P:void 0})}),q=await V.json();if(!V.ok||!q.success)throw new Error(q.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",q.data);const X=q.data;if(!X.name||!X.data)throw new Error("AI response missing required fields (name or data)");C("Saving new scenario..."),x(!0);const L={name:X.name,description:X.description||l,metadata:{data:X.data,interactiveExamplePath:(D=t.metadata)==null?void 0:D.interactiveExamplePath}},O=[...e.scenarios||[],L],z=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:O})}),G=await z.json();if(!z.ok||!G.success)throw new Error(G.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",G);const ee=(J=(A=G.analysis)==null?void 0:A.scenarios)==null?void 0:J.find(re=>re.name===X.name);if(!(ee!=null&&ee.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),C("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${s}`),1e3);return}if(k){C("Capturing screenshot...");const re=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:k,scenarioId:ee.id,projectId:e.projectId,viewportWidth:1440})}),ue=await re.json();!re.ok||!ue.success?(console.error("[CreateScenario] Capture failed:",ue),C("Scenario created! (Screenshot capture failed)")):C("Scenario created and captured!")}else C("Scenario created!");setTimeout(()=>{o(`/entity/${s}/scenarios/${ee.id}`)},1e3)}catch(V){console.error("[CreateScenario] Error:",V),w(V instanceof Error?V.message:String(V)),C(null)}finally{y(!1),x(!1)}},[l,P,e,t,s,k,o]),I=f||g,W=ie(()=>{h(!0)},[]),Y=ie(H=>{if(!p)return;const D=H.clientX;D>=250&&D<=600&&u(D)},[p]),U=ie(()=>{h(!1)},[]);return ne(()=>(p?(document.addEventListener("mousemove",Y),document.addEventListener("mouseup",U)):(document.removeEventListener("mousemove",Y),document.removeEventListener("mouseup",U)),()=>{document.removeEventListener("mousemove",Y),document.removeEventListener("mouseup",U)}),[p,Y,U]),d("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:d("div",{className:"flex items-end h-full px-6 gap-6",children:[d("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:()=>void o(`/entity/${s}`),className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:r==null?void 0:r.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:r==null?void 0:r.filePath,children:r==null?void 0:r.filePath})]}),d("div",{className:"flex items-end gap-8 shrink-0",children:[n(me,{to:`/entity/${s}/scenarios`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-medium border-b-2",style:{color:"#005C75",borderColor:"#005C75"},children:d("span",{className:"flex items-center gap-2",children:["Scenarios",n("span",{className:"inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full bg-[#cbf3fa] text-[#005c75]",children:((B=e==null?void 0:e.scenarios)==null?void 0:B.length)||0})]})}),n(me,{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(me,{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(me,{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(me,{to:`/entity/${s}/history`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"History"})]})]})}),d("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[d("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${m}px`},children:[d("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select execution flows and/or describe how you'd like to change it."})]}),S.length>0&&d("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[d("summary",{className:"px-3 py-2 text-sm font-medium text-gray-700 cursor-pointer hover:bg-gray-50 rounded-lg",children:["Select Execution Flows"," ",P.length>0&&d("span",{className:"text-blue-600",children:["(",P.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(ig,{executionFlows:S,selections:P,onChange:N,disabled:I})})]}),d("div",{className:"mb-4",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"Describe your scenario"}),n("textarea",{id:"prompt",value:l,onChange:H=>c(H.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:I})]}),d("div",{className:"space-y-2",children:[n("button",{onClick:()=>void R(),disabled:I||!l.trim()&&P.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:I?"Creating...":"Create Scenario"}),v&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:v}),b&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:b})]})]}),d("div",{onMouseDown:W,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:p?"#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:`
|
|
217
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
218
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
219
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
220
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
221
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:n(us,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:k,isStarting:_,isLoading:j,showIframe:T,iframeKey:E,onIframeLoad:$,projectSlug:a,defaultWidth:1440,defaultHeight:900})})]})]})}const mg=Je(function(){return n(ds,{children:n(ug,{})})}),pg=Object.freeze(Object.defineProperty({__proto__:null,default:mg,loader:dg,meta:cg},Symbol.toStringTag,{value:"Module"})),hg=$l;async function fg({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 Ie();if(!i)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:l}=await Re(i),c=je(),m=await c.selectFrom("editor_scenarios").selectAll().where("id","=",r).where("project_id","=",l.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,p=u&&u.startsWith("/"),h=!u||p?await Jl():null,f=hg(),y=na(u,h,f);if(console.log(`[editor-capture-scenario] URL resolution: explicit=${s||"none"}, db=${m.url||"none"}, proxy=${h||"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=Ct(m.name),b=F.join(g,".codeyam","active-scenario.json");await we.writeFile(b,JSON.stringify({scenarioId:r,scenarioSlug:x,timestamp:new Date().toISOString()})),qn(),console.log(`[editor-capture-scenario] Active scenario set to "${x}", cache invalidated`),await new Promise($=>setTimeout($,500));const w=F.join(g,".codeyam","editor-scenarios","screenshots");await we.mkdir(w,{recursive:!0});const v=F.join(w,`${r}.png`),C=aa(import.meta.url),P=await oa(C,g);console.log(`[editor-capture-scenario] Capture script: ${P}`);const N=zr({bodyWidth:a||m.viewport_width||void 0,bodyHeight:o||m.viewport_height||void 0,dimension:m.dimension||void 0,codeyamRoot:g}),S=JSON.stringify({url:y,outputPath:v,viewportWidth:N.width,viewportHeight:N.height,...m.component_name?{selector:"#codeyam-capture"}:{}});console.log(`[editor-capture-scenario] Running Playwright capture: url=${y}, output=${v}`);const k=Date.now(),_=await ia(P,S,g),j=Date.now()-k;if(console.log(`[editor-capture-scenario] Capture ${_.success?"succeeded":"FAILED"} in ${j}ms`),!_.success)return console.warn(`[editor-capture-scenario] Capture stdout: ${_.output.slice(0,500)}`),console.warn(`[editor-capture-scenario] Capture stderr: ${(_.error||"").slice(0,500)}`),new Response(JSON.stringify({error:"Failed to capture screenshot",details:_.error}),{status:500,headers:{"Content-Type":"application/json"}});const T=`screenshots/${r}.png`;try{await c.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}await c.updateTable("editor_scenarios").set({screenshot_path:T}).where("id","=",r).execute();const E=Vl(_.output);return await Gl(g,r,m.name,E),E.length>0&&console.warn(`[editor-capture-scenario] ${E.length} client-side error(s) detected:`,E),ct.notifyChange("scenario"),new Response(JSON.stringify({success:!0,screenshotPath:T,clientErrors:E}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-capture-scenario] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const gg=Object.freeze(Object.defineProperty({__proto__:null,action:fg},Symbol.toStringTag,{value:"Module"}));async function yg({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=Z.join(s,".codeyam","editor-scenarios","screenshots",r),o=Z.resolve(a),i=Z.resolve(Z.join(s,".codeyam","editor-scenarios","screenshots"));if(!o.startsWith(i))return new Response("Invalid path",{status:403});try{const l=await Ne.stat(a),c=`"${l.mtimeMs.toString(36)}-${l.size.toString(36)}"`;if(t.headers.get("if-none-match")===c)return new Response(null,{status:304,headers:{ETag:c}});const u=await Ne.readFile(a),p=Z.extname(a).toLowerCase(),h=p===".png"?"image/png":p===".jpg"||p===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(u,{status:200,headers:{"Content-Type":h,"Cache-Control":"public, max-age=0, must-revalidate",ETag:c}})}catch{return new Response("Image not found",{status:404})}}const xg=Object.freeze(Object.defineProperty({__proto__:null,loader:yg},Symbol.toStringTag,{value:"Module"}));async function bg({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=Z.join(s,".codeyam","journal","screenshots",r),o=Z.resolve(a),i=Z.resolve(Z.join(s,".codeyam","journal","screenshots"));if(!o.startsWith(i))return new Response("Invalid path",{status:403});try{const l=await Ne.stat(a),c=`"${l.mtimeMs.toString(36)}-${l.size.toString(36)}"`;if(t.headers.get("if-none-match")===c)return new Response(null,{status:304,headers:{ETag:c}});const u=await Ne.readFile(a),p=Z.extname(a).toLowerCase(),h=p===".png"?"image/png":p===".jpg"||p===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(u,{status:200,headers:{"Content-Type":h,"Cache-Control":"public, max-age=0, must-revalidate",ETag:c}})}catch{return new Response("Image not found",{status:404})}}const wg=Object.freeze(Object.defineProperty({__proto__:null,loader:bg},Symbol.toStringTag,{value:"Module"}));let Zt=null;async function vg({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioSlug:r,scenarioId:s,scenarioName:a,scenarioType:o,skipBroadcast:i}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({error:"scenarioSlug is required"}),{status:400,headers:{"Content-Type":"application/json"}});const l=he()||process.cwd(),c=Z.join(l,".codeyam"),m=Z.join(c,"active-scenario.json");let u=o||null;if(!u&&s){const y=Z.join(c,"editor-scenarios",`${s}.json`);try{fe.existsSync(y)&&(u=JSON.parse(fe.readFileSync(y,"utf-8")).type||null)}catch{}}fe.mkdirSync(c,{recursive:!0}),fe.writeFileSync(m,JSON.stringify({scenarioSlug:r,scenarioName:a||null,scenarioId:s||null,type:u,dataFile:s?`.codeyam/editor-scenarios/${s}.json`:null,switchedAt:new Date().toISOString()},null,2));let p=null;const h=u==="application"||u==="user";if(h&&s)if(Zt&&Zt.scenarioId===s)console.log(`[editor-switch-scenario] Seed already in progress for "${s}" — reusing`),p=await Zt.promise;else{const y=Ya(l),g=Z.join(c,"editor-scenarios",`${s}.seed.json`);if(y&&fe.existsSync(g)){console.log(`[editor-switch-scenario] Running seed adapter for ${u} scenario "${a||r}"`);const x=Ba(y,g).then(b=>{const w={success:b.success,error:b.error};return b.success?console.log(`[editor-switch-scenario] Seed adapter completed in ${b.durationMs}ms`):console.warn(`[editor-switch-scenario] Seed adapter failed: ${b.error}`),w});Zt={scenarioId:s,promise:x};try{p=await x}finally{Zt&&Zt.scenarioId===s&&(Zt=null)}}else y||(console.warn("[editor-switch-scenario] No seed adapter found — skipping database seeding"),p={success:!1,error:"No seed adapter found"})}qn();const f=i?0:Wa();return new Response(JSON.stringify({success:!0,scenarioSlug:r,refreshedClients:f,seeded:h,...p?{seedResult:p}:{}}),{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 Ng=Object.freeze(Object.defineProperty({__proto__:null,action:vg},Symbol.toStringTag,{value:"Module"}));var ye;(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={}))})(ye||(ye={}));function sc(e,t){return e?Object.values(ye.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const ac=sc(process.env.DEFAULT_SMALLER_MODEL,ye.Model.OPENAI_GPT4_1_MINI),Cg=sc(process.env.DEFAULT_LARGER_MODEL,ye.Model.OPENAI_GPT4_1),pt={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},zs={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},Sg={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},Bs={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},Rt={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},kg={[ye.Model.OPENAI_GPT5_1]:{id:ye.Model.OPENAI_GPT5_1,provider:pt,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[ye.Model.OPENAI_GPT5]:{id:ye.Model.OPENAI_GPT5,provider:pt,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[ye.Model.OPENAI_GPT5_MINI]:{id:ye.Model.OPENAI_GPT5_MINI,provider:pt,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[ye.Model.OPENAI_GPT5_NANO]:{id:ye.Model.OPENAI_GPT5_NANO,provider:pt,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[ye.Model.OPENAI_GPT4_1]:{id:ye.Model.OPENAI_GPT4_1,provider:pt,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[ye.Model.OPENAI_GPT4_1_MINI]:{id:ye.Model.OPENAI_GPT4_1_MINI,provider:pt,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ye.Model.OPENAI_GPT4_O]:{id:ye.Model.OPENAI_GPT4_O,provider:pt,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[ye.Model.OPENAI_GPT4_O_MINI]:{id:ye.Model.OPENAI_GPT4_O_MINI,provider:pt,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[ye.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:ye.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:zs,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[ye.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:ye.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:zs,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[ye.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:ye.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:zs,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[ye.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:ye.Model.OPENAI_GPT_OSS_120B_GROQ,provider:Sg,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[ye.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:ye.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:Rt,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[ye.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:ye.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:Rt,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[ye.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:ye.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:Rt,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ye.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:ye.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:Rt,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[ye.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:ye.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:Rt,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[ye.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:ye.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:Bs,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[ye.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:ye.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:Bs,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[ye.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:ye.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:Bs,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[ye.Model.PHIND_CODELLAMA]:{id:ye.Model.PHIND_CODELLAMA,provider:pt,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ye.Model.GOOGLE_GEMINI_PRO]:{id:ye.Model.GOOGLE_GEMINI_PRO,provider:Rt,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ye.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:ye.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:Rt,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ye.Model.META_CODELLAMA_34B_INSTRUCT]:{id:ye.Model.META_CODELLAMA_34B_INSTRUCT,provider:Rt,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ye.Model.OPENAI_GPT4_PREVIEW]:{id:ye.Model.OPENAI_GPT4_PREVIEW,provider:pt,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function fs(e){const t=kg[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function Eg(e){return fs(e).maxCompletionTokens}function _g(e){return fs(e).pricing}const Go=1e6;function Ag({model:e,usage:t}){const r=_g(e);return r?t.prompt_tokens*(r.input/Go)+t.completion_tokens*(r.output/Go):null}function Pg({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=Ag({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 jg({messages:{system:e,prompt:t},model:r,responseType:s,jsonSchema:a}){const o=r??ac,i=fs(o);Eg(o);const l=[];return e&&l.push({role:"system",content:e}),l.push({role:"user",content:[{type:"text",text:t}]}),{messages:l,model:i.apiModelName,response_format:s==="json_schema"&&a?{type:"json_schema",json_schema:{name:a.name,schema:a.schema,strict:a.strict!==!1}}:{type:s&&s=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}const la="/tmp/codeyam-e2e-tracking";let Ys,Us;function Mg(){return Ys===void 0&&(Ys=process.env.CODEYAM_E2E_TRACK_DATA==="true"),Ys}function Tg(){return Us===void 0&&(Us=!process.env.CODEYAM_LLM_FIXTURES_DIR),Us}function $g(){K.existsSync(la)||K.mkdirSync(la,{recursive:!0})}function Ig(e){const t=JSON.stringify(e,null,0);return Bd.createHash("md5").update(t).digest("hex")}function Rg(e,t,r){return[e].join("_")+".json"}function oc(e,t,r,s){if(!Mg())return;$g();const a=Rg(e),o=F.join(la,a),i=Ig(t);if(Tg()){const l={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:s,dataHash:i,data:t};K.writeFileSync(o,JSON.stringify(l,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(K.existsSync(o)){const l=JSON.parse(K.readFileSync(o,"utf-8")),c={matches:i===l.dataHash,firstRunHash:l.dataHash};if(c.matches)console.log(`[E2E Tracking] Match at ${e} hash=${i.substring(0,8)}`);else{c.differences=ca(l.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${l.dataHash}`),console.log(` Second run hash: ${i}`);const m=o.replace(".json","_DIFF.json");K.writeFileSync(m,JSON.stringify({checkpoint:e,entityName:r,scenarioName:s,firstRun:l.data,secondRun:t,differences:c.differences},null,2)),console.log(` Diff saved to: ${m}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function ca(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(...ca(e[o],t[o],`${r}[${o}]`));return s}if(typeof e=="object"&&typeof t=="object"){const a=Object.keys(e),o=Object.keys(t),i=Array.from(new Set([...a,...o]));for(const l of i){const c=e[l],m=t[l];l in e?l in t?s.push(...ca(c,m,`${r?r+".":""}${l}`)):s.push(`${r?r+".":""}${l}: missing in second run`):s.push(`${r?r+".":""}${l}: missing in first run`)}return s}if(e!==t){const a=JSON.stringify(e),o=JSON.stringify(t);a.length<100&&o.length<100?s.push(`${r||"root"}: ${a} vs ${o}`):s.push(`${r||"root"}: values differ (${a.length} chars vs ${o.length} chars)`)}return s}Ca(Na);const fr=new Vd({concurrency:100,timeout:1200*1e3,autoStart:!0}),Ko={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},Dt={};async function da({type:e,systemMessage:t,prompt:r,jsonResponse:s=!0,jsonSchema:a,model:o=ac,attempts:i=0}){var S,k,_,j,T,E,$;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await Dg(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${fr.size}, running=${fr.pending}]`);const l=Date.now();let c,m=0;const u=fs(o),p=process.env[u.provider.apiKeyEnvVar];if(!p)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 h=new Jd({apiKey:p,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=jg(f),g=await fr.add(()=>(c=Date.now(),Ao(async()=>{const R=Date.now(),I=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],W=setInterval(()=>{const Y=Math.floor((Date.now()-R)/1e3),U=Math.floor(Y/10)%I.length;jo(1,`${I[U]} [type=${e}, model=${o}, elapsed=${Y}s]`)},1e4);try{return await h.chat.completions.create(y,{timeout:300*1e3})}finally{clearInterval(W)}},{...Ko,onFailedAttempt:R=>{m++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:R,prompt:r,systemMessage:t,attempts:i,retryCount:m})}})));if(!g)throw new Error("Completion call returned no result");const x=g,b=Date.now(),w=Pg({chatRequest:f,chatCompletion:x,model:o});if(!w)throw new Error("Failed to get LLM call stats");w.retries=m,w.wait_ms=c-l,w.duration_ms=b-l;const v=(S=x.choices)==null?void 0:S[0];let C=null;if(v){if(!v.finish_reason)throw console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({chatCompletion:x,chatRequest:f},null,2)),new Error("completionCall(): missing finish_reason in LLM response");C=(k=v.message)==null?void 0:k.content}let P=C;C&&(P=C.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const N=s?P&&(((_=P.match(/\{[\s\S]*\}/))==null?void 0:_[0])??P):P;if(!N){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:N,rawCompletion:C,chatCompletion:x,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await da({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(N.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:C,prompt:r,systemMessage:t}),new Error("Empty completion");if(s)try{JSON.parse(N)}catch(R){if(console.log("CodeYam Error: Invalid JSON in completion",{error:R.message,model:o,completion:N.substring(0,500),rawCompletion:C==null?void 0:C.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:R.message});const I=`Your previous response contained invalid JSON with the following error:
|
|
222
|
-
|
|
223
|
-
${R.message}
|
|
224
|
-
|
|
225
|
-
Here was your previous response:
|
|
226
|
-
\`\`\`
|
|
227
|
-
${N}
|
|
228
|
-
\`\`\`
|
|
229
|
-
|
|
230
|
-
Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,W=await fr.add(()=>Ao(async()=>{const D=Date.now(),A=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],J=setInterval(()=>{const V=Math.floor((Date.now()-D)/1e3),q=Math.floor(V/10)%A.length;jo(1,`${A[q]} [type=${e}, model=${o}, elapsed=${V}s]`)},1e4);try{return await h.chat.completions.create({...y,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:N},{role:"user",content:I}]},{timeout:300*1e3})}finally{clearInterval(J)}},{...Ko,onFailedAttempt:D=>{console.log("CodeYam Error: Correction call failed",{error:D,attempts:i})}}));if(!W)throw new Error("Correction call returned no result");const Y=W,U=(E=(T=(j=Y.choices)==null?void 0:j[0])==null?void 0:T.message)==null?void 0:E.content;let B=U;U&&(B=U.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const H=B&&((($=B.match(/\{[\s\S]*\}/))==null?void 0:$[0])??B);if(!H)throw new Error("Correction attempt returned empty completion");try{JSON.parse(H),console.log("CodeYam: JSON correction successful");const D=Date.now();return w.duration_ms=D-l,{finishReason:Y.choices[0].finish_reason,completion:H,stats:w}}catch(D){return console.log("CodeYam Error: Corrected JSON still invalid",{error:D.message,correctedCompletion:H.substring(0,500)}),await da({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${R.message}`)}return oc(`completionCall_${e}`,{completion:N,finishReason:x.choices[0].finish_reason}),{finishReason:x.choices[0].finish_reason,completion:N,stats:w}}async function Dg(e,t,r){var o,i,l,c,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(w=>w.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${t}`);const p={};for(const w of u)try{const v=s.readFileSync(a.join(t,w),"utf-8"),C=JSON.parse(v);p[C.prompt_type]||(p[C.prompt_type]=[]),p[C.prompt_type].push(C)}catch(v){console.warn(`Failed to parse LLM fixture file ${w}:`,v)}for(const w of Object.keys(p))p[w].sort((v,C)=>{const P=v.created_at??0,N=C.created_at??0;return P-N});const h=p[e];if(!h||h.length===0){const w=Object.keys(p).join(", ");return console.warn(`CodeYam Test: No captured LLM call found for type '${e}'. Available types: ${w}`),{finishReason:"stop",completion:"{}",stats:{model:"fixture-fallback",prompt_type:e,system_message:"",prompt_text:"",response:"{}",input_tokens:0,output_tokens:0,cost:0}}}let f;if(["generateEntityScenarioData","generateChunkMockData","generateMissingMockData"].includes(e)&&r){const w=r.match(/Scenario name must match exactly: "([^"]+)"/),v=w==null?void 0:w[1];if(v){const C={};for(const N of h)try{const k=((o=JSON.parse(N.props||"{}").scenario)==null?void 0:o.name)||"__NO_SCENARIO__";C[k]||(C[k]=[]),C[k].push(N)}catch{}const P=C[v];if(P&&P.length>0){const N=`${t}::${e}::${v}`;Dt[N]===void 0&&(Dt[N]=0);const S=Dt[N];Dt[N]=(S+1)%P.length,f=P[S],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${v}' [${S+1}/${P.length}]`)}else{const N=Object.keys(C).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${v}'. Available: [${N}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const w=`${t}::${e}`;Dt[w]===void 0&&(Dt[w]=0);const v=Dt[w];Dt[w]=(v+1)%h.length,f=h[v],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${v+1}/${h.length}]`)}let g;try{g=((c=(l=(i=JSON.parse(f.response).choices)==null?void 0:i[0])==null?void 0:l.message)==null?void 0:c.content)||f.response}catch{g=f.response}let x=g;g&&(x=g.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const b=x&&(((m=x.match(/\{[\s\S]*\}/))==null?void 0:m[0])??x);return oc(`completionCall_${e}`,{completion:b||"",finishReason:"stop"}),{finishReason:"stop",completion:b||"",stats:{model:f.model??"fixture",prompt_type:e,system_message:f.system_message??"",prompt_text:f.prompt_text??"",response:f.response??"",input_tokens:f.input_tokens??0,output_tokens:f.output_tokens??0,cost:f.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(u){throw console.error("CodeYam Test Error: Failed to replay LLM call:",u),u}}function qo(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function Og(e){const{propsJson:t,...r}=e,s=JSON.stringify(t,null,2),a=va(),o=Date.now(),i={...r,id:a,created_at:o,props:s};let l;const c=`${i.object_id}_${a}.json`;if(process.env.DYNAMODB_PATH?l=F.join(process.env.DYNAMODB_PATH,c):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(l=F.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",c)),l)try{const u=F.dirname(l);return await we.mkdir(u,{recursive:!0}),await we.writeFile(l,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${l}`),{id:a}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const m=qo();if(!m)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,p]of Object.entries(i))typeof p>"u"&&console.log(`CodeYam Warning: LLM call ${a} property ${u} with explicit value 'undefined'`);try{return await new Kr().send(new Gd({TableName:qo(),Item:qd(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 Kr({});new Kr({});new Kr({});const Lg=3,Fg=2,Ga=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+Lg*String(t).length*(1+Fg)});new Ea(Ga());new Ea(Ga());new Ea(Ga());class zg{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 Bg{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 Yg{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 Ug{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 Wg{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 Hg{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 Jg{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 Vg{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.withReturnValues();s.addType(a,"unknown")}isComplete(){return!0}}class Gg{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 Kg{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 qg{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 Qg{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 Zg{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 Xg{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown"),s.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class e0{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 t0{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 n0{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 r0{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 s0{getReturnType(){return"unknown"}addEquivalences(t,r,s){t.getLastFunctionCallSegment()}isComplete(){return!0}}class a0{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 o0(){const e=new zg;return e.register("filter",new Bg,"Array"),e.register("map",new Qg,"Array"),e.register("flatMap",new Zg,"Array"),e.register("join",new qg,"Array"),e.register("find",new Wg,"Array"),e.register("findLast",new e0,"Array"),e.register("at",new Xg,"Array"),e.register("reduce",new Hg,"Array"),e.register("concat",new Jg,"Array"),e.register("slice",new Vg,"Array"),e.register("splice",new Gg,"Array"),e.register("push",new Kg,"Array"),e.register("some",new Yg,"Array"),e.register("every",new Ug,"Array"),e.register("fromEntries",new t0,"Object"),e.register("split",new n0,"String"),e.register("then",new r0,"Promise"),e.register("useState",new a0,"React"),e.register("useMemo",new s0,"React"),e}o0();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 i0=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),l0=new Set(["find","findLast","at","pop","shift"]),c0=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),d0=new Set([...i0,...l0,...c0]),u0=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),m0=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),p0=new Set([...u0,...m0]);[...d0,...p0];class h0{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 h0({enabled:!1});function Xt(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 f0(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function gr(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let g0=0;class Ka{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++g0,this.enabled=(t==null?void 0:t.enabled)??!1,this.outputPath=(t==null?void 0:t.outputPath)??"/tmp/codeyam/transform-trace.json",this.enabled&&console.log(`[Tracer] Initialized (id=${this.tracerId}, output=${this.outputPath})`)}log(t){this.isEnabled()&&console.log(`[Tracer] ${t}`)}isEnabled(){const t=process.env.CODEYAM_TRACE_TRANSFORMS;return t==="1"||t==="true"?!0:this.enabled}enable(){this.enabled=!0}disable(){this.enabled=!1}setOutputPath(t){this.outputPath=t}setProjectSlug(t){this.projectSlug=t}startEntity(t){if(!this.isEnabled())return;this.currentEntity=t.name;const r=this.traces.get(t.name);if(r){this.log(`startEntity: ${t.name} already exists, preserving ${r.stages.length} stages`);return}this.log(`startEntity: ${t.name}`),this.traces.set(t.name,{entityName:t.name,entityType:t.entityType,filePath:t.filePath,stages:[],operations:[]})}snapshot(t,r,s){var c,m,u,p;if(!this.isEnabled())return;const a=this.traces.get(t);if(!a)return this.log(`snapshot: no trace for ${t}, creating one`),this.startEntity({name:t,entityType:"unknown",filePath:"unknown"}),this.snapshot(t,r,s);this.log(`snapshot: ${t} → ${r}`),this.currentStage=r;const o=JSON.parse(JSON.stringify(s)),i={stage:r,timestamp:Date.now(),data:o},l=a.stages[a.stages.length-1];if(l&&(i.diffFromPrevious={signatureSchema:Xt(l.data.signatureSchema,o.signatureSchema),returnValueSchema:Xt(l.data.returnValueSchema,o.returnValueSchema)},o.dependencySchemas||l.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const h=new Set([...Object.keys(o.dependencySchemas??{}),...Object.keys(l.data.dependencySchemas??{})]);for(const f of h){const y=(c=l.data.dependencySchemas)==null?void 0:c[f],g=(m=o.dependencySchemas)==null?void 0:m[f];for(const x of new Set([...Object.keys(y??{}),...Object.keys(g??{})])){const b=`${f}::${x}`,w=(u=y==null?void 0:y[x])==null?void 0:u.returnValueSchema,v=(p=g==null?void 0:g[x])==null?void 0:p.returnValueSchema,C=Xt(w,v);f0(C)&&(i.diffFromPrevious.dependencySchemas[b]=C)}}}a.stages.push(i)}operation(t,r){if(!this.isEnabled())return;const s=this.traces.get(t);s&&s.operations.push({...r,stage:r.stage??this.currentStage??void 0,timestamp:Date.now()})}computeFlushSummary(){var a;const t={},r=new Map;for(const[o,i]of this.traces){let l=0;for(const c of i.stages){if(!c.diffFromPrevious)continue;const u=`${((a=i.stages[i.stages.indexOf(c)-1])==null?void 0:a.stage)??"start"}→${c.stage}`;if(t[u]||(t[u]={added:0,removed:0,changed:0}),c.diffFromPrevious.signatureSchema){const p=c.diffFromPrevious.signatureSchema;t[u].added+=Object.keys(p.added).length,t[u].removed+=Object.keys(p.removed).length,t[u].changed+=Object.keys(p.changed).length,l+=gr(p)}if(c.diffFromPrevious.returnValueSchema){const p=c.diffFromPrevious.returnValueSchema;t[u].added+=Object.keys(p.added).length,t[u].removed+=Object.keys(p.removed).length,t[u].changed+=Object.keys(p.changed).length,l+=gr(p)}}r.set(o,l)}const s=[...r.entries()].sort((o,i)=>i[1]-o[1]).slice(0,10).map(([o])=>o);return{stageChangeCounts:t,entitiesWithMostChanges:s}}flush(){if(!this.isEnabled())return;if(this.traces.size===0){this.log("flush: no traces to write");return}const t=Array.from(this.traces.keys()),r=t.map(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},l=F.dirname(this.outputPath);K.existsSync(l)||K.mkdirSync(l,{recursive:!0});const c=K.openSync(this.outputPath,"w");try{K.writeSync(c,`{
|
|
231
|
-
"meta": `),K.writeSync(c,JSON.stringify(o,null,2)),K.writeSync(c,`,
|
|
232
|
-
"summary": `),K.writeSync(c,JSON.stringify(i,null,2)),K.writeSync(c,`,
|
|
233
|
-
"entities": {`);let m=!0;for(const[u,p]of this.traces)m||K.writeSync(c,","),K.writeSync(c,`
|
|
234
|
-
${JSON.stringify(u)}: `),K.writeSync(c,JSON.stringify(p,null,2)),m=!1;K.writeSync(c,`
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
`),this.log(`flush: wrote trace to ${this.outputPath}`)}finally{K.closeSync(c)}}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=K.readFileSync(t,"utf-8"),s=JSON.parse(r),a=new Ka({enabled:!1});a.projectSlug=s.meta.projectSlug;for(const[o,i]of Object.entries(s.entities))a.traces.set(o,i);return a}getSummary(){var a,o,i;const t={},r=new Map;for(const[l,c]of this.traces){let m=0;for(let u=1;u<c.stages.length;u++){const p=c.stages[u],f=`${((a=c.stages[u-1])==null?void 0:a.stage)??"start"}→${p.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(o=p.diffFromPrevious)!=null&&o.signatureSchema){const y=p.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+=gr(y)}if((i=p.diffFromPrevious)!=null&&i.returnValueSchema){const y=p.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+=gr(y)}}r.set(l,m)}const s=[...r.entries()].sort((l,c)=>c[1]-l[1]).slice(0,10).map(([l,c])=>({name:l,totalChanges:c}));return{entityCount:this.traces.size,stageChangeCounts:t,entitiesWithMostChanges:s}}getEntitySummary(t){const r=this.traces.get(t);return r?{entityName:t,stages:r.stages.map(s=>({stage:s.stage,diffFromPrevious:s.diffFromPrevious?{signatureSchema:s.diffFromPrevious.signatureSchema,returnValueSchema:s.diffFromPrevious.returnValueSchema}:void 0}))}:null}getOperations(t,r){const s=this.traces.get(t);return s?r?s.operations.filter(a=>a.path&&r.test(a.path)):s.operations:[]}tracePath(t,r){var o,i;const s=this.traces.get(t),a=[];if(!s)return{entityName:t,path:r,history:a};for(const l of s.stages){const c=(o=l.data.signatureSchema)==null?void 0:o[r],m=(i=l.data.returnValueSchema)==null?void 0:i[r],u=c??m;u!==void 0&&a.push({stage:l.stage,value:u})}for(const l of s.operations)l.path===r&&a.push({operation:l.operation,stage:l.stage,value:l.after??l.before,context:l.context});return{entityName:t,path:r,history:a}}getEntityTrace(t){return this.traces.get(t)}getEntityNames(){return[...this.traces.keys()]}findProperty(t,r){const s=this.traces.get(t);if(!s)return[];const a=[],o=new RegExp(`(^|\\.)${r}(\\.|\\[|$)`);for(const i of s.stages){for(const[l,c]of Object.entries(i.data.signatureSchema??{}))o.test(l)&&a.push({stage:i.stage,path:l,type:c,schemaType:"signature"});for(const[l,c]of Object.entries(i.data.returnValueSchema??{}))o.test(l)&&a.push({stage:i.stage,path:l,type:c,schemaType:"returnValue"});for(const[l,c]of Object.entries(i.data.dependencySchemas??{}))for(const[m,u]of Object.entries(c))for(const[p,h]of Object.entries(u.returnValueSchema??{}))o.test(p)&&a.push({stage:i.stage,path:`${l}/${m}::${p}`,type:h,schemaType:"dependency"})}return a}findTypeInconsistencies(t){const r=this.traces.get(t);if(!r)return[];let s=r.stages[r.stages.length-1];for(let c=r.stages.length-1;c>=0;c--)if(Object.keys(r.stages[c].data.dependencySchemas??{}).length>0){s=r.stages[c];break}if(!s)return[];const a=new Set(["length","toString","valueOf","constructor"]),o=new Map,i=(c,m)=>{const u=c.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!u)return;const p=u[1],h=u[2]==="[]";if(a.has(p))return;const f=p+(h?"[]":"");o.has(f)||o.set(f,[]),o.get(f).push({path:c,type:m})};for(const[,c]of Object.entries(s.data.dependencySchemas??{}))for(const[,m]of Object.entries(c))for(const[u,p]of Object.entries(m.returnValueSchema??{}))i(u,p);const l=[];for(const[c,m]of o)new Set(m.map(p=>p.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&l.push({propertyName:c,paths:m.map(p=>({...p,stage:s.stage}))});return l.sort((c,m)=>{const u=new Set(c.paths.map(h=>h.type)).size;return new Set(m.paths.map(h=>h.type)).size-u}),l}getStageDiffSummary(t,r,s){const a=this.traces.get(t);if(!a)return null;const o=a.stages.find(h=>h.stage===r),i=a.stages.find(h=>h.stage===s);if(!o||!i)return null;const l={added:[],removed:[],typeChanged:[]},c=o.data.returnValueSchema??{},m=i.data.returnValueSchema??{},u=new Set(Object.keys(c)),p=new Set(Object.keys(m));for(const h of p)u.has(h)?c[h]!==m[h]&&l.typeChanged.push({path:h,from:c[h],to:m[h]}):l.added.push(`${h}: ${m[h]}`);for(const h of u)p.has(h)||l.removed.push(`${h}: ${c[h]}`);return l}traceSchemaTransform(t,r,s,a,o){if(!this.enabled)return a(s),s;const i={...s};a(s);const l=Xt(i,s);for(const[c,m]of Object.entries(l.added))this.operation(t,{operation:r,path:c,before:void 0,after:m,context:{...o,changeType:"added"}});for(const[c,m]of Object.entries(l.removed))this.operation(t,{operation:r,path:c,before:m,after:void 0,context:{...o,changeType:"removed"}});for(const[c,{from:m,to:u}]of Object.entries(l.changed))this.operation(t,{operation:r,path:c,before:m,after:u,context:{...o,changeType:"changed"}});return s}traceSchemaTransformResult(t,r,s,a,o){if(!this.enabled)return;const i=Xt(s,a);for(const[l,c]of Object.entries(i.added))this.operation(t,{operation:r,path:l,before:void 0,after:c,context:{...o,changeType:"added"}});for(const[l,c]of Object.entries(i.removed))this.operation(t,{operation:r,path:l,before:c,after:void 0,context:{...o,changeType:"removed"}});for(const[l,{from:c,to:m}]of Object.entries(i.changed))this.operation(t,{operation:r,path:l,before:c,after:m,context:{...o,changeType:"changed"}})}traceDependencySchemaTransform(t,r,s,a,o="both"){if(!this.enabled){for(const i in s)for(const l in s[i]){const c=s[i][l];(o==="signature"||o==="both")&&c.signatureSchema&&a(c.signatureSchema),(o==="returnValue"||o==="both")&&c.returnValueSchema&&a(c.returnValueSchema)}return}for(const i in s)for(const l in s[i]){const c=s[i][l],m={filePath:i,dependencyName:l};(o==="signature"||o==="both")&&c.signatureSchema&&this.traceSchemaTransform(t,r,c.signatureSchema,a,{...m,schemaType:"signature"}),(o==="returnValue"||o==="both")&&c.returnValueSchema&&this.traceSchemaTransform(t,r,c.returnValueSchema,a,{...m,schemaType:"returnValue"})}}traceDependencySchemaChanges(t,r,s,a){var i;if(!this.enabled){a();return}const o={};for(const l in s){o[l]={};for(const c in s[l]){const m=s[l][c];o[l][c]={sig:{...m.signatureSchema||{}},rv:{...m.returnValueSchema||{}}}}}a();for(const l in s)for(const c in s[l]){const m=s[l][c],u=(i=o[l])==null?void 0:i[c],p={filePath:l,dependencyName:c};if(m.signatureSchema){const h=(u==null?void 0:u.sig)||{},f=Xt(h,m.signatureSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...p,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:{...p,schemaType:"signature",changeType:"changed"}})}if(m.returnValueSchema){const h=(u==null?void 0:u.rv)||{},f=Xt(h,m.returnValueSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...p,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:{...p,schemaType:"returnValue",changeType:"changed"}})}}}}function y0(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const Qo=new Ka({enabled:y0(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{Qo.isEnabled()&&Qo.flush()});function ic(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 Kd.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),ic(e)}return null}}function x0({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:s}){let a="";return s&&s.length>0&&(a=`
|
|
238
|
-
User-selected Execution Flow Values:
|
|
239
|
-
The user has specifically requested these values be used in the scenario:
|
|
240
|
-
${s.map(o=>` - ${o.path}: ${o.value}${o.isCustom?" (custom value)":""}`).join(`
|
|
241
|
-
`)}
|
|
242
|
-
|
|
243
|
-
IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
|
|
244
|
-
`),`Mock Scenario Data Structure:
|
|
245
|
-
\`\`\`
|
|
246
|
-
${JSON.stringify(r,null,2)}
|
|
247
|
-
\`\`\`
|
|
248
|
-
Existing Mock Scenario Data:
|
|
249
|
-
\`\`\`
|
|
250
|
-
${JSON.stringify(t,null,2)}
|
|
251
|
-
\`\`\`
|
|
252
|
-
${a}
|
|
253
|
-
New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
|
|
254
|
-
`}function b0({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}){const o=s.find(i=>i.name===Zr);return`Mock Scenario Data Structure:
|
|
255
|
-
\`\`\`
|
|
256
|
-
${JSON.stringify({props:a.arguments,dataVariables:a.dataForMocks},null,2)}
|
|
257
|
-
\`\`\`
|
|
258
|
-
|
|
259
|
-
Existing Mock Scenario Data:
|
|
260
|
-
\`\`\`
|
|
261
|
-
${JSON.stringify(s.map(i=>({name:i.name,data:Vn(o.metadata.data,i.metadata.data)})),null,2)}
|
|
262
|
-
\`\`\`
|
|
263
|
-
|
|
264
|
-
Mock Scenario that should be edited: "${t}"
|
|
265
|
-
${r?`The portion of the data that should be edited:
|
|
266
|
-
\`\`\`
|
|
267
|
-
${JSON.stringify(r,null,2)}
|
|
268
|
-
\`\`\``:""}
|
|
269
|
-
|
|
270
|
-
How this data should be changed: "${e}"
|
|
271
|
-
`}async function w0({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,flowSelections:o,model:i}){const l=t?b0({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}):x0({description:e,existingScenarios:s,scenariosDataStructure:a,flowSelections:o}),c=await da({type:"guessScenarioDataFromDescription",systemMessage:t?N0(r):v0,prompt:l,model:i??Cg});await Og({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,model:i},...c.stats});const{completion:m}=c;return m?ic(m):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const v0=`
|
|
272
|
-
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.
|
|
273
|
-
|
|
274
|
-
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.
|
|
275
|
-
|
|
276
|
-
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.
|
|
277
|
-
|
|
278
|
-
You must respond with valid JSON following this format of this TS type definition:
|
|
279
|
-
\`\`\`
|
|
280
|
-
export type ScenarioData = {
|
|
281
|
-
name: string;
|
|
282
|
-
description: string;
|
|
283
|
-
data: {
|
|
284
|
-
mockData: { [key: string]: unknown };
|
|
285
|
-
argumentsData: { [key: string]: unknown };
|
|
286
|
-
};
|
|
287
|
-
};
|
|
288
|
-
|
|
289
|
-
\`\`\`
|
|
290
|
-
`,N0=e=>`
|
|
291
|
-
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.
|
|
292
|
-
|
|
293
|
-
Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
|
|
294
|
-
${e?`
|
|
295
|
-
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.`:""}
|
|
296
|
-
|
|
297
|
-
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.
|
|
298
|
-
|
|
299
|
-
You must respond with valid JSON following this type definition:
|
|
300
|
-
\`\`\`
|
|
301
|
-
{
|
|
302
|
-
data: {
|
|
303
|
-
mockData: { [key: string]: unknown };
|
|
304
|
-
argumentsData: { [key: string]: unknown };
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
\`\`\`
|
|
308
|
-
`;async function C0({request:e}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:s,scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:l}=t;if(!r&&(!l||l.length===0))return Q({error:"Missing required field: description or flowSelections"},{status:400});const c=await w0({description:r||"",existingScenarios:s??[],scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:l}),m=(c==null?void 0:c.data)||c;return Q({success:!0,data:m})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),Q({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const S0=Object.freeze(Object.defineProperty({__proto__:null,action:C0},Symbol.toStringTag,{value:"Module"}));function k0(e,t,r=new Date){const s={"1d":1,"3d":3,"7d":7,"30d":30}[t],a=new Date(r);a.setDate(a.getDate()-s);const o=a.toISOString().split("T")[0],i=e.filter(p=>p.date>=o),l=new Set(i.map(p=>p.commitSha).filter(Boolean)),c=new Map;for(const p of i)if(p.scenarioScreenshots)for(const h of p.scenarioScreenshots){c.has(h.name)||c.set(h.name,[]);const f=c.get(h.name);f.some(y=>y.path===h.path)||f.push({path:h.path,time:p.time})}for(const p of c.values())p.sort((h,f)=>h.time.localeCompare(f.time));const m=[],u=new Map;for(const[p,h]of c){const f=p.indexOf(" - ");if(f!==-1){const y=p.slice(0,f);u.has(y)||u.set(y,[]),u.get(y).push({name:p,screenshots:h})}else m.push({name:p,screenshots:h})}return{commitCount:l.size,entryCount:i.length,appScenarios:m,componentGroups:u,totalScenarios:c.size}}function E0(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 _0(e){const t=new Map;for(const r of e){let s;if("componentName"in r&&r.componentName)s=r.componentName;else if("componentName"in r&&r.componentName===null)s="App";else{const o=r.name.indexOf(" - ");s=o!==-1?r.name.slice(0,o):"App"}const a=t.get(s)||[];a.push(r),t.set(s,a)}return[...t.entries()].sort(([r],[s])=>r==="App"?-1:s==="App"?1:r.localeCompare(s))}function A0(e,t){const r=e.replace(/[^a-zA-Z0-9_\-]/g,"_");return`${t.toISOString().replace(/:/g,"-").replace(/\.\d+Z$/,"")}_${r}.png`}function P0(e){const{title:t,timeStr:r,type:s,description:a,allScenarioNames:o,screenshot:i,scenarioScreenshots:l,commitSha:c,commitMessage:m,featureName:u,userPrompt:p}=e,h=["","---","",`### ${t}`,`**Time:** ${r}`,`**Type:** ${s}`];if(u&&h.push(`**Feature:** ${u}`),p&&h.push(`**Prompt:** ${p}`),o.length>0&&h.push(`**Scenarios:** ${o.join(", ")}`),h.push(""),h.push(a),i&&(h.push(""),h.push(``)),l.length>0){h.push(""),h.push("**Scenario Screenshots:**");for(const f of l)h.push(""),h.push(``)}return c&&m&&(h.push(""),h.push(`**Commit:** \`${c}\` — ${m}`)),h.push(""),h.join(`
|
|
309
|
-
`)}function j0(e,t){return e.findIndex(r=>r.time===t)}function M0(e){return!!e.commitSha}function T0(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 $0(e,t,r,s){const a=`
|
|
310
|
-
**Commit:** \`${r}\` — ${s||"no message"}
|
|
311
|
-
`,o=`### ${t}`,i=e.lastIndexOf(o);if(i===-1)return null;const l=e.indexOf(`
|
|
312
|
-
---
|
|
313
|
-
`,i+1),c=l!==-1?l:e.length;return e.slice(0,c)+a+e.slice(c)}async function I0(e){console.log(`[editorScenarioLookup] Looking up screenshots for ${e.length} scenarios: ${e.join(", ")}`);try{const t=await Ie();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up scenarios"),[];const{project:r}=await Re(t),a=await je().selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","url"]).where("project_id","=",r.id).where("name","in",e).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] DB query returned ${a.length} matching scenarios:`,a.map(c=>({name:c.name,screenshot_path:c.screenshot_path,id:c.id})));const o=a.filter(c=>!c.screenshot_path);o.length>0&&console.warn(`[editorScenarioLookup] ${o.length} scenarios have no screenshot_path:`,o.map(c=>c.name));const i=a.filter(c=>c.screenshot_path),l=yt(i,c=>c.name).map(c=>({name:c.name,screenshotPath:c.screenshot_path,scenarioId:c.id,componentName:c.component_name||null,url:c.url||null}));return console.log(`[editorScenarioLookup] Found ${l.length} scenarios with screenshots`),l}catch(t){return console.error("[editorScenarioLookup] Failed to look up scenario screenshots:",t),[]}}async function R0(e){console.log(`[editorScenarioLookup] Looking up screenshots by entity names: ${e.join(", ")}`);try{const t=await Ie();if(!t)return[];const{project:r}=await Re(t),a=await je().selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","url"]).where("project_id","=",r.id).orderBy("created_at","asc").execute(),o=new Set(e),l=a.filter(m=>{const u=Ja({componentName:m.component_name,url:m.url});return o.has(u)}).filter(m=>m.screenshot_path),c=yt(l,m=>m.name).map(m=>({name:m.name,screenshotPath:m.screenshot_path,scenarioId:m.id,componentName:m.component_name||null,url:m.url||null}));return console.log(`[editorScenarioLookup] Found ${c.length} scenarios for ${e.length} entities`),c}catch(t){return console.error("[editorScenarioLookup] Failed to look up entity screenshots:",t),[]}}async function lc(e){console.log("[editorScenarioLookup] Looking up session scenario screenshots",e?`(after ${e})`:"(all session)");try{const t=await Ie();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up session scenarios"),[];const{project:r}=await Re(t),s=je(),a=he()||process.cwd();let o=null;const i=F.join(a,".codeyam","editor-step.json");try{const h=K.readFileSync(i,"utf8");o=JSON.parse(h).featureStartedAt||null}catch{return console.warn("[editorScenarioLookup] No editor-step.json found — cannot determine session start"),[]}if(!o)return console.warn("[editorScenarioLookup] No featureStartedAt found in editor-step.json"),[];const l=e&&e>o?e:o,c=La(l),m=await s.selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","url"]).where("project_id","=",r.id).where("created_at",">=",c).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] Query returned ${m.length} scenarios since ${l}`);const u=m.filter(h=>h.screenshot_path),p=yt(u,h=>h.name).map(h=>({name:h.name,screenshotPath:h.screenshot_path,scenarioId:h.id,componentName:h.component_name||null,url:h.url||null}));return console.log(`[editorScenarioLookup] Found ${p.length} session scenarios with screenshots`),p}catch(t){return console.error("[editorScenarioLookup] Failed to look up session scenario screenshots:",t),[]}}async function ua(e,t,r){const s=F.join(t,".codeyam","journal","screenshots");await we.mkdir(s,{recursive:!0});const a=[];for(const o of e){const i=F.join(t,".codeyam","editor-scenarios",o.screenshotPath),l=A0(o.name,r),c=F.join(s,l);console.log(`[editorScenarioLookup] Copying scenario screenshot: "${o.name}" from ${i} → ${c}`);try{await we.access(i),await we.copyFile(i,c),a.push({name:o.name,path:`screenshots/${l}`,componentName:o.componentName,url:o.url}),console.log(`[editorScenarioLookup] Successfully copied screenshot for "${o.name}"`)}catch(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 D0({request:e}){if(e.method!=="PATCH")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{time:r,commitSha:s,commitMessage:a,description:o,includeSessionScenarios:i}=t;if(!r)return new Response(JSON.stringify({error:"time is required to identify the entry"}),{status:400,headers:{"Content-Type":"application/json"}});const l=process.env.CODEYAM_ROOT_PATH||process.cwd(),c=F.join(l,".codeyam","journal"),m=F.join(c,"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 p=j0(u.entries,r);if(p===-1)return new Response(JSON.stringify({error:`No journal entry found with time "${r}"`}),{status:404,headers:{"Content-Type":"application/json"}});const h=u.entries[p];if(M0(h))return console.log(`[editor-journal-update] Rejected: entry "${h.title}" already committed (${h.commitSha}). Create a new entry instead.`),new Response(JSON.stringify({error:`Journal entry already committed (${h.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 lc();g.length>0&&(f=g.map(x=>x.name),y=await ua(g,l,new Date))}if(T0(h,{commitSha:s,commitMessage:a,description:o,scenarios:f,scenarioScreenshots:y}),u.entries[p]=h,await we.writeFile(m,JSON.stringify(u,null,2),"utf8"),console.log("[editor-journal-update] Updated index.json"),s)try{const g=h.date,x=F.join(c,`${g}.md`);let b="";try{b=await we.readFile(x,"utf8")}catch{}if(b){const w=$0(b,h.title,s,a||null);w&&(await we.writeFile(x,w,"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 "${h.title}"`),new Response(JSON.stringify({success:!0,entry:h}),{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 O0=Object.freeze(Object.defineProperty({__proto__:null,action:D0},Symbol.toStringTag,{value:"Module"}));async function L0({request:e}){var t;try{const r=process.env.CODEYAM_ROOT_PATH||process.cwd(),s=await Kl(r);let a=0;const o={};for(const[c,m]of Object.entries(s))m.errors.length>0&&(o[c]=m,a+=m.errors.length);const i=yf(),l=((t=i==null?void 0:i.errors)==null?void 0:t.length)??0;return new Response(JSON.stringify({hasErrors:a>0||l>0,totalErrors:a+l,scenarios:o,livePreview:i?{loaded:i.loaded,hasContent:i.hasContent,errors:i.errors,url:i.url,lastUpdated:i.lastUpdated}:null}),{headers:{"Content-Type":"application/json"}})}catch(r){const s=r instanceof Error?r.message:String(r);return console.error("[editor-client-errors] Error:",r),new Response(JSON.stringify({error:s}),{status:500,headers:{"Content-Type":"application/json"}})}}const F0=Object.freeze(Object.defineProperty({__proto__:null,loader:L0},Symbol.toStringTag,{value:"Module"}));async function z0({request:e}){try{const r=(await mn()||[]).filter(i=>i.analyses&&i.analyses.length>0).map(i=>{var y;const l=i.analyses[0],c=l.scenarios||[],m=!((y=l.status)!=null&&y.finishedAt),u=i.entityType||"visual",h=u==="library"||u==="functionCall"?c.some(g=>{var x;return!!((x=g.metadata)!=null&&x.executionResult)}):c.some(g=>{var x,b,w,v;return((b=(x=g.metadata)==null?void 0:x.screenshotPaths)==null?void 0:b[0])&&!((w=g.metadata)!=null&&w.noScreenshotSaved)&&!((v=g.metadata)!=null&&v.sameAsDefault)}),f=c.length;return{name:i.name,entityType:u,filePath:i.filePath||"",hasScreenshot:h,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 B0=Object.freeze(Object.defineProperty({__proto__:null,loader:z0},Symbol.toStringTag,{value:"Module"}));async function Y0({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{title:r,type:s,description:a,scenarios:o,includeSessionScenarios:i,screenshot:l,commitSha:c,commitMessage:m}=t;if(console.log(`[editor-journal-entry] Creating journal entry: title="${r}", type="${s}", scenarios=${JSON.stringify(o||[])}, includeSessionScenarios=${!!i}, screenshot=${l||"none"}`),!r||!s||!a)return console.warn("[editor-journal-entry] Missing required fields:",{title:!!r,type:!!s,description:!!a}),new Response(JSON.stringify({error:"title, type, and description are required"}),{status:400,headers:{"Content-Type":"application/json"}});const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),p=F.join(u,".codeyam","journal");await we.mkdir(p,{recursive:!0});const h=new Date,f=h.toISOString().split("T")[0],y=h.toISOString();let g=o||[];const x=F.join(p,"index.json");let b={entries:[]};try{const I=await we.readFile(x,"utf8");b=JSON.parse(I)}catch{}let w;i&&b.entries.length>0&&(w=b.entries[b.entries.length-1].time);const v=i?await lc(w):o&&o.length>0?await I0(o):[];i&&v.length>0&&(g=v.map(I=>I.name));const C=await ua(v,u,h);let P;try{const I=he()||process.cwd(),W=await Ie();if(W){const{project:Y}=await Re(W),B=await je().selectFrom("editor_scenarios").select(["name","component_name","component_path","url"]).where("project_id","=",Y.id).orderBy("created_at","asc").execute(),D=yt(B,J=>`${J.name}::${J.url||"/"}`).map(J=>({componentName:J.component_name||null,componentPath:J.component_path||null,url:J.url??null})),A=await or({projectRoot:I,scenarioInputs:D});Object.keys(A.entityChangeStatus).length>0&&(P=A.entityChangeStatus)}}catch{}if(P&&Object.keys(P).length>0){const I=new Set(v.map(Y=>Y.name)),W=Object.entries(P).filter(([,Y])=>Y.status==="impacted").map(([Y])=>Y);if(W.length>0){const Y=[],U=new Set(v.map(B=>Ja(B)));for(const B of W)U.has(B)||Y.push(B);if(Y.length>0)try{const B=await R0(Y);if(B.length>0){const H=await ua(B.filter(D=>!I.has(D.name)),u,h);C.push(...H),g.push(...H.map(D=>D.name))}}catch{}}}let N=C,S=g;if(!i&&P&&Object.keys(P).length>0){N=Gf(C,P);const I=new Set(N.map(W=>W.name));S=g.filter(W=>I.has(W))}const k=nc(u),_=rc(u);let j;try{const I=jn();I.length>0&&(j=I.filter(W=>W.status!=="deleted").map(W=>({path:W.path,status:W.status})))}catch{}const T=F.join(p,`${f}.md`);let E="";try{E=await we.readFile(T,"utf8")}catch{E=`# Development Journal — ${f}
|
|
314
|
-
`}const $=P0({title:r,timeStr:y,type:s,description:a,allScenarioNames:S,screenshot:l||null,scenarioScreenshots:N,commitSha:c||null,commitMessage:m||null,featureName:k,userPrompt:_});await we.writeFile(T,E+$,"utf8"),console.log(`[editor-journal-entry] Written daily markdown: ${T}`);const R={date:f,time:y,title:r,type:s,description:a,scenarios:S,screenshot:l||null,scenarioScreenshots:N,commitSha:c||null,commitMessage:m||null,entityChangeStatus:P,featureName:k,userPrompt:_,modifiedFiles:j};return b.entries.push(R),await we.writeFile(x,JSON.stringify(b,null,2),"utf8"),console.log(`[editor-journal-entry] Updated index.json (now ${b.entries.length} entries)`),ct.notifyChange("journal"),console.log(`[editor-journal-entry] Done: title="${r}", scenarioScreenshotsEmbedded=${N.length}`),new Response(JSON.stringify({success:!0,entry:R,scenarioScreenshotsFound:N.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 U0=Object.freeze(Object.defineProperty({__proto__:null,action:Y0},Symbol.toStringTag,{value:"Module"}));function W0({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 c=F.join(r,".codeyam","active-scenario.json");if(!K.existsSync(c))return new Response(JSON.stringify({}),{headers:t});o=JSON.parse(K.readFileSync(c,"utf-8")).scenarioId||null}if(!o)return new Response(JSON.stringify({}),{headers:t});const i=F.join(r,".codeyam","editor-scenarios",`${o}.json`);if(!K.existsSync(i))return new Response(JSON.stringify({}),{headers:t});const l=K.readFileSync(i,"utf-8");return new Response(l,{headers:t})}catch{return new Response(JSON.stringify({}),{headers:t})}}const H0=Object.freeze(Object.defineProperty({__proto__:null,loader:W0},Symbol.toStringTag,{value:"Module"}));async function J0(e,t){const r=he();if(!r)return{entityCalls:[],analysisCalls:[]};const s=F.join(r,".codeyam","llm-calls");try{await we.access(s)}catch{return{entityCalls:[],analysisCalls:[]}}const a=[],o=[];try{const l=(await we.readdir(s)).filter(b=>b.endsWith(".json")),c=`${e}_`,m=t?`${t}_`:null,u=[],p=[];for(const b of l)b.startsWith(c)||m&&b.startsWith(m)?u.push(b):p.push(b);const h=u.map(async b=>{try{const w=F.join(s,b),v=await we.readFile(w,"utf-8");return JSON.parse(v)}catch{return null}}),f=p.map(async b=>{try{const w=F.join(s,b),v=await we.readFile(w,"utf-8"),C=JSON.parse(v);return C.object_id===e||t&&C.object_id===t?C:null}catch{return null}}),[y,g]=await Promise.all([Promise.all(h),Promise.all(f)]),x=[...y,...g].filter(b=>b!==null);for(const b of x)b.object_id===e?a.push(b):t&&b.object_id===t&&o.push(b);a.sort((b,w)=>w.created_at-b.created_at),o.sort((b,w)=>w.created_at-b.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:a,analysisCalls:o}}async function V0({params:e,request:t}){const{entitySha:r}=e;if(!r)return Q({error:"Entity SHA is required"},{status:400});const a=new URL(t.url).searchParams.get("analysisId")||void 0,o=await J0(r,a);return Q(o)}const G0=Object.freeze(Object.defineProperty({__proto__:null,loader:V0},Symbol.toStringTag,{value:"Module"}));async function K0({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=he()||process.cwd(),r=Z.join(t,".codeyam","config.json");if(!fe.existsSync(r))return new Response(JSON.stringify({error:"No config.json found"}),{status:404,headers:{"Content-Type":"application/json"}});const s=await e.json(),a=JSON.parse(fe.readFileSync(r,"utf8"));return s.projectTitle!==void 0&&(a.projectTitle=s.projectTitle),s.projectDescription!==void 0&&(a.projectDescription=s.projectDescription),s.defaultScreenSize!==void 0&&(a.defaultScreenSize=s.defaultScreenSize),s.screenSizes!==void 0&&(a.screenSizes=s.screenSizes),fe.writeFileSync(r,JSON.stringify(a,null,2)),s.defaultScreenSize&&!s.skipBroadcast&&ql(s.defaultScreenSize),ct.notifyChange("unknown"),new Response(JSON.stringify({success:!0,projectTitle:a.projectTitle||null,projectDescription:a.projectDescription||null,defaultScreenSize:a.defaultScreenSize||null,screenSizes:a.screenSizes||null}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const q0=Object.freeze(Object.defineProperty({__proto__:null,action:K0},Symbol.toStringTag,{value:"Module"}));function Q0(e){try{const t=F.join(e,"package.json"),r=JSON.parse(K.readFileSync(t,"utf8")),s={...r.dependencies,...r.devDependencies};return s.vitest?"vitest":s.jest?"jest":null}catch{return null}}function Z0(e,t){var i;const s=JSON.parse(t).testResults||[],a=[];for(const l of s)for(const c of l.assertionResults||[]){const m=c.ancestorTitles||[],u=c.title||c.fullName||"unknown",p=m.length>0?`${m.join(" > ")} > ${u}`:u;a.push({title:u,fullName:p,status:c.status==="passed"?"passed":c.status==="failed"?"failed":"skipped",duration:c.duration,failureMessages:(i=c.failureMessages)!=null&&i.length?c.failureMessages:void 0})}const o=a.some(l=>l.status==="failed");return{testFilePath:e,status:o?"failed":"passed",testCases:a}}async function cc(e,t){const r=Q0(e);if(!r)return{testFilePath:t,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};const s=F.isAbsolute(t)?t:F.join(e,t);if(!K.existsSync(s))return{testFilePath:t,status:"error",testCases:[],errorMessage:"Test file not found"};const a=F.join(wa.tmpdir(),`codeyam-test-result-${Date.now()}.json`);return new Promise(o=>{var p;let i,l;r==="vitest"?(l="node",i=["./node_modules/.bin/vitest","run","--reporter=json","--outputFile",a,t]):(l="./node_modules/.bin/jest",i=["--json","--outputFile",a,"--testPathPatterns",t]);const c=Et(l,i,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let m="";(p=c.stderr)==null||p.on("data",h=>{m+=h.toString()});const u=setTimeout(()=>{c.kill("SIGTERM"),o({testFilePath:t,status:"error",testCases:[],errorMessage:"Test timed out after 30 seconds"})},3e4);c.on("close",()=>{clearTimeout(u);try{const h=K.readFileSync(a,"utf8");K.unlinkSync(a),o(Z0(t,h))}catch{o({testFilePath:t,status:"error",testCases:[],errorMessage:m.trim().slice(0,500)||"Test runner failed to produce output"})}}),c.on("error",h=>{clearTimeout(u),o({testFilePath:t,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${h.message}`})})})}async function X0({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 cc(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 ey=Object.freeze(Object.defineProperty({__proto__:null,loader:X0},Symbol.toStringTag,{value:"Module"}));function Zo(e,t){var r,s;try{return((s=(r=Ee(`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 ty(e,t,r,s){const a=rr.createHash("sha256");return a.update(`${e}:${t}:${r}:${s}`),a.digest("hex").substring(0,16)}function dc(){const e=he();if(!e)throw new Error("No project root found");const t=Z.join(e,".codeyam","cache","branch-entity-diff");return fe.existsSync(t)||fe.mkdirSync(t,{recursive:!0}),t}function ny(e){try{const t=dc(),r=Z.join(t,`${e}.json`);if(!fe.existsSync(r))return null;const s=fe.readFileSync(r,"utf8");return JSON.parse(s)}catch(t){return console.error("Failed to read cache:",t),null}}function ry(e,t){try{const r=dc(),s=Z.join(r,`${e}.json`);fe.writeFileSync(s,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function sy(e,t,r){const s=Ir(t,e),a=Ir(r,e),o=new Map(s.map(u=>[u.name,u])),i=new Map(a.map(u=>[u.name,u])),l=[],c=[],m=[];for(const[u,p]of i){const h=o.get(u);h?h.sha!==p.sha&&c.push({name:u,baseSha:h.sha,compareSha:p.sha,entityType:p.entityType}):l.push(p)}for(const[u,p]of o)i.has(u)||m.push(p);return{filePath:e,newEntities:l,modifiedEntities:c,deletedEntities:m}}function ay(e,t){const r=he();if(!r)throw new Error("No project root found");const s=Zo(e,r),a=Zo(t,r);if(!s||!a)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=ty(e,t,s,a),i=ny(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const l=Ql(e,t),c=[];for(const u of l)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const p=Sr(u.path,e,t),h=Ir(p.oldContent,u.path);c.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:h})}else if(u.status==="added"){const p=Sr(u.path,e,t),h=Ir(p.newContent,u.path);c.push({filePath:u.path,newEntities:h,modifiedEntities:[],deletedEntities:[]})}else{const p=Sr(u.path,e,t),h=sy(u.path,p.oldContent,p.newContent);(h.newEntities.length>0||h.modifiedEntities.length>0||h.deletedEntities.length>0)&&c.push(h)}const m={baseBranch:e,compareBranch:t,baseCommitSha:s,compareCommitSha:a,fileComparisons:c,cacheKey:o,computedAt:new Date().toISOString()};return ry(o,m),m}function oy({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),s=t.searchParams.get("compare");if(!r||!s)return Q({error:"Missing required parameters: base and compare"},{status:400});const a=ay(r,s);return Q(a)}catch(t){return console.error("Failed to compute branch entity diff:",t),Q({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const iy=Object.freeze(Object.defineProperty({__proto__:null,loader:oy},Symbol.toStringTag,{value:"Module"}));async function ly({request:e}){if(e.method!=="POST")return Q({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 Q({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 Q({error:"Project root not found"},{status:500});const l=F.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),c=JSON.stringify({url:r,scenarioId:s,projectId:a,projectRoot:i,viewportWidth:o}),m=await new Promise(h=>{const f=F.join(i,".codeyam","db.sqlite3"),y=Et("npx",["tsx",l,c],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let g="",x="";y.stdout.on("data",b=>{const w=b.toString();g+=w;const v=w.trim().split(`
|
|
315
|
-
`);for(const C of v)C.includes("[Capture]")&&console.log(C)}),y.stderr.on("data",b=>{const w=b.toString();x+=w,console.error("[Capture:Error]",w.trim())}),y.on("close",b=>{h(b===0?{success:!0,output:g}:{success:!1,output:g,error:x||`Process exited with code ${b}`})}),y.on("error",b=>{console.error("[Capture] Failed to spawn child process:",b),h({success:!1,output:"",error:b.message})})});if(!m.success)return Q({error:"Failed to capture screenshot",details:m.error},{status:500});const u=m.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return Q({error:"Failed to parse capture result"},{status:500});const p=JSON.parse(u[1]);return Q(p)}catch(t){return console.error("[Capture] Error:",t),Q({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const cy=Object.freeze(Object.defineProperty({__proto__:null,action:ly},Symbol.toStringTag,{value:"Module"}));function dy(e){const t=e||process.cwd();try{return Ee("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 uy(e){const t=e||process.cwd();try{return Ee("git rev-parse --git-dir",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),!0}catch{return!1}}function my(e){if(uy(e))return!1;Ee("git init",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]});try{Ee('git config user.email "codeyam@local"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Ee('git config user.name "CodeYam"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}catch{}return!0}function py(e){Ee("git add -A",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}function hy(e,t){return Ee(`git commit -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),dy(e)}function fy(e){return/^[0-9a-f]{7,40}$/i.test(e)}function gy(e,t){try{return Ee(`git cat-file -t ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"}),!0}catch{return!1}}function yy(e,t){try{return{stashed:!Ee(`git stash push -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:"pipe"}).includes("No local changes")}}catch{return{stashed:!1}}}function xy(e,t){Ee(`git checkout ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"})}async function by({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(!fy(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}`),!gy(s,r))return new Response(JSON.stringify({success:!1,error:`Commit ${r} not found`}),{status:400,headers:{"Content-Type":"application/json"}});const{stashed:a}=yy(s,"codeyam: auto-stash before time travel");a&&console.log("[editor-load-commit] Stashed uncommitted changes");try{xy(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 wy=Object.freeze(Object.defineProperty({__proto__:null,action:by},Symbol.toStringTag,{value:"Module"}));async function vy(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await ze();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=je(),o=s.entitySha,i=await a.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let l={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?l=JSON.parse(i.metadata):l=i.metadata),l.defaultWidth=t,await a.updateTable("entities").set({metadata:JSON.stringify(l)}).where("sha","=",o).execute(),console.log(`[recapture] Updated defaultWidth for entity ${o} to ${t}`),!s.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=s.scenarios)==null?void 0:f.length)||0} scenarios`),await En(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 c=he();if(!c)throw new Error("Project root not found");const m=F.join(c,".codeyam","config.json"),u=JSON.parse(K.readFileSync(m,"utf8")),{projectSlug:p}=u;if(!p)throw new Error("Project slug not found in config");const{jobId:h}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:p,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${h}`),{jobId:h}}async function Ny(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await ze();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(p=>p.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 En(e,p=>{if(p&&(p.readyToBeCaptured=!0,delete p.finishedAt,p.scenarios)){const h=p.scenarios.find(f=>f.name===a.name);h&&(delete h.finishedAt,delete h.startedAt,delete h.error,delete h.errorStack,delete h.screenshotStartedAt,delete h.screenshotFinishedAt,delete h.interactiveStartedAt,delete h.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${a.name} for recapture`);const o=he();if(!o)throw new Error("Project root not found");const i=F.join(o,".codeyam","config.json"),l=JSON.parse(K.readFileSync(i,"utf8")),{projectSlug:c}=l;if(!c)throw new Error("Project slug not found in config");const{jobId:m}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:c,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${m}`),{jobId:m}}async function Cy({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Mt()),!r)return Q({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a||!o)return Q({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${a}, scenario ${o}`);const i=await Ny(a,o,r);return console.log("[API] Scenario recapture queued",i),Q({success:!0,message:"Scenario recapture queued",...i})}catch(s){return console.log("[API] Error during scenario recapture:",s),Q({error:"Failed to recapture scenario",details:s instanceof Error?s.message:String(s)},{status:500})}}const Sy=Object.freeze(Object.defineProperty({__proto__:null,action:Cy},Symbol.toStringTag,{value:"Module"}));async function ma(e){try{return await Ne.stat(e),!0}catch{return!1}}async function uc(){try{const e=he();if(!e)return null;const t=Z.join(e,".codeyam","config.json");return JSON.parse(await Ne.readFile(t,"utf-8")).projectSlug||null}catch{return null}}function ky(){return`/private/tmp/claude-501/-${(he()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const kr="/tmp/claude-rule-markers",Ey=/<system-reminder>[\s\S]*?<\/system-reminder>/g,Xo=2e3;function _y(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 Ay=["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 Py(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 jy(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(`
|
|
316
|
-
###`);return a!==-1&&(s=s.slice(0,a).trim()),s||void 0}function My(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const s of Ay)if(r.includes(s))return!0}return!1}function Ty(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 $y(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 Iy(e){const t=[],r={};for(const s of e){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}const i=o.type;if(i==="progress"||i==="system"||i==="result")continue;const c=(o.message||{}).content,m=o.timestamp||"";if(i==="user"){if(typeof c=="string")t.push({type:"user_prompt",text:c,timestamp:m,agent_id:String(o.agentId||o.session_id||"unknown"),slug:String(o.slug||"")});else if(Array.isArray(c)){for(const u of c)if(typeof u=="object"&&u!==null&&u.type==="tool_result"){const p=u,h=String(p.tool_use_id||"");let f=p.content;const y=!!p.is_error;typeof f=="string"&&(f=f.replace(Ey,"").trim()),t.push({type:"tool_result",tool_use_id:h,tool_name:r[h]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:y,timestamp:m})}}}else if(i==="assistant"&&Array.isArray(c))for(const u of c){if(typeof u!="object"||u===null)continue;const p=u;if(p.type==="text"){const h=String(p.text||"").trim();h&&t.push({type:"assistant_text",text:h,timestamp:m})}else if(p.type==="tool_use"){const h=String(p.id||""),f=String(p.name||"unknown"),y=p.input||{};r[h]=f,t.push({type:"tool_call",tool_use_id:h,name:f,input:y,timestamp:m})}}}return t}function Ry(e,t){return e.type==="user_prompt"||e.type==="assistant_text"?(e.text||"").toLowerCase().includes(t):e.type==="tool_call"?(e.name||"").toLowerCase().includes(t)?!0:JSON.stringify(e.input||{}).toLowerCase().includes(t):e.type==="tool_result"?(e.content||"").toLowerCase().includes(t):!1}const yn=20;async function ei(e){const r=(await Ne.readFile(e.filePath,"utf-8")).split(`
|
|
317
|
-
`),s=Iy(r);if(s.length===0)return null;const a=s.find(v=>v.type==="user_prompt"),o=e.stem,i=Ty(r);let l=(a==null?void 0:a.slug)||"",c=(a==null?void 0:a.timestamp)||"";c||(c=new Date(e.mtime).toISOString());let m;if(e.filePath.endsWith(".log")){e.stem.endsWith("-stale")?l=l||"rule-reflection/stale":e.stem.endsWith("-conversation")?l=l||"rule-reflection/conversation":e.stem.endsWith("-interruption")?l=l||"rule-reflection/interruption":l=l||"rule-reflection";const v=e.filePath.replace(/\.log$/,".context");if(await ma(v))try{m=await Ne.readFile(v,"utf-8")}catch{}}const u=s.filter(v=>v.type==="tool_call").length,p=s.filter(v=>v.type==="assistant_text").length,h=s.filter(v=>v.type==="tool_result"&&v.is_error&&v.content!=="Sibling tool call errored"),f=h.length,y=h.map(v=>{const C=v.content||"Unknown error";return C.length>150?C.slice(0,150)+"...":C});for(const v of s)v.type==="tool_call"&&v.name&&v.input&&(v.summary=_y(v.name,v.input));for(const v of s)v.type==="tool_result"&&v.content&&v.content.length>Xo&&(v.truncated=!0,v.fullLength=v.content.length,v.content=v.content.slice(0,Xo));const g=Py(s),x=My(s),b=jy(m),w=$y(r);return{id:o,slug:l,timestamp:c,model:i,sourceFile:e.filePath,stats:{toolCalls:u,textBlocks:p,errors:f,errorMessages:y},entries:s,context:m,conversationSnippet:b,ruleChanges:g,hasConfusion:x,sessionResult:w}}async function Dy(){const e=ky(),t=kr,r=[];if(await ma(e)){const i=await Ne.readdir(e);for(const l of i)if(l.endsWith(".output")){const c=Z.join(e,l),m=await Ne.stat(c);r.push({filePath:c,stem:l.replace(".output",""),mtime:m.mtimeMs})}}const s=new Set,a=await uc(),o=[];a&&o.push(Z.join(t,a)),o.push(t);for(const i of o){if(!await ma(i))continue;const l=await Ne.readdir(i);for(const c of l){if(!c.endsWith(".log")||s.has(c))continue;s.add(c);const m=Z.join(i,c),u=await Ne.stat(m);r.push({filePath:m,stem:c.replace(".log",""),mtime:u.mtimeMs})}}return r.sort((i,l)=>l.mtime-i.mtime),r}async function Oy({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 Dy();if(!s){const u=o.length,p=(a-1)*yn,h=o.slice(p,p+yn),f=[];for(const y of h){const g=await ei(y);g&&f.push(g)}return Response.json({agents:f,total:u,page:a,pageSize:yn})}const i=[];for(const u of o){const p=await ei(u);if(!p)continue;(p.id.toLowerCase().includes(s)||p.slug.toLowerCase().includes(s)||p.entries.some(f=>Ry(f,s)))&&i.push(p)}const l=i.length,c=(a-1)*yn,m=i.slice(c,c+yn);return Response.json({agents:m,total:l,page:a,pageSize:yn})}catch(r){return console.error("[api.agent-transcripts] Error:",r),Response.json({error:"Failed to load agent transcripts",details:r instanceof Error?r.message:String(r)},{status:500})}}const Ly=Object.freeze(Object.defineProperty({__proto__:null,loader:Oy},Symbol.toStringTag,{value:"Module"})),mc="__codeyam_editor_dev_server__",ti=30;function qa(){return globalThis[mc]??null}function pc(e){globalThis[mc]=e}function yr(e,t){const r=[Z.join(e,".next","dev","lock"),Z.join(e,"node_modules",".vite","deps","_lock")];for(const s of r)try{fe.existsSync(s)&&(fe.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=Ee(`lsof -ti:${t}`,{encoding:"utf8"}).trim();s&&(Ee(`lsof -ti:${t} | xargs kill`),console.log(`[editor-dev-server] Killed orphaned process(es) on port ${t}: ${s}`))}catch{}}function Fy({request:e}){const t=qa();return t?new Response(JSON.stringify({status:t.status,url:t.url,proxyUrl:Bl(),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 zy({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"?pa():r==="stop"?ni():r==="restart"?(ni(),await new Promise(s=>setTimeout(s,1e3)),pa()):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 By(){let t=Z.dirname(new URL(import.meta.url).pathname);for(let s=0;s<5;s++){const a=Z.dirname(t);if(Z.basename(a)==="webserver"||Z.basename(t)==="webserver"){t=Z.basename(t)==="webserver"?t:a;break}t=a}const r=[Z.join(t,"scripts","codeyam-preload.mjs"),Z.join(t,"scripts","codeyam-preload.mjs")];for(const s of r)if(fe.existsSync(s))return s;return console.warn("[editor-dev-server] codeyam-preload.mjs not found, SSR fetch interception disabled"),null}function pa(e=!1){var N,S;const t=qa();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=parseInt(process.env.CODEYAM_PORT||"3111",10),{proxyPort:a,devServerPort:o}=Tl(s),i=cf(r,o);if("error"in i)return new Response(JSON.stringify({error:i.error}),{status:400,headers:{"Content-Type":"application/json"}});const{command:l,args:c,env:m}=i;yr(r,o),yr(r,3e3),yr(r,3001),yr(r,5173),console.log(`[editor-dev-server] Starting: ${l} ${c.join(" ")} in ${r}`);const u=By(),p=u?`--import ${u}`:"",{NODE_OPTIONS:h,PORT:f,CODEYAM_PORT:y,...g}=process.env,x={};try{const k=Z.join(r,".codeyam","config.json"),_=JSON.parse(fe.readFileSync(k,"utf-8"));for(const j of _.environmentVariables||[])j.key&&j.value!==void 0&&(x[j.key]=j.value)}catch{}const b=Et(l,c,{cwd:r,stdio:["ignore","pipe","pipe"],env:{...g,...x,FORCE_COLOR:"1",BROWSER:"none",...p?{NODE_OPTIONS:p}:{},CODEYAM_PROXY_URL:`http://localhost:${a}`,...m},detached:!0});b.unref();const w=e?((t==null?void 0:t.retryCount)??0)+1:0,v={process:b,url:null,status:"starting",errorMessage:null,stderrBuffer:[],pid:b.pid||0,startedAt:Date.now(),retryCount:w};pc(v);const C=(k,_)=>{const j=k.toString(),T=j.split(`
|
|
318
|
-
`).filter(E=>E.trim());if(T.length>0&&(v.stderrBuffer.push(...T),v.stderrBuffer.length>ti&&(v.stderrBuffer=v.stderrBuffer.slice(-ti))),v.status==="starting"){const E=uf(j);E&&(v.url=E,v.status="running",console.log(`[editor-dev-server] URL detected: ${v.url}`),sa({port:a,targetUrl:v.url}).then(()=>Jo()))}};(N=b.stdout)==null||N.on("data",k=>C(k)),(S=b.stderr)==null||S.on("data",k=>C(k));const P=parseInt(m.PORT||"0",10);return P>0&&(async()=>{if(await new Promise(_=>setTimeout(_,1e4)),v.status!=="starting")return;console.log(`[editor-dev-server] Stdout detection timed out, polling port ${P}...`);const k=await pf(P,{intervalMs:2e3,maxAttempts:15});k&&v.status==="starting"&&(v.url=k,v.status="running",console.log(`[editor-dev-server] URL detected via polling: ${v.url}`),sa({port:a,targetUrl:v.url}).then(()=>Jo()))})(),b.on("exit",k=>{console.log(`[editor-dev-server] Process exited with code ${k}`);const _=Date.now()-v.startedAt,j=v.status==="running",T=hf({exitCode:k??null,uptime:_,retryCount:v.retryCount,wasRunning:j});if(T.action==="retry")console.log(`[editor-dev-server] Quick failure (${_}ms), auto-retrying...`),v.status="stopped",pa(!0);else if(T.action==="error"){v.status="error";const E=v.stderrBuffer.length>0?v.stderrBuffer.join(`
|
|
319
|
-
`):"",$=j?`Dev server exited with code ${k}`:`Dev server exited (code ${k}) before it started serving`;v.errorMessage=E?`${$}
|
|
320
|
-
|
|
321
|
-
${E}`:$,console.error(`[editor-dev-server] Server failed: ${v.errorMessage}`)}else v.status="stopped"}),b.on("error",k=>{console.error("[editor-dev-server] Process error:",k),v.status="error",v.errorMessage=k.message}),new Response(JSON.stringify({status:"starting",pid:b.pid,message:`Starting ${l} ${c.join(" ")}`}),{headers:{"Content-Type":"application/json"}})}function ni(){const e=qa();if(!e||e.status==="stopped")return new Response(JSON.stringify({status:"stopped",message:"No server to stop"}),{headers:{"Content-Type":"application/json"}});Hl();try{e.process.pid&&process.kill(-e.process.pid,"SIGTERM")}catch{try{e.process.kill("SIGTERM")}catch{}}return e.status="stopped",pc(null),new Response(JSON.stringify({status:"stopped",message:"Dev server stopped"}),{headers:{"Content-Type":"application/json"}})}const Yy=Object.freeze(Object.defineProperty({__proto__:null,action:zy,loader:Fy},Symbol.toStringTag,{value:"Module"}));async function Uy({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=rs(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 Wy({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=rs(t);try{if(!Ot(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 qs(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 Hy=Object.freeze(Object.defineProperty({__proto__:null,action:Uy,loader:Wy},Symbol.toStringTag,{value:"Module"}));function Jy({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=F.resolve(s,r);if(!a.startsWith(s+F.sep)&&a!==s)return Response.json({error:"Path outside project root"},{status:403});const o=Zl(r,s);return Response.json(o)}const Vy=Object.freeze(Object.defineProperty({__proto__:null,loader:Jy},Symbol.toStringTag,{value:"Module"}));async function Gy(){const e=await Ie();if(!e)return Response.json({error:"No project configured"},{status:400});const{project:t}=await Re(e),r=je(),s=process.env.CODEYAM_PORT||"3111",a=he()||process.cwd(),o=await r.selectFrom("editor_scenarios").select(["id","name","component_name","component_path","url","type","screenshot_path"]).where("project_id","=",t.id).orderBy("created_at","asc").execute(),i=yt(o,m=>`${m.name}::${m.url||"/"}`);let l={};try{const m=i.map(p=>({componentName:p.component_name||null,componentPath:p.component_path||null,url:p.url??null}));l=(await or({projectRoot:a,scenarioInputs:m})).entityChangeStatus}catch{}const c=i.map(m=>{let u=null;m.component_name?u=m.component_name:u=Xe(m.url??null);const p=u?l[u]:void 0;return{id:m.id,name:m.name,componentName:m.component_name||null,type:m.type||null,changeStatus:(p==null?void 0:p.status)||null,screenshotPath:m.screenshot_path||null,link:`http://localhost:${s}/editor?scenario=${m.id}&ref=link`}});return Response.json({scenarios:c})}const Ky=Object.freeze(Object.defineProperty({__proto__:null,loader:Gy},Symbol.toStringTag,{value:"Module"}));async function qy(e,t){var o,i,l,c,m,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await ze();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(p=>p.id===t);if(!s)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${s.name}`);const a={returnValue:{status:"success",data:((c=(l=(i=s.metadata)==null?void 0:i.data)==null?void 0:l.argumentsData)==null?void 0:c[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(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 Qy({request:e}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),s=t.get("scenarioId");if(!r||!s)return Q({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${s}`);const a=await qy(r,s);return console.log("[API] Function execution completed successfully"),Q({success:!0,result:a})}catch(t){return console.log("[API] Error during function execution:",t),Q({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const Zy=Object.freeze(Object.defineProperty({__proto__:null,action:Qy},Symbol.toStringTag,{value:"Module"}));function Xy({request:e}){return Q({status:"ok"})}async function ex({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Mt()),!r)return console.error("[Interactive Mode API] Queue not initialized"),Q({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 Q({error:"Missing required fields: action and analysisId"},{status:400});if(a!=="start"&&a!=="stop")return Q({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await Ie();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return Q({error:"Project not initialized"},{status:500});if(a==="start"){const c=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:l});return Q({success:!0,action:"start",message:"Interactive mode starting...",jobId:c})}else{const c=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:l});return Q({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:c})}}catch(s){console.error("[Interactive Mode API] Error:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Interactive Mode API] Error stack:",o),Q({error:"Failed to control interactive mode",details:a},{status:500})}}const tx=Object.freeze(Object.defineProperty({__proto__:null,action:ex,loader:Xy},Symbol.toStringTag,{value:"Module"}));async function nx({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=Z.join(a,".codeyam","captures","screenshots",o);try{await Ne.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(l){console.log(`[API] Could not delete screenshot ${i}:`,l instanceof Error?l.message:l)}}}await wm({ids:[r]});try{const a=he()||process.cwd();Mf(a,r)}catch{}return console.log(`[API] Scenario ${r} deleted successfully`),Response.json({success:!0,message:"Scenario deleted successfully"})}catch(t){return console.error("[API] Error deleting scenario:",t),Response.json({error:"Failed to delete scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const rx=Object.freeze(Object.defineProperty({__proto__:null,action:nx},Symbol.toStringTag,{value:"Module"}));class sx extends Gr{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 ha="__codeyam_dev_mode_event_emitter__";if(!globalThis[ha]){const e=new sx;e.setMaxListeners(20),globalThis[ha]=e}const ri=globalThis[ha];function ax({request:e}){const t=new ReadableStream({start(r){const s=new TextEncoder;r.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
322
|
-
|
|
323
|
-
`));let a=!1;const o=()=>{if(!a){a=!0,ri.off("event",i),clearInterval(l);try{r.close()}catch{}}},i=c=>{try{r.enqueue(s.encode(`data: ${JSON.stringify(c)}
|
|
324
|
-
|
|
325
|
-
`))}catch{o()}};ri.on("event",i);const l=setInterval(()=>{try{r.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
326
|
-
|
|
327
|
-
`))}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 ox=Object.freeze(Object.defineProperty({__proto__:null,loader:ax},Symbol.toStringTag,{value:"Module"})),er="/tmp/codeyam",fa=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",hc=500,ix=hc*1024*1024;function rn(e,t){try{return Ee(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function Er(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function fc(e){return rn("config user.email",e)}function lx(e){const t=F.join(e,".codeyam","debug-report.md");if(!K.existsSync(t))return null;try{return K.readFileSync(t,"utf8")}catch{return null}}function cx(e,t=20){const r=F.join(er,"local-dev",e,"codeyam","log.txt");if(!K.existsSync(r))return[];try{return K.readFileSync(r,"utf8").split(`
|
|
328
|
-
`).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function dx(e){try{const t=await fetch(`${fa}/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 ux(e,t){try{Ee(`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 mx(e){const{projectRoot:t,projectSlug:r,outputPath:s,metadata:a,screenshot:o,onProgress:i}=e,l=i||(()=>{}),c=Date.now(),m=F.join(er,`delta-staging-${c}`),u=F.join(m,"delta");K.mkdirSync(u,{recursive:!0});try{const p=rn("diff --binary HEAD",t)||"";K.writeFileSync(F.join(u,"tracked.patch"),p?p+`
|
|
329
|
-
`:"");const h=rn("ls-files --others --exclude-standard",t);if(h){const x=F.join(u,"untracked");K.mkdirSync(x,{recursive:!0});for(const b of h.split(`
|
|
330
|
-
`).filter(Boolean)){const w=F.join(t,b),v=F.join(x,b);if(K.existsSync(w)){const C=F.dirname(v);K.mkdirSync(C,{recursive:!0}),K.statSync(w).isFile()&&K.copyFileSync(w,v)}}}const f=F.join(t,".codeyam");if(K.existsSync(f)){const x=F.join(u,"codeyam");K.cpSync(f,x,{recursive:!0})}K.writeFileSync(F.join(u,"meta.json"),JSON.stringify(a,null,2));const y=F.join(er,"local-dev",r,"codeyam","log.txt");K.existsSync(y)?K.copyFileSync(y,F.join(u,"codeyam-log.txt")):K.writeFileSync(F.join(u,"codeyam-log.txt"),`# Log file not found
|
|
331
|
-
`);const g=F.join(t,".codeyam","debug-report.md");K.existsSync(g)&&(K.copyFileSync(g,F.join(u,"debug-report.md")),l("Debug report included")),o&&o.length>0&&(K.writeFileSync(F.join(u,"screenshot.jpg"),o),l(`Screenshot included (${Er(o.length)})`));try{Ee(`tar -czf "${s}" -C "${m}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{K.rmSync(m,{recursive:!0,force:!0})}}async function px(e){const{projectRoot:t,projectSlug:r,feedback:s,screenshot:a,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const l=rn("rev-parse HEAD",t);if(!l)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const c=rn("rev-parse --abbrev-ref HEAD",t)||"unknown",m=rn("status --porcelain",t),u=rn("remote get-url origin",t),p=m!==null&&m.length>0,h=Cl(r),f=lx(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:l,branch:c,isDirty:p,remoteUrl:u},versions:{cli:h.cliVersion,webserver:h.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:y},x=Date.now(),b=F.join(er,`base-${l}-${x}.tar.gz`),w=F.join(er,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const v=await dx(l);let C=null;v?i("Server already has base, skipping..."):(i("Generating base archive..."),ux(t,b),C=K.statSync(b).size,i(`Base archive: ${Er(C)}`)),i("Generating delta archive..."),mx({projectRoot:t,projectSlug:r,outputPath:w,metadata:g,screenshot:a,onProgress:o});const N=K.statSync(w).size;i(`Delta archive: ${Er(N)}`);const S=(C||0)+N;if(S>ix)throw K.existsSync(b)&&K.unlinkSync(b),K.unlinkSync(w),new Error(`Bundle too large: ${Er(S)} (max: ${hc} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:v?null:b,deltaPath:w,metadata:g,baseSha:l,baseSize:C,deltaSize:N}}async function hx(e){const{basePath:t,deltaPath:r,projectSlug:s,metadata:a,baseSha:o,deltaSize:i,onProgress:l}=e,c=l||(()=>{}),m=K.statSync(r),u=t?K.statSync(t):null,p=m.size+((u==null?void 0:u.size)||0);c("Requesting upload URLs...");const h=await fetch(`${fa}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:s,fileSizeBytes:p,baseSha:o,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:a.timestamp,git:a.git,versions:a.versions,system:a.system,feedback:a.feedback}})});if(!h.ok){const v=await h.json();throw new Error(v.error||`Server returned ${h.status}`)}const{reportId:f,deltaUploadUrl:y,baseUploadUrl:g}=await h.json(),x=[];if(t&&g){c("Uploading base...");const v=K.readFileSync(t);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:v}).then(C=>{if(!C.ok)throw new Error(`Base upload failed: ${C.status}`)}))}c("Uploading delta...");const b=K.readFileSync(r);x.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:b}).then(v=>{if(!v.ok)throw new Error(`Delta upload failed: ${v.status}`)})),await Promise.all(x),c("Confirming upload...");const w=await fetch(`${fa}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!w.ok){const v=await w.json();throw new Error(v.error||`Confirm failed: ${w.status}`)}return t&&K.existsSync(t)&&K.unlinkSync(t),K.unlinkSync(r),{bundleId:f}}async function fx({request:e}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),s=t.get("description"),a=t.get("email"),o=t.get("source"),i=t.get("entitySha"),l=t.get("scenarioId"),c=t.get("analysisId"),m=t.get("currentUrl"),u=t.get("entityName"),p=t.get("entityType"),h=t.get("scenarioName"),f=t.get("errorMessage"),y=t.get("screenshot");let g=s||void 0;!g&&u&&(h?g=`Issue on ${u} scenario "${h}"`:g=`Issue on ${u}`);let x;if(y&&y.size>0){const S=await y.arrayBuffer();x=Buffer.from(S),console.log(`[Bundle] Screenshot received: ${y.size} bytes`)}const b=he();if(!b)return Q({error:"Project root not found"},{status:500});const w=await Ie();if(!w)return Q({error:"Project slug not found"},{status:500});const v={issueType:r||"other",description:g,email:a||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:l||void 0,analysisId:c||void 0,currentUrl:m||void 0,recentActivity:cx(w,20),entityName:u||void 0,entityType:p||void 0,scenarioName:h||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${w}...`),console.log(`[Bundle] Context: ${v.source}, issue: ${v.issueType}`);const C=await px({projectRoot:b,projectSlug:w,feedback:v,screenshot:x,onProgress:S=>{console.log(`[Bundle] ${S}`)}}),P=(C.baseSize||0)+C.deltaSize;console.log(`[Bundle] Archives created: delta=${C.deltaSize} bytes${C.basePath?`, base=${C.baseSize} bytes`:" (base reused)"}`);const N=await hx({basePath:C.basePath,deltaPath:C.deltaPath,projectSlug:w,metadata:C.metadata,baseSha:C.baseSha,deltaSize:C.deltaSize,onProgress:S=>{console.log(`[Bundle] ${S}`)}});return console.log(`[Bundle] Upload complete: ${N.bundleId}`),Q({success:!0,reportId:N.bundleId,size:P})}catch(t){return console.error("[Bundle] Error:",t),Q({error:t.message||"Failed to generate bundle"},{status:500})}}function gx(){const e=he(),t=e?fc(e):null;return Q({defaultEmail:t})}const yx=Object.freeze(Object.defineProperty({__proto__:null,action:fx,loader:gx},Symbol.toStringTag,{value:"Module"}));async function xx({request:e}){try{const r=new URL(e.url).searchParams.get("date"),s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=F.join(s,".codeyam","journal","index.json");let o={entries:[]};try{const l=await we.readFile(a,"utf8");o=JSON.parse(l)}catch{}let i=o.entries;return r&&(i=i.filter(l=>l.date===r)),new Response(JSON.stringify({entries:i}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const bx=Object.freeze(Object.defineProperty({__proto__:null,loader:xx},Symbol.toStringTag,{value:"Module"}));function gc(e){if(!K.existsSync(e))return Ke.Unknown;try{const t=JSON.parse(K.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:r.expo?Ke.Expo:r.vite?Ke.Vite:Ke.Unknown}catch{return Ke.Unknown}}function wx(e,t){let r=e;const s=F.resolve(t);for(;;){const a=F.resolve(r);if(K.existsSync(F.join(a,"pnpm-lock.yaml")))return"pnpm";if(K.existsSync(F.join(a,"yarn.lock")))return"yarn";if(K.existsSync(F.join(a,"package-lock.json")))return"npm";if(a===s)break;const o=F.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 vx(e){const t=/cd\s+([^\s;&|]+)\s*(?:&&|;)/,r=e.match(t);return r?r[1]:null}function Nx(e){const t=F.join(e,"package.json");if(!K.existsSync(t))return{isWebApp:!1};if(gc(t)===Ke.Unknown)return{isWebApp:!1};try{const a=JSON.parse(K.readFileSync(t,"utf8")).scripts||{},o=["remix","react-router","next dev","vite","react-scripts","webpack-dev-server","parcel","expo"],l=Object.keys(a).filter(c=>["dev","start","serve","build"].some(m=>c.includes(m))).filter(c=>o.some(m=>a[c].includes(m)));if(l.length===0)return{isWebApp:!1};for(const c of l){const m=a[c],u=vx(m);if(u){const p=F.join(e,u);if(K.existsSync(p)&&K.statSync(p).isDirectory())return{isWebApp:!0,actualPath:p}}}return{isWebApp:!0}}catch{return{isWebApp:!1}}}function yc(e,t=e,r=0,s=3){if(r>s)return[];const a=[],o=Nx(t);if(o.isWebApp){const l=o.actualPath||t,c=F.relative(e,l);return a.push(c||"."),a}const i=["node_modules",".git",".next","dist","build",".cache","coverage",".codeyam"];try{const l=K.readdirSync(t,{withFileTypes:!0});for(const c of l)if(c.isDirectory()&&!i.includes(c.name)){const m=F.join(t,c.name);a.push(...yc(e,m,r+1,s))}}catch{}return a}function Cx(e){const t=yc(e);return t.length===0?[]:t.map(s=>{const a=F.join(e,s),o=F.join(a,"package.json"),i=gc(o),l=wx(a,e);let c;if(i===Ke.Remix||i===Ke.Next){const p=F.join(a,"app");K.existsSync(p)&&K.statSync(p).isDirectory()&&(c="app")}const m=Sx(s,e),u=m?{command:"sh",args:["-c",`${l} run ${m} -- --port $PORT`]}:void 0;return{path:s,framework:i,packageManager:l,appDirectory:c,startCommand:u}})}function Sx(e,t){const r=F.join(t,e),s=F.join(r,"package.json");if(!K.existsSync(s))return null;try{const o=JSON.parse(K.readFileSync(s,"utf8")).scripts||{},i=["dev","start","serve"];for(const l of i)if(o[l])return l;return null}catch{return null}}function kx(e,t){const r=new Set(e.map(a=>a.path)),s=[...e];for(const a of t)r.has(a.path)||s.push(a);return s}async function Ex({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=he()||process.cwd(),r=Z.join(t,".codeyam","config.json");let s=[];try{s=Cx(t)}catch{}if(fe.existsSync(r)){const i=JSON.parse(fe.readFileSync(r,"utf8")),l=i.webapps||[];i.webapps=kx(s,l),s=i.webapps,fe.writeFileSync(r,JSON.stringify(i,null,2))}const a=await Ie();if(a)try{await vn({projectSlug:a,metadataUpdate:{webapps:s}})}catch{}let o=!1;if(s.length>0)try{const i=process.env.CODEYAM_PORT||"3111",c=await(await fetch(`http://localhost:${i}/api/editor-dev-server`)).json();(c.status==="stopped"||c.status===void 0)&&(await fetch(`http://localhost:${i}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}),o=!0)}catch{}return new Response(JSON.stringify({success:!0,webapps:s,devServerStarted:o,message:`Detected ${s.length} webapp(s)`}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const _x=Object.freeze(Object.defineProperty({__proto__:null,action:Ex},Symbol.toStringTag,{value:"Module"}));function an(){const e=process.memoryUsage(),t=Qd.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(Qs.totalmem()/1024/1024),freeMemory:Math.round(Qs.freemem()/1024/1024)}}}function Ax(){const e=an();console.log(`
|
|
332
|
-
[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 Px(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=an();global.gc();const t=an(),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 jx(){const e=an(),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 Mx({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=Px(),a=an();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=Ax();return Response.json({success:!0,stats:s})}case"leaks":{const s=jx(),a=an();return Response.json({success:!0,leakCheck:s,stats:a})}default:{const s=an();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 Tx=Object.freeze(Object.defineProperty({__proto__:null,loader:Mx},Symbol.toStringTag,{value:"Module"})),xr=Ca(Na);async function $x({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=Ix(o),l=i?await Rx(o):null;return{pid:o,isRunning:i,processName:l}}));return Response.json({processes:a})}function Ix(e){try{return process.kill(e,0),!0}catch{return!1}}async function Rx(e){if(process.platform==="win32")try{const{stdout:r}=await xr(`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 xr(`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 xr(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:s}=await xr(`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 Dx=Object.freeze(Object.defineProperty({__proto__:null,loader:$x},Symbol.toStringTag,{value:"Module"})),Ox=Vr(import.meta.url),Lx=F.dirname(Ox);function Fx({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=is(),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=F.join(Lx,"..","..","..","..","webserver","bootstrap.js"),o=F.join(r,".codeyam","logs");K.existsSync(o)||K.mkdirSync(o,{recursive:!0});const i=K.openSync(F.join(o,"background-server.log"),"a"),l=K.openSync(F.join(o,"background-server-error.log"),"a"),c=new Date().toISOString();K.appendFileSync(F.join(o,"background-server.log"),`
|
|
333
|
-
[${c}] Server restart requested via dashboard
|
|
334
|
-
`),Da();const m=Et("node",[a],{detached:!0,stdio:["ignore",i,l],env:{...process.env,CODEYAM_PORT:s.toString(),CODEYAM_ROOT_PATH:r,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});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 zx=Object.freeze(Object.defineProperty({__proto__:null,action:Fx},Symbol.toStringTag,{value:"Module"}));async function Bx({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:s}=t;if(!r||!s)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${r.id}`),console.log(`[API] Received ${s.length} scenarios to save`),s.forEach((l,c)=>{var p,h,f,y,g;const m=(h=(p=l.metadata)==null?void 0:p.data)==null?void 0:h.argumentsData,u=Array.isArray(m)&&m.length>0?JSON.stringify(m[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${c}: ${l.name}`,{id:l.id,projectId:l.projectId,analysisId:l.analysisId,hasMetadata:!!l.metadata,hasData:!!((f=l.metadata)!=null&&f.data),mockDataKeys:(g=(y=l.metadata)==null?void 0:y.data)!=null&&g.mockData?Object.keys(l.metadata.data.mockData):[],argumentsDataLength:Array.isArray(m)?m.length:"not-array",argumentsDataPreview:u})});const a=s.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),o=await Dm(a);if(!o||o.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${o.length} scenarios to database`),o.forEach((l,c)=>{var u,p;const m=(p=(u=l.metadata)==null?void 0:u.data)==null?void 0:p.argumentsData;console.log(`[API] Saved scenario ${c}: ${l.name}`,{id:l.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 Yx=Object.freeze(Object.defineProperty({__proto__:null,action:Bx},Symbol.toStringTag,{value:"Module"})),Ux=()=>[{title:"Agent Transcripts - CodeYam"},{name:"description",content:"View background agent transcripts and tool call history"}];async function Wx({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("search")||"",s=t.searchParams.get("page")||"1",a=new URLSearchParams;r&&a.set("search",r),s!=="1"&&a.set("page",s);const o=a.toString(),i=new URL(`/api/agent-transcripts${o?`?${o}`:""}`,e.url),c=await(await fetch(i.toString())).json();if(c.error)return Q({agents:[],error:c.error,search:r,page:1,totalPages:1});const m=c.total??(c.agents||[]).length,u=c.pageSize??20;return Q({agents:c.agents||[],error:null,search:r,page:c.page??parseInt(s,10),totalPages:Math.max(1,Math.ceil(m/u))})}catch(t){return console.error("Failed to load agent transcripts:",t),Q({agents:[],error:"Failed to load agent transcripts",search:"",page:1,totalPages:1})}}function Hx(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 Jx(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 Vx(e){return e.includes("opus")?"Opus":e.includes("sonnet")?"Sonnet":e.includes("haiku")?"Haiku":e}function _r({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 Gx({input:e}){return n("div",{className:"text-xs font-mono space-y-1",children:Object.entries(e).map(([t,r])=>{let s=typeof r=="string"?r:JSON.stringify(r);return s.length>500&&(s=s.slice(0,500)+"..."),d("div",{children:[d("span",{className:"text-[#f4a261] font-bold",children:[t,":"]})," ",n("span",{className:"text-gray-700",children:s})]},t)})})}function Kx({content:e,truncated:t,fullLength:r}){const[s,a]=M(!1);return d("div",{children:[d("pre",{className:"whitespace-pre-wrap break-words text-xs max-h-96 overflow-y-auto text-gray-700",children:[e,t&&!s&&"..."]}),t&&n("button",{onClick:()=>a(!s),className:"text-[11px] text-gray-500 hover:text-gray-700 mt-1 font-mono cursor-pointer",children:s?"Show less":`Show more (${(r||0)-e.length} more chars)`})]})}function qx({entry:e,pairedResult:t}){const[r,s]=M(!1),a=Hx(e.timestamp||"");return e.type==="user_prompt"?d("div",{className:"my-2",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(_r,{type:"user_prompt"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:a})]}),n("pre",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#00b4d8] max-h-72 overflow-y-auto text-gray-800",children:e.text})]}):e.type==="assistant_text"?d("div",{className:"my-2",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(_r,{type:"assistant_text"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:a})]}),n("div",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-sm border-l-[3px] border-l-[#a8dadc] text-gray-800",children:e.text})]}):e.type==="tool_call"?d("div",{className:"my-2",children:[d("button",{onClick:()=>s(!r),className:"flex items-center gap-2 w-full text-left bg-white border border-gray-200 rounded-md px-3 py-2 hover:bg-gray-50 cursor-pointer",children:[r?n(dt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n(Yt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n(_r,{type:"tool_call",toolName:e.name}),n("span",{className:"text-xs text-gray-500 font-mono truncate flex-1",children:e.summary||""}),n("span",{className:"text-[11px] text-gray-400 font-mono flex-shrink-0",children:a})]}),r&&d("div",{className:"bg-white border border-t-0 border-gray-200 rounded-b-md px-3 py-2 border-l-[3px] border-l-[#f4a261]",children:[n(Gx,{input:e.input||{}}),t&&d("div",{className:"mt-3 pt-3 border-t border-gray-200",children:[d("div",{className:"text-[11px] font-bold uppercase tracking-wide text-[#2a9d8f] mb-1",children:["Result",t.is_error?" (Error)":"",":"]}),n(Kx,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function Qx({context:e}){const[t,r]=M(!1);return d("div",{className:"my-2",children:[d("button",{onClick:()=>r(!t),className:"flex items-center gap-2 mb-1 cursor-pointer hover:opacity-80",children:[t?n(dt,{className:"w-3 h-3 text-gray-400"}):n(Yt,{className:"w-3 h-3 text-gray-400"}),n(_r,{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 Zx({snippet:e}){const[t,r]=M(!1),s=e.split(`
|
|
335
|
-
`).filter(l=>l.trim()),a=s.slice(0,4),o=s.length>4,i=t?s:a;return d("div",{className:"my-2 bg-blue-50 border border-blue-200 rounded-md p-3",children:[d("div",{className:"flex items-center gap-2 mb-2",children:[n(yd,{className:"w-3.5 h-3.5 text-blue-600"}),n("span",{className:"text-xs font-bold text-blue-800",children:"Source Conversation"}),d("span",{className:"text-[10px] text-blue-500",children:[s.length," message",s.length!==1?"s":""]})]}),n("div",{className:"space-y-1",children:i.map((l,c)=>{const m=l.match(/^\[(\w+)\]:\s*(.*)/);if(!m)return null;const[,u,p]=m,h=u==="user";return d("div",{className:"text-xs",children:[d("span",{className:`font-bold ${h?"text-blue-700":"text-gray-500"}`,children:[h?"User":"Assistant",":"]})," ",n("span",{className:"text-gray-700",children:p.length>200?p.slice(0,200)+"...":p})]},c)})}),o&&n("button",{onClick:()=>r(!t),className:"text-[11px] text-blue-600 hover:text-blue-800 mt-2 font-mono cursor-pointer",children:t?"Show less":`Show all ${s.length} messages`})]})}function Xx({change:e}){const[t,r]=M(!1),s=e.action==="created"?!!e.content:e.action==="modified"?!!(e.oldString||e.newString):!1;return d("li",{children:[n("button",{onClick:()=>s&&r(!t),className:`text-left w-full ${s?"hover:text-green-900 cursor-pointer":""}`,children:d("span",{className:"inline-flex items-center gap-1",children:[s&&(t?n(dt,{className:"w-3 h-3 inline flex-shrink-0"}):n(Yt,{className:"w-3 h-3 inline flex-shrink-0"})),e.action==="created"?"Created":"Modified"," ",e.filePath]})}),t&&e.action==="created"&&e.content&&n("pre",{className:"mt-1 mb-2 ml-4 p-2 bg-white border border-green-200 rounded text-[11px] text-gray-700 whitespace-pre-wrap break-words max-h-64 overflow-y-auto",children:e.content}),t&&e.action==="modified"&&d("div",{className:"mt-1 mb-2 ml-4 space-y-1",children:[e.oldString&&d("pre",{className:"p-2 bg-red-50 border border-red-200 rounded text-[11px] text-red-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["- ",e.oldString]}),e.newString&&d("pre",{className:"p-2 bg-green-50 border border-green-300 rounded text-[11px] text-green-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["+ ",e.newString]})]})]})}function eb({changes:e}){const t=e.filter(i=>i.action==="touched"),r=e.filter(i=>i.action!=="touched"),s=r.some(i=>i.action==="created"),a=r.some(i=>i.action==="modified");return d("div",{className:`my-2 border rounded-md p-3 ${s?"bg-green-50 border-green-200 text-green-800 [&_ul]:text-green-700":a?"bg-amber-50 border-amber-200 text-amber-800 [&_ul]:text-amber-700":"bg-gray-50 border-gray-200 text-gray-600 [&_ul]:text-gray-500"}`,children:[n("div",{className:"text-xs font-bold mb-1",children:"Rule Changes:"}),d("ul",{className:"text-xs space-y-0.5 font-mono",children:[r.map((i,l)=>n(Xx,{change:i},l)),t.length>0&&d("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function tb({result:e}){const t=e.is_error,r=t?"bg-red-50 border-red-200":"bg-green-50 border-green-200",s=t?"text-red-800":"text-green-800",a=t?"text-red-700":"text-green-700",o=e.subtype.replace(/^error_/,"").replace(/_/g," "),i=c=>c>=6e4?`${(c/6e4).toFixed(1)}m`:`${(c/1e3).toFixed(1)}s`,l=c=>c>=1e3?`${(c/1e3).toFixed(1)}k`:String(c);return d("div",{className:`my-2 border rounded-md p-3 ${r}`,children:[d("div",{className:`text-xs font-bold mb-1 ${s}`,children:["Session Result: ",o]}),d("div",{className:`text-xs ${a} font-mono space-y-0.5`,children:[d("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5",children:[e.duration_ms!=null&&d("span",{children:["Duration: ",i(e.duration_ms)]}),e.duration_api_ms!=null&&d("span",{children:["API time: ",i(e.duration_api_ms)]}),e.num_turns!=null&&d("span",{children:["Turns: ",e.num_turns]}),e.total_cost_usd!=null&&d("span",{children:["Cost: $",e.total_cost_usd.toFixed(4)]})]}),e.usage&&d("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5 mt-1",children:[e.usage.input_tokens!=null&&d("span",{children:["Input: ",l(e.usage.input_tokens)]}),e.usage.output_tokens!=null&&d("span",{children:["Output: ",l(e.usage.output_tokens)]}),e.usage.cache_read_input_tokens!=null&&d("span",{children:["Cache read: ",l(e.usage.cache_read_input_tokens)]}),e.usage.cache_creation_input_tokens!=null&&d("span",{children:["Cache write:"," ",l(e.usage.cache_creation_input_tokens)]})]}),e.errors&&e.errors.length>0&&n("div",{className:"mt-1",children:e.errors.map((c,m)=>n("div",{className:"text-red-700 break-words",children:c},m))})]})]})}function nb({agent:e,defaultOpen:t,isAdmin:r}){var P,N,S;const[s,a]=M(t),[o,i]=M(!1),[l,c]=M(null),[m,u]=M(!1),p=ae(()=>{const k={};for(const _ of e.entries)_.type==="tool_result"&&_.tool_use_id&&(k[_.tool_use_id]=_);return k},[e.entries]),h=ae(()=>{const k=new Set;for(const _ of e.entries)_.type==="tool_call"&&_.tool_use_id&&p[_.tool_use_id]&&k.add(_.tool_use_id);return k},[e.entries,p]),f=k=>{k.stopPropagation(),i(!0),c(null),fetch("/api/save-fixture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e.id})}).then(_=>_.json()).then(_=>{_.success?c(`Saved to ${_.fixturePath}`):c(`Error: ${_.error}`)}).catch(_=>{c(`Error: ${_ instanceof Error?_.message:String(_)}`)}).finally(()=>{i(!1)})},y=(e.ruleChanges||[]).filter(k=>k.action!=="touched"),g=y.filter(k=>k.action==="created"),x=y.filter(k=>k.action==="modified"),b=(e.ruleChanges||[]).filter(k=>k.action==="touched"),w=y.length>0,v=b.length>0,C=w||v;return d("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:[d("button",{onClick:()=>a(!s),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:[s?n(dt,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n(Yt,{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:Vx(e.model)}),g.length>0&&d("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-green-100 text-green-800",children:[n(Pr,{className:"w-3 h-3"}),g.length," rule",g.length!==1?"s":""," ","created"]}),x.length>0&&d("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-100 text-amber-800",children:[n(Pr,{className:"w-3 h-3"}),x.length," rule",x.length!==1?"s":""," ","modified"]}),!w&&v&&d("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-gray-100 text-gray-500",children:[b.length," timestamp",b.length!==1?"s":""," ","touched"]}),e.stats.errors>0&&d("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-red-100 text-red-800",children:[n(Ar,{className:"w-3 h-3 flex-shrink-0"}),e.stats.errors," ",e.stats.errors===1?"Error":"Errors"]}),d("span",{className:"text-[11px] text-gray-400 font-mono",children:[e.stats.toolCalls," tool calls, ",e.stats.textBlocks," text blocks",((P=e.sessionResult)==null?void 0:P.duration_ms)!=null&&d(de,{children:[" · ",e.sessionResult.duration_ms>=6e4?`${(e.sessionResult.duration_ms/6e4).toFixed(1)}m`:`${(e.sessionResult.duration_ms/1e3).toFixed(1)}s`]}),((N=e.sessionResult)==null?void 0:N.total_cost_usd)!=null&&d(de,{children:[" · ","$",e.sessionResult.total_cost_usd.toFixed(2)]})]}),d("span",{className:"text-[11px] text-gray-400 font-mono ml-auto flex items-center gap-2",children:[Jx(e.timestamp),r&&w&&d("button",{onClick:f,disabled:o,className:"inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] font-bold bg-gray-100 text-gray-600 hover:bg-gray-200 disabled:opacity-50 cursor-pointer",title:"Save as test fixture",children:[n(gd,{className:"w-3 h-3"}),o?"Saving...":"Save Fixture"]})]})]}),l&&n("div",{className:`px-4 py-2 text-xs font-mono ${l.startsWith("Error")?"bg-red-50 text-red-700":"bg-green-50 text-green-700"}`,children:l}),s&&d("div",{className:"px-4 pb-4 border-t border-gray-100",children:[e.sourceFile&&d("div",{className:"flex items-center gap-2 py-2 text-xs text-gray-500 font-mono",children:[n("span",{className:"text-gray-400",children:"FILE:"}),n("span",{className:"truncate",children:e.sourceFile}),n("button",{onClick:k=>{k.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(ut,{className:"w-3.5 h-3.5 text-green-500"}):n(ft,{className:"w-3.5 h-3.5"})})]}),e.sessionResult&&n(tb,{result:e.sessionResult}),e.stats.errors>0&&((S=e.stats.errorMessages)==null?void 0:S.length)>0&&d("div",{className:"my-2 bg-red-50 border border-red-200 rounded-md p-3",children:[d("div",{className:"text-xs font-bold text-red-800 mb-1",children:[e.stats.errors," Error",e.stats.errors!==1?"s":"",":"]}),n("ul",{className:"text-xs text-red-700 space-y-1 font-mono",children:e.stats.errorMessages.map((k,_)=>n("li",{className:"break-words",children:k},_))})]}),e.conversationSnippet&&n(Zx,{snippet:e.conversationSnippet}),C&&n(eb,{changes:e.ruleChanges}),e.context&&n(Qx,{context:e.context}),e.entries.map((k,_)=>{if(k.type==="tool_result"&&k.tool_use_id&&h.has(k.tool_use_id))return null;const j=k.type==="tool_call"&&k.tool_use_id?p[k.tool_use_id]:void 0;return n(qx,{entry:k,pairedResult:j},`${e.id}-${_}`)})]})]})}function Ws(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 rb=Je(function(){const{agents:t,error:r,search:s,page:a,totalPages:o}=qe(),i=St(),l=Gc("root"),c=(l==null?void 0:l.isAdmin)??!1,[m,u]=M(s),[p,h]=M(!1),[f,y]=M(0);xt({source:"agent-transcripts-page"});const g=b=>{b.preventDefault(),window.location.href=Ws(1,m)},x=()=>{h(!p),y(b=>b+1)};return r?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:r})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-20 py-12 font-sans",children:[d("div",{className:"mb-8",children:[d("div",{className:"flex items-center gap-3 mb-1",children:[n("button",{onClick:()=>{i("/memory")},className:"text-gray-600 hover:text-[#005C75] transition-colors cursor-pointer",title:"Back to Memory","aria-label":"Back to Memory",children:n(hd,{className:"w-5 h-5"})}),n(jr,{className:"w-6 h-6 text-[#232323]"}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Agent Transcripts"})]}),n("p",{className:"text-[15px] text-gray-500 ml-14",children:"View background agent transcripts and tool call history"})]}),d("div",{className:"flex items-center gap-4 mb-6",children:[d("form",{onSubmit:g,className:"relative flex-1 max-w-md",children:[n(nr,{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:b=>u(b.target.value),placeholder:"Search transcripts...",className:"w-full pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),n("button",{onClick:x,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:p?"Collapse All":"Expand All"})]}),d("div",{className:"text-sm text-gray-500 mb-4",children:["Page ",a," of ",o,s&&d("span",{children:[" ","matching “",s,"”",n(me,{to:"/agent-transcripts",className:"text-[#005C75] hover:underline ml-2",children:"Clear"})]})]}),t.length===0?d("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(jr,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Agent Transcripts Found"}),n("p",{className:"text-gray-500",children:"Background agent output files will appear here when available."})]}):n("div",{children:t.map(b=>n(nb,{agent:b,defaultOpen:p,isAdmin:c},b.id))},f),o>1&&d("div",{className:"flex items-center justify-center gap-3 mt-8",children:[d("a",{href:a>1?Ws(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(fd,{className:"w-4 h-4"}),"Prev"]}),d("span",{className:"text-sm text-gray-500 font-mono",children:[a," / ",o]}),d("a",{href:a<o?Ws(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(Yt,{className:"w-4 h-4"})]})]})]})})}),sb=Object.freeze(Object.defineProperty({__proto__:null,default:rb,loader:Wx,meta:Ux},Symbol.toStringTag,{value:"Module"}));async function ab({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=my(s);a&&console.log("[editor-commit] Initialized new git repository"),py(s),console.log("[editor-commit] Staged all changes");const o=hy(s,r);console.log(`[editor-commit] Created commit: ${o}`);try{const{broadcastHideResults:i}=await Promise.resolve().then(()=>$f);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 ob=Object.freeze(Object.defineProperty({__proto__:null,action:ab},Symbol.toStringTag,{value:"Module"})),ib=["JSX","React","Element","ReactNode"];function lb(e){return e.returnType?ib.some(t=>e.returnType.includes(t)):!1}function cb(e){const t=[],r=[];for(const s of e)lb(s)?t.push(s):r.push(s);return{components:t,functions:r}}function db({components:e,functions:t,scenarioCounts:r,testFileExistence:s,testResults:a,clientErrors:o}){const i=e.map(g=>{const x=r[g.name]||0,b=o==null?void 0:o[g.name],w=x>0&&b&&b.length>0;let v;return x===0?v="missing":w?v="has_errors":v="ok",{name:g.name,filePath:g.filePath,scenarioCount:x,status:v,...w?{clientErrors:b}:{}}}),l=t.map(g=>{if(!(g.testFile?s[g.testFile]??!1:!1))return{name:g.name,filePath:g.filePath,testFile:g.testFile,testFileExists:!1,status:"missing"};const b=g.testFile&&a?a[g.testFile]:void 0;if(!b)return{name:g.name,filePath:g.filePath,testFile:g.testFile,testFileExists:!0,status:"ok"};let w;return b.passing?b.hasEntityNameDescribe?w="ok":w="name_mismatch":w="failing",{name:g.name,filePath:g.filePath,testFile:g.testFile,testFileExists:!0,testsPassing:b.passing,testsVisibleInUi:b.hasEntityNameDescribe,status:w}}),c=i.filter(g=>g.status==="ok").length,m=i.filter(g=>g.status==="has_errors").length,u=i.filter(g=>g.status==="missing").length,p=l.filter(g=>g.status==="ok").length,h=l.filter(g=>g.status==="failing").length,f=l.filter(g=>g.status==="name_mismatch").length,y=l.filter(g=>g.status==="missing").length;return{components:i,functions:l,summary:{totalComponents:i.length,componentsOk:c,componentsMissing:u,componentsWithErrors:m,totalFunctions:l.length,functionsOk:p,functionsMissing:y,functionsFailing:h,functionsNameMismatch:f,allPassing:u===0&&m===0&&h===0&&f===0&&y===0}}}function ub(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>!!(t[r.name]||t[r.filePath]))}async function mb(){const e=he()||process.cwd(),t=F.join(e,".codeyam","glossary.json");let r;try{const g=K.readFileSync(t,"utf8");r=JSON.parse(g),Array.isArray(r)||(r=[])}catch{return Response.json({components:[],functions:[],summary:{totalComponents:0,componentsOk:0,componentsMissing:0,componentsWithErrors: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,componentsWithErrors:0,totalFunctions:0,functionsOk:0,functionsMissing:0,functionsFailing:0,functionsNameMismatch:0,allPassing:!0}});const s=F.join(e,".codeyam","editor-step.json");let a=null;try{const g=K.readFileSync(s,"utf8");a=JSON.parse(g).featureStartedAt||null}catch{}let o;const i=await Ie();if(i)try{const{project:g}=await Re(i),b=await je().selectFrom("editor_scenarios").select(["name","component_name","component_path","url"]).where("project_id","=",g.id).orderBy("created_at","asc").execute(),v=yt(b,P=>`${P.name}::${P.url||"/"}`).map(P=>({componentName:P.component_name||null,componentPath:P.component_path||null,url:P.url??null})),C=await or({projectRoot:e,scenarioInputs:v});Object.keys(C.entityChangeStatus).length>0&&(o=C.entityChangeStatus)}catch{}const l=ub(r,o),{components:c,functions:m}=cb(l),u={};if(i)try{const{project:g}=await Re(i),x=je();let b=x.selectFrom("editor_scenarios").select(["component_name"]).select(x.fn.count("id").as("count")).where("project_id","=",g.id).where("component_name","is not",null).groupBy("component_name");if(a){const v=a.replace("T"," ").replace(/\.\d{3}Z$/,"");b=b.where("created_at",">=",v)}const w=await b.execute();for(const v of w)v.component_name&&(u[v.component_name]=Number(v.count))}catch{}const p={};try{const g=process.env.CODEYAM_ROOT_PATH||process.cwd(),x=await Kl(g);for(const[,b]of Object.entries(x)){if(b.errors.length===0)continue;const w=b.scenarioName,v=w.indexOf(" - "),C=v>=0?w.slice(0,v):w;C&&(p[C]||(p[C]=[]),p[C].push(...b.errors))}}catch{}const h={};for(const g of m)g.testFile&&(h[g.testFile]=K.existsSync(F.join(e,g.testFile)));const f={};for(const g of m)if(!(!g.testFile||!h[g.testFile]))try{const x=await cc(e,g.testFile),b=x.status==="passed",w=x.testCases.some(v=>v.fullName.startsWith(g.name));f[g.testFile]={passing:b,hasEntityNameDescribe:w}}catch{f[g.testFile]={passing:!1,hasEntityNameDescribe:!1}}const y=db({components:c,functions:m,scenarioCounts:u,testFileExistence:h,testResults:f,clientErrors:p});return Response.json(y)}const pb=Object.freeze(Object.defineProperty({__proto__:null,loader:mb},Symbol.toStringTag,{value:"Module"}));async function hb({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(!si(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,s)}catch(u){return Response.json({error:"Failed to kill process",pid:r,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,l=500,c=Date.now();let m=!0;for(;m&&Date.now()-c<i;)await new Promise(u=>setTimeout(u,l)),m=si(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 Lt({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(u){console.error("Failed to update database after killing process:",u)}return Response.json({success:!0,pid:r,signal:s,message:`Process ${r} killed successfully`,waitedMs:Date.now()-c})}catch(t){return console.error("Error in kill-process API:",t),Response.json({error:"Internal server error",details:t instanceof Error?t.message:String(t)},{status:500})}}function si(e){try{return process.kill(e,0),!0}catch{return!1}}const fb=Object.freeze(Object.defineProperty({__proto__:null,action:hb},Symbol.toStringTag,{value:"Module"})),gb=Vr(import.meta.url),yb=Z.dirname(gb),xb=Z.resolve(yb,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function bb(e){const t=[],r=new Set;for(const s of e.split(`
|
|
336
|
-
`)){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}if(o.type!=="assistant")continue;const i=o.message;if(!(!i||!Array.isArray(i.content)))for(const l of i.content){if(typeof l!="object"||l===null)continue;const c=l;if(c.type!=="tool_use")continue;const m=String(c.name||""),u=c.input||{};if(m==="Write"||m==="Edit"){const p=String(u.file_path||"");if(p.includes(".claude/rules/")){const h=p.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${m}:${h}`;r.has(f)||(r.add(f),t.push({action:m==="Write"?"created":"modified",filePath:h}))}}else if(m==="Bash"){const p=String(u.command||"");if(p.includes("codeyam memory touch")){const h=`touch:${p}`;r.has(h)||(r.add(h),t.push({action:"touched",filePath:p}))}}}}return t}async function wb({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 uc(),a=s?Z.join(kr,s):null;let o=a?Z.join(a,`${r}.log`):"";if((!o||!Ot(o))&&(o=Z.join(kr,`${r}.log`)),!Ot(o))return Response.json({error:`Log file not found: ${r}.log`},{status:404});const i=await qs(o,"utf-8");let l=a?Z.join(a,`${r}.context`):"";(!l||!Ot(l))&&(l=Z.join(kr,`${r}.context`));let c=null;if(Ot(l))try{c=await qs(l,"utf-8")}catch{}const m=bb(i),p=c?["no,","no ","that's not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","shouldn't","try again","that broke","that failed","error","bug"].some(x=>c.toLowerCase().includes(x)):!1,h=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":r.endsWith("-interruption")?"-int":"",f=r.slice(0,8)+h,y=Z.join(xb,f);await Fd(y,{recursive:!0}),await Jn(Z.join(y,"agent-log.jsonl"),i),c&&await Jn(Z.join(y,"context.md"),c),await Jn(Z.join(y,"rule-changes.json"),JSON.stringify(m,null,2)),await Jn(Z.join(y,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:p,ruleChangeCount:m.length},null,2));const g=Z.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 vb=Object.freeze(Object.defineProperty({__proto__:null,action:wb},Symbol.toStringTag,{value:"Module"}));async function Nb({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=Z.join(r,".codeyam","captures","screenshots",t);try{await Ne.access(s);const a=await Ne.readFile(s),o=Z.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 Cb=Object.freeze(Object.defineProperty({__proto__:null,loader:Nb},Symbol.toStringTag,{value:"Module"})),ai={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 Qa({type:e,className:t=""}){const r=ai[e]||ai.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 Sb={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 br({variant:e,pid:t,label:r,className:s=""}){const a=Sb[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 oi=!1;function kb(){if(oi)return;const e=document.createElement("style");e.textContent=`
|
|
337
|
-
@keyframes strongPulse {
|
|
338
|
-
0%, 100% { opacity: 0.2; }
|
|
339
|
-
50% { opacity: 1; }
|
|
340
|
-
}
|
|
341
|
-
`,document.head.appendChild(e),oi=!0}function Za({size:e="medium",className:t=""}){typeof document<"u"&&kb();const r={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:s,centerDotSize:a,gap:o}=r[e];return d("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${o}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}const Eb=()=>[{title:"Activity - CodeYam"},{name:"description",content:"View analysis activity and queue status"}];async function _b({request:e,context:t,params:r}){var B,H,D,A,J,V,q,X;let s=t.analysisQueue;s||(s=await Mt());const a=new URL(e.url),o=parseInt(a.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!s)return Q({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:l,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const c=s.getState(),m=await Ie();let u=null;if(m&&((B=c==null?void 0:c.currentlyExecuting)!=null&&B.commitSha)){const{project:L,branch:O}=await Re(m),z=await Rr({projectId:L.id,branchId:O.id,shas:[c.currentlyExecuting.commitSha]});u=z&&z.length>0?z[0]:null}else u=await _n();const p=async L=>{const O=await dn(L);if(!O)return null;const{getAnalysesForEntity:z}=await Promise.resolve().then(()=>rp),G=await z(L,!1);return{...O,analyses:G||[]}},h=await Promise.all(((c==null?void 0:c.jobs)||[]).map(async L=>{const O=[];if(L.entityShas&&L.entityShas.length>0){const z=L.entityShas.map(ee=>p(ee)),G=await Promise.all(z);O.push(...G.filter(ee=>ee!==null))}return{...L,entities:O}}));let f=null;if(c!=null&&c.currentlyExecuting){const L=c.currentlyExecuting,O=[];if(L.entityShas&&L.entityShas.length>0){const z=L.entityShas.map(ee=>p(ee)),G=await Promise.all(z);O.push(...G.filter(ee=>ee!==null))}f={...L,entities:O}}const y=f?h.filter(L=>L.id!==f.id):h,g=((D=(H=u==null?void 0:u.metadata)==null?void 0:H.currentRun)==null?void 0:D.currentEntityShas)||[],b=(await Promise.all(g.map(L=>p(L)))).filter(L=>L!==null),w=[];if(m)try{const{project:L,branch:O}=await Re(m),z=await Rr({projectId:L.id,branchId:O.id,limit:100});for(const G of z){const ee=((A=G.metadata)==null?void 0:A.historicalRuns)||[];w.push(...ee)}}catch(L){console.error("[activity.tsx] Failed to load historical runs from commits:",L)}const v=[...w].sort((L,O)=>{const z=L.lastCaptureAt||L.analysisCompletedAt||L.archivedAt||L.createdAt||"";return(O.lastCaptureAt||O.analysisCompletedAt||O.archivedAt||O.createdAt||"").localeCompare(z)}),C=(o-1)*i,P=C+i,N=v.slice(C,P),S=Math.ceil(v.length/i),k=await Promise.all(N.map(async L=>{const O=L.currentEntityShas||[];if(O.length===0)return{...L,entities:[]};const z=await Promise.all(O.map(G=>p(G)));return{...L,entities:z.filter(G=>G!==null)}})),_=!!f,j=y.length,T=v.filter(L=>{const O=!!L.failedAt,z=L.readyToBeCaptured,G=L.capturesCompleted??0,ee=z===void 0?!0:z===0||G>=z;return!O&&!!L.analysisCompletedAt&&ee}),E=new Set(((J=f==null?void 0:f.entities)==null?void 0:J.map(L=>L.sha))||[]),$=T.filter(L=>!(L.currentEntityShas||[]).some(z=>E.has(z))),I=(await Promise.all($.slice(0,3).map(async L=>{const O=L.currentEntityShas||[];if(O.length===0)return{run:L,entities:[]};const z=await Promise.all(O.map(G=>p(G)));return{run:L,entities:z.filter(G=>G!==null)}}))).flatMap(({run:L,entities:O})=>O.map(z=>({...z,runId:L.id,completedAt:L.lastCaptureAt||L.analysisCompletedAt||L.archivedAt||L.createdAt})));let W=[],Y=null,U=null;if((q=(V=u==null?void 0:u.metadata)==null?void 0:V.currentRun)!=null&&q.analysisCompletedAt&&b.length>0){const L=b[0].sha;Y=b[0];const O=await Xr(L);O&&O.length>0&&O[0].scenarios&&(W=O[0].scenarios,U=O[0].status)}return Q({state:{...c,jobs:y,currentlyExecuting:f},currentRun:(X=u==null?void 0:u.metadata)==null?void 0:X.currentRun,historicalRuns:k,totalHistoricalRuns:v.length,currentPage:o,totalPages:S,projectSlug:m,commitSha:u==null?void 0:u.sha,queueJobs:y,currentlyExecuting:f,currentEntities:b,tab:l,hasCurrentActivity:_,queuedCount:j,recentCompletedEntities:I,hasMoreCompletedRuns:$.length>3,currentEntityScenarios:W,currentEntityForScenarios:Y,currentAnalysisStatus:U})}function Ab({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(me,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
|
|
342
|
-
relative pb-4 px-2 text-sm transition-colors cursor-pointer
|
|
343
|
-
${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
|
|
344
|
-
`,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:d("span",{className:"flex items-center gap-2",children:[o.label,o.count!==null&&o.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
|
|
345
|
-
inline-block w-2 h-2 rounded-full
|
|
346
|
-
${i?"":"bg-gray-400"}
|
|
347
|
-
`,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function Pb({currentlyExecuting:e,currentRun:t,state:r,projectSlug:s,commitSha:a,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:l,currentEntityScenarios:c,currentEntityForScenarios:m,currentAnalysisStatus:u}){var R,I,W,Y;const[p,h]=M({}),[f,y]=M({isKilling:!1,current:0,total:0}),g=kt(),x=!!e,b=(e==null?void 0:e.entities)||[],w=!!(t!=null&&t.analysisCompletedAt),v=w&&!!(t!=null&&t.capturePid),C=!w,P=x,N=c||[],{lastLine:S}=_t(s,P);ne(()=>{if(!t)return;const U=[t.analyzerPid,t.capturePid].filter(A=>!!A);if(U.length===0)return;let B=!0;const H=async()=>{try{const J=await(await fetch(`/api/process-status?pids=${U.join(",")}`)).json();if(J.processes&&B){const V={};J.processes.forEach(q=>{V[q.pid]={isRunning:q.isRunning,processName:q.processName}}),h(V)}}catch(A){B&&console.error("Failed to fetch process statuses:",A)}};H();const D=setInterval(()=>void H(),5e3);return()=>{B=!1,clearInterval(D)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[k,_]=M(!1),[j,T]=M(!1);ne(()=>{b.length<=3&&k&&_(!1)},[b.length,k]),ne(()=>{i.length<=3&&j&&T(!1)},[i.length,j]);const E=k?b:b.slice(0,3),$=b.length>3;return d("div",{className:"flex flex-col gap-[45px]",children:[P?d("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"1px solid #e0e9ec"},children:[d("div",{className:"flex items-center gap-2 mb-[15px]",children:[n(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:v?"Capturing...":"Analyzing..."})]}),E.map(U=>d("div",{className:"bg-white border border-[#e1e1e1] rounded-[4px] mb-[15px]",style:{height:"60px",padding:"0 15px",display:"flex",alignItems:"center",justifyContent:"space-between",boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1)"},children:[d("div",{className:"flex items-center gap-3",children:[n("div",{children:n(at,{type:U.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col gap-[1px]",children:[d("div",{className:"flex items-center gap-[14px]",children:[n(me,{to:`/entity/${U.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:U.name}),U.entityType&&n(Qa,{type:U.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:U.filePath,children:U.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"})]},U.sha)),$&&!k&&d("button",{onClick:()=>_(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",b.length-3," more"," ",b.length-3===1?"entity":"entities"]}),k&&$&&n("button",{onClick:()=>_(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"}),v&&N&&N.length>0&&m&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:N.map(U=>{var q,X,L,O;if(!U.id)return null;const B=(X=(q=U.metadata)==null?void 0:q.screenshotPaths)==null?void 0:X[0],H=(L=U.metadata)==null?void 0:L.noScreenshotSaved,D=B&&!H,A=(O=u==null?void 0:u.scenarios)==null?void 0:O.find(z=>z.name===U.name),V=A&&A.screenshotStartedAt&&!A.screenshotFinishedAt||!D&&!H;return n(me,{to:`/entity/${m.sha}/scenarios/${U.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:V?"#f9f9f9":void 0,borderColor:V?"#efefef":"#ccc"},children:D?n(Ze,{screenshotPath:B,alt:U.name,className:"w-full h-full object-contain bg-gray-100"}):V?n("div",{className:"w-full h-full flex items-center justify-center",children:n(Za,{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"})},U.id)})}),S&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:S}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.capturePid))&&d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center gap-2",children:[d("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(t==null?void 0:t.analyzerPid)&&n(br,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(C||((R=p[t.analyzerPid])==null?void 0:R.isRunning))&&n(br,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(br,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(v||((I=p[t.capturePid])==null?void 0:I.isRunning))&&n(br,{variant:"running"})]}),(((W=p[t==null?void 0:t.analyzerPid])==null?void 0:W.isRunning)||((Y=p[t==null?void 0:t.capturePid])==null?void 0:Y.isRunning))&&n("button",{onClick:()=>{const U=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(D=>{var A;return!!D&&((A=p[D])==null?void 0:A.isRunning)});if(U.length===0)return;const B=U.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${B})?`))return;y({isKilling:!0,current:1,total:U.length}),(async()=>{for(let D=0;D<U.length;D++){const A=U[D];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:A,commitSha:a||""})})}catch(J){console.error(`Failed to kill process ${A}:`,J)}D<U.length-1&&y({isKilling:!0,current:D+2,total:U.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"})]})]}):d("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[d("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Yi,{size:24,style:{color:"#005C75"}})}),d("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Current Activity"}),d("p",{className:"text-sm",style:{color:"#8e8e8e"},children:["There are no analyses running. Trigger one from"," ",n(me,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(me,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),d(me,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]}),i&&i.length>0&&d("div",{children:[n("h3",{className:"font-mono uppercase",style:{fontSize:"12px",lineHeight:"18px",color:"#8e8e8e",marginBottom:"16px",fontWeight:500,letterSpacing:"0.05em"},children:"Recently Completed Analyses"}),d("div",{className:"flex flex-col gap-4",children:[(j?i:i.slice(0,3)).map(U=>{var D;const B=(D=U.analyses)==null?void 0:D[0],H=(B==null?void 0:B.scenarios)||[];return B==null||B.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:d("div",{className:"flex flex-col gap-[15px]",children:[d("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",children:n(at,{type:U.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[d("div",{className:"flex items-center gap-[5px]",children:[n(me,{to:`/entity/${U.sha}`,className:"hover:underline cursor-pointer",title:U.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:U.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:U.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:U.filePath,children:U.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:A=>{A.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:A=>{A.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),H.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:H.map(A=>{var X,L,O;if(!A.id)return null;const J=(L=(X=A.metadata)==null?void 0:X.screenshotPaths)==null?void 0:L[0],V=(O=A.metadata)==null?void 0:O.noScreenshotSaved,q=J&&!V;return d("div",{className:"shrink-0 flex flex-col gap-2",children:[n(me,{to:`/entity/${U.sha}/scenarios/${A.id}`,className:"block cursor-pointer",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{backgroundColor:q?"#f3f4f6":"#FAFAFA",borderColor:q?"#d1d5db":"#BCCDD3",borderStyle:q?"solid":"dashed"},onMouseEnter:z=>{q&&(z.currentTarget.style.borderColor="#005C75",z.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:z=>{z.currentTarget.style.borderColor=q?"#d1d5db":"#BCCDD3",z.currentTarget.style.boxShadow="none"},children:q?n(Ze,{screenshotPath:J,alt:A.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:A.name})]},A.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},U.sha)}),i.length>3&&!j&&d("button",{onClick:()=>T(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",i.length-3," more"," ",i.length-3===1?"entity":"entities"]}),j&&i.length>3&&n("button",{onClick:()=>T(!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 jb({queueJobs:e,state:t,currentRun:r}){if(!e||e.length===0)return d("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[d("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(xd,{size:24,style:{color:"#005C75"}})}),d("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Queued Jobs"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Analysis jobs will appear here when they are queued but not yet started."})]})]}),d(me,{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]=M(null),[o,i]=M(null),[l,c]=M(null),[m,u]=M(!1),[p,h]=M(!1),[f,y]=M(new Set),g=kt();ne(()=>{e.length<=3&&p&&h(!1)},[e.length,p]);const x=N=>{a(N)},b=(N,S)=>{N.preventDefault(),i(S)},w=async(N,S)=>{if(N.preventDefault(),!s){i(null);return}const k=e.findIndex(T=>T.id===s);if(k===-1){a(null),i(null);return}if(k===S){a(null),i(null);return}const _=k<S?"down":"up",j=Math.abs(S-k);u(!0);try{for(let T=0;T<j;T++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:s,direction:_})});g.revalidate()}catch(T){console.error("Failed to reorder job:",T)}finally{u(!1),a(null),i(null)}},v=()=>{m||(a(null),i(null))},C=async N=>{if(confirm("Are you sure you want to cancel this job?"))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"remove",jobId:N})}),window.location.reload()}catch(S){console.error("Failed to cancel job:",S)}},P=async()=>{if(confirm(`Are you sure you want to cancel all ${e.length} queued jobs?`))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}),window.location.reload()}catch(N){console.error("Failed to cancel jobs:",N)}};return d("div",{children:[d("div",{className:"flex items-center justify-between mb-4",children:[d("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:[e.length," Queued Job",e.length!==1?"s":""]}),e.length>0&&n("button",{onClick:()=>void P(),className:"px-[10px] py-0 rounded transition-colors cursor-pointer hover:bg-red-300",style:{backgroundColor:"#ffdcd9",color:"#ef4444",fontSize:"12px",fontWeight:500,height:"29px"},children:"Cancel All"})]}),d("div",{className:"flex flex-col gap-3",children:[(p?e:e.slice(0,3)).map(N=>{var $,R,I,W;const S=e.findIndex(Y=>Y.id===N.id),k=l===S,_=s===N.id,j=o===S,T=f.has(N.id),E=(($=N.entities)==null?void 0:$.length)>0?T?N.entities:N.entities.slice(0,3):[];return d("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:_||m?.5:1,transform:j&&s!==null&&!_?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:m?"not-allowed":_?"grabbing":"grab"},onMouseEnter:()=>c(S),onMouseLeave:()=>c(null),draggable:!m,onDragStart:Y=>{x(N.id),Y.dataTransfer.effectAllowed="move"},onDragOver:Y=>b(Y,S),onDrop:Y=>void w(Y,S),onDragEnd:v,children:[d("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(bd,{size:16,style:{color:"#005C75"}}),d("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",S+1]})]}),d("div",{className:"flex flex-col gap-2 mt-8",children:[E.length>0?d(de,{children:[E.map(Y=>n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(at,{type:Y.entityType||"other",size:"large"})}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(me,{to:`/entity/${Y.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:Y.name}),Y.entityType&&n(Qa,{type:Y.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:Y.filePath})]})]})})},Y.sha)),((R=N.entities)==null?void 0:R.length)>3&&n("button",{onClick:()=>{y(Y=>{const U=new Set(Y);return U.has(N.id)?U.delete(N.id):U.add(N.id),U})},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:T?"Show less":`+${N.entities.length-3} more ${N.entities.length-3===1?"entity":"entities"}`})]}):n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(Mr,{size:18,style:{color:"#8e8e8e"}})}),d("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((I=N.entityNames)==null?void 0:I[0])||(N.type==="analysis"?"Analysis Job":N.type==="recapture"?"Recapture Job":N.type==="debug-setup"?"Debug Setup":N.type.charAt(0).toUpperCase()+N.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((W=N.filePaths)==null?void 0:W[0])||(N.filePaths&&N.filePaths.length>1?`${N.filePaths.length} files`:N.entityShas&&N.entityShas.length>0?`${N.entityShas.length} ${N.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),d("div",{className:"flex items-center justify-end gap-2 mt-1",children:[k&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(wd,{size:20})}),n("button",{onClick:()=>void C(N.id),className:"transition-colors cursor-pointer hover:bg-red-100 rounded flex items-center justify-center",style:{fontSize:"10px",fontWeight:600,lineHeight:"22px",color:"#ef4444",backgroundColor:"#fef6f6",padding:"0 10px",height:"22px"},children:"Cancel"})]})]})]},N.id)}),e.length>3&&!p&&d("button",{onClick:()=>h(!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"]}),p&&e.length>3&&n("button",{onClick:()=>h(!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 Mb({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:s,tab:a,onShowLogs:o}){if(t===0)return d("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[d("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(vd,{size:24,style:{color:"#005C75"}})}),d("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Historic Activity"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Completed analyses will appear here for historical reference."})]})]}),d(me,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[i,l]=M(!1),c=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(p=>{c.push({...p,runCreatedAt:u.createdAt})})});const m=i?c:c.slice(0,3);return d("div",{className:"flex flex-col gap-4",children:[m.map(u=>{var y;const p=(y=u.analyses)==null?void 0:y[0],h=(p==null?void 0:p.scenarios)||[],f=!u.isUncommitted;return d("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[d("div",{className:"flex items-start justify-between mb-3",children:[d("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{children:n(at,{type:u.entityType||"other",size:"large"})}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(me,{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"})]}),h.length>0&&d("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[h.slice(0,8).map(g=>{var v,C,P;if(!g.id)return null;const x=(C=(v=g.metadata)==null?void 0:v.screenshotPaths)==null?void 0:C[0],b=(P=g.metadata)==null?void 0:P.noScreenshotSaved,w=x&&!b;return n(me,{to:`/entity/${u.sha}/scenarios/${g.id}`,className:"border rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px",borderColor:w?"#ccc":"#BCCDD3",borderStyle:w?"solid":"dashed"},children:w?n(Ze,{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)}),h.length>8&&d("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",h.length-8," more"]})]})]},`${u.sha}-${u.runCreatedAt}`)}),c.length>3&&!i&&d("button",{onClick:()=>l(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",c.length-3," more"," ",c.length-3===1?"entity":"entities"]}),i&&c.length>3&&n("button",{onClick:()=>l(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})}const Tb=Je(function(){const t=qe(),r=Fi(),[s,a]=M(!1);xt({source:"activity-page"});const o=r.tab||"current";return t?d("div",{className:"px-20 py-12",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-[15px] text-gray-500",children:"View queued, current, and historical analysis activity."})]}),n(Ab,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(Pb,{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(jb,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(Mb,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>a(!0)}),s&&t.projectSlug&&n(Ft,{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..."})})})}),$b=Object.freeze(Object.defineProperty({__proto__:null,default:Tb,loader:_b,meta:Eb},Symbol.toStringTag,{value:"Module"}));async function xc(e,t,r){var C,P;await ze();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=F.join(a,".codeyam","config.json"),i=JSON.parse(K.readFileSync(o,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const c=rs(l);try{K.writeFileSync(c,"","utf8")}catch{}const{project:m}=await Re(l),u=((C=m.metadata)==null?void 0:C.packageManager)||"npm",p=3112,h=gt(l),f=((P=m.metadata)==null?void 0:P.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const y=i.environmentVariables||[],g=ym({filePath:s.filePath,webapps:f,environmentVariables:y,port:p,packageManager:u});await En(e,N=>{if(N&&(N.readyToBeCaptured=!0,N.scenarios))for(const S of N.scenarios)(!t||S.name===t)&&(delete S.screenshotStartedAt,delete S.screenshotFinishedAt,delete S.interactiveStartedAt,delete S.interactiveFinishedAt,delete S.error,delete S.errorStack)});const{jobId:x}=r.enqueue({type:"debug-setup",commitSha:s.commit.sha,projectSlug:l,analysisId:e,scenarioId:t,prepOnly:!0}),b=g.startCommand,w={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:h}]},{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 ${h}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:b,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${p}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:h,projectSlug:l,port:p,packageManager:u,framework:g.framework,instructions:w}}async function Ib({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 Q({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 Mt()),!o)return Q({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:s,scenarioId:a});try{const i=await xc(s,a,o);return Q({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),Q({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function Rb({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Mt()),!r)return Q({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a)return Q({error:"Missing required field: analysisId"},{status:400});const i=await xc(a,o,r);return Q({...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),Q({error:"Failed to setup debug environment",details:a},{status:500})}}const Db=Object.freeze(Object.defineProperty({__proto__:null,action:Rb,loader:Ib},Symbol.toStringTag,{value:"Module"}));function Ob({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=F.resolve(s,r);if(!a.startsWith(s+F.sep)&&a!==s)return new Response("Path outside project root",{status:403});try{const o=K.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 Lb=Object.freeze(Object.defineProperty({__proto__:null,loader:Ob},Symbol.toStringTag,{value:"Module"})),Fb=process.env.LABS_UNLOCK_SALT||"codeyam-labs-default-salt";function bc(e){const t=Yd("sha256",Fb);return t.update(e),`CY-${t.digest("hex").slice(0,16)}`}function zb(e,t){return t===bc(e)}async function Bb({request:e}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});try{const r=(await e.formData()).get("unlockCode");if(!r)return Q({success:!1,error:"Unlock code is required"},{status:400});const s=await Ie();return s?zb(s,r)?(await vn({projectSlug:s,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),Q({success:!0})):Q({success:!1,error:"Invalid unlock code"},{status:400}):Q({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("[Labs Unlock] Error:",t),Q({success:!1,error:"Failed to validate unlock code. Please try again."},{status:500})}}const Yb=Object.freeze(Object.defineProperty({__proto__:null,action:Bb},Symbol.toStringTag,{value:"Module"}));async function Ub({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Mt()),!r)return Q({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("defaultWidth");if(!a||!o)return Q({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return Q({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${a} with width ${i}`);const l=await vy(a,i,r);return console.log("[API] Recapture queued",l),Q({success:!0,message:"Recapture queued",...l})}catch(s){return console.log("[API] Error during recapture:",s),Q({error:"Failed to recapture screenshots",details:s instanceof Error?s.message:String(s)},{status:500})}}const Wb=Object.freeze(Object.defineProperty({__proto__:null,action:Ub},Symbol.toStringTag,{value:"Module"}));function Hb(e){if(e.length===0)throw new Error("paths array must not be empty");return e.map(Jb).map(a=>a===""?[]:a.split("/")).reduce((a,o)=>{const i=[];for(let l=0;l<Math.min(a.length,o.length)&&a[l]===o[l];l++)i.push(a[l]);return i}).join("/")}function Jb(e){const r=e.replace(/\/+$/,"").split("/");for(;r.length>0;){const s=r[r.length-1];if(Vb(s))r.pop();else break}return r.join("/")}function Vb(e){return!!(e.includes("*")||/\.\w+$/.test(e))}function Gb({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=Hb(r),a=s?`.claude/rules/${s}/`:".claude/rules/";return Response.json({result:a})}const Kb=Object.freeze(Object.defineProperty({__proto__:null,loader:Gb},Symbol.toStringTag,{value:"Module"}));function qb(e,t){var i,l,c,m,u;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,s=e.analyses&&e.analyses.length>0&&e.analyses.some(p=>p.scenarios&&p.scenarios.length>0);if(!r){const p=!!((l=e.metadata)!=null&&l.previousVersionWithAnalyses),h=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return p||h?s?{state:"committed_no_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Committed - Simulations Outdated",color:"text-orange-700",bgColor:"bg-orange-50",borderColor:"border-orange-300",icon:"⚠"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Yet Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}:s?{state:"committed_with_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up to date",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"✓"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}const a=!!((c=e.metadata)!=null&&c.previousCommittedSha);if(!!((m=e.metadata)!=null&&m.previousVersionWithAnalyses)||a){const p=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return s&&!p?{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 Qb(e){return qb(e).hasOutdatedSimulations}function gs(e,t,r,s,a){var Y,U,B,H,D,A,J,V;const o=(Y=t==null?void 0:t.scenarios)==null?void 0:Y.find(q=>q.name===e.name),i=!!(o!=null&&o.startedAt),l=!!(o!=null&&o.screenshotStartedAt),c=!!(o!=null&&o.screenshotFinishedAt),m=!!(o!=null&&o.finishedAt),u=1800*1e3,p=l&&!c&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,h=!!((B=(U=e.metadata)==null?void 0:U.screenshotPaths)!=null&&B[0])||!!((H=e.metadata)!=null&&H.executionResult),f=l&&!c,y=o==null?void 0:o.error,g=(A=(D=e.metadata)==null?void 0:D.executionResult)==null?void 0:A.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const q of t.errors)x.push({source:`${q.phase} phase`,message:q.message});if(t!=null&&t.steps)for(const q of t.steps)q.error&&x.push({source:q.name,message:q.error});const b=!h&&!y&&!g&&x.length>0,w=!!(y||g||p||b),v=p?"Capture timed out after 30 minutes":(typeof y=="string"?y:null)||(g==null?void 0:g.message)||(b?`Analysis error: ${x[0].message}`:null),C=p?"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,N=(s&&a?a.jobs.some(q=>{var X;return((X=q.entityShas)==null?void 0:X.includes(s))||q.type==="analysis"&&q.entityShas&&q.entityShas.length===0})||((V=(J=a.currentlyExecuting)==null?void 0:J.entityShas)==null?void 0:V.includes(s)):!1)&&!i&&!w||!!(o!=null&&o.analyzing)&&!i&&!w,S=i&&!l&&!m&&!w,k=(N||S||f)&&!w,_=(N||S)&&r===!1&&!h;let j;_?j="crashed":w?j="error":h||m?j="completed":f?j="capturing":S?j="starting":N?j="queued":j="pending";let T="📷",E="pending",$=!1,R=`Not captured: ${e.name}`;const I="border-gray-300",W=w||_?"bg-red-50":"bg-white";return w||_?(T="⚠️",E="error",R=`Error: ${_?"Analysis process crashed":v||"Unknown error"}`):N?(T="⋯",E="queued",R=`Queued: ${e.name}`):S?(T="⋯",E="starting",$=!0,R=`Starting server for ${e.name}...`):f&&!w?(T="⋯",E="capturing",$=!0,R=`Capturing ${e.name}...`):h&&(T="✓",E="completed",R=e.name),{hasError:w||_,errorMessage:_?"Analysis process crashed":v,errorStack:_?"Process terminated unexpectedly before completing analysis":C,isCapturing:f,isCaptured:h,hasCrashed:_,isAnalyzing:k,isQueued:N,isServerStarting:S,status:j,icon:T,iconType:E,shouldSpin:$,title:R,borderColor:I,bgColor:W}}function wc({scenario:e,entitySha:t,size:r="medium",showBorder:s=!0,isOutdated:a=!1}){var C,P,N,S,k,_;const o=gs(e,void 0,void 0,t,void 0),i=(C=e.metadata)==null?void 0:C.executionResult,l=!!i,m=(((N=(P=e.metadata)==null?void 0:P.data)==null?void 0:N.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,p=((k=(S=i==null?void 0:i.sideEffects)==null?void 0:S.consoleOutput)==null?void 0:k.length)||0,h=((_=i==null?void 0:i.timing)==null?void 0:_.duration)||0;let f=0;m>0&&f++,m>2&&f++,u&&f++,p>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"}:l?a?{border:"border-amber-500",bg:"bg-amber-50",icon:"text-amber-700",badge:"bg-amber-100 text-amber-700"}:{border:"border-blue-400",bg:"bg-blue-50",icon:"text-blue-600",badge:"bg-blue-100 text-blue-700"}:{border:"border-gray-300 border-dashed",bg:"bg-gray-50",icon:"text-gray-400",badge:"bg-gray-100 text-gray-600"},b=s?`border-2 ${x.border}`:"",w=Array.from({length:3},(j,T)=>n("div",{className:`w-1 h-1 rounded-full ${T<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},T)),v=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:l?`${e.name}
|
|
348
|
-
${m} args → ${u?"value":"void"}${p>0?` (${p} logs)`:""}
|
|
349
|
-
${h}ms`:`Not executed: ${e.name}`;return d(me,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${y.width} ${y.height} ${b} rounded ${x.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:v,onClick:j=>j.stopPropagation(),children:[n("div",{className:`${x.icon} ${y.iconSize} font-mono font-bold`,children:o.hasError?"⚠":l?"ƒ":"○"}),l&&!o.hasError&&d("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?"✓":"∅"})]}),l&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:w}),l&&!o.hasError&&h>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:h>1e3?`${Math.round(h/1e3)}s`:`${h}ms`}),l&&!o.hasError&&p>0&&r==="medium"&&d("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",p]})]})}function ga({size:e=24,className:t=""}){return d("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:[n("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),n("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),n("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function ii({scenario:e,entity:t,analysisStatus:r,queueState:s,processIsRunning:a,size:o="medium",cacheBuster:i,className:l="",viewMode:c}){var g,x;if(t.entityType==="library")return n(wc,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=gs(e,r,a,t.sha,s),p=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"},h=`relative ${p.containerClass} ${l}`,f=()=>{const b=`/entity/${t.sha}/scenarios/${e.id}`;return c?`${b}/${c}`:b};if(u.isCaptured){const b=(x=(g=e.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return n(me,{to:f(),className:`${h} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(Ze,{screenshotPath:b,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const y=()=>{const b={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},w=n(Za,{size:o});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return w;switch(u.iconType){case"starting":case"capturing":return w;case"error":return d("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(ga,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(Nd,{...b});default:return w}};return n(me,{to:f(),className:`${h} ${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:p.iconSize,children:y()})})}const xn=70;function Zb({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:s,entitySha:a,cacheBuster:o,activeTab:i,entityType:l,entity:c,queueState:m,processIsRunning:u,isEntityAnalyzing:p,areScenariosStale:h,viewMode:f,setViewMode:y,isBreakdownView:g}){var $,R,I,W,Y,U;const x=ve(null),[b,w]=M(new Set),[v,C]=M(!1);ne(()=>{x.current&&i==="scenarios"&&x.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[s==null?void 0:s.id,i]);const P=B=>`/entity/${a}/scenarios/${B}`,N=B=>{w(H=>{const D=new Set(H);return D.has(B)?D.delete(B):D.add(B),D})},S=(B,H=2)=>{const A=B.split(`
|
|
350
|
-
`).slice(0,H).join(" ").trim();return A.length>xn?A.substring(0,xn-3):(B.split(`
|
|
351
|
-
`).length>H||B.length>A.length,A)},k=ae(()=>{var H;if(!((H=r==null?void 0:r.metadata)!=null&&H.executionFlows)||!(r!=null&&r.scenarios))return null;const B=r.scenarios.filter(D=>{var A;return!((A=D.metadata)!=null&&A.sameAsDefault)});return Va(r.metadata.executionFlows,B)},[r]),_=(k==null?void 0:k.totalFlows)||0,j=(k==null?void 0:k.coveredFlows)||0,T=(k==null?void 0:k.coveragePercentage)||0;($=c==null?void 0:c.metadata)!=null&&$.defaultWidth||(R=r==null?void 0:r.metadata)!=null&&R.defaultWidth;const E=(I=r==null?void 0:r.status)!=null&&I.finishedAt?new Date(r.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return d("aside",{className:"w-[250px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-4",children:[r&&e.length>0&&d("div",{className:"flex flex-col gap-2",children:[n("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),d("div",{className:"grid grid-cols-2 gap-2",children:[d(me,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((W=e[0])==null?void 0:W.id)}`:`/entity/${a}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[d("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(T),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),d(me,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((Y=e[0])==null?void 0:Y.id)}`:`/entity/${a}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[d("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[j,"/",_]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),d(me,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((U=e[0])==null?void 0:U.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"})})]})]}),c&&c.filePath&&n("div",{children:n(me,{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&&d("div",{className:"py-3 flex items-center justify-between",children:[d("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),E&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:E})]}),p&&(h||e.length===0)?d("div",{className:"",children:[d("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[d("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}),n("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):e.length===0?n("div",{className:"",children:n("p",{className:"text-[#8e8e8e] text-xs font-medium m-0 text-left leading-5",children:"No Scenarios"})}):n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"flex flex-col gap-[11.6px]",children:e.map((B,H)=>{const D=!g&&(s==null?void 0:s.id)===B.id,A=b.has(B.id||"");return B.id?d(me,{to:P(B.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(ii,{scenario:B,entity:{sha:a,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:m,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),d("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${A?"":"line-clamp-1"}`,children:B.name}),B.description&&n("div",{className:"mt-2",children:d("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[A?B.description:S(B.description),!A&&B.description.length>xn&&d(de,{children:["...",n("button",{onClick:J=>{J.preventDefault(),J.stopPropagation(),N(B.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),A&&B.description.length>xn&&n("button",{onClick:J=>{J.preventDefault(),J.stopPropagation(),N(B.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},H):null})})}),t.length>0&&!(p&&h)&&d("div",{className:"border-t border-[#e1e1e1] pt-3",children:[d("button",{onClick:()=>C(!v),className:"flex items-center gap-1 text-[10px] text-[#626262] font-medium cursor-pointer bg-transparent border-none p-0 hover:text-[#005c75] transition-colors w-full",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`transition-transform ${v?"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,")"]}),v&&d("div",{className:"mt-2",children:[n("p",{className:"text-[10px] text-[#8e8e8e] leading-[14px] mb-3",children:"These scenarios were hidden because the screenshots did not differ from the Default Scenario."}),n("div",{className:"flex flex-col gap-[11.6px]",children:t.map((B,H)=>{const D=!g&&(s==null?void 0:s.id)===B.id,A=b.has(B.id||"");return B.id?d(me,{to:`/entity/${a}/scenarios/${B.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(ii,{scenario:B,entity:{sha:a,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:m,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),d("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${A?"":"line-clamp-1"}`,children:B.name}),B.description&&n("div",{className:"mt-2",children:d("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[A?B.description:S(B.description),!A&&B.description.length>xn&&d(de,{children:["...",n("button",{onClick:J=>{J.preventDefault(),J.stopPropagation(),N(B.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),A&&B.description.length>xn&&n("button",{onClick:J=>{J.preventDefault(),J.stopPropagation(),N(B.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},H):null})})]})]})]})}function Xb({scenario:e,entitySha:t,onApply:r,onSave:s,onEditMockData:a,onDelete:o,isApplying:i=!1,isSaving:l=!1,saveMessage:c=null,showDeleteConfirm:m=!1,onShowDeleteConfirm:u,isDeleting:p=!1,deleteError:h=null}){const[f,y]=M(""),g=async()=>{await r(f)},x=async b=>{await s(f,b),b||y("")};return d("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[d("div",{className:"border-b border-[#e1e1e1] pb-3",children:[d("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(me,{to:`/entity/${t}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),n("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),d("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[d("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange:b=>y(b.target.value),placeholder:"e.g. change amount of data to zero",className:"w-full px-[7px] py-[6px] border border-[#c7c7c7] rounded-[4px] text-xs focus:outline-none focus:ring-1 focus:ring-[#005c75] focus:border-[#005c75] resize-none",rows:4}),d("button",{onClick:()=>void 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&&d("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),i?"Applying...":"Apply"]})]}),n("div",{className:"border-t border-[#e1e1e1] my-1"}),d("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick:a,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),c&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${c.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:c}),c==="Recapture successful"&&n("div",{children:n(me,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),d("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[n("button",{onClick:()=>void x(!1),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center",children:l?"Saving...":"Save Scenario Data"}),n("button",{onClick:()=>void x(!0),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:"Save As New"}),o&&d(de,{children:[m?d("div",{className:"flex flex-col gap-1",children:[d("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),d("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void o(),disabled:p,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:p?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>u==null?void 0:u(!1),disabled:p,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"}),h&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:h})]})]})]})}function ew({scenario:e,analysis:t,entity:r}){var i,l,c;const s=((i=e.metadata)==null?void 0:i.executionResult)||null,a=((c=(l=e.metadata)==null?void 0:l.data)==null?void 0:c.argumentsData)||[],o=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=[],p=((y=m.sideEffects)==null?void 0:y.consoleOutput)||[];p.length>0&&(u.push(`Console Output: ${p.length} log ${p.length===1?"entry":"entries"} captured`),p.forEach(b=>{u.push(` [${b.level.toUpperCase()}] ${b.args.join(" ")}`)}));const h=((g=m.sideEffects)==null?void 0:g.fileWrites)||[];h.length>0&&(u.push(`
|
|
352
|
-
File System Operations: ${h.length} ${h.length===1?"operation":"operations"} detected`),h.forEach(b=>{u.push(` ${b.operation}: ${b.path}${b.size?` (${b.size} bytes)`:""}`)}));const f=((x=m.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(u.push(`
|
|
353
|
-
API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(b=>{u.push(` ${b.method} ${b.url}${b.status?` → ${b.status}`:""}${b.duration?` (${b.duration}ms)`:""}`)})),m.error&&u.push(`
|
|
354
|
-
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(`
|
|
355
|
-
`)};return d("div",{className:"flex w-full h-full gap-0",children:[d("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(a,null,2)})})]}),d("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:s?n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:s.returnValue!==void 0?JSON.stringify(s.returnValue,null,2):"undefined"}):n("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),d("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:o(s)})})]})]})}const en={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function wr({scenarioId:e,analysisId:t}){const[r,s]=M(!1),[a,o]=M(!1),[i,l]=M(null),[c,m]=M(!1),u=e||t;if(!u)return null;const p=`/codeyam-diagnose ${u}`,h=async()=>{o(!0);try{const{default:y}=await import("html2canvas-pro"),x=(await y(document.body,{scale:.5})).toDataURL("image/jpeg",.8);l(x),s(!0)}catch(y){console.error("Screenshot capture failed:",y),s(!0)}finally{o(!1)}},f=()=>{s(!1),l(null)};return d(de,{children:[d("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[n("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:en.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:en.subtext},children:"Simply run this command in Claude Code:"}),d("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:en.commandBoxBg,borderColor:en.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:en.commandBoxText},children:p}),n("button",{onClick:y=>{y.stopPropagation(),navigator.clipboard.writeText(p),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:c?"#22c55e":en.commandBoxText},title:c?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:c?n(ut,{size:14}):n(ft,{size:14})})]}),d("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",n("button",{onClick:()=>void h(),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:en.link},children:a?"capturing...":"please do so here"}),"."]})]}),n(Ki,{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 li=1440,vr=[{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 vc({selectedScenario:e,analysis:t,entity:r,viewMode:s,cacheBuster:a,hasScenarios:o,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:c=!0,processIsRunning:m,queueState:u}){var G,ee,re,ue,se,pe,Ce,_e,Ae,De,Le;const p=Fe(),[h,f]=M(!1),[y,g]=M(!1),[x,b]=M({name:"Desktop",width:li,height:900}),[w,v]=M(li),[C,P]=M(1),{customSizes:N,addCustomSize:S,removeCustomSize:k}=cs(l),_=ae(()=>[...vr,...N],[N]),j=(Se,oe)=>{v(Se);const xe=_.find(ke=>ke.width===Se&&ke.height===oe);b({name:(xe==null?void 0:xe.name)||"Custom",width:Se,height:oe})},T=Se=>{v(Se.width),b({name:Se.name,width:Se.width,height:Se.height})},E=Se=>{S(Se,x.width,x.height??900),g(!1),b(oe=>({...oe,name:Se}))},$=(Se,oe)=>{v(Se);const xe=_.find(ke=>ke.width===Se&&ke.height===oe);b(ke=>({name:(xe==null?void 0:xe.name)||"Custom",width:Se,height:ke.height}))},R=(ee=(G=e==null?void 0:e.metadata)==null?void 0:G.screenshotPaths)==null?void 0:ee[0],I=ae(()=>e?gs(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]),W=ae(()=>{var oe,xe;const Se=[];if((oe=t==null?void 0:t.status)!=null&&oe.errors&&t.status.errors.length>0)for(const ke of t.status.errors)Se.push({source:`${ke.phase} phase`,message:ke.message,stack:ke.stack});if((xe=t==null?void 0:t.status)!=null&&xe.steps)for(const ke of t.status.steps)ke.error&&Se.push({source:ke.name,message:ke.error,stack:ke.errorStack});return Se},[(re=t==null?void 0:t.status)==null?void 0:re.errors,(ue=t==null?void 0:t.status)==null?void 0:ue.steps]),Y=(I==null?void 0:I.errorMessage)||null,U=(I==null?void 0:I.errorStack)||null,{interactiveServerUrl:B,isStarting:H,isLoading:D,showIframe:A,iframeKey:J,onIframeLoad:V}=pn({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:l,enabled:s==="interactive"}),q=ae(()=>B||null,[B]),X=!i&&o&&e&&!((pe=(se=e.metadata)==null?void 0:se.screenshotPaths)!=null&&pe[0])&&((_e=(Ce=t==null?void 0:t.status)==null?void 0:Ce.scenarios)==null?void 0:_e.some(Se=>Se.name===e.name&&Se.screenshotStartedAt&&!Se.screenshotFinishedAt)),{lastLine:L}=_t(l,i||s==="interactive"||X||!1);if(!e){if(i&&r)return d(de,{children:[n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:d("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children: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."}),L&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:L}),l&&n("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})}),h&&l&&n(Ft,{projectSlug:l,onClose:()=>f(!1)})]});if(!o&&r&&!i){if(W.length>0){const Se=W.length===1?((Ae=W[0])==null?void 0:Ae.message)||"An error occurred during analysis.":`${W.length} errors occurred during analysis.`;return d(de,{children:[n("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:d("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded",style:{backgroundColor:vt.background,border:`2px solid ${vt.border}`},role:"alert",children:d("div",{className:"flex items-center gap-3",children:[n(ga,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:d("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:vt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",Se," ",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(wr,{analysisId:t==null?void 0:t.id})})]})}),h&&l&&n(Ft,{projectSlug:l,onClose:()=>f(!1)})]})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:d("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{p.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:p.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:p.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return d(de,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
|
|
356
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
357
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
358
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
359
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
360
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||X&&!R)&&!Y&&s==="screenshot"?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-linear-to-br from-blue-50 to-indigo-50",children:d("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[d("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children: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${((Le=t==null?void 0:t.scenarios)==null?void 0:Le.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&d("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),L&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:d("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),d("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:L,children:L})]})]})}),l&&n("button",{onClick:()=>f(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),n("p",{className:"text-xs text-gray-500 mt-8 m-0",children:"Screenshots will appear here as they are captured. This may take a few minutes."})]})}):s==="screenshot"&&(R||Y)||s==="interactive"&&(q||H)||s==="data"?d(de,{children:[Y&&!R&&n("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:d("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:vt.background,border:`2px solid ${vt.border}`,maxHeight:"50vh"},role:"alert",children:d("div",{className:"flex flex-col gap-3",children:[d("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:vt.text},children:[n(ga,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),d("div",{className:"text-center",children:[n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color: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:Y})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(wr,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),s==="interactive"?d("div",{className:"flex-1 flex flex-col min-h-0",children:[q&&d("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center items-center gap-4",children:[n(Fh,{presets:[...vr],customSizes:N,currentWidth:x.width,currentHeight:x.height??900,scale:C,onSizeChange:j,onSaveCustomSize:()=>g(!0),onRemoveCustomSize:k}),e&&r&&d(me,{to:`/entity/${r.sha}/scenarios/${e.id}/fullscreen?from=${encodeURIComponent(`/entity/${r.sha}/scenarios/${e.id}/interactive`)}`,className:"flex items-center gap-2 px-4 py-2 bg-[#005c75] text-white rounded hover:bg-[#004a5c] transition-colors text-sm font-medium no-underline",title:"Open in fullscreen",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:n("path",{d:"M2 5V2H5M11 2H14V5M14 11V14H11M5 14H2V11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Fullscreen"]})]}),q&&n("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${vr[vr.length-1].width}px`,width:"100%"},children:n(Oa,{currentViewportWidth:w,currentPresetName:x.name,onDevicePresetClick:T,devicePresets:_})})}),n(us,{scenarioId:e.id,scenarioName:e.name,iframeUrl:q,isStarting:H,isLoading:D,showIframe:A,iframeKey:J,onIframeLoad:V,onScaleChange:P,onDimensionChange:$,projectSlug:l,defaultWidth:x.width,defaultHeight:x.height})]}):s==="data"?n("div",{className:"flex-1 min-h-0",children:n(ew,{scenario:e,analysis:t,entity:r})}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 p-6 flex items-center justify-center",children:n("div",{className:"transition-all duration-300",style:{maxWidth:`${w}px`},children:(R||!Y)&&n(Ze,{screenshotPath:R,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&&!R?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),d("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),d("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),L&&d("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:L})]}),l&&n("button",{onClick:()=>f(!0),className:"mt-4 px-4 py-2 bg-[#005c75] text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-[#004a5e]",children:"📋 View Full Logs"})]})]})})}):Y?d("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!c&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:d("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[d("div",{className:"flex items-start gap-4",children:[n("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),d("div",{className:"bg-white border border-blue-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-blue-900 m-0 mb-2 uppercase tracking-wide",children:"CodeYam requires an AI API key for reliable analysis."}),d("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[n("li",{children:"You can use API keys for a variety of models"}),n("li",{children:"Faster analysis processing"}),n("li",{children:"Better handling of complex code structures"}),n("li",{children:"Improved scenario generation quality"})]})]}),n(me,{to:"/settings",className:"inline-block px-4 py-2 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700",children:"🔐 Configure API Keys"})]})}),n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),d("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),d("div",{className:"bg-white border border-red-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),n("div",{className:"max-h-[300px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:Y})})]}),U&&d("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:U})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(wr,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):W.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),d("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:W,title:"Analysis Error",description:W.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${W.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(wr,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):d("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),h&&l&&n(Ft,{projectSlug:l,onClose:()=>f(!1)}),y&&n(ls,{width:x.width,height:x.height??900,onSave:E,onCancel:()=>g(!1)})]})}function tw({analysis:e,entitySha:t}){kt();const[r,s]=M(e);ne(()=>{s(e)},[e]);const[a,o]=M(null),i=ae(()=>{var p;if(!((p=r==null?void 0:r.metadata)!=null&&p.executionFlows)||!(r!=null&&r.scenarios))return null;const u=r.scenarios.filter(h=>{var f;return!((f=h.metadata)!=null&&f.sameAsDefault)});return Va(r.metadata.executionFlows,u)},[r]),l=ae(()=>i?lg(i):[],[i]),c=ae(()=>r!=null&&r.scenarios?r.scenarios.filter(u=>{var p;return!((p=u.metadata)!=null&&p.sameAsDefault)}):[],[r]),m=u=>{var h;const p=((h=u.metadata)==null?void 0:h.coveredFlows)||[];return i?i.executionFlows.filter(f=>p.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:d("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:d("div",{className:"p-6 space-y-6",children:[d("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),d("div",{className:"grid grid-cols-4 gap-4 text-center",children:[d("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:c.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:i.executionFlows.length}),n("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[d("div",{className:"text-2xl font-bold text-gray-900",children:[i.coveredFlows,"/",i.totalFlows]}),n("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[d("div",{className:`text-2xl font-bold ${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"})]})]})]}),d("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:d("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",c.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:c.length===0?d("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",n(me,{to:`/entity/${t}/create-scenario`,className:"text-blue-600 hover:underline",children:"Create one"})]}):c.map(u=>{var f,y,g;const p=(y=(f=u.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0],h=m(u);return d("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(Ze,{screenshotPath:p,alt:u.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),d("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:d("div",{children:[n(me,{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}),h.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:h.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:d(me,{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"]})})]}),l.length>0&&d("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[d("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[l.length," uncovered execution flow",l.length>1?"s":""," — consider adding scenarios to cover these"]}),d("div",{className:"flex flex-wrap gap-1",children:[l.slice(0,10).map(u=>d("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)),l.length>10&&d("span",{className:"text-xs text-amber-600",children:["+",l.length-10," more"]})]})]}),d("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:d("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",i.executionFlows.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:i.executionFlows.map(u=>{const p=a===u.id,h=u.usedInScenarios.length>0;return d("div",{children:[n("button",{onClick:()=>o(p?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:d("div",{className:"flex items-start gap-3 flex-1",children:[n("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:p?"▼":"▶"}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-medium text-sm text-gray-900",children:u.name}),h?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})]})]})}),p&&d("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[u.requiredValues.length>0&&d("div",{className:"mb-4",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),n("div",{className:"space-y-1",children:u.requiredValues.map((f,y)=>d("div",{className:"flex items-center gap-2 text-xs",children:[n("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children: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))})]}),h&&d("div",{children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),n("div",{className:"flex flex-wrap gap-1",children: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&&d("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:u.codeSnippet})})]})]})]},u.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:d("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function ci({hasIndirectBadge:e,onAnalyze:t}){return d(de,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:d("div",{className:"flex items-center justify-end gap-2",children:[e&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:"0 scenarios"})]})}),d("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[n("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),n("button",{className:"px-[15px] py-0 h-[23px] bg-[#005c75] text-white rounded text-xs font-medium leading-5 border-none cursor-pointer hover:bg-[#004a5e] transition-colors flex items-center justify-center",onClick:t,children:"Analyze"})]})]})}function nw({entity:e,history:t}){const[r,s]=M("entity"),[a,o]=M(new Set),i=t.filter(u=>u.analyses.length>0).length,l=ae(()=>{const u=new Map;return t.forEach(p=>{p.analyses.forEach(h=>{(h.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:p,analysis:h,scenario:y})})})}),Array.from(u.entries()).map(([p,h])=>{var f;return{name:p,description:((f=h[0])==null?void 0:f.scenario.description)||"",versions:h.sort((y,g)=>{const x=new Date(y.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-x})}})},[t]),c=l.length,m=u=>{o(p=>{const h=new Set(p);return h.has(u)?h.delete(u):h.add(u),h})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:d("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:d("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[d("button",{onClick:()=>s("entity"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="entity"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-semibold leading-6",children:"Entity History"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="entity"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:i})]}),d("button",{onClick:()=>s("scenarios"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="scenarios"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-normal leading-6",children:"Scenario Changes"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="scenarios"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:c})]})]})}),t.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):r==="entity"?d("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((u,p)=>d("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center gap-3",children:[u.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),d(me,{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((h,f)=>{var g;const y=(h.scenarios??[]).filter(x=>{var b;return!((b=x.metadata)!=null&&b.sameAsDefault)});return n("div",{children:y.length===0?n(ci,{hasIndirectBadge:h.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):d(de,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:d("div",{className:"flex items-center justify-end gap-2",children:[h.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),d("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[y.length," scenario",y.length!==1?"s":""]})]})}),((g=h.metadata)==null?void 0:g.scenarioChangesOverview)&&n("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:d("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[d("span",{className:"font-medium",children:["What Changed:"," "]}),h.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,b)=>{var C,P;const w=(P=(C=x.metadata)==null?void 0:C.screenshotPaths)==null?void 0:P[0],v=`${x.name}-${b}`;return d(me,{to:`/entity/${u.sha}/scenarios/${x.id}`,className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden hover:border-[#005c75] hover:shadow-sm transition-all",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:w?n(Ze,{screenshotPath:w,alt:x.name,className:"max-w-full max-h-full object-contain rounded-sm"}):d("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:x.name})})]},v)})})})]})},h.id||f)})}):n(ci,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:l.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):l.map((u,p)=>{const h=a.has(u.name),f=h?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,d("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),d("div",{className:"p-5 bg-white",children:[f.map((x,b)=>{var S,k;const{version:w,analysis:v,scenario:C}=x,P=(k=(S=C.metadata)==null?void 0:S.screenshotPaths)==null?void 0:k[0],N=b===0;return d("div",{className:`flex gap-5 items-start ${N?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(me,{to:`/entity/${w.sha}/scenarios/${C.id}`,className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0 hover:border-[#005c75] hover:shadow-sm transition-all",children:P?n(Ze,{screenshotPath:P,alt:C.name,className:"max-w-full max-h-full object-contain rounded-sm"}):d("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),d("div",{className:"flex-1 flex flex-col gap-2",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[w.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),N&&u.versions.length>1&&d("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[u.versions.length," versions"]})]}),d(me,{to:`/entity/${w.sha}/scenarios`,className:"text-xs font-mono text-[#646464] m-0 leading-5 hover:text-[#005c75] transition-colors w-fit",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:w.sha.substring(0,8)})]}),v.createdAt&&d("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(v.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),v.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${w.sha}-${b}`)}),y>0&&d("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 ${h?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),h?"Hide":`${y} previous version${y!==1?"s":""}`]})]})]})]},u.name)})})]})})}function di({entity:e,analysisInfo:t,from:r}){const s=Fe(),a=s.state!=="idle",o=e.entityType==="visual"||e.entityType==="library",i=l=>{l.preventDefault(),l.stopPropagation(),o&&s.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(me,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:d("div",{className:"flex gap-0 border border-gray-200 rounded-lg overflow-hidden transition-all hover:border-[#005c75] hover:shadow-md bg-white h-[100px]",children:[e.screenshotPath?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(Ze,{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(at,{type:e.entityType})})}),d("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(at,{type:e.entityType}),n("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),n("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),t.hasScenarios&&d("div",{className:"flex items-center gap-2 mt-2",children:[d("span",{className:"px-[5px] py-0 bg-[#efefef] text-[#3e3e3e] rounded text-[10px] font-medium",children:[t.scenarioCount," scenarios"]}),n("span",{className:"text-xs text-[#8e8e8e]",children:t.timestamp})]})]}),n("div",{className:"shrink-0 ml-4",children:t.status==="not_analyzed"?d(de,{children:[d("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:a,children:a?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?d("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):d(de,{children:[d("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:a,children:a?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const ui=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 rw({importedEntities:e,importingEntities:t}){const[r]=Cn(),s=r.get("from"),a=Fe(),o=a.state!=="idle",i=e.length>0,l=t.length>0,c=h=>h.filter(f=>f.entityType==="visual"||f.entityType==="library"),m=h=>{const f=c(h);f.length!==0&&a.submit({entityShas:f.map(y=>y.sha).join(",")},{method:"post",action:"/api/analyze"})},u=c(e).length>0,p=c(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-6 py-4 flex items-start justify-between",children:[d("div",{children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&n("button",{onClick:()=>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(h=>n(di,{entity:h,analysisInfo:ui(h),from:s},h.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-6 py-4 flex items-start justify-between",children:[d("div",{children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),p&&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"})]}),l?n("div",{className:"p-6 space-y-4",children:t.map(h=>n(di,{entity:h,analysisInfo:ui(h),from:s},h.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 sw({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(rw,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function aw({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(tr,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function tr({data:e,depth:t,defaultExpanded:r,maxDepth:s,objectKey:a,showInlineToggle:o=!1}){const[i,l]=M(r||t<2);if(ne(()=>{l(r||t<2)},[r,t]),e===null)return n("span",{className:"text-gray-500",children:"null"});if(e===void 0)return n("span",{className:"text-gray-500",children:"undefined"});const c=typeof e;if(c==="string")return d("span",{className:"text-green-600",children:['"',e,'"']});if(c==="number")return n("span",{className:"text-blue-600",children:e});if(c==="boolean")return n("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?n("span",{className:"text-gray-600",children:"[]"}):d("span",{children:[d("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[d("span",{children:[i?"▼":"▶"," ","["]}),!i&&d("span",{children:[e.length,"]"]})]}),i?d(de,{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(tr,{data:m,depth:t+1,defaultExpanded:r,maxDepth:s})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(c==="object"){const m=Object.keys(e);if(m.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=h=>h!==null&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,p=h=>Array.isArray(h)&&h.length>0;return d("span",{children:[d("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[d("span",{children:[i?"▼":"▶"," ","{"]}),!i&&d("span",{children:[m.length,"}"]})]}),i?d(de,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:m.map(h=>{const f=e[h],y=u(f),g=p(f);return n("div",{className:"py-0.5",children:y?n(Xa,{propertyKey:h,value:f,depth:t,defaultExpanded:r,maxDepth:s}):g?n(eo,{propertyKey:h,value:f,depth:t,defaultExpanded:r,maxDepth:s}):d(de,{children:[d("span",{className:"text-orange-600",children:[h,": "]}),n(tr,{data:f,depth:t+1,defaultExpanded:r,maxDepth:s})]})},h)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function Xa({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=M(s||r<2),l=Object.keys(t);return ne(()=>{i(s||r<2)},[s,r]),d(de,{children:[d("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),d("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&d("span",{className:"text-gray-600",children:[l.length,"}"]})]}),o&&d(de,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:l.map(c=>{const m=t[c],u=m!==null&&typeof m=="object"&&!Array.isArray(m)&&Object.keys(m).length>0,p=Array.isArray(m)&&m.length>0;return n("div",{className:"py-0.5",children:u?n(Xa,{propertyKey:c,value:m,depth:r+1,defaultExpanded:s,maxDepth:a}):p?n(eo,{propertyKey:c,value:m,depth:r+1,defaultExpanded:s,maxDepth:a}):d(de,{children:[d("span",{className:"text-orange-600",children:[c,": "]}),n(tr,{data:m,depth:r+2,defaultExpanded:s,maxDepth:a})]})},c)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function eo({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=M(s||r<2);return ne(()=>{i(s||r<2)},[s,r]),d(de,{children:[d("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),d("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&d("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&d(de,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((l,c)=>{const m=l!==null&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,u=Array.isArray(l)&&l.length>0;return n("div",{className:"py-0.5",children:m?n(Xa,{propertyKey:c.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:a}):u?n(eo,{propertyKey:c.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:a}):n(tr,{data:l,depth:r+2,defaultExpanded:s,maxDepth:a})},c)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function Hs({label:e,count:t,isActive:r,onClick:s,badgeColorActive:a,badgeTextActive:o}){return d("button",{onClick:s,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${a} ${o}`:"bg-gray-200 text-gray-700"}`,children:t}),r&&n("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function mi({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 pi({call:e,scenarioName:t}){const[r,s]=M(!1),[a,o]=M("system"),i=h=>new Date(h).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),l=h=>h?`$${h.toFixed(4)}`:null,c=(h,f)=>{if(!h&&!f)return null;const y=[];return h&&y.push(`${h.toLocaleString()} in`),f&&y.push(`${f.toLocaleString()} out`),y.join(" / ")},m=ae(()=>{var h,f,y,g,x;try{const b=JSON.parse(e.response);return(y=(f=(h=b.choices)==null?void 0:h[0])==null?void 0:f.message)!=null&&y.content?b.choices[0].message.content:(x=(g=b.content)==null?void 0:g[0])!=null&&x.text?b.content[0].text:e.response}catch{return e.response}},[e.response]),u=ae(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),p=ae(()=>{var h;if(t)return t;try{const f=JSON.parse(e.props);return((h=f==null?void 0:f.scenario)==null?void 0:h.name)||null}catch{return null}},[e.props,t]);return d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>s(!r),children:d("div",{className:"flex items-start justify-between gap-4",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),p&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:p}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),d("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),c(e.input_tokens,e.output_tokens)&&n("span",{children:c(e.input_tokens,e.output_tokens)}),l(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:l(e.cost)})]}),d("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.object_id,"_",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&d("div",{className:"border-t border-[#e1e1e1]",children:[d("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>o("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>o("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>o("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),a&&d("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[a==="system"&&n("div",{children:e.system_message?n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.system_message}):n("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),a==="prompt"&&n("div",{children:n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.prompt_text})}),a==="response"&&d("div",{children:[e.error&&d("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children: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:d("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const hi=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function ow({entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a}){var v,C,P,N,S,k,_,j,T;const[o,i]=M("entity"),[l,c]=M("analysis"),[m,u]=M(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[p,h]=M("entity"),{entityLlmCalls:f,scenarioLlmCalls:y,totalLlmCalls:g}=ae(()=>{if(!a)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const E=[...a.entityCalls,...a.analysisCalls],$=E.filter(I=>I.object_type==="entity"||hi.includes(I.prompt_type)),R=E.filter(I=>I.object_type!=="entity"&&!hi.includes(I.prompt_type));return $.sort((I,W)=>W.created_at-I.created_at),R.sort((I,W)=>W.created_at-I.created_at),{entityLlmCalls:$,scenarioLlmCalls:R,totalLlmCalls:E.length}},[a]),x=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(v=e==null?void 0:e.metadata)==null?void 0:v.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(C=t==null?void 0:t.metadata)==null?void 0:C.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(N=(P=e==null?void 0:e.metadata)==null?void 0:P.isolatedDataStructure)==null?void 0:N.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(S=t==null?void 0:t.metadata)==null?void 0:S.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(k=e==null?void 0:e.metadata)==null?void 0:k.importedExports,"External Dependencies":(_=e==null?void 0:e.metadata)==null?void 0:_.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(j=t==null?void 0:t.metadata)==null?void 0:j.scenariosDataStructure,description:"Structure template used across all scenarios"}],b=x.filter(E=>E.data!==void 0&&E.data!==null).length;let w=null;if(o==="entity"){const E=x.find($=>$.id===l);E&&E.data!==void 0&&E.data!==null&&(w={title:E.title,description:E.description,data:E.data})}else if(o==="scenarios"&&m){const E=r.find($=>($.id||$.name)===m.scenarioId);E&&(w={title:E.name,description:E.description||"Scenario data and configuration",data:E.metadata})}return d("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:d("div",{className:"flex border-b border-gray-200 relative",children:[n(Hs,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(Hs,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(Hs,{label:"LLM Calls",count:g,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((T=t==null?void 0:t.metadata)==null?void 0:T.analyzerVersion)&&d("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?d("div",{className:"flex-1 min-h-0",children:[d("div",{className:"flex gap-4 mb-4",children:[d("button",{onClick:()=>h("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${p==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),d("button",{onClick:()=>h("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${p==="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:p==="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(E=>n(pi,{call:E},E.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(E=>n(pi,{call:E},E.id))})]}):d("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:o==="entity"?d(de,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),b===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:x.map(E=>{const $=E.data!==void 0&&E.data!==null;return n(mi,{label:E.title,isActive:l===E.id,onClick:()=>c(E.id),disabled:!$},E.id)})})]}):d(de,{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(E=>{const $=E.id||E.name,R=(m==null?void 0:m.scenarioId)===$;return n(mi,{label:E.name,isActive:R,onClick:()=>u({scenarioId:$})},$)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:w?n(iw,{title:w.title,description:w.description,data:w.data}):o==="scenarios"&&r.length===0?n(fi,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:s}):o==="entity"?n(fi,{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 fi({title:e,description:t,onAnalyze:r}){return d("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[n("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),n("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:t}),r&&n("button",{onClick:r,className:"h-[54px] w-[183px] bg-[#005c75] text-white text-base font-medium rounded-lg border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]})}function iw({title:e,description:t,data:r}){const[s,a]=M(!0);return d(de,{children:[d("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[n("h3",{className:"text-base font-semibold text-black m-0",children:e}),n("p",{className:"text-sm text-[#646464] mt-1 m-0",children:t})]}),d("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[d("div",{className:"flex gap-2",children:[n("button",{onClick:()=>a(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),n("button",{onClick:()=>a(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),n(jt,{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(aw,{data:r,defaultExpanded:s,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function lw({entity:e,analysis:t,scenarios:r,onAnalyze:s}){const a=Fe();return ne(()=>{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(ow,{entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a.data})})}const cw={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},dw={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},uw=2e3,mw=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 pw({entity:e,entityCode:t}){const r=Hr(),s=ve(null);return ne(()=>{const a=r.hash;if(!a||!s.current)return;const o=a.match(/^#L(\d+)$/);if(!o)return;const i=parseInt(o[1],10);setTimeout(()=>{if(!s.current)return;const l=s.current.querySelector(`[data-line-number="${i}"]`);if(l&&l instanceof HTMLElement){l.scrollIntoView({behavior:"smooth",block:"center"});const c=l.style.backgroundColor;l.style.backgroundColor="rgba(255, 255, 0, 0.2)",setTimeout(()=>{l.style.backgroundColor=c},2e3)}},300)},[r.hash,t]),n("div",{ref:s,className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:d("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[d("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),n("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e==null?void 0:e.filePath})]}),t&&n(jt,{content:t,label:"Copy Code",duration:uw,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(Zd,{language:mw(e==null?void 0:e.filePath),style:Xd,showLineNumbers:!0,customStyle:cw,lineNumberStyle:dw,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 hw=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function fw({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 gw({params:e,request:t,context:r}){const{sha:s}=e;if(!s)throw new Response("Entity SHA is required",{status:400});const o=new URL(t.url).searchParams.get("from"),l=(e["*"]||"").split("/").filter(Boolean),c=l[0]||"scenarios",m=l[1]||null,u=l[2]||null,p=r.analysisQueue,h=p?p.getState():{paused:!1,jobs:[]},[f,y,g,x]=await Promise.all([dn(s),Ie(),_n(),ap(he()||process.cwd())]),b=f?await es(f):null,w=f?await dl(f.sha):null;let v={importedEntities:[],importingEntities:[]},C=null,P=[];f&&(v=await ul(f),C=await ml(f),P=await hl(f));const N=!!(f&&P.length>0&&P[0].sha!==f.sha),S=P.length>0?P[0].sha:null,k=!!(P.length>0&&P[0].analyses&&P[0].analyses.length>0),_=f?await pl(f):!1;return Q({entity:f??void 0,analysis:b??void 0,currentEntityAnalysis:w??void 0,projectSlug:y,from:o,relatedEntities:v,entityCode:C??void 0,hasNewerVersion:N,newestEntitySha:S,newestVersionHasAnalysis:k,fileModifiedSinceEntity:_,history:P,tab:c,scenarioId:m,viewModeFromUrl:u,currentCommit:g,hasAnApiKey:x,queueState:h})}const yw=Je(function(){var te,be,Pe,Oe,He,It,lr,gn,mo,po,ho,fo,go,yo,xo;const t=qe(),a=(Fi()["*"]||"").split("/").filter(Boolean),o=a[0]||"scenarios",i=a[1]||null,l=a[2]||null,c=t.entity,m=t.analysis,u=t.currentEntityAnalysis,p=u||m,h=t.projectSlug;t.from;const f=t.relatedEntities,y=t.entityCode,g=t.hasNewerVersion,x=t.newestEntitySha,b=t.newestVersionHasAnalysis,w=t.fileModifiedSinceEntity,v=t.history,C=t.currentCommit,P=t.hasAnApiKey,N=t.queueState;(te=p==null?void 0:p.status)==null||te.errors;const S=(p==null?void 0:p.scenarios)||[],k=S.filter(ce=>{var Te;return!((Te=ce.metadata)!=null&&Te.sameAsDefault)}),_=S.filter(ce=>{var Te;return(Te=ce.metadata)==null?void 0:Te.sameAsDefault}),j=St(),T=ve(null);ne(()=>{T.current===null&&(T.current=window.history.length)},[]);const E=()=>{if(typeof window>"u")return;const ce=window.history.state;if(ce===null||(ce==null?void 0:ce.idx)===void 0||(ce==null?void 0:ce.idx)===0)j("/");else{const Te=window.history.length,nt=T.current;if(nt!==null&&Te>nt){const Be=Te-nt+1;j(-Be)}else j(-1)}},$=!!N.currentlyExecuting,R=o,I=(be=C==null?void 0:C.metadata)==null?void 0:be.currentRun,W=!!(I!=null&&I.createdAt)&&!(I!=null&&I.analysisCompletedAt),Y=!!(c!=null&&c.sha&&((Pe=I==null?void 0:I.currentEntityShas)!=null&&Pe.includes(c.sha))),U=!!(c!=null&&c.sha&&((He=(Oe=N.currentlyExecuting)==null?void 0:Oe.entityShas)!=null&&He.includes(c.sha))),B=!!(c!=null&&c.sha&&((It=N.jobs)!=null&&It.some(ce=>{var Te;return(Te=ce.entityShas)==null?void 0:Te.includes(c.sha)}))),H=Y||U||B,D=H&&((lr=p==null?void 0:p.status)==null?void 0:lr.finishedAt)!=null&&k.length>0&&p.entitySha!==(c==null?void 0:c.sha),A=ae(()=>{if(R!=="scenarios")return null;if(i){const ce=k.find(Te=>Te.id===i);if(ce)return ce}return k.length>0&&!H?k[0]:null},[R,i,k,H]),J=((po=(mo=(gn=A==null?void 0:A.metadata)==null?void 0:gn.executionResult)==null?void 0:mo.error)==null?void 0:po.message)||((go=(fo=(ho=p==null?void 0:p.status)==null?void 0:ho.errors)==null?void 0:fo[0])==null?void 0:go.message);xt({source:A?"scenario-page":"entity-page",entitySha:c==null?void 0:c.sha,scenarioId:A==null?void 0:A.id,analysisId:p==null?void 0:p.id,entityName:c==null?void 0:c.name,entityType:c==null?void 0:c.entityType,scenarioName:A==null?void 0:A.name,errorMessage:J});const[V,q]=M(()=>l&&l!=="edit"?l:(c==null?void 0:c.entityType)==="library"?"data":"screenshot");ne(()=>{l&&l!==V&&l!=="edit"&&q(l)},[l]);const X=l==="edit",[L,O]=M(!1),[z,G]=M(!1),[ee,re]=M(null),[ue,se]=M(!1),[pe,Ce]=M(!1),[_e,Ae]=M(null),[De,Le]=M(null),[Se,oe]=M(0),{interactiveServerUrl:xe,isStarting:ke,isLoading:et,showIframe:ge,iframeKey:Ye,onIframeLoad:We}=pn({analysisId:p==null?void 0:p.id,scenarioId:A==null?void 0:A.id,scenarioName:A==null?void 0:A.name,projectSlug:h,enabled:X&&!!A,refreshTrigger:Se}),[Ht,bs]=M(!1),[uo,Mn]=M(""),[Tt,Jt]=M(!1),[hn,Tn]=M(Date.now()),[$t,Vt]=M(!1),Qe=Fe(),mt=Fe(),Ve=Fe(),Ge=kt(),bt=N.jobs.some(ce=>{var Te;return(c==null?void 0:c.sha)&&((Te=ce.entityShas)==null?void 0:Te.includes(c.sha))||ce.type==="analysis"&&ce.commitSha===(C==null?void 0:C.sha)&&ce.entityShas&&ce.entityShas.length===0}),$n=H,In=((yo=c==null?void 0:c.metadata)==null?void 0:yo.defaultWidth)||((xo=p==null?void 0:p.metadata)==null?void 0:xo.defaultWidth)||1440,ws=Math.round(In*(900/1440));Qe.state==="submitting"||Qe.state,ae(()=>{var ce;return!!((ce=A==null?void 0:A.metadata)!=null&&ce.interactiveExamplePath)},[A]);const{isCompleted:Rn}=_t(h,Tt);ne(()=>{Qe.state==="idle"&&Qe.data&&(Qe.data.success?setTimeout(()=>{Tn(Date.now()),Ge.revalidate(),Jt(!1)},1500):Qe.data.error&&(Jt(!1),alert(`Recapture failed: ${Qe.data.error}`)))},[Qe.state,Qe.data,Ge]),ne(()=>{Tt&&Rn&&setTimeout(()=>{Tn(Date.now()),Ge.revalidate(),Jt(!1)},1500)},[Tt,Rn,Ge]),ne(()=>{mt.state==="idle"&&mt.data&&(mt.data.success?setTimeout(()=>{Tn(Date.now()),Ge.revalidate(),Jt(!1)},1500):mt.data.error&&(Jt(!1),alert(`Recapture failed: ${mt.data.error}`)))},[mt.state,mt.data,Ge]);const Dn=()=>{c&&(g&&x&&x!==c.sha?(j(`/entity/${x}/scenarios`),setTimeout(()=>{Ve.submit({entitySha:x,filePath:c.filePath||""},{method:"post",action:"/api/analyze"})},100)):Ve.submit({entitySha:c.sha,filePath:c.filePath||""},{method:"post",action:"/api/analyze"}))};ne(()=>{Ve.state==="idle"&&Ve.data&&(Ve.data.success?Ge.revalidate():Ve.data.error&&alert(`Analysis failed: ${Ve.data.error}`))},[Ve.state,Ve.data,c==null?void 0:c.sha,Ge]),ne(()=>{const ce=setTimeout(()=>{Ge.revalidate()},500);return()=>clearTimeout(ce)},[]),ne(()=>{if(W||$n){const ce=setInterval(()=>{Ge.revalidate()},3e3);return()=>clearInterval(ce)}},[W,$n,Ge]);const On=(ce,Te)=>ce==="scenarios"?`/entity/${c==null?void 0:c.sha}/scenarios`:`/entity/${c==null?void 0:c.sha}/${ce}`,Gt=(ce,Te)=>`/entity/${c==null?void 0:c.sha}/scenarios/${ce}/${Te}`,vs=ce=>{q(ce),A!=null&&A.id&&(ce==="interactive"?j(`/entity/${c==null?void 0:c.sha}/scenarios/${A.id}/fullscreen`,{replace:!0}):j(Gt(A.id,ce),{replace:!0}))},Ns=async ce=>{var Te,nt;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:ce,hasSelectedScenario:!!A,hasAnalysis:!!p}),!A||!p){const Be="Error: No scenario or analysis available";console.error("[EntityDetail]",Be),re(Be);return}O(!0),re(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:ce,scenarioId:A.id,scenarioName:A.name,currentData:A.data});try{const Be=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:ce,existingScenarios:p.scenarios,scenariosDataStructure:(Te=p.metadata)==null?void 0:Te.scenariosDataStructure,editingMockName:A.name,editingMockData:De||((nt=A.metadata)==null?void 0:nt.data)})}),wt=await Be.json();if(!Be.ok||!wt.success)throw new Error(wt.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",wt.data),Le(wt.data);const cr=(p.scenarios||[]).map(tt=>tt.id===A.id?{...tt,metadata:{...tt.metadata,data:wt.data}}:tt),Ln=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:p,scenarios:cr})}),it=await Ln.json();if(!Ln.ok||!it.success)throw console.error("[EntityDetail] Temp save failed:",it),new Error(it.error||"Failed to apply preview");if(re("Generating preview. Capturing screenshot..."),xe){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:xe});const tt=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:xe,scenarioId:A.id,projectId:p.projectId,viewportWidth:1440})}),Fn=await tt.json();!tt.ok||!Fn.success?(console.error("[EntityDetail] Direct capture failed:",Fn),re("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),re('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const tt=new FormData;tt.append("analysisId",p.id||""),tt.append("scenarioId",A.id||"");const Fn=await fetch("/api/recapture-scenario",{method:"POST",body:tt}),Es=await Fn.json();!Fn.ok||!Es.success?(console.warn("[EntityDetail] Recapture failed:",Es.error),re("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",Es.jobId),re('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}oe(tt=>tt+1),Ge.revalidate()}catch(Be){console.error("Error applying changes:",Be),re(`Error: ${Be instanceof Error?Be.message:String(Be)}`)}finally{O(!1)}},Cs=async(ce,Te)=>{var nt;if(!A||!p){re("Error: No scenario or analysis available");return}G(!0),re(null),console.log("[EntityDetail] Saving scenario to database",{description:ce,saveAsNew:Te});try{const Be=De||((nt=A.metadata)==null?void 0:nt.data);let wt;if(Te){const it={...A,id:`${A.name}-${Date.now()}`,name:`${A.name} (Copy)`,metadata:{...A.metadata,data:Be},description:ce||A.description};wt=[...p.scenarios||[],it]}else wt=(p.scenarios||[]).map(it=>it.id===A.id?{...it,metadata:{...it.metadata,data:Be},description:ce||it.description}:it);const cr=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:p,scenarios:wt})}),Ln=await cr.json();if(!cr.ok||!Ln.success)throw new Error(Ln.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),re(Te?"New scenario created successfully":"Scenario saved successfully"),Le(null),Ge.revalidate()}catch(Be){console.error("Error saving scenario:",Be),re(`Error: ${Be instanceof Error?Be.message:String(Be)}`)}finally{G(!1)}},Ss=()=>{A!=null&&A.id&&(c!=null&&c.sha)&&j(`/entity/${c.sha}/scenarios/${A.id}/dev`)},Kt=async()=>{var ce;if(!(A!=null&&A.id)){Ae("Cannot delete scenario without ID");return}se(!0),Ae(null);try{const Te=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:A.id,screenshotPaths:((ce=A.metadata)==null?void 0:ce.screenshotPaths)||[]})}),nt=await Te.json();if(!Te.ok||!nt.success)throw new Error(nt.error||"Failed to delete scenario");j(`/entity/${c==null?void 0:c.sha}/scenarios`)}catch(Te){console.error("[EntityDetail] Error deleting scenario:",Te),Ae(Te instanceof Error?Te.message:"Failed to delete scenario"),Ce(!1)}finally{se(!1)}},fn=p&&c&&p.entitySha!==c.sha,ks=c?Qb(c):!1;return n(ds,{children:d("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:d("div",{className:"flex items-end h-full px-6 gap-6",children:[d("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:E,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:c==null?void 0:c.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:c==null?void 0:c.filePath,children:c==null?void 0:c.filePath})]}),n("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:k.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(ce=>n(me,{to:On(ce.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${R===ce.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:R===ce.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:d("span",{className:"flex items-center gap-2",children:[ce.label,ce.count!==void 0&&ce.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${R===ce.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:ce.count})]})},ce.id))})]})}),(g||fn&&!u||w&&ks)&&!H&&!bt&&n("div",{className:"border-b border-[#FEE585] px-6 py-3 flex items-center justify-center shrink-0",style:{backgroundColor:"#FEE585"},children:d("div",{className:"flex items-center gap-3",children:[n("svg",{className:"w-4 h-4",style:{color:"#714A25"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),n("span",{className:"text-sm font-semibold",style:{color:"#714A25"},children:fn&&!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.":fn?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),g&&x&&b?n(me,{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:ce=>{ce.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:ce=>{ce.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:Dn,disabled:Ve.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:ce=>{Ve.state==="idle"&&(ce.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:ce=>{Ve.state==="idle"&&(ce.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),d("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[R==="scenarios"&&d(de,{children:[X&&A?n(Xb,{scenario:A,entitySha:(c==null?void 0:c.sha)||"",onApply:Ns,onSave:Cs,onEditMockData:Ss,onDelete:Kt,isApplying:L,isSaving:z,saveMessage:ee,showDeleteConfirm:pe,onShowDeleteConfirm:Ce,isDeleting:ue,deleteError:_e}):n(Zb,{scenarios:k,hiddenScenarios:_,analysis:p,selectedScenario:A,entitySha:(c==null?void 0:c.sha)||"",cacheBuster:hn,activeTab:R,entityType:c==null?void 0:c.entityType,entity:c,queueState:N,processIsRunning:$,isEntityAnalyzing:H,areScenariosStale:D,viewMode:V,setViewMode:vs,isBreakdownView:i==="breakdown"}),i==="breakdown"?n(tw,{analysis:p??null,entitySha:(c==null?void 0:c.sha)||""}):X&&A?n(us,{scenarioId:A.id||A.name,scenarioName:A.name,iframeUrl:xe,isStarting:ke,isLoading:et,showIframe:ge,iframeKey:Ye,onIframeLoad:We,projectSlug:h,defaultWidth:1440,defaultHeight:900}):d("div",{className:"flex flex-col flex-1 min-h-0",children:[A&&d("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:A.name}),d("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[In," × ",ws]})]}),d("div",{className:"flex items-center gap-2",children:[n(me,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${A.id}/edit`,className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors no-underline flex items-center",title:"Edit Scenario Data",children:"Edit Scenario"}),d("button",{className:"px-3 py-1.5 bg-[#022A35] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#011a21] transition-colors flex items-center gap-1.5",onClick:()=>{alert("Download functionality coming soon")},title:"Download",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"})}),"Download"]}),d(me,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${A.id}/dev`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Dev Mode - Live preview with data editor and code sync",children:[d("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n("polyline",{points:"16 18 22 12 16 6"}),n("polyline",{points:"8 6 2 12 8 18"})]}),"Dev Mode"]}),d(me,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${A.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(vc,{selectedScenario:A,analysis:p,entity:c,viewMode:V,cacheBuster:hn,hasScenarios:k.length>0,isAnalyzing:$n,projectSlug:h,hasAnApiKey:P,processIsRunning:$,queueState:N})]})]}),R==="related"&&n(sw,{relatedEntities:f}),R==="data"&&n(lw,{entity:c,analysis:p,scenarios:k,onAnalyze:Dn}),R==="code"&&n(pw,{entity:c,entityCode:y}),R==="history"&&n(nw,{entity:c,history:v})]}),$t&&h&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>Vt(!1),children:d("div",{className:"bg-white rounded-xl max-w-[1200px] w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:ce=>ce.stopPropagation(),children:[d("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>Vt(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(Ft,{projectSlug:h,onClose:()=>Vt(!1)})})]})})]})})}),xw=Object.freeze(Object.defineProperty({__proto__:null,default:yw,loader:gw,meta:hw,shouldRevalidate:fw},Symbol.toStringTag,{value:"Module"}));async function bw(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 ze();const i=he();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=Z.join(i,".codeyam","config.json"),c=JSON.parse(await Ne.readFile(l,"utf8")),{projectSlug:m,branchId:u}=c;if(!m||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${m}, Branch: ${u}`);const p=rs(m);try{await Ne.writeFile(p,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:h,branch:f}=await Re(m);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const y=await st({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(w=>w.filePath).filter(w=>!!w))],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 tp(h,f,g);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await Lt({commitSha:x.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:w=>{if(!w)return;const v=w.currentRun;if(v&&v.id&&v.archivedAt)return;v&&(v.analysesCompleted&&v.analysesCompleted>0||v.capturesCompleted&&v.capturesCompleted>0)&&pp(w)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:b}=o.enqueue({type:"analysis",commitSha:x.sha,projectSlug:m,filePaths:g,entityShas:t,entityNames:y.map(w=>w.name),...s?{context:s}:{},...a?{scenarioCount:a}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${b} for ${t.length} entities`),{jobId:b}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function ww({request:e,context:t}){if(e.method!=="POST")return Q({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Mt()),!r)return Q({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("entitySha"),o=s.get("entityShas"),i=s.get("filePath"),l=s.get("context"),c=s.get("scenarioCount");let m;if(o)m=o.split(",").filter(Boolean);else if(a)m=[a];else return Q({error:"Missing required field: entitySha or entityShas"},{status:400});if(m.length===0)return Q({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${m.length} entity(ies)`);const u=await st({shas:m}),h=[...new Set(u.map(y=>y.filePath).filter(y=>!!y))].length,{jobId:f}=await bw({entityShas:m,filePaths:i?[i]:void 0,context:l||void 0,scenarioCount:c?parseInt(c,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),Q({success:!0,message:`Analysis queued for ${m.length} entity(ies)`,entityCount:m.length,fileCount:h,jobId:f})}catch(s){return console.error("[API] Error starting analysis:",s),Q({error:"Failed to start analysis",details:s.message},{status:500})}}const vw=Object.freeze(Object.defineProperty({__proto__:null,action:ww},Symbol.toStringTag,{value:"Module"}));function Nw(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:d("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function Nc(e){if(!e)return"Never";const t=new Date(e),r=new Date;if(t.getDate()===r.getDate()&&t.getMonth()===r.getMonth()&&t.getFullYear()===r.getFullYear()){const a=t.getHours(),o=t.getMinutes(),i=a>=12?"pm":"am",l=a%12||12,c=o.toString().padStart(2,"0");return`Today, ${l}:${c} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function lt(e,t=[],r=!1){var u,p;if(t.some(h=>{var f,y;return!!((f=h.entityShas)!=null&&f.includes(e.sha)||(y=h.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(h=>h.screenshotFinishedAt||h.finishedAt))||a.entitySha!==e.sha)return"not-analyzed";const i=a.createdAt?new Date(a.createdAt).getTime():0,l=(p=e.metadata)!=null&&p.editedAt?new Date(e.metadata.editedAt).getTime():0,c=a.scenarios||[],m=c.some(h=>{var f,y,g;return((y=(f=h.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||((g=h.metadata)==null?void 0:g.executionResult)});return i>=l?c.length>0&&m?c.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":c.length>0?"incomplete":"not-analyzed":"out-of-date"}const Cw=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function Sw({request:e,context:t}){try{const r=t.analysisQueue,s=r?r.getState():{paused:!1,jobs:[]},a=await mn();return Q({entities:a||[],queueState:s})}catch(r){return console.error("Failed to load simulations:",r),Q({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const kw=Je(function(){const t=qe(),r=t.entities,s=t.queueState;xt({source:"simulations-page"});const[a,o]=M(""),[i,l]=M("visual"),c=ae(()=>{const g=[];return r.forEach(x=>{var w;const b=(w=x.analyses)==null?void 0:w[0];if(b!=null&&b.scenarios){const v=b.scenarios.filter(C=>{var P;return!((P=C.metadata)!=null&&P.sameAsDefault)}).map(C=>{var T,E,$,R,I;const P=(E=(T=C.metadata)==null?void 0:T.screenshotPaths)==null?void 0:E[0],N=($=C.metadata)==null?void 0:$.noScreenshotSaved,S=P&&!N,k=(I=(R=b.status)==null?void 0:R.scenarios)==null?void 0:I.find(W=>W.name===C.name),_=k&&k.screenshotStartedAt&&!k.screenshotFinishedAt;let j;return S?j="completed":_?j="capturing":j="error",{scenarioName:C.name,scenarioDescription:C.description||"",screenshotPath:P||"",scenarioId:C.id,state:j}}).filter(C=>C.state==="completed"||C.state==="capturing");v.length>0&&g.push({entity:x,screenshots:v,createdAt:b.createdAt||""})}}),g.sort((x,b)=>new Date(b.createdAt).getTime()-new Date(x.createdAt).getTime()),g},[r]),m=ae(()=>r.filter(g=>{var w,v;const x=(w=g.analyses)==null?void 0:w[0];return!((v=x==null?void 0:x.scenarios)==null?void 0:v.some(C=>{var P,N;return(N=(P=C.metadata)==null?void 0:P.screenshotPaths)==null?void 0:N[0]}))}),[r]),u=ae(()=>c.filter(({entity:g})=>{const x=!a||g.name.toLowerCase().includes(a.toLowerCase()),b=i==="all"||g.entityType===i;return x&&b}),[c,a,i]),p=ae(()=>m.filter(g=>{const x=!a||g.name.toLowerCase().includes(a.toLowerCase()),b=i==="all"||g.entityType===i;return x&&b}),[m,a,i]),h=ie(g=>{o(g.target.value)},[]),f=ie(g=>{l(g.target.value)},[]),y=c.length>0;return n("div",{className:"bg-[#F8F7F6] min-h-screen overflow-y-auto",children:d("div",{className:"px-20 py-12",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!y&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:d("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",n("strong",{children:"Start by analyzing your first component below."})]})}),d("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),d("div",{className:"flex gap-3",children:[d("div",{className:"relative",children:[d("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 pr-8 text-[13px] h-[39px] cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:i,onChange:f,children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(dt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"flex-1 relative",children:[n(nr,{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:h})]})]})]}),y&&u.length>0&&n("div",{className:"mb-2",children:d("div",{className:"flex items-center py-3",children:[d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:u.length})," ",u.length===1?"entity":"entities"]}),d("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:d("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:u.reduce((g,{screenshots:x})=>g+x.length,0)})," ","scenarios"]})]})}),d("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(de,{children:u.map(({entity:g,screenshots:x})=>n(Ew,{entity:g,screenshots:x,queueJobs:(s==null?void 0:s.jobs)||[]},g.sha))})),!y&&(p.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."}):p.map(g=>n(_w,{entity:g},g.sha)))]})]})})});function Ew({entity:e,screenshots:t,queueJobs:r}){var f,y,g;const s=St(),a=Fe(),[o,i]=M(!1),l=t.length||(((g=(y=(f=e.analyses)==null?void 0:f[0])==null?void 0:y.scenarios)==null?void 0:g.length)??0),c=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"})};ne(()=>{a.state==="idle"&&o&&i(!1)},[a.state,o]);const u=lt(e,r),p=Nw(u),h=u==="out-of-date";return n("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:d("div",{className:"flex flex-col",children:[d("div",{className:"flex items-center px-[15px] py-[15px]",children:[n("div",{className:"flex-shrink-0",children:n(at,{type:e.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[d("div",{className:"flex items-center gap-[5px]",children:[d(me,{to:`/entity/${e.sha}`,className:"hover:underline cursor-pointer",title:e.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:[e.name," (",l,")"]}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:p.bgColor,color:p.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:p.text})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),d("div",{className:"flex-shrink-0 flex items-center gap-2",children:[h&&n(de,{children:o||a.state!=="idle"?d("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=>d("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>c(x.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:x.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:x.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:b=>{x.state==="completed"&&(b.currentTarget.style.borderColor="#005C75",b.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:b=>{b.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",b.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(Ze,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(Za,{size:"medium"}):null})}),d("div",{className:"relative group",children:[n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.scenarioName}),n("div",{className:"fixed hidden group-hover:block pointer-events-none",style:{zIndex:1e4,transform:"translateY(8px)"},children:d("div",{className:"bg-gray-100 text-gray-800 text-xs rounded-lg px-3 py-2 shadow-lg max-w-xs border border-gray-200",children:[x.scenarioName,x.scenarioDescription&&d(de,{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 _w({entity:e}){const t=Fe(),[r,s]=M(!1),a=()=>{s(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return ne(()=>{t.state==="idle"&&r&&s(!1)},[t.state,r]),n("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:a,children:d("div",{className:"px-5 py-4 flex items-center",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(at,{type:e.entityType}),d("div",{className:"min-w-0",children:[d("div",{className:"flex items-center gap-3 mb-0.5",children:[n(me,{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:Nc(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?d("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(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 Aw=Object.freeze(Object.defineProperty({__proto__:null,default:kw,loader:Sw,meta:Cw},Symbol.toStringTag,{value:"Module"}));function Pw({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"})}
|
|
361
|
-
|
|
362
|
-
`)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",c),clearInterval(m);try{a.close()}catch{}}},c=u=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
|
|
363
|
-
|
|
364
|
-
`))}catch{l()}};r.on("change",c);const m=setInterval(()=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
365
|
-
|
|
366
|
-
`))}catch{l()}},3e4);e.signal.addEventListener("abort",l)}});return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const jw=Object.freeze(Object.defineProperty({__proto__:null,loader:Pw},Symbol.toStringTag,{value:"Module"}));function Mw(){return new Response(JSON.stringify({status:"ok",version:Ia,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const Tw=Object.freeze(Object.defineProperty({__proto__:null,loader:Mw},Symbol.toStringTag,{value:"Module"}));function to(e){const t=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,r=e.match(t);if(!r)return{frontmatter:{},body:e};const s=r[1],a=r[2],o={},i=s.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/),l=s.match(/paths:\s*\[([^\]]*)\]/);i&&i[1].trim()?o.paths=i[1].split(`
|
|
367
|
-
`).filter(m=>m.trim().startsWith("-")).map(m=>m.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean):l&&(o.paths=l[1].split(",").map(m=>m.replace(/['"]/g,"").trim()).filter(Boolean));const c=s.match(/^category:\s*(.+)$/m);return c&&(o.category=c[1].replace(/['"]/g,"").trim()),{frontmatter:o,body:a}}async function ys(e,t=""){const r=[];try{const s=await Ne.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){const i=await ys(Z.join(e,a.name),o);r.push(...i)}else a.isFile()&&a.name.endsWith(".md")&&r.push(o)}}catch{}return r}async function ir(e){const t=await ys(e),r=[];for(const s of t){const a=Z.join(e,s);try{const o=await Ne.readFile(a,"utf-8"),{frontmatter:i,body:l}=to(o);r.push({filePath:s,absolutePath:a,frontmatter:i,body:l})}catch{}}return r}function Cc(e){const t=Z.posix.dirname(e.filePath);return!t||t==="."?null:`${t}/**`}function Sc(e,t){if(t.frontmatter.paths&&t.frontmatter.paths.length>0)return t.frontmatter.paths.some(s=>Zs(e,s,{matchBase:!0}));const r=Cc(t);return r?Zs(e,r,{matchBase:!0}):!1}function $w(e,t){return(!e.frontmatter.paths||e.frontmatter.paths.length===0)&&!Cc(e)?[]:t.filter(r=>Sc(r,e))}const Iw=new Set(["node_modules",".git","dist",".codeyam",".claude","build","coverage"]);async function no(e){const t=[];async function r(s,a){try{const o=await we.readdir(s,{withFileTypes:!0});for(const i of o){const l=F.join(s,i.name),c=a?`${a}/${i.name}`:i.name;i.isDirectory()&&Iw.has(i.name)||(i.isDirectory()?await r(l,c):i.isFile()&&t.push(c))}}catch{}}return await r(e,""),t}const Rw="codeyam-rule-state.json",Js=1;function kc(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return rr.createHash("sha256").update(t).digest("hex")}function Ec(e){return Z.join(e,".claude",Rw)}async function _c(e){const t=Ec(e);try{const r=await Ne.readFile(t,"utf-8"),s=JSON.parse(r);return s.version!==Js?(console.warn(`[ruleState] Unknown version ${s.version}, using empty state`),{version:Js,rules:{}}):s}catch{return{version:Js,rules:{}}}}async function Ac(e,t){const r=Ec(e),s=Z.dirname(r);await Ne.mkdir(s,{recursive:!0}),await Ne.writeFile(r,JSON.stringify(t,null,2)+`
|
|
368
|
-
`,"utf-8")}async function ro(e,t){const r=await _c(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 Ne.readFile(a.absolutePath,"utf-8"),i=kc(o),l=r.rules[a.filePath];l?l.contentHash!==i&&(r.rules[a.filePath]={...l,contentHash:i,reviewed:!1}):r.rules[a.filePath]={contentHash:i,reviewed:!1}}return await Ac(e,r),r}async function gi(e,t,r,s){const a=await _c(e);if(r){const o=Z.join(e,".claude","rules"),i=Z.join(o,t),l=await Ne.readFile(i,"utf-8"),c=kc(l);a.rules[t]?(a.rules[t].reviewed=!0,a.rules[t].contentHash=c):a.rules[t]={contentHash:c,reviewed:!0}}else a.rules[t]&&(a.rules[t].reviewed=!1);await Ac(e,a)}function so(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function Pc(e,t=""){const r=[],s=await Ne.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;a.isDirectory()?r.push(...await Pc(Z.join(e,a.name),o)):a.name.endsWith(".md")&&r.push(o)}return r}function Br(e){if(!e||e==="(diff not available)")return!1;const t=e.split(`
|
|
369
|
-
`).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 Dw({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=Z.join(t,".claude","rules");if(s==="recent-changes")return Lw(t,a);if(s==="reviewed-status")return zw(t,a);if(s==="audit")return Bw(t,a);if(s==="source-files")return Yw(t);if(s==="rule-coverage")return Uw(t,a);if(s==="rule-diff"){const o=r.searchParams.get("filePath");return o?Fw(t,o):Response.json({error:"Missing required parameter: filePath"},{status:400})}if(s==="rules-for-path"){const o=r.searchParams.get("path");return o?Ww(a,o):Response.json({error:"Missing required parameter: path"},{status:400})}try{const o=await ys(a),i=[];for(const u of o){const p=Z.join(a,u);try{const h=await Ne.readFile(p,"utf-8"),f=await Ne.stat(p),{frontmatter:y,body:g}=to(h);i.push({filePath:u,content:h,frontmatter:y,body:g,lastModified:f.mtime.toISOString()})}catch{}}i.sort((u,p)=>new Date(p.lastModified).getTime()-new Date(u.lastModified).getTime());let l=i.length>0;if(!l)try{await Ne.access(Z.join(t,".claude","codeyam-rule-state.json")),l=!0}catch{}const c=await ir(a),m={};if(c.length>0){const u=await ro(t,c);for(const p of c)m[p.filePath]=so(u,p.filePath)}return Response.json({memories:i,memoryInitialized:l,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 Ow(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(`
|
|
370
|
-
`).filter(Boolean)){const o=a.substring(0,2);let i=a.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const l=o[0],c=o[1];let m=[i];if(i.endsWith("/")&&l==="?"){const u=Z.join(e,i);try{m=(await Pc(u)).map(h=>i+h)}catch{continue}}for(const u of m){if(u.endsWith("/"))continue;const p=u.replace(".claude/rules/","");let h="modified";l==="A"||l==="?"?h="added":l==="D"||c==="D"?h="deleted":(l==="M"||c==="M")&&(h="modified");let f="";try{if(h==="deleted")f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(h==="added"&&l==="?"){const y=`${e}/${u}`;try{const g=await Ne.readFile(y,"utf-8");f=`diff --git a/${u} b/${u}
|
|
371
|
-
new file mode 100644
|
|
372
|
-
--- /dev/null
|
|
373
|
-
+++ b/${u}
|
|
374
|
-
@@ -0,0 +1,${g.split(`
|
|
375
|
-
`).length} @@
|
|
376
|
-
${g.split(`
|
|
377
|
-
`).map(x=>"+"+x).join(`
|
|
378
|
-
`)}`}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)+`
|
|
379
|
-
... (truncated)`)}catch{f="(diff not available)"}h==="modified"&&Br(f)||r.push({filePath:p,changeType:h,diff:f})}}}catch{}return r}async function Lw(e,t){try{const{execSync:r}=await import("child_process"),s=[],a=await ir(t),o={};if(a.length>0){const u=await ro(e,a);for(const p of a)o[p.filePath]=so(u,p.filePath)}const l=(await Ow(e,r)).filter(u=>!o[u.filePath]);l.length>0&&s.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:l});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(`
|
|
380
|
-
`).filter(Boolean).slice(0,20);for(const u of m){const[p,h,...f]=u.split("|"),y=f.join("|");if(!p||!h)continue;const g=r(`git diff-tree --no-commit-id --name-status -r ${p} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),x=[];for(const b of g.split(`
|
|
381
|
-
`).filter(Boolean)){const[w,v]=b.split(" ");if(!v||!v.startsWith(".claude/rules/"))continue;const C=v.replace(".claude/rules/","");let P="modified";if(w==="A"?P="added":w==="D"&&(P="deleted"),o[C])continue;let N="";try{N=r(`git show ${p} --format="" -- "${v}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),N.length>5e3&&(N=N.substring(0,5e3)+`
|
|
382
|
-
... (truncated)`)}catch{N="(diff not available)"}P==="modified"&&Br(N)||x.push({filePath:C,changeType:P,diff:N})}x.length>0&&s.push({commitHash:p.substring(0,8),date:h,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 Fw(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(Br(i))return Response.json({diff:null});const g=i.length>5e3?i.substring(0,5e3)+`
|
|
383
|
-
... (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=Z.join(e,s);try{const x=await Ne.readFile(g,"utf-8"),b=`diff --git a/${s} b/${s}
|
|
384
|
-
new file mode 100644
|
|
385
|
-
--- /dev/null
|
|
386
|
-
+++ b/${s}
|
|
387
|
-
@@ -0,0 +1,${x.split(`
|
|
388
|
-
`).length} @@
|
|
389
|
-
${x.split(`
|
|
390
|
-
`).map(w=>"+"+w).join(`
|
|
391
|
-
`)}`;return Response.json({diff:{diff:b.length>5e3?b.substring(0,5e3)+`
|
|
392
|
-
... (truncated)`:b,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,p,...h]=m.split("|"),f=h.join("|");if(!u||!p)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()?Br(y)?Response.json({diff:null}):(y.length>5e3&&(y=y.substring(0,5e3)+`
|
|
393
|
-
... (truncated)`),Response.json({diff:{diff:y,commitMessage:f,date:p,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 zw(e,t){try{const r=await ir(t),s={};if(r.length>0){const a=await ro(e,r);for(const o of r)s[o.filePath]=so(a,o.filePath)}return Response.json({reviewedStatus:s})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function Bw(e,t){try{const r=await ir(t),s=await no(e),a=[];for(const o of s){const i=r.filter(l=>Sc(o,l));if(i.length>0){const l=i.reduce((c,m)=>c+m.body.length,0);a.push({filePath:o,matchingRules:i.map(c=>({filePath:c.filePath,patterns:c.frontmatter.paths||[],bodyLength:c.body.length})),totalTextLength:l})}}return a.sort((o,i)=>i.totalTextLength-o.totalTextLength),Response.json({topPaths:a,totalFilesWithCoverage:a.length,allSourceFiles:s})}catch(r){return console.error("[API] Error getting audit data:",r),Response.json({error:"Failed to get audit data",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Yw(e){try{const t=await no(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 Uw(e,t){try{const[r,s]=await Promise.all([ir(t),no(e)]),a={};for(const o of r)a[o.filePath]=$w(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 Ww(e,t){try{const r=await ys(e),s=[];for(const o of r){const i=Z.join(e,o);try{const l=await Ne.readFile(i,"utf-8"),c=await Ne.stat(i),{frontmatter:m,body:u}=to(l);m.paths&&m.paths.some(p=>Zs(t,p,{matchBase:!0}))&&s.push({filePath:o,content:l,frontmatter:m,body:u,lastModified:c.mtime.toISOString()})}catch{}}const a=s.reduce((o,i)=>o+i.body.length,0);return Response.json({rules:s,totalTextLength:a})}catch(r){return console.error("[API] Error getting rules for path:",r),Response.json({error:"Failed to get rules for path",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Hw({request:e}){const t=he();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=Z.join(t,".claude","rules");try{const s=await e.json(),{action:a,filePath:o,content:i,lastModified:l}=s;if(!o)return Response.json({error:"Missing required field: filePath"},{status:400});if(a==="mark-reviewed")return await gi(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 gi(t,o,!1),console.log(`[API] Rule marked as unreviewed: ${o}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:o});const c=Z.normalize(o);if(c.includes("..")||Z.isAbsolute(c))return Response.json({error:"Invalid file path"},{status:400});const m=Z.join(r,c);switch(a){case"create":case"update":return i?(await Ne.mkdir(Z.dirname(m),{recursive:!0}),await Ne.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 Ne.unlink(m),console.log(`[API] Memory deleted: ${o}`);const u=Z.dirname(m);try{(await Ne.readdir(u)).length===0&&u!==r&&await Ne.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 Jw=Object.freeze(Object.defineProperty({__proto__:null,action:Hw,loader:Dw},Symbol.toStringTag,{value:"Module"}));async function Vw({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await Mt()),!r)return Q({error:"Queue not initialized"},{status:500});const s=new URL(e.url),a=s.searchParams.get("queryType");if(!a)return Q({error:"Missing queryType parameter for GET request"},{status:400});if(a==="job"){const i=s.searchParams.get("jobId");if(!i)return Q({error:"Missing jobId parameter for job query"},{status:400});const l=r.getState();if(((o=l.currentlyExecuting)==null?void 0:o.id)===i)return Q({jobId:i,status:"running",job:l.currentlyExecuting});const c=l.jobs.find(u=>u.id===i);if(c){const u=l.jobs.indexOf(c);return Q({jobId:i,status:"queued",position:u,job:c})}const m=r.getJobResult(i);return m?Q({jobId:i,status:m.status==="error"?"failed":"completed",error:m.error}):Q({jobId:i,status:"completed"})}if(a==="full"){const i=r.getState(),l=await Promise.all(i.jobs.map(async m=>{const u=[];if(m.entityShas&&m.entityShas.length>0){const p=m.entityShas.map(f=>dn(f)),h=await Promise.all(p);u.push(...h.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 c;if(i.currentlyExecuting){const m=i.currentlyExecuting,u=[];if(m.entityShas&&m.entityShas.length>0){const p=m.entityShas.map(f=>dn(f)),h=await Promise.all(p);u.push(...h.filter(f=>f!==null))}c={id:m.id,type:m.type,commitSha:m.commitSha,projectSlug:m.projectSlug,queuedAt:m.queuedAt,entities:u,filePaths:m.filePaths}}return Q({state:{...i,jobsWithEntities:l,currentlyExecutingWithEntities:c}})}return Q({error:"Unknown queryType"},{status:400})}async function Gw({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 Mt(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),Q({error:"Queue not initialized"},{status:500});const s=await e.json(),{action:a,...o}=s;if(console.log("[Queue API] Action:",a,"Params:",Object.keys(o)),a==="enqueue"){const{jobId:i,completion:l}=r.enqueue(o);return l.catch(c=>{console.error(`[Queue API] Job ${i} failed:`,c)}),Q({jobId:i,status:"queued"})}if(a==="resume")return r.resume(),Q({status:"resumed"});if(a==="pause")return r.pause(),Q({status:"paused"});if(a==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?Q({status:"removed",jobId:i}):Q({error:"Job not found in queue"},{status:404}):Q({error:"Missing jobId parameter"},{status:400})}if(a==="clear"){const i=r.clearQueue();return Q({status:"cleared",count:i})}if(a==="reorder"){const{jobId:i,direction:l}=o;return!i||!l?Q({error:"Missing jobId or direction parameter"},{status:400}):l!=="up"&&l!=="down"?Q({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,l)?Q({status:"reordered",jobId:i,direction:l}):Q({error:"Could not reorder job (not found or at boundary)"},{status:400})}return Q({error:"Unknown action"},{status:400})}const Kw=Object.freeze(Object.defineProperty({__proto__:null,action:Gw,loader:Vw},Symbol.toStringTag,{value:"Module"})),qw=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],Qw=Je(function(){return Fe(),n(ds,{children:d("div",{className:"h-screen bg-[#F8F7F6] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:d("div",{className:"flex items-center h-full px-6 gap-6",children:[d("div",{className:"flex items-center gap-3 min-w-0",children:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[d("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),d("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:d("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[d("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded bg-[#343434] text-[#efefef] font-semibold h-8",children:["Scenarios",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),d("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),d("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(vc,{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})]})]})})}),Zw=Object.freeze(Object.defineProperty({__proto__:null,default:Qw,meta:qw},Symbol.toStringTag,{value:"Module"})),Xw=()=>[{title:"Settings - CodeYam"},{name:"description",content:"Configure project settings"}];async function ev({request:e}){var t,r;try{const s=await ts();if(!s)return Q({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Project configuration not found"});let a=!1;try{const c=await Ie();if(c){const{project:m}=await Re(c);a=((r=(t=m.metadata)==null?void 0:t.labs)==null?void 0:r.simulations)===!0}}catch{}const o=he()||process.cwd(),i=await ns(o),l=Cl(s.projectSlug);return Q({config:s,secrets:{GROQ_API_KEY:i.GROQ_API_KEY||"",ANTHROPIC_API_KEY:i.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:i.OPENAI_API_KEY||""},versionInfo:l,simulationsEnabled:a,error:null})}catch(s){return console.error("Failed to load config:",s),Q({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Failed to load configuration"})}}function tv(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 nv({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),s=t.get("startCommands"),a=t.get("groqApiKey"),o=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),l=t.get("pathsToIgnore"),c=t.get("memorySettings");let m;if(r)try{m=JSON.parse(r)}catch{return Q({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let u;if(s)try{u=JSON.parse(s)}catch{return Q({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let p;l&&(p=l.split(",").map(x=>x.trim()).map(x=>x.startsWith('"')&&x.endsWith('"')||x.startsWith("'")&&x.endsWith("'")?x.slice(1,-1):x).filter(x=>x.length>0));let h;if(c)try{h=JSON.parse(c)}catch{return Q({success:!1,error:"Invalid memorySettings JSON format",requiresRestart:!1},{status:400})}let f;if(u){const x=await ts();x!=null&&x.webapps&&(f=x.webapps.map((b,w)=>{if(u[w]!==void 0){const v=tv(u[w]);return{...b,startCommand:v}}return b}))}if(!await fl({universalMocks:m,pathsToIgnore:p,webapps:f,memory:h}))return Q({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(),b=await ns(x);g=a!==void 0&&a!==(b.GROQ_API_KEY||"")||o!==void 0&&o!==(b.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(b.OPENAI_API_KEY||""),await sp(x,{...b,GROQ_API_KEY:a||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return Q({success:!0,error:null,requiresRestart:g})}catch(t){return console.log("[Settings Action] Failed to save config:",t),Q({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function yi(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function xi({mock:e,onSave:t,onCancel:r}){const[s,a]=M(e.entityName),[o,i]=M(e.filePath),[l,c]=M(e.content);return d("div",{className:"space-y-3",children:[d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:s,onChange:u=>a(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., determineDatabaseType"})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:o,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:l,onChange:u=>c(u.target.value),rows:6,className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., function determineDatabaseType() { return 'postgresql' }"})]}),d("div",{className:"flex gap-2 justify-end",children:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!s.trim()||!o.trim()||!l.trim()){alert("All fields are required");return}t({entityName:s,filePath:o,content:l})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function rv(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const sv=Je(function(){var _e,Ae,De,Le,Se;const{config:t,secrets:r,versionInfo:s,simulationsEnabled:a,error:o}=qe(),i=Kc(),l=Fe(),c=kt(),[m,u]=M(a?"project-metadata":"memory");xt({source:"settings-page"});const[p,h]=M((t==null?void 0:t.universalMocks)||[]),[f,y]=M(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,x]=M(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[b,w]=M((r==null?void 0:r.GROQ_API_KEY)||""),[v,C]=M((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[P,N]=M((r==null?void 0:r.OPENAI_API_KEY)||""),[S,k]=M(!1),[_,j]=M(!1),[T,E]=M(!1),[$,R]=M(!1),[I,W]=M(!1),[Y,U]=M(!1),[B,H]=M(null),[D,A]=M(!1),[J,V]=M({}),[q,X]=M(((_e=t==null?void 0:t.memory)==null?void 0:_e.conversationReflection)??!0),[L,O]=M(((Ae=t==null?void 0:t.memory)==null?void 0:Ae.ruleMaintenance)??!0),[z,G]=M(((De=t==null?void 0:t.memory)==null?void 0:De.promptModel)??"haiku");ne(()=>{var oe,xe,ke,et;if(t){h(t.universalMocks||[]);const ge=(t.pathsToIgnore||[]).join(", ");y(ge),x(ge);const Ye={};(oe=t.webapps)==null||oe.forEach((We,Ht)=>{We.startCommand&&(Ye[Ht]=yi(We.startCommand))}),V(Ye),X(((xe=t.memory)==null?void 0:xe.conversationReflection)??!0),O(((ke=t.memory)==null?void 0:ke.ruleMaintenance)??!0),G(((et=t.memory)==null?void 0:et.promptModel)??"haiku")}r&&(w(r.GROQ_API_KEY||""),C(r.ANTHROPIC_API_KEY||""),N(r.OPENAI_API_KEY||""))},[t,r]),ne(()=>{if(i!=null&&i.success){R(!0);const oe=setTimeout(()=>R(!1),3e3);return()=>clearTimeout(oe)}},[i]),ne(()=>{if(l.state==="idle"&&l.data&&!Y){console.log("[Settings] Fetcher data:",l.data);const oe=l.data;if(oe.success){console.log("[Settings] Save successful, revalidating..."),R(!0),U(!0),(f!==g||oe.requiresRestart)&&W(!0),c.revalidate();const xe=setTimeout(()=>{R(!1),U(!1)},3e3);return()=>clearTimeout(xe)}}},[l.state,l.data,Y,c,f,g]);const ee=oe=>{oe.preventDefault();const xe=new FormData(oe.currentTarget);xe.set("universalMocks",JSON.stringify(p)),xe.set("startCommands",JSON.stringify(J)),xe.set("memorySettings",JSON.stringify({conversationReflection:q,ruleMaintenance:L,promptModel:z})),console.log("[Settings] Submitting form data:",{universalMocks:xe.get("universalMocks"),startCommands:xe.get("startCommands"),openAiApiKey:xe.get("openAiApiKey")?"***":"(empty)"}),l.submit(xe,{method:"post"})},re=oe=>{h([...p,oe]),A(!1)},ue=(oe,xe)=>{const ke=[...p];ke[oe]=xe,h(ke),H(null)},se=oe=>{h(p.filter((xe,ke)=>ke!==oe))};if(o)return d("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:o})})]});const pe=[{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"}],Ce=a?pe:pe.filter(oe=>oe.id==="memory");return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-6 sm:px-12 lg:px-20 pt-8 pb-12 font-sans",children:[d("div",{className:"mb-8 flex justify-between items-start",children:[d("div",{children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Settings"}),n("p",{className:"text-[15px] text-gray-500",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:l.state==="submitting",className:"px-6 py-2 bg-[#005C75] text-white border-none rounded text-sm font-medium cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 hover:bg-[#004a5d] whitespace-nowrap",children:l.state==="submitting"?"Saving...":"Save Settings"})]}),($||I||(i==null?void 0:i.error)||l.data&&typeof l.data=="object"&&"error"in l.data)&&d("div",{className:"mb-4 space-y-3",children:[$&&n("div",{className:"text-emerald-600 text-sm font-medium bg-emerald-50 border border-emerald-200 rounded px-4 py-2",children:"Settings saved successfully!"}),I&&d("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[n("div",{children:"Settings changed. Please restart CodeYam for changes to take effect:"}),d("div",{className:"flex items-center gap-2 mt-1",children:[n("code",{className:"bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"}),n(jt,{content:"codeyam stop && codeyam",className:"px-2 py-1 text-xs bg-amber-200 hover:bg-amber-300 text-amber-800 rounded border-none transition-colors"})]})]}),(i==null?void 0:i.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:i.error}),(()=>{if(l.data&&typeof l.data=="object"&&"error"in l.data){const oe=l.data;return typeof oe.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:oe.error}):null}return null})()]}),d("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8 items-start",children:[n("nav",{className:"w-full lg:w-64 flex-shrink-0",children:n("ul",{className:"flex lg:flex-col overflow-x-auto gap-1",children:Ce.map(oe=>n("li",{children:n("button",{type:"button",onClick:()=>u(oe.id),className:`w-full text-left px-3 lg:px-0 py-2.5 text-sm transition-colors cursor-pointer whitespace-nowrap ${m===oe.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:oe.label})},oe.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:d("form",{id:"settings-form",onSubmit:ee,className:"space-y-6",children:[m==="project-metadata"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),d("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((oe,xe)=>{var ke;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:d("div",{className:"space-y-2 text-sm",children:[d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:oe.path==="."?"Root":oe.path})]}),oe.appDirectory&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:oe.appDirectory})]}),d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:oe.framework})]}),oe.startCommand&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",d("span",{className:"text-gray-900 font-mono text-xs",children:[oe.startCommand.command," ",(ke=oe.startCommand.args)==null?void 0:ke.join(" ")]})]})]})},xe)})}):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"&&d("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),d("div",{className:"space-y-6",children:[d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),d("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:S?"text":"password",id:"groqApiKey",name:"groqApiKey",value:b,onChange:oe=>w(oe.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:()=>k(!S),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:S?"Hide":"Show"})]})]})]}),d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),d("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:_?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:v,onChange:oe=>C(oe.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:()=>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:_?"Hide":"Show"})]})]})]}),d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),d("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:T?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:P,onChange:oe=>N(oe.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:()=>E(!T),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:T?"Hide":"Show"})]})]})]})]})]}),m==="commands"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((oe,xe)=>d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[d("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:oe.path==="."?"Root":oe.path}),n("div",{className:"text-sm text-gray-600",children:oe.framework})]}),d("div",{children:[n("label",{htmlFor:`startCommand-${xe}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${xe}`,name:`startCommand-${xe}`,value:J[xe]||"",onChange:ke=>V({...J,[xe]: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"})]})]},xe))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),m==="paths-to-ignore"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:f,onChange:oe=>y(oe.target.value),placeholder:"e.g., __tests__, \\.test\\.ts$, ^background (no quotes needed)",className:"w-full px-3 py-3 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-2 focus:ring-[#005C75]/10"}),d("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),m==="universal-mocks"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),p.length===0?d("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>A(!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:p.map((oe,xe)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:B===xe?n(xi,{mock:oe,onSave:ke=>ue(xe,ke),onCancel:()=>H(null)}):n(de,{children:d("div",{className:"flex justify-between items-start mb-2",children:[d("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:oe.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:oe.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:oe.content})]}),d("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>H(xe),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:()=>se(xe),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},xe))}),p.length>0&&n("button",{type:"button",onClick:()=>A(!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"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Memory"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure how CodeYam reflects on conversations and maintains rules between sessions."}),d("div",{className:"space-y-6",children:[n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Conversation Reflection"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent reviews the session for architectural decisions, tribal knowledge, confusion, or corrections that future sessions would benefit from knowing. It creates or updates Claude Rules based on what it learns."})]}),n("button",{type:"button",role:"switch","aria-checked":q,onClick:()=>X(!q),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${q?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${q?"translate-x-5":"translate-x-0"}`})})]})}),n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Rule Maintenance"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent checks if any existing Claude Rules have become stale based on recent code changes. It reviews the rule content against file diffs and updates rules that are out of date."})]}),n("button",{type:"button",role:"switch","aria-checked":L,onClick:()=>O(!L),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 ${L?"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 ${L?"translate-x-5":"translate-x-0"}`})})]})}),d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Memory Prompt Model"}),n("p",{className:"text-sm text-gray-600 mb-4",children:"Choose the Claude model used for conversation reflection and rule maintenance tasks."}),n("div",{className:"space-y-3",children:[{value:"haiku",label:"Haiku",badge:"Default, Recommended",description:"Fastest and cheapest. Good for routine reflection tasks."},{value:"sonnet",label:"Sonnet",badge:null,description:"Balanced speed and quality. Better at nuanced rule writing."},{value:"opus",label:"Opus",badge:null,description:"Highest quality. Best for complex architectural decisions. Costs significantly more."}].map(oe=>d("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${z===oe.value?"border-[#005C75] bg-[#005C75]/5":"border-gray-200 hover:border-gray-300"}`,children:[n("input",{type:"radio",name:"promptModel",value:oe.value,checked:z===oe.value,onChange:()=>G(oe.value),className:"mt-1 accent-[#005C75]"}),d("div",{children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-gray-900",children:oe.label}),oe.badge&&n("span",{className:"px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:oe.badge})]}),n("p",{className:"text-sm text-gray-600 mt-0.5",children:oe.description})]})]},oe.value))})]})]})]}),m==="current-configuration"&&d("div",{className:"space-y-6",children:[t&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:d("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&d("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((oe,xe)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:d("div",{className:"space-y-2 text-sm",children:[d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:oe.path==="."?"Root":oe.path})]}),oe.appDirectory&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:oe.appDirectory})]}),d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:oe.framework})]}),oe.startCommand&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:yi(oe.startCommand)})]})]})},xe))})]})]}),s&&d("div",{className:"mt-6",children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:d("div",{className:"space-y-2 text-sm",children:[s.webserverVersion&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",n("span",{className:"text-gray-900 font-mono",children:s.webserverVersion.version||"unknown"})]}),s.templateVersion&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",n("span",{className:"font-mono text-gray-900",children:s.templateVersion.version||((Le=s.templateVersion.gitCommit)==null?void 0:Le.slice(0,7))||"unknown"}),s.templateVersion.buildTimestamp&&d("span",{className:"text-gray-500 ml-2",children:["(built"," ",rv(s.templateVersion.buildTimestamp),")"]})]}),s.cachedAnalyzerVersion&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"font-mono text-gray-900",children:s.cachedAnalyzerVersion.version||((Se=s.cachedAnalyzerVersion.gitCommit)==null?void 0:Se.slice(0,7))||"unknown"}),s.isCacheStale?n("span",{className:"ml-2 px-2 py-0.5 bg-amber-100 text-amber-800 rounded text-xs",children:"Stale - will update on next analysis"}):n("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]}),!s.cachedAnalyzerVersion&&(t==null?void 0:t.projectSlug)&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),D&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:d("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[n("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),n(xi,{mock:{entityName:"",filePath:"",content:""},onSave:re,onCancel:()=>A(!1)})]})})]})})}),av=Object.freeze(Object.defineProperty({__proto__:null,action:nv,default:sv,loader:ev,meta:Xw},Symbol.toStringTag,{value:"Module"}));async function ov({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=Z.extname(t)!==""?t:`${t}.html`,o=Z.join(r,".codeyam","captures","static",a);try{await Ne.access(o);let i=await Ne.readFile(o);const l=Z.extname(o).toLowerCase();let c="application/octet-stream";if(l===".html"){c="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 h=u[1].match(/=\s*(\{[\s\S]*\})/);if(h){const f=JSON.parse(h[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(p){console.error("[Static] Failed to parse Remix context:",p)}i=Buffer.from(m,"utf-8")}else l===".js"||l===".mjs"?c="application/javascript":l===".css"?c="text/css":l===".json"?c="application/json":l===".png"?c="image/png":l===".jpg"||l===".jpeg"?c="image/jpeg":l===".svg"?c="image/svg+xml":l===".woff"?c="font/woff":l===".woff2"?c="font/woff2":l===".ttf"&&(c="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":c,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const iv=Object.freeze(Object.defineProperty({__proto__:null,loader:ov},Symbol.toStringTag,{value:"Module"}));function lv(e,t,r=10){var c;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=(c=m.metadata)==null?void 0:c.importedBy;if(u)for(const p of Object.keys(u))for(const h of Object.keys(u[p])){const{shas:f}=u[p][h];for(const y of f)o.has(m.sha)||o.set(m.sha,new Set),o.get(m.sha).add(y)}}const i=[],l=new Set;for(const m of e)i.push({sha:m.sha,depth:0}),l.add(m.sha);for(;i.length>0;){const{sha:m,depth:u}=i.shift();if(u>=r)continue;const p=o.get(m);if(p)for(const h of p){if(l.has(h))continue;l.add(h);const f=t.find(y=>y.sha===h);if(f){if(a(f)){const y=u+1,g=s.get(h);(!g||y<g.depth)&&s.set(h,{entity:f,depth:y})}i.push({sha:h,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 Yr(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 l=((m=o.metadata)==null?void 0:m.editedAt)||o.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(l)});r.push(a[0])}return r}function jc(e,t){const r=new Map,s=new Set(e.map(a=>a.path));for(const a of e)a.status==="renamed"&&a.oldPath&&s.add(a.oldPath);for(const a of e){const o=t.filter(c=>c.filePath===a.path||a.status==="renamed"&&a.oldPath&&c.filePath===a.oldPath),i=o.filter(c=>{var m,u;return s.has(c.filePath)&&((m=c.metadata)==null?void 0:m.isUncommitted)&&!((u=c.metadata)!=null&&u.isSuperseded)}),l=Yr(i);r.set(a.path,{status:a,entities:o,editedEntities:l})}return r}function cv(e,t,r){const s=new Map;if(!r){for(const o of e)if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const i=t.filter(c=>c.filePath===o.path||o.status==="renamed"&&o.oldPath&&c.filePath===o.oldPath),l=Yr(i);s.set(o.path,{status:o,entities:l})}return s}const a=new Map;for(const o of r.fileComparisons){const i=new Set;for(const l of o.newEntities)i.add(l.name);for(const l of o.modifiedEntities)i.add(l.name);for(const l of o.deletedEntities)i.add(l.name);i.size>0&&a.set(o.filePath,i)}for(const o of e){const i=a.get(o.path);if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const l=i?t.filter(m=>(m.filePath===o.path||o.status==="renamed"&&o.oldPath&&m.filePath===o.oldPath)&&i.has(m.name)):[],c=Yr(l);s.set(o.path,{status:o,entities:c})}}return s}function dv(e,t){const r=new Map,s=Mc(e,t);for(const a of s){const i=lv([a],t).filter(({depth:l})=>l>0);r.set(a.sha,i)}return r}function Mc(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 Yr(s)}function uv({recentSimulations:e}){const t=ae(()=>{const r=new Map;return e.forEach(s=>{const a=s.entitySha,o=r.get(a);o?o.push(s):r.set(a,[s])}),Array.from(r.entries()).map(([s,a])=>({entitySha:s,entityName:a[0].entityName,scenarios:a}))},[e]);return d("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:d("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:e.length>0?`Latest ${e.length} captured screenshot${e.length!==1?"s":""}`:"No simulations captured yet"})]})}),e.length>0?d(de,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>d("div",{children:[d("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(Zn,{size:16,style:{color:"#8B5CF6"}})}),n(me,{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(me,{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(Ze,{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(me,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:r=>r.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:r=>r.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):d("div",{className:"py-12 px-6 text-center rounded-lg w-full flex flex-col items-center justify-center min-h-50 border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:n(Zn,{size:24,style:{color:"#7A9BA5"},strokeWidth:1.5})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No simulations captured yet."}),d("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",n(me,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(me,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const mv="/assets/codeyam-name-logo-CvKwUgHo.svg",pv=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function hv({request:e,context:t}){var r,s,a,o,i;try{const l=await Ie();if(l){const{project:$}=await Re(l);if(((r=$.metadata)==null?void 0:r.editorMode)??!1)return No("/editor");if(!(((a=(s=$.metadata)==null?void 0:s.labs)==null?void 0:a.simulations)??!1))return No("/memory")}const c=t.analysisQueue,m=c?c.getState():{paused:!1,jobs:[]},[u,p]=await Promise.all([mn(),_n()]),h=jn(),f=u?jc(h,u):new Map,y=Array.from(f.entries()).sort(($,R)=>$[0].localeCompare(R[0])),g=(u==null?void 0:u.length)||0,x=(u==null?void 0:u.filter($=>$.entityType==="visual").length)||0,b=(u==null?void 0:u.filter($=>$.entityType==="library").length)||0,w=u?Mc(h,u):[],v=w.length,C=(u==null?void 0:u.filter($=>($.analyses??[]).filter(R=>R.scenarios&&R.scenarios.length>0).length>0).length)||0,P=(u==null?void 0:u.reduce(($,R)=>{var W,Y,U;const I=((U=(Y=(W=R.analyses)==null?void 0:W[0])==null?void 0:Y.scenarios)==null?void 0:U.length)||0;return $+I},0))||0,N=(u==null?void 0:u.reduce(($,R)=>{var Y,U;const W=(((U=(Y=R.analyses)==null?void 0:Y[0])==null?void 0:U.scenarios)||[]).filter(B=>{var H,D;return(D=(H=B.metadata)==null?void 0:H.screenshotPaths)==null?void 0:D[0]}).length;return $+W},0))||0,S=[];u==null||u.forEach($=>{var I;const R=(I=$.analyses)==null?void 0:I[0];R!=null&&R.scenarios&&R.scenarios.filter(Y=>{var U;return!((U=Y.metadata)!=null&&U.sameAsDefault)}).forEach(Y=>{var B,H;const U=(H=(B=Y.metadata)==null?void 0:B.screenshotPaths)==null?void 0:H[0];U&&S.push({entitySha:$.sha,entityName:$.name,scenarioId:Y.id,scenarioName:Y.name,screenshotPath:U,createdAt:R.createdAt||""})})}),S.sort(($,R)=>new Date(R.createdAt).getTime()-new Date($.createdAt).getTime());const k=S.slice(0,16),_=(u==null?void 0:u.filter($=>$.entityType==="visual").filter($=>{var W,Y;const R=(W=$.analyses)==null?void 0:W[0];return!((Y=R==null?void 0:R.scenarios)==null?void 0:Y.some(U=>{var B,H;return(H=(B=U.metadata)==null?void 0:B.screenshotPaths)==null?void 0:H[0]}))}).slice(0,8))||[],j=(o=p==null?void 0:p.metadata)==null?void 0:o.currentRun,T=((i=j==null?void 0:j.currentEntityShas)==null?void 0:i.length)||0,E=m.jobs.length||0;return Q({stats:{totalEntities:g,visualEntities:x,libraryEntities:b,uncommittedEntities:v,entitiesWithAnalyses:C,totalScenarios:P,capturedScreenshots:N,currentlyAnalyzing:T,filesOnQueue:E},uncommittedFiles:y,uncommittedEntitiesList:w,recentSimulations:k,visualEntitiesForSimulation:_,projectSlug:l,queueState:m,currentCommit:p})}catch(l){return console.error("Failed to load dashboard data:",l),Q({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 fv=Je(function(){var B,H;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:s,recentSimulations:a,visualEntitiesForSimulation:o,projectSlug:i,queueState:l,currentCommit:c}=qe(),m=Fe(),u=kt(),{showToast:p}=Aa();xt({source:"dashboard"});const[h,f]=M(new Set),[y,g]=M(null),[x,b]=M(!1),[w,v]=M(!1),{lastLine:C,isCompleted:P}=_t(i,!!y),{simulatingEntity:N,scenarios:S,scenarioStatuses:k,allScenariosCaptured:_}=ae(()=>{var O,z;const D={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!y)return D;const A=o==null?void 0:o.find(G=>G.sha===y);if(!A)return D;const J=(O=A.analyses)==null?void 0:O[0],V=(J==null?void 0:J.scenarios)||[],q=((z=J==null?void 0:J.status)==null?void 0:z.scenarios)||[],X=q.filter(G=>G.screenshotFinishedAt).length,L=V.length>0&&X===V.length;return{simulatingEntity:A,scenarios:V,scenarioStatuses:q,allScenariosCaptured:L}},[y,o]);ne(()=>{(P||_)&&g(null)},[P,_]);const j=(B=c==null?void 0:c.metadata)==null?void 0:B.currentRun,T=new Set((j==null?void 0:j.currentEntityShas)||[]),E=new Set(l.jobs.flatMap(D=>D.entityShas||[])),$=new Set(((H=l.currentlyExecuting)==null?void 0:H.entityShas)||[]),R=s.filter(D=>D.entityType==="visual"||D.entityType==="library"),I=R.filter(D=>!T.has(D.sha)&&!E.has(D.sha)&&!$.has(D.sha)),W=()=>{if(I.length===0){p("All entities are already queued or analyzing","info",3e3);return}const D=I.map(A=>A.sha);v(!0),p(`Starting analysis for ${I.length} entities...`,"info",3e3),m.submit({entityShas:D.join(",")},{method:"post",action:"/api/analyze"})};ne(()=>{if(m.state==="idle"&&m.data){const D=m.data;D.success?(console.log("[Analyze All] Success:",D.message),p(`Analysis started for ${D.entityCount} entities in ${D.fileCount} files. Watch the logs for progress.`,"success",6e3),v(!1)):D.error&&(console.error("[Analyze All] Error:",D.error),p(`Error: ${D.error}`,"error",8e3),v(!1))}},[m.state,m.data,p]);const Y=D=>{f(A=>{const J=new Set(A);return J.has(D)?J.delete(D):J.add(D),J})},U=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#005C75",tooltip:"In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested."},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981",tooltip:"Entities that have been analyzed by CodeYam and have generated scenarios."},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6",tooltip:"React components and visual elements that can be rendered and captured as screenshots."},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9",tooltip:"Reusable functions and utilities that can be independently tested."}];return n("div",{className:"bg-cygray-10 min-h-screen",children:d("div",{className:"px-20 pt-8 pb-12",children:[d("header",{className:"mb-8 flex justify-between items-center",children:[d("div",{className:"flex items-center gap-4",children:[n("img",{src:mv,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:U.map((D,A)=>n(me,{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:d("div",{className:"px-6 py-6 flex flex-col gap-3 flex-1",children:[d("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[d("div",{className:"flex items-center gap-1.5 group relative",children:[n("span",{className:"text-xs text-gray-700 font-medium font-mono uppercase",children:D.label}),d("svg",{className:"w-3 h-3 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:d("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[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 →"})]}),d("div",{className:"flex flex-col gap-2",children:[d("div",{className:"flex items-center gap-3",children:[d("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${D.color}15`},children:[D.iconType==="folder"&&n(Cd,{size:20,style:{color:D.color}}),D.iconType==="check"&&n(xa,{size:20,style:{color:D.color}}),D.iconType==="image"&&n(Zn,{size:20,style:{color:D.color}}),D.iconType==="code-xml"&&n(Sd,{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 →"})]})]})},A))}),d("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[d("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[d("div",{className:"flex justify-between items-start mb-5",children:[d("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),n("p",{className:"text-sm text-gray-500 m-0",children:r.length>0?`${r.length} file${r.length!==1?"s":""} with ${s.length} uncommitted entit${s.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),R.length>0&&n("button",{onClick:W,disabled:m.state!=="idle"||w||I.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"||w?"Starting analysis...":I.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([D,A])=>{const J=h.has(D),V=A.editedEntities||[];return d("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#005C75"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>Y(D),role:"button",tabIndex:0,children:d("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:J?"▼":"▶"}),d("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[d("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),d("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:D}),d("span",{className:"text-xs text-gray-500",children:[V.length," entit",V.length!==1?"ies":"y"]})]})]})}),J&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:V.length>0?V.map(q=>{const X=T.has(q.sha),L=E.has(q.sha)||$.has(q.sha);return d(me,{to:`/entity/${q.sha}`,className:"flex items-center gap-4 p-4 bg-white border border-gray-200 rounded-lg no-underline transition-all hover:shadow-md hover:-translate-y-0.5",style:{borderColor:"inherit"},onMouseEnter:O=>O.currentTarget.style.borderColor="#005C75",onMouseLeave:O=>O.currentTarget.style.borderColor="inherit",children:[d("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:q.entityType==="visual"?"#8B5CF615":q.entityType==="library"?"#6366F1":"#EC4899"},children:[q.entityType==="visual"&&n(Zn,{size:16,style:{color:"#8B5CF6"}}),q.entityType==="library"&&n(Bi,{size:16,className:"text-white"}),q.entityType==="other"&&n(kd,{size:16,className:"text-white"})]}),d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:q.name}),q.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),q.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),q.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),q.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:q.description})]}),d("div",{className:"flex items-center gap-2 shrink-0",children:[X&&d("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(ht,{size:14,className:"animate-spin"}),"Analyzing..."]}),!X&&L&&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&&!L&&n("button",{onClick:O=>{O.preventDefault(),O.stopPropagation(),p(`Starting analysis for ${q.name}...`,"info",3e3),m.submit({entityShas:q.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:O=>O.currentTarget.style.backgroundColor="#004560",onMouseLeave:O=>O.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},q.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},D)})}):d("div",{className:"py-12 px-6 text-center flex flex-col items-center rounded-lg min-h-50 justify-center border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:d("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#7A9BA5",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n("polyline",{points:"14 2 14 8 20 8"}),n("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),n("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!y&&n(uv,{recentSimulations:a}),y&&d("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:d("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:a.length>0?`Latest ${a.length} captured screenshot${a.length!==1?"s":""}`:"No simulations captured yet"})]})}),y&&d("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[N&&n("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:d("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(at,{type:"visual"})}),d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",N.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:N.filePath})]})]})}),_?d("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[n("span",{className:"text-lg",children:"✅"}),d("span",{children:["Complete (",S.length," scenario",S.length!==1?"s":"",")"]})]}):C?d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(ht,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:C,children:C}),i&&n("button",{onClick:()=>b(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):m.state!=="idle"?d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(ht,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(ht,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),S.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:S.slice(0,8).map((D,A)=>{var z,G,ee;const J=(z=N==null?void 0:N.analyses)==null?void 0:z[0],V=gs(D,J==null?void 0:J.status,void 0,y||void 0,void 0),q=(ee=(G=D.metadata)==null?void 0:G.screenshotPaths)==null?void 0:ee[0],X=V.isCaptured,L=V.status==="capturing"||V.status==="starting",O=V.hasError;return X?n(me,{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(Ze,{screenshotPath:q,alt:D.name,title:D.name,className:"max-w-full max-h-full object-contain object-center"})},A):O?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:V.errorMessage||"Capture error",children:n("span",{className:"text-red-500",children:"⚠️"})},A):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:`${L?"Capturing":"Pending"} ${D.name}...`,children:n("span",{className:L?"animate-pulse":"text-gray-400",children:L?"⋯":"⏹️"})},A)})})]})]})]}),x&&i&&n(Ft,{projectSlug:i,onClose:()=>b(!1)})]})})}),gv=Object.freeze(Object.defineProperty({__proto__:null,default:fv,loader:hv,meta:pv},Symbol.toStringTag,{value:"Module"}));function ao(e){const[t,r]=M(null),[s,a]=M(!1),o=ie(()=>{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 ne(()=>{e&&o()},[e,o]),{results:t,isRunning:s,runTests:o}}function Wn({imgSrc:e,name:t,isActive:r,onSelect:s}){return d("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 Vs({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=ao(e);if(s&&!r)return d("div",{className:"px-2 pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!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(c=>c.fullName.startsWith(t)):r.testCases,i=o.length>0?o:r.testCases;if(i.length===0)return null;const l=t?`${t} > `:"";return d("div",{className:"px-2 pt-1 space-y-0.5",children:[i.map(c=>{var u;const m=l&&c.fullName.startsWith(l)?c.fullName.slice(l.length):c.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[c.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):c.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] ${c.status==="passed"?"text-green-400":c.status==="failed"?"text-red-400":"text-gray-500"}`,children:m})]}),c.status==="failed"&&((u=c.failureMessages)==null?void 0:u.map((p,h)=>n("div",{className:"pl-4 text-[9px] text-red-300/70 truncate max-w-full",title:p,children:p.split(`
|
|
394
|
-
`)[0]},h)))]},c.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 tn({filePath:e}){return e?d("div",{className:"flex items-center gap-1 px-2 mt-0.5",children:[d("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(jt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function yv({scenarios:e,projectRoot:t,activeScenarioId:r,onScenarioSelect:s,zoomComponent:a,onZoomChange:o,analyzedEntities:i=[],glossaryFunctions:l=[],activeAnalyzedScenarioId:c,onAnalyzedScenarioSelect:m,entityImports:u,pageFilePaths:p={}}){const{pageGroups:h,componentGroups:f}=ae(()=>{var _;const N=new Map,S=new Map;for(const j of e)if(j.componentName){const T=S.get(j.componentName)||[];T.push(j),S.set(j.componentName,T)}else if(Ha(j.url)){const T=(_=j.url)==null?void 0:_.match(/[?&]c=([^&]+)/),E=T?decodeURIComponent(T[1]):"Isolated",$=S.get(E)||[];$.push(j),S.set(E,$)}else{const T=Xe(j.url),E=N.get(T)||[];E.push(j),N.set(T,E)}const k=new Map([...S.entries()].sort(([j],[T])=>j.localeCompare(T)));return{pageGroups:N,componentGroups:k}},[e]),y=ae(()=>{const N=new Set((i||[]).filter(k=>k.entityType==="visual").map(k=>k.name)),S=new Map;for(const[k,_]of f)N.has(k)||S.set(k,_);return S},[f,i]),{visualEntities:g,libraryEntities:x}=ae(()=>{const N=i.filter(k=>k.entityType==="visual").sort((k,_)=>k.name.localeCompare(_.name)),S=i.filter(k=>k.entityType==="library"||k.entityType==="functionCall").sort((k,_)=>k.name.localeCompare(_.name));return{visualEntities:N,libraryEntities:S}},[i]),b=ae(()=>{const N=new Set(x.map(S=>S.name));return l.filter(S=>!N.has(S.name)).sort((S,k)=>S.name.localeCompare(k.name))},[l,x]),w=i.some(N=>N.isAnalyzing),v=ve(null),C=ve(0),P=ie(()=>{v.current&&(C.current=v.current.scrollTop)},[]);if(ne(()=>{v.current&&C.current>0&&(v.current.scrollTop=C.current)}),e.length===0&&i.length===0&&b.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:d("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No scenarios yet"}),n("p",{className:"text-xs",children:"Scenarios will appear here as Claude creates them alongside your code. Each scenario represents a different state of your app's data."})]})});if(a){const N=f.get(a)||[],S=new Set((u==null?void 0:u[a])||[]),k=S.size>0,_=k?g.filter(T=>S.has(T.name)):[],j=k?x.filter(T=>S.has(T.name)):[];return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-1",children:[d("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:N.length===0?n("div",{className:"px-3 py-2 text-xs text-gray-500",children:"No scenarios for this component"}):N.map(T=>n(Wn,{imgSrc:T.screenshotPath?`/api/editor-scenario-image/${T.id}.png`:null,name:T.name,isActive:T.id===r,onSelect:()=>s(T)},T.id))}),_.length>0&&d("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),_.map(T=>d("div",{className:"mt-2",children:[n("div",{className:"flex items-center gap-2 px-2 py-1",children:n("button",{onClick:()=>o(T.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:T.name})}),n(tn,{filePath:T.filePath,projectRoot:t}),(T.scenarios.length>0||T.pendingScenarios.length>0)&&n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:T.scenarios.map(E=>n(Wn,{imgSrc:E.screenshotPath?`/api/screenshot/${E.screenshotPath}`:null,name:E.name,isActive:E.id===c,onSelect:()=>m==null?void 0:m({analysisId:T.analysisId,scenarioId:E.id,scenarioName:E.name,entitySha:T.sha,entityName:T.name})},E.id))})]},T.sha))]}),j.length>0&&d("div",{className:"pt-2 mt-1",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),j.map(T=>d("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:T.name})}),n(tn,{filePath:T.filePath,projectRoot:t}),T.testFile&&n(Vs,{testFile:T.testFile,entityName:T.name})]},T.sha))]})]})})}return n("div",{ref:v,onScroll:P,className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-3",children:[h.size>0&&d("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"})}),[...h.entries()].sort(([N],[S])=>N==="Home"?-1:S==="Home"?1:N.localeCompare(S)).map(([N,S])=>d("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:N})}),p[N]&&n(tn,{filePath:p[N],projectRoot:t}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:S.map(k=>n(Wn,{imgSrc:k.screenshotPath?`/api/editor-scenario-image/${k.id}.png`:null,name:k.name,isActive:k.id===r&&!c,onSelect:()=>s(k)},k.id))})]},N))]}),y.size>0&&d("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),[...y.entries()].map(([N,S])=>{var k;return d("div",{className:"mt-2",children:[n("div",{className:"flex items-center justify-between px-2 py-1",children:n("button",{onClick:()=>o(N),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:N})}),((k=S[0])==null?void 0:k.componentPath)&&n(tn,{filePath:S[0].componentPath,projectRoot:t}),n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:S.map(_=>n(Wn,{imgSrc:_.screenshotPath?`/api/editor-scenario-image/${_.id}.png`:null,name:_.name,isActive:_.id===r&&!c,onSelect:()=>s(_)},_.id))})]},N)})]}),g.length>0&&d("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[d("div",{className:"px-2 py-1",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),w&&e.length===0&&i.every(N=>N.scenarioCount===0)&&n("span",{className:"ml-2 text-[10px] text-gray-500",children:"— Entities are being analyzed..."})]}),g.map(N=>d("div",{className:"mt-2",children:[d("div",{className:"flex items-center gap-2 px-2 py-1",children:[n("button",{onClick:()=>o(N.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:N.name}),N.isAnalyzing&&N.scenarioCount===0&&d("span",{className:"flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(tn,{filePath:N.filePath,projectRoot:t}),(N.scenarios.length>0||N.pendingScenarios.length>0)&&d("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:[N.scenarios.map(S=>n(Wn,{imgSrc:S.screenshotPath?`/api/screenshot/${S.screenshotPath}`:null,name:S.name,isActive:S.id===c,onSelect:()=>m==null?void 0:m({analysisId:N.analysisId,scenarioId:S.id,scenarioName:S.name,entitySha:N.sha,entityName:N.name})},S.id)),N.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))]})]},N.sha))]}),(x.length>0||b.length>0)&&d("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(N=>d("div",{className:"mt-2",children:[d("div",{className:"px-2 py-1",children:[n("span",{className:"text-[11px] font-medium text-gray-300",children:N.name}),N.isAnalyzing&&N.scenarioCount===0&&d("span",{className:"ml-2 inline-flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(tn,{filePath:N.filePath,projectRoot:t}),N.testFile?n(Vs,{testFile:N.testFile,entityName:N.name}):n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},N.sha)),b.map(N=>d("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:N.name})}),n(tn,{filePath:N.filePath,projectRoot:t}),n(Vs,{testFile:N.testFile,entityName:N.name})]},N.name))]})]})})}const bi=120;function Tc({text:e,theme:t}){const[r,s]=M(!1),a=e.length>bi,o=a&&!r?e.slice(0,bi)+"…":e,i=t==="light";return d("div",{className:`px-4 py-2 ${i?"border-b border-gray-200 bg-gray-50":"border-b border-[#3d3d3d] bg-[#252525]"}`,children:[n("span",{className:"text-[9px] font-semibold uppercase tracking-wider text-gray-500",children:"User Prompt"}),d("p",{className:`text-[11px] mt-0.5 mb-0 leading-relaxed ${i?"text-gray-600":"text-gray-400"}`,children:[o,a&&n("button",{onClick:()=>s(!r),className:`ml-1 text-[11px] font-medium bg-transparent border-none p-0 cursor-pointer ${i?"text-blue-500 hover:text-blue-700":"text-[#00a0c4] hover:text-[#00c0e8]"}`,children:r?"Show less":"Read more…"})]})]})}function wi({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 xv({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=ao(e);if(s&&!r)return d("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#00a0c4] animate-pulse"}),n("span",{className:"text-[10px] text-gray-500",children:"Running tests..."})]});if(!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(c=>c.fullName.startsWith(t)):r.testCases,i=o.length>0?o:r.testCases;if(i.length===0)return null;const l=t?`${t} > `:"";return d("div",{className:"pt-1 space-y-0.5",children:[i.map(c=>{var u;const m=l&&c.fullName.startsWith(l)?c.fullName.slice(l.length):c.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[c.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):c.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] ${c.status==="passed"?"text-green-400":c.status==="failed"?"text-red-400":"text-gray-500"}`,children:m})]}),c.status==="failed"&&((u=c.failureMessages)==null?void 0:u.map((p,h)=>n("div",{className:"pl-4 text-[9px] text-red-400/70 truncate max-w-full",title:p,children:p.split(`
|
|
395
|
-
`)[0]},h)))]},c.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 bv={added:"text-green-400",untracked:"text-green-400",modified:"text-blue-400",renamed:"text-purple-400"};function wv({files:e}){return d("div",{className:"border-t border-[#3d3d3d] pt-2 mt-1",children:[d("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:["Modified Files (",e.length,")"]}),n("div",{className:"mt-1 space-y-0.5 max-h-[150px] overflow-auto",children:e.map(t=>d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold uppercase w-[14px] text-center ${bv[t.status]||"text-gray-500"}`,children:t.status==="added"||t.status==="untracked"?"A":t.status==="modified"?"M":t.status==="renamed"?"R":"?"}),n("span",{className:"text-[10px] text-gray-400 truncate font-mono",children:t.path})]},t.path))})]})}const vv={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 Nv(e){try{return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function Cv(e){try{return new Date(e+"T00:00:00").toLocaleDateString([],{weekday:"long",month:"long",day:"numeric"})}catch{return e}}const Sv=[{value:"1d",label:"1 Day"},{value:"3d",label:"3 Days"},{value:"7d",label:"1 Week"},{value:"30d",label:"1 Month"}];function kv({entries:e,onScreenshotClick:t}){const[r,s]=M(!1),[a,o]=M("7d"),i=ae(()=>k0(e,a),[e,a]);return d("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[d("button",{onClick:()=>s(!r),className:"w-full flex items-center justify-between px-3 py-2.5 cursor-pointer bg-transparent border-none text-left hover:bg-[#333] transition-colors",children:[n("span",{className:"text-xs font-semibold text-gray-400 uppercase tracking-wider",children:"Timeframe Summary"}),n("span",{className:`text-gray-500 text-[10px] transition-transform ${r?"rotate-180":""}`,children:"▼"})]}),r&&d("div",{className:"px-3 pb-3 space-y-3 border-t border-[#3d3d3d]",children:[n("div",{className:"flex gap-1 pt-2.5",children:Sv.map(l=>n("button",{onClick:()=>o(l.value),className:`px-2.5 py-1 text-[10px] font-medium rounded transition-colors cursor-pointer border ${a===l.value?"bg-[#005c75] text-white border-[#005c75]":"bg-transparent text-gray-400 border-[#4d4d4d] hover:text-white hover:border-[#005c75]"}`,children:l.label},l.value))}),d("div",{className:"flex items-center gap-3 text-[11px] text-gray-400",children:[d("span",{children:[n("span",{className:"text-white font-medium",children:i.commitCount})," ",i.commitCount===1?"commit":"commits"]}),n("span",{className:"text-[#3d3d3d]",children:"|"}),d("span",{children:[n("span",{className:"text-white font-medium",children:i.totalScenarios})," ",i.totalScenarios===1?"scenario changed":"scenarios changed"]}),n("span",{className:"text-[#3d3d3d]",children:"|"}),d("span",{children:[n("span",{className:"text-white font-medium",children:i.entryCount})," ",i.entryCount===1?"entry":"entries"]})]}),i.totalScenarios===0?n("p",{className:"text-[11px] text-gray-500 italic m-0",children:"No scenario changes in this period."}):d("div",{className:"space-y-3",children:[i.appScenarios.length>0&&d("div",{className:"space-y-2",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),i.appScenarios.map(l=>n(vi,{scenario:l,onScreenshotClick:t},l.name))]}),i.componentGroups.size>0&&d("div",{className:"space-y-2",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),[...i.componentGroups.entries()].sort(([l],[c])=>l.localeCompare(c)).map(([l,c])=>d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:l}),c.map(m=>n(vi,{scenario:m,onScreenshotClick:t},m.name))]},l))]})]})]})]})}function vi({scenario:e,onScreenshotClick:t}){const r=e.name.indexOf(" - "),s=r!==-1?e.name.slice(r+3):e.name;return d("div",{className:"pl-2",children:[n("span",{className:"text-[10px] text-gray-500 block mb-1",children:s}),n("div",{className:"flex items-center gap-1 overflow-x-auto",children:e.screenshots.map((a,o)=>d("div",{className:"flex items-center shrink-0",children:[o>0&&n("span",{className:"text-[8px] text-gray-600 mx-0.5",children:"→"}),n("button",{type:"button",className:"w-16 h-16 rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] shrink-0 flex items-center justify-center cursor-pointer transition-colors",title:`${e.name} (${new Date(a.time).toLocaleDateString()})`,onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${a.path.replace("screenshots/","")}`,commitSha:null,commitMessage:null,scenarioName:e.name}),children:n("img",{src:`/api/editor-journal-image/${a.path.replace("screenshots/","")}`,alt:e.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})})]},a.path))})]})}function Ev({isActive:e,onScreenshotClick:t,glossaryFunctions:r=[]}){const[s,a]=M([]),[o,i]=M(!0),[l,c]=M(new Set),m=ie(h=>{c(f=>{const y=new Set(f);return y.has(h)?y.delete(h):y.add(h),y})},[]),u=ie(async()=>{try{const h=await fetch("/api/editor-journal");if(h.ok){const f=await h.json();a(f.entries||[])}}catch{}finally{i(!1)}},[]);if(ne(()=>{u()},[u]),ne(()=>{e&&u()},[e,u]),ne(()=>{if(!e)return;const h=setInterval(()=>void u(),5e3);return()=>clearInterval(h)},[e,u]),o)return n("div",{className:"flex-1 flex items-center justify-center",children:n("span",{className:"text-gray-500 text-sm",children:"Loading journal..."})});if(s.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:d("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No journal entries yet"}),n("p",{className:"text-xs",children:"Journal entries will appear as you build. Claude records features, screenshots, and commits as the project evolves."})]})});const p=E0(s);return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-4",children:[n(kv,{entries:s,onScreenshotClick:t}),[...p.entries()].map(([h,f])=>d("div",{children:[n("div",{className:"px-3 py-1.5 sticky top-0 bg-[#1e1e1e] z-10",children:n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:Cv(h)})}),n("div",{className:"space-y-2",children:f.map((y,g)=>{const x=vv[y.type]||{label:y.type,color:"bg-gray-600"},b=`${y.time}-${g}`,w=l.has(b);return d("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[d("div",{className:`p-3 space-y-2 ${w?"":"max-h-[300px] overflow-y-auto"}`,children:[n("div",{className:"flex items-start gap-2 cursor-pointer",onClick:()=>m(b),children:d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-white truncate",children:y.title}),n("span",{className:`${x.color} text-white text-[9px] font-bold px-1.5 py-0.5 rounded uppercase tracking-wider shrink-0`,children:x.label})]}),n("span",{className:"text-[10px] text-gray-500",children:Nv(y.time)}),y.featureName&&n("span",{className:"text-[10px] text-gray-500 italic truncate",title:y.featureName,children:y.featureName})]})}),y.userPrompt&&n(Tc,{text:y.userPrompt,theme:"dark"}),n("p",{className:"text-xs text-gray-400 leading-relaxed",children:y.description}),y.screenshot&&n("button",{type:"button",className:"rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] flex items-center justify-center p-1 cursor-pointer transition-colors w-full",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${y.screenshot.replace("screenshots/","")}`,commitSha:y.commitSha,commitMessage:y.commitMessage,scenarioName:y.title}),children:n("img",{src:`/api/editor-journal-image/${y.screenshot.replace("screenshots/","")}`,alt:y.title,className:"max-w-full max-h-full object-contain",loading:"lazy"})}),y.scenarioScreenshots&&y.scenarioScreenshots.length>0&&(()=>{const v=_0(y.scenarioScreenshots),C=y.entityChangeStatus,P=v.filter(([j])=>j==="App").flatMap(([,j])=>j),N=v.filter(([j])=>j!=="App"),S=new Map;for(const j of P){const T=Xe(j.url??null),E=S.get(T)||[];E.push(j),S.set(T,E)}const k=[...S.entries()],_=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:y.commitSha,commitMessage:y.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 d("div",{className:"space-y-2",children:[k.length>0&&d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),k.map(([j,T])=>d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:j}),(C==null?void 0:C[j])&&n(wi,{status:C[j]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:T.map(_)})]},j))]}),N.length>0&&d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),N.map(([j,T])=>d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:j}),(C==null?void 0:C[j])&&n(wi,{status:C[j]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:T.map(_)})]},j))]})]})})(),r.length>0&&d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"}),n("div",{className:"space-y-2",children:r.map(v=>d("div",{children:[n("span",{className:"text-[11px] font-medium text-gray-200",children:v.name}),n("span",{className:"text-[9px] text-gray-500 truncate block",children:v.filePath}),v.testFile?n(xv,{testFile:v.testFile,entityName:v.name}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},v.name))})]}),y.commitSha&&d("div",{className:"flex items-center gap-1.5 text-[10px]",children:[n("span",{className:"font-mono text-[#00a0c4] bg-[#00a0c4]/10 px-1.5 py-0.5 rounded",children:y.commitSha.slice(0,7)}),n("span",{className:"text-gray-500 truncate",children:y.commitMessage})]}),w&&y.modifiedFiles&&y.modifiedFiles.length>0&&n(wv,{files:y.modifiedFiles})]}),d("button",{onClick:()=>m(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:["——— ",w?"Collapse":"Expand"," ———"]})]},b)})})]},h))]})})}const Ni=()=>n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"text-gray-500 shrink-0",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})});function _v(e,t){if(e.length<=t)return e;const r=t-2;return[e[0],"ellipsis",...e.slice(e.length-r)]}function Av({items:e,onNavigate:t}){if(e.length===0)return null;const r=_v(e,4);return n("nav",{className:"flex items-center gap-1 text-xs min-w-0",children:r.map((s,a)=>{if(s==="ellipsis")return d("span",{className:"flex items-center gap-1",children:[n(Ni,{}),n("span",{className:"text-gray-500",children:"..."})]},"ellipsis");const o=a===r.length-1;return d("span",{className:"flex items-center gap-1 min-w-0",children:[a>0&&n(Ni,{}),o?n("span",{className:"text-white font-medium truncate",children:s.name}):n("button",{onClick:()=>t(s.componentName),className:"text-gray-400 hover:text-white transition-colors cursor-pointer bg-transparent border-none p-0 truncate",children:s.name})]},s.componentName||"app")})})}function Hn({imgSrc:e,name:t,isActive:r,onSelect:s}){return d("button",{onClick:s,className:"flex flex-col items-center gap-1 cursor-pointer group w-full",title:t,children:[n("div",{className:`w-full aspect-square 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-full ${r?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:t})]})}function Nr({filePath:e}){return e?d("div",{className:"flex items-center gap-1 mt-0.5",children:[d("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-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(jt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function Pv({hasProject:e,scenarios:t,analyzedEntities:r,glossaryFunctions:s=[],glossaryEntries:a=[],projectRoot:o,activeScenarioId:i,onScenarioSelect:l,onAnalyzedScenarioSelect:c,onSwitchToBuild:m,zoomComponent:u,onZoomChange:p,entityImports:h,pageFilePaths:f={},projectTitle:y,projectDescription:g,breadcrumbItems:x=[]}){const{pageGroups:b,componentGroups:w}=ae(()=>{var E;const _=new Map,j=new Map;for(const $ of t)if($.componentName){const R=j.get($.componentName)||[];R.push($),j.set($.componentName,R)}else if(Ha($.url)){const R=(E=$.url)==null?void 0:E.match(/[?&]c=([^&]+)/),I=R?decodeURIComponent(R[1]):"Isolated",W=j.get(I)||[];W.push($),j.set(I,W)}else{const R=Xe($.url),I=_.get(R)||[];I.push($),_.set(R,I)}const T=new Map([...j.entries()].sort(([$],[R])=>$.localeCompare(R)));return{pageGroups:_,componentGroups:T}},[t]),v=ae(()=>r.filter(_=>_.entityType==="visual").sort((_,j)=>_.name.localeCompare(j.name)),[r]),C=ae(()=>{const _=new Map;for(const j of s)_.set(j.name,j);return _},[s]),P=ve(null),N=ve(0),S=ie(()=>{P.current&&(N.current=P.current.scrollTop)},[]);if(ne(()=>{P.current&&N.current>0&&(P.current.scrollTop=N.current)}),!e)return n("div",{className:"flex-1 flex items-center justify-center",children:d("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:m,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(!(t.length>0||v.length>0))return n("div",{className:"flex-1 flex items-center justify-center",children:d("div",{className:"flex flex-col items-center gap-4 px-8 text-center",children:[y?d(de,{children:[n("h2",{className:"text-lg font-medium text-white font-['IBM_Plex_Sans'] m-0",children:y}),g&&n("p",{className:"text-sm text-gray-400 m-0 font-['IBM_Plex_Sans'] leading-relaxed",children:g})]}):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",children:"Describe what you want to build in the Chat and your pages and components will appear here."}),n("button",{onClick:m,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(u){const _=b.get(u)||[],j=w.get(u)||[],T=v.find(A=>A.name===u),E=C.get(u),$=[..._,...j],R=new Set((h==null?void 0:h[u])||[]),I=R.size>0,W=I?[...w.entries()].filter(([A])=>R.has(A)):[],Y=I?v.filter(A=>R.has(A.name)&&!W.some(([J])=>J===A.name)):[],U=I?a.filter(A=>R.has(A.name)&&A.returnType!=="JSX.Element"&&A.returnType!=="React.ReactNode").map(A=>({name:A.name,filePath:A.filePath,description:A.description||"",testFile:A.testFile,feature:A.feature})):[],B=W.length>0||Y.length>0,H=U.length>0,D=B||H;return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-4 space-y-3",children:[n(Av,{items:x,onNavigate:p}),d("div",{children:[n("h2",{className:"text-sm font-semibold text-white m-0 font-['IBM_Plex_Sans'] uppercase tracking-wider",children:u}),(()=>{const A=(E==null?void 0:E.filePath)||(T==null?void 0:T.filePath)||f[u];return A?n(Nr,{filePath:A,projectRoot:o}):null})()]}),$.length>0&&n("div",{className:"grid grid-cols-3 gap-2",children:$.map(A=>n(Hn,{imgSrc:A.screenshotPath?`/api/editor-scenario-image/${A.id}.png`:null,name:A.name,isActive:A.id===i,onSelect:()=>l(A)},A.id))}),T&&(T.scenarios.length>0||T.pendingScenarios.length>0)&&d("div",{className:"grid grid-cols-3 gap-2",children:[T.scenarios.map(A=>n(Hn,{imgSrc:A.screenshotPath?`/api/screenshot/${A.screenshotPath}`:null,name:A.name,isActive:!1,onSelect:()=>c({analysisId:T.analysisId,scenarioId:A.id,scenarioName:A.name,entitySha:T.sha,entityName:T.name})},A.id)),T.pendingScenarios.map(A=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:A,children:A},A))]}),E&&d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] text-gray-500",children:"Tests:"}),n(Nr,{filePath:E.testFile,projectRoot:o})]}),$.length===0&&!T&&!E&&n("div",{className:"text-xs text-gray-500",children:"No scenarios for this entity"}),D&&d("div",{className:"pt-3 mt-2 border-t border-[#3d3d3d] space-y-3",children:[B&&d("div",{children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),W.map(([A,J])=>d("div",{className:"mt-3",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>p(A),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:A})}),J.length>0&&n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:J.map(V=>n(Hn,{imgSrc:V.screenshotPath?`/api/editor-scenario-image/${V.id}.png`:null,name:V.name,isActive:V.id===i,onSelect:()=>l(V)},V.id))})]},A)),Y.map(A=>d("div",{className:"mt-3",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>p(A.name),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:A.name})}),(A.scenarios.length>0||A.pendingScenarios.length>0)&&d("div",{className:"grid grid-cols-3 gap-2 pt-1",children:[A.scenarios.map(J=>n(Hn,{imgSrc:J.screenshotPath?`/api/screenshot/${J.screenshotPath}`:null,name:J.name,isActive:!1,onSelect:()=>c({analysisId:A.analysisId,scenarioId:J.id,scenarioName:J.name,entitySha:A.sha,entityName:A.name})},J.id)),A.pendingScenarios.map(J=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:J,children:J},J))]})]},A.sha))]}),H&&d("div",{children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"}),U.map(A=>d("div",{className:"mt-2",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>p(A.name),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:A.name})}),n(Nr,{filePath:A.filePath,projectRoot:o}),A.testFile&&d("div",{className:"flex items-center gap-1.5 mt-0.5",children:[n("span",{className:"text-[9px] text-gray-600",children:"test:"}),n("span",{className:"text-[9px] text-gray-500 truncate",children:A.testFile})]})]},A.name))]})]})]})})}return n("div",{ref:P,onScroll:S,className:"flex-1 overflow-auto",children:d("div",{className:"p-4 space-y-4",children:[y&&d("div",{children:[n("h2",{className:"text-base font-semibold text-white m-0 font-['IBM_Plex_Sans']",children:y}),g&&n("p",{className:"text-xs text-gray-400 m-0 mt-1 font-['IBM_Plex_Sans'] leading-relaxed",children:g})]}),b.size>0&&d("div",{children:[d("div",{className:"flex items-center justify-between",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),n("button",{onClick:m,className:"px-2.5 py-1 text-[10px] font-medium text-gray-400 bg-[#2a2a2a] border border-[#4d4d4d] rounded hover:bg-[#333] hover:text-white hover:border-[#005c75] transition-colors cursor-pointer",children:"+ New Page"})]}),d("p",{className:"text-[11px] text-gray-500 m-0 mt-1.5 font-['IBM_Plex_Sans'] leading-relaxed",children:["Select a page scenario below and switch to"," ",n("button",{onClick:m,className:"text-[#00a0c4] hover:text-[#00c4eb] bg-transparent border-none p-0 cursor-pointer underline font-inherit text-inherit",children:"Build"})," ","to change or enhance an existing page or"," ",n("button",{onClick:m,className:"text-[#00a0c4] hover:text-[#00c4eb] bg-transparent border-none p-0 cursor-pointer underline font-inherit text-inherit",children:"create a new page"})]}),[...b.entries()].sort(([_],[j])=>_==="Home"?-1:j==="Home"?1:_.localeCompare(j)).map(([_,j])=>d("div",{className:"mt-2",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>p(_),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:_})}),f[_]&&n(Nr,{filePath:f[_],projectRoot:o}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:j.map(T=>n(Hn,{imgSrc:T.screenshotPath?`/api/editor-scenario-image/${T.id}.png`:null,name:T.name,isActive:T.id===i,onSelect:()=>l(T)},T.id))})]},_))]})]})})}const Ci={new:0,edited:1,impacted:2};function Si({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 ki({filePath:e}){const[t,r]=M(null),[s,a]=M(!0),[o,i]=M(null);return ne(()=>{import("react-diff-viewer-continued").then(l=>{i(()=>l.default)})},[]),ne(()=>{a(!0),fetch(`/api/editor-file-diff?path=${encodeURIComponent(e)}`).then(l=>l.json()).then(l=>{r({oldContent:l.oldContent,newContent:l.newContent})}).catch(()=>{r(null)}).finally(()=>a(!1))},[e]),s?n("div",{className:"p-2 text-[10px] text-gray-400",children:"Loading diff..."}):!t||!o?n("div",{className:"p-2 text-[10px] text-gray-400",children:"Could not load diff"}):n("div",{className:"mt-2 border border-gray-200 rounded-lg overflow-hidden max-h-[300px] overflow-auto text-xs",children:n(o,{oldValue:t.oldContent,newValue:t.newContent,splitView:!1,useDarkTheme:!1,showDiffOnly:!0,styles:{contentText:{fontSize:"11px",lineHeight:"1.4"},line:{padding:"1px 8px",fontSize:"11px"}}})})}function Ei({impactedBy:e,changedEntities:t}){return n("div",{className:"mt-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5",children:e&&e.length>0?d(de,{children:[n("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"Re-captured because these dependencies changed"}),n("ul",{className:"mt-1.5 space-y-1",children:e.map(r=>d("li",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold px-1 py-0 rounded-full uppercase tracking-wider border ${r.changeType==="new"?"bg-green-100 text-green-700 border-green-200":"bg-blue-100 text-blue-700 border-blue-200"}`,children:r.changeType==="new"?"New":"Edited"}),n("span",{className:"text-[11px] font-medium text-amber-800",children:r.name}),n("span",{className:"text-[9px] text-amber-500 truncate",children:r.filePath})]},r.filePath))})]}):t&&t.length>0?d(de,{children:[n("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"Unchanged — these entities were modified in this session"}),n("ul",{className:"mt-1.5 space-y-1",children:t.map(r=>d("li",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold px-1 py-0 rounded-full uppercase tracking-wider border ${r.status==="new"?"bg-green-100 text-green-700 border-green-200":"bg-blue-100 text-blue-700 border-blue-200"}`,children:r.status==="new"?"New":"Edited"}),n("span",{className:"text-[11px] font-medium text-amber-800",children:r.name})]},r.name))})]}):n("span",{className:"text-[10px] text-amber-600",children:"This component was re-captured because a dependency changed"})})}function _i({scenarioId:e,name:t,isActive:r,onSelect:s}){const[a,o]=M(!1);return ne(()=>{o(!1)},[e]),d("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 jv({filePath:e}){return e?d("div",{className:"flex items-center gap-1 mt-0.5",children:[d("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-400 hover:text-gray-600 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(jt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-400 hover:text-gray-600 transition-colors"})]}):null}function Mv({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=ao(e);if(s&&!r)return d("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#0ea5e9] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!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(c=>c.fullName.startsWith(t)):r.testCases,i=o.length>0?o:r.testCases;if(i.length===0)return null;const l=t?`${t} > `:"";return d("div",{className:"pt-1 space-y-0.5",children:[i.map(c=>{var u;const m=l&&c.fullName.startsWith(l)?c.fullName.slice(l.length):c.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[c.status==="passed"?n("span",{className:"text-green-600 text-[10px]",children:"✓"}):c.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] ${c.status==="passed"?"text-green-600":c.status==="failed"?"text-red-500":"text-gray-400"}`,children:m})]}),c.status==="failed"&&((u=c.failureMessages)==null?void 0:u.map((p,h)=>n("div",{className:"pl-4 text-[9px] text-red-400 truncate max-w-full",title:p,children:p.split(`
|
|
396
|
-
`)[0]},h)))]},c.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 Ai(e){const t=e.indexOf(" - ");return t!==-1?e.slice(t+3):e}function Pi(e,t){return!t||Object.keys(t).length===0?e:[...e].sort(([r],[s])=>{var l,c;const a=((l=t[r])==null?void 0:l.status)||"impacted",o=((c=t[s])==null?void 0:c.status)||"impacted",i=(Ci[a]??2)-(Ci[o]??2);return i!==0?i:r.localeCompare(s)})}function Tv({scenarios:e,allScenarios:t=[],glossaryFunctions:r=[],projectRoot:s,activeScenarioId:a,onScenarioSelect:o,onClose:i,entityChangeStatus:l={},modifiedFiles:c=[],featureName:m,userPrompt:u}){const p=ae(()=>{if(t.length===0||Object.keys(l).length===0)return e;const S=new Set(e.map(_=>_.id)),k=t.filter(_=>{var T;if(S.has(_.id))return!1;const j=_.componentName||Xe(_.url);return((T=l[j])==null?void 0:T.status)==="impacted"});return k.length===0?e:[...e,...k]},[e,t,l]),h=ae(()=>Object.entries(l).filter(([,S])=>S.status==="new"||S.status==="edited").map(([S,k])=>({name:S,status:k.status})),[l]),[f,y]=M(null),g=ie(S=>{y(k=>k===S?null:S)},[]),{pageGroups:x,componentGroups:b}=ae(()=>{var _;const S=new Map,k=new Map;for(const j of p)if(j.componentName){const T=k.get(j.componentName)||[];T.push(j),k.set(j.componentName,T)}else if(Ha(j.url)){const T=(_=j.url)==null?void 0:_.match(/[?&]c=([^&]+)/),E=T?decodeURIComponent(T[1]):"Isolated",$=k.get(E)||[];$.push(j),k.set(E,$)}else{const T=Xe(j.url),E=S.get(T)||[];E.push(j),S.set(T,E)}return{pageGroups:S,componentGroups:k}},[p]),w=ae(()=>Pi([...x.entries()],l),[x,l]),v=ae(()=>Pi([...b.entries()],l),[b,l]),C=w,P=v,N=ae(()=>Vf(r,l),[r,l]);return p.length===0&&r.length===0?d("div",{className:"h-full bg-white flex items-center justify-center relative",children:[n("button",{onClick:i,className:"absolute top-2 right-3 text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none",title:"Close results",children:"×"}),n("span",{className:"text-sm text-gray-400",children:"No scenarios registered yet"})]}):d("div",{className:"h-full bg-white flex flex-col overflow-hidden",children:[d("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-gray-200 shrink-0",children:[d("div",{className:"min-w-0",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Working Session Results"}),m&&n("div",{className:"text-[11px] text-gray-400 truncate",title:m,children:m})]}),n("button",{onClick:i,className:"text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none shrink-0",title:"Close results",children:"×"})]}),u&&n(Tc,{text:u,theme:"light"}),n("div",{className:"flex-1 overflow-auto p-4",children:d("div",{className:"space-y-5",children:[C.length>0&&d("div",{children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"})}),n("div",{className:"space-y-3 pl-1",children:C.map(([S,k])=>{var E;const _=l[S],j=f===S,T=(E=k[0])==null?void 0:E.componentPath;return d("div",{children:[d("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:S}),_&&n(Si,{status:_,onClick:()=>g(S)})]}),j&&(_==null?void 0:_.status)==="edited"&&T&&n(ki,{filePath:T}),j&&(_==null?void 0:_.status)==="impacted"&&n(Ei,{impactedBy:_.impactedBy,changedEntities:h}),n("div",{className:"flex flex-wrap gap-3",children:k.map($=>n(_i,{scenarioId:$.id,name:Ai($.name),isActive:$.id===a,onSelect:()=>o($)},$.id))})]},S)})})]}),P.length>0&&d("div",{className:C.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),n("div",{className:"space-y-3 pl-1",children:P.map(([S,k])=>{var E;const _=l[S],j=f===S,T=(E=k[0])==null?void 0:E.componentPath;return d("div",{children:[d("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:S}),_&&n(Si,{status:_,onClick:()=>g(S)})]}),j&&(_==null?void 0:_.status)==="edited"&&T&&n(ki,{filePath:T}),j&&(_==null?void 0:_.status)==="impacted"&&n(Ei,{impactedBy:_.impactedBy,changedEntities:h}),n("div",{className:"flex flex-wrap gap-3",children:k.map($=>n(_i,{scenarioId:$.id,name:Ai($.name),isActive:$.id===a,onSelect:()=>o($)},$.id))})]},S)})})]}),N.length>0&&d("div",{className:C.length>0||P.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:N.map(S=>d("div",{children:[n("div",{className:"flex items-center gap-2",children:n("span",{className:"text-[11px] font-medium text-gray-700",children:S.name})}),n(jv,{filePath:S.filePath,projectRoot:s}),S.testFile?n(Mv,{testFile:S.testFile,entityName:S.name}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-400",children:"No test file"})})]},S.name))})]}),c.length>0&&d("div",{className:C.length>0||P.length>0||N.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:d("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:["Modified Files (",c.length,")"]})}),n("div",{className:"space-y-0.5 pl-1 max-h-[200px] overflow-auto",children:c.map(S=>d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold uppercase w-[14px] text-center ${S.status==="added"||S.status==="untracked"?"text-green-600":S.status==="modified"?"text-blue-600":S.status==="renamed"?"text-purple-600":"text-gray-400"}`,children:S.status==="added"||S.status==="untracked"?"A":S.status==="modified"?"M":S.status==="renamed"?"R":"?"}),n("span",{className:"text-[10px] text-gray-500 truncate font-mono",children:S.path})]},S.path))})]})]})})]})}const $v=[{key:"app",label:"App"},{key:"build",label:"Build"},{key:"data",label:"Structure"},{key:"journal",label:"Journal"}];function Iv({activeTab:e,onTabChange:t,buildIdle:r,zoomComponent:s,breadcrumbItems:a,onBreadcrumbNavigate:o,panelLayout:i,onToggleExpand:l}){return d("div",{className:"bg-[#3d3d3d] h-10 flex items-center px-3 gap-3 shrink-0 z-20 border-b border-[#2d2d2d]",children:[d("div",{className:"flex items-center gap-2 shrink-0",children:[n("img",{src:qr,alt:"CodeYam",className:"h-5 brightness-0 invert"}),n("span",{className:"text-white font-medium text-xs whitespace-nowrap",children:"Codeyam Editor"})]}),n("div",{className:"flex-1"}),d("div",{className:"flex items-center gap-2 shrink-0",children:[n("div",{className:"flex items-center gap-0.5 bg-[#4a3232] rounded-lg p-0.5",children:$v.map(c=>d("button",{onClick:()=>t(c.key),className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors cursor-pointer ${e===c.key?"bg-[#7a4444] text-white":"text-gray-300 hover:text-white"}`,children:[c.label,c.key==="build"&&r&&e!=="build"&&n("span",{className:"ml-1 inline-block w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"})]},c.key))}),l&&n("button",{onClick:l,className:"p-1.5 rounded text-gray-400 hover:text-white transition-colors cursor-pointer",title:i==="editor-only"?"Show preview":"Hide preview",children:n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:i==="editor-only"?d(de,{children:[n("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),n("path",{d:"M9 3v18"}),n("path",{d:"M16 15l-3-3 3-3"})]}):d(de,{children:[n("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),n("path",{d:"M9 3v18"}),n("path",{d:"M14 9l3 3-3 3"})]})})})]})]})}function Rv({preview:e,onDismiss:t,onLoadCommit:r}){return d("div",{className:"flex flex-col items-center gap-6 max-w-[700px] w-full",children:[d("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:e.screenshotUrl,alt:e.scenarioName,className:"max-w-full h-auto block"})}),d("div",{className:"flex items-center gap-2 text-sm text-[#666]",children:[e.commitSha&&n("span",{className:"font-mono text-xs text-[#00a0c4] bg-[#00a0c4]/15 px-2 py-0.5 rounded",children:e.commitSha.slice(0,7)}),d("span",{className:"truncate",children:[e.scenarioName,e.commitMessage&&` — ${e.commitMessage}`]})]}),n("div",{className:"flex items-center gap-3",children:e.commitSha&&r&&n(Dv,{commitSha:e.commitSha,onLoadCommit:r})})]})}function Dv({commitSha:e,onLoadCommit:t}){const[r,s]=M(!1),[a,o]=M(null);return d(de,{children:[n("button",{onClick:()=>{s(!0),o(null),t(e).then(i=>{i.success||o(i.error||"Failed to load commit")}).catch(i=>{o(i instanceof Error?i.message:"Network error")}).finally(()=>s(!1))},disabled:r,className:"bg-[#005c75] hover:bg-[#004d63] disabled:opacity-50 text-white text-sm font-medium px-4 py-1.5 rounded transition-colors cursor-pointer",children:r?"Reverting...":"Revert to this code and load this version"}),a&&n("div",{className:"bg-red-50 border border-red-200 rounded px-4 py-2 text-sm text-red-600 w-full text-center",children:a})]})}function Ov({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,onStateChange:o}){const{interactiveServerUrl:i,isStarting:l,isLoading:c}=pn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:!0});return ne(()=>{o(i,l||c)},[i,l,c,o]),null}function Lv(e,t){return t.status==="error"?{url:null,proxyUrl:null,isStarting:!1,error:t.errorMessage||"Dev server crashed",canStartServer:e.canStartServer,autoStartAttempted:e.autoStartAttempted,shouldAutoStart:!1}:t.url?{url:t.url,proxyUrl:t.proxyUrl||null,isStarting:!1,error:null,canStartServer:!0,autoStartAttempted:e.autoStartAttempted,shouldAutoStart:!1}:t.status==="starting"?{...e,isStarting:!0,error:null,canStartServer:!0,shouldAutoStart:!1}:t.status==="stopped"?e.url?{...e,url:null,isStarting:!1,shouldAutoStart:!1}:e.autoStartAttempted?{...e,isStarting:!1,shouldAutoStart:!1}:{...e,autoStartAttempted:!0,shouldAutoStart:!0}:{...e,shouldAutoStart:!1}}function Fv(){const[e,t]=M({url:null,proxyUrl:null,isStarting:!1,error:null,canStartServer:!0,autoStartAttempted:!1}),r=ve(e);r.current=e,ne(()=>{let o=!1,i=null;const l=async()=>{try{const c=await fetch("/api/editor-dev-server");if(o)return;const m=await c.json(),u=Lv(r.current,m),{shouldAutoStart:p,...h}=u;if(t(h),p)try{const f=await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})});if(o)return;f.ok?t(y=>({...y,isStarting:!0})):t(y=>({...y,canStartServer:!1}))}catch{}}catch{}};return l(),i=setInterval(()=>void l(),2e3),()=>{o=!0,i&&clearInterval(i)}},[e.url]);const s=ie(()=>{t(o=>({...o,error:null,isStarting:!0})),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})}).catch(()=>{})},[]),a=ie(()=>{t(o=>({...o,error:null,isStarting:!0})),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}).catch(()=>{})},[]);return{devServerUrl:e.url,proxyUrl:e.proxyUrl,isStarting:e.isStarting,error:e.error,canStartServer:e.canStartServer,retryServer:s,startServer:a}}function zv(e){return e.filter(t=>t.testFile&&t.returnType!=="JSX.Element"&&t.returnType!=="React.ReactNode").map(t=>({name:t.name,filePath:t.filePath,description:t.description||"",testFile:t.testFile,feature:t.feature}))}function ji(e,t){var r,s,a,o,i;return t?!!((r=e.metadata)!=null&&r.executionResult):!!((a=(s=e.metadata)==null?void 0:s.screenshotPaths)!=null&&a[0])&&!((o=e.metadata)!=null&&o.noScreenshotSaved)&&!((i=e.metadata)!=null&&i.sameAsDefault)}function Bv(e,t){return e.filter(r=>r.analyses&&r.analyses.length>0).map(r=>{var p;const s=r.analyses[0],a=s.scenarios||[],o=!((p=s.status)!=null&&p.finishedAt),i=r.entityType||"visual",l=i==="library"||i==="functionCall",c=a.filter(h=>ji(h,l)),m=a.filter(h=>!ji(h,l)),u=t.find(h=>h.filePath===(r.filePath||""));return{sha:r.sha,name:r.name,entityType:i,filePath:r.filePath||"",analysisId:s.id,isAnalyzing:o,scenarioCount:a.length,scenarios:c.map(h=>{var f,y;return{id:h.id,name:h.name,description:h.description||"",screenshotPath:((y=(f=h.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||null}}),pendingScenarios:m.map(h=>h.name),testFile:u==null?void 0:u.testFile}})}function Yv(e,t){var s;const r={};for(const a of e){const i=(((s=a.metadata)==null?void 0:s.importedExports)||[]).map(l=>l.name).filter(l=>t.has(l));i.length>0&&(r[a.name]=i)}return r}function Uv(e,t,r){const s={...e},a=new Map;for(const o of r)o.filePath&&a.set(o.filePath,o.name);for(const[o,i]of Object.entries(t)){if(s[o])continue;const l=a.get(i);l&&s[l]&&(s[o]=s[l])}return s}const Wv=()=>[{title:"Editor - CodeYam"},{name:"description",content:"CodeYam Code + Data Editor"}];async function Hv({request:e}){var P;const t=await Ie();let r=!1,s=[],a=[];if(t){const{project:N}=await Re(t);r=((P=N.metadata)==null?void 0:P.editorMode)??!1;try{const S=je();for(const E of["component_name","component_path","screenshot_path","url","viewport_width","viewport_height"])try{await S.schema.alterTable("editor_scenarios").addColumn(E,"varchar").execute()}catch{}const k=await S.selectFrom("editor_scenarios").selectAll().where("project_id","=",N.id).orderBy("created_at","asc").execute(),_=E=>({id:E.id,name:E.name,description:E.description||"",componentName:E.component_name||null,componentPath:E.component_path||null,screenshotPath:E.screenshot_path||null,url:E.url||null,type:E.type||null,viewportWidth:E.viewport_width||null,viewportHeight:E.viewport_height||null,dimension:E.dimension||null});a=yt(k,E=>`${E.name}::${E.url||"/"}`).map(_);const j=he()||process.cwd(),T=rg(j);if(T){const E=La(T),$=k.filter(R=>R.created_at>=E);s=yt($,R=>`${R.name}::${R.url||"/"}`).map(_)}else s=a}catch{}}const o=[...new Set(a.map(N=>N.componentName).filter(N=>N!==null))];let i=[];try{const N=he()||process.cwd(),S=F.join(N,".codeyam","glossary.json");if(K.existsSync(S)){const k=K.readFileSync(S,"utf8");i=JSON.parse(k)}}catch{}const l=zv(i);let c=[];try{const N=await mn()||[];c=Bv(N,i)}catch{}let m=[];try{if(c.length>0){const N=c.map(S=>S.sha);await ze(),m=await st({shas:N})||[]}}catch{}let u={};try{if(m.length>0){const N=new Set([...c.map(S=>S.name),...o,...i.map(S=>S.name)]);u=Yv(m,N)}}catch{}let p={};try{const N=he()||process.cwd();p=scanPageFilePaths(N)}catch{}Object.keys(p).length>0&&m.length>0&&(u=Uv(u,p,m));let h={};try{h=(await or({projectRoot:he()||process.cwd(),scenarioInputs:a,glossaryInputs:l})).entityChangeStatus}catch{}let f=[];try{f=jn().filter(S=>S.status!=="deleted").map(S=>({path:S.path,status:S.status}))}catch{}const y=he()||process.cwd(),g=nc(y),x=rc(y);let b=null,w=null,v=null,C=null;try{const N=F.join(y,".codeyam","config.json");if(K.existsSync(N)){const S=JSON.parse(K.readFileSync(N,"utf8"));b=S.projectTitle||null,w=S.projectDescription||null,v=S.defaultScreenSize||null,C=S.screenSizes||null}}catch{}return Q({projectSlug:t,projectRoot:he(),hasProject:!!t,editorMode:r,scenarios:s,allScenarios:a,components:o,analyzedEntities:c,glossaryFunctions:l,glossaryEntries:i,entityImports:u,pageFilePaths:p,entityChangeStatus:h,modifiedFiles:f,featureName:g,userPrompt:x,projectTitle:b,projectDescription:w,defaultScreenSize:v,screenSizes:C})}class Jv extends ed{constructor(){super(...arguments);zn(this,"state",{error:null,errorInfo:null})}static getDerivedStateFromError(r){return{error:r,errorInfo:null}}componentDidCatch(r,s){console.error("[EditorErrorBoundary] Error:",r.message),console.error("[EditorErrorBoundary] Component stack:",s.componentStack),console.error("[EditorErrorBoundary] Loader snapshot:",JSON.stringify(this.props.loaderSnapshot,null,2)),this.setState({errorInfo:s})}render(){var r;return this.state.error?n("div",{className:"fixed inset-0 bg-[#1e1e1e] flex items-center justify-center p-8",children:d("div",{className:"max-w-[600px] w-full space-y-4",children:[n("h2",{className:"text-lg font-semibold text-red-400 font-['IBM_Plex_Sans'] m-0",children:"Something went wrong"}),n("pre",{className:"text-xs text-gray-300 bg-[#2d2d2d] p-3 rounded overflow-auto max-h-[120px]",children:this.state.error.message}),((r=this.state.errorInfo)==null?void 0:r.componentStack)&&d("details",{className:"text-xs text-gray-500",children:[n("summary",{className:"cursor-pointer hover:text-gray-300 transition-colors",children:"Component stack"}),n("pre",{className:"mt-2 bg-[#2d2d2d] p-3 rounded overflow-auto max-h-[200px] text-yellow-300",children:this.state.errorInfo.componentStack})]}),n("p",{className:"text-xs text-gray-500 m-0",children:"Full diagnostics are in the browser console."}),n("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 bg-[#005c75] text-white text-sm rounded hover:bg-[#004d63] transition-colors cursor-pointer",children:"Reload"})]})}):this.props.children}}const Mi=[{name:"Desktop",width:1440,height:900},{name:"Laptop",width:1024,height:768},{name:"Tablet",width:768,height:1024},{name:"Mobile",width:375,height:667}],Vv=Je(function(){const{projectSlug:t,projectRoot:r,hasProject:s,scenarios:a,allScenarios:o,analyzedEntities:i,glossaryFunctions:l,glossaryEntries:c,entityImports:m,pageFilePaths:u,entityChangeStatus:p,modifiedFiles:h,featureName:f,userPrompt:y,projectTitle:g,projectDescription:x,defaultScreenSize:b,screenSizes:w}=qe(),[v,C]=Cn(),P=ve(null),N=ve(null),S=ve(null),k=v.get("zoom")||void 0,_=v.get("scenario")||void 0,[j,T]=M(()=>{if(typeof window>"u")return[];const te=new URLSearchParams(window.location.search).get("zoom");return te?[te]:[]}),E=ve(null);ne(()=>{if(!_h(_,E.current))return;const te=o.find(Pe=>Pe.id===_);if(!te)return;E.current=_;const be=Ct(te.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:be,scenarioId:te.id,scenarioName:te.name,scenarioType:te.type})}).catch(()=>{})},[_,o]),ne(()=>{const te=new BroadcastChannel("codeyam-editor");return te.onmessage=be=>{var Pe;if(((Pe=be.data)==null?void 0:Pe.type)==="switch-scenario"&&be.data.scenarioId){const Oe=be.data.scenarioId,He=o.find(gn=>gn.id===Oe);if(!He)return;E.current=Oe;const It=new URLSearchParams(v);It.set("scenario",Oe),It.delete("zoom"),C(It),J(null),q(null),z(null),bt(!0);const lr=Ct(He.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:lr,scenarioId:Oe,scenarioType:He.type})}).then(()=>{Qe(gn=>gn+1)}).catch(()=>{bt(!1)})}},()=>te.close()},[v,C,o]),ne(()=>{if(v.get("ref")!=="link"||!_)return;const te=new BroadcastChannel("codeyam-editor");te.postMessage({type:"switch-scenario",scenarioId:_}),te.close(),window.close()},[]);const{devServerUrl:$,proxyUrl:R,isStarting:I,error:W,canStartServer:Y,retryServer:U,startServer:B}=Fv(),[H,D]=M(!1),[A,J]=M(null),[V,q]=M(null),[X,L]=M(!1),[O,z]=M(null),G=ie(async te=>{const Pe=await(await fetch("/api/editor-load-commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commitSha:te})})).json();return Pe.success&&(z(null),D(!1)),Pe},[]),ee=ie((te,be)=>{q(Pe=>(te&&te!==Pe&&D(!1),te)),!be&&te&&D(!0),L(be)},[]),re=ie(te=>{z(null),J(Pe=>(Pe&&Pe.analysisId===te.analysisId||(q(null),Qe(He=>He+1)),te)),L(!0),D(!1);const be=new URLSearchParams(v);be.delete("scenario"),be.delete("zoom"),C(be)},[v,C]),[ue,se]=M(b?{name:b.name,width:b.width,height:b.height}:{name:"Desktop",width:1440,height:900}),[pe,Ce]=M(!1),[_e,Ae]=M("app"),De=ie(()=>{Ae("build"),Se(!0)},[]),[Le,Se]=M(!1),[oe,xe]=M(!1),ke=ie(te=>{xe(te)},[]),[et,ge]=M("split"),[Ye,We]=M(!1),Ht=ie(()=>{We(!0),Ae("build"),Se(!0)},[]),bs=ie(()=>{We(!1)},[]),uo=ie(te=>{se(te),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:te,skipBroadcast:!0})})},[]),[Mn,Tt]=M(!1),Jt=ie(()=>{if(Mn){Tt(!1);return}typeof Notification<"u"&&Notification.permission==="default"?Notification.requestPermission().then(te=>{te==="granted"&&Tt(!0)}):Tt(!0)},[Mn]);ne(()=>{if(_e==="build"){xe(!1);const te=setTimeout(()=>{var be,Pe;(be=P.current)==null||be.scrollToBottom(),(Pe=P.current)==null||Pe.focus()},50);return()=>clearTimeout(te)}},[_e]);const[hn,Tn]=M(null);ne(()=>{const te=S.current;if(!te)return;const be=new ResizeObserver(Pe=>{const Oe=Pe[0];Oe&&Tn({width:Oe.contentRect.width,height:Oe.contentRect.height})});return be.observe(te),()=>be.disconnect()},[]);const $t=ae(()=>hn?Ah(hn,ue):1,[hn,ue]),[Vt,Qe]=M(0),[mt,Ve]=M(null),[Ge,bt]=M(!1),$n=ie((te,be)=>{if(Ve(te||null),be){const Pe=new URLSearchParams(v);Pe.set("scenario",be),E.current=be,C(Pe)}z(null),Qe(Pe=>Pe+1)},[v,C]),{customSizes:In,addCustomSize:ws}=cs(t),Rn=ae(()=>[...w?Object.entries(w).map(([be,Pe])=>({name:be,width:Pe.width,height:Pe.height})):Mi,...In],[w,In]),Dn=ae(()=>{const te=[{name:"App"}];for(const be of j)te.push({name:be,componentName:be});return te},[j]),On=ie(te=>{const be=new URLSearchParams(v);if(te){be.set("zoom",te);const Pe=j.indexOf(te);Pe>=0?T(j.slice(0,Pe+1)):T([...j,te]);const Oe=o.find(He=>He.componentName===te||He.componentName===null&&Xe(He.url)===te);if(Oe){be.set("scenario",Oe.id),E.current=Oe.id,bt(!0);const He=Ct(Oe.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:He,scenarioId:Oe.id,scenarioType:Oe.type})}).then(()=>{Qe(It=>It+1)}).catch(()=>{bt(!1)})}else be.delete("scenario")}else be.delete("zoom"),be.delete("scenario"),T([]);C(be)},[v,C,o,j]),Gt=ie(te=>{if(J(null),q(null),z(null),Ve(null),te.viewportWidth&&te.viewportHeight){const Oe=Rn.find(He=>He.width===te.viewportWidth&&He.height===te.viewportHeight);se({name:(Oe==null?void 0:Oe.name)||"Custom",width:te.viewportWidth,height:te.viewportHeight})}E.current=te.id;const be=new URLSearchParams(v);be.set("scenario",te.id),C(be),bt(!0);const Pe=Ct(te.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Pe,scenarioId:te.id,scenarioType:te.type,skipBroadcast:!0})}).then(()=>{Qe(Oe=>Oe+1)}).catch(()=>{bt(!1)})},[v,C,Rn]),vs=ie(te=>{if(!te.commitSha){const be=o.find(Pe=>Pe.name===te.scenarioName);if(be){Gt(be);return}}z(te)},[o,Gt]),Ns=te=>{const be={name:te.name,width:te.width,height:te.height};se(be),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:be,skipBroadcast:!0})})},Cs=te=>{ws(te,ue.width,ue.height??900),Ce(!1),se(be=>({...be,name:te}))},Ss=()=>{A||D(!0),bt(!1)},Kt=ae(()=>Eh({activeAnalyzedScenario:!!A,analyzedPreviewUrl:V,activeScenarioId:_||null,scenarios:o,proxyUrl:R,devServerUrl:$,zoomComponent:k||null}),[R,$,k,_,o,A,V]),fn=ae(()=>{const te=Pl(Kt,mt);if(!te)return null;const be=te.includes("?")?"&":"?";return`${te}${be}__cb=${Vt}`},[Kt,mt,Vt]),ks=ae(()=>({projectSlug:t,hasProject:s,scenarioCount:a==null?void 0:a.length,allScenarioCount:o==null?void 0:o.length,analyzedEntityCount:i==null?void 0:i.length,glossaryFunctionCount:l==null?void 0:l.length,entityChangeStatusKeys:p?Object.keys(p):[],featureName:f}),[t,s,a,o,i,l,p,f]);return n(Jv,{loaderSnapshot:ks,children:d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[A&&n(Ov,{analysisId:A.analysisId,scenarioId:A.scenarioId,scenarioName:A.scenarioName,entityName:A.entityName,projectSlug:t,onStateChange:ee},A.analysisId),d("div",{className:"flex-1 flex min-h-0",children:[d("div",{className:"flex-1 flex flex-col min-w-0",style:et==="editor-only"?{display:"none"}:void 0,children:[d("div",{className:"bg-[#2d2d2d] border-b border-[#3d3d3d] shrink-0 z-10 h-10 flex items-center px-4 gap-1",children:[n("button",{onClick:()=>ge(te=>te==="preview-only"?"split":"preview-only"),className:"p-1.5 rounded text-gray-500 hover:text-gray-300 transition-colors cursor-pointer shrink-0",title:et==="preview-only"?"Show sidebar":"Hide sidebar",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),n("path",{d:"M9 3v18"})]})}),n("div",{className:"w-px h-4 bg-[#3d3d3d] mx-1"}),d("div",{className:"flex-1 flex items-center justify-center gap-1",children:[Mi.map(te=>d("button",{onClick:()=>Ns(te),className:`p-1.5 rounded transition-colors cursor-pointer ${ue.name===te.name?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:`${te.name} (${te.width}×${te.height})`,children:[te.name==="Desktop"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n("path",{d:"M8 21h8M12 17v4"})]}),te.name==="Laptop"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8H4V6z"}),n("path",{d:"M2 18h20"})]}),te.name==="Tablet"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]}),te.name==="Mobile"&&d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"7",y:"2",width:"10",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]})]},te.name)),n("button",{onClick:()=>Ce(!0),className:`p-1.5 rounded transition-colors cursor-pointer ${ue.name==="Custom"?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:"Custom dimensions",children:n("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),n("div",{className:"w-px h-4 bg-[#3d3d3d] mx-1"}),d("span",{className:"text-gray-400 text-xs font-mono",children:[ue.width," × ",ue.height??900]}),n("div",{className:"w-px h-4 bg-[#3d3d3d] mx-1"}),n("button",{onClick:()=>{const te=fn||Kt;te&&window.open(te,"_blank")},className:"p-1.5 rounded text-gray-500 hover:text-gray-300 transition-colors cursor-pointer",title:"Open preview in new window",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),n("polyline",{points:"15 3 21 3 21 9"}),n("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})})]})]}),n("div",{ref:S,className:"flex-1 flex items-center justify-center overflow-hidden p-8",style:O?{backgroundColor:"#f5f0e8",backgroundImage:"repeating-linear-gradient(0deg, transparent, transparent 19px, #e8e0d0 19px, #e8e0d0 20px), repeating-linear-gradient(90deg, transparent, transparent 19px, #e8e0d0 19px, #e8e0d0 20px)"}:{backgroundImage:`
|
|
397
|
-
linear-gradient(45deg, #333 25%, transparent 25%),
|
|
398
|
-
linear-gradient(-45deg, #333 25%, transparent 25%),
|
|
399
|
-
linear-gradient(45deg, transparent 75%, #333 75%),
|
|
400
|
-
linear-gradient(-45deg, transparent 75%, #333 75%)
|
|
401
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#2d2d2d"},children:O?n(Rv,{preview:O,onDismiss:()=>z(null),onLoadCommit:G}):Kt?n("div",{style:{width:`${ue.width*$t}px`,height:`${(ue.height??900)*$t}px`},children:d("div",{className:"relative bg-white origin-top-left",style:{width:`${ue.width}px`,height:`${ue.height??900}px`,transform:$t<1?`scale(${$t})`:void 0},children:[!H&&!Ge&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-[#2a2a2a] rounded-lg p-8 w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the app to render"})]})]})}),Ge&&n("div",{className:"absolute inset-0 z-20 flex items-center justify-center",style:{backgroundColor:"rgba(0, 0, 0, 0.25)",backdropFilter:"blur(1px)",transition:"opacity 200ms ease-out"},children:d("div",{className:"flex flex-col items-center gap-3 animate-pulse",children:[n("svg",{className:"w-6 h-6 text-white/80 animate-spin",viewBox:"0 0 24 24",fill:"none",children:n("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"50 100"})}),n("span",{className:"text-white/70 text-xs font-['IBM_Plex_Sans']",children:"Switching scenario"})]})}),n("iframe",{ref:N,src:fn||Kt,className:"w-full h-full border-none",title:"Editor preview",onLoad:Ss,style:{opacity:H?1:0}},Vt)]})}):n("div",{className:"bg-[#2a2a2a] rounded-lg flex flex-col items-center justify-center",style:{width:`${ue.width*$t}px`,height:`${(ue.height??900)*$t}px`},children:W?d("div",{className:"flex flex-col gap-4 text-center px-8 max-w-[600px]",children:[n("h2",{className:"text-xl font-medium text-red-400 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Dev Server Failed"}),n("pre",{className:"text-xs text-left bg-[#1e1e1e] text-gray-300 p-4 rounded overflow-auto max-h-[300px] w-full font-mono whitespace-pre-wrap",children:W}),n("button",{onClick:U,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"})]}):I||X?d(de,{children:[n("div",{className:"mb-4",children:n(Bt,{})}),d("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:X?"Starting Interactive Mode":"Starting Dev Server"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:X?"Loading component preview...":"Your dev server is starting up..."})]})]}):d("div",{className:"flex flex-col gap-3 text-center px-8",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Live Preview"}),n("p",{className:"text-sm text-gray-500 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Describe what you want to build in the Build tab"})]})})})]}),d("aside",{className:`bg-[#1e1e1e] border-r border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden order-first ${et==="editor-only"?"w-full max-w-none min-w-0":"w-[50%] min-w-[400px] max-w-[800px]"}`,style:et==="preview-only"?{display:"none"}:void 0,children:[n(Iv,{activeTab:_e,onTabChange:te=>{Ae(te),te==="build"&&Se(!0)},buildIdle:oe,zoomComponent:k,breadcrumbItems:Dn,onBreadcrumbNavigate:On,panelLayout:et,onToggleExpand:()=>ge(te=>te==="editor-only"?"split":"editor-only")}),d("div",{className:"flex-1 overflow-hidden relative",children:[Le&&d("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:_e==="build"?"visible":"hidden"},children:[n("div",{className:Ye?"flex-1 min-h-0":"flex-1",style:Ye?{flex:"1 1 50%"}:void 0,children:n(Al,{ref:P,entityName:"Editor",projectSlug:t,entityFilePath:null,scenarioName:null,onRefreshPreview:$n,onShowResults:Ht,onHideResults:bs,onSetViewport:uo,editorMode:!0,onIdleChange:ke,notificationsEnabled:Mn})}),Ye&&n("div",{style:{flex:"1 1 50%"},className:"min-h-0 border-t-2 border-gray-300",children:n(Tv,{scenarios:a,allScenarios:o,glossaryFunctions:l,projectRoot:r,activeScenarioId:_,onScenarioSelect:Gt,onClose:bs,entityChangeStatus:p,modifiedFiles:h,featureName:f,userPrompt:y})})]}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:_e==="app"?"visible":"hidden"},children:n(Pv,{hasProject:s,scenarios:o,analyzedEntities:i,glossaryFunctions:l,glossaryEntries:c,projectRoot:r,activeScenarioId:_,onScenarioSelect:Gt,onAnalyzedScenarioSelect:re,onSwitchToBuild:De,zoomComponent:k,onZoomChange:On,entityImports:m,pageFilePaths:u,projectTitle:g,projectDescription:x,breadcrumbItems:Dn})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:_e==="data"?"visible":"hidden"},children:n(yv,{scenarios:o,projectRoot:r,activeScenarioId:_,onScenarioSelect:Gt,zoomComponent:k,onZoomChange:On,analyzedEntities:[],glossaryFunctions:l,activeAnalyzedScenarioId:A==null?void 0:A.scenarioId,onAnalyzedScenarioSelect:re,entityImports:m,pageFilePaths:u})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:_e==="journal"?"visible":"hidden"},children:n(Ev,{isActive:_e==="journal",onScreenshotClick:vs,glossaryFunctions:l})})]}),n(_l,{serverUrl:$,isStarting:I,projectSlug:t,devServerError:W,onStartServer:Y?B:void 0,notificationsEnabled:Mn,onToggleNotifications:Jt})]})]}),pe&&n(ls,{width:ue.width,height:ue.height??900,onSave:Cs,onCancel:()=>Ce(!1)})]})})}),Gv=Object.freeze(Object.defineProperty({__proto__:null,default:Vv,loader:Hv,meta:Wv},Symbol.toStringTag,{value:"Module"}));function $c({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(tu,{remarkPlugins:[nu],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(de,{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 Ic(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 Rc(e){let t=e.memories.length;for(const r of e.children.values())t+=Rc(r);return t}function xs(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 Qn(e){return Math.round(e/3.5)}function bn(e){const t=new Date(e),r=new Date;if(t.toDateString()===r.toDateString()){const c=r.getTime()-t.getTime(),m=Math.floor(c/(1e3*60)),u=Math.floor(c/(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(),l=r.getFullYear();return i===l?`${a} ${o}`:`${a} ${o}, ${i}`}function Kv({rule:e,onEdit:t,onDelete:r,onView:s,isReviewed:a,onToggleReviewed:o,changeType:i,isUncommitted:l,changeDate:c,diff:m,isFadingOut:u,showLeftBorder:p}){const[h,f]=M(!1),[y,g]=M(!1),x=ae(()=>xs(e.body,e.filePath),[e.body,e.filePath]),b=Qn(e.body.length),w=h?"#3e3e3e":l?"#d97706":"#c7c7c7",v=`rounded-lg border overflow-hidden transition-all ease-in-out ${l?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,C={...u&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return d("div",{className:v,style:C,children:[n("div",{className:`p-4 cursor-pointer ${l?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>s?s(e):f(!h),children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:h?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:w})})}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:l?"#78350f":"#000"},children:x}),i&&n("span",{className:`px-2 py-0.5 rounded uppercase font-medium tracking-wider ${i==="deleted"?"bg-red-100 text-red-700":""}`,style:{fontSize:"10px",...i==="added"&&{backgroundColor:"#CBF3FA",color:"#005C75"},...i==="modified"&&{backgroundColor:"#FFE8C1",color:"#C67E06"}},children:i}),l&&n("span",{className:"px-2 py-0.5 bg-amber-200 text-amber-800 rounded font-medium uppercase tracking-wider",style:{fontSize:"10px"},children:"Uncommitted"}),d("span",{className:"text-xs text-gray-400",children:["~",b.toLocaleString()," tokens"]})]}),n("div",{className:"flex items-center gap-2 text-xs text-gray-500 flex-wrap",children:e.frontmatter.paths&&e.frontmatter.paths.length>0&&d(de,{children:[e.frontmatter.paths.slice(0,2).map((P,N)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:P},N)),e.frontmatter.paths.length>2&&d("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-2," more"]})]})})]})]}),d("div",{className:"flex items-center gap-3 flex-shrink-0",children:[c&&n("span",{className:"text-xs text-gray-400",children:bn(c)}),o&&n("button",{onClick:P=>{P.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"})})})]})]})}),h&&d("div",{className:`border-t ${l?"border-amber-200":"border-gray-100"}`,children:[d("div",{className:`px-4 py-3 flex items-center justify-between ${l?"bg-amber-50":"bg-white"}`,children:[n("div",{className:"flex items-center gap-2",children:i==="modified"&&m&&d("button",{onClick:P=>{P.stopPropagation(),g(!y)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${y?l?"bg-amber-200 text-amber-900":"bg-gray-200 text-gray-900":l?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(jr,{className:"w-3 h-3"}),y?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&d("div",{className:"flex items-center gap-2",children:[d("button",{onClick:P=>{P.stopPropagation(),t(e)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${l?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(Ed,{className:"w-3 h-3"}),"Edit"]}),d("button",{onClick:P=>{P.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(_d,{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(`
|
|
402
|
-
`).map((P,N)=>{let S="";return P.startsWith("+")&&!P.startsWith("+++")?S="text-green-400":P.startsWith("-")&&!P.startsWith("---")?S="text-red-400":P.startsWith("@@")&&(S="text-cyan-400"),n("div",{className:S,children:P},N)})}),d("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Edit with Claude:"}),d("div",{className:"flex items-center gap-2",children:[d("span",{className:"px-2 py-1 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:["Claude, can you help me edit this rule: `",e.filePath,"`"]}),n(jt,{content:`Claude, can you help me edit this rule: \`${e.filePath}\``,icon:!0,iconSize:14,className:"p-1 text-gray-400 hover:text-gray-600 rounded transition-colors"})]})]}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&d("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Applies to paths:"}),n("div",{className:"flex flex-wrap gap-1.5",children:e.frontmatter.paths.map((P,N)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:P},N))})]}),!y&&n("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[500px] overflow-auto bg-white border-gray-200",children:n($c,{content:e.body})})]})]})}function qv(){return new Date().toISOString().split(".")[0]+"",`---
|
|
403
|
-
paths:
|
|
404
|
-
- '**/*.ts'
|
|
405
|
-
---
|
|
406
|
-
|
|
407
|
-
## Title
|
|
408
|
-
|
|
409
|
-
Description here.
|
|
410
|
-
`}function Qv({rule:e,onSave:t,onCancel:r}){const[s,a]=M(e?`.claude/rules/${e.filePath}`:""),[o,i]=M((e==null?void 0:e.content)||qv()),[l,c]=M(!!e),[m,u]=M(!1),p=!e;return d("div",{className:"p-6",children:[d("div",{className:"flex items-center justify-between mb-4",children:[n("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),n("button",{onClick:r,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Sn,{className:"w-5 h-5"})})]}),p&&d("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:d("div",{className:"flex items-start gap-3",children:[n(jr,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),d("div",{children:[n("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),n("p",{className:"text-sm text-[#0369a1] mb-2",children:"Run this command in Claude Code to create a properly formatted rule with the right file location and paths:"}),d("div",{className:"relative",children:[n("code",{className:"block bg-white px-3 py-2 pr-9 rounded border border-[#bae6fd] font-mono text-sm text-[#0c4a6e]",children:"/codeyam-new-rule"}),n("button",{onClick:()=>{navigator.clipboard.writeText("/codeyam-new-rule"),u(!0),setTimeout(()=>u(!1),2e3)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[#0284c7] hover:text-[#0c4a6e] cursor-pointer transition-colors",title:"Copy command",children:m?n(ut,{className:"w-4 h-4 text-green-500"}):n(ft,{className:"w-4 h-4"})})]})]})]})}),d("button",{onClick:()=>c(!l),className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:l?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:l?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(l||!p)&&d("div",{className:"space-y-4",children:[d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),d("div",{className:"relative",children:[n("input",{type:"text",value:s,onChange:h=>a(h.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(ft,{className:"w-4 h-4"})})]})]}),e&&d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ask Claude for help editing:"}),d("div",{className:"relative",children:[n("input",{type:"text",value:`Claude, can you help me edit the rule: \`${s}\``,readOnly:!0,className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md bg-gray-50 font-mono text-sm text-gray-600"}),n("button",{onClick:()=>{navigator.clipboard.writeText(`Claude, can you help me edit the rule: \`${s}\``)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy prompt",children:n(ft,{className:"w-4 h-4"})})]})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:o,onChange:h=>i(h.target.value),rows:20,className:"w-full px-3 py-2 border border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm bg-gray-900 text-gray-100 [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-track]:bg-gray-800 [&::-webkit-scrollbar-thumb]:bg-gray-600 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:hover:bg-gray-500 [&::-webkit-resizer]:bg-gray-700"})]}),d("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-[#001f3f] hover:text-[#001530] rounded-md cursor-pointer font-mono uppercase text-xs font-semibold",children:"Cancel"}),n("button",{onClick:()=>t(s.replace(/^\.claude\/rules\//,""),o),disabled:!s.trim()||!o.trim(),className:"px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer font-mono uppercase text-xs font-semibold",children:"Save"})]})]})]})}function Zv({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:s,onToggleFolder:a}){const o=ae(()=>Ic(e),[e]),i=(m,u,p)=>{if(m.target.closest(".chevron-toggle")){p&&a(u||"root");return}const f=u||null;r(t===f?null:f),p&&!s.has(u||"root")&&a(u||"root")},l=m=>{r(t===m?null:m)},c=(m,u=0)=>{const p=s.has(m.path||"root"),h=Rc(m),f=m.children.size>0,y=m.name==="root"?"(root)":m.name,g=m.memories.length>0||f,x=m.path||"",b=t===x||t===null&&x==="";return d("div",{children:[d("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${b?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${u*12+8}px`},onClick:w=>i(w,m.path,g),children:[g&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:w=>{w.stopPropagation(),a(m.path||"root")},children:n(Yt,{className:`w-3 h-3 text-gray-500 transition-transform ${p?"rotate-90":""}`})}),!g&&n("div",{className:"w-3"}),n(Ui,{className:"w-3.5 h-3.5 text-[#005C75]"}),n("span",{className:`text-xs font-mono font-semibold ${b?"text-[#005C75]":""}`,style:{color:"#005C75"},children:y}),d("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[h," rules"]})]}),p&&d("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(w=>{var C;const v=t===w.filePath;return n("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${v?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>l(w.filePath),children:n("span",{className:"text-xs",children:(C=w.filePath.split("/").pop())==null?void 0:C.replace(".md","")})},w.filePath)})}),f&&n("div",{children:Array.from(m.children.values()).sort((w,v)=>w.name.localeCompare(v.name)).map(w=>c(w,u+1))})]})]},m.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:c(o)})}function Xv({memories:e,onEdit:t,onDelete:r,expandedFolders:s,onToggleFolder:a,reviewedStatus:o,onMarkReviewed:i,onMarkUnreviewed:l,onViewRule:c}){const[m,u]=M({});ne(()=>{u({})},[o]);const p=ae(()=>({...o,...m}),[o,m]),h=ae(()=>Ic(e),[e]),f=(g,x,b)=>{u(w=>({...w,[g]:!b})),b?l(g):i(g,x)},y=(g,x=0)=>{const b=s.has(g.path||"root"),w=g.children.size>0,v=g.name==="root"?"root":g.name,C=g.memories.length>0||w;return d("div",{children:[d("div",{className:"flex items-center gap-2 py-2 cursor-pointer hover:bg-gray-50 rounded px-2 mb-2",style:{backgroundColor:"rgba(224, 233, 236, 0.5)"},onClick:()=>C&&a(g.path||"root"),children:[C&&n(Yt,{className:`w-4 h-4 text-gray-500 transition-transform ${b?"rotate-90":""}`}),!C&&n("div",{className:"w-4"}),n(Ui,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:v})]}),b&&d("div",{className:"ml-10 space-y-4 relative",children:[(g.memories.length>0||w)&&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(P=>n(Kv,{rule:P,onEdit:t,onDelete:r,onView:c,isReviewed:p[P.filePath]??!1,onToggleReviewed:f},P.filePath))}),w&&n("div",{className:"space-y-4",children:Array.from(g.children.values()).sort((P,N)=>P.name.localeCompare(N.name)).map(P=>y(P,x+1))})]})]},g.path||"root")};return n("div",{children:y(h)})}function eN({memories:e,reviewedStatus:t,onViewRule:r,refreshKey:s}){const[a,o]=M("unreviewed"),[i,l]=M("by-date"),[c,m]=M(null),[u,p]=M(!0),[h,f]=M(new Map),y=ve(t),g=ve([]);ne(()=>()=>{g.current.forEach(clearTimeout)},[]),ne(()=>{(async()=>{p(!0);try{const N=await(await fetch("/api/memory?action=rule-coverage")).json();m(N.coverage??null)}catch{m(null)}finally{p(!1)}})()},[s]),ne(()=>{const C=y.current,P=[];for(const[N,S]of Object.entries(t))S&&!C[N]&&P.push(N);y.current=t,P.length!==0&&(f(N=>{const S=new Map(N);return P.forEach(k=>S.set(k,"approved")),S}),g.current.push(setTimeout(()=>{f(N=>{const S=new Map(N);return P.forEach(k=>S.set(k,"fading")),S})},1500)),g.current.push(setTimeout(()=>{f(N=>{const S=new Map(N);return P.forEach(k=>S.delete(k)),S})},2500)))},[t]);const x=ae(()=>{const C=[...e];return i==="by-impact"&&c!==null?C.sort((P,N)=>{const S=c[P.filePath]??0,k=c[N.filePath]??0;return k!==S?k-S:new Date(N.lastModified).getTime()-new Date(P.lastModified).getTime()}):C.sort((P,N)=>new Date(N.lastModified).getTime()-new Date(P.lastModified).getTime()),C},[e,i,c]),b=ae(()=>x.filter(C=>!t[C.filePath]).length,[x,t]),w=ae(()=>a==="unreviewed"?x.filter(C=>!t[C.filePath]||h.has(C.filePath)):x,[x,a,t,h]),v=!u&&c!==null;return d("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:[d("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Recently Changed Rules"})}),n("div",{className:"flex-1"}),d("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),d("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:["Unreviewed Rules (",b,")"]})]}),d("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),d("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:["All (",x.length,")"]})]})]}),d("div",{className:"grid grid-cols-[1fr_90px_80px_100px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Rule"}),d("button",{onClick:()=>v&&l("by-impact"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none p-0 ${v?"cursor-pointer hover:text-gray-600":"cursor-default"} ${i==="by-impact"?"text-[#005C75]":"text-gray-400"}`,children:["Src Files",i==="by-impact"&&n(dt,{className:"w-3 h-3"})]}),d("button",{onClick:()=>l("by-date"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none cursor-pointer p-0 hover:text-gray-600 ${i==="by-date"?"text-[#005C75]":"text-gray-400"}`,children:["Changed At",i==="by-date"&&n(dt,{className:"w-3 h-3"})]}),d("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center flex items-center justify-center gap-1 whitespace-nowrap",children:["✓ Reviewed",d("span",{className:"relative group",children:[n(Ks,{className:"w-3 h-3 text-gray-300 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Showing which rules have been reviewed and approved. Click a rule to view it and approve it"})]})]})]}),n("div",{className:"flex-1 overflow-y-auto max-h-[400px]",children:w.map(C=>{const P=t[C.filePath]??!1,N=h.get(C.filePath),S=xs(C.body,C.filePath),k=(c==null?void 0:c[C.filePath])??0;return n("div",{className:`border-b border-gray-50 transition-all ${N==="fading"?"duration-1000":"duration-300"}`,style:{opacity:N==="fading"?0:1},children:d("div",{className:`grid grid-cols-[1fr_90px_80px_100px] px-5 py-2.5 items-center cursor-pointer transition-colors duration-300 ${N==="approved"?"bg-[#f0fdf4]":"hover:bg-gray-50"}`,onClick:()=>r(C),children:[n("div",{className:"flex items-center gap-2 min-w-0",children:n("span",{className:"text-sm text-gray-900 truncate",children:S})}),n("span",{className:"text-xs text-center",children:u?n("span",{className:"inline-block w-6 h-3 bg-gray-100 rounded animate-pulse"}):c!==null?n("span",{className:k>0?"text-gray-700 font-medium":"text-gray-300",children:k}):n("span",{className:"text-gray-300",children:"—"})}),n("span",{className:"text-xs text-gray-500 text-center",children:bn(C.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 ${P?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:P&&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"})})})})]})},C.filePath)})}),w.length===0&&a==="unreviewed"&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:"All rules have been reviewed"})]})}function tN(e,t){const r=t.map(s=>`- \`${s}\``).join(`
|
|
411
|
-
`);return`Please audit the following Claude Rules that apply to the file \`${e}\`:
|
|
412
|
-
|
|
413
|
-
${r}
|
|
414
|
-
|
|
415
|
-
Please review these rules in conjunction with one another as they all apply to this file.
|
|
416
|
-
|
|
417
|
-
Review each rule with the other rules in mind:
|
|
418
|
-
- Necessary: Is this rule really necessary to avoid confusion in future work sessions?
|
|
419
|
-
- Efficiency: Are the rules concise and well-structured?
|
|
420
|
-
- Effectiveness: Does the rules provide clear, actionable guidance?
|
|
421
|
-
- Context window impact: Can the rules be shortened without losing important information?
|
|
422
|
-
- Overlap: Is there any redundant information across the rules that can be consolidated?
|
|
423
|
-
- Duplication: Are there any rules that are nearly identical that can be merged or removed?
|
|
424
|
-
|
|
425
|
-
Remember that documenting past confusion isn't helpul unless that confusion will likely happen again.
|
|
426
|
-
|
|
427
|
-
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 nN({filePath:e,rulePaths:t,onClose:r}){const[s,a]=M(!1),o=tN(e,t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:l=>l.stopPropagation(),children:[n("button",{onClick:r,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Sn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-1",children:"Audit Rules For File"}),n("p",{className:"font-mono text-sm text-gray-500 mb-4 truncate",title:e,children:e}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can audit these rules to try and make them as efficient and effective as possible, reducing the impact on the context window."}),n("textarea",{readOnly:!0,value:o,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-4",children:n("button",{onClick:()=>{navigator.clipboard.writeText(o),a(!0),setTimeout(()=>a(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:s?d(de,{children:[n(ut,{className:"w-4 h-4"}),"Copied!"]}):d(de,{children:[n(ft,{className:"w-4 h-4"}),"Copy Prompt"]})})})]})})}function rN({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:s}){const[a,o]=M("unreviewed"),[i,l]=M(null),[c,m]=M(""),[u,p]=M(0),[h,f]=M(!1),[y,g]=M(null),[x,b]=M(null),w=ve(null),v=ve(null),[C,P]=M({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[N,S]=M(!0);ne(()=>{(async()=>{S(!0);try{const Y=await(await fetch("/api/memory?action=audit")).json();P({topPaths:Y.topPaths||[],totalFilesWithCoverage:Y.totalFilesWithCoverage||0,allSourceFiles:Y.allSourceFiles||[]})}catch(W){console.error("Failed to load audit data:",W)}finally{S(!1)}})()},[e]);const k=ae(()=>a==="all"?C.topPaths:C.topPaths.filter(I=>I.matchingRules.some(W=>!t[W.filePath])),[C.topPaths,a,t]);ae(()=>C.topPaths.filter(I=>I.matchingRules.some(W=>!t[W.filePath])).length,[C.topPaths,t]);const _=I=>I.split("/").pop()||I,j=ae(()=>{const I=new Map;for(const W of C.topPaths)I.set(W.filePath,W);return I},[C.topPaths]),T=ae(()=>{if(!c.trim())return[];const I=c.toLowerCase(),W=[],Y=[];for(const U of C.allSourceFiles){const B=U.toLowerCase();if(!B.includes(I))continue;const H=j.get(U)||{filePath:U,matchingRules:[],totalTextLength:0};B.startsWith(I)?W.push(H):Y.push(H)}return W.sort((U,B)=>U.filePath.localeCompare(B.filePath)),Y.sort((U,B)=>U.filePath.localeCompare(B.filePath)),[...W,...Y].slice(0,8)},[c,C.allSourceFiles,j]),E=ie(I=>{var W;g(I),l(I.filePath),m(I.filePath),f(!1),(W=w.current)==null||W.blur()},[]),$=ie(()=>{var I;m(""),g(null),l(null),(I=w.current)==null||I.focus()},[]),R=ie(I=>{var W;!h||T.length===0||(I.key==="ArrowDown"?(I.preventDefault(),p(Y=>Math.min(Y+1,T.length-1))):I.key==="ArrowUp"?(I.preventDefault(),p(Y=>Math.max(Y-1,0))):I.key==="Enter"?(I.preventDefault(),E(T[u])):I.key==="Escape"&&(f(!1),(W=w.current)==null||W.blur()))},[h,T,u,E]);return ne(()=>{p(0)},[T]),d("div",{className:"bg-white rounded-lg border border-gray-200 flex flex-col",children:[d("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Rule Audit"})}),d("div",{className:"relative flex-1 max-w-[300px]",children:[n(nr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),n("input",{ref:w,type:"text",value:c,onChange:I=>{m(I.target.value),f(!0)},onFocus:()=>{c.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:R,placeholder:"Search files...",className:`w-full pl-8 ${c?"pr-7":"pr-3"} py-1 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-[#005C75] focus:border-[#005C75] bg-gray-50`}),c&&n("button",{type:"button",onMouseDown:I=>{I.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"})})}),h&&T.length>0&&n("div",{ref:v,className:"absolute left-0 top-full mt-0.5 bg-white border border-gray-200 rounded-md shadow-lg z-10 max-h-75 overflow-y-auto min-w-75 max-w-120",children:T.map((I,W)=>d("div",{onMouseDown:Y=>{Y.preventDefault(),E(I)},onMouseEnter:()=>p(W),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${W===u?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(Mr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:I.filePath,children:(()=>{const Y=I.filePath.toLowerCase().indexOf(c.toLowerCase());if(Y===-1)return I.filePath;const U=I.filePath.slice(0,Y),B=I.filePath.slice(Y,Y+c.length),H=I.filePath.slice(Y+c.length);return d(de,{children:[U,n("span",{className:"font-semibold text-[#005C75]",children:B}),H]})})()}),d("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[I.matchingRules.length," rule",I.matchingRules.length!==1?"s":""]})]},I.filePath))})]}),n("div",{className:"flex-1"}),d("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:"Unreviewed Rules"})]}),d("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:"All"})]})]}),d("div",{className:"grid grid-cols-[1fr_140px_150px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Source file"}),d("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Rules",d("span",{className:"relative group",children:[n(Ks,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-48 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Number of rules not yet reviewed for this file / Total number of rules that apply to this file"})]})]}),d("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Tokens",d("span",{className:"relative group",children:[n(Ks,{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"})]})]})]}),N&&n("div",{className:"px-5 py-6",children:d("div",{className:"animate-pulse space-y-3",children:[n("div",{className:"h-4 bg-gray-200 rounded w-3/4"}),n("div",{className:"h-3 bg-gray-100 rounded w-1/2"}),n("div",{className:"h-4 bg-gray-200 rounded w-2/3 mt-4"})]})}),!N&&(k.length>0||y)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(y?[y,...k.filter(W=>W.filePath!==y.filePath)].slice(0,8):k.slice(0,8)).map((I,W)=>{const Y=I.matchingRules.length,U=I.matchingRules.filter(V=>!t[V.filePath]),B=U.length,H=U.reduce((V,q)=>V+q.bodyLength,0),D=B>0,A=i===I.filePath,J=(y==null?void 0:y.filePath)===I.filePath;return d("div",{children:[d("div",{onClick:()=>l(A?null:I.filePath),className:`grid grid-cols-[1fr_140px_150px] px-5 py-2.5 items-center border-b border-gray-50 cursor-pointer ${J?"bg-[#f0f9ff] hover:bg-[#e0f2fe]":"hover:bg-gray-50"}`,children:[d("div",{className:"flex items-center gap-2 min-w-0",children:[A?n(dt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n(Yt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(Mr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:I.filePath,children:J?I.filePath:_(I.filePath)})]}),d("span",{className:"text-sm text-center",children:[n("span",{className:D?"font-semibold text-[#1A5276]":"text-gray-400",children:B}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:Y})]}),d("span",{className:"text-sm text-center",children:[n("span",{className:D?"font-semibold text-[#1A5276]":"text-gray-400",children:Qn(H).toLocaleString()}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:Qn(I.totalTextLength).toLocaleString()})]})]}),A&&d("div",{className:"bg-gray-50 border-b border-gray-100",children:[I.matchingRules.map(V=>{const q=r.find(L=>L.filePath===V.filePath),X=t[V.filePath]??!1;return d("div",{onClick:L=>{L.stopPropagation(),q&&s(q)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(Pr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-700 truncate flex-1",children:q?xs(q.body,q.filePath):V.filePath}),d("span",{className:"text-xs text-gray-400 flex-shrink-0",children:[Qn(V.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"})})})]},V.filePath)}),d("div",{className:"flex items-center justify-center gap-3 px-5 py-2 border-t border-gray-200",children:[n("span",{className:"text-xs text-gray-400",children:"Have Claude audit these rules"}),n("button",{onClick:V=>{V.stopPropagation(),b({filePath:I.filePath,rulePaths:I.matchingRules.map(q=>q.filePath)})},className:"px-3 py-1 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer",children:"Prompt"})]})]})]},I.filePath)})}),!N&&k.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(nN,{filePath:x.filePath,rulePaths:x.rulePaths,onClose:()=>b(null)})]})}function sN({rule:e,changeInfo:t,isReviewed:r,onApprove:s,onEdit:a,onDelete:o,onClose:i}){const l=xs(e.body,e.filePath),c=Qn(e.body.length),m=e.frontmatter.category,u=`.claude/rules/${e.filePath}`,[p,h]=M(null),f=(t==null?void 0:t.changeType)==="added"||p!=null&&p.commitCount!=null&&p.commitCount<=1&&!(p.commitCount===1&&p.isUncommitted);return ne(()=>{h(null),fetch(`/api/memory?action=rule-diff&filePath=${encodeURIComponent(e.filePath)}`).then(y=>y.json()).then(y=>{y.diff&&h(y.diff)}).catch(()=>{})},[e.filePath]),ne(()=>{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:d("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:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"min-w-0 flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[n("h2",{className:"text-[16px] font-bold text-gray-900",children:l}),t&&d(de,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:bn(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&&d("div",{className:"flex items-center gap-2 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"TYPE:"}),n("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase font-semibold tracking-wider bg-[#E0F2F1] text-[#00796B]",children:m})]}),d("div",{className:"flex items-center gap-1.5 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"FILE:"}),n("code",{className:"text-[11px] text-gray-600 font-mono",children:u}),n(jt,{content:u,icon:!0,iconSize:12,className:"p-0.5 rounded text-gray-400 hover:text-gray-600 transition-colors",ariaLabel:"Copy file path"})]}),d("div",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:["TOKENS: ~",c.toLocaleString()]})]}),d("div",{className:"flex items-center gap-2 flex-shrink-0 ml-4",children:[d("button",{onClick:s,className:`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer transition-colors ${r?"bg-green-600 text-white":"border border-green-600 text-green-700 hover:bg-green-50"}`,children:[n(ut,{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(Sn,{className:"w-5 h-5"})})]})]})}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&d("div",{className:"px-6 pb-4",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Applies to paths:"}),n("div",{className:"bg-white rounded-lg p-4 space-y-2.5",style:{border:"1px solid #E6E6E6"},children:e.frontmatter.paths.map((y,g)=>{const x=y.split("/"),b=x.pop()||y,w=x.length>0?x.join("/")+"/":"";return d("div",{className:"flex items-center gap-2 text-[13px] font-mono",children:[n(Mr,{className:"w-4 h-4 text-[#005C75] flex-shrink-0"}),d("span",{children:[w&&n("span",{className:"text-gray-500",children:w}),n("span",{className:"font-bold text-gray-900",children:b})]})]},g)})})]}),f?n("div",{className:"px-6 pb-4",children:d("div",{className:"text-[13px] text-gray-500",children:["Created"," ",t!=null&&t.date?bn(t.date):p!=null&&p.date?bn(p.date):"recently"]})}):p&&n("div",{className:"px-6 pb-4",children:d("details",{children:[d("summary",{className:"text-[13px] text-gray-700 font-semibold cursor-pointer",children:["Recent change: ",p.commitMessage," —"," ",bn(p.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:p.diff.split(`
|
|
428
|
-
`).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)})})]})}),d("div",{className:"px-6 pb-6",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Rule Text:"}),n("div",{className:"bg-white rounded-lg p-6",style:{border:"1px solid #E6E6E6"},children:n($c,{content:e.body})})]})]})})}function aN(){return d("svg",{width:"24",height:"24",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#232323"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#232323"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#232323"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#232323"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#232323"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#232323"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#232323"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#232323"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#232323"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#232323"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#232323"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#232323"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#232323"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#232323"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#232323"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#232323"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#232323"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#232323"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#232323"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#232323"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#232323"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#232323"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#232323"})]})}function oN(){return d("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}function iN(){return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans max-w-3xl mx-auto",children:[d("div",{className:"text-center mb-10",children:[n("h1",{className:"text-[22px] font-semibold mb-4",style:{fontFamily:"Sora",color:"#232323"},children:"Get Started with CodeYam Memory"}),n("p",{className:"text-[15px] text-gray-500 leading-relaxed max-w-2xl mx-auto",children:"CodeYam Memory generates path-scoped Claude Rules that load automatically when Claude works on matching files. These rules capture any confusion, architectural decisions, and tribal knowledge from your as you work with Claude, ensuring sessions become more efficient and aligned with your codebase over time."})]}),d("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"Setup Steps"}),d("ol",{className:"space-y-5",children:[d("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"1"}),n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Open Claude Code in your project terminal"})]}),d("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"2"}),d("div",{children:[d("div",{className:"flex items-center gap-2 pt-0.5",children:[n("span",{className:"text-[14px] font-medium text-gray-900",children:"Run"}),n(Ti,{value:"/codeyam-memory"}),n("span",{className:"text-[14px] font-medium text-gray-900",children:"in the Claude Code session"})]}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"This kicks off analysis of your git history to find confusion patterns."})]})]}),d("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"3"}),d("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Return to this dashboard page to review the new rules"}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"You can review, edit, and approve the rules Claude creates."})]})]})]})]}),d("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"What Gets Created"}),d("div",{className:"relative",children:[n("div",{className:"absolute left-[15px] top-8 bottom-4",style:{borderLeft:"2px dotted #B0BEC5"}}),d("div",{className:"space-y-6",children:[d("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),d("div",{children:[d("p",{className:"text-[14px] font-medium text-gray-900",children:[n("code",{className:"bg-gray-200/60 px-1.5 py-0.5 rounded text-[13px]",children:".claude/rules/*.md"}),n("span",{className:"text-gray-400 mx-1.5",children:"—"}),"path-scoped guidance files"]}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"Markdown files with frontmatter specifying which file paths they apply to."})]})]}),d("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),d("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Rules load automatically when Claude works on matching files"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"No manual steps needed — Claude picks up relevant rules based on the files it touches."})]})]}),d("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),d("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Pre-commit hook to keep rules fresh and capture new patterns"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"A git hook runs automatically to update rules when related code changes and looks for any new patterns of confusion in work sessions."})]})]})]})]})]}),d("div",{className:"rounded-lg px-8 py-5 flex items-center justify-center gap-3",style:{backgroundColor:"#1A2332"},children:[n("span",{className:"text-white text-[15px] font-medium",children:"Run"}),n(Ti,{value:"/codeyam-memory"}),n("span",{className:"text-white text-[15px] font-medium",children:"in Claude Code to get started"})]})]})})}function Ti({value:e}){const[t,r]=M(!1);return d("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[13px] font-mono cursor-pointer border-0",style:{backgroundColor:"#2C3E50",color:"#E0E0E0"},title:"Copy to clipboard",children:[e,t?n(ut,{className:"w-3.5 h-3.5 text-green-400"}):d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-400",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})}function Cr({label:e,count:t,icon:r,bgColor:s,iconBgColor:a,textColor:o}){return n("div",{className:"rounded-lg p-4",style:{backgroundColor:s,border:"1px solid #EFEFEF"},children:d("div",{className:"flex items-start gap-3",children:[n("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:a},children:r}),d("div",{className:"flex-1",children:[n("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:o},children:t}),n("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:o},children:e})]})]})})}function lN({searchFilter:e,onSearchChange:t,onCreateNew:r,onLearnMore:s,reviewCounts:a}){return d("div",{className:"mb-8",children:[d("div",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[d("div",{children:[d("div",{className:"flex items-center gap-3 mb-2",children:[n(aN,{}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),d("p",{className:"text-[15px] text-gray-500",children:["Rules help Claude understand your codebase patterns and conventions."," ",n("button",{onClick:s,className:"text-[#005C75] underline cursor-pointer",children:"Learn more about rules."})]})]}),d("div",{className:"flex items-center gap-3",children:[d("div",{className:"relative",children:[n(nr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:e,onChange:o=>t(o.target.value),placeholder:"Search rules...",className:"w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),d("button",{onClick:r,className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(ba,{className:"w-4 h-4"}),"New Rule"]})]})]}),d("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[n(Cr,{label:"Total Rules",count:a.total,icon:n(oN,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(Cr,{label:"Unreviewed",count:a.unreviewed,icon:n(Ad,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(Cr,{label:"Reviewed",count:a.reviewed,icon:n(ut,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(Cr,{label:"Stale",count:a.stale,icon:n(Yi,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]})}function cN({onClose:e,onCreateNew:t}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:r=>r.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Sn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-4",children:"What are Claude Rules?"}),n("h3",{className:"mb-4 font-semibold",children:"And how does CodeYam Memory work with Claude Rules?"}),d("div",{className:"text-gray-600 text-[15px] space-y-3 mb-6",children:[d("p",{children:["Claude Rules are a component of"," ",n("a",{href:"https://code.claude.com/docs/en/memory#modular-rules-with-claude%2Frules%2F",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 underline",children:"Memory Management in Claude Code"}),'. The text of each rule is passed into the context window when working on the specific files described in the "paths" frontmatter field of the rule.']}),n("p",{children:"This allows you to provide context that is surgically specific to certain files in your codebase. They are a powerful tool but are harder to write and maintain than CLAUDE.md files."}),n("p",{children:"CodeYam Memory helps write and maintain Claude Rules. Hooks ensure that rules are reviewed and added during Claude Code working sessions. The CodeYam CLI Dashboard provides a page dedicated to Memory where you can view, edit, create, delete, and review Claude Rules."})]}),n("div",{className:"flex justify-center",children:d("button",{onClick:t,className:"flex items-center gap-2 px-5 py-2.5 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(ba,{className:"w-4 h-4"}),"New Rule"]})})]})})}function dN({rule:e,onConfirm:t,onCancel:r}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:d("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[n("h3",{className:"text-lg font-semibold mb-2",children:"Delete Memory?"}),d("p",{className:"text-gray-600 mb-4",children:["Are you sure you want to delete"," ",n("span",{className:"font-mono text-sm",children:e.filePath}),"? This cannot be undone."]}),d("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>t(e),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})}const $i="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!",Ii="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function Ri({text:e}){const[t,r]=M(!1);return n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:t?d(de,{children:[n(ut,{className:"w-4 h-4"}),"Copied!"]}):d(de,{children:[n(ft,{className:"w-4 h-4"}),"Copy Prompt"]})})}function uN({onClose:e}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative max-h-[90vh] overflow-y-auto",onClick:t=>t.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Sn,{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:$i,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(Ri,{text:$i})}),d("div",{className:"border-t border-gray-200 mt-6 pt-5",children:[n("p",{className:"text-gray-500 text-sm mb-3",children:"If you would like to avoid reviewing all of the changes Claude makes you can ask Claude to mark all rules as reviewed."}),n("textarea",{readOnly:!0,value:Ii,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(Ri,{text:Ii})})]})]})})}function mN(){const[e,t]=M(!1);return d(de,{children:[d("div",{className:"border border-gray-200 rounded-lg px-5 py-4 flex items-center gap-3",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit All Rules"}),n("p",{className:"text-sm text-gray-500",children:"Ask Claude to review, audit, and improve all rules."}),n("button",{onClick:()=>t(!0),className:"px-4 py-2 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer flex-shrink-0",children:"Get Prompt"})]}),e&&n(uN,{onClose:()=>t(!1)})]})}function pN(e){return`Can you help me review my unreviewed rules? The following rules in \`.claude/rules\` have not been reviewed yet:
|
|
429
|
-
|
|
430
|
-
${e.map(r=>`- \`.claude/rules/${r}\``).join(`
|
|
431
|
-
`)}
|
|
432
|
-
|
|
433
|
-
Are they organized properly? Ideally they should be in a folder that is the best representation of the files they impact (e.g. if the rule impacts \`folder1/folder2/file1\` and \`folder1/folder2/folder3/file2\` then the rule should be in \`.claude/rules/folder1/folder2\`). Do they make sense? Are they oriented toward avoiding future confusion (vs documenting bug fixes or temporary workarounds, etc)? Please literally read each one to ensure you understand what it is saying and learn something useful from it. Are they concise and efficient in their communication? We want to be respectful of the context window so any information in a rule that does not make sense, is not particularly helpful, or is repetitive should be removed. All other information should be presented as directly as possible. Bullets and tables can help with this as opposed to paragraphs. Take into consideration how rules interact as any one file may have multiple rules applied to it. Please look at the impacted files as well to ensure that it is an appropriate rule for them and to ensure the rule is not just repeating information that can be ascertained from the code. We don't want Claude to have to read a large number of files (or a single very large file) to figure out how everything works, so architectural guidance can be quite valuable, but information that is specific to one file and can be ascertained by the code and comments in that file is unnecessary. Too often rules reflect past confusion that has been resolved and is unlikely to happen again. Content and rules like this should be removed. If you have any questions please ask!`}const Di="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function Oi({text:e}){const[t,r]=M(!1);return n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:t?d(de,{children:[n(ut,{className:"w-4 h-4"}),"Copied!"]}):d(de,{children:[n(ft,{className:"w-4 h-4"}),"Copy Prompt"]})})}function hN({onClose:e,unreviewedRulePaths:t}){const r=pN(t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:d("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative max-h-[90vh] overflow-y-auto",onClick:s=>s.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Sn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-2",children:"Audit Unreviewed Rules"}),d("p",{className:"text-gray-600 text-sm mb-4",children:["Claude will review only the ",t.length," unreviewed"," ",t.length===1?"rule":"rules"," for quality, relevance, and organization."]}),n("textarea",{readOnly:!0,value:r,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(Oi,{text:r})}),d("div",{className:"border-t border-gray-200 mt-6 pt-5",children:[n("p",{className:"text-gray-500 text-sm mb-3",children:"If you would like to avoid reviewing all of the changes Claude makes you can ask Claude to mark all rules as reviewed."}),n("textarea",{readOnly:!0,value:Di,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(Oi,{text:Di})})]})]})})}function fN({unreviewedRulePaths:e}){const[t,r]=M(!1);return e.length===0?d("div",{className:"border border-gray-200 rounded-lg px-5 py-4 flex items-center gap-3 opacity-50",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit Unreviewed Rules"}),n("p",{className:"text-sm text-gray-500",children:"All rules have been reviewed."})]}):d(de,{children:[d("div",{className:"border border-gray-200 rounded-lg px-5 py-4 flex items-center gap-3",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit Unreviewed Rules"}),d("p",{className:"text-sm text-gray-500",children:["Ask Claude to review the ",e.length," unreviewed"," ",e.length===1?"rule":"rules","."]}),n("button",{onClick:()=>r(!0),className:"px-4 py-2 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer flex-shrink-0",children:"Get Prompt"})]}),t&&n(hN,{onClose:()=>r(!1),unreviewedRulePaths:e})]})}const gN=()=>[{title:"Memory - CodeYam"},{name:"description",content:"Manage Claude Memory documentation"}];async function yN({request:e}){try{const r=await(await fetch(new URL("/api/memory",e.url).toString())).json();return r.error?Q({memories:[],reviewedStatus:{},memoryInitialized:r.memoryInitialized??!1,error:r.error}):r.memoryInitialized??!1?Q({memories:r.memories||[],reviewedStatus:r.reviewedStatus||{},memoryInitialized:!0,error:null}):Q({memories:[],reviewedStatus:{},memoryInitialized:!1,error:null})}catch(t){return console.error("Failed to load memories:",t),Q({memories:[],reviewedStatus:{},memoryInitialized:!1,error:"Failed to load memories"})}}const xN=Je(function(){const{memories:t,reviewedStatus:r,memoryInitialized:s,error:a}=qe(),o=Fe(),i=kt(),[l,c]=M(""),[m,u]=M(null),[p,h]=M(new Set(["root"])),[f,y]=M(null),[g,x]=M(!1),[b,w]=M(null),[v,C]=M(0),[P,N]=M(!1),[S,k]=M(null),[_,j]=M(null),[T,E]=M({}),$=L=>{h(O=>{const z=new Set(O);return z.has(L)?z.delete(L):z.add(L),z})};xt({source:"memory-page"});const R=ae(()=>({...r,...T}),[r,T]),I=ve(o.state);ne(()=>{const L=I.current==="loading"||I.current==="submitting",O=o.state==="idle";L&&O&&o.data&&(i.revalidate(),y(null),x(!1),C(z=>z+1)),I.current=o.state},[o.state,o.data,i]),ne(()=>{E(L=>{const O={};for(const[z,G]of Object.entries(L))r[z]!==G&&(O[z]=G);return Object.keys(O).length===Object.keys(L).length?L:O})},[r]);const W=(L,O)=>{E(z=>({...z,[L]:!0})),o.submit({action:"mark-reviewed",filePath:L,lastModified:O},{method:"POST",action:"/api/memory",encType:"application/json"})},Y=L=>{E(O=>({...O,[L]:!1})),o.submit({action:"mark-unreviewed",filePath:L},{method:"POST",action:"/api/memory",encType:"application/json"})},U=(L,O)=>{k(L),j(O??null)},B=ae(()=>{let L=t;if(l.trim()){const O=l.toLowerCase();L=L.filter(z=>{var ee;return(((ee=z.filePath.split("/").pop())==null?void 0:ee.replace(".md",""))||"").toLowerCase().includes(O)||z.body.toLowerCase().includes(O)})}return L},[t,l]),H=ae(()=>m?B.some(O=>O.filePath===m)?B.filter(O=>O.filePath===m):B.filter(O=>O.filePath.startsWith(m+"/")||O.filePath===m):B,[B,m]),D=(L,O)=>{const z=f?"update":"create";o.submit({action:z,filePath:L,content:O},{method:"POST",action:"/api/memory",encType:"application/json"})},A=L=>{o.submit({action:"delete",filePath:L.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),w(null)},J=ae(()=>{const L=t.filter(O=>R[O.filePath]).length;return{total:t.length,reviewed:L,unreviewed:t.length-L,stale:0}},[t,R]),V=ae(()=>{const L=new Set(["root"]);for(const O of B){const z=O.filePath.split("/");z.pop();let G="";for(const ee of z)G=G?`${G}/${ee}`:ee,L.add(G)}return L},[B]),q=V.size===p.size&&[...V].every(L=>p.has(L)),X=()=>{h(q?new Set(["root"]):new Set(V))};return a?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:a})]})}):s?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans",children:[n(lN,{searchFilter:l,onSearchChange:c,onCreateNew:()=>x(!0),onLearnMore:()=>N(!0),reviewCounts:J}),(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:L=>L.stopPropagation(),children:n(Qv,{rule:f,onSave:D,onCancel:()=>{x(!1),y(null)}})})}),d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(eN,{memories:B,reviewedStatus:R,onViewRule:U,refreshKey:v}),n(rN,{onEditRule:y,onDeleteRule:w,refreshKey:v,reviewedStatus:R,onMarkReviewed:W,onMarkUnreviewed:Y,memories:t,onViewRule:U})]}),d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(fN,{unreviewedRulePaths:t.filter(L=>!R[L.filePath]).map(L=>L.filePath)}),n(mN,{})]}),d("div",{className:"flex items-center justify-between mb-4",children:[n("h2",{className:"text-xl leading-6 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"All Rules"}),n("div",{className:"flex items-center gap-4",children:V.size>1&&n("button",{onClick:X,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:q?"Collapse All":"Expand All"})})]}),d("div",{className:"flex gap-6",children:[n("div",{className:"hidden lg:block w-80 flex-shrink-0",children:n(Zv,{memories:B,selectedPath:m,onSelectPath:u,expandedFolders:p,onToggleFolder:$})}),n("div",{className:"flex-1 min-w-0",children:t.length===0?d("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(Pd,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Rules Yet"}),d("p",{className:"text-gray-500 mb-4",children:["Run"," ",n("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam-memory"})," ","to generate initial memories for your codebase."]}),d("button",{onClick:()=>x(!0),className:"inline-flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer",children:[n(ba,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):d("div",{children:[m&&d("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:["Showing rules in"," ",n("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:m||"(root)"}),n("button",{onClick:()=>u(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(Xv,{memories:H,onEdit:y,onDelete:w,expandedFolders:p,onToggleFolder:$,reviewedStatus:R,onMarkReviewed:W,onMarkUnreviewed:Y,onViewRule:U})]})})]}),n("div",{className:"mt-8 mb-8",children:n(me,{to:"/agent-transcripts",className:"block bg-white border border-gray-200 rounded-lg p-5 hover:border-[#005C75] hover:shadow-sm transition-all group",children:d("div",{className:"flex items-center gap-3",children:[n("div",{className:"w-10 h-10 rounded-lg bg-[#EDF1F3] flex items-center justify-center",children:d("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#005C75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("polyline",{points:"4 17 10 11 4 5"}),n("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),d("div",{children:[n("h3",{className:"text-sm font-semibold text-[#232323] group-hover:text-[#005C75]",style:{fontFamily:"Sora"},children:"Agent Transcripts"}),n("p",{className:"text-xs text-gray-500",children:"View background agent transcripts and tool call history"})]})]})})}),S&&!f&&(()=>{const L=t.find(O=>O.filePath===S.filePath)??S;return n(sN,{rule:L,changeInfo:_??void 0,isReviewed:R[L.filePath]??!1,onApprove:()=>{R[L.filePath]??!1?Y(L.filePath):W(L.filePath,L.lastModified),k(null)},onEdit:()=>{y(L)},onDelete:()=>{w(L),k(null)},onClose:()=>k(null)})})(),P&&n(cN,{onClose:()=>N(!1),onCreateNew:()=>{N(!1),x(!0)}}),b&&n(dN,{rule:b,onConfirm:A,onCancel:()=>w(null)})]})}):n(iN,{})}),bN=Object.freeze(Object.defineProperty({__proto__:null,default:xN,loader:yN,meta:gN},Symbol.toStringTag,{value:"Module"}));function Gs(e){return`${e.filePath||""}::${e.name}`}function Dc(e,t){const r=Fe(),{showToast:s}=Aa(),[a,o]=M(new Map);ne(()=>{if(r.state==="idle"&&r.data){const h=r.data;h!=null&&h.error&&s(`Error: ${h.error}`,"error",6e3)}},[r.state,r.data,s]),ne(()=>{var f;if(a.size===0)return;const h=new Set;(f=t==null?void 0:t.jobs)==null||f.forEach(y=>{var g;(g=y.entityShas)==null||g.forEach(x=>{a.forEach((b,w)=>{b===x&&h.add(w)})})}),e==null||e.forEach(y=>{a.forEach((g,x)=>{g===y&&h.add(x)})}),h.size>0&&o(y=>{const g=new Map(y);return h.forEach(x=>g.delete(x)),g})},[t,e,a]);const i=ie(h=>{console.log("Generate analysis clicked for entity:",h.sha,h.name);const f=Gs(h);o(g=>new Map(g).set(f,h.sha));const y=new FormData;y.append("entitySha",h.sha),y.append("filePath",h.filePath||""),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),l=ie(h=>{const f=h.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(x=>{const b=new Map(x);return f.forEach(w=>b.set(Gs(w),w.sha)),b});const y=f.map(x=>x.sha).join(","),g=new FormData;g.append("entityShas",y),r.submit(g,{method:"post",action:"/api/analyze"})},[r]),c=ie(h=>(e==null?void 0:e.includes(h))??!1,[e]),m=ie(h=>{const f=Gs(h);return a.has(f)},[a]),u=ie(h=>{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(h)}))??!1},[t]),p=ae(()=>Array.from(a.keys()),[a]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:l,isEntityBeingAnalyzed:c,isEntityPending:m,isEntityInQueue:u,pendingEntityKeys:p}}function oo({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:s,analyzeAllDisabled:a=!1,analyzeAllText:o="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:d("div",{className:"flex justify-between items-center px-3 py-2",children:[d("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:n("span",{children:"STATE"})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:n("span",{children:"SIMULATIONS"})}),d("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),d("div",{className:"flex items-center justify-center gap-1 cursor-pointer hover:text-[#232323] transition-colors",style:{width:"116px"},onClick:r,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r==null||r())},children:[n("span",{children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:t==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&n("div",{className:"text-center",style:{width:"127px"},children:s&&n("button",{onClick:s,disabled:a,className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap px-3 py-1.5 normal-case",title:a?o:"Analyze all entities",children:o})})]})]})]})})}function wN({status:e,variant:t="compact"}){const r={modified:{label:"M",bgColor:"bg-[#f59e0c]"},added:{label:"A",bgColor:"bg-emerald-500"},deleted:{label:"D",bgColor:"bg-red-500",showWarning:!0},renamed:{label:"R",bgColor:"bg-indigo-500"},untracked:{label:"U",bgColor:"bg-purple-500"}},s={modified:{label:"MODIFIED",textColor:"#BB6BD9"},added:{label:"ADDED",textColor:"#F2994A"},deleted:{label:"DELETED",textColor:"#EF4444"},renamed:{label:"RENAMED",textColor:"#3B82F6"},untracked:{label:"UNTRACKED",textColor:"#6B7280"}};if(t==="full"){const o=s[e]||{label:"UNKNOWN",textColor:"#6B7280"};return n("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:o.textColor},children:o.label})})}const a=r[e]||{label:"?",bgColor:"bg-gray-500"};return d("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${a.bgColor}`,title:e,children:a.label}),a.showWarning&&n("span",{className:"inline-flex items-center justify-center w-3 h-3 text-[10px] text-amber-600",title:"Warning: File will be deleted",children:"⚠"})]})}function io({filePath:e,isExpanded:t,onToggle:r,fileStatus:s,simulationPreviews:a,entityCount:o,state:i,lastModified:l,actionButton:c,uncommittedCount:m,children:u,isNotAnalyzable:p=!1,isUncommitted:h=!1}){return d("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[d("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${p?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[d("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(Qi,{filePath:e}),s&&n(wN,{status:typeof s=="string"?s:s.status,variant:"full"}),h&&i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(h||i==="out-of-date")&&d("div",{className:"flex gap-1.5 items-center",children:[h&&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"&&!h&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:a}),d("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:d("span",{className:"text-[13px] text-[#3e3e3e]",children:[o," ",o===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:Nc(l)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:c})]})]})]}),t&&u&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:u})]})}function lo({entities:e,maxPreviews:t=3}){var s,a,o,i,l;const r=[];for(const c of e){if(r.length>=t)break;const m=((a=(s=c.analyses)==null?void 0:s[0])==null?void 0:a.scenarios)||[];if(c.entityType==="library"){const u=m.find(p=>{var h,f;return((h=p.metadata)==null?void 0:h.executionResult)||((f=p.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:c.sha})}else if(c.entityType==="visual"){const u=m.find(p=>{var h,f;return(f=(h=p.metadata)==null?void 0:h.screenshotPaths)==null?void 0:f[0]});if(u){const p=(i=(o=u.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],h=!!((l=u.metadata)!=null&&l.error);p&&r.push({type:"screenshot",screenshot:p,hasError:h,scenario:u,entitySha:c.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(de,{children:r.map((c,m)=>{if(c.type==="screenshot"&&c.screenshot){const u=c.hasError?"border-red-400":"border-gray-200";return d(me,{to:c.scenario?`/entity/${c.entitySha}/scenarios/${c.scenario.id}`:`/entity/${c.entitySha}`,className:`relative w-[50px] h-[38px] border ${u} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:p=>p.stopPropagation(),children:[n(Ze,{screenshotPath:c.screenshot,alt:`Preview ${m+1}`,className:"max-w-full max-h-full object-contain object-center"}),c.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(Ar,{size:12,color:"white"})})]},`screenshot-${m}`)}return c.type==="library"&&c.scenario&&c.entitySha?n(wc,{scenario:c.scenario,entitySha:c.entitySha,size:"small",showBorder:!0},`library-${m}`):null})})}function co({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:s}){var u,p;const a=t||r?[{entityShas:[e.sha]}]:[],o=lt(e,a,t),i=e.entityType==="visual"||e.entityType==="library",l=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,m=(((p=(u=e.analyses)==null?void 0:u[0])==null?void 0:p.scenarios)||[]).filter(h=>{var f,y;return(y=(f=h.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0]});return d("div",{className:"bg-white rounded-lg",children:[d(me,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[d("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 shrink-0"}),e.entityType==="type"?n("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:n("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:n(at,{type:"type"})})}):n(at,{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(Qa,{type:e.entityType||"other"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),d("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?o==="queued"?d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):o==="analyzing"?d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):o==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):o==="out-of-date"?n("button",{onClick:h=>{h.preventDefault(),h.stopPropagation(),s(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):l&&n("button",{onClick:h=>{h.preventDefault(),h.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((h,f)=>{var g,x;const y=(x=(g=h.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return y?n(me,{to:`/entity/${e.sha}?scenario=${h.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:b=>b.stopPropagation(),children:n(Ze,{screenshotPath:y,alt:h.name,className:"max-w-full max-h-full object-contain object-center"})},h.id):null})})]})}function vN({entities:e,page:t,itemsPerPage:r=50,currentRun:s,filter:a,entityType:o,queueState:i,isEntityPending:l,pendingEntityKeys:c,onGenerateSimulation:m,onGenerateAllSimulations:u,totalFilesCount:p,totalEntitiesCount:h,uncommittedFilesCount:f,showOnlyUncommitted:y,onToggleUncommitted:g}){const[x,b]=Cn(),[w,v]=M(new Set),[C,P]=M(""),[N,S]=M(!1),[k,_]=M("all"),[j,T]=M("desc"),E=o||"all",$=ae(()=>{let A=e;return E!=="all"&&(A=A.filter(J=>J.entityType===E)),a==="analyzed"&&(A=A.filter(J=>J.analyses&&J.analyses.length>0)),A},[e,E,a]),R=ae(()=>{const A=new Map,J=new Map,V=new Map;$.forEach(O=>{var ee,re;const z=`${O.filePath}::${O.name}`,G=J.get(z);if(!G)J.set(z,O),V.set(z,[]);else{const ue=((ee=G.metadata)==null?void 0:ee.editedAt)||G.createdAt||"",se=((re=O.metadata)==null?void 0:re.editedAt)||O.createdAt||"";let pe=!1;if(se>ue)pe=!0;else if(se===ue){const Ce=G.createdAt||"";pe=(O.createdAt||"")>Ce}pe?(V.get(z).push(G),J.set(z,O)):V.get(z).push(O)}}),J.forEach((O,z)=>{var ee;if(!(O.analyses&&O.analyses.length>0)&&((ee=O.metadata)!=null&&ee.previousVersionWithAnalyses)){const ue=(V.get(z)||[]).find(se=>{var pe;return se.sha===((pe=O.metadata)==null?void 0:pe.previousVersionWithAnalyses)});ue&&ue.analyses&&ue.analyses.length>0&&(O.analyses=ue.analyses)}}),Array.from(J.values()).sort((O,z)=>{var re,ue,se,pe;const G=!((re=O.metadata)!=null&&re.notExported)&&!((ue=O.metadata)!=null&&ue.namedExport),ee=!((se=z.metadata)!=null&&se.notExported)&&!((pe=z.metadata)!=null&&pe.namedExport);return G&&!ee?-1:!G&&ee?1:0}).forEach(O=>{var ue,se,pe,Ce,_e;const z=O.filePath??"No File Path";A.has(z)||A.set(z,{filePath:z,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const G=A.get(z);G.entities.push(O),G.totalCount++,(ue=O.metadata)!=null&&ue.isUncommitted&&G.uncommittedCount++;const ee=((Ce=(pe=(se=O.analyses)==null?void 0:se[0])==null?void 0:pe.scenarios)==null?void 0:Ce.length)||0;G.simulationCount+=ee;const re=((_e=O.metadata)==null?void 0:_e.editedAt)||O.updatedAt;re&&(!G.lastUpdated||new Date(re)>new Date(G.lastUpdated))&&(G.lastUpdated=re)});const q=(i==null?void 0:i.jobs)||[],X=O=>{const z=`${O.filePath||""}::${O.name}`;return(c==null?void 0:c.includes(z))||!1};A.forEach(O=>{const z=O.entities.map(G=>X(G)?"queued":lt(G,q));z.includes("analyzing")||z.includes("queued")?O.state="analyzing":z.includes("incomplete")?O.state="incomplete":z.includes("out-of-date")?O.state="out-of-date":z.includes("not-analyzed")?O.state="not-analyzed":O.state="up-to-date"}),A.forEach(O=>{var z,G,ee,re,ue;for(const se of O.entities){if(O.previewScreenshots.length+O.previewLibraryScenarios.length>=3)break;const Ce=((G=(z=se.analyses)==null?void 0:z[0])==null?void 0:G.scenarios)||[];if(se.entityType==="library"){const _e=Ce.find(Ae=>{var De,Le;return((De=Ae.metadata)==null?void 0:De.executionResult)||((Le=Ae.metadata)==null?void 0:Le.error)});_e&&O.previewLibraryScenarios.push({scenario:_e,entitySha:se.sha})}else{const _e=Ce.find(Ae=>{var De,Le;return(Le=(De=Ae.metadata)==null?void 0:De.screenshotPaths)==null?void 0:Le[0]});if(_e){const Ae=(re=(ee=_e.metadata)==null?void 0:ee.screenshotPaths)==null?void 0:re[0],De=!!((ue=_e.metadata)!=null&&ue.error);Ae&&!O.previewScreenshots.includes(Ae)&&(O.previewScreenshots.push(Ae),O.previewScreenshotErrors.push(De))}}}});const L=Array.from(A.values());return L.sort((O,z)=>{if(a==="analyzed"){const re=Math.max(...O.entities.filter(se=>{var pe,Ce;return(Ce=(pe=se.analyses)==null?void 0:pe[0])==null?void 0:Ce.createdAt}).map(se=>new Date(se.analyses[0].createdAt).getTime()),0),ue=Math.max(...z.entities.filter(se=>{var pe,Ce;return(Ce=(pe=se.analyses)==null?void 0:pe[0])==null?void 0:Ce.createdAt}).map(se=>new Date(se.analyses[0].createdAt).getTime()),0);return j==="desc"?ue-re:re-ue}if(O.uncommittedCount>0&&z.uncommittedCount===0)return-1;if(O.uncommittedCount===0&&z.uncommittedCount>0)return 1;const G=O.lastUpdated?new Date(O.lastUpdated).getTime():0,ee=z.lastUpdated?new Date(z.lastUpdated).getTime():0;return j==="desc"?ee-G:G-ee}),L},[$,a,j,i,c]),I=ae(()=>{let A=R;if(k!=="all"&&(A=A.filter(J=>J.state===k)),C.trim()){const J=C.toLowerCase();A=A.filter(V=>V.filePath.toLowerCase().includes(J))}return A},[R,C,k]),W=(t-1)*r,Y=W+r,U=I.slice(W,Y),B=Math.ceil(I.length/r),H=A=>{v(J=>{const V=new Set(J);return V.has(A)?V.delete(A):V.add(A),V})},D=()=>{T(A=>A==="desc"?"asc":"desc")};return d("div",{children:[d("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),d("div",{className:"flex gap-3",children:[d("div",{className:"relative w-[130px]",children:[d("select",{value:E,onChange:A=>{const J=A.target.value,V=new URLSearchParams(x);J==="all"?V.delete("entityType"):V.set("entityType",J),V.set("page","1"),b(V)},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(dt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"relative w-[130px]",children:[d("select",{value:k,onChange:A=>_(A.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(dt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"flex-1 relative",children:[n(nr,{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:C,onChange:A=>P(A.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"})]})]})]}),p!==void 0&&h!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center",children:[d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:I.length})," ",I.length===1?"file":"files"]}),d("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:d("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:I.reduce((A,J)=>A+J.totalCount,0)})," ",I.reduce((A,J)=>A+J.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?d("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:[I.filter(A=>A.uncommittedCount>0).length," ","uncommitted"," ",I.filter(A=>A.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):d("button",{onClick: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"]})]}),U.length>0&&d("div",{className:"flex gap-6",children:[d("button",{onClick:()=>{v(new Set(U.map(A=>A.filePath))),S(!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(Wi,{className:"w-3.5 h-3.5"}),"Expand All"]}),d("button",{onClick:()=>{v(new Set),S(!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(Hi,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(oo,{showActions:!0,sortOrder:j,onSortChange:D}),n("div",{className:"flex flex-col gap-[3px]",children:U.map(A=>{const J=w.has(A.filePath),q=A.entities.filter(z=>(z.entityType==="visual"||z.entityType==="library")&&(lt(z,(i==null?void 0:i.jobs)||[])==="not-analyzed"||lt(z,(i==null?void 0:i.jobs)||[])==="out-of-date"||lt(z,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,X=z=>{var G;return((G=s==null?void 0:s.currentEntityShas)==null?void 0:G.includes(z))||!1},L=z=>{var G;return l!=null&&l(z)?!0:((G=i==null?void 0:i.jobs)==null?void 0:G.some(ee=>{var re;return(re=ee.entityShas)==null?void 0:re.includes(z.sha)}))||!1},O=z=>{m==null||m(z)};return n(io,{filePath:A.filePath,isExpanded:J,onToggle:()=>H(A.filePath),simulationPreviews:n(lo,{entities:A.entities,maxPreviews:1}),entityCount:A.totalCount,state:A.state,lastModified:A.lastUpdated,uncommittedCount:A.uncommittedCount,isUncommitted:A.uncommittedCount>0,actionButton:q?n("button",{onClick:z=>{z.stopPropagation();const G=A.entities.filter(ee=>(ee.entityType==="visual"||ee.entityType==="library")&&(lt(ee,(i==null?void 0:i.jobs)||[])==="not-analyzed"||lt(ee,(i==null?void 0:i.jobs)||[])==="out-of-date"||lt(ee,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(G)},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:A.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:A.entities.sort((z,G)=>{var pe,Ce,_e,Ae;const ee=!((pe=z.metadata)!=null&&pe.notExported)&&!((Ce=z.metadata)!=null&&Ce.namedExport),re=!((_e=G.metadata)!=null&&_e.notExported)&&!((Ae=G.metadata)!=null&&Ae.namedExport);if(ee&&!re)return-1;if(!ee&&re)return 1;const ue=z.entityType==="visual"||z.entityType==="library",se=G.entityType==="visual"||G.entityType==="library";return ue&&!se?-1:!ue&&se?1:z.name.localeCompare(G.name)}).map(z=>n(co,{entity:z,isActivelyAnalyzing:X(z.sha),isQueued:L(z),onGenerateSimulation:O},z.sha))},A.filePath)})}),B>1&&d("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),d("span",{children:["Page ",t," of ",B]}),t<B&&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 NN=()=>[{title:"Files & Entities - CodeYam"},{name:"description",content:"Browse your codebase files and entities"}];async function CN({request:e,context:t}){try{const r=new URL(e.url),s=parseInt(r.searchParams.get("page")||"1"),a=r.searchParams.get("filter")||null,o=r.searchParams.get("entityType"),i=t.analysisQueue,l=i?i.getState():{paused:!1,jobs:[]},[c,m]=await Promise.all([mn(),_n()]);return Q({entities:c,currentCommit:m,page:s,filter:a,entityType:o,queueState:l})}catch(r){return console.error("Failed to load entities:",r),Q({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const SN=Je(function(){var C,P,N;const{entities:t,currentCommit:r,page:s,filter:a,entityType:o,queueState:i,error:l}=qe();kt();const[c,m]=Cn(),[u,p]=M(!1);xt({source:"files-page"});const{handleGenerateSimulation:h,handleGenerateAllSimulations:f,isEntityPending:y,pendingEntityKeys:g}=Dc((P=(C=r==null?void 0:r.metadata)==null?void 0:C.currentRun)==null?void 0:P.currentEntityShas,i),x=t||[],b=ae(()=>{const S=new Set([]);for(const k of x)S.add(k.filePath??"No File Path");return Array.from(S)},[x]),w=ae(()=>{let S=x;return u&&(S=S.filter(k=>{var _;return(_=k.metadata)==null?void 0:_.isUncommitted})),S.sort((k,_)=>{var j,T,E,$,R,I;return(j=k.metadata)!=null&&j.isUncommitted&&!((T=_.metadata)!=null&&T.isUncommitted)?-1:!((E=k.metadata)!=null&&E.isUncommitted)&&(($=_.metadata)!=null&&$.isUncommitted)?1:new Date(((R=_.metadata)==null?void 0:R.editedAt)||0).getTime()-new Date(((I=k.metadata)==null?void 0:I.editedAt)||0).getTime()})},[x,u]),v=ae(()=>{var k;const S=new Set([]);for(const _ of x)(k=_.metadata)!=null&&k.isUncommitted&&S.add(_.filePath??"No File Path");return Array.from(S)},[x]);return l?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:l})]})}):x.length===0?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-20 py-12 font-sans",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:d("div",{className:"max-w-md mx-auto",children:[n("h2",{className:"text-xl font-semibold text-gray-900 mb-3",children:"No entities found"}),d("p",{className:"text-[15px] text-gray-600 mb-6",children:["Your project hasn't been analyzed yet. Run"," ",n("code",{className:"px-2 py-1 bg-gray-100 rounded text-sm font-mono",children:"codeyam analyze"})," ","to extract entities from your codebase."]}),n("p",{className:"text-sm text-gray-500",children:"Entities include React components, functions, and other analyzable code elements."})]})})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-20 py-12 font-sans",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n(vN,{entities:w,page:s,itemsPerPage:50,currentRun:(N=r==null?void 0:r.metadata)==null?void 0:N.currentRun,filter:a,entityType:o,queueState:i,isEntityPending:y,pendingEntityKeys:g,onGenerateSimulation:h,onGenerateAllSimulations:f,totalFilesCount:b.length,totalEntitiesCount:x.length,uncommittedFilesCount:v.length,showOnlyUncommitted:u,onToggleUncommitted:()=>p(!u)})]})})}),kN=Object.freeze(Object.defineProperty({__proto__:null,default:SN,loader:CN,meta:NN},Symbol.toStringTag,{value:"Module"})),EN=()=>[{title:"Labs - CodeYam"},{name:"description",content:"Experimental features"}];async function _N({request:e}){var t;try{const r=await Ie();if(!r)return Q({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Project not found"});const{project:s}=await Re(r),a=he()||process.cwd(),o=fc(a)||"";let i="";try{const c=await ts();if(c!=null&&c.webapps&&Array.isArray(c.webapps)){const m=c.webapps.map(u=>u.framework).filter(Boolean);m.length>0&&(i=m.join(", "))}}catch{}const l=bc(r);return Q({labs:((t=s.metadata)==null?void 0:t.labs)??null,projectSlug:r,defaultEmail:o,detectedTechStack:i,unlockCode:l,error:null})}catch(r){return console.error("Failed to load labs config:",r),Q({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Failed to load labs configuration"})}}async function AN({request:e}){try{const t=await e.formData(),r=t.get("feature"),s=t.get("enabled")==="true";if(!r)return Q({success:!1,error:"Missing feature name"},{status:400});const a=await Ie();return a?(r==="clearAccess"?await vn({projectSlug:a,metadataUpdate:{labs:{accessGranted:!1,simulations:!1}}}):await vn({projectSlug:a,metadataUpdate:{labs:{[r]:s}}}),Q({success:!0,error:null})):Q({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),Q({success:!1,error:"Failed to save labs configuration"},{status:500})}}const PN=[{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}],Li="https://docs.google.com/forms/d/e/1FAIpQLSfopqQOQsjY9S4Ns0l3xDLzGl7iYNpKa2Wn2Xzmtxj8CR1sMA/viewform",jN=[{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 MN({onClose:e}){const t=ve(null),r=ve(0);return ne(()=>{const s=t.current;if(!s)return;const a=100,o=2e3,i=500;let l=null,c=!1;const m=()=>{r.current=Date.now(),!l&&!c&&(l=setInterval(()=>{const u=Date.now()-r.current,p=s.scrollTop>a,h=u>o;p&&h&&(s.scrollTo({top:0,behavior:"smooth"}),c=!0,l&&(clearInterval(l),l=null))},i))};return s.addEventListener("scroll",m,{passive:!0}),()=>{s.removeEventListener("scroll",m),l&&clearInterval(l)}},[]),d("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:s=>{s.target===s.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),d("div",{className:"relative bg-white rounded-xl max-w-3xl w-full mx-4 max-h-[90vh] overflow-hidden",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none z-10",children:"×"}),d("div",{ref:t,className:"overflow-y-auto max-h-[90vh] p-4 md:p-6",children:[d("div",{className:"mb-4",children:[n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Request Early Access"}),n("p",{className:"text-sm text-gray-500",children:"Complete the form below to join the waitlist for CodeYam Labs."})]}),n("div",{className:"bg-white rounded-lg overflow-hidden",children:n("iframe",{src:`${Li}?embedded=true`,width:"100%",height:"1400",style:{border:0,minHeight:"1400px"},title:"Labs Waitlist Form",loading:"eager",children:n("div",{className:"flex items-center justify-center p-8 text-gray-600",children:d("div",{className:"text-center",children:[n("div",{className:"mb-4",children:"Loading form..."}),d("div",{className:"text-sm",children:["If this takes too long,"," ",n("a",{href:Li,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"open the form directly"})]})]})})})})]})]})]})}function TN({onClose:e,unlockCodeInput:t,setUnlockCodeInput:r,unlockFetcher:s}){var i,l;const a=(i=s.data)==null?void 0:i.error,o=(l=s.data)==null?void 0:l.success;return d("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:c=>{c.target===c.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),d("div",{className:"relative bg-white rounded-xl p-8 max-w-md w-full mx-4",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none",children:"×"}),n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Have an unlock code?"}),n("p",{className:"text-sm text-cygray-50 mb-6",children:"If you've received an unlock code, paste it below to enable Simulations immediately."}),d(s.Form,{method:"post",action:"/api/labs-unlock",className:"space-y-4",children:[n("input",{type:"text",name:"unlockCode",value:t,onChange:c=>r(c.target.value),placeholder:"CY-...",className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-100 focus:border-transparent"}),n("button",{type:"submit",disabled:!t.trim()||s.state==="submitting",className:"w-full py-3 text-white border-none rounded-lg text-sm font-mono font-semibold uppercase tracking-wider cursor-pointer transition-all bg-primary-200 hover:bg-primary-100 disabled:bg-gray-400 disabled:cursor-not-allowed",children:s.state==="submitting"?"Validating...":"Unlock"}),a&&n("p",{className:"text-red-600 text-sm mt-2",children:a}),o&&n("p",{className:"text-emerald-600 text-sm mt-2",children:"Simulations enabled! Refresh the page to see all tabs."})]})]})]})}const $N=Je(function(){const{labs:t,unlockCode:r,error:s}=qe(),a=Fe(),o=Fe(),i=Fe(),[l,c]=M(""),[m,u]=M(!1),[p,h]=M(!1);xt({source:"labs-page"});const f=(t==null?void 0:t.accessGranted)===!0||(t==null?void 0:t.simulations)===!0;return s?n("div",{className:"bg-cygray-10 min-h-screen",children:d("div",{className:"px-20 pt-8 pb-12 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Labs"}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 mt-4",children:n("p",{className:"text-red-700",children:s})})]})}):f?d("div",{className:"bg-cygray-10 min-h-screen font-sans flex flex-col",children:[n("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"})}),d("div",{className:"px-6 sm:px-12 pt-8 pb-10",children:[n("h2",{className:"font-serif italic text-[32px] sm:text-[48px] text-primary-100 mb-3 font-normal leading-tight",children:"Congrats!"}),n("p",{className:"font-serif text-[18px] sm:text-[24px] text-cyblack-100 font-normal leading-snug max-w-2xl",children:"You were granted early access to software simulation and other experimental features."})]}),n("div",{className:"px-6 sm:px-12 space-y-6 flex-1",children:PN.map(y=>{var b;const g=(t==null?void 0:t[y.id])??y.defaultEnabled,x=o.state==="submitting"&&((b=o.formData)==null?void 0:b.get("feature"))===y.id;return n("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:d("div",{className:"flex items-center justify-between gap-4",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-3 mb-3",children:[n("h3",{className:"text-lg font-semibold text-cyblack-100 m-0",children: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})]}),d(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:d("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:[n("h3",{className:"text-base font-semibold text-cyblack-100 mb-1",children:"Unlock Code"}),n("p",{className:"text-sm text-cygray-50 mb-3",children:"This code was used to enable Labs access. Clear it to revoke access and return to the landing page."}),d("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[n("code",{className:"sm:flex-1 px-4 py-2.5 bg-cygray-10 border border-cygray-30 rounded-lg text-sm font-mono text-cyblack-100 overflow-x-auto",children:r}),d(i.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:"clearAccess"}),n("input",{type:"hidden",name:"enabled",value:"false"}),n("button",{type:"submit",disabled:i.state==="submitting",className:"px-4 py-2.5 bg-red-50 border border-red-200 rounded-lg text-sm font-medium text-red-700 cursor-pointer transition-colors hover:bg-red-100 disabled:opacity-60 disabled:cursor-not-allowed",children:i.state==="submitting"?"Clearing...":"Clear"})]})]})]})})]}):d("div",{className:"bg-cygray-10 min-h-screen font-sans",children:[m&&n(MN,{onClose:()=>u(!1)}),p&&n(TN,{onClose:()=>h(!1),unlockCodeInput:l,setUnlockCodeInput:c,unlockFetcher:a}),d("div",{className:"flex flex-wrap justify-between items-center gap-3 px-6 sm:px-12 pt-8 pb-4",children:[n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"}),d("div",{className:"flex flex-wrap items-center gap-3",children:[n("button",{onClick:()=>h(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cygray-30 bg-transparent text-cygray-50 cursor-pointer transition-colors hover:border-cyblack-100 hover:text-cyblack-100",children:"Have a Code?"}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cyblack-100 bg-transparent text-cyblack-100 cursor-pointer transition-colors hover:bg-cyblack-100 hover:text-white",children:"Apply for Early Access"})]})]}),d("div",{className:"px-6 sm:px-12 pt-12 pb-8",children:[n("h2",{className:"font-serif text-[24px] sm:text-[32px] leading-snug text-cyblack-100 max-w-xl mb-4 font-normal",children:"Powerful tools for the AI coding era."}),d("p",{className:"text-base sm:text-lg text-cygray-50 leading-relaxed max-w-xl mb-8",children:["We're opening early access to"," ",n("strong",{className:"text-cyblack-100",children:"experimental features"})," to a small group of developers and teams."]}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded bg-primary-200 text-white border-none cursor-pointer transition-colors hover:bg-primary-100",children:"Apply for Early Access"})]}),n("div",{className:"px-6 sm:px-12 py-8",children:n("hr",{className:"border-t border-cygray-30 m-0"})}),d("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:[n("h3",{className:"font-serif text-[22px] sm:text-[28px] text-cyblack-100 mb-10 font-normal text-center",children:"In The Works"}),n("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5 max-w-4xl mx-auto",children:jN.map(y=>d("div",{className:"border border-cygray-30 bg-white p-5 sm:p-8 rounded-lg",children:[d("h4",{className:"text-base font-semibold text-cyblack-100 mb-1",children:[y.title," ",d("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:d("div",{className:"rounded-lg p-6 sm:p-12 bg-primary-200",children:[n("h3",{className:"font-serif text-[20px] sm:text-[24px] text-white mb-4 font-semibold",children:"Request Early Access"}),n("p",{className:"text-sm text-white/80 leading-relaxed max-w-lg mb-10 font-mono",children:"We're onboarding a limited number of developers and teams. Tell us about how you build and we'll let you know when you can try simulations and other Labs features."}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded border border-white bg-white text-cyblack-100 cursor-pointer transition-colors hover:bg-white/90 mb-4",children:"Apply for Early Access"}),n("p",{className:"text-xs text-white/60 m-0",children:"Takes about 2 minutes. Your answers help us determine eligibility and prioritize access."})]})})]})}),IN=Object.freeze(Object.defineProperty({__proto__:null,action:AN,default:$N,loader:_N,meta:EN},Symbol.toStringTag,{value:"Module"}));function RN(e,t,r){const[s,a]=M(()=>new Set),[o,i]=M(()=>new Set),l=ve([]),c=ve([]);return ne(()=>{(t.length!==l.current.length||t.some((g,x)=>g!==l.current[x]))&&(l.current=t,a(g=>{const x=new Set;return t.forEach(b=>{g.has(b)&&x.add(b)}),x}))},[t]),ne(()=>{(r.length!==c.current.length||r.some((g,x)=>g!==c.current[x]))&&(c.current=r,i(g=>{const x=new Set;return r.forEach(b=>{g.has(b)&&x.add(b)}),x}))},[r]),{expandedUncommitted:s,expandedBranch:o,setExpandedUncommitted:a,setExpandedBranch:i,toggleFile:(y,g,x)=>{x(b=>{const w=new Set(b);return w.has(y)?w.delete(y):w.add(y),w})},expandAllUncommitted:()=>{a(new Set(t))},collapseAllUncommitted:()=>{a(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function DN(e,t,r){const[s,a]=M(null),[o,i]=M(null),l=Fe();ne(()=>{var p,h;((p=l.data)==null?void 0:p.oldContent)!==void 0&&((h=l.data)==null?void 0:h.newContent)!==void 0&&i({oldContent:l.data.oldContent,newContent:l.data.newContent,fileName:l.data.fileName})},[l.data]);const c=p=>{a({type:"file",path:p}),i(null);const h=new FormData;h.append("actionType","getDiff"),h.append("filePath",p),h.append("diffType","branch"),h.append("baseBranch",e),h.append("currentBranch",t||""),l.submit(h,{method:"post"})},m=(p,h)=>{a({type:"entity",path:p,entitySha:h}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",p),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",h),l.submit(f,{method:"post"})},u=()=>{a(null),i(null)};return{diffView:s,diffContent:o,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:c,handleShowEntityDiff:m,handleCloseDiff:u}}function ON({diffView:e,diffContent:t,isLoading:r,entities:s,onClose:a}){var m;const[o,i]=M(!1),[l,c]=M(!1);return ne(()=>{c(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:d("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[d("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[d("div",{children:[n("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),n("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&d("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((m=s.find(u=>u.sha===e.entitySha))==null?void 0:m.name)||e.entitySha]})]}),d("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick:a,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:l&&n(ru,{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 LN({files:e,currentBranch:t,defaultBranch:r,baseBranch:s,allBranches:a,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:l,sortOrder:c,onToggleFile:m,onBranchChange:u,onGenerateSimulation:p,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=e.flatMap(([v,{entities:C}])=>{const P=C.filter(N=>i(N.sha)||l(N)).map(N=>N.sha);return P.length>0?[{entityShas:P}]:[]}),b=v=>{const C=v.map(P=>lt(P,x));return C.includes("analyzing")||C.includes("queued")?"analyzing":C.includes("out-of-date")?"out-of-date":C.includes("not-analyzed")?"not-analyzed":"up-to-date"},w=ae(()=>[...e].sort((v,C)=>{const P=v[1].entities.reduce((_,j)=>{var E;const T=((E=j.metadata)==null?void 0:E.editedAt)||j.updatedAt;return T?_?new Date(T)>new Date(_)?T:_:T:_},null),N=C[1].entities.reduce((_,j)=>{var E;const T=((E=j.metadata)==null?void 0:E.editedAt)||j.updatedAt;return T?_?new Date(T)>new Date(_)?T:_:T:_},null);if(!P&&!N)return 0;if(!P)return 1;if(!N)return-1;const S=new Date(P).getTime(),k=new Date(N).getTime();return c==="desc"?k-S:S-k}),[e,c]);return n("div",{children:e.length>0?d("div",{children:[n(oo,{showActions:!0,sortOrder:c,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:w.map(([v,{status:C,entities:P,isUncommitted:N}])=>{const S=o.has(v),k=b(P),_=P.reduce(($,R)=>{var W;const I=((W=R.metadata)==null?void 0:W.editedAt)||R.updatedAt;return I?$?new Date(I)>new Date($)?I:$:I:$},null),T=P.filter($=>$.entityType==="visual"||$.entityType==="library").length===0;let E;return T?E=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):k==="analyzing"?E=d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):k==="up-to-date"?E=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"}):k==="out-of-date"?E=n("button",{onClick:$=>{$.stopPropagation(),P.filter(R=>(R.entityType==="visual"||R.entityType==="library")&&!i(R.sha)&&!l(R)).forEach(R=>p(R))},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"}):k==="not-analyzed"&&(E=n("button",{onClick:$=>{$.stopPropagation(),P.filter(R=>(R.entityType==="visual"||R.entityType==="library")&&!i(R.sha)&&!l(R)).forEach(R=>p(R))},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(io,{filePath:v,isExpanded:S,onToggle:()=>m(v),fileStatus:C,isUncommitted:N,simulationPreviews:n(lo,{entities:P,maxPreviews:1}),entityCount:P.length,state:k,lastModified:_,isNotAnalyzable:T,actionButton:E,children:P.sort(($,R)=>{const I=$.entityType==="visual"||$.entityType==="library",W=R.entityType==="visual"||R.entityType==="library";return I&&!W?-1:!I&&W?1:0}).map($=>n(co,{entity:$,isActivelyAnalyzing:i($.sha),isQueued:l($),onGenerateSimulation:p},$.sha))},v)})})]}):d("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function FN({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:s,isEntityQueued:a,projectSlug:o,baseBranch:i,currentBranch:l,sortOrder:c,onToggleFile:m,onShowFileDiff:u,onGenerateSimulation:p,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=ae(()=>{const v=[];return e.forEach(([C,{editedEntities:P}])=>{const N=P.filter(S=>s(S.sha)||a(S)).map(S=>S.sha);N.length>0&&v.push({entityShas:N})}),v},[e,s,a]),b=ae(()=>{const v=new Map;return e.forEach(([C,{editedEntities:P}])=>{const N=P.map(j=>lt(j,x));let S;N.includes("analyzing")||N.includes("queued")?S="analyzing":N.includes("out-of-date")?S="out-of-date":N.includes("not-analyzed")?S="not-analyzed":S="up-to-date";const k=P.reduce((j,T)=>{var $;const E=(($=T.metadata)==null?void 0:$.editedAt)||T.updatedAt;return E&&(!j||new Date(E)>new Date(j))?E:j},null),_=P.filter(j=>j.entityType==="visual"||j.entityType==="library").length;v.set(C,{state:S,lastModified:k,analyzableCount:_})}),v},[e,x]),w=ae(()=>[...e].sort((v,C)=>{const P=b.get(v[0]),N=b.get(C[0]),S=P==null?void 0:P.lastModified,k=N==null?void 0:N.lastModified;if(!S&&!k)return 0;if(!S)return 1;if(!k)return-1;const _=new Date(S).getTime(),j=new Date(k).getTime();return c==="desc"?j-_:_-j}),[e,b,c]);return e.length===0?d("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"If you edit a file in your project, it will show up here."})]}):d("div",{children:[n(oo,{showActions:!0,sortOrder:c,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:w.map(([v,{status:C,editedEntities:P}])=>{const N=r.has(v),S=b.get(v),{state:k,lastModified:_,analyzableCount:j}=S,T=j===0;let E;return T?E=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):k==="analyzing"?E=d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):k==="up-to-date"?E=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"}):k==="out-of-date"?E=n("button",{onClick:$=>{$.stopPropagation(),P.filter(R=>(R.entityType==="visual"||R.entityType==="library")&&!s(R.sha)&&!a(R)).forEach(R=>p(R))},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"}):k==="not-analyzed"&&(E=n("button",{onClick:$=>{$.stopPropagation(),P.filter(R=>(R.entityType==="visual"||R.entityType==="library")&&!s(R.sha)&&!a(R)).forEach(R=>p(R))},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(io,{filePath:v,isExpanded:N,onToggle:()=>m(v),fileStatus:C,simulationPreviews:n(lo,{entities:P,maxPreviews:1}),entityCount:P.length,state:k,lastModified:_,isNotAnalyzable:T,isUncommitted:!0,actionButton:E,children:P.sort(($,R)=>{const I=$.entityType==="visual"||$.entityType==="library",W=R.entityType==="visual"||R.entityType==="library";return I&&!W?-1:!I&&W?1:0}).map($=>n(co,{entity:$,isActivelyAnalyzing:s($.sha),isQueued:a($),onGenerateSimulation:p},$.sha))},v)})})]})}function zN({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:s}){return n("div",{className:"border-b border-gray-200",children:d("nav",{className:"flex gap-8 items-center",children:[d("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[d("span",{className:"flex items-center gap-2",children:["Branch Changes",s>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="branch"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:s})]}),e==="branch"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]}),d("button",{onClick:()=>t("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[d("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:r})]}),e==="uncommitted"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const BN=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function YN({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const s=t.get("filePath"),a=t.get("diffType"),o=t.get("baseBranch"),i=t.get("currentBranch"),l=t.get("entitySha");let c;return a==="branch"?c=Sr(s,o,i):c=Wf(s),Q({...c,entitySha:l})}return Q({error:"Unknown action"},{status:400})}async function UN({request:e,context:t}){try{const r=new URL(e.url),s=r.searchParams.get("compare"),a=r.searchParams.get("viewBranch"),o=t.analysisQueue,i=o?o.getState():{paused:!1,jobs:[]},[l,c,m]=await Promise.all([mn(),_n(),Ie()]),u=jn(),p=zf(),h=Bf(),f=Yf(),y=a||p,g=s||h;let x=[];return y&&y!==g&&(x=Ql(g,y)),Q({entities:l||[],gitStatus:u,currentBranch:y,actualCurrentBranch:p,defaultBranch:h,allBranches:f,baseBranch:g,branchDiff:x,currentCommit:c,projectSlug:m,queueState:i})}catch(r){return console.error("Failed to load git data:",r),Q({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 WN=Je(function(){var ke,et;const{entities:t,gitStatus:r,currentBranch:s,actualCurrentBranch:a,defaultBranch:o,allBranches:i,baseBranch:l,branchDiff:c,currentCommit:m,projectSlug:u,queueState:p}=qe();xt({source:"git-page"});const[h,f]=Cn(),[y,g]=M(null),[x,b]=M("desc"),[w,v]=M("branch"),C=h.get("expanded")==="true",P=()=>{b(ge=>ge==="desc"?"asc":"desc")},N=Fe(),S=N.data;ne(()=>{s&&l&&s!==l&&N.state==="idle"&&!S&&N.load(`/api/branch-entity-diff?base=${encodeURIComponent(l)}&compare=${encodeURIComponent(s)}`)},[s,l,N,S]);const k=ae(()=>{const ge=jc(r,t);return Array.from(ge.entries()).sort((Ye,We)=>Ye[0].localeCompare(We[0]))},[r,t]),_=ae(()=>{const ge=cv(c,t,S);return Array.from(ge.entries()).sort((Ye,We)=>Ye[0].localeCompare(We[0]))},[c,t,S]),j=ae(()=>dv(r,t),[r,t]),T=ae(()=>w==="uncommitted"?k:_,[w,k,_]),E=ae(()=>T.map(([ge])=>ge),[T]),{expandedUncommitted:$,setExpandedUncommitted:R,toggleFile:I,expandAllUncommitted:W,collapseAllUncommitted:Y}=RN(C,E,[]),{diffView:U,diffContent:B,isLoading:H,handleShowFileDiff:D,handleCloseDiff:A}=DN(l,s),J=(ke=m==null?void 0:m.metadata)==null?void 0:ke.currentRun,V=new Set((J==null?void 0:J.currentEntityShas)||[]),q=new Set(p.jobs.flatMap(ge=>ge.entityShas||[])),X=new Set(((et=p.currentlyExecuting)==null?void 0:et.entityShas)||[]),{isAnalyzing:L,handleGenerateSimulation:O,handleGenerateAllSimulations:z,isEntityBeingAnalyzed:G,isEntityPending:ee}=Dc(J==null?void 0:J.currentEntityShas,p),re=ge=>ee(ge)||q.has(ge.sha)||X.has(ge.sha),ue=ge=>{ge===(a||s)?h.delete("viewBranch"):h.set("viewBranch",ge),f(h)},se=ge=>{ge===o?h.delete("compare"):h.set("compare",ge),f(h)},pe=()=>{const Ye=T.flatMap(([We,Ht])=>Ht.editedEntities||Ht.entities||[]).filter(We=>!V.has(We.sha)&&!q.has(We.sha)&&!X.has(We.sha)&&!ee(We));z(Ye)},Ce=k.length,_e=_.length,Ae=T.flatMap(([ge,Ye])=>Ye.editedEntities||Ye.entities||[]),De=Ae.filter(ge=>ge.entityType==="visual"||ge.entityType==="library"),Le=De.length>0&&De.every(ge=>V.has(ge.sha)),Se=De.length>0&&!Le&&De.every(ge=>q.has(ge.sha)||X.has(ge.sha)),oe=L||Le||Se,xe=Le?"Analyzing...":Se?"Queued...":L?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-20 py-12",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Git Changes"}),d("p",{className:"text-[15px] text-gray-500",children:["This is a list of all the files that are affected by your local changes. ",n("strong",{children:"Analyze a file to get simulations."})]})]}),n("div",{className:"mb-6",children:n(zN,{activeTab:w,onTabChange:v,uncommittedCount:Ce,branchCount:_e})}),s&&w==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:s===o?d("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:o}),"."]}):d("div",{className:"flex gap-6 items-center",children:[d("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?d("div",{className:"relative w-50",children:[n("select",{value:s,onChange:ge=>ue(ge.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(ge=>n("option",{value:ge,children:ge},ge))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}):n("span",{className:"text-gray-900 font-medium text-[12px]",children:s})]}),d("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),d("div",{className:"relative w-[200px]",children:[n("select",{value:l,onChange:ge=>se(ge.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(ge=>ge!==s).map(ge=>n("option",{value:ge,children:ge},ge))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children:d("div",{className:"relative flex items-center",children:[n("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),n("div",{className:"mb-3",children:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center",children:[d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:T.length})," ","modified ",T.length===1?"file":"files"]}),d("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:d("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:Ae.length})," ",Ae.length===1?"entity":"entities"]})]}),T.length>0&&d("div",{className:"flex gap-6",children:[d("button",{onClick:W,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(Wi,{className:"w-3.5 h-3.5"}),"Expand All"]}),d("button",{onClick:Y,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(Hi,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),d("div",{className:"overflow-hidden",children:[w==="branch"&&s&&n(LN,{files:_,currentBranch:s,defaultBranch:o,baseBranch:l,allBranches:i,expandedFiles:$,isEntityBeingAnalyzed:G,isEntityQueued:re,sortOrder:x,onToggleFile:ge=>I(ge,$,R),onBranchChange:se,onGenerateSimulation:O,onSortChange:P,onAnalyzeAll:pe,analyzeAllDisabled:oe,analyzeAllText:xe}),w==="uncommitted"&&n(FN,{files:k,entityImpactMap:j,expandedFiles:$,isEntityBeingAnalyzed:G,isEntityQueued:re,projectSlug:u,baseBranch:l,currentBranch:s,sortOrder:x,onToggleFile:ge=>I(ge,$,R),onShowFileDiff:D,onGenerateSimulation:O,onSortChange:P,onAnalyzeAll:pe,analyzeAllDisabled:oe,analyzeAllText:xe})]}),U&&n(ON,{diffView:U,diffContent:B,isLoading:H,entities:t,onClose:A}),y&&u&&n(Ft,{projectSlug:u,onClose:()=>g(null)})]})})}),HN=Object.freeze(Object.defineProperty({__proto__:null,action:YN,default:WN,loader:UN,meta:BN},Symbol.toStringTag,{value:"Module"})),GC={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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/root-CHOdrM6Y.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-BzHcG7SE.js","/assets/useReportContext-O-jkvSPx.js","/assets/loader-circle-DaAZ_H2w.js","/assets/createLucideIcon-CC6AbExI.js","/assets/book-open-BYOypzCa.js","/assets/useToast-9FIWuYfK.js","/assets/useLastLogLine-C14nCb1q.js","/assets/LogViewer-ceAyBX-H.js","/assets/EntityTypeIcon-CQIG2qda.js","/assets/TruncatedFilePath-C8OKAR5x.js","/assets/chevron-down-C_Pmso5S.js","/assets/circle-check-BVMi9VA5.js","/assets/CopyButton-BPXZwM4t.js","/assets/triangle-alert-BLdiCuG-.js","/assets/copy-n2FB0_Sw.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.fullscreen-CF164ouH.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/Spinner-Bb5uFQ5V.js","/assets/useLastLogLine-C14nCb1q.js","/assets/ViewportInspectBar-oAf2Kqsf.js","/assets/useCustomSizes-CrAK28Bc.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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.dev-C7YX6r3H.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/Spinner-Bb5uFQ5V.js","/assets/useLastLogLine-C14nCb1q.js","/assets/ViewportInspectBar-oAf2Kqsf.js","/assets/useCustomSizes-CrAK28Bc.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/InlineSpinner-Bu6c6aDe.js","/assets/editorPreview-BLQMSKZa.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,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-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,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-register-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-coverage":{id:"routes/api.editor-scenario-coverage",parentId:"root",path:"api/editor-scenario-coverage",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-coverage-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha_.create-scenario-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,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-capture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-switch-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-update-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-client-errors-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-entity-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-entry-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-project-info":{id:"routes/api.editor-project-info",parentId:"root",path:"api/editor-project-info",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-project-info-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-test-results-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-load-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.agent-transcripts-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-dev-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.logs._projectSlug-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-file-diff":{id:"routes/api.editor-file-diff",parentId:"root",path:"api/editor-file-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.execute-function-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-mode-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.delete-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.dev-mode-events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.generate-report-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-refresh-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.memory-profile-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.restart-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/agent-transcripts-Bni3iiUj.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/createLucideIcon-CC6AbExI.js","/assets/terminal-Br7MOqts.js","/assets/search-Di64LWVb.js","/assets/chevron-down-C_Pmso5S.js","/assets/book-open-BYOypzCa.js","/assets/triangle-alert-BLdiCuG-.js","/assets/copy-n2FB0_Sw.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-audit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.save-fixture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-BcY3q6nt.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/LogViewer-ceAyBX-H.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityTypeIcon-CQIG2qda.js","/assets/EntityTypeBadge-g3saevPb.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LoadingDots-BU_OAEMP.js","/assets/loader-circle-DaAZ_H2w.js","/assets/pause-f5-1lKBt.js","/assets/createLucideIcon-CC6AbExI.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.debug-setup-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.labs-unlock-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.rule-path-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha._-BF4oLwaE.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-0DY_NKil.js","/assets/createLucideIcon-CC6AbExI.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-CQIG2qda.js","/assets/CopyButton-BPXZwM4t.js","/assets/LogViewer-ceAyBX-H.js","/assets/useReportContext-O-jkvSPx.js","/assets/preload-helper-ckwbz45p.js","/assets/InlineSpinner-Bu6c6aDe.js","/assets/ViewportInspectBar-oAf2Kqsf.js","/assets/useCustomSizes-CrAK28Bc.js","/assets/ReportIssueModal-BzHcG7SE.js","/assets/circle-check-BVMi9VA5.js","/assets/triangle-alert-BLdiCuG-.js","/assets/copy-n2FB0_Sw.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.analyze-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/simulations-DWT-CvLy.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LoadingDots-BU_OAEMP.js","/assets/EntityTypeIcon-CQIG2qda.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/chevron-down-C_Pmso5S.js","/assets/search-Di64LWVb.js","/assets/loader-circle-DaAZ_H2w.js","/assets/createLucideIcon-CC6AbExI.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.health-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.memory-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.queue-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/dev.empty-Csi0_PMl.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/ScenarioViewer-0DY_NKil.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/ViewportInspectBar-oAf2Kqsf.js","/assets/useCustomSizes-CrAK28Bc.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-BzHcG7SE.js","/assets/createLucideIcon-CC6AbExI.js","/assets/circle-check-BVMi9VA5.js","/assets/triangle-alert-BLdiCuG-.js","/assets/copy-n2FB0_Sw.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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/settings-0OrEMU6J.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/CopyButton-BPXZwM4t.js","/assets/copy-n2FB0_Sw.js","/assets/createLucideIcon-CC6AbExI.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/static._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/_index-DLxKhri3.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-CQIG2qda.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-CC6AbExI.js","/assets/circle-check-BVMi9VA5.js","/assets/loader-circle-DaAZ_H2w.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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor-BBAGP_mE.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useCustomSizes-CrAK28Bc.js","/assets/editorPreview-BLQMSKZa.js","/assets/CopyButton-BPXZwM4t.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/Spinner-Bb5uFQ5V.js","/assets/copy-n2FB0_Sw.js","/assets/createLucideIcon-CC6AbExI.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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/memory-9gnxSZlb.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/createLucideIcon-CC6AbExI.js","/assets/terminal-Br7MOqts.js","/assets/copy-n2FB0_Sw.js","/assets/CopyButton-BPXZwM4t.js","/assets/chevron-down-C_Pmso5S.js","/assets/search-Di64LWVb.js","/assets/pause-f5-1lKBt.js","/assets/book-open-BYOypzCa.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/files-BZrlFE1F.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityItem-BcgbViKV.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/chevron-down-C_Pmso5S.js","/assets/search-Di64LWVb.js","/assets/createLucideIcon-CC6AbExI.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-BLdiCuG-.js","/assets/EntityTypeIcon-CQIG2qda.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,hasDefaultExport:!0,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,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/git-DdZcvjGh.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityItem-BcgbViKV.js","/assets/LogViewer-ceAyBX-H.js","/assets/index-yHOVb4rc.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/createLucideIcon-CC6AbExI.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-BLdiCuG-.js","/assets/EntityTypeIcon-CQIG2qda.js","/assets/EntityTypeBadge-g3saevPb.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-9c70d1f3.js",version:"9c70d1f3",sri:void 0},KC="build/client",qC="/",QC={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,unstable_previewServerPrerendering:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},ZC=!0,XC=!1,eS=[],tS={mode:"lazy",manifestPath:"/__manifest"},nS="/",rS={module:au},sS={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:dh},"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:fh},"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:Mh},"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:$h},"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:tf},"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:eg},"routes/api.editor-scenario-coverage":{id:"routes/api.editor-scenario-coverage",parentId:"root",path:"api/editor-scenario-coverage",index:void 0,caseSensitive:void 0,module:og},"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:pg},"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:gg},"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:xg},"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:wg},"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:Ng},"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:S0},"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:O0},"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:F0},"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:B0},"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:U0},"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:H0},"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:G0},"routes/api.editor-project-info":{id:"routes/api.editor-project-info",parentId:"root",path:"api/editor-project-info",index:void 0,caseSensitive:void 0,module:q0},"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:ey},"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:iy},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:cy},"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:wy},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:Sy},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:Ly},"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:Yy},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:Hy},"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:Vy},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,module:Ky},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:Zy},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:tx},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:rx},"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:ox},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:yx},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,module:bx},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,module:_x},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:Tx},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:Dx},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:zx},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:Yx},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:sb},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,module:ob},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,module:pb},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:fb},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:vb},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:Cb},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:$b},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:Db},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,module:Lb},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,module:Yb},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:Wb},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,module:Kb},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:xw},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:vw},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:Aw},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:jw},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:Tw},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:Jw},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:Kw},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:Zw},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:av},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:iv},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:gv},"routes/editor":{id:"routes/editor",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,module:Gv},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:bN},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:kN},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:IN},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:HN}},aS=!1;export{Vu as $,Ym as A,Fm as B,Hm as C,Dm as D,je as E,om as F,im as G,un as H,zC as I,ku as J,_u as K,Au as L,Pu as M,Xi as N,Mu as O,Tu as P,el as Q,Iu as R,Ru as S,qu as T,tl as U,Fu as V,Bu as W,Yu as X,Uu as Y,Hu as Z,Ju as _,xu as a,Gu as a0,Cu as a1,Su as a2,Ku as a3,$r as a4,Zu as a5,Xu as a6,em as a7,tm as a8,rm as a9,nm as aa,il as ab,qm as ac,Qm as ad,WC as ae,HC as af,Cx as ag,VC as ah,Wt as ai,BC as aj,YC as ak,UC as al,KC as am,qC as an,QC as ao,ZC as ap,XC as aq,eS as ar,tS as as,nS as at,rS as au,sS as av,aS as aw,GC as ax,ln as b,on as c,At as d,sr as e,Pa as f,Qr as g,Zi as h,gu as i,wm as j,vm as k,zt as l,Pt as m,Ma as n,Pm as o,Rr as p,st as q,sl as r,al as s,Ta as t,Lt as u,ol as v,En as w,vn as x,xm as y,To as z};
|