@codeyam/codeyam-cli 0.1.30 → 0.1.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/analyzer-template/.build-info.json +7 -7
  2. package/analyzer-template/log.txt +3 -3
  3. package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js +1 -0
  4. package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js.map +1 -1
  5. package/codeyam-cli/src/commands/editor.js +39 -0
  6. package/codeyam-cli/src/commands/editor.js.map +1 -1
  7. package/codeyam-cli/src/commands/init.js +3 -2
  8. package/codeyam-cli/src/commands/init.js.map +1 -1
  9. package/codeyam-cli/src/utils/__tests__/editorRoadmap.test.js +712 -2
  10. package/codeyam-cli/src/utils/__tests__/editorRoadmap.test.js.map +1 -1
  11. package/codeyam-cli/src/utils/__tests__/envFile.test.js +125 -0
  12. package/codeyam-cli/src/utils/__tests__/envFile.test.js.map +1 -0
  13. package/codeyam-cli/src/utils/__tests__/handoffContext.test.js +500 -0
  14. package/codeyam-cli/src/utils/__tests__/handoffContext.test.js.map +1 -0
  15. package/codeyam-cli/src/utils/editorRoadmap.js +290 -17
  16. package/codeyam-cli/src/utils/editorRoadmap.js.map +1 -1
  17. package/codeyam-cli/src/utils/envFile.js +90 -0
  18. package/codeyam-cli/src/utils/envFile.js.map +1 -0
  19. package/codeyam-cli/src/utils/handoffContext.js +257 -0
  20. package/codeyam-cli/src/utils/handoffContext.js.map +1 -0
  21. package/codeyam-cli/src/utils/install-skills.js +9 -0
  22. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  23. package/codeyam-cli/src/utils/techStackConfig.js +38 -0
  24. package/codeyam-cli/src/utils/techStackConfig.js.map +1 -0
  25. package/codeyam-cli/src/utils/techStackConfig.test.js +85 -0
  26. package/codeyam-cli/src/utils/techStackConfig.test.js.map +1 -0
  27. package/codeyam-cli/src/webserver/__tests__/buildPtyEnv.test.js +119 -1
  28. package/codeyam-cli/src/webserver/__tests__/buildPtyEnv.test.js.map +1 -1
  29. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  30. package/codeyam-cli/src/webserver/build/client/assets/{MiniClaudeChat-BusrvT2F.js → MiniClaudeChat-Bs2_Oua4.js} +1 -1
  31. package/codeyam-cli/src/webserver/build/client/assets/api.editor-database-verify-l0sNRNKZ.js +1 -0
  32. package/codeyam-cli/src/webserver/build/client/assets/api.editor-github-verify-l0sNRNKZ.js +1 -0
  33. package/codeyam-cli/src/webserver/build/client/assets/api.editor-handoff-l0sNRNKZ.js +1 -0
  34. package/codeyam-cli/src/webserver/build/client/assets/api.editor-hosting-verify-l0sNRNKZ.js +1 -0
  35. package/codeyam-cli/src/webserver/build/client/assets/editor.entity.(_sha)-DOXe0Qx7.js +161 -0
  36. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-Ce1s4OQ1.js → entity._sha._-pc-vc6wO.js} +1 -1
  37. package/codeyam-cli/src/webserver/build/client/assets/globals-L-aUIeux.css +1 -0
  38. package/codeyam-cli/src/webserver/build/client/assets/manifest-30c44d84.js +1 -0
  39. package/codeyam-cli/src/webserver/build/client/assets/{root-Didv9PLi.js → root-CLedrjXQ.js} +3 -3
  40. package/codeyam-cli/src/webserver/build/server/assets/{analysisRunner-BKMsxwqe.js → analysisRunner-CuR5TvUx.js} +1 -1
  41. package/codeyam-cli/src/webserver/build/server/assets/{index-CvuvIPEn.js → index-D4MWAsqb.js} +1 -1
  42. package/codeyam-cli/src/webserver/build/server/assets/init-JObA4lXD.js +14 -0
  43. package/codeyam-cli/src/webserver/build/server/assets/server-build-i8OXK4oL.js +765 -0
  44. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  45. package/codeyam-cli/src/webserver/build-info.json +5 -5
  46. package/codeyam-cli/src/webserver/terminalServer.js +81 -11
  47. package/codeyam-cli/src/webserver/terminalServer.js.map +1 -1
  48. package/codeyam-cli/templates/codeyam-editor-codex.md +61 -0
  49. package/codeyam-cli/templates/nextjs-prisma-sqlite/gitignore +1 -0
  50. package/codeyam-cli/templates/seed-adapters/supabase.ts +143 -31
  51. package/package.json +1 -1
  52. package/codeyam-cli/src/webserver/build/client/assets/editor.entity.(_sha)-CsYVRiNH.js +0 -147
  53. package/codeyam-cli/src/webserver/build/client/assets/globals-Gp2o-NMc.css +0 -1
  54. package/codeyam-cli/src/webserver/build/client/assets/manifest-ef0f624d.js +0 -1
  55. package/codeyam-cli/src/webserver/build/server/assets/init-B3gVLAAJ.js +0 -14
  56. package/codeyam-cli/src/webserver/build/server/assets/server-build-B4LxStYP.js +0 -741
@@ -1,741 +0,0 @@
1
- var qp=Object.defineProperty;var fl=e=>{throw TypeError(e)};var Qp=(e,t,r)=>t in e?qp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ht=(e,t,r)=>Qp(e,typeof t!="symbol"?t+"":t,r),Zp=(e,t,r)=>t.has(e)||fl("Cannot "+r);var gl=(e,t,r)=>(Zp(e,t,"read from private field"),r?r.call(e):t.get(e)),yl=(e,t,r)=>t.has(e)?fl("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 ve}from"react/jsx-runtime";import{PassThrough as Xp}from"node:stream";import{createReadableStreamFromReadable as eh}from"@react-router/node";import{ServerRouter as th,useFetcher as Ge,useLocation as Jr,useNavigate as Dt,Link as ke,UNSAFE_withComponentProps as et,Meta as nh,Links as rh,ScrollRestoration as sh,Scripts as ah,UNSAFE_withErrorBoundaryProps as oh,useRouteError as ih,isRouteErrorResponse as Wa,useLoaderData as ot,useRevalidator as Rt,Outlet as td,data as re,useSearchParams as ir,useRouteLoaderData as nd,useParams as rd,useActionData as lh,redirect as ch}from"react-router";import{isbot as dh}from"isbot";import{renderToPipeableStream as uh}from"react-dom/server";import{useState as A,useEffect as ne,useCallback as oe,createContext as zo,useContext as Zs,useRef as ye,useMemo as le,forwardRef as ph,useImperativeHandle as hh,Component as mh}from"react";import{Settings as xl,CheckCircle2 as Bo,Bug as sd,AlertTriangle as Ds,Check as Et,Copy as It,Loader2 as $t,PencilRuler as fh,HomeIcon as gh,GitCommitIcon as bl,File as yh,RefreshCw as xh,BookOpen as Rs,FlaskConical as bh,SettingsIcon as vh,PanelsTopLeftIcon as wh,ComponentIcon as Nh,FileText as vl,Code as wl,Box as Sh,List as Ch,BarChart3 as kh,Tag as _h,Image as Lr,Code2 as ad,Activity as Ua,ChevronDown as kt,CircleEqual as Eh,ArrowLeft as jh,Terminal as Os,Search as Hr,ChevronLeft as Ah,ChevronRight as pn,Save as Ph,MessageSquare as Th,Pause as od,ListTodo as Mh,PauseCircle as $h,FileCode as Ls,GripVertical as Ih,Ban as Fh,CheckCircle as Dh,FolderOpen as Rh,CodeXml as Oh,Zap as Lh,Pencil as zh,Trash2 as Bh,X as lr,Folder as id,Info as xo,Plus as Yo,Eye as Yh,FolderTree as Wh,ChevronsUpDown as ld,ChevronsDownUp as cd}from"lucide-react";import"fetch-retry";import Uh from"better-sqlite3";import{Pool as Jh}from"pg";import*as G from"fs";import ue,{existsSync as Ct,readdirSync as Hh,rmSync as Ja,readFileSync as Nl}from"fs";import*as H from"path";import ee,{join as zr}from"path";import{OperationNodeTransformer as Vh,sql as mt,Kysely as dd,ParseJSONResultsPlugin as Kh,SqliteDialect as Gh,PostgresDialect as qh}from"kysely";import*as Qh from"kysely/helpers/sqlite";import*as Zh from"kysely/helpers/postgres";import Ze from"typescript";import*as Ae from"fs/promises";import Pe,{writeFile as $r,readFile as bo,mkdir as Xh}from"fs/promises";import*as Xs from"os";import vo,{homedir as em}from"os";import tm from"prompts";import zs from"chalk";import*as Wo from"crypto";import cr,{randomUUID as Uo,createHmac as nm}from"crypto";import{execSync as De,spawn as xt,exec as Jo}from"child_process";import{fileURLToPath as ea}from"url";import{promisify as Ho}from"util";import rm from"dotenv";import sm,{EventEmitter as Vr}from"events";import{v4 as am}from"uuid";import Vo from"http";import ud from"net";import{WebSocket as Ko}from"ws";import"node-pty";import om from"openai";import im from"p-queue";import Sl from"p-retry";import{DynamoDBClient as ta,PutItemCommand as lm}from"@aws-sdk/client-dynamodb";import{LRUCache as Go}from"lru-cache";import"pluralize";import"piscina";import cm from"json5";import{marshall as dm}from"@aws-sdk/util-dynamodb";import um from"v8";import{Prism as pm}from"react-syntax-highlighter";import{vscDarkPlus as hm}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as mm}from"node:crypto";import{minimatch as wo}from"minimatch";import fm from"react-markdown";import gm from"remark-gfm";import ym from"react-diff-viewer-continued";const pd=5e3;function xm(e,t,r,s,a){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let l=!1,c=e.headers.get("user-agent"),p=c&&dh(c)||s.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>m(),pd+1e3);const{pipe:h,abort:m}=uh(n(th,{context:s,url:e.url}),{[p](){l=!0;const f=new Xp({final(g){clearTimeout(u),u=void 0,g()}}),y=eh(f);r.set("Content-Type","text/html"),h(f),o(new Response(y,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const bm=Object.freeze(Object.defineProperty({__proto__:null,default:xm,streamTimeout:pd},Symbol.toStringTag,{value:"Module"})),vm=2e3,wm=5e3;function Nm(e){return e.startsWith("/editor")?wm:vm}function Sm(e){const{now:t,lastRevalidation:r,throttleMs:s}=e;if(r===0)return"immediate";const a=t-r;return a>=s?"immediate":{action:"deferred",delayMs:s-a}}function Cm({id:e,selected:t,onClick:r,icon:s,name:a}){const[o,i]=A(!1);ne(()=>{i(!0)},[]);const l=oe(()=>{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 na="/assets/cy-logo-cli-DoA97ML3.svg";function km(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 _m({content:e,className:t=""}){const[r,s]=A(!1),a=oe(()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),2e3)}).catch(o=>{console.error("Failed to copy:",o)})},[e]);return n("button",{onClick:a,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?d(ve,{children:[n(Et,{size:14}),"Copied"]}):d(ve,{children:[n(It,{size:14}),"Copy"]})})}function hd({isOpen:e,onClose:t,context:r,defaultEmail:s="",screenshotDataUrl:a}){const[o,i]=A(""),[l,c]=A(s),[p,u]=A(!1),[h,m]=A(!1),[f,y]=A(null),[g,x]=A(null),b=Ge(),v=b.state!=="idle",N=!!(r.scenarioId||r.analysisId),w=r.analysisId||r.scenarioId||"",C=()=>{const _=`/codeyam-diagnose ${w}`;return o.trim()?`${_} ${o.trim()}`:_};if(b.data&&!h&&!g){const _=b.data;_.success&&_.reportId?(m(!0),y(_.reportId)):_.error&&x(_.error)}const S=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 M=await(await fetch(a)).blob();_.append("screenshot",M,"screenshot.jpg")}catch(F){console.error("Failed to convert screenshot:",F)}b.submit(_,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},k=()=>{i(""),u(!1),m(!1),y(null),x(null),t()},j=_=>{_.key==="Escape"&&k()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:j,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:[v?n("div",{className:"animate-spin",children:n(xl,{size:24,style:{strokeWidth:1.5}})}):h?n(Bo,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(sd,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:h?"Report Submitted":"Report Issue"})]}),n("button",{onClick:k,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),h?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:k,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):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:km(r)}),n("button",{type:"button",onClick:()=>u(!p),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:p?"Hide":"Details"})]}),p&&d("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[d("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),d("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&d("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&d("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&d("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),a&&d("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:a,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),d("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:o,onChange:_=>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"})]}),N&&d(ve,{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:C()}),n(_m,{content:C(),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:N?"opacity-75":"",children:[N&&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(Ds,{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."})]})]}),v&&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(Ds,{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:k,disabled:v,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 S(),disabled:v,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:v?d(ve,{children:[n("div",{className:"animate-spin",children:n(xl,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):g?"Try Again":"Submit Report"})]})]})]})]})}):null}const Cl={source:"navbar"},qo=zo(void 0);function Em({children:e}){const[t,r]=A(Cl),s=oe(o=>{r(o)},[]),a=oe(()=>{r(Cl)},[]);return n(qo.Provider,{value:{contextData:t,setContextData:s,resetContextData:a},children:e})}function Ot(e){const t=Zs(qo),r=ye(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 jm(){const e=Zs(qo),t=Jr();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 Am({labs:e,isAdmin:t,editorMode:r}){var S;const s=Jr(),a=Dt(),[o,i]=A(),[l,c]=A(!1),[p,u]=A(!1),[h,m]=A(null),f=Ge();ne(()=>{f.state==="idle"&&!f.data&&f.load("/api/generate-report")},[f]);const y=((S=f.data)==null?void 0:S.defaultEmail)||"",g={width:"20px",height:"20px",strokeWidth:1.5},x=(e==null?void 0:e.simulations)??!1,b=[{id:"editor",icon:n(fh,{style:g}),link:"/editor",name:"Editor",hidden:!r,newTab:!0},{id:"dashboard",icon:n(gh,{style:g}),link:"/",name:"Dashboard",hidden:!x||r},{id:"simulations",icon:d("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style: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||r},{id:"git",icon:n(bl,{style:g}),link:"/git",name:"Git",hidden:!x||r},{id:"files",icon:n(yh,{style:g}),link:"/files",name:"Files",hidden:!x||r},{id:"activity",icon:n(xh,{style:g}),link:"/activity",name:"Activity",hidden:!x||r},{id:"memory",icon:n(Rs,{style:g}),link:"/memory",name:"Memory"},{id:"labs",icon:n(bh,{style:g}),link:"/labs",name:"Labs"},{id:"settings",icon:n(vh,{style:g}),link:"/settings",name:"Settings"},{id:"commits",icon:n(bl,{style:g}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(wh,{style:g}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(Nh,{style:g}),link:"/components",name:"Components",hidden:!0}],v=oe(k=>{const j=b.find(_=>_.id===k);j!=null&&j.link&&(j.newTab?window.open(j.link,"_blank"):a(j.link)),i(_=>_===k?void 0:k)},[b,a]);ne(()=>{const k={editor:["editor"],dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],memory:["memory","agent-transcripts"],files:["files"],labs:["labs"],settings:["settings"],pages:["pages"],components:["components"]};for(const[j,_]of Object.entries(k))if(_.some(F=>F==="/"?s.pathname==="/":s.pathname.includes(F))){i(j);return}i(void 0)},[s]);const N=async()=>{u(!0);try{const{default:k}=await import("html2canvas-pro"),_=(await k(document.body)).toDataURL("image/jpeg",.8);m(_),c(!0)}catch(k){console.error("Screenshot capture failed:",k),c(!0)}finally{u(!1)}},w=()=>{c(!1),m(null)},C=jm();return d(ve,{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(ke,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:na,alt:"CodeYam",className:"h-6"})})}),b.filter(k=>!k.hidden).map(k=>n(Cm,{id:k.id,selected:k.id===o,onClick:v,icon:k.icon,name:k.name},`sidebar-button-${k.id}`))]}),t&&n("div",{className:"w-full flex flex-col items-center pb-2",children:d("button",{onClick:()=>void N(),disabled:p,className:"w-full px-1.5 py-2 flex flex-col items-center justify-center gap-1 text-[#568B94] hover:text-[#CBF3FA] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait",children:[n("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center",children:p?n($t,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n(sd,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:p?"Capturing...":`Report
6
- Bug`})]})})]}),l&&n(hd,{isOpen:!0,onClose:w,context:C,defaultEmail:y,screenshotDataUrl:h??void 0})]})}const md=zo(void 0);function Pm({children:e}){const[t,r]=A([]),s=oe((o,i="info",l=5e3)=>{const p={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:l};r(u=>[...u,p])},[]),a=oe(o=>{r(i=>i.filter(l=>l.id!==o))},[]);return n(md.Provider,{value:{toasts:t,showToast:s,closeToast:a},children:e})}function Qo(){const e=Zs(md);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Tm({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 Mm({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(Tm,{toast:r,onClose:t},r.id))]})}function Jt(e,t){const[r,s]=A(""),[a,o]=A(!1),[i,l]=A(null),[c,p]=A(null),[u,h]=A(!1);ne(()=>{t&&(h(!1),o(!1),l(null),p(null))},[t]),ne(()=>{if(!e||!t){t||s("");return}const f=async()=>{if(!u)try{const g=await fetch(`/api/logs/${e}`);if(g.ok){const b=(await g.text()).trim().split(`
18
- `).filter(C=>C.length>0);if(b.length<3){o(!1),h(!1),l(null),p(null),s("");return}const v=b.filter(C=>C.includes("CodeYam Log Level 1"));if(v.length>0){const C=v[v.length-1];s(C.replace(/.*CodeYam Log Level 1: /,""))}const N=b.find(C=>C.includes("$$INTERACTIVE_SERVER_URL$$:"));if(N){const C=N.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();l(C),h(!0)}const w=b.find(C=>C.includes("$$INTERACTIVE_SCENARIO_URLS$$:"));if(w)try{const C=w.split("$$INTERACTIVE_SCENARIO_URLS$$:")[1].trim();p(JSON.parse(C))}catch{}b.some(C=>C.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};f().catch(()=>{});const y=setInterval(()=>{f().catch(()=>{})},500);return()=>clearInterval(y)},[e,t,u]);const m=oe(()=>{s(""),o(!1),l(null),p(null),h(!1)},[]);return{lastLine:r,interactiveUrl:i,scenarioUrlMap:c,isCompleted:a,resetLogs:m}}function on({projectSlug:e,onClose:t}){const[r,s]=A("Loading logs..."),[a,o]=A(!0),[i,l]=A(!0),[c,p]=A("all"),u=ye(null);return ne(()=>{const h=async()=>{try{const m=await fetch(`/api/logs/${e}`);if(m.ok){const f=await m.text();if(c==="all")s(f);else{const 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: ${m.status} - ${await m.text()}`)}catch(m){s(`Error fetching logs: ${m.message}`)}};if(h().catch(()=>{}),a){const m=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(m)}},[e,a,i,c]),ne(()=>{const h=m=>{m.key==="Escape"&&t()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:d("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:h=>h.stopPropagation(),children:[d("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[d("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),d("div",{className:"flex items-center gap-4",children:[d("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),d("select",{value:c,onChange:h=>p(h.target.value==="all"?"all":Number(h.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),d("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:a,onChange:h=>o(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),d("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:h=>l(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:u,children:r})]})})}function gt({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(ad,{size:a,color:s.iconColor});case"visual":return n(Lr,{size:a,color:s.iconColor});case"type":return n(_h,{size:a,color:s.iconColor});case"data":return n(kh,{size:a,color:s.iconColor});case"index":return n(Ch,{size:a,color:s.iconColor});case"functionCall":return n(wl,{size:a,color:s.iconColor});case"class":return n(Sh,{size:a,color:s.iconColor});case"method":return n(wl,{size:a,color:s.iconColor});case"other":return n(vl,{size:a,color:s.iconColor});default:return n(vl,{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 fd({filePath:e,maxLength:t=60,className:r,style:s}){const o=((l,c)=>{if(l.length<=c)return l;const p="...",u=c-p.length,h=Math.ceil(u*.4),m=Math.floor(u*.6),f=l.slice(0,h),y=l.slice(-m),g=f.lastIndexOf("/"),x=y.indexOf("/"),b=g>h*.5?f.slice(0,g+1):f,v=x!==-1&&x<m*.5?y.slice(x):y;return`${b}${p}${v}`})(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 Ha({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(gt,{type:e.entityType||"other"}),d(ke,{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(fd,{filePath:e.filePath,maxLength:s,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const Va={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function $m({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:s=!1,queuedJobCount:a=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:l=[]}){var Y,I,L;const[c,p]=A(!1),[u,h]=A(!1),[m,f]=A(null),[y,g]=A(new Set),[x,b]=A(new Set),[v,N]=A(!1),w=!!i||o.length>0,C=!!i,S=(i==null?void 0:i.entities)||r,k=!!(e!=null&&e.analysisCompletedAt),j=(e==null?void 0:e.readyToBeCaptured)??0,_=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||k&&(j===0||_>=j);const F=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,M=w,{lastLine:$}=Jt(t,M),O=C||o.length>0,D=new Set(((Y=i==null?void 0:i.entities)==null?void 0:Y.map(P=>P.sha))||[]),T=l.filter(P=>!(P.currentEntityShas||[]).some(E=>D.has(E))),B=(()=>{const R=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&F){const E=e.analysisCompletedAt||e.createdAt;if(new Date(E).getTime()>R)return!0}if(T.length>0){const E=T[0],J=E.analysisCompletedAt||E.archivedAt||E.createdAt;if(J&&new Date(J).getTime()>R)return!0}return!1})();return ne(()=>{const P=(i==null?void 0:i.id)||null;w&&!u&&P!==m&&h(!0),!w&&m!==null&&f(null)},[w,i==null?void 0:i.id,u,m]),d(ve,{children:[d("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${u?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!u&&d("div",{onClick:()=>{h(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[O?n($t,{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(Ua,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:O?"Analyzing...":"Activity: No Activity Yet"}),O&&n("button",{onClick:P=>{P.stopPropagation(),p(!0)},className:"ml-auto px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),u&&d("div",{children:[d("div",{className:"flex items-center justify-between px-3 py-2",children:[d("div",{className:"flex items-center gap-2",children:[O?n($t,{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(Ua,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:O?"Analyzing...":"Activity"})]}),d("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>p(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{h(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:n(kt,{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:[O&&i&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Ua,{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:S.length>0?d("div",{className:"space-y-1.5",children:[(v?S:S.slice(0,3)).map(P=>n(Ha,{entity:P,nameSize:"11px",pathSize:"10px",pathMaxLength:150},P.sha)),S.length>3&&n("button",{onClick:()=>N(P=>!P),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Va,"aria-label":v?"Show fewer entities":`Show ${S.length-3} more entities`,children:v?"Show less":`+${S.length-3} more`}),$&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:$})]}):d("div",{children:[i.entityNames&&i.entityNames.length>0?d("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((P,R)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:P},R)),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"," ",((I=i.entityShas)==null?void 0:I.length)||0," ",((L=i.entityShas)==null?void 0:L.length)===1?"entity":"entities","..."]}),$&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:$})]})})]}),o.length>0&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Eh,{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(P=>{var J,K;const R=y.has(P.id),E=R?P.entities:P.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:P.entities.length>0?d("div",{className:"space-y-1.5",children:[E.map(Q=>n(Ha,{entity:Q,nameSize:"10px",pathSize:"9px",pathMaxLength:120},Q.sha)),P.entities.length>3&&n("button",{onClick:()=>{g(Q=>{const q=new Set(Q);return q.has(P.id)?q.delete(P.id):q.add(P.id),q})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Va,"aria-label":R?"Show fewer entities":`Show ${P.entities.length-3} more entities`,children:R?"Show less":`+${P.entities.length-3} more`})]}):d("div",{style:{fontSize:"10px",color:"#343434"},children:[P.type==="analysis"&&n(ve,{children:P.entityNames&&P.entityNames.length>0?d("div",{className:"space-y-0.5",children:[P.entityNames.slice(0,5).map((Q,q)=>n("div",{children:Q},q)),P.entityNames.length>5&&d("div",{className:"italic",children:["+",P.entityNames.length-5," more"]})]}):`Analyzing ${((J=P.entityShas)==null?void 0:J.length)||0} ${((K=P.entityShas)==null?void 0:K.length)===1?"entity":"entities"}`}),P.type==="recapture"&&"Recapturing scenario",P.type==="debug-setup"&&"Setting up debug environment"]})},P.id)})})]}),B&&T.length>0&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Bo,{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:T.slice(0,3).map((P,R)=>{const E=P.entities||[],J=P.analysisCompletedAt||P.archivedAt||P.createdAt||"",K=(()=>{if(!J)return"";const z=Date.now()-new Date(J).getTime(),W=Math.floor(z/6e4),V=Math.floor(z/36e5);return V>0?`${V}h ago`:W>0?`${W}m ago`:"just now"})(),Q=x.has(R),U=(Q?E:E.slice(0,3)).map(z=>{var W,V,ae;return{...z,scenarioCount:((ae=(V=(W=z.analyses)==null?void 0:W[0])==null?void 0:V.scenarios)==null?void 0:ae.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:E.length>0&&d("div",{className:"space-y-1.5",children:[U.map((z,W)=>d("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(Ha,{entity:z,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:z.scenarioCount})}),W===0&&K&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:K})]},z.sha)),E.length>3&&n("button",{onClick:()=>{b(z=>{const W=new Set(z);return W.has(R)?W.delete(R):W.add(R),W})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Va,"aria-label":Q?"Show fewer entities":`Show ${E.length-3} more entities`,children:Q?"Show less":`+${E.length-3} more`})]})},R)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(ke,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),c&&t&&n(on,{projectSlug:t,onClose:()=>p(!1)})]})}function bt(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function Kr(e){const{file_id:t,project_id:r,commit_id:s,file_path:a,entity_type:o,entity_branches:i,analyses:l,commit:c,created_at:p,updated_at:u,...h}=e,m=(i??[]).map(g=>g.branch_id),f=l?l.map(Ht):void 0,y=c?En(c):void 0;return bt({...h,fileId:t,projectId:r,commitId:s,filePath:a,entityType:o,commit:y,analyses:f,branchIds:m,createdAt:p,updatedAt:u})}function Zo(e){return bt({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 ra(e){const{branches:t,files:r,analyzed_at:s,content_changed_at:a,created_at:o,updated_at:i,github_token:l,configuration:c,team_id:p,...u}=e;return bt({...u,branches:t?t.map(jn):void 0,files:r?r.map(Zo):void 0,analyzedAt:s,contentChangedAt:a,createdAt:o,updatedAt:i})}function Im(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 bt({id:t,projectId:r,userId:s,scenarioId:a,thumbsUp:!!o,user:l})}function Fm(e){const{id:t,project_id:r,user_id:s,scenario_id:a,text:o,created_at:i,updated_at:l,user:c}=e,p=c?{username:c.github_username,avatarUrl:c.github_user.avatar_url}:void 0;return bt({id:t,projectId:r,userId:s,scenarioId:a,text:o,createdAt:i,updatedAt:l,user:p})}function gd(e){const{project_id:t,analysis_id:r,previous_version_id:s,analysis:a,user_scenarios:o,scenario_comments:i,approved:l,...c}=e,p=a?Ht(a):void 0,u=o?o.map(Im):void 0,h=i?i.map(Fm):void 0;return bt({...c,projectId:t,analysisId:r,previousVersionId:s,analysis:p,userScenarios:u,comments:h})}function Dm(e){return bt({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?Ht(e.analysis):void 0,entity:e.entity?Kr(e.entity):void 0,branch:e.branch?jn(e.branch):void 0,createdAt:e.created_at})}function Ht(e){const{project_id:t,commit_id:r,file_id:s,file_path:a,entity_sha:o,entity_type:i,entity_name:l,previous_analysis_id:c,file:p,entity:u,commit:h,project:m,scenarios:f,analysis_branches:y,dependency_analyzed_tree_sha:g,analyzed_tree_sha:x,branch_commit_sha:b,committed_at:v,completed_at:N,created_at:w,updated_at:C,indirect:S,...k}=e,j=u?Kr(u):void 0,_=p?Zo(p):void 0,F=m?ra(m):void 0,M=h?En(h):void 0,$=f?f.map(gd):void 0,O=y?y.map(Dm):void 0,D=O?O.map(T=>T.branch):void 0;return bt({...k,projectId:t,commitId:r,fileId:s,filePath:a,entitySha:o,entityType:i,entityName:l,previousAnalysisId:c,entity:j,file:_,commit:M,project:F,scenarios:$,analysisBranches:O,branches:D,dependencyAnalyzedTreeSha:g,analyzedTreeSha:x,branchCommitSha:b,committedAt:v,completedAt:N,createdAt:w,updatedAt:C,indirect:!!S})}function Xo(e){return bt({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?En(e.commit):void 0,branch:e.branch?jn(e.branch):void 0})}function Rm(e){const{project_id:t,commit_id:r,created_at:s,updated_at:a,success:o,...i}=e;return bt({...i,projectId:t,commitId:r,createdAt:s,updatedAt:a,success:!!o})}function En(e){const{project_id:t,branch_id:r,branch:s,background_jobs:a,merged_branch_id:o,mergedBranch:i,ai_message:l,html_url:c,author:p,analyses:u,entities:h,commit_branches:m,committed_at:f,analyzed_at:y,...g}=e,x=s?jn(s):void 0,b=i?jn(i):void 0,v=(a==null?void 0:a.length)>0?Rm(a[a.length-1]):void 0,N=(u??[]).map(Ht),w=(h??[]).map(Kr),C=(m==null?void 0:m.length)>0?m.map(Xo):void 0;return p&&(p.username=p.preferredUsername??p.username),bt({...g,projectId:t,branchId:r,branch:x,backgroundJob:v,mergedBranchId:o,mergedBranch:b,aiMessage:l,htmlUrl:c,author:p,analyses:N,entities:w,commitBranches:C,committedAt:f,analyzedAt:y})}function jn(e){const{project_id:t,content_changed_at:r,commits:s,analysis_branches:a,active_at:o,created_at:i,updated_at:l,primary:c,...p}=e,u=s?s.map(En):void 0,h=a?a.flatMap(m=>Ht(m.analysis)):void 0;return bt({...p,projectId:t,contentChangedAt:r,commits:u,analyses:h,activeAt:o,createdAt:i,updatedAt:l,primary:!!c})}var qs;class Om{constructor(){yl(this,qs,new Lm)}transformQuery(t){return gl(this,qs).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}qs=new WeakMap;class Lm extends Vh{transformValue(t){return{...super.transformValue(t),value:typeof t.value=="boolean"?t.value?1:0:t.value}}transformPrimitiveValueList(t){return{...t,values:t.values.map(r=>typeof r=="boolean"?r?1:0:r)}}}const be=()=>null;function Be(e=!1){return t=>(t=t.defaultTo(mt`CURRENT_TIMESTAMP`),e&&(t=t.notNull()),t)}const zm={analyzed_at:be(),configuration:be(),content_changed_at:be(),created_at:be(),description:be(),github_token:be(),id:be(),metadata:be(),name:be(),path:be(),slug:be(),team_id:be(),updated_at:be()},Bm=Object.keys(zm);async function Ym(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",Be(!0)).addColumn("updated_at","datetime",Be()).addColumn("team_id","integer").ifNotExists().execute()}async function Wm(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",Be(!0)).addColumn("updated_at","datetime",Be(!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 Um={active:be(),analysis_id:be(),branch_id:be(),created_at:be(),entity_sha:be(),id:be()},Jm=Object.keys(Um);async function Hm(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",Be()).ifNotExists().execute()}async function Vm(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",Be(!0)).addColumn("updated_at","datetime").addPrimaryKeyConstraint("background_jobs_pkey",["project_id","commit_id"]).ifNotExists().execute()}const Km={active_at:be(),content_changed_at:be(),created_at:be(),id:be(),metadata:be(),name:be(),primary:be(),project_id:be(),ref:be(),sha:be(),updated_at:be()},yd=Object.keys(Km);async function Gm(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",Be()).addColumn("active_at","datetime").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be()).ifNotExists().execute()}async function qm(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",Be(!0)).ifNotExists().execute()}const Qm={ai_message:be(),analyzed_at:be(),author_github_username:be(),branch_id:be(),committed_at:be(),created_at:be(),files:be(),html_url:be(),id:be(),merged_branch_id:be(),message:be(),metadata:be(),project_id:be(),sha:be(),title:be(),url:be()},xd=Object.keys(Qm),Zm=xd.filter(e=>e!=="files");async function Xm(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",Be(!0)).ifNotExists().execute()}async function ef(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",Be(!0)).addColumn("uploaded_at","datetime").addColumn("base_sha","varchar").addColumn("delta_size_bytes","bigint").ifNotExists().execute()}async function tf(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",Be(!0)).addColumn("approved_at","datetime").ifNotExists().execute()}const nf={commit_id:be(),created_at:be(),description:be(),documentation:be(),entity_type:be(),file_id:be(),file_path:be(),metadata:be(),name:be(),project_id:be(),quality:be(),sha:be(),updated_at:be()},bd=Object.keys(nf);async function rf(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",Be(!0)).addColumn("updated_at","datetime").ifNotExists().execute()}const sf={active:be(),branch_id:be(),entity_sha:be()},af=Object.keys(sf);async function of(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 lf(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",Be(!0)).ifNotExists().execute()}const cf={created_at:be(),deleted:be(),id:be(),metadata:be(),name:be(),path:be(),project_id:be(),updated_at:be()},df=Object.keys(cf);async function uf(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",Be(!0)).addColumn("updated_at","datetime",Be()).addColumn("metadata","text").ifNotExists().execute()}async function pf(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",Be(!0)).ifNotExists().execute()}async function hf(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",Be(!0)).addColumn("updated_at","datetime",Be()).ifNotExists().execute()}async function mf(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",Be(!0)).addColumn("updated_at","datetime",Be(!0)).ifNotExists().execute()}async function ff(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",Be(!0)).addColumn("updated_at","datetime",Be(!0)).ifNotExists().execute();for(const t of["component_name","component_path","url","type","screenshot_path"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"varchar").execute()}catch{}for(const t of["viewport_width","viewport_height"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"integer").execute()}catch{}for(const t of["dimensions","screenshot_paths"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"text").execute()}catch{}for(const t of["page_file_path","entity_sha","display_name"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"varchar").execute()}catch{}try{const t=await e.selectFrom("editor_scenarios").select(["id","dimension","dimensions"]).execute();for(const r of t){const s=r;s.dimension&&!s.dimensions&&await e.updateTable("editor_scenarios").set({dimensions:JSON.stringify([s.dimension])}).where("id","=",s.id).execute()}}catch{}try{const t=await e.selectFrom("editor_scenarios").select(["id","screenshot_path","screenshot_paths","dimensions"]).execute();for(const r of t){const s=r;if(s.screenshot_path&&!s.screenshot_paths){let a="Default";try{const o=s.dimensions?JSON.parse(s.dimensions):null;Array.isArray(o)&&o.length>0&&(a=o[0])}catch{}await e.updateTable("editor_scenarios").set({screenshot_paths:JSON.stringify({[a]:s.screenshot_path})}).where("id","=",s.id).execute()}}}catch{}}const gf={analysis_id:be(),approved:be(),created_at:be(),description:be(),id:be(),metadata:be(),name:be(),previous_version_id:be(),project_id:be()},Bs=Object.keys(gf);async function yf(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",Be(!0)).ifNotExists().execute()}async function xf(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",Be(!0)).ifNotExists().execute()}async function bf(e){await e.schema.createTable("teams").addColumn("id","serial",t=>t.primaryKey()).addColumn("name","varchar",t=>t.notNull()).addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}async function vf(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",Be(!0)).ifNotExists().execute()}async function wf(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 Nf(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",Be(!0)).addColumn("updated_at","datetime",Be()).ifNotExists().execute()}const Sf=!!An("ENABLE_QUERY_LOGGING"),Cf=!!An("ENABLE_QUERY_ERROR_LOGGING");An("USE_LOCAL_POSTGRESQL_FOR_TESTING");let ps;function $e(){if(!ps){const e=wd();if(e==="sqlite")ps=kf();else if(e==="postgresql")ps=_f();else throw new Error(`Unknown database type: ${e}`)}return ps}function kf(e){if(e||(e=An("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=G.existsSync(e),r=H.dirname(e);if(!G.existsSync(r))G.mkdirSync(r,{recursive:!0,mode:493});else try{G.chmodSync(r,493)}catch(a){console.warn(`Warning: Could not set permissions on database directory: ${a.message}`)}const s=new Uh(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 dd({dialect:new Gh({database:s}),plugins:[new Kh,new Om],log:vd})}function _f(){const e=jf();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new Jh({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,s)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new dd({dialect:new qh({pool:t}),log:vd})}let Ka=null;function Mn(){return Ka||(Ka=Ef(wd())),Ka}function vd(e){e.level==="error"?Cf&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):Sf&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function Ef(e){if(e==="sqlite")return Qh;if(e==="postgresql")return Zh;throw new Error(`Unknown database type: ${e}`)}function wd(){if(An("SQLITE_PATH"))return"sqlite";if(An("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}async function T_(e){await Ym(e),await Wm(e),await Hm(e),await Vm(e),await Gm(e),await qm(e),await Xm(e),await ef(e),await ff(e),await rf(e),await of(e),await lf(e),await uf(e),await pf(e),await hf(e),await tf(e),await mf(e),await yf(e),await xf(e),await bf(e),await vf(e),await wf(e),await Nf(e)}function jf(){const e=An("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function An(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}const Af=()=>crypto.randomUUID();function Pf(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??Af(),project_id:r,active_at:s,content_changed_at:a,metadata:o?JSON.stringify(o):null}}var nt=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Vite="Vite",e.Expo="Expo",e.Unknown="Unknown",e))(nt||{});const sa="Default Scenario";let Tf="<main>";function Mf(){return Tf}function kl(e,...t){Oe(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function Oe(...e){const t=Mf(),r=e.map(a=>{if(a)return typeof a=="string"?a:a instanceof Error?`${a.name}: ${a.message}
21
- ${a.stack}`:typeof a=="object"?$f(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 $f(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 Ys(e,t){try{let r=function(o){var i,l;if(Ze.isFunctionDeclaration(o)&&jr(o)){const c=((i=o.name)==null?void 0:i.text)||"default",p=o.getText(s),u=Ga(o);a.push({name:c,code:p,sha:bn(t,c,p),entityType:"function",isDefault:u})}else if(Ze.isClassDeclaration(o)&&jr(o)){const c=((l=o.name)==null?void 0:l.text)||"default",p=o.getText(s),u=Ga(o),h=p.includes("React.")||p.includes("jsx")||p.includes("tsx");a.push({name:c,code:p,sha:bn(t,c,p),entityType:h?"component":"class",isDefault:u})}else if(Ze.isInterfaceDeclaration(o)&&jr(o)){const c=o.name.text,p=o.getText(s);a.push({name:c,code:p,sha:bn(t,c,p),entityType:"interface",isDefault:!1})}else if(Ze.isTypeAliasDeclaration(o)&&jr(o)){const c=o.name.text,p=o.getText(s);a.push({name:c,code:p,sha:bn(t,c,p),entityType:"type",isDefault:!1})}else if(Ze.isVariableStatement(o)&&jr(o)){const c=Ga(o);o.declarationList.declarations.forEach(p=>{var u;if(Ze.isIdentifier(p.name)){const h=p.name.text,m=o.getText(s),f=((u=p.initializer)==null?void 0:u.getText(s))||"",y=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));a.push({name:h,code:m,sha:bn(t,h,m),entityType:y?"component":"variable",isDefault:c})}})}else if(Ze.isExportAssignment(o)){const c=o.getText(s);a.push({name:"default",code:c,sha:bn(t,"default",c),entityType:"unknown",isDefault:!0})}else if(Ze.isExportDeclaration(o)&&o.exportClause&&Ze.isNamedExports(o.exportClause)){const c=o.getText(s);for(const p of o.exportClause.elements){const u=p.name.text;a.push({name:u,code:c,sha:bn(t,u,c),entityType:"unknown",isDefault:!1})}}Ze.forEachChild(o,r)};const s=Ze.createSourceFile(t,e,Ze.ScriptTarget.Latest,!0),a=[];return r(s),a}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function jr(e){if(!Ze.canHaveModifiers(e))return!1;const t=Ze.getModifiers(e);return t?t.some(r=>r.kind===Ze.SyntaxKind.ExportKeyword):!1}function Ga(e){if(!Ze.canHaveModifiers(e))return!1;const t=Ze.getModifiers(e);return t?t.some(r=>r.kind===Ze.SyntaxKind.DefaultKeyword):!1}function bn(e,t,r){const s=cr.createHash("sha256");return s.update(`${e}:${t}:${r}`),s.digest("hex").substring(0,40)}function If(e){var p;const{webapp:t,port:r,environmentVariables:s,packageManager:a}=e,o=t==null?void 0:t.startCommand;if(!o)return`${a} ${a==="npm"?"run ":""}dev`;const i=((p=o.args)==null?void 0:p.map(u=>u.replace(/\$PORT/g,String(r))))??[],l=[];for(const u of s)if(u.key&&u.value!==void 0){const h=String(u.value).replace(/'/g,"'\\''");l.push(`${u.key}='${h}'`)}if(o.env)for(const[u,h]of Object.entries(o.env)){const f=String(h).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");l.push(`${u}='${f}'`)}const c=l.length>0?l.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${c}sh -c "${i[1]}"`:`${c}${o.command} ${i.join(" ")}`}function Ff(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=H.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=H.normalize(a.path??".");if(o==="."||r.startsWith(o+H.sep)||r===o)return a}return t[0]}function Df(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=Ff(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const l=If({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 dr(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 Rf(e){if(e.length===0)return[];const t=$e(),r=e.map(Pf);try{return(await t.insertInto("branches").values(r).onConflict(dr(r[0],"id",["created_at"])).returningAll().execute()).map(jn)}catch(s){return Oe("CodeYam Error: Database error upserting branches",s,{branchCount:e.length,branchIds:e.map(a=>a.id)}),[]}}function Of(e){const{jsonObjectFrom:t}=Mn();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 Lf({ids:e,analysisId:t}){const r=$e();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 Oe("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 Oe("CodeYam Error: Database error deleting scenarios",s,{ids:e,analysisId:t}),s}}function zf(...e){try{const t=cr.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 qa(e,t){return t.map(r=>Bf(e,r))}function Bf(e,t){return mt` ${mt.ref(e)}.${mt.ref(t)}`.as(t)}function Yf(e,t,r){return t.map(s=>Wf(e,s,r))}function Wf(e,t,r){return mt` ${mt.ref(e)}.${mt.ref(t)}`.as(`_cy_${r}:${t}`)}function Uf(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 Jf=50;function Hf(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 _l({projectId:e,ids:t,fileIds:r,entityName:s,entityShas:a,commitIds:o,branchCommitSha:i,limit:l,excludeMetadata:c}){const p=$e(),{jsonObjectFrom:u,jsonArrayFrom:h}=Mn();let m=c?p.selectFrom("analyses").select(["analyses.id","analyses.project_id","analyses.file_id","analyses.commit_id","analyses.entity_sha","analyses.entity_name","analyses.entity_type","analyses.file_path","analyses.status","analyses.created_at","analyses.updated_at","analyses.tree_sha","analyses.analyzed_tree_sha","analyses.dependency_analyzed_tree_sha","analyses.previous_analysis_id","analyses.branch_commit_sha","analyses.indirect","analyses.committed_at","analyses.completed_at"]):p.selectFrom("analyses").selectAll("analyses");if(e&&(m=m.where("project_id","=",e)),t){if(t.length===0)return null;m=m.where("id","in",t)}if(r){if(r.length===0)return null;m=m.where("file_id","in",r)}if(o){if(o.length===0)return null;m=m.where("commit_id","in",o)}return s&&(m=m.where("entity_name","=",s)),a&&(m=m.where("entity_sha","in",a)),i&&(m=m.where("branch_commit_sha","=",i)),l&&(m=m.limit(l)),c?p.with("filtered_analyses",()=>m).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[h(f.selectFrom("scenarios").select(qa("scenarios",Bs)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),h(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):p.with("filtered_analyses",()=>m).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select(qa("entities",bd)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),h(f.selectFrom("scenarios").select(qa("scenarios",Bs)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),h(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function dn(e){const{ids:t,fileIds:r,entityShas:s,commitIds:a}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:s,key:"entityShas"},commit_id:{arr:a,key:"commitIds"}}).find(([c,{arr:p}])=>(p==null?void 0:p.length)>0);let l=[];if(i){const[c,{arr:p,key:u}]=i,h=Hf(p,Jf),m=[];for(let f=0;f<h.length;f++){const y=h[f],x=await _l({...e,[u]:y}).execute();x&&m.push(...x)}l=m}else{const p=await _l(e).execute();if(!p||p.length===0)return Oe("CodeYam: No analyses found",null,e),null;l=p}return l.length===0?null:l.map(Ht)}catch(o){return Oe("CodeYam Error: Database error in loadAnalyses",o,e),null}}function Vf(e,t){const{jsonArrayFrom:r,jsonObjectFrom:s}=Mn();let a=e.selectFrom("analysis_branches").select(Jm).select(o=>s(o.selectFrom("branches").select(yd).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(a=t(a)),r(a)}async function Vt({id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:c,includeProject:p,includeCommitAndBranch:u,includeScenarios:h,includeBranches:m}){const f=$e(),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}=Mn();g=g.select(w=>{const C=[];return C.push(x(w.selectFrom("entities").select(bd).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),c&&C.push(x(w.selectFrom("files").select(df).whereRef("files.id","=","analyses.file_id")).as("file")),p&&C.push(x(w.selectFrom("projects").select(Bm).whereRef("projects.id","=","analyses.project_id")).as("project")),h&&C.push(b(w.selectFrom("scenarios").select(Bs).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),m&&C.push(Vf(w,S=>S.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&C.push(x(w.selectFrom("commits").select(xd).select(S=>Of(S).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),C});const v=await g.executeTakeFirst(),N=Date.now()-y;if(!v)return Oe(!!i?`CodeYam: Analysis cache miss for dependency tree SHA ${i.substring(0,12)}...`:`CodeYam Error: Analysis not found${o?` for ${o}`:""}${e?` (id=${e})`:""}`,null,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:c,includeProject:p,includeCommitAndBranch:u,includeScenarios:h,includeBranches:m}),null;if(N>100&&u){const w=v.commit,C=w!=null&&w.files?JSON.stringify(w.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${N}ms (files: ${Math.round(C/1024)}KB)`,{id:v.id,entityName:v.entity_name})}return Ht(v)}catch(g){return Oe("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:p,includeCommitAndBranch:u,includeScenarios:h,includeBranches:m}),null}}async function ei({projectId:e,ids:t,names:r,includeInactive:s}){const a=$e();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(jn)}catch(o){return Oe("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:s}),[]}}async function Kf({projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}){const o=$e();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(a,p=>p.select(Yf("branches",yd,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),s!==void 0&&(i=i.where("commit_branches.active","=",s));const l=await i.execute();return!l||l.length===0?null:l.map(p=>Uf(p,"branch")).map(Xo)}catch(i){return Oe("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}),null}}async function Gf(e){if(e.length===0)return new Map;const t=$e();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 Oe("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function qf(e){if(e.length===0)return new Map;const t=$e(),{jsonObjectFrom:r,jsonArrayFrom:s}=Mn();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(Bs).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 Oe("CodeYam Error: Loading analyses for commits",a,{commitIds:e}),new Map}}async function Qf(e){if(e.length===0)return new Map;const t=$e();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 Oe("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function Ws({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=$e(),{jsonObjectFrom:c}=Mn(),p=Date.now();try{let u;if(i){const v=Zm.map(N=>`commits.${N}`);u=l.selectFrom("commits").select(v)}else u=l.selectFrom("commits").selectAll("commits").select(v=>[c(v.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",v.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 v=mt.join(a.map(N=>mt`${N}`),mt`, `);u=u.where(mt`
24
- EXISTS (
25
- SELECT 1
26
- FROM json_each(${mt.ref("commits.files")}) AS f
27
- WHERE json_extract(f.value, '$.fileName') IN (${v})
28
- )
29
- `)}t&&(u=u.where("branch_id","=",t));const h=await u.orderBy("committed_at","desc").limit(o).execute(),m=Date.now()-p;if(!h||h.length===0)return[];if(m>100){const v=h.reduce((N,w)=>N+(w.files?JSON.stringify(w.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${m}ms (${h.length} commits, totalFiles: ${Math.round(v/1024)}KB)`)}if(i)return h.map(N=>({...N,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(En);const f=h.map(v=>v.id),[y,g,x]=await Promise.all([Gf(f),qf(f),Qf(f)]);return h.map(v=>{const N=v.branch_id?y.get(v.branch_id):void 0,w=v.merged_branch_id?y.get(v.merged_branch_id):void 0,C=g.get(v.id)||[],S=x.get(v.id)||[];return{...v,branch:N,mergedBranch:w,analyses:C,entities:S}}).map(En)}catch(u){return Oe("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:t,ids:r,shas:s,limit:o}),[]}}async function Xe({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:o,excludeMetadata:i}){if(r&&r.length==0||s&&s.length==0||a&&a.length==0||o&&o.length==0)return[];if(o&&o.length>50){const c=[];for(let p=0;p<o.length;p+=50){const u=o.slice(p,p+50),h=await Xe({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:u,excludeMetadata:i});h&&c.push(...h)}return c}const l=$e();try{const u=await(i?l.selectFrom("entities").select(["entities.project_id","entities.file_id","entities.commit_id","entities.name","entities.sha","entities.entity_type","entities.file_path","entities.description","entities.documentation","entities.quality","entities.created_at","entities.updated_at"]):l.selectFrom("entities").selectAll("entities")).$if(!!t,h=>h.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,h=>h.where("entities.project_id","=",e)).$if(!!o,h=>h.where("entities.sha","in",o)).$if(!!s,h=>h.where("entities.file_path","in",s)).$if(!!a,h=>h.where("entities.name","in",a)).$if(!!r,h=>h.where("entities.file_id","in",r)).execute();return!u||u.length===0?null:u.map(Kr)}catch(c){return console.log("Load Entities: Error occurred",c,{projectId:e,fileIds:r,filePaths:s,shas:o}),null}}function Zf(e,t){const{jsonArrayFrom:r}=Mn();let s=e.selectFrom("entity_branches").select(af);return t&&(s=t(s)),r(s)}async function Nd({projectId:e,sha:t,silent:r}){const s=$e();try{const a=await s.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(o=>Zf(o,i=>i.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return a?Kr(a):(!r&&process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&Oe(`CodeYam Error: Load Entity: Entity not found (sha=${t==null?void 0:t.substring(0,12)})`,null,{projectId:e,sha:t}),null)}catch(a){return Oe("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:t}),null}}const Qa=1e3;async function Sd({projectId:e,filePaths:t,fileIds:r,fileNames:s}){if(t&&t.length>50){const l=[];for(let c=0;c<t.length;c+=50){const p=t.slice(c,c+50),u=await Sd({projectId:e,filePaths:p,fileIds:r,fileNames:s});u&&l.push(...u)}return l}const a=$e(),o=[];let i=0;try{for(;;){let l=a.selectFrom("files").selectAll().where("project_id","=",e).limit(Qa).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<Qa))break;i+=Qa}return o==null?void 0:o.map(Zo)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function ti({id:e,slug:t,withBranches:r,withFiles:s,silent:a}){try{let i=$e().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=ra(l);return s&&(c.files=await Sd({projectId:c.id})),r&&(c.branches=await ei({projectId:c.id,includeInactive:!1})),c}catch{return null}}function Us(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]=Us(o,a):a!==void 0&&(r[s]=a)}return r}async function an({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:s,archiveCurrentRun:a,updateCallback:o}){for(let c=0;c<=4;c++)try{return await $e().transaction().execute(async p=>{const u=await p.selectFrom("commits").select(["id","metadata"]).$if(!!e,f=>f.where("id","=",e)).$if(!!t,f=>f.where("sha","=",t)).executeTakeFirst();if(!u)return Oe(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const h=u.metadata||{};if(s)s.lastUpdatedAt??(s.lastUpdatedAt=new Date().toISOString()),r=Us(r??{},{currentRun:s});else if(!r&&!o)return h;const m=r?Us(h,r):h;if(a&&m.currentRun){const f={...m.currentRun,archivedAt:new Date().toISOString()};m.historicalRuns=[...m.historicalRuns||[],f]}o&&await o(m);try{return await p.updateTable("commits").set({metadata:JSON.stringify(m)}).where("id","=",u.id).returning(["id"]).executeTakeFirst()?m:(Oe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),h)}catch(f){return Oe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,f),h}})}catch(p){const u=p instanceof Error&&p.message.includes("database is locked");if(u&&c<4){const h=250*Math.pow(2,c);await new Promise(m=>setTimeout(m,h));continue}return Oe(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}${u?` after ${c+1} attempts`:""}`,p),null}return null}async function Cd(e,t,r="analysis"){try{return await $e().transaction().execute(async s=>{const a=await s.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!a)return Oe(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=Ht(a);return t(o.metadata,o),await s.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(Oe(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(s){return Oe(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,s,{analysisId:e,source:r}),null}}async function ur(e,t,r="capture"){for(let o=0;o<=4;o++)try{return await $e().transaction().execute(async i=>{const l=await i.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!l)return Oe(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const c=Ht(l);return t(c.status,c),await i.updateTable("analyses").set({status:JSON.stringify(c.status)}).where("id","=",e).returningAll().executeTakeFirst()?c.status:(Oe(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(i){const l=i instanceof Error&&i.message.includes("database is locked");if(l&&o<4){const c=250*Math.pow(2,o);await new Promise(p=>setTimeout(p,c));continue}return Oe(`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 sr({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:s}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await $e().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 Oe(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!s)return i;const l=r?Us(i,r):i;s&&await s(l,ra(o));try{return await a.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",o.id).returningAll().executeTakeFirst()?l:(Oe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(c){return Oe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,c),null}})}catch(a){return Oe(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,a),null}}const Xf=()=>crypto.randomUUID();function eg(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??Xf(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:s,previous_version_id:a}}async function tg(e){if(e.length===0)return[];const t=$e(),r=e.map(eg);try{return(await t.insertInto("scenarios").values(r).onConflict(dr(r[0],"id",["created_at"])).returningAll().execute()).map(gd)}catch(s){return Oe("CodeYam Error: Database error upserting scenarios",s,{scenarioCount:e.length}),null}}const ng=()=>crypto.randomUUID();function rg(e){const{id:t,commitId:r,branchId:s,...a}=e;return delete a.commit,delete a.branch,{...a,id:t??ng(),commit_id:r,branch_id:s}}async function El(e){if(e.length===0)return[];const t=$e(),r=e.map(rg);try{return(await t.insertInto("commit_branches").values(r).onConflict(dr(r[0],"id",["created_at"])).returningAll().execute()).map(Xo)}catch(s){return Oe("CodeYam Error: Database error upserting commit branches",s,{commitBranchCount:e.length,commitBranchIds:e.map(a=>a.id)}),[]}}async function sg(e,t){const r=$e(),s={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(s).onConflict(dr(s,"username",[])).returningAll().executeTakeFirst()||null}catch(a){return Oe("CodeYam Error: Error upserting github user",a,{username:e,avatarUrl:t}),null}}const ag=()=>crypto.randomUUID();function og(e,t){const{id:r,projectId:s,branchId:a,mergedBranchId:o,aiMessage:i,htmlUrl:l,analyzedAt:c,committedAt:p,author:u,metadata:h,files:m,...f}=e;return delete f.branch,delete f.mergedBranch,delete f.backgroundJob,delete f.analyses,delete f.parents,delete f.entities,delete f.commitBranches,{...f,id:r??ag(),project_id:s??String(t),metadata:h?JSON.stringify(h):void 0,files:m?JSON.stringify(m):void 0,branch_id:a,merged_branch_id:o,author_github_username:u==null?void 0:u.username,html_url:l,ai_message:i,analyzed_at:c,committed_at:p}}async function ig({projectId:e,commits:t}){const r=$e();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 sg(i,s[i]);const a=t.map(i=>og(i,e));return(await r.insertInto("commits").values(a).onConflict(dr(a[0],"id",["created_at"])).returningAll().execute()).map(En)}catch(s){return Oe("CodeYam Error: Error saving commits",s,{projectId:e,commitCount:t.length,commitIds:t.map(a=>a.id).filter(Boolean)}),[]}}const lg=()=>crypto.randomUUID();function cg(e){const{id:t,files:r,branches:s,team:a,analyzedAt:o,contentChangedAt:i,createdAt:l,updatedAt:c,metadata:p,...u}=e;return{...u,id:t??lg(),analyzed_at:o||null,content_changed_at:i||null,created_at:l||new Date().toISOString(),updated_at:c||null,metadata:p?JSON.stringify(p):null,github_token:null,configuration:null,team_id:null}}async function dg(e){try{if(e.length===0)return null;const t=$e(),r=e.map(o=>cg(o)),s=await t.insertInto("projects").values(r).onConflict(dr(r[0],"id",["created_at"])).returningAll().execute(),a=s==null?void 0:s[0];return a?ra(a):null}catch(t){return console.log("Error saving project",t),null}}const Js=H.join(Xs.homedir(),".codeyam","secrets.json"),Hs=H.join(process.cwd(),".codeyam","secrets.json");async function hn(){let e={};try{if(G.existsSync(Hs)){const o=await Ae.readFile(Hs,"utf8");e=JSON.parse(o)}}catch{console.warn(zs.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(G.existsSync(Js)){const o=await Ae.readFile(Js,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(zs.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 ug(e,t=!0){const r=t?Js:Hs,s=H.dirname(r);await Ae.mkdir(s,{recursive:!0}),await Ae.writeFile(r,JSON.stringify(e,null,2)),await Ae.chmod(r,384)}function pg(e=!0){return e?Js:Hs}async function jl(){const e=await hn(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function hg(e){console.log(),console.log(zs.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const s=await tm({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 mg(e=!0){const t=await jl();if(t.isValid)return t.secrets;const r=await hg(t.missing),a={...await hn(),...r};await ug(a,e);const o=pg(e);return console.log(zs.green(`✓ Configuration saved to ${o}`)),(await jl()).secrets}function fg(e){const t=H.resolve(e),r=H.parse(t).root;return t===r||t===H.resolve(Xs.homedir())}function kd(e=process.cwd()){let t=H.resolve(e);const r=H.parse(t).root;for(;t!==r;){if(fg(t))return null;const s=H.join(t,".codeyam","config.json");if(G.existsSync(s))return t;t=H.dirname(t)}return null}let _d=kd();function Ce(){return _d}function gg(e){_d=e}function Ed(e){const t={...e};for(const r in e)if(r.includes(".")){const s=r.replace(/\./g,"");t[s]=e[r]}return t}const yg={"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>`};Ed(yg);const xg={"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>`};Ed(xg);function Ir(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]=Ir(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]=Ir(o[i],l,r):s[a][i]=l}}else typeof t[a]=="object"&&t[a]!==null?s[a]=Ir(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 bg({projectId:e,commit:t,branch:r}){var l,c,p,u,h,m,f;let s;const a={commitId:t.id,branchId:r.id,active:!0},o=await Kf({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){s=(l=o.sort((g,x)=>{var b,v,N,w;return(((v=(b=g.branch.metadata)==null?void 0:b.permanent)==null?void 0:v.order)??999)-(((w=(N=x.branch.metadata)==null?void 0:N.permanent)==null?void 0:w.order)??999)})[0])==null?void 0:l.branch,s&&((p=(c=r.metadata)==null?void 0:c.permanent)==null?void 0:p.order)!==void 0&&(((h=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:h.order)<=((f=(m=s.metadata)==null?void 0:m.permanent)==null?void 0:f.order)?s=r:a.active=!1);const y=o.filter(g=>g.active&&g.branch.id!==s.id||!g.active&&g.branch.id===s.id);y.length>0&&await El(y.map(g=>({...g,active:g.branchId===s.id})))}(o==null?void 0:o.find(y=>y.branchId===a.branchId))||await El([a])}let Al=!1;function mn(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=Ce();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return ee.join(e,".codeyam","db.sqlite3")}async function Je(){if(!Al){Al=!0;const t=Ce();t&&await wg(t)}const e=await mg();process.env.SQLITE_PATH=mn(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function M_(){try{return await Je(),await ti({slug:"__test_connection__",silent:!0}),!0}catch(e){return console.error("Database connection test failed:",e),!1}}async function Re(e){await Je();const t=await ti({slug:e,silent:!0});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await ei({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 $_(e){await Je();const t=await ti({slug:e.slug,silent:!0});if(t)return{project:t,created:!1};const r={id:Uo(),name:e.slug,slug:e.slug,path:`local:${process.cwd()}`,metadata:{packageManager:e.packageManager,unapprovedPaths:e.unapprovedPaths,webapps:e.webapps}};try{return{project:await dg([r]),created:!0}}catch(s){throw new Error(`Failed to create project: ${s.message}`)}}async function I_(e){await Je();const t=await ei({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 Rf([r]);if(!s||s.length===0)throw new Error("Failed to create _local branch");return{branch:s[0],created:!0}}async function vg(e,t,r){await Je();const s=Ce(),a=zf(`${e.slug}-local-${Date.now()}-${Math.random()}`),o=r.map(c=>{let p="";if(s)try{if(p=De(`git diff HEAD -- "${c}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!p)try{const u=De(`cat "${c}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const h=u.split(`
30
- `);p=`@@ -0,0 +1,${h.length} @@
31
- ${h.map(m=>`+${m}`).join(`
32
- `)}`}}catch{}}catch{}return{fileName:c,status:"modified",patch:p}}),i={sha:a,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${a}`,htmlUrl:`local://codeyam/${e.slug}/${a}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:o,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},l=await ig({projectId:e.id,commits:[i]});if(!l||l.length===0)throw new Error("Failed to create fake commit");return await bg({projectId:e.id,commit:l[0],branch:t}),l[0]}async function wg(e){const t=ee.join(e,".codeyam","db.sqlite3"),r=ee.join(e,".codeyam","config.json");if(G.existsSync(t)||!G.existsSync(r))return!1;const{default:s}=await import("./init-B3gVLAAJ.js");return await s.handler({force:!0,autoInit:!0,$0:"",_:[]}),!0}async function $n(){await Je();const e=await Xe({excludeMetadata:!0});if(!e||e.length===0)return[];const t=new Map;for(const c of e){const p=`${c.name}::${c.filePath}`,u=t.get(p);(!u||c.createdAt&&u.createdAt&&c.createdAt>u.createdAt)&&t.set(p,c)}const r=[...t.values()],s=e.map(c=>c.sha),a=await dn({entityShas:s,excludeMetadata:!0}),o=new Map;if(a)for(const c of a)o.has(c.entitySha)||o.set(c.entitySha,[]),o.get(c.entitySha).push(c);const i=new Map;for(const c of e){const p=`${c.name}::${c.filePath}`,u=i.get(p)||[];u.push(c.sha),i.set(p,u)}return r.map(c=>{const p=o.get(c.sha)||[];if(p.length>0)return{...c,analyses:p};const u=`${c.name}::${c.filePath}`,h=i.get(u)||[];for(const m of h){if(m===c.sha)continue;const f=o.get(m);if(f&&f.length>0)return{...c,analyses:f}}return{...c,analyses:[]}})}async function Ng(e){await Je();const t=await Xe(e);return!t||t.length===0?[]:t.filter(r=>{var s;return!((s=r.metadata)!=null&&s.isSuperseded)})}async function aa(e,t){await Je();const r=await dn({entityShas:[e],limit:1});if(r&&r.length>0&&t){const s=await Nd({projectId:r[0].projectId,sha:e});if(s)for(const a of r)a.entity=s}return r||[]}async function oa(e){if(await Je(),e.name&&e.projectId){const r=await dn({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 dn({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function jd(e){await Je();const t=await dn({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function Pn(e){await Je();const t=await Ye();if(!t)return null;const{project:r}=await Re(t);return await Nd({projectId:r.id,sha:e})}async function Ad(e){var s,a,o,i,l,c,p,u;await Je();const t=[],r=[];if((s=e.metadata)!=null&&s.importedExports&&e.metadata.importedExports.length>0){const h=e.metadata.importedExports;for(const m of h){if(!m.filePath||!m.name)continue;const f=m.resolvedFilePath??m.filePath,y=m.resolvedName??m.name;let g=await Xe({projectId:e.projectId,filePaths:[f],names:[y]});if((!g||g.length===0)&&m.resolvedIsDefault&&(g=await Xe({projectId:e.projectId,filePaths:[f],names:["default"]})),g&&g.length>0){const x=g[0],b=await dn({entityShas:[x.sha],limit:1});let v,N,w;if(b&&b.length>0&&b[0].scenarios){const C=b[0],S=C.scenarios||[],k=S.length,j=S.find(F=>{var M,$;return($=(M=F.metadata)==null?void 0:M.screenshotPaths)==null?void 0:$[0]});j&&(v=(o=(a=j.metadata)==null?void 0:a.screenshotPaths)==null?void 0:o[0],N=j.name),w={status:((i=x.metadata)==null?void 0:i.previousVersionWithAnalyses)||C.entitySha!==x.sha?"out_of_date":"up_to_date",scenarioCount:k,timestamp:C.createdAt?new Date(C.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else w={status:"not_analyzed"};t.push({...x,screenshotPath:v,scenarioName:N,analysisStatus:w})}}}if((l=e.metadata)!=null&&l.importedBy){const h=[];for(const m in e.metadata.importedBy)for(const f in e.metadata.importedBy[m]){const y=e.metadata.importedBy[m][f];y.shas&&h.push(...y.shas)}if(h.length>0){const m=await Xe({projectId:e.projectId,shas:h});if(m)for(const f of m){const y=await dn({entityShas:[f.sha],limit:1});let g,x,b;if(y&&y.length>0&&y[0].scenarios){const v=y[0],N=v.scenarios||[],w=N.length,C=N.find(k=>{var j,_;return(_=(j=k.metadata)==null?void 0:j.screenshotPaths)==null?void 0:_[0]});C&&(g=(p=(c=C.metadata)==null?void 0:c.screenshotPaths)==null?void 0:p[0],x=C.name),b={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||v.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:w,timestamp:v.createdAt?new Date(v.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else b={status:"not_analyzed"};r.push({...f,screenshotPath:g,scenarioName:x,analysisStatus:b})}}}return{importedEntities:t,importingEntities:r}}async function Ye(){try{const e=Ce();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await Pe.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function pr(){await Je();try{const e=await Ye();if(!e)return null;const{project:t,branch:r}=await Re(e),s=await Ws({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 ia(){try{const e=Ce();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await Pe.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function Pd(e){try{const t=Ce();if(!t)return console.error("[getEntityCodeFromFilesystem] No project root found"),null;if(!e.filePath)return console.error("[getEntityCodeFromFilesystem] Entity has no filePath"),null;const r=ee.join(t,e.filePath);return await Pe.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function Td(e){try{const t=Ce();if(!t||!e.filePath)return!1;const r=ee.join(t,e.filePath),a=(await Pe.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 Md(e){if(await Je(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await Xe({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),s=await dn({entityShas:r}),a=new Map;if(s)for(const i of s)a.has(i.entitySha)||a.set(i.entitySha,[]),a.get(i.entitySha).push(i);for(const[i,l]of a.entries())l.sort((c,p)=>{const u=new Date(c.createdAt||0).getTime();return new Date(p.createdAt||0).getTime()-u});const o=t.map(i=>({...i,analyses:a.get(i.sha)||[]}));return o.sort((i,l)=>{var u,h;const c=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",p=((h=l.analyses[0])==null?void 0:h.createdAt)||l.createdAt||"";return new Date(p).getTime()-new Date(c).getTime()}),o}async function $d(e){try{const t=Ce();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=ee.join(t,".codeyam","config.json"),s=await Pe.readFile(r,"utf8"),a=JSON.parse(s),o={...a,...e},i=JSON.stringify(o,null,2);if(await Pe.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 sr({projectSlug:a.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const Sg=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:$n,getAnalysesForEntity:aa,getAnalysisForExactEntitySha:jd,getCurrentCommit:pr,getCurrentEntities:Ng,getEntityBySha:Pn,getEntityCodeFromFilesystem:Pd,getEntityHistory:Md,getLatestAnalysisForEntity:oa,getProjectConfig:ia,getProjectSlug:Ye,getRelatedEntities:Ad,hasFileBeenModifiedSinceEntity:Td,requireBranchAndProject:Re,updateProjectConfig:$d},Symbol.toStringTag,{value:"Module"})),Id="secrets.json";function Fd(e){return ee.join(e,".codeyam",Id)}function Dd(){return ee.join(vo.homedir(),".codeyam",Id)}async function la(e){let t={};try{const r=Dd(),s=await Pe.readFile(r,"utf-8");t=JSON.parse(s)}catch{}try{const r=Fd(e),s=await Pe.readFile(r,"utf-8"),a=JSON.parse(s);t={...t,...a}}catch{}return t}async function Cg(e,t,r=!0){const s=r?Dd():Fd(e),a=ee.dirname(s);await Pe.mkdir(a,{recursive:!0}),await Pe.writeFile(s,JSON.stringify(t,null,2)+`
33
- `,"utf-8")}async function kg(e){const t=await la(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 _g=3;let Ar=0;async function hs(e){if(!e||e.length===0)return[];if(Ar>=_g)return console.warn(`[Loader] Circuit breaker open (${Ar} 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,Ar++,console.warn(`[Loader] Entity fetch timeout after ${t}ms for ${e.length} entities`),r([]))},t);Xe({shas:e,excludeMetadata:!0}).then(o=>{s||(s=!0,clearTimeout(a),Ar=0,r(o||[]))}).catch(()=>{s||(s=!0,clearTimeout(a),Ar++,r([]))})})}function Eg({sourcePath:e,destinationPath:t,excludes:r,silent:s}){if(process.platform!=="darwin")return!1;if(Ct(t))try{if(Hh(t).length>0)return!1;Ja(t,{recursive:!0})}catch{return!1}try{De(`cp -c -R "${e}" "${t}"`,{stdio:"pipe",timeout:3e5});for(const a of r)if(a.includes("*"))try{De(`rm -rf "${zr(t,a)}"`,{stdio:"pipe",shell:"/bin/sh"})}catch{}else{const o=zr(t,a);Ct(o)&&Ja(o,{recursive:!0,force:!0})}return s||console.log(`Directory cloned (APFS CoW) from ${e} to ${t}`),!0}catch{if(Ct(t))try{Ja(t,{recursive:!0})}catch{}return!1}}async function jg({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:s=!1,silent:a=!1,extraArgs:o=[],timeoutMs:i=3e5}){const l=Date.now();if(!s&&o.length===0&&Eg({sourcePath:e,destinationPath:t,excludes:r,silent:a})){if(!a){const p=((Date.now()-l)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${p}s]`)}return}return new Promise((c,p)=>{const u=e.endsWith("/")?e:`${e}/`,h=t.endsWith("/")?t:`${t}/`,m=["-a","--no-specials"];s||m.push("--delete","--force"),m.push(...o);for(const x of r)m.push(`--exclude=${x}`);m.push(u,h);const f=xt("rsync",m);let y=!1;const g=i?setTimeout(()=>{if(!y){y=!0,f.kill("SIGKILL");const x=((Date.now()-l)/1e3).toFixed(1);p(new Error(`rsync timed out after ${x}s syncing ${e} → ${t}`))}},i):void 0;f.on("exit",x=>{if(!y)if(y=!0,g&&clearTimeout(g),x===0){if(!a){const b=((Date.now()-l)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${b}s]`)}c()}else console.error(`CodeYam Error: rsync failed with code: ${x}`,JSON.stringify({rsyncArgs:m},null,2)),p(new Error(`rsync failed with exit code ${x}`))}),f.on("error",x=>{y||(y=!0,g&&clearTimeout(g),a||console.log("Error occurred:",x),p(x))})})}const Ag=Ho(Jo);async function Pg(e){return new Promise(t=>setTimeout(t,e))}function Tg(e){try{return process.kill(e,0),!0}catch{return!1}}async function Rd(e){try{const{stdout:t}=await Ag(`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 Rd(a);s.push(...o)}return s}catch{return[]}}function Pl(e,t,r){try{process.kill(e,t)}catch(s){r==null||r(`Error sending ${t} to process ${e}: ${s}`)}}async function Mg(e,t,r){const s=await Rd(e);for(const a of s.reverse())await Pl(a,t,r);await Pl(e,t,r)}async function Br(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 Mg(e,o,t);for(let l=0;l<i;l++)if(await Pg(1e3),s+=1e3,!await Tg(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 $g(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:mm(),createdAt:t}}rm.config({quiet:!0});var Od=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(Od||{});class Ig extends sm{constructor(){super(...arguments),this.processes=new Map}register(t){const r=am(),{process:s,type:a,name:o,metadata:i,parentId:l}=t,c={id:r,type:a,name:o,pid:s.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:l,children:[]};if(this.processes.set(r,{info:c,process:s}),l){const h=this.processes.get(l);h&&(h.info.children=h.info.children||[],h.info.children.push(r))}const p=(h,m)=>{this.handleProcessExit(r,h,m)},u=h=>{this.handleProcessError(r,h)};return s.on("exit",p),s.on("error",u),s.__cleanup=()=>{s.removeListener("exit",p),s.removeListener("error",u)},this.emit("processStarted",c),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const s=this.processes.get(t);if(!s)throw new Error(`Process not found: ${t}`);const{info:a,process:o}=s;if(a.state==="completed"||a.state==="failed"||a.state==="killed")return;if(r.shutdownChildren&&a.children&&a.children.length>0&&await Promise.all(a.children.map(l=>this.shutdown(l,r))),o.pid)try{await Br(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 Za=null;function Fg(){return Za||(Za=new Ig),Za}const Dg={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function Rg({command:e,args:t,workingDir:r,outputOptions:s=Dg,processName:a,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${a}`},l=xt(e,t,{cwd:r,env:i});return Fg().register({process:l,type:Od.Other,name:a,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const h=f=>{const y=ee.join(r,"log.txt");G.appendFile(y,f,g=>{g&&console.log("Error writing to log file:",g)})},m=(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=m(y);s.stdoutToConsole&&console.log(g),s.stdoutToFile&&h(g+`
37
- `),s.stdoutCallback&&s.stdoutCallback(y)}),l.stderr.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=m(y,"<STDERR>");s.stderrToConsole&&console.error(g),s.stderrToFile&&h(g+`
38
- `),s.stderrCallback&&s.stderrCallback(y)}),l.on("exit",function(f){u(f)})}),process:l}}function Og(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 Lg({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:s}){const a=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
39
- `);G.writeFileSync(`${e}/.env`,a);const o=Og(r);return Rg({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:s,processName:"analyzer",env:t})}const zg="/tmp/codeyam/local-dev";function Ld(e){return H.join(zg,e)}function zd(e){return H.join(Ld(e),"codeyam")}function Ft(e){return H.join(Ld(e),"project")}function Gr(e){return H.join(zd(e),"log.txt")}const Bg=[".sync-metadata.json","__codeyamMocks__"];async function Yg(e,t={}){const{port:r,silent:s=!0}=t,a=Ft(e);if(r)try{De(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}try{De(`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 Wg(e,t={}){const{killProcesses:r=!0,port:s,silent:a=!0}=t,o=Ft(e),i=[],l=[];if(!G.existsSync(o))return{removed:i,errors:l};r&&await Yg(e,{port:s,silent:a});for(const c of Bg){const p=H.join(o,c);if(G.existsSync(p))try{(await Ae.stat(p)).isDirectory()?await Ae.rm(p,{recursive:!0,force:!0}):await Ae.unlink(p),i.push(c)}catch(u){l.push(`${c}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:l}}const Ug=H.dirname(ea(import.meta.url));function Jg(e){let t=e;for(;t!==H.dirname(t);){const r=H.join(t,"package.json");if(G.existsSync(r))try{if(JSON.parse(G.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=H.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function ca(){const e=Jg(Ug);return H.join(e,"analyzer-template")}function hr(e){return zd(e)}function Hg(){const e=ca();return G.existsSync(H.join(e,".finalized"))}async function Tl(e){const t=ca(),r=hr(e),s=Date.now(),a=()=>`${((Date.now()-s)/1e3).toFixed(1)}s`;if(!G.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await Ae.mkdir(H.dirname(r),{recursive:!0}),console.log(`[createAnalyzer] Starting rsync: ${t} → ${r}`),await jg({sourcePath:t,destinationPath:r,silent:!0}),console.log(`[createAnalyzer] rsync completed (${a()})`),G.existsSync(H.join(r,"dist"))||(console.warn("[createAnalyzer] WARNING: dist/ not found after rsync — template may not be built. Attempting build..."),De("npm install --include=dev && npm run build",{cwd:r,stdio:"pipe",timeout:3e5}),console.log(`[createAnalyzer] npm install + build completed (${a()})`)),console.log(`[createAnalyzer] Done (${a()})`)}function mr(e,t,r,s){const a=hr(e);if(!G.existsSync(a))throw new Error(`Analyzer not found at ${a}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const o=void 0;return Lg({absoluteCodeyamRootPath:a,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function Vg(e){const t=ca(),r=hr(e),s=H.join(t,".build-info.json"),a=H.join(r,".build-info.json");if(!G.existsSync(s))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!G.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!G.existsSync(a))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(G.readFileSync(s,"utf8")),i=JSON.parse(G.readFileSync(a,"utf8"));return o.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${o.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(o){return{isFresh:!1,reason:`Error reading build markers: ${o.message}`}}}async function qr(e,t){const r=hr(e);if(!G.existsSync(r)){t.update("Creating analyzer..."),await Tl(e);return}const s=Vg(e);s.isFresh||(t.update(`Updating analyzer (${s.reason})...`),await Tl(e),t.update("Analyzer updated"))}async function ni(e){await Wg(e,{killProcesses:!1})}const Kg=H.dirname(ea(import.meta.url));function da(){let e=Kg;for(;e!==H.dirname(e);){const t=H.join(e,"package.json");if(G.existsSync(t))try{if(JSON.parse(G.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=H.dirname(e)}return null}function rr(e){if(!G.existsSync(e))return null;try{return JSON.parse(G.readFileSync(e,"utf8"))}catch{return null}}function Gg(){const e=da();if(e){const t=[H.join(e,"src/webserver/build-info.json"),H.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const s=rr(r);if(s!=null&&s.semanticVersion)return s.semanticVersion}}return"unknown"}function qg(){const e=da();if(e){const t=H.join(e,"package.json");try{const r=JSON.parse(G.readFileSync(t,"utf8"));if(r.version)return r.version}catch{}}return"unknown"}const ri=Gg(),Xa=qg();function si(){if(Xa!=="unknown"&&Xa!=="0.1.0")return Xa;const e=da();if(e)for(const t of[H.join(e,"src/webserver/build-info.json"),H.join(e,"codeyam-cli/src/webserver/build-info.json")]){const r=rr(t);if(r!=null&&r.buildNumber)return`dev (build ${r.buildNumber})`}return"dev"}function Bd(e){const t=da();let r=null;if(t){const c=[H.join(t,"src/webserver/build-info.json"),H.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const p of c)if(r=rr(p),r)break}const s=ca(),a=H.join(s,".build-info.json"),o=rr(a);let i=null;if(e){const c=hr(e),p=H.join(c,".build-info.json");i=rr(p)}let l=!1;return o&&i?l=o.buildTime>i.buildTime:o&&!i&&e&&(l=!0),{cliVersion:ri,webserverVersion:r,templateVersion:o,cachedAnalyzerVersion:i,isCacheStale:l}}function ua(e){const t=hr(e),r=H.join(t,".build-info.json"),s=rr(r);return(s==null?void 0:s.version)??null}function ai(){const e=Ce();return e?H.join(e,".codeyam","server.json"):null}function F_(e){const t=ai();t&&G.writeFileSync(t,JSON.stringify(e,null,2))}function pa(){const e=ai();if(!e||!G.existsSync(e))return null;try{const t=G.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function oi(){const e=ai();if(e)try{G.unlinkSync(e)}catch{}}function Yd(e){try{return process.kill(e,0),!0}catch{return!1}}function Wd(){try{const e=process.platform==="win32",r=De(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{De(`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 D_(){const e=pa();if(e)if(!Yd(e.pid))oi();else return{running:!0,state:e};const t=Wd();return t.length>0?{running:!0,pids:t}:{running:!1}}function Qg(e,t=5e3){if(e.length===0)return!0;const r=Date.now()+t;for(;Date.now()<r;){if(!e.some(a=>Yd(a)))return!0;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100)}return!1}function R_(){let e=!1;const t=[],r=pa();if(r){try{process.kill(r.pid,"SIGTERM"),t.push(r.pid),e=!0}catch{}oi()}const s=Wd();for(const a of s)try{process.kill(a,"SIGTERM"),t.includes(a)||t.push(a),e=!0}catch{}return Qg(t),e}function O_(e,t,r=10,s=10){if(t(e))return e;for(let a=1;a<=s;a++){const o=e+a*r;if(t(o))return o}throw new Error(`Could not find a free port starting from ${e} (tried ${s} candidates)`)}function L_(e){try{return De(`lsof -ti:${e}`,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}),!1}catch{return!0}}const Zg="/assets/globals-Gp2o-NMc.css";function Ml({text:e,subtext:t,linkText:r,linkTo:s}){const[a,o]=A(!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(ke,{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 Xg({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 e0({serverVersion:e}){const[t,r]=A("stale"),[s,a]=A(null),o=async()=>{r("restarting"),a(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let l=0;const c=30,p=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}l++,l<c?setTimeout(()=>void u(),p):(a("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void u(),500)}catch(i){a(i instanceof Error?i.message:"Failed to restart server"),r("stale")}};return n("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:n("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-amber-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),d("div",{className:"flex-1",children:[t==="stale"&&d(ve,{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(ve,{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(ve,{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 pt({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:s="",duration:a=2e3,ariaLabel:o,icon:i=!1,iconSize:l=14}){const[c,p]=A(!1),u=oe(()=>{navigator.clipboard.writeText(e).then(()=>{p(!0),setTimeout(()=>p(!1),a)}).catch(h=>{console.error("Failed to copy:",h)})},[e,a]);return n("button",{onClick:u,className:`cursor-pointer ${s}`,disabled:c,"aria-label":o||(c?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?c?n(Et,{size:l,className:"text-green-500"}):n(It,{size:l}):c?r:t})}function t0({currentVersion:e,latestVersion:t}){const[r,s]=A(!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(pt,{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 Pr=null,ms=0;const n0=3600*1e3;function r0(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 s0(){const e=si();if(Pr&&Date.now()-ms<n0)return Pr;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 Pr=l,ms=Date.now(),l}const o=(await s.json()).version;if(!o){const l={updateAvailable:!1,latestVersion:null,currentVersion:e};return Pr=l,ms=Date.now(),l}const i={updateAvailable:r0(o,e),latestVersion:o,currentVersion:e};return Pr=i,ms=Date.now(),i}catch{return{updateAvailable:!1,latestVersion:null,currentVersion:e}}}function Vs(e){return H.join(e,".codeyam","queue.json")}function Fr(e){const t=Vs(e);if(!G.existsSync(t))return{paused:!1,jobs:[]};try{const r=G.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function a0(e,t){const r=Vs(e),s=H.dirname(r);G.existsSync(s)||G.mkdirSync(s,{recursive:!0});try{G.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(a){throw console.error("Failed to save queue state:",a),a}}const Qs=class Qs extends Vr{constructor(t){super(),this.watcher=null,this.debounceTimers=new Map,this.DEBOUNCE_MS=300,this.options=t}start(){try{this.watcher=ue.watch(this.options.projectRootPath,{recursive:!0},(t,r)=>{if(!r||!/\.(ts|tsx|js|jsx|css|scss|json|svg|html)$/.test(r)||Qs.IGNORED_DIRS.some(a=>r.includes(a+"/")||r.includes(a+"\\")))return;const s=this.debounceTimers.get(r);s&&clearTimeout(s),this.debounceTimers.set(r,setTimeout(()=>{this.debounceTimers.delete(r),this.syncFile(r)},this.DEBOUNCE_MS))}),console.log(`[InteractiveSyncWatcher] Watching ${this.options.projectRootPath} for changes`)}catch(t){console.error("[InteractiveSyncWatcher] Failed to start:",t)}}syncFile(t){const r=ee.join(this.options.projectRootPath,t),s=ee.join(this.options.tmpProjectPath,t);try{if(!ue.existsSync(r)){ue.existsSync(s)&&(ue.unlinkSync(s),console.log(`[InteractiveSyncWatcher] Removed: ${t}`));return}const a=ee.dirname(s);ue.existsSync(a)||ue.mkdirSync(a,{recursive:!0}),ue.copyFileSync(r,s);const o=ee.basename(t);console.log(`[InteractiveSyncWatcher] Synced: ${t}`);const i={type:"file-synced",fileName:o,filePath:t,timestamp:Date.now()};this.emit("sync",i)}catch(a){console.error(`[InteractiveSyncWatcher] Error syncing ${t}:`,a);const o={type:"error",fileName:ee.basename(t),filePath:t,timestamp:Date.now()};this.emit("sync",o)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null);for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),console.log("[InteractiveSyncWatcher] Stopped")}};Qs.IGNORED_DIRS=["node_modules",".git",".codeyam","__codeyamMocks__",".next","dist","build",".turbo",".vercel","coverage",".cache"];let No=Qs,o0=class extends Vr{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 So="__codeyam_dev_mode_event_emitter__";globalThis[So]||(globalThis[So]=new o0);const $l=globalThis[So],Co=new Map;async function i0(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await l0(e,t,r);else if(e.type==="baseline")await c0(e,t,r);else if(e.type==="recapture")await d0(e,t,r);else if(e.type==="capture-only")await u0(e,t,r);else if(e.type==="debug-setup")await p0(e,t,r);else if(e.type==="interactive-start")await h0(e,t,r);else if(e.type==="interactive-stop")await m0(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 l0(e,t,r){var b,v,N,w;const{projectSlug:s,commitSha:a,entityShas:o}=e;if(!a)throw new Error("Analysis job missing commitSha");const i=o||[],l=e.onlyDataStructure,c=Gr(s),p=C=>{const S=`CodeYam Log Level 1: ${C}`;console.log(`[Queue] ${C}`);try{G.mkdirSync(H.dirname(c),{recursive:!0}),G.appendFileSync(c,`[${new Date().toLocaleString()}] ${S}
42
-
43
- `)}catch{}},{project:u}=await Re(s);p("Preparing project cache..."),await ni(s),p("Preparing simulation engine..."),await qr(s,{update:C=>p(C)});const h=ua(s),m={...await hn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:mn(),...!l&&i.length>0?{ENTITY_SHAS:i.join(",")}:{},...l?{ONLY_DATA_STRUCTURE:"true"}:{},...h?{ANALYZER_VERSION:h}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},f=(v=(b=u.metadata)==null?void 0:b.webapps)==null?void 0:v[0];if(!f)throw new Error("No webapps found in project metadata");const y={packageManager:((N=u.metadata)==null?void 0:N.packageManager)||"npm",absoluteProjectRootPath:Ft(s),port:0,noServer:!0,framework:f.framework,...l?{}:{orchestrateCapture:"local-sequential"}},g=mr(s,m,y),x=C=>{try{return process.kill(C,0),!0}catch{return!1}};await an({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:g.process.pid}}),r==null||r.notifyChange("commit");try{try{const C=new Promise((S,k)=>setTimeout(()=>k(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([g.promise,C]),await an({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await an({commitSha:a,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(S=>setTimeout(S,2e3))}finally{if(g.process.pid)try{x(g.process.pid)&&await Br(g.process.pid,()=>{})}catch{}}}catch(C){if(console.error(`[Queue] Analysis job ${e.id} failed:`,C),g.process.pid&&x(g.process.pid))try{await Br(g.process.pid,()=>{})}catch{}try{await an({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:C instanceof Error?C.message:String(C)}}),r==null||r.notifyChange("commit")}catch(S){console.error("[Queue] Failed to update commit metadata after job failure:",S)}throw C}}async function c0(e,t,r){var m,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 ni(s),await qr(s,{update:g=>console.log(`[Queue] ${g}`)});const i=ua(s),l={...await hn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:mn(),...i?{ANALYZER_VERSION:i}:{}},c=(f=(m=o.metadata)==null?void 0:m.webapps)==null?void 0:f[0];if(!c)throw new Error("No webapps found in project metadata");const p={packageManager:((y=o.metadata)==null?void 0:y.packageManager)||"npm",absoluteProjectRootPath:Ft(s),port:0,noServer:!0,framework:c.framework,orchestrateCapture:"local-sequential"},u=mr(s,l,p),h=g=>{try{return process.kill(g,0),!0}catch{return!1}};await an({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 an({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${s}`),await new Promise(x=>setTimeout(x,2e3))}finally{if(u.process.pid)try{h(u.process.pid)&&await Br(u.process.pid,()=>{})}catch{}}}async function d0(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 Vt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:b}=await import("./index-CvuvIPEn.js"),v=b(),N=await v.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let w={};N!=null&&N.metadata&&(typeof N.metadata=="string"?w=JSON.parse(N.metadata):w=N.metadata),w.defaultWidth=i,await v.updateTable("entities").set({metadata:JSON.stringify(w)}).where("sha","=",l.entitySha).execute()}await ur(a,b=>{if(b.readyToBeCaptured=!0,b.scenarios)for(const v of b.scenarios)(!o||v.name===o)&&(delete v.finishedAt,delete v.startedAt,delete v.screenshotStartedAt,delete v.screenshotFinishedAt,delete v.interactiveStartedAt,delete v.interactiveFinishedAt,delete v.error,delete v.errorStack);delete b.finishedAt});const{project:c}=await Re(s);await qr(s,{update:b=>console.log(`[Queue] ${b}`)});const p=ua(s),u={...await hn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:mn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...p?{ANALYZER_VERSION:p}:{}},h={packageManager:((f=c.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:Ft(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)??nt.Next,orchestrateCapture:"local-sequential"},m=mr(s,u,h);try{await m.promise}finally{try{m.process.kill("SIGTERM")}catch{}}}async function u0(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 Vt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:b}=await import("./index-CvuvIPEn.js"),v=b(),N=await v.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let w={};N!=null&&N.metadata&&(typeof N.metadata=="string"?w=JSON.parse(N.metadata):w=N.metadata),w.defaultWidth=i,await v.updateTable("entities").set({metadata:JSON.stringify(w)}).where("sha","=",l.entitySha).execute()}await ur(a,b=>{if(b.readyToBeCaptured=!0,b.scenarios)for(const v of b.scenarios)(!o||v.name===o)&&(delete v.finishedAt,delete v.startedAt,delete v.screenshotStartedAt,delete v.screenshotFinishedAt,delete v.interactiveStartedAt,delete v.interactiveFinishedAt,delete v.error,delete v.errorStack);delete b.finishedAt});const{project:c}=await Re(s);await qr(s,{update:b=>console.log(`[Queue] ${b}`)});const p=ua(s);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await hn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:mn(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...p?{ANALYZER_VERSION:p}:{}},h={packageManager:((f=c.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:Ft(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)??nt.Next,orchestrateCapture:"local-sequential"},m=mr(s,u,h);try{await m.promise}finally{try{m.process.kill("SIGTERM")}catch{}}}async function p0(e,t,r){var m,f,y,g;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Debug setup job missing analysisId");const i=await Vt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:l}=await Re(s);await ni(s),await qr(s,{update:x=>console.log(`[Queue] ${x}`)});const c={...await hn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:mn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,PREP_ONLY:"true"};o&&(c.SCENARIO_IDS=o);const p={packageManager:((m=l.metadata)==null?void 0:m.packageManager)||"npm",absoluteProjectRootPath:Ft(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)||nt.Next},h=await mr(s,c,p).promise;if(h!==0)throw new Error(`Prep process exited with code ${h}`)}async function h0(e,t,r){var x,b,v,N;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Interactive start job missing analysisId");const i=await Vt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:l}=await Re(s),c={...await hn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:mn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,INTERACTIVE_MODE:"true"};o&&(c.INITIAL_SCENARIO_ID=o),i.scenarios&&i.scenarios.length>0&&(c.SCENARIO_IDS=i.scenarios.map(w=>w.id).join(","));const p=Ft(s),u=ee.join(p,".next","dev","lock");if(ue.existsSync(u)){console.log("[Queue] Found stale .next/dev/lock, cleaning up old processes");try{const w=De(`pgrep -f ${JSON.stringify(p)} 2>/dev/null || true`,{encoding:"utf-8"}).trim();if(w)for(const C of w.split(`
44
- `).filter(Boolean))try{process.kill(parseInt(C,10),"SIGTERM"),console.log(`[Queue] Killed stale process ${C}`)}catch{}}catch{}try{ue.unlinkSync(u),console.log("[Queue] Removed stale lock file")}catch{}}const h=ue.existsSync(p)&&ue.existsSync(ee.join(p,"package.json")),m={packageManager:((x=l.metadata)==null?void 0:x.packageManager)||"npm",absoluteProjectRootPath:p,port:void 0,noServer:!1,fast:h,framework:((N=(v=(b=l.metadata)==null?void 0:b.webapps)==null?void 0:v[0])==null?void 0:N.framework)||nt.Next};await ur(a,w=>{w.readyToBeCaptured=!0});const f=mr(s,c,m);await Cd(a,w=>{w.interactiveMode={pid:f.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${a}, PID: ${f.process.pid}`);const y=Ft(s),g=new No({projectRootPath:t,tmpProjectPath:y});g.on("sync",w=>{w.type==="file-synced"?$l.emitFileSynced(w.fileName,w.filePath):w.type==="error"&&$l.emitError(w.fileName,w.filePath)}),g.start(),Co.set(a,g),console.log(`[Queue] File sync watcher started for analysis ${a}`)}async function m0(e,t,r){var p;const{projectSlug:s,analysisId:a}=e;if(!a)throw new Error("Interactive stop job missing analysisId");const o=await Vt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!o)throw new Error(`Analysis ${a} not found`);const i=(p=o.metadata)==null?void 0:p.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${a}`);return}const l=Co.get(a);l&&(l.stop(),Co.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 Br(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 Cd(a,u=>{u.interactiveMode=null})}}class f0{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=Fr(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||Uo(),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 i0(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(){a0(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class g0{constructor(t,r,s=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=s}start(){const t=Vs(this.projectRoot);if(!G.existsSync(t)){console.log("[QueueFileWatcher] Queue file does not exist yet, will start watching when created"),this.watchDirectory();return}this.watchFile(t)}watchDirectory(){const t=Vs(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=G.watch(r,(s,a)=>{a==="queue.json"&&(this.stop(),this.watchFile(t),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(s){console.error("[QueueFileWatcher] Failed to watch directory:",s)}}watchFile(t){try{this.watcher=G.watch(t,r=>{r==="change"&&this.notifyChange()}),console.log("[QueueFileWatcher] Watching queue.json for changes")}catch(r){console.error("[QueueFileWatcher] Failed to watch queue file:",r)}}notifyChange(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.onChange(),this.debounceTimer=null},this.debounceMs)}stop(){this.watcher&&(this.watcher.close(),this.watcher=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}class y0{constructor(t,r,s){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=s,this.cachedState=Fr(r)}start(){this.cachedState=Fr(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 g0(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=Fr(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=Fr(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 x0(e){const t=H.join(e,".codeyam","server.json");if(!G.existsSync(t))return null;try{const r=G.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function b0(e){try{return process.kill(e,0),!0}catch{return!1}}async function v0(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 w0(e){const t=x0(e);return!t||!b0(t.pid)||!await v0(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class N0 extends Vr{constructor(){super();ht(this,"watcher",null);ht(this,"dbPath",null);ht(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=mn();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 ft=new N0;let kn=null,Dr=null;async function S0(){if(!kn){if(Dr){await Dr;return}Dr=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||kd()||process.cwd();if(gg(e),console.log(`[GlobalQueue] Project root: ${e}`),await Je(),process.env.NODE_ENV==="development")try{const r=ee.join(e,".codeyam","config.json"),a=JSON.parse(await ue.promises.readFile(r,"utf8")).projectSlug;a&&(await sr({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 w0(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new y0(t,e,()=>{ft.notifyChange("unknown")});await r.start(),kn=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new f0(e,ft);await r.start(),kn=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Dr}}async function Kt(){return kn||await S0(),kn}function C0(){return kn||(Dr&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const k0=()=>[{rel:"stylesheet",href:Zg},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}],_0={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:si()};async function E0({request:e,context:t}){var r,s,a,o,i,l,c,p,u,h,m;try{const f=e.signal,y=()=>{if(f.aborted)throw new Response(null,{status:499})};y();const g=Ce()||process.cwd(),[x,b,v]=await Promise.all([Ye(),la(g),s0().catch(()=>null)]);if(!x)throw new Error("Project slug not found");const{project:N,branch:w}=await Re(x);y();const C=await Ws({projectId:N.id,branchId:w.id,limit:20,skipRelations:!0});y();const S=C.length>0?C[0]:null,k=t.analysisQueue||C0(),j=k==null?void 0:k.getState();y();const _=await Promise.all(((j==null?void 0:j.jobs)||[]).map(async V=>{var pe;const ae=await hs(V.entityShas||[]);return ae.length===0&&((pe=V.entityShas)!=null&&pe.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",V.id),{...V,entities:ae}}));let F=null;if(j!=null&&j.currentlyExecuting){const V=j.currentlyExecuting,ae=await hs(V.entityShas||[]);ae.length===0&&((r=V.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",V.id),F={...V,entities:ae}}const M=F?_.filter(V=>V.id!==F.id):_;let $=((a=(s=S==null?void 0:S.metadata)==null?void 0:s.currentRun)==null?void 0:a.currentEntityShas)||[];if($.length===0){const V=((o=S==null?void 0:S.metadata)==null?void 0:o.historicalRuns)||[];if(V.length>0){const pe=[...V].sort((xe,ie)=>{const me=xe.archivedAt||xe.createdAt||"";return(ie.archivedAt||ie.createdAt||"").localeCompare(me)})[0];if(pe){const xe=pe.analysisCompletedAt||pe.createdAt;if(xe){const ie=new Date(xe).getTime(),we=Date.now()-1440*60*1e3;ie>we&&($=pe.currentEntityShas||[])}}}}const O=await hs($),D=[];b.ANTHROPIC_API_KEY&&D.push("ANTHROPIC_API_KEY"),b.GROQ_API_KEY&&D.push("GROQ_API_KEY"),b.OPENAI_API_KEY&&D.push("OPENAI_API_KEY"),b.OPENROUTER_API_KEY&&D.push("OPENROUTER_API_KEY"),y();const T=[];for(const V of C){const ae=((i=V.metadata)==null?void 0:i.historicalRuns)||[];for(const pe of ae)T.push(pe)}T.sort((V,ae)=>{const pe=V.archivedAt||V.analysisCompletedAt||V.createdAt||"";return(ae.archivedAt||ae.analysisCompletedAt||ae.createdAt||"").localeCompare(pe)});const B=new Set(((l=F==null?void 0:F.entities)==null?void 0:l.map(V=>V.sha))||[]),I=T.filter(V=>!(V.currentEntityShas||[]).some(pe=>B.has(pe))).slice(0,3),L=new Set;for(const V of I)for(const ae of V.currentEntityShas||[])L.add(ae);const P=await hs(Array.from(L)),R=new Map;for(const V of P)R.set(V.sha,V);const E=I.map(V=>({...V,entities:(V.currentEntityShas||[]).map(ae=>R.get(ae)).filter(ae=>ae!=null)})),J=pa(),K=(J==null?void 0:J.cliVersion)??"unknown",Q=K!=="unknown"&&K!==ri,q=((p=(c=N.metadata)==null?void 0:c.labs)==null?void 0:p.simulations)??!1,U=q?Hg():!1,z=((u=N.metadata)==null?void 0:u.editorMode)??!1,W={currentRun:(h=S==null?void 0:S.metadata)==null?void 0:h.currentRun,projectSlug:x,currentEntities:O,availableAPIKeys:D,queuedJobCount:M.length,queueJobs:M,currentlyExecuting:F,historicalRuns:E,isServerOutOfDate:Q,serverVersion:K,npmUpdate:v!=null&&v.updateAvailable&&v.latestVersion?{latestVersion:v.latestVersion,currentVersion:v.currentVersion}:null,labs:((m=N.metadata)==null?void 0:m.labs)??null,simulationsEnabled:q,isSimulationsReady:U,isAdmin:!!process.env.CODEYAM_ADMIN,editorMode:z,displayVersion:si()};return re(W)}catch(f){return f instanceof Response&&f.status===499||console.error("Failed to load root data:",f),re(_0)}}function j0(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:s,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:l,isServerOutOfDate:c,serverVersion:p,npmUpdate:u,labs:h,simulationsEnabled:m,isSimulationsReady:f,isAdmin:y,editorMode:g,displayVersion:x}=ot(),{toasts:b,closeToast:v}=Qo(),N=Rt(),w=ye(N),C=Jr(),S=ye(C.pathname);ne(()=>{w.current=N},[N]),ne(()=>{S.current=C.pathname},[C.pathname]);const k=C.pathname.startsWith("/entity/")&&C.pathname.includes("/edit/")||C.pathname.startsWith("/dev/")||C.pathname.startsWith("/editor"),j=C.pathname.includes("/fullscreen")||C.pathname.startsWith("/editor");return ne(()=>{let _=null,F=null,M=0;function $(){_||(_=new EventSource("/api/events"),_.addEventListener("message",T=>{const B=JSON.parse(T.data);(B.type==="queue"||B.type==="db-change")&&B.type;const Y=Nm(S.current),I=Sm({now:Date.now(),lastRevalidation:M,throttleMs:Y});I==="immediate"?(w.current.revalidate(),M=Date.now()):(F&&clearTimeout(F),F=setTimeout(()=>{w.current.revalidate(),M=Date.now(),F=null},I.delayMs))}),_.addEventListener("error",()=>{}))}function O(){F&&(clearTimeout(F),F=null),_&&(_.close(),_=null)}function D(){document.hidden?O():($(),w.current.revalidate())}return document.hidden||$(),document.addEventListener("visibilitychange",D),()=>{document.removeEventListener("visibilitychange",D),O()}},[]),d(ve,{children:[d("div",{className:`min-h-screen ${k?"":"grid"} bg-cygray-10`,style:k?void 0:{gridTemplateColumns:"65px minmax(0, 1fr)"},children:[!k&&n(Am,{labs:h,isAdmin:y,editorMode:g}),d("div",{className:"max-h-screen overflow-auto bg-cygray-10 flex flex-col min-h-screen",children:[c&&n(e0,{serverVersion:p}),u&&u.currentVersion&&n(t0,{currentVersion:u.currentVersion,latestVersion:u.latestVersion}),m&&!g&&s.length===0&&n(Ml,{text:"No AI API keys configured. Please provide an AI API key at your earliest convenience.",subtext:"An API key is required for stable, frequent use of CodeYam",linkText:"Configure API Keys",linkTo:"/settings"}),m&&!g&&!f&&n(Ml,{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(td,{})}),n(Xg,{version:x})]})]}),n(Mm,{toasts:b,onClose:v}),!j&&m&&n($m,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:l})]})}const A0=et(function(){return d("html",{lang:"en",children:[d("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(nh,{}),n(rh,{})]}),d("body",{children:[n(Pm,{children:n(Em,{children:n(j0,{})})}),n(sh,{}),n(ah,{})]})]})});function P0(e){if(e instanceof TypeError&&/fetch/i.test(e.message)||e instanceof Error&&/fetch/i.test(e.message))return!0;const t=String(e);return/failed to fetch|fetch.*failed|load.*chunk/i.test(t)}const T0=oh(function(){const t=ih(),r=!Wa(t)&&P0(t),s=Wa(t)?t.status:500,a=Wa(t)?t.statusText||"Server Error":"Something went wrong";return d("html",{lang:"en",children:[d("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),d("title",{children:[s," - CodeYam"]})]}),n("body",{style:{margin:0,fontFamily:'"IBM Plex Sans", system-ui, -apple-system, sans-serif',backgroundColor:"#1e1e1e",color:"#ffffff",minHeight:"100vh",display:"flex",alignItems:"center"},children:d("div",{style:{maxWidth:700,width:"100%",padding:"64px 80px"},children:[d("div",{style:{fontFamily:'"IBM Plex Mono", monospace',fontSize:32,fontWeight:400,color:"#8E8E8E",lineHeight:1,marginBottom:12},children:["<",s,">"]}),n("h1",{style:{fontSize:42,fontWeight:600,margin:"0 0 20px",color:"#ffffff",lineHeight:1.2},children:r?"Something went wrong :(":a}),r?d("div",{children:[n("p",{style:{fontSize:16,color:"#8E8E8E",lineHeight:1.7,margin:"0 0 28px",maxWidth:480},children:"It looks like the CodeYam server is no longer running. This usually happens when the terminal session that started it was closed."}),d("p",{style:{fontSize:16,color:"#ffffff",margin:0,lineHeight:1.7,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["Run"," ",d("button",{id:"copy-cmd-btn",type:"button",style:{display:"inline-flex",alignItems:"center",gap:8,backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:6,padding:"6px 12px",fontFamily:'"IBM Plex Mono", monospace',fontSize:13,color:"#ffffff",letterSpacing:"0.05em",textTransform:"uppercase",cursor:"pointer",minWidth:172,justifyContent:"center"},children:[n("span",{id:"copy-cmd-label",children:"codeyam editor"}),d("svg",{id:"copy-cmd-icon",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#D7FF63",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})," ","in your project directory to restart the server. Then refresh this page."]}),n("script",{dangerouslySetInnerHTML:{__html:`
45
- document.getElementById('copy-cmd-btn').addEventListener('click', function() {
46
- var label = document.getElementById('copy-cmd-label');
47
- var icon = document.getElementById('copy-cmd-icon');
48
- navigator.clipboard.writeText('codeyam editor').then(function() {
49
- label.textContent = 'copied!';
50
- icon.style.display = 'none';
51
- setTimeout(function() {
52
- label.textContent = 'codeyam editor';
53
- icon.style.display = '';
54
- }, 2000);
55
- });
56
- });
57
- `}})]}):d("div",{children:[n("p",{style:{fontSize:16,color:"#8E8E8E",lineHeight:1.7,margin:"0 0 28px",maxWidth:480},children:"An unexpected error occurred. Try refreshing the page."}),t instanceof Error&&t.message&&n("pre",{style:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:8,padding:"16px 20px",fontFamily:'"IBM Plex Mono", monospace',fontSize:13,color:"#8E8E8E",textAlign:"left",overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},children:t.message})]})]})})]})}),M0=Object.freeze(Object.defineProperty({__proto__:null,ErrorBoundary:T0,default:A0,links:k0,loader:E0},Symbol.toStringTag,{value:"Module"}));function fs(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}async function Il(e,t){try{await fetch("/api/interactive-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e,scenarioName:t})})}catch(r){console.error("[useInteractiveMode] Failed to seed scenario:",r)}}function In({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:o=!0,refreshTrigger:i=0}){const l=Ge(),[c,p]=A(null),[u,h]=A(!1),[m,f]=A(!1),[y,g]=A(!1),x=ye(!1),b=ye(void 0),v=ye(null),N=ye(null),w=ye(null),C=ye(null),[S,k]=A(0),[j,_]=A(0),F=ye(null),M=ye(!1),$=ye(!1),O=ye(r),{interactiveUrl:D,scenarioUrlMap:T,resetLogs:B}=Jt(a,o),Y=ye(t);ne(()=>{O.current=r},[r]);const I=ye(i);ne(()=>{I.current!==i&&(I.current=i,c&&(f(!0),g(!1),k(0),_(E=>E+1),M.current=!1,$.current=!1,F.current&&(clearTimeout(F.current),F.current=null)))},[i,c]),ne(()=>{if(Y.current===t||(Y.current=t,!c||!t))return;f(!0),g(!1),k(0),M.current=!1,$.current=!1,O.current=r,F.current&&(clearTimeout(F.current),F.current=null),(async()=>{await Il(t,r);const J=v.current;let K;if(J&&J[t])K=J[t]+"?width=600px";else if(N.current&&w.current&&r){if(K=N.current,C.current&&s){const U=fs(C.current),z=fs(s);U!==z&&(K=K.replace(U,z))}const Q=fs(w.current),q=fs(r);K=K.replace(Q,q)}else K=c;p(K),_(Q=>Q+1)})()},[t,r,s,c]),ne(()=>{if(D){const E=D+"?width=600px";T&&(v.current=T),N.current=E,r&&(w.current=r),s&&(C.current=s),h(!1),f(!0),(async()=>{t&&r&&await Il(t,r);const K=v.current,Q=t&&K&&K[t]?K[t]+"?width=600px":E;p(Q)})()}},[D]);const L=()=>{g(!0),b.current=t;const E=O.current;requestAnimationFrame(()=>{requestAnimationFrame(()=>{O.current===E&&f(!1)})})};ne(()=>{const E=J=>{if(J.data.type==="codeyam-resize"){if(J.data.name&&O.current&&J.data.name!==O.current)return;M.current||(M.current=!0,F.current&&(clearTimeout(F.current),F.current=null),k(0),$.current&&L())}};return window.addEventListener("message",E),()=>window.removeEventListener("message",E)},[]);const P=()=>{if($.current=!0,M.current){L();return}F.current&&clearTimeout(F.current);const E=300*Math.pow(2,S);F.current=setTimeout(()=>{M.current||(S<2?(k(J=>J+1),_(J=>J+1),f(!0),$.current=!1):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),L()))},E)};ne(()=>{o&&!x.current&&t&&e&&(x.current=!0,h(!0),g(!1),p(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(J){console.error("[useInteractiveMode] Failed to clear log file:",J)}B(),l.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[o,t,e,B,a]),ne(()=>{const E=e,J=()=>{if(x.current&&E){const Q=new URLSearchParams({action:"stop",analysisId:E});navigator.sendBeacon("/api/interactive-mode",Q)||fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Q,keepalive:!0}).catch(U=>console.error("Failed to stop interactive mode:",U))}},K=()=>{J()};return window.addEventListener("beforeunload",K),()=>{window.removeEventListener("beforeunload",K),J()}},[e]);const R=y&&b.current===t;return{interactiveServerUrl:c,isStarting:u,isLoading:m,showIframe:R,iframeKey:j,onIframeLoad:P}}const gs=10,$0=1024;function ii({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:s,onHoverChange:a,hideLabel:o=!1,lightMode:i=!1}){const[l,c]=A(null),p=ye(null),u=le(()=>[...s].sort((v,N)=>v.width-N.width),[s]),{fittingPresets:h,overflowPresets:m}=le(()=>{const v=[],N=[];for(const w of u)w.width<=$0?v.push(w):N.push(w);return N.sort((w,C)=>C.width-w.width),{fittingPresets:v,overflowPresets:N}},[u]),f=oe(v=>{if(!p.current)return null;const N=p.current.getBoundingClientRect(),w=v-N.left,C=N.width,S=C/2,j=(h.length>0?h[h.length-1].width:0)/2,_=S-j,F=S+j,M=m.length>0?(m.length-1)*gs:0;if(m.length>0){if(w<_){if(w<=M){const O=Math.min(Math.floor(w/gs),m.length-1);return m[O]}return m[m.length-1]}if(w>F){const O=C-w;if(O<=M){const D=Math.min(Math.floor(O/gs),m.length-1);return m[D]}return m[m.length-1]}}const $=Math.abs(w-S);for(let O=h.length-1;O>=0;O--){const D=h[O],T=h[O-1],B=D.width/2,Y=T?T.width/2:0;if($<=B&&$>=Y)return D}return h[0]||m[m.length-1]||null},[h,m]),y=oe(v=>{const N=f(v.clientX);c(N),a==null||a(N)},[f,a]),g=oe(()=>{c(null),a==null||a(null)},[a]),x=oe(v=>{const N=f(v.clientX);N&&r(N)},[f,r]),b=l||{name:t,width:e};return d("div",{ref:p,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:h.map(v=>{const N=v.width===e,w=(l==null?void 0:l.name)===v.name,C=v.width/2;return d("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${C}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${N||w?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${C}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${N||w?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},v.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:m.map((v,N)=>{const w=N*gs,C=v.width===e,S=(l==null?void 0:l.name)===v.name;return d("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${w}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${C||S?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{right:`${w}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${C||S?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},v.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 I0({currentWidth:e,currentHeight:t,devicePresets:r,customSizes:s,onApply:a,onSave:o,onRemove:i,onClose:l}){const[c,p]=A(String(e)),[u,h]=A(String(t)),[m,f]=A(""),[y,g]=A(!1),x=ye(null),b=ye(null);ne(()=>{const _=F=>{x.current&&!x.current.contains(F.target)&&l()};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[l]),ne(()=>{const _=F=>{F.key==="Escape"&&l()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[l]),ne(()=>{var _;(_=b.current)==null||_.select()},[]);const v=parseInt(c,10),N=parseInt(u,10),w=v>0&&N>0,C=w&&(v!==e||N!==t),S=()=>{w&&(a({name:"Custom",width:v,height:N}),l())},k=()=>{const _=m.trim();!_||!w||(o(_,v,N),a({name:_,width:v,height:N}),l())},j=_=>{_.key==="Enter"&&(y&&m.trim()?k():C&&S())};return d("div",{ref:x,className:"absolute top-full mt-1 right-0 bg-[#2a2a2a] border border-[#444] rounded-lg shadow-xl z-50 w-64",children:[r&&r.length>0&&d("div",{className:"border-b border-[#444]",children:[n("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wider text-gray-500",children:"Presets"}),r.map(_=>d("button",{onClick:()=>{a(_),l()},className:`w-full px-3 py-1.5 text-left text-xs transition-colors cursor-pointer ${_.width===e&&_.height===t?"text-white bg-[#444]":"text-gray-300 hover:text-white hover:bg-[#333]"}`,children:[n("span",{className:"font-medium",children:_.name}),d("span",{className:"text-gray-500 ml-1.5",children:[_.width,"×",_.height]})]},_.name))]}),s.length>0&&d("div",{className:"border-b border-[#444]",children:[n("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wider text-gray-500",children:"Saved Sizes"}),s.map(_=>d("div",{className:"flex items-center group hover:bg-[#333] transition-colors",children:[d("button",{onClick:()=>{a(_),l()},className:"flex-1 px-3 py-1.5 text-left text-xs text-gray-300 hover:text-white transition-colors cursor-pointer",children:[n("span",{className:"font-medium",children:_.name}),d("span",{className:"text-gray-500 ml-1.5",children:[_.width,"×",_.height]})]}),n("button",{onClick:()=>i(_.name),className:"px-2 py-1.5 text-gray-600 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-all cursor-pointer",title:"Remove",children:n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M18 6L6 18M6 6l12 12"})})})]},_.name))]}),d("div",{className:"p-3",children:[d("div",{className:"flex items-center gap-2 mb-2",children:[n("input",{ref:b,type:"number",value:c,onChange:_=>p(_.target.value),onKeyDown:j,min:"100",max:"7680",className:"w-full px-2 py-1.5 bg-[#1a1a1a] border border-[#555] rounded text-xs text-white text-center focus:outline-none focus:border-[#007a99] [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",placeholder:"Width"}),n("span",{className:"text-gray-500 text-xs flex-shrink-0",children:"×"}),n("input",{type:"number",value:u,onChange:_=>h(_.target.value),onKeyDown:j,min:"100",max:"7680",className:"w-full px-2 py-1.5 bg-[#1a1a1a] border border-[#555] rounded text-xs text-white text-center focus:outline-none focus:border-[#007a99] [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",placeholder:"Height"})]}),d("div",{className:"flex gap-2",children:[n("button",{onClick:S,disabled:!w||!C,className:"flex-1 px-2 py-1.5 bg-[#007a99] text-white text-xs font-medium rounded hover:bg-[#006080] transition-colors cursor-pointer disabled:bg-[#333] disabled:text-gray-600 disabled:cursor-not-allowed",children:"Apply"}),y?d("div",{className:"flex gap-1",children:[n("input",{type:"text",value:m,onChange:_=>f(_.target.value),onKeyDown:j,placeholder:"Name",className:"w-20 px-2 py-1.5 bg-[#1a1a1a] border border-[#555] rounded text-xs text-white focus:outline-none focus:border-[#007a99]",autoFocus:!0}),n("button",{onClick:k,disabled:!m.trim()||!w,className:"px-2 py-1.5 bg-[#007a99] text-white text-xs rounded hover:bg-[#006080] transition-colors cursor-pointer disabled:bg-[#333] disabled:text-gray-600 disabled:cursor-not-allowed",children:"OK"})]}):n("button",{onClick:()=>g(!0),disabled:!w,className:"px-2 py-1.5 bg-[#333] text-gray-300 text-xs rounded hover:bg-[#444] transition-colors cursor-pointer disabled:text-gray-600 disabled:cursor-not-allowed",title:"Save as preset",children:"Save"})]})]})]})}function li({width:e,height:t,onSave:r,onCancel:s}){const[a,o]=A(""),[i,l]=A(""),c=()=>{const p=a.trim();if(!p){l("Please enter a name");return}r(p)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:d("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[d("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),d("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),d("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),d("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:a,onChange:p=>{o(p.target.value),l("")},onKeyDown:p=>{p.key==="Enter"&&a.trim()&&c(),p.key==="Escape"&&s()},placeholder:"e.g., iPhone 15 Pro",className:`w-full px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] ${i?"border-red-300":"border-gray-300"}`,autoFocus:!0}),i&&n("p",{className:"mt-1 text-sm text-red-600",children:i})]}),d("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:s,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 transition-colors cursor-pointer",children:"Cancel"}),n("button",{onClick:c,disabled:!a.trim(),className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function ha(e){const[t,r]=A([]),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=oe(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=oe((l,c,p)=>{r(u=>{const h=u.findIndex(y=>y.name===l),m={name:l,width:c,height:p};let f;return h>=0?(f=[...u],f[h]=m):f=[...u,m],a(f),f})},[a]),i=oe(l=>{r(c=>{const p=c.filter(u=>u.name!==l);return a(p),p})},[a]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}function Ut(){return d("div",{className:"spinner-container",children:[n("span",{className:"loader"}),n("style",{children:`
58
- .loader {
59
- width: 48px;
60
- height: 48px;
61
- border: 3px solid rgba(0, 92, 117, 0.2);
62
- border-radius: 50%;
63
- display: inline-block;
64
- position: relative;
65
- box-sizing: border-box;
66
- animation: rotation 1s linear infinite;
67
- }
68
- .loader::after {
69
- content: '';
70
- box-sizing: border-box;
71
- position: absolute;
72
- left: 50%;
73
- top: 50%;
74
- transform: translate(-50%, -50%);
75
- width: 56px;
76
- height: 56px;
77
- border-radius: 50%;
78
- border: 3px solid;
79
- border-color: #005c75 transparent;
80
- }
81
-
82
- @keyframes rotation {
83
- 0% {
84
- transform: rotate(0deg);
85
- }
86
- 100% {
87
- transform: rotate(360deg);
88
- }
89
- }
90
- `})]})}const Fl=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],F0=80;function ar(){const[e,t]=A(0);return ne(()=>{const r=setInterval(()=>{t(s=>(s+1)%Fl.length)},F0);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:Fl[e]})}async function D0({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw re("Invalid parameters",{status:400});const s=await Pn(t);if(!s)throw re("Entity not found",{status:404});const a=await oa(s),o=((l=a==null?void 0:a.scenarios)==null?void 0:l.find(c=>c.id===r))||null;if(!o)throw re("Scenario not found",{status:404});const i=await Ye();return re({entity:s,scenario:o,analysis:a,projectSlug:i})}const eo=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1920,height:1080}],R0=et(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=ot(),o=Dt(),[i]=ir(),[l,c]=A(null),[p,u]=A(1920),[h,m]=A({name:"Desktop",width:1920,height:1080}),[f,y]=A(!1),[g,x]=A(null),{customSizes:b,addCustomSize:v}=ha(a),N=le(()=>[...eo,...b],[b]),w=ye(null),[C,S]=A(1),k=oe(()=>{if(!w.current)return;const z=32,W=w.current.clientWidth-z,V=w.current.clientHeight-z,ae=h.width,pe=h.height??900,xe=Math.min(1,W/ae,V/pe);S(xe)},[h.width,h.height]);ne(()=>(k(),window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)),[k]);const{interactiveServerUrl:j,isStarting:_,isLoading:F,showIframe:M,iframeKey:$,onIframeLoad:O}=In({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:D}=Jt(a,_||F),T=()=>{o(`/entity/${t.sha}`)},B=(z,W)=>{u(z);const V=N.find(pe=>pe.width===z&&pe.height===W);c(V||null),m({name:(V==null?void 0:V.name)||"Custom",width:z,height:W})},Y=z=>{c(z),u(z.width),m({name:z.name,width:z.width,height:z.height})},I=z=>{v(z,h.width,h.height??900),y(!1),m(W=>({...W,name:z}))},L=((s==null?void 0:s.scenarios)||[]).filter(z=>{var W;return!((W=z.metadata)!=null&&W.sameAsDefault)}),P=L.findIndex(z=>z.id===(r==null?void 0:r.id)),R=P+1,E=L.length,J=P>0,K=P<L.length-1,Q=()=>{if(J){const z=L[P-1],W=encodeURIComponent(`/entity/${t.sha}/scenarios/${z.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${z.id}/fullscreen?from=${W}`)}},q=()=>{if(K){const z=L[P+1],W=encodeURIComponent(`/entity/${t.sha}/scenarios/${z.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${z.id}/fullscreen?from=${W}`)}},U=_||F||!M;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:na,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),d("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:Q,disabled:!J,className:`${J?"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:[R,"/",E]}),n("button",{onClick:q,disabled:!K,className:`${K?"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:`${eo[eo.length-1].width}px`,width:"100%"},children:n(ii,{currentViewportWidth:p,currentPresetName:h.name,onDevicePresetClick:Y,devicePresets:N,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)||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:z=>{const W=N.find(V=>V.name===z.target.value);W&&Y(W)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[N.map(z=>n("option",{value:z.name,children:z.name},z.name)),h.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:h.width,onChange:z=>{const W=parseInt(z.target.value,10);!isNaN(W)&&W>0&&B(W,h.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:h.height??900}),h.name==="Custom"&&n("button",{onClick:()=>y(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{ref:w,className:"flex-1 flex items-center justify-center overflow-hidden p-4",style:{backgroundImage:`
91
- linear-gradient(45deg, #ebebeb 25%, transparent 25%),
92
- linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
93
- linear-gradient(45deg, transparent 75%, #ebebeb 75%),
94
- linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
95
- `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:j?d("div",{className:"relative bg-white",style:{width:`${h.width}px`,height:`${h.height??900}px`,transform:`scale(${C})`,transformOrigin:"center center"},children:[U&&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(Ut,{})}),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"}),D&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(ar,{}),D]})]})]})}),n("iframe",{src:j,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:O,style:{opacity:M?1:0}},$)]}):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(Ut,{})}),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"}),D&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(ar,{}),D]})]})]})}),f&&n(li,{width:h.width,height:h.height??900,onSave:I,onCancel:()=>y(!1)})]})}),O0=Object.freeze(Object.defineProperty({__proto__:null,default:R0,loader:D0},Symbol.toStringTag,{value:"Module"})),tr={sound:"soft-double-tap",systemNotification:!0},L0=[{id:"soft-double-tap",label:"Soft double tap"},{id:"gentle-chime",label:"Gentle chime"},{id:"warm-ding",label:"Warm ding"},{id:"mellow-two-tone",label:"Mellow two-tone"},{id:"triangle-bell",label:"Triangle bell"},{id:"off",label:"No sound"}],Ud="codeyam-editor-notifications";function z0(){try{const e=localStorage.getItem(Ud);if(!e)return tr;const t=JSON.parse(e);return typeof t=="string"?t==="true"?tr:{...tr,sound:"off",systemNotification:!1}:{...tr,...t}}catch{return tr}}function B0(e){localStorage.setItem(Ud,JSON.stringify(e))}function Jd(e){var t;if(e!=="off")try{const r=new AudioContext,s={"soft-double-tap":a=>{[0,.12].forEach(o=>{const i=a.createOscillator(),l=a.createGain();i.connect(l),l.connect(a.destination),i.type="sine",i.frequency.value=392,l.gain.setValueAtTime(.25,a.currentTime+o),l.gain.exponentialRampToValueAtTime(.01,a.currentTime+o+.1),i.start(a.currentTime+o),i.stop(a.currentTime+o+.1)})},"gentle-chime":a=>{const o=a.createOscillator(),i=a.createGain();o.connect(i),i.connect(a.destination),o.type="sine",o.frequency.setValueAtTime(523,a.currentTime),o.frequency.setValueAtTime(659,a.currentTime+.15),i.gain.setValueAtTime(.3,a.currentTime),i.gain.exponentialRampToValueAtTime(.01,a.currentTime+.4),o.start(),o.stop(a.currentTime+.4)},"warm-ding":a=>{const o=a.createOscillator(),i=a.createGain();o.connect(i),i.connect(a.destination),o.type="sine",o.frequency.value=330,i.gain.setValueAtTime(.35,a.currentTime),i.gain.exponentialRampToValueAtTime(.01,a.currentTime+.6),o.start(),o.stop(a.currentTime+.6)},"mellow-two-tone":a=>{const o=a.createOscillator(),i=a.createGain();o.connect(i),i.connect(a.destination),o.type="sine",o.frequency.setValueAtTime(294,a.currentTime),o.frequency.setValueAtTime(440,a.currentTime+.18),i.gain.setValueAtTime(.3,a.currentTime),i.gain.exponentialRampToValueAtTime(.01,a.currentTime+.5),o.start(),o.stop(a.currentTime+.5)},"triangle-bell":a=>{const o=a.createOscillator(),i=a.createGain();o.connect(i),i.connect(a.destination),o.type="triangle",o.frequency.value=523,i.gain.setValueAtTime(.4,a.currentTime),i.gain.exponentialRampToValueAtTime(.01,a.currentTime+.8),o.start(),o.stop(a.currentTime+.8)}};(t=s[e])==null||t.call(s,r)}catch{}}function Hd({serverUrl:e,isStarting:t,projectSlug:r,devServerError:s,onStartServer:a,notificationSettings:o,onChangeNotificationSettings:i}){const[l,c]=A(null),[p,u]=A(!1),h=ye(null),m=ye(null);ne(()=>{if(!r)return;const b=new EventSource("/api/dev-mode-events");return b.onmessage=v=>{try{const N=JSON.parse(v.data);N.type==="file-synced"&&(c(N.fileName),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{c(null)},5e3))}catch{}},()=>{b.close(),m.current&&clearTimeout(m.current)}},[r]),ne(()=>{if(!p)return;function b(v){h.current&&!h.current.contains(v.target)&&u(!1)}return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[p]);let f;s?f="error":t?f="starting":e?f="running":f="stopped";const y={starting:"bg-yellow-400",running:"bg-green-400",stopped:"bg-gray-400",error:"bg-red-400"},g={starting:"Starting...",running:e||"Running",stopped:"Stopped",error:"Error"},x=o&&(o.sound!=="off"||o.systemNotification);return d("div",{className:"bg-[#1e1e1e] border-t border-[#3d3d3d] h-7 flex items-center px-4 gap-4 shrink-0 text-xs font-mono",children:[d("div",{className:"flex items-center gap-2",children:[n("div",{className:`w-2 h-2 rounded-full ${y[f]}`}),d("span",{className:"text-gray-400",children:["Server:"," ",n("span",{className:"text-gray-300",children:g[f]})]}),(f==="stopped"||f==="error")&&a&&n("button",{onClick:a,className:"ml-1 px-2.5 py-0.5 bg-[#005c75] hover:bg-[#007a9a] text-white text-[11px] font-medium rounded transition-colors cursor-pointer border-none leading-tight",children:"Start Server"})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"}),l&&d(ve,{children:[d("div",{className:"flex items-center gap-1.5",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2",children:n("path",{d:"M20 6L9 17l-5-5"})}),d("span",{className:"text-green-400",children:["Synced: ",l]})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"})]}),n("div",{className:"flex-1"}),i&&o&&d("div",{className:"relative",ref:h,children:[n("button",{onClick:()=>u(!p),className:`text-[11px] rounded transition-colors cursor-pointer ${x?"text-cygreen hover:text-cygreen/80":"text-gray-500 hover:text-gray-300"}`,children:x?"Notifications On":"Notifications Off"}),p&&d("div",{className:"absolute bottom-full right-0 mb-2 w-56 bg-[#2d2d2d] border border-[#4d4d4d] rounded-lg shadow-xl p-3 flex flex-col gap-3 z-50",children:[d("div",{children:[n("div",{className:"text-[11px] text-gray-400 mb-1.5",children:"Notification sound"}),n("div",{className:"flex flex-col gap-0.5",children:L0.map(b=>n("button",{onClick:()=>{i({...o,sound:b.id}),b.id!=="off"&&Jd(b.id)},className:`text-left text-[11px] px-2 py-1 rounded cursor-pointer transition-colors ${o.sound===b.id?"bg-[#444] text-white":"text-gray-300 hover:bg-[#3a3a3a]"}`,children:b.label},b.id))})]}),d("div",{className:"border-t border-[#4d4d4d] pt-2",children:[d("label",{className:"flex items-center gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:o.systemNotification,onChange:b=>{const v=b.target.checked;i({...o,systemNotification:v}),v&&typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()},className:"accent-green-500"}),n("span",{className:"text-[11px] text-gray-300",children:"System notification"})]}),n("div",{className:"text-[10px] text-gray-500 mt-1 ml-5",children:"Shows when tab is not visible"})]})]})]})]})}async function Y0(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(),Dl(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 Dl(e);return r||(t==null||t("canvas","dom",new Error("Canvas addon failed")),{type:"dom",dispose:()=>{}})}async function Dl(e){try{const{CanvasAddon:t}=await import("@xterm/addon-canvas"),r=new t;return e.loadAddon(r),{type:"canvas",dispose:()=>r.dispose()}}catch{return null}}class W0{constructor(t,r){ht(this,"deferred",!1);ht(this,"userActiveSinceLastOutput",!1);ht(this,"actions");ht(this,"env");this.actions=t,this.env=r}reportUserActivity(){this.userActiveSinceLastOutput=!0}resetActivityFlag(){this.userActiveSinceLastOutput=!1}onIdle(t,r){return this.deferred=!1,r&&this.env.hasBrowserFocus()&&this.userActiveSinceLastOutput?(this.userActiveSinceLastOutput=!1,"suppressed"):this.notify(t)}onBuildTabChange(t,r){return!t&&this.deferred?(this.deferred=!1,this.notify(r),!0):!1}onActive(){this.deferred=!1}onUserEngagement(){const t=this.deferred;return this.deferred=!1,t}get isDeferred(){return this.deferred}notify(t){const r=!!(t!=null&&t.sound)&&t.sound!=="off";return r&&this.actions.playSound(t.sound),!this.env.hasBrowserFocus()&&(t!=null&&t.systemNotification)&&this.env.hasNotificationPermission()&&this.actions.showSystemNotification(),r?"played":"played-no-sound"}}class U0{constructor(t){ht(this,"_isIdle",!1);ht(this,"_isBuilding",!1);ht(this,"callbacks");this.callbacks=t}get isIdle(){return this._isIdle}get isBuilding(){return this._isBuilding}handleClaudeIdle(t,r,s){console.log("[TerminalIdleHandler] claude-idle, building: %s → false",this._isBuilding),t==null||t.onIdle(r,s),this._isIdle=!0,this._isBuilding=!1,this.callbacks.onIdleChange(!0),this.callbacks.onBuildingChange(!1)}handleClaudeActive(t){console.log("[TerminalIdleHandler] claude-active, building: %s → true",this._isBuilding),this._isIdle=!1,this._isBuilding=!0,this.callbacks.onIdleChange(!1),this.callbacks.onBuildingChange(!0),t==null||t.onActive(),t==null||t.resetActivityFlag(),this.callbacks.onCloseNotification()}handleOutput(t){this.callbacks.onIdleChange(!1),t==null||t.resetActivityFlag()}reset(){this._isBuilding&&(console.log("[TerminalIdleHandler] reset, was building: true"),this._isBuilding=!1,this.callbacks.onBuildingChange(!1))}}const J0=`
96
- .xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
97
- .xterm.focus, .xterm:focus { outline: none; }
98
- .xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
99
- .xterm .xterm-helper-textarea { padding: 0; border: 0; margin: 0; position: absolute; opacity: 0; left: -9999em; top: 0; width: 0; height: 0; z-index: -5; white-space: nowrap; overflow: hidden; resize: none; caret-color: transparent !important; clip-path: inset(100%) !important; }
100
- .xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
101
- .xterm .composition-view.active { display: block; }
102
- .xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
103
- .xterm .xterm-screen { position: relative; }
104
- .xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
105
- .xterm .xterm-scroll-area { visibility: hidden; }
106
- .xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
107
- .xterm.enable-mouse-events { cursor: default; }
108
- .xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
109
- .xterm.column-select.focus { cursor: crosshair; }
110
- .xterm .xterm-accessibility:not(.debug), .xterm .xterm-message { position: absolute; left: 0; top: 0; bottom: 0; right: 0; z-index: 10; color: transparent; pointer-events: none; }
111
- .xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
112
- .xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
113
- .xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
114
- .xterm-dim { opacity: 1 !important; }
115
- .xterm-underline-1 { text-decoration: underline; }
116
- .xterm-underline-2 { text-decoration: double underline; }
117
- .xterm-underline-3 { text-decoration: wavy underline; }
118
- .xterm-underline-4 { text-decoration: dotted underline; }
119
- .xterm-underline-5 { text-decoration: dashed underline; }
120
- .xterm-overline { text-decoration: overline; }
121
- .xterm-strikethrough { text-decoration: line-through; }
122
- .xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
123
- .xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
124
- .xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
125
- .xterm-decoration-top { z-index: 2; position: relative; }
126
- `;function H0(){let e=document.getElementById("xterm-css");e||(e=document.createElement("style"),e.id="xterm-css",document.head.appendChild(e)),e.textContent=J0}const Vd=ph(function({entityName:t,entityType:r,entitySha:s,entityFilePath:a,scenarioName:o,scenarioDescription:i,analysisId:l,projectSlug:c,onRefreshPreview:p,onShowResults:u,onHideResults:h,onSetViewport:m,editorMode:f,onIdleChange:y,onBuildingChange:g,notificationSettings:x,buildTabActive:b,claudeStartMode:v,claudeSessionId:N,onFeatureComplete:w,onDataMutationForwarded:C,resultsOpen:S,editorStepLabel:k},j){const _=ye(null),F=ye(null),M=ye(null),$=ye(null),O=ye(null),D=ye(!1),T=ye(0),B=ye(!1),Y=ye(y);Y.current=y;const I=ye(g);I.current=g;const L=ye(x);L.current=x;const P=ye(b);P.current=b;const R=ye(S);R.current=S;const E=ye(null),J=ye(!1),K=ye(null);K.current||(K.current=new W0({playSound:W=>Jd(W),showSystemNotification:()=>{E.current&&E.current.close();const W=new Notification("Claude is ready for you",{body:"Claude has finished and is waiting for your input.",tag:"claude-idle"});W.onclick=()=>{window.focus(),W.close()},E.current=W}},{hasBrowserFocus:()=>document.hasFocus(),hasNotificationPermission:()=>typeof Notification<"u"&&Notification.permission==="granted"}));const Q=ye(null);Q.current||(Q.current=new U0({onIdleChange:W=>{var V;J.current=W,(V=Y.current)==null||V.call(Y,W)},onCloseNotification:()=>{E.current&&(E.current.close(),E.current=null)},onBuildingChange:W=>{var V;(V=I.current)==null||V.call(I,W)}}));function q(){E.current&&(E.current.close(),E.current=null)}function U(){var W,V;J.current&&(J.current=!1,q(),(W=Y.current)==null||W.call(Y,!1),(V=K.current)==null||V.onUserEngagement())}ne(()=>{function W(){var xe;document.hasFocus()&&P.current&&U(),P.current&&document.hasFocus()&&((xe=K.current)==null||xe.reportUserActivity())}function V(){!document.hidden&&P.current&&U()}function ae(){var xe;document.hasFocus()&&P.current&&U(),P.current&&document.hasFocus()&&((xe=K.current)==null||xe.reportUserActivity())}function pe(){var xe;P.current&&U(),P.current&&((xe=K.current)==null||xe.reportUserActivity())}return window.addEventListener("focus",pe),document.addEventListener("visibilitychange",V),document.addEventListener("mousemove",W),document.addEventListener("mousedown",ae),document.addEventListener("keydown",W),()=>{window.removeEventListener("focus",pe),document.removeEventListener("visibilitychange",V),document.removeEventListener("mousemove",W),document.removeEventListener("mousedown",ae),document.removeEventListener("keydown",W)}},[]),ne(()=>{var W;b&&J.current&&document.hasFocus()&&U(),(W=K.current)==null||W.onBuildTabChange(!!b,L.current)},[b]);const z=oe(()=>{var W;(W=M.current)==null||W.focus()},[]);return hh(j,()=>({sendInput(W){const V=$.current;V&&V.readyState===WebSocket.OPEN&&(V.send(JSON.stringify({type:"input",data:W})),setTimeout(()=>{V.readyState===WebSocket.OPEN&&V.send(JSON.stringify({type:"input",data:"\r"}))},100))},focus(){var W;(W=M.current)==null||W.focus()},scrollToBottom(){var V;const W=(V=_.current)==null?void 0:V.querySelector(".xterm-viewport");W&&(W.scrollTop=W.scrollHeight)}})),ne(()=>{const W=_.current;if(!W)return;let V=!1;return H0(),Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit"),import("@xterm/addon-web-links")]).then(([ae,pe,xe])=>{if(V)return;const ie=new ae.Terminal({cursorBlink:!1,cursorInactiveStyle:"none",scrollback:5e3,fontSize:13,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#1e1e1e",selectionBackground:"#264f78"},linkHandler:{activate(se,ce){try{const je=new URL(ce),ge=je.searchParams.get("scenario");if(ge&&je.pathname.startsWith("/editor")){const ze=new BroadcastChannel("codeyam-editor");ze.postMessage({type:"switch-scenario",scenarioId:ge}),ze.close();return}}catch{}window.open(ce,"_blank")}}}),me=new pe.FitAddon;ie.loadAddon(me),ie.loadAddon(new xe.WebLinksAddon),ie.open(W),ie.attachCustomKeyEventHandler(se=>{if(R.current&&(se.key==="ArrowLeft"||se.key==="ArrowRight")&&!se.ctrlKey&&!se.altKey&&!se.metaKey&&se.type==="keydown"){const ce=se.key==="ArrowLeft"?"\x1B[D":"\x1B[C",je=$.current;return je&&je.readyState===WebSocket.OPEN&&je.send(JSON.stringify({type:"input",data:ce})),!1}return!0}),ie.write("\x1B[?25l");let we=null;Y0(ie,(se,ce,je)=>{console.warn(`[Terminal] Renderer fallback: ${se} → ${ce}`,je)}).then(se=>{if(V){se.dispose();return}console.log(`[Terminal] Using ${se.type} renderer`),we=se.dispose}),requestAnimationFrame(()=>{try{me.fit()}catch{}}),M.current=ie,ie.focus(),setTimeout(()=>ie.focus(),100),setTimeout(()=>ie.focus(),500);const Te=window.location.protocol==="https:"?"wss:":"ws:",Ne=window.location.host;function _e(se){const ce=new URLSearchParams;return ce.set("entityName",t),r&&ce.set("entityType",r),s&&ce.set("entitySha",s),a&&ce.set("entityFilePath",a),o&&ce.set("scenarioName",o),i&&ce.set("scenarioDescription",i),l&&ce.set("analysisId",l),c&&ce.set("projectSlug",c),f&&ce.set("editorMode","true"),se&&ce.set("reconnectId",se),v&&ce.set("claudeStartMode",v),N&&ce.set("claudeSessionId",N),k&&ce.set("editorStepLabel",k),`${Te}//${Ne}/ws/terminal?${ce.toString()}`}function Z(se){const ce=_e(se),je=new WebSocket(ce);$.current=je,je.onopen=()=>{T.current=0,B.current=!1,je.send(JSON.stringify({type:"resize",cols:ie.cols,rows:ie.rows}))},je.onmessage=ge=>{var ze,Ve,it;try{const Le=JSON.parse(ge.data);if(Le.type==="session-id"){O.current=Le.sessionId;return}if(Le.type==="refresh-preview"){p==null||p(Le.path,Le.scenarioId);return}if(Le.type==="show-results"){u==null||u();return}if(Le.type==="hide-results"){h==null||h();return}if(Le.type==="feature-complete"){w==null||w();return}if(Le.type==="data-mutation-forwarded"){C==null||C();return}if(Le.type==="set-viewport"){m==null||m({name:Le.name,width:Le.width,height:Le.height});return}if(Le.type==="claude-idle"){(ze=Q.current)==null||ze.handleClaudeIdle(K.current,L.current,P.current??!1);return}if(Le.type==="claude-active"){(Ve=Q.current)==null||Ve.handleClaudeActive(K.current);return}Le.type==="output"&&(ie.write(Le.data),(it=Q.current)==null||it.handleOutput(K.current))}catch{ie.write(ge.data)}},je.onclose=()=>{var ze,Ve;if(console.log("[Terminal] WS closed, intentional=%s",D.current),D.current){ie.write(`\r
127
- \x1B[90m[Terminal session ended]\x1B[0m\r
128
- `),(ze=Q.current)==null||ze.reset();return}const ge=T.current;if(ge<5&&O.current){const it=1e3*Math.pow(2,Math.min(ge,3));T.current=ge+1,ie.write(`\r
129
- \x1B[33m[Reconnecting...]\x1B[0m\r
130
- `),setTimeout(()=>{D.current||Z(O.current)},it)}else B.current?(ie.write(`\r
131
- \x1B[90m[Terminal session ended]\x1B[0m\r
132
- `),(Ve=Q.current)==null||Ve.reset()):(B.current=!0,ie.write(`\r
133
- \x1B[33m[Starting new session...]\x1B[0m\r
134
- `),O.current=null,T.current=0,Z())},je.onerror=()=>{}}Z(),ie.onData(se=>{const ce=$.current;ce&&ce.readyState===WebSocket.OPEN&&ce.send(JSON.stringify({type:"input",data:se})),U()});let he=null;const te=new ResizeObserver(()=>{he&&clearTimeout(he),he=setTimeout(()=>{let se;try{se=me.proposeDimensions()}catch{return}if(!se||se.cols===ie.cols&&se.rows===ie.rows)return;const ce=W.querySelector(".xterm-viewport");let je,ge=!0;ce&&(je=ce.scrollTop,ge=ce.scrollTop+ce.clientHeight>=ce.scrollHeight-10),me.fit(),ce&&je!==void 0&&(ge?ce.scrollTop=ce.scrollHeight:ce.scrollTop=je);const ze=$.current;ze&&ze.readyState===WebSocket.OPEN&&ze.send(JSON.stringify({type:"resize",cols:ie.cols,rows:ie.rows}))},150)});te.observe(W),F.current=()=>{var se;he&&clearTimeout(he),te.disconnect(),D.current=!0,(se=$.current)==null||se.close(),$.current=null,we==null||we(),ie.dispose(),M.current=null}}),()=>{var ae;V=!0,(ae=F.current)==null||ae.call(F),F.current=null}},[]),n("div",{ref:_,onClick:z,className:"w-full h-full relative overflow-hidden",style:{padding:"4px 0 0 8px"}})});function dt({screenshotPath:e,cacheBuster:t,alt:r,className:s="",title:a}){const[o,i]=A("loading"),[l,c]=A(!1),p=ye(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,h=()=>{i("success"),c(!0)},m=()=>{i("error"),c(!1)};return ne(()=>{i("loading"),c(!1);const f=p.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),c(!0)):(i("error"),c(!1)))},[u]),e?d("div",{className:"relative w-full h-full flex items-center justify-center",title:a,children:[n("img",{ref:p,src:u,alt:r,onLoad:h,onError:m,className:s||"max-w-full max-h-full object-contain",style:{visibility:l?"visible":"hidden",position:l?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&d("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:a,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}function V0({scenarios:e,currentScenarioId:t,entitySha:r,cacheBuster:s}){const a=Dt();return e.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8",children:n("p",{className:"text-gray-500 text-sm",children:"No scenarios found"})}):n("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:e.map(o=>{var c,p;const i=o.id===t,l=(p=(c=o.metadata)==null?void 0:c.screenshotPaths)==null?void 0:p[0];return d("button",{onClick:()=>{a(`/entity/${r}/scenarios/${o.id}/dev`)},className:`w-full text-left rounded-lg overflow-hidden border transition-colors cursor-pointer flex ${i?"border-[#005c75] bg-[#1a3a44]":"border-[#3d3d3d] bg-[#252525] hover:border-[#555]"}`,children:[n("div",{className:"w-24 h-20 shrink-0 bg-[#1a1a1a]",children:n(dt,{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 jt(e){var l;if(!e.startsWith("app/")&&!e.startsWith("("))return"/";const r=e.replace(/^app\//,"").split("/"),s=r.pop(),a=((l=s.match(/\.(tsx?|jsx?|js)$/))==null?void 0:l[0])||"",o=s.slice(0,-a.length);let i;return o==="page"||o==="index"?i=r:i=[...r,o],i=i.filter(c=>!c.startsWith("(")),i.length===0?"/":"/"+i.join("/")}function Lt(e){return e==="/"?"Home":e.replace(/^\//,"").split("/").map(r=>r.startsWith("[")?r:r.charAt(0).toUpperCase()+r.slice(1)).join(" / ")}function Kd(e,t){if(!e)return null;const r=e.split("?")[0].replace(/\/+$/,"")||"/",s=t.map(l=>({filePath:l,pattern:jt(l)})),a=r==="/"?[]:r.replace(/^\//,"").split("/");let o=null,i=-1;for(const l of s){const c=l.pattern==="/"?[]:l.pattern.replace(/^\//,"").split("/");if(c.length!==a.length)continue;let p=!0,u=0;for(let h=0;h<c.length;h++){const m=c[h],f=a[h];if(!(m.startsWith("[")&&m.endsWith("]")))if(m===f)u++;else{p=!1;break}}p&&u>i&&(i=u,o=l.filePath)}return o}function Gd(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 yt(e){if(!e||e==="/")return"Home";const t=e.split("?")[0].replace(/^\//,"");if(!t)return"Home";const r=t.split("/")[0].replace(/\.[^.]+$/,"");return r.charAt(0).toUpperCase()+r.slice(1)}function ma(e){return e?e.includes("/isolated-components")||e.includes("/codeyam-isolate"):!1}function Gt(e){return e.componentName?e.componentName:e.pageFilePath?Lt(jt(e.pageFilePath)):yt(e.url)}function qd(e,t,r){var o;const s=[],a=new Set;for(const i of e){let l=null,c=null;if(i.componentName&&i.componentPath)l=i.componentName,c=i.componentPath;else if(!i.componentName&&i.pageFilePath)l=i.displayName||(i.pageFilePath.startsWith("app/")?Lt(jt(i.pageFilePath)):yt(i.url)),c=i.pageFilePath;else if(!i.componentName&&i.url!==void 0){const p=yt(i.url);t[p]&&(l=p,c=t[p])}if(l&&c&&!a.has(l)){a.add(l);const p=r.find(u=>u.name===l)||(c?r.find(u=>u.filePath===c):void 0);s.push({name:l,filePath:c,importedBy:(o=p==null?void 0:p.metadata)==null?void 0:o.importedBy})}}return s}function K0(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 G0(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>t[r.name])}function q0(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>{if("componentName"in r){const a=Gt(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 Q0(e){const t=new Set,r=new Map;for(const a of e)t.add(a.name),a.filePath&&r.set(a.filePath,a.name);const s=new Map;for(const a of e){const o=a.importedBy;if(!o||typeof o!="object")continue;const i=new Set;for(const l of Object.keys(o))for(const c of Object.keys(o[l]))if(t.has(c))i.add(c);else{const p=r.get(l);p&&p!==a.name?i.add(p):i.add(c)}i.size>0&&s.set(a.name,i)}return s}function Z0(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 X0=20;function Qd(e,t,r=X0){const s={};if(t.length===0||e.size===0)return s;const a=new Map;for(const p of t)a.set(p.name,p);const o=Q0(t),i=Z0(e,t);for(const[p,u]of i)s[p]={status:u};const l=new Map;for(const[p]of i)l.set(p,new Set([p]));const c=[];for(const[p]of i)c.push({name:p,depth:0});for(;c.length>0;){const{name:p,depth:u}=c.shift();if(u>=r)continue;const h=l.get(p)||new Set,m=o.get(p);if(m)for(const f of m){if(!a.has(f))continue;l.has(f)||l.set(f,new Set);const y=l.get(f);let g=!1;for(const x of h)y.has(x)||(y.add(x),g=!0);g&&c.push({name:f,depth:u+1})}}for(const[p,u]of l){if(i.has(p))continue;const h=[];for(const m of u){const f=a.get(m),y=i.get(m);f&&y&&h.push({name:m,filePath:f.filePath,changeType:y})}h.sort((m,f)=>m.name.localeCompare(f.name)),s[p]={status:"impacted",impactedBy:h.length>0?h:void 0}}return s}function fa(e){if(Array.isArray(e))return e;if(e&&typeof e=="object"){const t=e;for(const s of["components","entries","functions","glossary"]){const a=t[s];if(Array.isArray(a))return a}for(const s of Object.values(t))if(Array.isArray(s))return s;const r=Object.entries(t);if(r.length>0&&r.every(([,s])=>s&&typeof s=="object"&&!Array.isArray(s)))return r.map(([s,a])=>({...a,filePath:s}))}return[]}function ey(e){return fa(e).filter(r=>r.testFile&&r.returnType!=="JSX.Element"&&r.returnType!=="React.ReactNode").map(r=>({name:r.name,filePath:r.filePath,description:r.description||"",testFile:r.testFile,feature:r.feature}))}function Rl(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 ty(e,t){return e.filter(r=>r.analyses&&r.analyses.length>0).map(r=>{var h;const s=r.analyses[0],a=s.scenarios||[],o=!((h=s.status)!=null&&h.finishedAt),i=r.entityType||"visual",l=i==="library"||i==="functionCall",c=a.filter(m=>Rl(m,l)),p=a.filter(m=>!Rl(m,l)),u=t.find(m=>m.filePath===(r.filePath||""));return{sha:r.sha,name:r.name,entityType:i,filePath:r.filePath||"",analysisId:s.id,isAnalyzing:o,scenarioCount:a.length,scenarios:c.map(m=>{var f,y;return{id:m.id,name:m.name,description:m.description||"",screenshotPath:((y=(f=m.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||null}}),pendingScenarios:p.map(m=>m.name),testFile:u==null?void 0:u.testFile}})}function ny(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 ry(e,t,r){const s={...e},a=new Map;for(const o of r)o.filePath&&a.set(o.filePath,o.name);for(const[o,i]of Object.entries(t)){if(s[o])continue;const l=a.get(i);l&&s[l]&&(s[o]=s[l])}return s}function _t(e,t){const r=new Map;for(const s of e)r.set(t(s),s);return[...r.values()]}function Mt(e){return e.replace(/[^a-zA-Z0-9_]+/g,"_")}function Zd(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Qr(e){return e.replace("T"," ").replace(/\.\d{3}Z$/,"")}function ci(e,t){return!!(e.created_at&&e.created_at>=t||e.updated_at&&e.updated_at>=t)}const sy=["defaultScreenSize","screenSizes","projectTitle","projectDescription","appFormats"];function B_(e){try{const t=JSON.parse(ue.readFileSync(e,"utf8")),r={};for(const s of sy)t[s]!==void 0&&(r[s]=t[s]);return r}catch{return{}}}function ay(e){const t=ee.join(e,".codeyam","editor-step.json");try{ue.unlinkSync(t)}catch{}}function di(e,t,r){const s=e&&e.startsWith("/");return s&&t?`${t}${e}`:e&&!s?e:t||r||null}function oy(e){var t,r;try{const s=ee.join(e,".codeyam","config.json"),a=JSON.parse(ue.readFileSync(s,"utf8"));if(a.screenSizes&&typeof a.screenSizes=="object")for(const o of Object.values(a.screenSizes)){const i=o;if(i.default&&i.width&&i.height)return{width:i.width,height:i.height}}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 ui(e){try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(ue.readFileSync(t,"utf8"));if(r.screenSizes&&typeof r.screenSizes=="object"&&!Array.isArray(r.screenSizes))return r.screenSizes}catch{}return{}}function iy(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 ga(e){let t=null;if(e.dimension){const a=ui(e.codeyamRoot)[e.dimension];a!=null&&a.width&&(a!=null&&a.height)&&(t={width:a.width,height:a.height})}const r=t||oy(e.codeyamRoot);return iy({bodyWidth:e.bodyWidth,bodyHeight:e.bodyHeight,projectDefault:r})}async function ly(e,t){const r=t.dimensions?JSON.stringify(t.dimensions):null,s=t.screenshotPaths?JSON.stringify(t.screenshotPaths):null,a=await e.selectFrom("editor_scenarios").selectAll().where("name","=",t.name).where("project_id","=",t.projectId).orderBy("created_at","desc").execute();if(a.length>0){const c=a[0].id,p={description:t.description,component_name:t.componentName,component_path:t.componentPath,url:t.url,type:t.type,viewport_width:t.viewportWidth,viewport_height:t.viewportHeight,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")};t.dimensions!==void 0&&(p.dimensions=r,p.screenshot_paths=s),t.pageFilePath!==void 0&&(p.page_file_path=t.pageFilePath),t.entitySha!==void 0&&(p.entity_sha=t.entitySha),t.displayName!==void 0&&(p.display_name=t.displayName),await e.updateTable("editor_scenarios").set(p).where("id","=",c).execute();const u=a.slice(1).map(h=>h.id);return u.length>0&&await e.deleteFrom("editor_scenarios").where("id","in",u).execute(),{scenarioId:c,isNew:!1,cleanedUpIds:u}}const o=globalThis.crypto.randomUUID(),i={id:o,project_id:t.projectId,name:t.name,description:t.description,component_name:t.componentName,component_path:t.componentPath,url:t.url,type:t.type,viewport_width:t.viewportWidth,viewport_height:t.viewportHeight};return t.dimensions!==void 0&&(i.dimensions=r,i.screenshot_paths=s),t.pageFilePath!==void 0&&(i.page_file_path=t.pageFilePath),t.entitySha!==void 0&&(i.entity_sha=t.entitySha),t.displayName!==void 0&&(i.display_name=t.displayName),await e.insertInto("editor_scenarios").values(i).execute(),{scenarioId:o,isNew:!0,cleanedUpIds:[]}}function cy(e,t){const r=ee.join(e,".codeyam","editor-scenarios"),s=ee.join(r,"screenshots");for(const a of t){for(const o of[`${a}.json`,`${a}.seed.json`,ee.join("screenshots",`${a}.png`)])try{ue.unlinkSync(ee.join(r,o))}catch{}try{const o=ue.readdirSync(s);for(const i of o)if(i.startsWith(`${a}--`)&&i.endsWith(".png"))try{ue.unlinkSync(ee.join(s,i))}catch{}}catch{}}}function dy(e){const{lookupFilePath:t,scenarioType:r,projectRoot:s}=e;if(r!=="application"&&r!=="user")return{valid:!0};if(!t)return{valid:!0};const a=ee.join(s,".codeyam","glossary.json");let o=[];try{const l=JSON.parse(ue.readFileSync(a,"utf8"));o=fa(l)}catch{}if(!o.some(l=>l.filePath===t)){const l=o.length===0?` glossary.json is empty or could not be parsed. It must be a JSON array: [{"name": "...", "filePath": "${t}", ...}]`:` Found ${o.length} entries but none with filePath "${t}".`;return{valid:!1,error:`No glossary entry found for '${t}'.${l} Add this file to .codeyam/glossary.json before registering app scenarios.`}}return{valid:!0,needsAnalysis:!0}}function uy(e){const{componentName:t,url:r}=e;return!t||!r?{valid:!0}:ma(r)?{valid:!0}:{valid:!1,error:`Scenario has componentName "${t}" but URL "${r}" is not an isolation route. Component scenarios must use an isolation URL like /isolated-components/${t}?s=ScenarioName or /codeyam-isolate/${t}?s=ScenarioName. Either change the URL to an isolation route, or remove componentName to register as an application scenario.`}}const py=Xd;async function Xd(e,t){const r=new Map,s=new Map;for(const i of t)if(i.filePath){r.set(`${i.name}::${i.filePath}`,i);const l=s.get(i.filePath);(!l||!l.isDefaultExport||i.isDefaultExport)&&s.set(i.filePath,i)}const a=await e.selectFrom("editor_scenarios").selectAll().where(i=>i.or([i("component_path","is not",null),i("page_file_path","is not",null)])).execute();if(a.length===0)return{updated:0};let o=0;for(const i of a){const l=i,c=l.component_path||l.page_file_path;if(!c)continue;const p=l.component_name&&r.get(`${l.component_name}::${c}`)||s.get(c);if(!p||l.entity_sha===p.sha)continue;let u=null;l.component_name?u=l.component_name:l.page_file_path&&l.page_file_path.startsWith("app/")?u=Lt(jt(l.page_file_path)):l.url&&(u=yt(l.url)),await e.updateTable("editor_scenarios").set({entity_sha:p.sha,...u?{display_name:u}:{}}).where("id","=",l.id).execute(),o++}return{updated:o}}async function Ol(e,t,r){const s=ee.join(e,".codeyam","editor-scenarios"),a=i=>{const l=ee.join(s,`${i}.seed.json`);if(ue.existsSync(l))try{return JSON.parse(ue.readFileSync(l,"utf-8"))}catch{return null}const c=ee.join(s,`${i}.json`);if(ue.existsSync(c))try{return JSON.parse(ue.readFileSync(c,"utf-8")).seed||null}catch{return null}return null},o=a(r);if(o)return o;try{const i=await t.selectFrom("editor_scenarios").select("id").where("name","=",r).orderBy("created_at","desc").limit(1).executeTakeFirst();if(i)return a(i.id)}catch{}return null}function hy(e){const{activeAnalyzedScenario:t,analyzedPreviewUrl:r,activeScenarioId:s,scenarios:a,proxyUrl:o,devServerUrl:i,zoomComponent:l}=e;if(t&&r)return r;if(t&&!r)return null;if(s){const p=a.find(u=>u.id===s);if(p!=null&&p.url){const u=o||i;return u?p.url.startsWith("/")?`${u}${p.url}`:p.url:null}}const c=o||i;if(!c)return null;if(l&&s){const p=a.find(h=>h.id===s),u=p?Mt(p.name):"Default";return`${c}/__codeyam__/${l}/${u}`}return c}function eu(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 my(e,t){return e?e!==t:!1}function ys(e){if(e.length!==0)return e.find(t=>t.url==="/")||e.find(t=>t.type==="application")||e[0]}function to(e,t,r){if(!e.viewportWidth||!e.viewportHeight)return r??null;const s=t.find(a=>a.width===e.viewportWidth&&a.height===e.viewportHeight);return{name:(s==null?void 0:s.name)||"Custom",width:e.viewportWidth,height:e.viewportHeight}}function Ll(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 fy({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw re("Invalid parameters",{status:400});const s=await Pn(t);if(!s)throw re("Entity not found",{status:404});const a=await oa(s),o=((l=a==null?void 0:a.scenarios)==null?void 0:l.find(c=>c.id===r))||null;if(!o)throw re("Scenario not found",{status:404});const i=await Ye();return re({entity:s,scenario:o,analysis:a,projectSlug:i})}const no=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],gy=et(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=ot(),o=Dt(),i=ye(null),l=ye(null),[c,p]=A(null),[u,h]=A(1440),[m,f]=A({name:"Desktop",width:1440,height:900}),[y,g]=A(!1),[x,b]=A(null),[v,N]=A("chat"),[w,C]=A(0),[S,k]=A(null),j=oe(ie=>{k(ie||null),C(me=>me+1)},[]),{customSizes:_,addCustomSize:F}=ha(a),M=le(()=>[...no,..._],[_]),{interactiveServerUrl:$,isStarting:O,isLoading:D,showIframe:T,iframeKey:B,onIframeLoad:Y}=In({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0,refreshTrigger:w}),I=le(()=>eu($,S),[$,S]),{lastLine:L}=Jt(a,O||D),P=()=>{o(`/entity/${t.sha}`)},R=(ie,me)=>{h(ie);const we=M.find(Ne=>Ne.width===ie&&Ne.height===me);p(we||null),f({name:(we==null?void 0:we.name)||"Custom",width:ie,height:me})},E=ie=>{p(ie),h(ie.width),f({name:ie.name,width:ie.width,height:ie.height})},J=ie=>{F(ie,m.width,m.height??900),g(!1),f(me=>({...me,name:ie}))},K=()=>{var me;N("chat"),(me=l.current)==null||me.sendInput("Create a new scenario for this entity based on the work we've just done. Create a name and description that reflects what the live preview is showing. Use the scenario data you've changed to create a new scenario in the database. If the data structure was fixed in any way you need to update that in the database as well and backfill all existing scenarios, then save to the database and capture a screenshot. Remember the database is at `.codeyam/db.sqlite3`, the scenarios table has all scenarios and the analyses table contains the scenariosDataStructure is its metadata.")},Q=((s==null?void 0:s.scenarios)||[]).filter(ie=>{var me;return!((me=ie.metadata)!=null&&me.sameAsDefault)}),q=Q.findIndex(ie=>ie.id===(r==null?void 0:r.id)),U=q+1,z=Q.length,W=q>0,V=q<Q.length-1,ae=()=>{if(W){const ie=Q[q-1];o(`/entity/${t.sha}/scenarios/${ie.id}/dev`)}},pe=()=>{if(V){const ie=Q[q+1];o(`/entity/${t.sha}/scenarios/${ie.id}/dev`)}},xe=O||D||!T;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:na,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:ae,disabled:!W,className:`${W?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),d("span",{className:"text-gray-400 text-sm",children:[U,"/",z]}),n("button",{onClick:pe,disabled:!V,className:`${V?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),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:P,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:`${no[no.length-1].width}px`,width:"100%"},children:n(ii,{currentViewportWidth:u,currentPresetName:m.name,onDevicePresetClick:E,devicePresets:M,hideLabel:!0,onHoverChange:b,lightMode:!0})})}),d("div",{className:"relative z-10 flex items-center gap-2",children:[d("div",{className:"relative w-28 h-5",children:[d("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(x==null?void 0:x.name)||m.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),d("select",{value:m.name,onChange:ie=>{const me=M.find(we=>we.name===ie.target.value);me&&E(me)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[M.map(ie=>n("option",{value:ie.name,children:ie.name},ie.name)),m.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:m.width,onChange:ie=>{const me=parseInt(ie.target.value,10);!isNaN(me)&&me>0&&R(me,m.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"x"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:m.height??900}),m.name==="Custom"&&n("button",{onClick:()=>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:`
135
- linear-gradient(45deg, #ebebeb 25%, transparent 25%),
136
- linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
137
- linear-gradient(45deg, transparent 75%, #ebebeb 75%),
138
- linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
139
- `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:$?d("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${m.width}px`,maxHeight:`${m.height}px`},children:[xe&&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(Ut,{})}),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"}),L&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(ar,{}),L]})]})]})}),n("iframe",{ref:i,src:I||$,className:"w-full h-full border-none",title:`Dev mode preview: ${r==null?void 0:r.name}`,onLoad:Y,style:{opacity:T?1:0}},B)]}):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(Ut,{})}),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"}),L&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(ar,{}),L]})]})]})})]}),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:()=>N("chat"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${v==="chat"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Chat",v==="chat"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),d("button",{onClick:()=>N("scenarios"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${v==="scenarios"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Scenarios",v==="scenarios"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]})]}),v==="chat"&&n("button",{onClick:K,disabled:!$,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:v==="chat"?"flex":"none"},className:"flex-1 overflow-hidden flex-col",children:n(Vd,{ref:l,entityName:t.name,entityType:t.entityType,entitySha:t.sha,entityFilePath:t.filePath||t.localFilePath,scenarioName:r==null?void 0:r.name,scenarioDescription:r==null?void 0:r.description,analysisId:s==null?void 0:s.id,projectSlug:a,onRefreshPreview:j})}),v==="scenarios"&&n(V0,{scenarios:Q,currentScenarioId:r==null?void 0:r.id,entitySha:t.sha,cacheBuster:0})]})]}),n(Hd,{serverUrl:$,isStarting:O,projectSlug:a}),y&&n(li,{width:m.width,height:m.height??900,onSave:J,onCancel:()=>g(!1)})]})}),yy=Object.freeze(Object.defineProperty({__proto__:null,default:gy,loader:fy},Symbol.toStringTag,{value:"Module"})),tu=3e4,xy="seed-session.json";function by(e){const t={};try{const r=G.readFileSync(e,"utf-8");for(const s of r.split(`
140
- `)){const a=s.trim();if(!a||a.startsWith("#"))continue;const o=a.indexOf("=");if(o===-1)continue;const i=a.slice(0,o).trim();let l=a.slice(o+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),i&&(t[i]=l)}}catch{}return t}function nu(e){const t=[".env",".env.local",".env.development",".env.development.local"];let r={};for(const s of t){const a=by(H.join(e,s));r={...r,...a}}return r}function ru(e){const t={};try{const r=H.join(e,".codeyam","config.json"),s=JSON.parse(G.readFileSync(r,"utf-8"));for(const a of s.environmentVariables||[]){const o=a.key||a.name;o&&a.value!==void 0&&(t[o]=a.value)}}catch{}return t}function vy(e){const t=H.join(e,".codeyam","tmp",xy);try{if(!G.existsSync(t))return{};const r=G.readFileSync(t,"utf-8"),s=JSON.parse(r);G.unlinkSync(t);const a={};return s.cookies&&Array.isArray(s.cookies)&&(a.sessionCookies=s.cookies),s.externalApis&&typeof s.externalApis=="object"&&(a.externalApis=s.externalApis),a}catch{return{}}}function pi(e,t,r){const s=tu,a=H.basename(H.dirname(e))===".codeyam"?H.dirname(H.dirname(e)):H.dirname(e);return new Promise(o=>{const i=Date.now(),l=e.endsWith(".ts");let c,p;if(l){const b=Ny(a);b?(c=b,p=[e,t]):(c="npx",p=["tsx",e,t])}else c=e,p=[t];const u=nu(a),h=ru(a),m=xt(c,p,{cwd:a,env:{...process.env,...u,...h}});let f="",y="",g=!1;const x=setTimeout(()=>{g=!0,m.kill("SIGTERM")},s);m.stdout.on("data",b=>{f+=b.toString()}),m.stderr.on("data",b=>{y+=b.toString()}),m.on("close",b=>{clearTimeout(x);const v=Date.now()-i;if(g)o({success:!1,output:f,error:`Seed adapter timeout after ${s}ms`,durationMs:v});else if(b===0){const N=vy(a);o({success:!0,output:f,durationMs:v,sessionCookies:N.sessionCookies,externalApis:N.externalApis})}else o({success:!1,output:f,error:y||`Seed adapter exited with code ${b}`,durationMs:v})}),m.on("error",b=>{clearTimeout(x),o({success:!1,output:"",error:b.message,durationMs:Date.now()-i})})})}function wy(e,t,r){const s=tu,a=H.basename(H.dirname(e))===".codeyam"?H.dirname(H.dirname(e)):H.dirname(e);return new Promise(o=>{const i=Date.now(),l=e.endsWith(".ts"),c=l?"npx":e,p=l?["tsx",e,"--export",t]:["--export",t],u=nu(a),h=ru(a),m=xt(c,p,{cwd:a,env:{...process.env,...u,...h}});let f="",y="",g=!1;const x=setTimeout(()=>{g=!0,m.kill("SIGTERM")},s);m.stdout.on("data",b=>{f+=b.toString()}),m.stderr.on("data",b=>{y+=b.toString()}),m.on("close",b=>{clearTimeout(x);const v=Date.now()-i;o(g?{success:!1,output:f,error:`Seed adapter export timeout after ${s}ms`,durationMs:v}:b===0?{success:!0,output:f,durationMs:v}:{success:!1,output:f,error:y||`Seed adapter export exited with code ${b}`,durationMs:v})}),m.on("error",b=>{clearTimeout(x),o({success:!1,output:"",error:b.message,durationMs:Date.now()-i})})})}function Yr(e){const t=["seed-adapter.ts","seed-adapter.js"];for(const r of t){const s=H.join(e,".codeyam",r);try{return G.accessSync(s),s}catch{}}return null}function Ny(e){const t=[H.join(e,"node_modules",".bin","tsx"),H.join(e,"..","node_modules",".bin","tsx")];for(const r of t)try{return G.accessSync(r,G.constants.X_OK),r}catch{}return null}function zl(e,t){const r={};for(const[s,a]of Object.entries(e))r[s]=JSON.parse(JSON.stringify(a));for(const[s,a]of Object.entries(t))r[s]=JSON.parse(JSON.stringify(a));return r}let vn=null;async function ya(e){const{scenarioId:t,projectRoot:r}=e,s=ee.join(r,".codeyam"),a=ee.join(s,"editor-scenarios");let o=e.scenarioSlug||null;if(!o)try{const m=ee.join(a,`${t}.json`);ue.existsSync(m)?o=JSON.parse(ue.readFileSync(m,"utf-8")).name||t:o=t}catch{o=t}let i=e.scenarioType||null;if(!i)try{const m=ee.join(a,`${t}.json`);ue.existsSync(m)&&(i=JSON.parse(ue.readFileSync(m,"utf-8")).type||null)}catch{}const l=ee.join(s,"active-scenario.json");ue.mkdirSync(s,{recursive:!0}),ue.writeFileSync(l,JSON.stringify({scenarioSlug:o,scenarioName:e.scenarioName||o,scenarioId:t,type:i,dataFile:`.codeyam/editor-scenarios/${t}.json`,switchedAt:new Date().toISOString()},null,2));let c=null,p,u;const h=i==="application"||i==="user";if(h)if(vn&&vn.scenarioId===t)c=await vn.promise;else{const m=Yr(r),f=ee.join(a,`${t}.seed.json`);if(m&&ue.existsSync(f)){const y=pi(m,f).then(g=>({success:g.success,error:g.error,sessionCookies:g.sessionCookies,externalApis:g.externalApis}));vn={scenarioId:t,promise:y};try{const g=await y;c={success:g.success,error:g.error},p=g.sessionCookies,u=g.externalApis}finally{vn&&vn.scenarioId===t&&(vn=null)}if(c!=null&&c.success){const g=p&&p.length>0,x=u&&Object.keys(u).length>0;if(g||x)try{const b=ee.join(a,`${t}.json`),v=JSON.parse(ue.readFileSync(b,"utf-8"));g&&(v.sessionCookies=p),x&&(v.externalApis={...v.externalApis,...u}),ue.writeFileSync(b,JSON.stringify(v,null,2))}catch{}}}else m||(c={success:!1,error:"No seed adapter found"})}return{success:!0,scenarioSlug:o,scenarioId:t,type:i,seeded:h,...c?{seedResult:c}:{},...p&&p.length>0?{sessionCookies:p}:{}}}function Sy(e){return cr.createHash("sha256").update(JSON.stringify(e)).digest("hex")}function Cy(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 ky(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 _y(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 Ey(){let e=[],t={},r=null,s=null,a=!1,o=null;function i(p){const u=[],h=p.routes;if(h&&typeof h=="object")for(const[m,f]of Object.entries(h)){const{method:y,pathPattern:g}=Cy(m),{regex:x,paramNames:b}=ky(g),v=typeof f=="object"&&f!==null?f:{body:f};u.push({method:y,pathPattern:g,pathRegex:x,paramNames:b,response:{body:v.body,status:typeof v.status=="number"?v.status:200}})}return u}function l(p){const u=p.state;if(u&&typeof u=="object"){a=!0,t={};for(const[h,m]of Object.entries(u))t[h]=Array.isArray(m)?JSON.parse(JSON.stringify(m)):[];r=JSON.stringify(u)}else a=!1,t={},r=null}return{loadScenario(p){const u=Sy(p);s&&u===s||(s=u,o=p,e=i(p),l(p))},matchRequest(p,u,h){if(!o&&e.length===0&&!a)return null;const m=Object.keys(t);if(a){const y=_y(u,m);if(y&&p==="GET"&&y===u)return{body:t[y],status:200};if(y){const g=c(p,u);if(p==="POST"&&y===u&&g){const x=t[y],b=typeof h=="object"&&h!==null?{...h}:{};if(!("id"in b)){const v=x.reduce((N,w)=>{const C=typeof w.id=="number"?w.id:0;return Math.max(N,C)},0);b.id=v+1}return x.push(b),{body:b,status:g.response.status}}if(p==="DELETE"&&g&&g.params){const x=g.params.id,b=t[y],v=b.findIndex(N=>String(N.id)===String(x));return v===-1?{body:{error:"Not found"},status:404}:(b.splice(v,1),{body:null,status:g.response.status})}if(p==="PUT"&&g&&g.params){const x=g.params.id,b=t[y],v=b.findIndex(w=>String(w.id)===String(x));if(v===-1)return{body:{error:"Not found"},status:404};const N=typeof h=="object"&&h!==null?{...h}:b[v];return b[v]=N,{body:N,status:g.response.status}}}}const f=c(p,u);if(f)return{body:f.response.body??null,status:f.response.status,params:f.params};if(o&&p==="GET"){const 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 p=JSON.parse(r);t={};for(const[u,h]of Object.entries(p))t[u]=Array.isArray(h)?JSON.parse(JSON.stringify(h)):[]}},getState(){return{...t}}};function c(p,u){for(const h of e)if(h.method!==null&&h.method===p&&h.paramNames.length===0&&h.pathRegex.exec(u))return{response:h.response};if(p==="GET"){for(const h of e)if(h.method===null&&h.paramNames.length===0&&h.pathRegex.exec(u))return{response:h.response}}for(const h of e)if(h.paramNames.length>0){if((h.method??"GET")!==p)continue;const f=h.pathRegex.exec(u);if(f){const y={};for(let g=0;g<h.paramNames.length;g++)y[h.paramNames[g]]=f[g+1];return{response:h.response,params:y}}}return null}}function jy(e){var a,o;const t=ee.join(e,"package.json");if(!ue.existsSync(t))return{error:"No package.json found."};let r="npm",s=["run","dev"];try{const i=JSON.parse(ue.readFileSync(t,"utf8"));if(ue.existsSync(ee.join(e,"pnpm-lock.yaml"))?r="pnpm":ue.existsSync(ee.join(e,"yarn.lock"))?r="yarn":ue.existsSync(ee.join(e,"bun.lockb"))&&(r="bun"),!((a=i.scripts)!=null&&a.dev))if((o=i.scripts)!=null&&o.start)s=["run","start"];else return{error:'No "dev" or "start" script found in package.json.'}}catch{}return{command:r,args:s}}function Ay(e,t){const r=t.toString(),s={PORT:r},a=ee.join(e,".codeyam","config.json");if(ue.existsSync(a))try{const c=(JSON.parse(ue.readFileSync(a,"utf8")).webapps||[])[0];if(c!=null&&c.startCommand){const{command:p,args:u,env:h}=c.startCommand,m=(u||[]).map(f=>f.includes("$PORT")?f.replace(/\$PORT/g,r):f);if(h)for(const[f,y]of Object.entries(h))typeof y=="string"&&y.includes("$PORT")?s[f]=y.replace(/\$PORT/g,r):typeof y=="string"&&(s[f]=y);return{command:p,args:m,env:s}}}catch{}const o=jy(e);return"error"in o?o:{command:o.command,args:o.args,env:s}}function su(e){return{proxyPort:e+1,devServerPort:e+2}}const Py=[/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 Ty(e){for(const t of Py){const r=e.match(t);if(r){const s=r[1]||r[0];return My(s).trim()}}return null}function My(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function hi(){const e=globalThis.__codeyam_editor_dev_server__;return e&&e.status==="running"&&e.url?e.url:null}async function $y(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 Iy(e){const{exitCode:t,uptime:r,retryCount:s,wasRunning:a}=e,o=r<1e4;return t!==0&&t!==null&&o&&s===0?{action:"retry"}:t!==0&&t!==null?{action:"error"}:a===!1?{action:"error"}:{action:"stopped"}}class Fy extends Vr{emitDataMutationForwarded(t,r){this.emit("event",{type:"data-mutation-forwarded",method:t,pathname:r,timestamp:Date.now()})}}const ko="__codeyam_mock_state_event_emitter__";if(!globalThis[ko]){const e=new Fy;e.setMaxListeners(20),globalThis[ko]=e}const Dy=globalThis[ko];function Ry(e){try{return new URL(e).toString().replace(/\/$/,"")}catch{return e}}async function Oy(e){const t=["127.0.0.1","::1"];for(const r of t)try{if(await new Promise(a=>{const o=new ud.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 au="__codeyam_editor_proxy__",ou="__codeyam_preview_health__";function iu(){return globalThis[ou]??null}function lu(e){globalThis[ou]=e}function Bl(){return iu()}function cu(){lu(null)}const Ly=`<script data-codeyam-health>
141
- (function() {
142
- var errors = [];
143
- var reported = false;
144
- function report(type, msg, stack) {
145
- errors.push({ type: type, message: msg, stack: stack, timestamp: Date.now() });
146
- if (!reported) {
147
- reported = true;
148
- setTimeout(function() { flush(); }, 500);
149
- }
150
- }
151
- function flush() {
152
- fetch('/__codeyam__/preview-health', {
153
- method: 'POST',
154
- headers: { 'Content-Type': 'application/json' },
155
- body: JSON.stringify({ errors: errors, url: location.href })
156
- }).catch(function(){});
157
- reported = false;
158
- errors = [];
159
- }
160
- window.addEventListener('error', function(e) {
161
- report('error', e.message, e.error && e.error.stack);
162
- });
163
- window.addEventListener('unhandledrejection', function(e) {
164
- report('unhandledrejection', String(e.reason), e.reason && e.reason.stack);
165
- });
166
- var origError = console.error;
167
- console.error = function() {
168
- report('console.error', Array.prototype.join.call(arguments, ' '));
169
- origError.apply(console, arguments);
170
- };
171
- window.addEventListener('load', function() {
172
- setTimeout(function() {
173
- var hasContent = document.body && document.body.innerText.trim().length > 0;
174
- fetch('/__codeyam__/preview-health', {
175
- method: 'POST',
176
- headers: { 'Content-Type': 'application/json' },
177
- body: JSON.stringify({
178
- loaded: true,
179
- hasContent: hasContent,
180
- url: location.href,
181
- errorCount: errors.length
182
- })
183
- }).catch(function(){});
184
- }, 1000);
185
- });
186
-
187
- // Network-idle detection: notify the parent editor when all initial
188
- // fetch requests have completed, so it can show the preview after
189
- // client-side data (API calls) has arrived — not just when the DOM loads.
190
- var inflight = 0;
191
- var settled = false;
192
- var settleTimer = null;
193
- var origFetch = window.fetch;
194
- window.fetch = function() {
195
- if (!settled) inflight++;
196
- return origFetch.apply(this, arguments).then(function(resp) {
197
- if (!settled) { inflight--; checkSettle(); }
198
- return resp;
199
- }, function(err) {
200
- if (!settled) { inflight--; checkSettle(); }
201
- throw err;
202
- });
203
- };
204
- function checkSettle() {
205
- if (inflight <= 0 && !settled) {
206
- clearTimeout(settleTimer);
207
- // Small delay to allow React to re-render with the fetched data
208
- settleTimer = setTimeout(function() {
209
- if (inflight <= 0) {
210
- settled = true;
211
- try {
212
- window.parent.postMessage({ type: 'codeyam-preview-ready' }, '*');
213
- } catch(e) {}
214
- }
215
- }, 100);
216
- }
217
- }
218
- // Fallback: if no fetches happen (static page), settle after load
219
- window.addEventListener('load', function() {
220
- setTimeout(function() { checkSettle(); }, 200);
221
- });
222
- })();
223
- <\/script>`,zy=500;let Wt={data:null,timestamp:0},St,ln,xa=null,ba=null,va=null,_o=null;const Yl=10*1024*1024;function wa(){return globalThis[au]??null}function du(e){globalThis[au]=e}function uu(){const e="__codeyam_mock_state__";return globalThis[e]||(globalThis[e]=Ey()),globalThis[e]}function pu(){const e=wa();return e?`http://localhost:${e.port}`:null}function By(){const e=Date.now();if(Wt.data!==null&&e-Wt.timestamp<zy)return Wt.data;const t=Ce()||process.env.CODEYAM_ROOT_PATH||process.cwd(),r=ee.join(t,".codeyam","active-scenario.json");try{if(!ue.existsSync(r))return Wt={data:null,timestamp:e},null;const s=JSON.parse(ue.readFileSync(r,"utf-8")),a=s.scenarioId;if(!a)return va=s.prototypeId||null,Wt={data:null,timestamp:e},null;const o=ee.join(t,".codeyam","editor-scenarios",`${a}.json`);if(!ue.existsSync(o))return console.log(`[editorProxy] Scenario data file not found: ${o}`),Wt={data:null,timestamp:e},null;const i=JSON.parse(ue.readFileSync(o,"utf-8"));St=i.session||null,ln=i.sessionCookies||void 0,xa=i.localStorage||null,ba=a;const l=s.type||i.type||null;_o=l;let c;return(l==="application"||l==="user")&&i.seed?i.externalApis&&typeof i.externalApis=="object"?c={routes:i.externalApis}:c={}:c=i,Wt={data:c,timestamp:e},uu().loadScenario(c),c}catch(s){return console.warn("[editorProxy] Error reading scenario data:",s),Wt={data:null,timestamp:e},null}}function Yy(e){return new Promise(t=>{const r=[];let s=0;e.on("data",a=>{s+=a.length,s>Yl?(t(null),e.resume()):r.push(a)}),e.on("end",()=>{s>Yl||t(Buffer.concat(r))}),e.on("error",()=>{t(null)})})}function mi(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function Wl(e,t,r,s){const a=new URL(r),o=mi(a.hostname),i={...e.headers,host:`${a.hostname}:${a.port}`};delete i["accept-encoding"],mu(i),s&&(i["content-length"]=String(s.length));const l={hostname:o,port:a.port,path:e.url,method:e.method,headers:i},c=Vo.request(l,p=>{const u=p.statusCode||200;u>=300&&u<400&&console.log(`[editorProxy] Target redirect ${u} for ${e.method} ${e.url} → ${p.headers.location}`),u>=400&&console.warn(`[editorProxy] Target returned ${u} for ${e.method} ${e.url}`);const h={...p.headers};if(hu(h),(p.headers["content-type"]||"").includes("text/html")){cu();const f=[];p.on("data",y=>f.push(y)),p.on("end",()=>{const y=Buffer.concat(f).toString("utf-8"),g=fu(xa,ba||"",va),x=gu(y,g);delete h["content-length"],delete h["content-encoding"],h["cache-control"]="no-store, must-revalidate",t.writeHead(u,h),t.end(x)});return}t.writeHead(u,h),p.pipe(t,{end:!0})});c.on("error",p=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${p.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),s&&s.length>0?c.end(s):c.end()}function Wy(e,t,r){const s=new URL(r),a=mi(s.hostname),{"accept-encoding":o,...i}=e.headers,l={...i,host:`${s.hostname}:${s.port}`};mu(l);const c={hostname:a,port:s.port,path:e.url,method:e.method,headers:l},p=Vo.request(c,u=>{const h=u.statusCode||200;h>=300&&h<400&&console.log(`[editorProxy] Target redirect ${h} for ${e.method} ${e.url} → ${u.headers.location}`),h>=400&&console.warn(`[editorProxy] Target returned ${h} for ${e.method} ${e.url}`);const m={...u.headers};if(hu(m),(u.headers["content-type"]||"").includes("text/html")){cu();const y=[];u.on("data",g=>y.push(g)),u.on("end",()=>{const g=Buffer.concat(y).toString("utf-8"),x=fu(xa,ba||"",va),b=gu(g,x);delete m["content-length"],delete m["content-encoding"],m["cache-control"]="no-store, must-revalidate",t.writeHead(h,m),t.end(b)});return}t.writeHead(h,m),u.pipe(t,{end:!0})});p.on("error",u=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${u.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),e.pipe(p,{end:!0})}function hu(e){const t=[];if(St!==void 0&&(St!=null&&St.cookieValue?t.push(`session-token=${St.cookieValue}; Path=/; SameSite=Lax`):t.push("session-token=; Path=/; Max-Age=0")),ln&&ln.length>0)for(const s of ln){const a=s.path||"/",o=s.sameSite||"Lax";t.push(`${s.name}=${s.value}; Path=${a}; SameSite=${o}`)}if(t.length===0)return;const r=e["set-cookie"];r?e["set-cookie"]=[...Array.isArray(r)?r:[r],...t]:e["set-cookie"]=t}function Uy(){const e=[];if(St!=null&&St.cookieValue&&e.push({name:"session-token",value:St.cookieValue}),ln&&ln.length>0)for(const t of ln)e.push({name:t.name,value:t.value});return e.length>0?e:null}function mu(e){const t=Uy();if(!t)return;const r=typeof e.cookie=="string"?e.cookie:"",s=r?r.split(";").map(i=>i.trim()):[],a=new Map;for(const i of s){const l=i.indexOf("=");l!==-1&&a.set(i.slice(0,l),i.slice(l+1))}for(const{name:i,value:l}of t)a.set(i,l);const o=[];for(const[i,l]of a)o.push(`${i}=${l}`);o.length>0&&(e.cookie=o.join("; "))}function Jy(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)|0;return(t>>>0).toString(36)}function fu(e,t,r){if(!e||typeof e!="object"){const c=t?`clear:${t}`:"";return r?`<script data-codeyam-ls>
224
- (function() {
225
- if (localStorage.getItem('__codeyam_proto__') === ${JSON.stringify(r)}) return;
226
- localStorage.clear();
227
- localStorage.setItem('__codeyam_proto__', ${JSON.stringify(r)});
228
- })();
229
- <\/script>`:t?`<script data-codeyam-ls>
230
- (function() {
231
- if (localStorage.getItem('__codeyam_ls_sid__') === ${JSON.stringify(c)}) return;
232
- var prev = JSON.parse(localStorage.getItem('__codeyam_ls_keys__') || '[]');
233
- for (var i = 0; i < prev.length; i++) localStorage.removeItem(prev[i]);
234
- localStorage.removeItem('__codeyam_ls_keys__');
235
- localStorage.setItem('__codeyam_ls_sid__', ${JSON.stringify(c)});
236
- })();
237
- <\/script>`:""}const s=Object.entries(e),a=s.map(([c])=>c),o=s.map(([c,p])=>{const u=typeof p=="string"?p:JSON.stringify(p);return`localStorage.setItem(${JSON.stringify(c)}, ${JSON.stringify(u)});`}).join(`
238
- `),i=Jy(JSON.stringify(e)),l=`${t}:${i}`;return`<script data-codeyam-ls>
239
- (function() {
240
- if (localStorage.getItem('__codeyam_ls_sid__') === ${JSON.stringify(l)}) return;
241
- var prev = JSON.parse(localStorage.getItem('__codeyam_ls_keys__') || '[]');
242
- for (var i = 0; i < prev.length; i++) localStorage.removeItem(prev[i]);
243
- ${o}
244
- localStorage.setItem('__codeyam_ls_keys__', ${JSON.stringify(JSON.stringify(a))});
245
- localStorage.setItem('__codeyam_ls_sid__', ${JSON.stringify(l)});
246
- })();
247
- <\/script>`+Hy()}function Hy(){return`<script data-codeyam-ls-watcher>
248
- (function() {
249
- if (window.__codeyam_ls_watcher_installed__) return;
250
- window.__codeyam_ls_watcher_installed__ = true;
251
-
252
- var origSet = localStorage.setItem.bind(localStorage);
253
- var origRemove = localStorage.removeItem.bind(localStorage);
254
- var origClear = localStorage.clear.bind(localStorage);
255
- window.__codeyam_orig_setItem__ = origSet;
256
- window.__codeyam_orig_removeItem__ = origRemove;
257
- window.__codeyam_orig_clear__ = origClear;
258
-
259
- function isInternal(key) {
260
- return typeof key === 'string' && key.indexOf('__codeyam_') === 0;
261
- }
262
-
263
- localStorage.setItem = function(key, value) {
264
- origSet(key, value);
265
- if (!isInternal(key) && window.parent !== window) {
266
- window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'set', key: key }, '*');
267
- }
268
- };
269
-
270
- localStorage.removeItem = function(key) {
271
- origRemove(key);
272
- if (!isInternal(key) && window.parent !== window) {
273
- window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'remove', key: key }, '*');
274
- }
275
- };
276
-
277
- localStorage.clear = function() {
278
- origClear();
279
- if (window.parent !== window) {
280
- window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'clear' }, '*');
281
- }
282
- };
283
-
284
- window.addEventListener('message', function(event) {
285
- if (event.data && event.data.type === 'codeyam-get-localstorage') {
286
- var data = {};
287
- for (var i = 0; i < localStorage.length; i++) {
288
- var k = localStorage.key(i);
289
- if (k && !isInternal(k)) {
290
- data[k] = localStorage.getItem(k);
291
- }
292
- }
293
- event.source.postMessage({ type: 'codeyam-localstorage-state', data: data }, '*');
294
- }
295
- });
296
- })();
297
- <\/script>`}function gu(e,t){const r=(t||"")+Ly;return e.includes("</head>")?e.replace("</head>",r+"</head>"):e.includes("</body>")?e.replace("</body>",r+"</body>"):e+r}function Vy(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=iu()||{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(),lu(a)}catch{}t.writeHead(204),t.end()})}function Ky(e,t,r,s){const a=new URL(s),o=mi(a.hostname),i=parseInt(a.port,10)||80;console.log(`[editorProxy] WebSocket upgrade: ${e.url} → ${o}:${i}`);const l=ud.connect(i,o,()=>{const c=`${e.method} ${e.url} HTTP/${e.httpVersion}\r
298
- `,p=Object.entries(e.headers).filter(([,u])=>u!=null).map(([u,h])=>`${u}: ${Array.isArray(h)?h.join(", "):h}`).join(`\r
299
- `);l.write(c+p+`\r
300
- \r
301
- `),r.length>0&&l.write(r),l.pipe(t,{end:!0}),t.pipe(l,{end:!0})});l.on("error",c=>{console.warn(`[editorProxy] WebSocket proxy error: ${c.message}`),t.destroy()}),t.on("error",()=>{l.destroy()})}function Gy(e,t){const r=Ce()||process.env.CODEYAM_ROOT_PATH||process.cwd(),s=ee.join(r,".codeyam","proxy-config.json");try{ue.mkdirSync(ee.dirname(s),{recursive:!0}),ue.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 qy(){const e=Ce()||process.env.CODEYAM_ROOT_PATH||process.cwd(),t=ee.join(e,".codeyam","proxy-config.json");try{ue.existsSync(t)&&ue.unlinkSync(t)}catch{}}async function Eo(e){const t=wa();if(t)return console.log(`[editorProxy] Proxy already running on port ${t.port} → ${t.targetUrl}`),{port:t.port};await yu();let r=Ry(e.targetUrl),s=e.port;try{const l=new URL(r);if(l.hostname==="localhost"){const c=parseInt(l.port||"80",10),p=await Oy(c);p&&(l.hostname=p,r=l.toString().replace(/\/$/,""),console.log(`[editorProxy] Resolved localhost to ${p} for port ${c}`))}}catch{}console.log(`[editorProxy] Starting proxy (requested port ${s}, target ${r})`);const a=uu(),o=Vo.createServer((l,c)=>{(async()=>{const u=new URL(l.url||"/",`http://localhost:${s}`).pathname,h=l.method||"GET";if(h==="OPTIONS"){c.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Max-Age":"86400"}),c.end();return}if(h==="POST"&&u==="/__codeyam__/preview-health"){Vy(l,c);return}if(By(),h==="POST"||h==="PUT"||h==="DELETE"||h==="PATCH"){const y=await Yy(l);if(y===null){Wl(l,c,r,null);return}let g;if(y.length>0)try{g=JSON.parse(y.toString("utf-8"))}catch{}const x=a.matchRequest(h,u,g);if(x){console.log(`[editorProxy] Intercepted ${h} ${u} → mock response (status ${x.status})`),c.writeHead(x.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data","Cache-Control":"no-store"}),c.end(x.body!=null?JSON.stringify(x.body):"");return}(_o==="application"||_o==="user")&&u.startsWith("/api/")&&Dy.emitDataMutationForwarded(h,u),Wl(l,c,r,y);return}const f=a.matchRequest(h,u);if(f){console.log(`[editorProxy] Intercepted ${h} ${u} → mock response (status ${f.status})`),c.writeHead(f.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data","Cache-Control":"no-store"}),c.end(f.body!=null?JSON.stringify(f.body):"");return}Wy(l,c,r)})()});o.on("upgrade",(l,c,p)=>{Ky(l,c,p,r)});const i=10;for(let l=0;l<i;l++){const c=s+l;try{await new Promise((h,m)=>{o.once("error",m),o.listen(c,"0.0.0.0",()=>{o.removeListener("error",m),h()})});const p=o.address();return s=typeof p=="object"&&p!==null?p.port:c,du({server:o,port:s,targetUrl:r}),Gy(s,r),console.log(`[editorProxy] Proxy started on port ${s}, forwarding to ${r}`),{port:s}}catch(p){if((p==null?void 0:p.code)==="EADDRINUSE"&&l<i-1){console.log(`[editorProxy] Port ${c} in use, trying ${c+1}`);continue}return console.error("[editorProxy] Failed to start proxy:",p),null}}return null}async function yu(){const e=wa();if(e)return console.log(`[editorProxy] Stopping proxy on port ${e.port}`),qy(),new Promise(t=>{e.server.close(()=>{console.log("[editorProxy] Proxy stopped"),t()}),du(null),setTimeout(t,2e3)})}function Tn(){Wt={data:null,timestamp:0},St=void 0,ln=void 0,xa=null,ba=null,va=null}async function Ul(){const e=wa();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 fi(){const e=pu();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}=su(r);console.log(`[editorProxy] Proxy not running, starting on-demand (port ${s}, target ${t.url})`);const a=await Eo({port:s,targetUrl:t.url});if(a){const o=`http://localhost:${a.port}`;return console.log(`[editorProxy] On-demand proxy started at ${o}`),o}return console.error("[editorProxy] Failed to start on-demand proxy"),null}async function Qy({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioId:r,scenarioName:s,scenarioSlug:a}=t;if(!r||typeof r!="string")return Response.json({error:"scenarioId is required"},{status:400});const o=Ce()||process.cwd(),i=await ya({scenarioId:r,scenarioName:s,scenarioSlug:a,projectRoot:o});return Tn(),Response.json({success:i.success,seeded:i.seeded,seedResult:i.seedResult})}catch(t){const r=t instanceof Error?t.message:String(t);return Response.json({error:r},{status:500})}}const Zy=Object.freeze(Object.defineProperty({__proto__:null,action:Qy},Symbol.toStringTag,{value:"Module"}));async function Xy({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=H.join(i,".codeyam","journal","screenshots");await Ae.mkdir(l,{recursive:!0});const c=s.replace(/[^a-zA-Z0-9_\-T]/g,"_"),p=H.join(l,`${c}.png`),u=H.dirname(new URL(import.meta.url).pathname);let h=u;for(let v=0;v<5;v++){const N=H.dirname(h);if(H.basename(N)==="webserver"||H.basename(h)==="webserver"){h=H.basename(h)==="webserver"?h:N;break}h=N}const m=[H.join(h,"scripts","journalCapture.ts"),H.join(h,"app","lib","journalCapture.ts"),H.join(i,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),H.resolve(u,"..","lib","journalCapture.ts")];let f="";for(const v of m)try{await Ae.access(v),f=v;break}catch{}f||(console.warn(`[editor-journal-screenshot] journalCapture.ts not found in any of: ${m.join(", ")}`),f=m[0]);const y=ga({bodyWidth:a,bodyHeight:o,codeyamRoot:i}),g=JSON.stringify({url:r,outputPath:p,viewportWidth:y.width,viewportHeight:y.height}),x=await new Promise(v=>{const N=xt("npx",["tsx",f,g],{cwd:i,env:{...process.env}});let w="",C="";N.stdout.on("data",S=>{w+=S.toString()}),N.stderr.on("data",S=>{C+=S.toString()}),N.on("close",S=>{v(S===0?{success:!0,output:w}:{success:!1,output:w,error:C||`Process exited with code ${S}`})}),N.on("error",S=>{v({success:!1,output:"",error:S.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 ex=Object.freeze(Object.defineProperty({__proto__:null,action:Xy},Symbol.toStringTag,{value:"Module"}));async function tx({request:e}){const t={"Content-Type":"application/json"};try{const r=Ce()||process.cwd(),s=await e.json(),{scenarioId:a,table:o,rowIndex:i,column:l,value:c}=s;if(!a||!o||i==null||!l)return new Response(JSON.stringify({success:!1,error:"Missing required fields"}),{headers:t,status:400});const p=H.join(r,".codeyam","editor-scenarios",`${a}.json`);if(!G.existsSync(p))return new Response(JSON.stringify({success:!1,error:"Scenario file not found"}),{headers:t,status:404});const u=JSON.parse(G.readFileSync(p,"utf-8"));if(Array.isArray(u[o])&&i<u[o].length)return u[o][i][l]=c,G.writeFileSync(p,JSON.stringify(u,null,2)),new Response(JSON.stringify({success:!0}),{headers:t});if(u.seed&&typeof u.seed=="object"){const h=o.charAt(0).toLowerCase()+o.slice(1);for(const m of[o,h,`${h}s`])if(Array.isArray(u.seed[m])&&i<u.seed[m].length){u.seed[m][i][l]=c,G.writeFileSync(p,JSON.stringify(u,null,2));const f=p.replace(/\.json$/,".seed.json");if(G.existsSync(f))try{const y=JSON.parse(G.readFileSync(f,"utf-8"));Array.isArray(y[m])&&(y[m][i][l]=c,G.writeFileSync(f,JSON.stringify(y,null,2)))}catch{}return new Response(JSON.stringify({success:!0}),{headers:t})}}if(u.localStorage&&typeof u.localStorage=="object"){for(const[h,m]of Object.entries(u.localStorage))if(typeof m=="string")try{let f=JSON.parse(m);const y=!Array.isArray(f)&&typeof f=="object"&&f!==null;if(y&&(f=[f]),!Array.isArray(f))continue;const g=o.charAt(0).toLowerCase()+o.slice(1),x=()=>{f[i][l]=c;const b=y?f[0]:f;u.localStorage[h]=JSON.stringify(b),G.writeFileSync(p,JSON.stringify(u,null,2))};if((h===o||h===g||h===`${g}s`||h===`${o}s`)&&i<f.length)return x(),new Response(JSON.stringify({success:!0}),{headers:t});if(f.length>0&&l in f[0]&&i<f.length)return x(),new Response(JSON.stringify({success:!0}),{headers:t})}catch{}}return new Response(JSON.stringify({success:!1,error:"Table not found in scenario"}),{headers:t,status:404})}catch(r){return new Response(JSON.stringify({success:!1,error:r instanceof Error?r.message:"Unknown error"}),{headers:t,status:500})}}const nx=Object.freeze(Object.defineProperty({__proto__:null,action:tx},Symbol.toStringTag,{value:"Module"})),xu=zo({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),gi=()=>{const e=Zs(xu);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},Na=({children:e})=>{const[t,r]=A({height:720,width:1200}),[s,a]=A(1),[o,i]=A(1200),l=ye(null),c=oe(({height:h,width:m})=>{r(f=>({height:h??f.height,width:m??f.width}))},[]),p=oe(h=>{a(h)},[]),u=oe(h=>{i(h)},[]);return n(xu.Provider,{value:{dimensions:t,updateDimensions:c,iframeRef:l,scale:s,updateScale:p,maxWidth:o,updateMaxWidth:u},children:e})},rx=typeof window<"u";function sx(){const[e,t]=A(null);return ne(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const ax=1200,ox=720,Jl=30,ix=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:s=1440,defaultHeight:a=900,onDataOverride:o,onIframeLoad:i,onScaleChange:l,onDimensionChange:c})=>{const p=sx(),[u,h]=A(!1),[m,f]=A(!1),[y,g]=A(ax),[x,b]=A(ox),[v,N]=A(null),[w,C]=A(null),{dimensions:S,updateDimensions:k,iframeRef:j,updateScale:_,updateMaxWidth:F}=gi(),M=le(()=>Math.min(1,y/S.width),[y,S.width]),$=w!==null?w:M;ne(()=>{u||(_($),l==null||l($))},[$,_,l,u]),ne(()=>{F(y)},[y,F]);const O=oe(()=>{h(!0),C(M)},[M]),D=oe(()=>{h(!1),C(null)},[]),T=oe((P,R)=>{const E=w!==null?w:1,J=Math.round(R.size.width/E);k({width:J}),c==null||c(J,S.height)},[k,w,c,S.height]),B=oe(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);ne(()=>{const P=R=>{if(R.data.type==="codeyam-resize"){if(t&&R.data.name!==t||S.height===R.data.height||R.data.height===0)return;k({height:R.data.height})}};return window.addEventListener("message",P),()=>{window.removeEventListener("message",P)}},[j,t,s,S,k]),ne(()=>{m&&o&&o(j.current)},[m,o,j]),ne(()=>{if(!t)return;const P=setInterval(()=>{var R,E;(E=(R=j==null?void 0:j.current)==null?void 0:R.contentWindow)==null||E.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(P)},[t,j]),ne(()=>{const P=()=>{const R=document.getElementById("scenario-container");if(!R)return;const E=R.getBoundingClientRect(),J=R.clientWidth-Jl*2,K=window.innerHeight-E.top-Jl*2,Q=Math.max(K,400),q=window.innerHeight-E.top;g(J),b(Q),N(q)};return P(),window.addEventListener("resize",P),()=>window.removeEventListener("resize",P)},[]),ne(()=>{k({width:s,height:a})},[s,a,k]);const Y=le(()=>S.width*$,[S.width,$]),I=le(()=>{const P=S.height,R=P*$;return P&&P!==720&&P!==900&&R<x?R:x},[S.height,x,$]),L=oe(()=>{window.history.back()},[]);return!rx||!p?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):d("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:v?{height:`${v}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
302
- .react-resizable-handle-e {
303
- display: flex !important;
304
- align-items: center !important;
305
- justify-content: center !important;
306
- width: 6px !important;
307
- height: 48px !important;
308
- right: -8px !important;
309
- top: 50% !important;
310
- transform: translateY(-50%) !important;
311
- cursor: ew-resize !important;
312
- background: #d1d5db !important;
313
- border-radius: 3px !important;
314
- opacity: 0 !important;
315
- transition: all 0.2s ease !important;
316
- }
317
- .react-resizable-handle-e:hover {
318
- opacity: 0.8 !important;
319
- background: #9ca3af !important;
320
- }
321
- .react-resizable:hover .react-resizable-handle-e {
322
- opacity: 0.4 !important;
323
- }
324
- `}),n(p,{width:Y,height:I,minConstraints:[300,200],maxConstraints:[y,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:O,onResizeStop:D,onResize:T,children:n("div",{className:"overflow-auto",style:{width:`${Y}px`,height:`${I}px`},children:n("div",{style:{width:`${S.width}px`,height:`${S.height}px`,transform:`scale(${$})`,transformOrigin:"top left"},children:r?n("iframe",{ref:j,className:"w-full h-full rounded-lg",src:r,onLoad:B,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:L,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function lx({presets:e,customSizes:t,currentWidth:r,currentHeight:s,scale:a,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:l,className:c=""}){const[p,u]=A(!1),[h,m]=A(String(r)),[f,y]=A(String(s)),[g,x]=A(!1),[b,v]=A(!1),N=ye(null);ne(()=>{g||m(String(r))},[r,g]),ne(()=>{b||y(String(s))},[s,b]),ne(()=>{const $=O=>{N.current&&!N.current.contains(O.target)&&u(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[]);const w=le(()=>{const $=e.find(D=>D.width===r&&D.height===s);if($)return $.name;const O=t.find(D=>D.width===r&&D.height===s);return O?O.name:"Custom"},[e,t,r,s]),C=w==="Custom",S=$=>{o($.width,$.height),u(!1)},k=$=>{const O=$.target.value;m(O);const D=parseInt(O,10);!isNaN(D)&&D>0&&o(D,s)},j=$=>{const O=$.target.value;y(O);const D=parseInt(O,10);!isNaN(D)&&D>0&&o(r,D)},_=()=>{x(!1);const $=parseInt(h,10);(isNaN($)||$<=0)&&m(String(r))},F=()=>{v(!1);const $=parseInt(f,10);(isNaN($)||$<=0)&&y(String(s))},M=$=>{($.key==="Enter"||$.key==="Escape")&&$.target.blur()};return d("div",{className:`flex items-center gap-3 ${c}`,children:[d("div",{className:"relative",ref:N,children:[d("button",{onClick:()=>u(!p),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:w}),n("svg",{className:`w-4 h-4 transition-transform ${p?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),p&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:d("div",{className:"py-1",children:[e.length>0&&d(ve,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map($=>d("button",{onClick:()=>S($),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${w===$.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:$.name}),d("span",{className:"text-xs text-gray-500",children:[$.width," x ",$.height]})]},$.name))]}),t.length>0&&d(ve,{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(($,O)=>$.width-O.width).map($=>d("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${w===$.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[d("button",{onClick:()=>S($),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:$.name}),d("span",{className:"text-xs text-gray-500",children:[$.width," x ",$.height]})]}),l&&n("button",{onClick:O=>{O.stopPropagation(),w===$.name&&e.length>0&&o(e[0].width,e[0].height),l($.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"})})})]},$.name))]})]})})]}),d("div",{className:"flex items-center gap-1 text-sm",children:[d("div",{className:"flex items-center",children:[n("input",{type:"text",value:h,onChange:k,onFocus:()=>x(!0),onBlur:_,onKeyDown:M,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:j,onFocus:()=>v(!0),onBlur:F,onKeyDown:M,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),"%)"]})]}),C&&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 ro(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 jo(e){return e&&(typeof e=="object"||Array.isArray(e))}function cx(e){return Array.isArray(e)?e.length:void 0}function dx(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=jo(t[a]),l=jo(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 ux({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 px({path:e,namedPath:t,isArray:r,count:s,onClick:a}){const o=oe(()=>{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 bu=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(bu||{});const hx=({name:e,value:t,options:r,onChange:s})=>{const a=oe(o=>{s({target:{name:e,value:o.target.value}})},[e,s]);return n("select",{name:e,value:t,onChange:a,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",children:r.map((o,i)=>n("option",{value:o.trim(),children:o.trim()},i))})},mx=({name:e,value:t,onChange:r})=>{const s=oe(a=>{const o=a.target.checked;r({target:{name:e,value:o}})},[e,r]);return n("label",{className:"flex items-center gap-2 cursor-pointer",children:n("input",{type:"checkbox",name:e,checked:t,onChange:s,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
325
- bg-gray-300 checked:bg-blue-600
326
- after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
327
- after:bg-white after:rounded-full after:transition-transform
328
- checked:after:translate-x-4`})})};function fx({dataType:e,path:t,value:r,onChange:s}){const a=le(()=>t[t.length-1],[t]),o=le(()=>t.join("-"),[t]),i=oe(c=>{s(t,c.target.value)},[s,t]),l=oe(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(hx,{name:o,value:r,options:e.split("|"),onChange:i}):e===bu.BOOLEAN?n(mx,{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 gx({analysis:e,scenarioName:t,dataItem:r,onResult:s,onGenerateData:a}){const[o,i]=A(!1),[l,c]=A(""),p=oe(async()=>{if(!a){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const h=e.scenarios.find(x=>x.name===t);if(!h)throw new Error("Scenario not found");const m=e.scenarios.find(x=>x.name===sa),f=await a(l,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const y=(x,b)=>{const v=Object.assign({},x);return g(x)&&g(b)&&Object.keys(b).forEach(N=>{g(b[N])?N in x?v[N]=y(x[N],b[N]):Object.assign(v,{[N]:b[N]}):Object.assign(v,{[N]:b[N]})}),v},g=x=>x&&typeof x=="object"&&!Array.isArray(x);h.metadata.data=y(y((m==null?void 0:m.metadata.data)||{},h.metadata.data),f.data||{}),s(h),i(!1),c("")}catch(h){console.error("Error generating AI data:",h),i(!1)}},[e,l,r,t,s,a]),u=oe(h=>{c(h.target.value)},[]);return d("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:l}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${l.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void p(),children:o?d(ve,{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 yx({namedPath:e,path:t,last:r,onClick:s}){const a=oe(()=>s(r?t.slice(0,-1):t),[r,t,s]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:a,children:e[e.length-1]})}function xx({dataItem:e,onClick:t}){const r=oe(()=>t([]),[t]),s=le(()=>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(yx,{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 Hl({analysis:e,scenarioName:t,dataItem:r,onClick:s,onChange:a,onAIResult:o,onGenerateData:i,saveFeedback:l}){const c=le(()=>r.data,[r]),p=le(()=>dx(r),[r]);return d("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(xx,{dataItem:r,onClick:s}),d("div",{className:"flex flex-col gap-3",children:[n(gx,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),p==null?void 0:p.map((u,h)=>{var f;if(jo(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(px,{path:g,namedPath:x,isArray:Array.isArray(c),count:cx(c[u]),onClick:s},`data-${u}-${h}`)}if(u==="id")return null;const m=[...r.path,u];return n(fx,{dataType:((f=r.structure)==null?void 0:f[u])??"string",path:m,value:c[u],onChange:a},`InputField-${m.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),d("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:l!=null&&l.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save & Recapture"})]}),(l==null?void 0:l.message)&&!(l!=null&&l.isSaving)&&n("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${l.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:l.message})]})}function Vl({title:e,children:t,defaultOpen:r=!1,borderT:s=!1,borderB:a=!1}){const[o,i]=A(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 bx=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:s,shouldCreateNewScenario:a,onSave:o,onNavigate:i,iframeRef:l,onGenerateData:c,saveFeedback:p})=>{const u=oe((k,j)=>{const _=Object.assign({},k),F=M=>M&&typeof M=="object"&&!Array.isArray(M);return F(k)&&F(j)&&Object.keys(j).forEach(M=>{F(j[M])?M in k?_[M]=u(k[M],j[M]):Object.assign(_,{[M]:j[M]}):Object.assign(_,{[M]:j[M]})}),_},[]),[h,m]=A({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,y]=A(null),g=le(()=>({...h.data}),[h]),x=le(()=>({...g.mockData?{"Retrieved Data":g.mockData}:{},...g.argumentsData?{"Function Arguments":g.argumentsData}:{}}),[g]),b=le(()=>{const k={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(k).reduce((j,_)=>{if(_.includes(".")){const[F,M]=_.split(".");j[F]||(j[F]={}),j[F][M]=k[_]}else j[_]=k[_];return j},{})},[r]),v=oe(async k=>{k.preventDefault();const j=k.target.querySelector('input[name="recapture"]'),_=(j==null?void 0:j.value)==="true",F={mockData:h.data.mockData??{},argumentsData:h.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:h.name,shouldRecapture:_,dataToSave:F,rawFormData:h.data,iframePayload:{arguments:g.argumentsData??[],...g.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(F,null,2).substring(0,1e3));const M=s==null?void 0:s.scenarios.map($=>!a&&$.name===e.name?{...$,name:h.name,description:h.description,metadata:{...$.metadata,data:F}}:$);a&&M.push({name:h.name,description:h.description,metadata:{data:F,interactiveExamplePath:s==null?void 0:s.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",M),o&&await o(M,{recapture:_}),i&&i(h.name)},[s,e.name,h,g,a,o,i]),N=oe(k=>{m(j=>({...j,[k.target.name]:k.target.value}))},[]),w=oe(k=>{y(j=>{if(!j)return null;for(const _ of[{arguments:k.metadata.data.argumentsData},k.metadata.data.mockData]){let F=_;for(const M of j.path)if(F=ro(F,M),!F)break;F&&(j.data=F)}return{...j}}),m({name:k.name,description:k.description,data:k.metadata.data})},[]),C=oe((k,j)=>{m(_=>{for(const F of[{"Function Arguments":_.data.argumentsData},{"Retrieved Data":_.data.mockData}]){let M=F;for(const $ of k.slice(0,-1))if(M=ro(M,$),!M)break;if(M){const $=M[k[k.length-1]];y(O=>O?(O.namedPath[O.namedPath.length-1]===$&&(O.namedPath[O.namedPath.length-1]=j.toString()),O.data[k[k.length-1]]=j,{...O}):null),M[k[k.length-1]]=j}}return{..._}})},[]),S=oe(k=>{var M,$,O;if(k.length===0){y(null);return}let j=x;const _=[];let F=b;for(const D of k){if(_.push(isNaN(parseInt(D))?D:((M=j[D])==null?void 0:M.name)??(($=j[D])==null?void 0:$.title)??((O=j[D])==null?void 0:O.id)??D),j=ro(j,D),!j){console.log("Data not found",j,D),y(null);return}Array.isArray(F)?F=F[0]:F=F[D]}y({path:k,namedPath:_,data:j,structure:F})},[x,b]);return ne(()=>{const k=j=>{var _;j.data.type==="codeyam-log"&&((_=j.data.data)!=null&&_.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",j.data.data)};return window.addEventListener("message",k),()=>window.removeEventListener("message",k)},[]),ne(()=>{var k;if((k=l==null?void 0:l.current)!=null&&k.contentWindow){const j={arguments:g.argumentsData??[],...g.mockData??{}},_={type:"codeyam-override-data",name:e.name,data:JSON.stringify(j)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:_.type,name:_.name,dataPreview:JSON.stringify(j).substring(0,200)+"...",fullData:j}),l.current.contentWindow.postMessage(_,"*")}},[g,e,l]),n("form",{method:"post",onSubmit:k=>void v(k),children:f?n(Hl,{analysis:s,scenarioName:h.name,dataItem:f,onClick:S,onChange:C,onAIResult:w,onGenerateData:c,saveFeedback:p}):d(ve,{children:[n(Vl,{title:"Edit Name and Description",borderT:!0,children:n(ux,{scenarioFormData:h,handleInputChange:N})}),e.metadata.data&&n(Vl,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(Hl,{analysis:s,scenarioName:h.name,dataItem:{path:[],namedPath:[],data:x,structure:b},onClick:S,onChange:C,onAIResult:w,onGenerateData:c,saveFeedback:p})})]})})};function Sa({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:s,isLoading:a,showIframe:o,iframeKey:i,onIframeLoad:l,onScaleChange:c,onDimensionChange:p,projectSlug:u,defaultWidth:h=1440,defaultHeight:m=900,retryCount:f=0}){const{lastLine:y}=Jt(u??null,s||a);return r?d("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:o?1:0,background:"transparent"},children:n(ix,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:h,defaultHeight:m,onIframeLoad:l,onScaleChange:c,onDimensionChange:p},i)}),!o&&(s||a)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Ut,{})}),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(ar,{}),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(Ut,{})}),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(ar,{}),y]})]})]})})}const vx=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function wx({params:e}){var c,p;const{sha:t,scenarioId:r}=e;if(!t)throw new Response("Entity SHA is required",{status:400});if(!r)throw new Response("Scenario ID is required",{status:400});const s=await aa(t,!0),a=s&&s.length>0?s[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const o=(c=a.scenarios)==null?void 0:c.find(u=>u.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=(p=a.scenarios)==null?void 0:p.find(u=>u.name===sa),l=await Ye();return re({analysis:a,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:l})}function Nx(){var D,T,B;const e=ot(),t=e.analysis,r=e.scenario,s=e.defaultScenario,a=e.entitySha,o=e.projectSlug,i=Dt(),{iframeRef:l}=gi(),[c,p]=A(!1),[u,h]=A(null),[m,f]=A(null),[y,g]=A(!1),[x,b]=A(!1),[v,N]=A(null),{interactiveServerUrl:w,isStarting:C,isLoading:S,showIframe:k,iframeKey:j,onIframeLoad:_}=In({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}),F=oe(async(Y,I)=>{p(!0),h(null),f(null),console.log("[EditScenario] Starting save with options:",I),console.log("[EditScenario] Scenarios to save:",Y);try{const L={analysis:t,scenarios:Y};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:Y.length,scenarioNames:Y.map(E=>E.name)});const P=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)}),R=await P.json();if(console.log("[EditScenario] API response:",R),!P.ok||!R.success)throw new Error(R.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),I!=null&&I.recapture&&r.id&&w){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:w}),h("Changes saved. Capturing screenshot...");const E={serverUrl:w,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",E);const J=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});console.log("[EditScenario] Capture response status:",J.status);const K=await J.json();if(console.log("[EditScenario] Capture response body:",K),!J.ok||!K.success)throw console.error("[EditScenario] Capture failed:",K),new Error(K.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",K),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),h("Recapture successful")}else if(I!=null&&I.recapture&&!w){console.log("[EditScenario] No running server, using queued recapture");const E=new FormData;E.append("analysisId",t.id||""),E.append("scenarioId",r.id||"");const J=await fetch("/api/recapture-scenario",{method:"POST",body:E}),K=await J.json();if(!J.ok||!K.success)throw new Error(K.error||"Failed to trigger recapture");console.log("Recapture queued:",K),f(K.jobId),h("Changes saved. Screenshot recapture queued.")}else h("Changes saved successfully.")}catch(L){console.error("Error saving scenarios:",L),h(`Error: ${L instanceof Error?L.message:String(L)}`)}finally{p(!1)}},[t,r.id,w]),M=oe(Y=>{},[]),$=oe(async(Y,I)=>{var R;const L=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:Y,existingScenarios:t.scenarios,scenariosDataStructure:(R=t.metadata)==null?void 0:R.scenariosDataStructure,editingMockName:r.name,editingMockData:I==null?void 0:I.data})}),P=await L.json();if(!L.ok||!P.success)throw new Error(P.error||"Failed to generate scenario data");return P.data},[t,r.name]),O=oe(async()=>{var Y;if(!r.id){N("Cannot delete scenario without ID");return}g(!0),N(null);try{const I=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)||[]})}),L=await I.json();if(!I.ok||!L.success)throw new Error(L.error||"Failed to delete scenario");i(`/entity/${a}`)}catch(I){console.error("[EditScenario] Error deleting scenario:",I),N(I instanceof Error?I.message:"Failed to delete scenario"),b(!1)}finally{g(!1)}},[r.id,(D=r.metadata)==null?void 0:D.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(ke,{to:`/entity/${a}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(T=t.entity)==null?void 0:T.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(bx,{currentScenario:r,defaultScenario:s,dataStructure:((B=t.metadata)==null?void 0:B.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:F,onNavigate:M,iframeRef:l,onGenerateData:$,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(ke,{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 O(),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"}),v&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:v})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(Sa,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:w,isStarting:C,isLoading:S,showIframe:k,iframeKey:j,onIframeLoad:_,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const Sx=et(function(){return n(Na,{children:n(Nx,{})})}),Cx=Object.freeze(Object.defineProperty({__proto__:null,default:Sx,loader:wx,meta:vx},Symbol.toStringTag,{value:"Module"})),kx=["/api/health","/__codeyam__/preview-health"];function vu(e){const t=[];for(const r of e.split(`
329
- `))if(r.includes("[JournalCapture] HTTP error:"))t.push(r.replace(/.*\[JournalCapture\] /,""));else if(r.includes("[JournalCapture] API response error:"))t.push(r.replace(/.*\[JournalCapture\] /,""));else if(r.includes("[JournalCapture] Page console.error:"))t.push(r.replace(/.*\[JournalCapture\] Page console\.error:\s*/,""));else if(r.includes("[JournalCapture] Network failed:")){if(kx.some(s=>r.includes(s)))continue;t.push(r.replace(/.*\[JournalCapture\] /,""))}return t}function _x(e){for(const t of e.split(`
330
- `))if(t.includes("[JournalCapture] Visible text: "))return t.replace(/.*\[JournalCapture\] Visible text: /,"");return null}async function wu(e,t,r,s){const a=H.join(e,".codeyam","editor-scenarios","client-errors.json");let o={};try{const i=await Ae.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 Ae.mkdir(H.dirname(a),{recursive:!0}),await Ae.writeFile(a,JSON.stringify(o,null,2),"utf8")}async function Nu(e){const t=H.join(e,".codeyam","editor-scenarios","client-errors.json");try{const r=await Ae.readFile(t,"utf8");return JSON.parse(r)}catch{return{}}}function yi(e){let r=H.dirname(new URL(e).pathname);for(let s=0;s<5;s++){const a=H.dirname(r);if(H.basename(a)==="webserver"||H.basename(r)==="webserver")return H.basename(r)==="webserver"?r:a;r=a}return r}async function xi(e,t){const r=[H.join(e,"scripts","journalCapture.ts"),H.join(e,"app","lib","journalCapture.ts"),H.join(t,"codeyam-cli","src","webserver","app","lib","journalCapture.ts")];for(const s of r)try{return await Ae.access(s),s}catch{}return r[0]}function bi(e,t,r){return new Promise(s=>{const a=e.endsWith(".ts"),l=xt(a?"npx":e,a?["tsx",e,t]:[t],{cwd:r,env:{...process.env}});let c="",p="";l.stdout.on("data",u=>{c+=u.toString()}),l.stderr.on("data",u=>{p+=u.toString()}),l.on("close",u=>{s(u===0?{success:!0,output:c}:{success:!1,output:c,error:p||`Process exited with code ${u}`})}),l.on("error",u=>{s({success:!1,output:"",error:u.message})})})}function Ex(e){const t=H.join(e,".codeyam","editor-scenarios");let r;try{r=G.readdirSync(t)}catch{return[]}const s=[];for(const a of r){if(!a.endsWith(".json")||a.endsWith(".seed.json")||a==="client-errors.json")continue;const o=H.join(t,a);try{if(!G.statSync(o).isFile())continue;const l=JSON.parse(G.readFileSync(o,"utf8"));if(l._metadata){const c=a.replace(/\.json$/,"");s.push({id:c,metadata:l._metadata})}}catch{}}return s}function Su(e,t,r){const s=H.join(e,".codeyam","editor-scenarios",`${t}.json`);let a={};try{a=JSON.parse(G.readFileSync(s,"utf8"))}catch{return}a._metadata=r,G.writeFileSync(s,JSON.stringify(a,null,2),"utf8")}function jx(e,t,r){const s=H.join(e,".codeyam","editor-scenarios",`${t}.json`);let a={};try{a=JSON.parse(G.readFileSync(s,"utf8"))}catch{return}a._metadata&&typeof a._metadata=="object"&&(a._metadata.screenshotPath=r,a._metadata.updatedAt=new Date().toISOString(),G.writeFileSync(s,JSON.stringify(a,null,2),"utf8"))}function Ax(e,t,r,s={}){const a=H.join(e,".codeyam","editor-scenarios");G.mkdirSync(a,{recursive:!0});const o=H.join(a,`${t}.json`);let i={};try{i=JSON.parse(G.readFileSync(o,"utf8"))}catch{}const l={...i,_metadata:r,...s};G.writeFileSync(o,JSON.stringify(l,null,2),"utf8")}function Px(e,t){const r=H.join(e,".codeyam","editor-scenarios");for(const s of[".json",".seed.json"]){const a=H.join(r,`${t}${s}`);try{G.unlinkSync(a)}catch{}}}const vi=globalThis.__codeyamTerminalSessions??(globalThis.__codeyamTerminalSessions=new Set);globalThis.__codeyamDetachedPtys??(globalThis.__codeyamDetachedPtys=new Map);function wi(e,t){const r=JSON.stringify({type:"refresh-preview",...e&&{path:e},...t&&{scenarioId:t}});let s=0;for(const a of vi)try{a.ws.readyState===Ko.OPEN&&(a.ws.send(r),s++)}catch{}return s}function Tx(){const e=JSON.stringify({type:"hide-results"});let t=0;for(const r of vi)try{r.ws.readyState===Ko.OPEN&&(r.ws.send(e),t++)}catch{}return t}function Ni(e){const t=JSON.stringify({type:"set-viewport",...e});let r=0;for(const s of vi)try{s.ws.readyState===Ko.OPEN&&(s.ws.send(t),r++)}catch{}return r}const Mx=Object.freeze(Object.defineProperty({__proto__:null,broadcastHideResults:Tx,broadcastPreviewRefresh:wi,broadcastSetViewport:Ni},Symbol.toStringTag,{value:"Module"}));function $x(e){if(e.dimension)try{Ni({name:e.dimension,width:e.viewport.width,height:e.viewport.height})}catch{}wi(e.refreshPath,e.scenarioId)}function Ix(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=De("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return Fx(r)}catch{return[]}}function Fx(e){const t=e.trim().split(`
331
- `).filter(s=>s.length>0),r=[];for(const s of t){const a=s[0],o=s[1];let i=s.slice(2).replace(/^[ \t]+/,""),l,c=!1,p;if(a==="A"||o==="A")l="added",c=a==="A";else if(a==="M"||o==="M")l="modified",c=a==="M";else if(a==="D"||o==="D")l="deleted",c=a==="D";else if(a==="R"||o==="R"){l="renamed",c=a==="R";const u=i.indexOf(" -> ");u!==-1&&(p=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(l="untracked",c=!1):(l="modified",c=a!==" "&&a!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=ee.join(u,i);try{const m=(y,g)=>{const x=ue.readdirSync(y,{withFileTypes:!0}),b=[];for(const v of x){const N=ee.join(y,v.name),w=ee.relative(u,N);v.isDirectory()?b.push(...m(N,g)):v.isFile()&&b.push(w)}return b},f=m(h,u);for(const y of f)r.push({path:y,status:l,staged:c,...p&&{oldPath:p}})}catch(m){console.error(`Failed to expand directory ${i}:`,m)}}else r.push({path:i,status:l,staged:c,...p&&{oldPath:p}})}return r}function Dx(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return De("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 Rx(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const s=De('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 De("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return De("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 Ox(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return De('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
332
- `).filter(s=>s.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function fr(){const e=Ce();return e?Ix(e):[]}function Lx(){const e=Ce();return e?Dx(e):null}function zx(){const e=Ce();return e?Rx(e):"main"}function Bx(){const e=Ce();return e?Ox(e):[]}function Cu(e,t){const r=Ce();return r?Yx(e,t,r):[]}function Yx(e,t,r){const s=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return De(`git diff --name-status ${e}...${t}`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
333
- `).filter(i=>i.length>0).map(i=>{const l=i.split(" "),c=l[0];let p=l[1],u,h;return c==="A"?h="added":c==="M"?h="modified":c==="D"?h="deleted":c.startsWith("R")?(h="renamed",u=l[1],p=l[2]):h="modified",{path:p,status:h,...u&&{oldPath:u}}})}catch(a){return console.error("Failed to get branch diff:",a),[]}}function ku(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=De(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let a="";try{a=ue.readFileSync(ee.join(r,e),"utf8")}catch(o){console.error(`Failed to read current file ${e}:`,o),a=""}return{oldContent:s,newContent:a,fileName:e}}catch(s){return console.error(`Failed to get diff for ${e}:`,s),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Wx(e){const t=Ce();return t?ku(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Ux(e,t,r,s){const a=s||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=De(`git show ${t}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=De(`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 Ps(e,t,r){const s=Ce();return s?Ux(e,t,r,s):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}async function Jx(e,t,r){const s=H.join(e,".codeyam","journal"),a=H.join(s,"index.json");H.join(s,"screenshots");let o;try{const l=await Ae.readFile(a,"utf8");o=JSON.parse(l)}catch{return}let i=!1;for(const l of o.entries)if(!l.commitSha&&l.scenarioScreenshots)for(let c=0;c<l.scenarioScreenshots.length;c++){const p=l.scenarioScreenshots[c];if(p.name!==t)continue;const u=H.join(s,p.path);try{await Ae.copyFile(r,u),i=!0,console.log(`[editor-register-scenario] Updated journal screenshot for "${t}" in entry "${l.title}"`)}catch(h){console.warn(`[editor-register-scenario] Failed to update journal screenshot: ${h instanceof Error?h.message:h}`)}}i&&ft.notifyChange("journal")}const Kl=hi;async function Hx({request:e}){var t,r;if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const s=await e.json();s.url=s.url||s.path||void 0;const a=uy({componentName:s.componentName,url:s.url,type:s.type});if(!a.valid)return new Response(JSON.stringify({error:a.error}),{status:400,headers:{"Content-Type":"application/json"}});const{name:o,description:i,componentName:l,componentPath:c}=s;if(!o)return new Response(JSON.stringify({error:"name is required"}),{status:400,headers:{"Content-Type":"application/json"}});if(l&&!c)return new Response(JSON.stringify({error:`componentPath is required when componentName is provided. Add "componentPath": "app/components/${l}.tsx" (or the actual file path) to the registration JSON.`}),{status:400,headers:{"Content-Type":"application/json"}});const p=await Ye();if(!p)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:u}=await Re(p),h=$e(),m=process.env.CODEYAM_ROOT_PATH||process.cwd();let f,y,g;if(!s.viewportWidth&&!s.viewportHeight&&!s.dimension&&!s.dimensions){const q=await h.selectFrom("editor_scenarios").selectAll().where("name","=",o).where("project_id","=",u.id).orderBy("created_at","desc").executeTakeFirst();if(q){f=q.viewport_width||void 0,y=q.viewport_height||void 0;try{const U=q.dimensions?JSON.parse(q.dimensions):void 0;Array.isArray(U)&&(g=U)}catch{}}}let x=null;s.dimensions&&s.dimensions.length>0?x=s.dimensions:s.dimension?x=[s.dimension]:g&&g.length>0&&(x=g);const b=(x==null?void 0:x[0])||void 0,v=ga({bodyWidth:s.viewportWidth||f,bodyHeight:s.viewportHeight||y,dimension:b,codeyamRoot:m});let N=null;if(!l){if(s.pageFilePath)N=s.pageFilePath;else if(s.url){const{scanPageFilePaths:q}=await Promise.resolve().then(()=>Kx),U=Ce()||process.cwd(),{allFiles:z}=q(U);if(N=Kd(s.url,z),!N){const W=await import("fs"),V=await import("path"),ae=["src/App.tsx","src/App.jsx","src/app/App.tsx","src/popup/App.tsx","src/pages/index.tsx","src/pages/index.jsx","src/routes/index.tsx","app/root.tsx"];for(const pe of ae)if(W.existsSync(V.join(U,pe))){N=pe;break}}}}let w=null,C=null;const S=c||N;if(S)try{await Je();const U=(await Xe({})||[]).filter(V=>V.filePath===S),W=U.find(V=>{var ae,pe;return((ae=V.metadata)==null?void 0:ae.notExported)===!1&&((pe=V.metadata)==null?void 0:pe.namedExport)===!1})||U[0];W&&(w=W.sha)}catch{}const k=s.type==="application"||s.type==="user";if(!w&&k&&S){const q=Ce()||process.cwd(),U=dy({lookupFilePath:S,scenarioType:s.type||null,projectRoot:q});if(!U.valid)return Response.json({error:U.error},{status:400});if(U.needsAnalysis)try{const{runAnalysisForEntities:z}=await import("./analysisRunner-BKMsxwqe.js");await z({projectRoot:q,filePaths:[S],onlyDataStructure:!0});try{const V=(await Xe({})||[]).filter(xe=>xe.filePath===S),pe=V.find(xe=>{var ie,me;return((ie=xe.metadata)==null?void 0:ie.notExported)===!1&&((me=xe.metadata)==null?void 0:me.namedExport)===!1})||V[0];pe&&(w=pe.sha)}catch{}if(w)try{const W=await Xe({});await py(h,(W||[]).map(V=>{var ae,pe;return{sha:V.sha,name:V.name,filePath:V.filePath||"",isDefaultExport:((ae=V.metadata)==null?void 0:ae.notExported)===!1&&((pe=V.metadata)==null?void 0:pe.namedExport)===!1}}))}catch{}}catch(z){console.warn(`[editor-register-scenario] Auto analyze-imports failed for ${S}: ${z.message}`)}}l?C=l:N&&N.startsWith("app/")?C=Lt(jt(N)):s.url&&(C=yt(s.url));const j=await ly(h,{projectId:u.id,name:o,description:i||null,componentName:l||null,componentPath:c||null,url:s.url||null,type:s.type||null,viewportWidth:v.width,viewportHeight:v.height,dimensions:x,screenshotPaths:null,pageFilePath:N,entitySha:w,displayName:C}),_=j.scenarioId;if(j.cleanedUpIds.length>0&&(cy(m,j.cleanedUpIds),console.log(`[editor-register-scenario] Cleaned up ${j.cleanedUpIds.length} duplicate(s) for "${o}"`)),s.seedFrom&&!s.seed){const q=await Ol(m,h,s.seedFrom);q?(s.seed=q,s.type||(s.type="application"),console.log(`[editor-register-scenario] Resolved seed data from "${s.seedFrom}"`)):console.warn(`[editor-register-scenario] seedFrom "${s.seedFrom}" not found — no seed data will be used`)}else if(s.seedFrom&&s.seed){const q=await Ol(m,h,s.seedFrom);q&&(s.seed=zl(q,s.seed),console.log(`[editor-register-scenario] Merged seed data: base from "${s.seedFrom}", overlay from registration`))}const F=s.type==="application"||s.type==="user",M=new Date().toISOString(),$={name:o,description:i||null,componentName:l||null,componentPath:c||null,url:s.url||null,type:s.type||(F?null:"component"),screenshotPath:null,viewportWidth:v.width,viewportHeight:v.height,dimensions:x,screenshotPaths:null,pageFilePath:N,entitySha:w,displayName:C,createdAt:M,updatedAt:M},O={};if(F&&s.seed){let q=s.seed;if(s.type==="user"&&s.baseScenario)try{const z=H.join(m,".codeyam","editor-scenarios",`${s.baseScenario}.json`),W=await Ae.readFile(z,"utf-8"),V=JSON.parse(W);V.seed&&(q=zl(V.seed,s.seed),console.log(`[editor-register-scenario] Merged seed data from base scenario ${s.baseScenario}`))}catch(z){console.warn(`[editor-register-scenario] Could not read base scenario ${s.baseScenario}: ${z instanceof Error?z.message:z}`)}O.type=s.type,O.seed=q,s.externalApis&&(O.externalApis=s.externalApis),s.session&&(O.session=s.session),s.auth&&(O.auth=s.auth),s.localStorage&&(O.localStorage=s.localStorage);const U=H.join(m,".codeyam","editor-scenarios");await Ae.mkdir(U,{recursive:!0}),await Ae.writeFile(H.join(U,`${_}.seed.json`),JSON.stringify(q,null,2))}else(s.mockData||s.localStorage)&&(s.mockData&&Object.assign(O,s.mockData),s.localStorage&&(O.localStorage=s.localStorage));let D=null;if(F&&!s.seed&&Yr(m)){const U=H.join(m,".codeyam","editor-scenarios",`${_}.json`);let z=!1;try{z=!!JSON.parse(await Ae.readFile(U,"utf-8")).seed}catch{}z||(D='WARNING: This application scenario has no seed data. A seed adapter exists — include "seed":{...} in registration so the page has database rows to render. Without seed data, the page will likely be empty.',console.warn(`[editor-register-scenario] ${D}`))}Ax(m,_,$,O);let T=null;if(F&&s.seed){const q=Yr(m);if(q){const U=H.join(m,".codeyam","editor-scenarios",`${_}.seed.json`);console.log(`[editor-register-scenario] Running seed adapter: ${q}`);const z=await pi(q,U);if(T={success:z.success,error:z.error},z.success){console.log(`[editor-register-scenario] Seed adapter completed in ${z.durationMs}ms`);const W=z.sessionCookies&&z.sessionCookies.length>0,V=z.externalApis&&Object.keys(z.externalApis).length>0;if(W||V)try{const ae=H.join(m,".codeyam","editor-scenarios",`${_}.json`),pe=JSON.parse(await Ae.readFile(ae,"utf-8"));W&&(pe.sessionCookies=z.sessionCookies),V&&(pe.externalApis={...pe.externalApis,...z.externalApis}),await Ae.writeFile(ae,JSON.stringify(pe,null,2)),console.log("[editor-register-scenario] Saved seed adapter auth data to scenario")}catch(ae){console.warn(`[editor-register-scenario] Failed to save seed adapter auth data: ${ae}`)}}else console.warn(`[editor-register-scenario] Seed adapter failed: ${z.error}`)}else console.warn(`[editor-register-scenario] No seed adapter found at ${m}/.codeyam/seed-adapter.ts`),T={success:!1,error:"No seed adapter found. Create .codeyam/seed-adapter.ts to use seed-based scenarios."}}ft.notifyChange("scenario"),console.log(`[editor-register-scenario] Starting auto-capture for scenario "${o}" (id: ${_})`);const B=s.url&&s.url.startsWith("/"),Y=!s.url||B?await fi():null,I=Kl(),L=di(s.url||null,Y,I);console.log(`[editor-register-scenario] Capture URL resolution: explicit=${s.url||"none"}, isPath=${B}, proxy=${Y||"none"}, devServer=${I||"none"} → using ${L||"none"}`);let P=null,R=null,E=[],J=null,K=null,Q={};if(L){const q=Mt(o),U=await ya({scenarioId:_,scenarioSlug:q,scenarioType:s.type||void 0,projectRoot:m});Tn(),!T&&U.seedResult&&(T=U.seedResult),console.log(`[editor-register-scenario] Active scenario set to "${q}" (${_}), type=${U.type}, seeded=${U.seeded}, seedResult=${JSON.stringify(U.seedResult??null)}, cache invalidated`),await new Promise(me=>setTimeout(me,300));const z=(t=s.url)!=null&&t.startsWith("/")?`${Kl()||"http://localhost:3113"}${s.url}`:L;for(let me=0;me<5;me++){try{const we=await fetch(z,{method:"GET",signal:AbortSignal.timeout(3e3)});if(we.status<500)break;console.log(`[editor-register-scenario] Route returned ${we.status}, waiting for HMR (attempt ${me+1}/5)...`)}catch{console.log(`[editor-register-scenario] Route not reachable, waiting for HMR (attempt ${me+1}/5)...`)}await new Promise(we=>setTimeout(we,2e3))}const W=H.join(m,".codeyam","editor-scenarios","screenshots");await Ae.mkdir(W,{recursive:!0});const V=yi(import.meta.url),ae=await xi(V,m);console.log(`[editor-register-scenario] Capture script: ${ae}`);const pe=ui(m),xe=x&&x.length>0?x:[null];Q={};let ie=null;for(let me=0;me<xe.length;me++){const we=xe[me];let Te=v;if(we){const ge=pe[we];ge!=null&&ge.width&&(ge!=null&&ge.height)&&(Te={width:ge.width,height:ge.height})}const Ne=we?Zd(we):null,_e=Ne&&xe.length>1?`${_}--${Ne}.png`:`${_}.png`,Z=H.join(W,_e),he=`screenshots/${_e}`;me===0&&(K=Te,ie=Z);const te=JSON.stringify({url:L,outputPath:Z,viewportWidth:Te.width,viewportHeight:Te.height,...l?{selector:"#codeyam-capture"}:{}});console.log(`[editor-register-scenario] Capture ${we||"default"}: ${Te.width}×${Te.height} → ${_e}`);const se=Date.now(),ce=await bi(ae,te,m),je=Date.now()-se;console.log(`[editor-register-scenario] Capture ${we||"default"} ${ce.success?"succeeded":"FAILED"} in ${je}ms`),ce.success||(console.warn(`[editor-register-scenario] Capture stdout: ${ce.output.slice(0,500)}`),console.warn(`[editor-register-scenario] Capture stderr: ${(ce.error||"").slice(0,500)}`)),me===0&&(E=vu(ce.output),J=_x(ce.output),await wu(m,_,o,E),E.length>0&&console.warn(`[editor-register-scenario] ${E.length} client-side error(s) detected:`,E)),ce.success?(we&&(Q[we]=he),me===0&&(P=he)):me===0&&(R=ce.error||"Unknown capture error",console.warn(`[editor-register-scenario] Screenshot capture failed (non-blocking): ${R}`))}if(P){try{await h.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}const me={screenshot_path:P,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")};Object.keys(Q).length>0&&(me.screenshot_paths=JSON.stringify(Q)),await h.updateTable("editor_scenarios").set(me).where("id","=",_).execute(),ft.notifyChange("scenario"),ie&&await Jx(m,o,ie)}}else console.log("[editor-register-scenario] Skipping screenshot — no capture URL available (dev server not running?)");if(console.log(`[editor-register-scenario] Done: scenario="${o}", screenshot=${P?"captured":"skipped"}`),L&&P)try{const q=Ce()||process.cwd(),U=H.join(q,".codeyam","editor-step.json");let z=null;try{const W=G.readFileSync(U,"utf8");z=JSON.parse(W).featureStartedAt||null}catch{}if(z){const W=Qr(z),V=await h.selectFrom("editor_scenarios").selectAll().where("project_id","=",u.id).orderBy("created_at","asc").execute(),ae=_t(V,xe=>`${xe.name}::${xe.url||"/"}`),pe=fr();if(pe.length>0){let xe=!1;try{const{execSync:se}=await import("child_process"),ce=se("git rev-list --count HEAD",{cwd:q,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();xe=parseInt(ce,10)<=1}catch{xe=!0}const ie=Gd(pe,xe),me={},we=H.join(q,"app");if(G.existsSync(we)){const se=(ce,je)=>{for(const ge of G.readdirSync(ce,{withFileTypes:!0}))if(ge.name!=="isolated-components"){if(ge.isDirectory())se(H.join(ce,ge.name),je?`${je}/${ge.name}`:ge.name);else if(ge.name==="page.tsx"||ge.name==="page.js"){const ze=yt(je?`/${je}`:"/");me[ze]=je?`app/${je}/${ge.name}`:`app/${ge.name}`}}};se(we,"")}let Te=[];try{await Je(),Te=await Xe({})||[]}catch{}const Ne=ae.map(se=>({componentName:se.component_name||null,componentPath:se.component_path||null,pageFilePath:se.page_file_path??null,url:se.url??null,displayName:se.display_name??null})),_e=qd(Ne,me,Te),Z=Qd(ie,_e),he=ae.filter(se=>se.created_at<W),te=new Map;for(const se of he){const ce=Gt({componentName:se.component_name,pageFilePath:se.page_file_path,url:se.url});((r=Z[ce])==null?void 0:r.status)==="impacted"&&te.set(ce,se)}if(te.size>0){console.log(`[editor-register-scenario] Recapturing ${te.size} impacted older scenario(s): ${[...te.keys()].join(", ")}`);const{recaptureScenarios:se}=await Promise.resolve().then(()=>Sb),ce=[...te.values()].map(ge=>({id:ge.id,name:ge.name,url:ge.url,component_name:ge.component_name,dimensions:ge.dimensions,viewport_width:ge.viewport_width,viewport_height:ge.viewport_height}));await se({scenarios:ce,codeyamRoot:m,proxyUrl:Y,devUrl:I,db:h,importMetaUrl:import.meta.url});const je=H.join(m,".codeyam","active-scenario.json");await Ae.writeFile(je,JSON.stringify({scenarioId:_,scenarioSlug:Mt(o),type:s.type||null,timestamp:new Date().toISOString()})),Tn(),ft.notifyChange("scenario")}}}}catch(q){console.warn(`[editor-register-scenario] Recapture of impacted scenarios failed (non-blocking): ${q instanceof Error?q.message:q}`)}try{const q=new Date().toISOString(),U=Object.keys(Q).length>0?Q:null;Su(m,_,{name:o,description:i||null,componentName:l||null,componentPath:c||null,url:s.url||null,type:s.type||null,screenshotPath:P||null,viewportWidth:v.width,viewportHeight:v.height,dimensions:x,screenshotPaths:U,pageFilePath:N,createdAt:q,updatedAt:q})}catch(q){console.warn(`[editor-register-scenario] Failed to update scenario metadata (non-blocking): ${q instanceof Error?q.message:q}`)}try{$x({dimension:b,viewport:v,refreshPath:s.url||void 0,scenarioId:_})}catch{}return new Response(JSON.stringify({success:!0,scenario:{id:_,name:o,description:i,componentName:l||null,componentPath:c||null,screenshotPath:P,url:s.url||null,type:s.type||null,viewportWidth:v.width,viewportHeight:v.height,dimensions:x,screenshotPaths:Object.keys(Q).length>0?Q:null},updated:!j.isNew,screenshotCaptured:P!==null,capturedViewport:K,captureError:R,clientErrors:E,...J?{visibleText:J}:{},...T?{seedResult:T}:{},...D?{missingSeedWarning:D}:{}}),{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 Vx=Object.freeze(Object.defineProperty({__proto__:null,action:Hx},Symbol.toStringTag,{value:"Module"}));function Si(e){const t={},r=[],s=H.join(e,"app");if(!G.existsSync(s))return{map:t,allFiles:r};const a=c=>c.split("/").filter(p=>!p.startsWith("(")).join("/"),o=new Set(["_layout.tsx","_layout.ts","_layout.js","layout.tsx","layout.ts","layout.js"]),i=new Set([".tsx",".ts",".jsx",".js"]),l=(c,p)=>{for(const u of G.readdirSync(c,{withFileTypes:!0}))if(u.name!=="isolated-components")if(u.isDirectory())l(H.join(c,u.name),p?`${p}/${u.name}`:u.name);else if(u.name==="page.tsx"||u.name==="page.js"){const h=p?`app/${p}/${u.name}`:`app/${u.name}`;r.push(h);const m=a(p);t[yt(m?`/${m}`:"/")]=h}else{if(o.has(u.name))continue;{const h=H.extname(u.name);if(!i.has(h))continue;const m=H.basename(u.name,h),f=p?`app/${p}/${u.name}`:`app/${u.name}`,y=a(p);let g;m==="index"?g=y?`/${y}`:"/":g=y?`/${y}/${m}`:`/${m}`,r.push(f);const x=yt(g);t[x]||(t[x]=f)}}};return l(s,""),{map:t,allFiles:r}}function _u(e){try{const t=De("git rev-list --count HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();return parseInt(t,10)<=1}catch{return!0}}function Eu(e){try{const t=H.join(e,".codeyam","editor-step.json"),r=G.readFileSync(t,"utf8");return JSON.parse(r).featureStartedAt||null}catch{return null}}function Ca(e){try{const t=H.join(e,".codeyam","editor-step.json"),r=G.readFileSync(t,"utf8");return JSON.parse(r).feature||null}catch{return null}}function Ci(e){try{const t=H.join(e,".codeyam","editor-step.json"),r=G.readFileSync(t,"utf8"),s=JSON.parse(r);return typeof s.step=="number"&&s.label?{step:s.step,label:s.label}:null}catch{return null}}function ki(e){try{const t=H.join(e,".codeyam","editor-step.json"),r=G.readFileSync(t,"utf8"),s=JSON.parse(r);return Array.isArray(s.appFormats)?s.appFormats:null}catch{return null}}function ju(e){try{const t=H.join(e,".codeyam","claude-session-id.txt");return G.readFileSync(t,"utf8").trim()||null}catch{return null}}function _i(e){try{const t=H.join(e,".codeyam","editor-user-prompt.txt");return G.readFileSync(t,"utf8").trim()||null}catch{return null}}function Au(e){const t=H.join(e,".codeyam","active-scenario.json");try{return G.existsSync(t)&&JSON.parse(G.readFileSync(t,"utf-8")).scenarioId||null}catch{return null}}const Kx=Object.freeze(Object.defineProperty({__proto__:null,detectFirstFeature:_u,readEditorAppFormats:ki,readEditorFeature:Ca,readEditorSessionId:ju,readEditorStep:Ci,readEditorUserPrompt:_i,readFeatureStartedAt:Eu,readSavedActiveScenarioId:Au,scanPageFilePaths:Si},Symbol.toStringTag,{value:"Module"}));async function gr(e){const{projectRoot:t,scenarioInputs:r,glossaryInputs:s}=e,o=(e.precomputedPageFilePaths??Si(t)).map,i=new Set(Object.keys(o)),l=e.precomputedGitFiles??fr();if(l.length===0)return{entityChangeStatus:{},pageEntityNames:i};const c=_u(t),p=Gd(l,c);let u=[];if(e.precomputedEntities)u=e.precomputedEntities;else try{await Je(),u=await Xe({})||[]}catch{}const h=qd(r,o,u);let m=h;if(s&&s.length>0){const y=new Set(h.map(x=>x.name)),g=K0(s,y);m=[...h,...g]}return{entityChangeStatus:Qd(p,m),pageEntityNames:i}}function Gx(e,t,r,s){const a=s?s.replace("T"," ").replace(/\.\d{3}Z$/,""):null,o=[],i=[],l=new Set;for(const u of e){const h=Gt({componentName:u.component_name,pageFilePath:u.page_file_path,url:u.url});if(!h)continue;const m=t[h];if(!m||u.component_name)continue;const f=u.created_at||"",y=u.updated_at||"";(a?f>=a||y>=a:!0)?(i.push({name:u.name,url:u.url,entityName:h}),l.add(h)):o.push({name:u.name,url:u.url,entityName:h,changeStatus:m.status,lastCaptured:f})}const c=[];for(const[u,h]of Object.entries(t)){if(!r.has(u)||l.has(u))continue;o.some(f=>f.entityName===u)||c.push({entityName:u,changeStatus:h.status})}const p=o.length===0&&c.length===0;return{staleScenarios:o,freshScenarios:i,uncoveredPages:c,pass:p}}async function qx(){const e=Ce()||process.cwd(),t=await Ye();if(!t)return Response.json({error:"No project configured"},{status:400});const r=H.join(e,".codeyam","editor-step.json");let s=null;try{const f=G.readFileSync(r,"utf8");s=JSON.parse(f).featureStartedAt||null}catch{}const{project:a}=await Re(t),i=await $e().selectFrom("editor_scenarios").select(["id","name","component_name","component_path","page_file_path","url","type","created_at","updated_at","display_name"]).where("project_id","=",a.id).orderBy("created_at","asc").execute(),l=_t(i,f=>`${f.name}::${f.url||"/"}`),c=l.map(f=>({componentName:f.component_name||null,componentPath:f.component_path||null,pageFilePath:f.page_file_path??null,url:f.url??null,displayName:f.display_name??null}));let p={},u=new Set;try{const f=await gr({projectRoot:e,scenarioInputs:c});p=f.entityChangeStatus,u=f.pageEntityNames}catch{}if(Object.keys(p).length===0)return Response.json({staleScenarios:[],uncoveredPages:[],freshScenarios:[],pass:!0,note:"No entity change data available — cannot determine coverage."});const h=l.map(f=>({name:f.name,component_name:f.component_name,page_file_path:f.page_file_path??null,url:f.url??null,created_at:f.created_at||"",updated_at:f.updated_at||null})),m=Gx(h,p,u,s);return Response.json(m)}const Qx=Object.freeze(Object.defineProperty({__proto__:null,loader:qx},Symbol.toStringTag,{value:"Module"}));function Zx({executionFlows:e,selections:t,onChange:r,disabled:s=!1}){const a=oe(i=>t.some(l=>l.flowId===i),[t]),o=oe(i=>{a(i.id)?r(t.filter(l=>l.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,a]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const l=a(i.id),c=i.usedInScenarios.length>0;return d("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[d("label",{className:"flex items-start gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:l,onChange:()=>o(i),disabled:s,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!c&&n("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&n("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&n("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),l&&i.requiredValues.length>0&&d("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[n("span",{className:"text-gray-700 font-medium",children:"Required values:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((p,u)=>d("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:p.attributePath})," ",n("span",{className:"text-gray-400",children:p.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:p.value})]},u))})]})]},i.id)})})}function Ei(e,t){const r=(e||[]).map(c=>({...c,usedInScenarios:[]})),s=new Map;r.forEach(c=>{s.set(c.id,c)});const a=[];t.forEach(c=>{var u;const p=((u=c.metadata)==null?void 0:u.coveredFlows)||[];p.forEach(h=>{const m=s.get(h);m&&m.usedInScenarios.push({id:c.id||"",name:c.name})}),a.push({scenario:c,coveredFlowIds:p})});const o=r.length,i=r.filter(c=>c.usedInScenarios.length>0).length,l=o>0?i/o*100:0;return{executionFlows:r,totalFlows:o,coveredFlows:i,coveragePercentage:l,scenariosWithFlows:a}}function Xx(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const eb=({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 tb({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await aa(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===sa);if(!a)throw new Response("Default scenario not found",{status:404});const o=await Ye();return re({analysis:s,defaultScenario:a,entity:s.entity,entitySha:t,projectSlug:o})}function nb(){var L;const{analysis:e,defaultScenario:t,entity:r,entitySha:s,projectSlug:a}=ot(),o=Dt(),{iframeRef:i}=gi(),[l,c]=A(""),[p,u]=A(400),[h,m]=A(!1),[f,y]=A(!1),[g,x]=A(!1),[b,v]=A(null),[N,w]=A(null),[C,S]=A([]),k=le(()=>{var R;return!((R=e==null?void 0:e.metadata)!=null&&R.executionFlows)||!(e!=null&&e.scenarios)?[]:Ei(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:j,isStarting:_,isLoading:F,showIframe:M,iframeKey:$,onIframeLoad:O}=In({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}),D=oe(async()=>{var P,R,E,J;if(!l.trim()&&C.length===0){v("Please describe how you want to change the scenario or select execution flows");return}y(!0),v(null),w("Generating scenario with AI...");try{const K=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,existingScenarios:e.scenarios,scenariosDataStructure:(P=e.metadata)==null?void 0:P.scenariosDataStructure,flowSelections:C.length>0?C:void 0})}),Q=await K.json();if(!K.ok||!Q.success)throw new Error(Q.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",Q.data);const q=Q.data;if(!q.name||!q.data)throw new Error("AI response missing required fields (name or data)");w("Saving new scenario..."),x(!0);const U={name:q.name,description:q.description||l,metadata:{data:q.data,interactiveExamplePath:(R=t.metadata)==null?void 0:R.interactiveExamplePath}},z=[...e.scenarios||[],U],W=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:z})}),V=await W.json();if(!W.ok||!V.success)throw new Error(V.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",V);const ae=(J=(E=V.analysis)==null?void 0:E.scenarios)==null?void 0:J.find(pe=>pe.name===q.name);if(!(ae!=null&&ae.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),w("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${s}`),1e3);return}if(j){w("Capturing screenshot...");const pe=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:j,scenarioId:ae.id,projectId:e.projectId,viewportWidth:1440})}),xe=await pe.json();!pe.ok||!xe.success?(console.error("[CreateScenario] Capture failed:",xe),w("Scenario created! (Screenshot capture failed)")):w("Scenario created and captured!")}else w("Scenario created!");setTimeout(()=>{o(`/entity/${s}/scenarios/${ae.id}`)},1e3)}catch(K){console.error("[CreateScenario] Error:",K),v(K instanceof Error?K.message:String(K)),w(null)}finally{y(!1),x(!1)}},[l,C,e,t,s,j,o]),T=f||g,B=oe(()=>{m(!0)},[]),Y=oe(P=>{if(!h)return;const R=P.clientX;R>=250&&R<=600&&u(R)},[h]),I=oe(()=>{m(!1)},[]);return ne(()=>(h?(document.addEventListener("mousemove",Y),document.addEventListener("mouseup",I)):(document.removeEventListener("mousemove",Y),document.removeEventListener("mouseup",I)),()=>{document.removeEventListener("mousemove",Y),document.removeEventListener("mouseup",I)}),[h,Y,I]),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(ke,{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:((L=e==null?void 0:e.scenarios)==null?void 0:L.length)||0})]})}),n(ke,{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(ke,{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(ke,{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(ke,{to:`/entity/${s}/history`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"History"})]})]})}),d("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[d("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${p}px`},children:[d("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select execution flows and/or describe how you'd like to change it."})]}),k.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"," ",C.length>0&&d("span",{className:"text-blue-600",children:["(",C.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(Zx,{executionFlows:k,selections:C,onChange:S,disabled:T})})]}),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:P=>c(P.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:T})]}),d("div",{className:"space-y-2",children:[n("button",{onClick:()=>void D(),disabled:T||!l.trim()&&C.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:T?"Creating...":"Create Scenario"}),N&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:N}),b&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:b})]})]}),d("div",{onMouseDown:B,style:{width:"20px",position:"absolute",top:0,left:`${p-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[n("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:h?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),n("div",{style:{position:"absolute",top:"50%",left:"10px",transform:"translate(-50%, -50%)",width:"8px",height:"40px",background:"#fff",border:"1px solid rgba(0,0,0,0.15)",borderRadius:"4px",cursor:"col-resize"}})]}),n("main",{className:"flex-1 overflow-auto flex items-center justify-center min-w-0",style:{backgroundImage:`
334
- linear-gradient(45deg, #ebebeb 25%, transparent 25%),
335
- linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
336
- linear-gradient(45deg, transparent 75%, #ebebeb 75%),
337
- linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
338
- `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:n(Sa,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:j,isStarting:_,isLoading:F,showIframe:M,iframeKey:$,onIframeLoad:O,projectSlug:a,defaultWidth:1440,defaultHeight:900})})]})]})}const rb=et(function(){return n(Na,{children:n(nb,{})})}),sb=Object.freeze(Object.defineProperty({__proto__:null,default:rb,loader:tb,meta:eb},Symbol.toStringTag,{value:"Module"})),ab=hi;async function ob({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioId:r,url:s,viewportWidth:a,viewportHeight:o}=t;if(!r)return new Response(JSON.stringify({error:"scenarioId is required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=await Ye();if(!i)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:l}=await Re(i),c=$e(),p=await c.selectFrom("editor_scenarios").selectAll().where("id","=",r).where("project_id","=",l.id).executeTakeFirst();if(!p)return new Response(JSON.stringify({error:"Scenario not found"}),{status:404,headers:{"Content-Type":"application/json"}});const u=s??p.url??null,h=u&&u.startsWith("/"),m=!u||h?await fi():null,f=ab(),y=di(u,m,f);if(console.log(`[editor-capture-scenario] URL resolution: explicit=${s||"none"}, db=${p.url||"none"}, proxy=${m||"none"}, devServer=${f||"none"} → captureUrl=${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 "${p.name}" (id: ${r}), url: ${y}`);const g=process.env.CODEYAM_ROOT_PATH||process.cwd(),x=Mt(p.name);await ya({scenarioId:r,scenarioSlug:x,scenarioType:p.type||void 0,projectRoot:g}),Tn(),console.log(`[editor-capture-scenario] Active scenario set to "${x}", cache invalidated`),await new Promise(M=>setTimeout(M,300));const b=H.join(g,".codeyam","editor-scenarios","screenshots");await Ae.mkdir(b,{recursive:!0});const v=yi(import.meta.url),N=await xi(v,g);console.log(`[editor-capture-scenario] Capture script: ${N}`);let w;const C=p;if(t.dimensions&&t.dimensions.length>0)w=t.dimensions;else if(C.dimensions)try{const M=typeof C.dimensions=="string"?JSON.parse(C.dimensions):C.dimensions;w=Array.isArray(M)&&M.length>0?M:[null]}catch{w=[null]}else w=[null];const S=ui(g);let k=null;const j={};let _=[],F=null;for(let M=0;M<w.length;M++){const $=w[M];let O;$&&S[$]?O=S[$]:O=ga({bodyWidth:a||C.viewport_width||void 0,bodyHeight:o||C.viewport_height||void 0,dimension:$||void 0,codeyamRoot:g});const D=$?Zd($):null,T=D&&w.length>1?`${r}--${D}.png`:`${r}.png`,B=H.join(b,T),Y=`screenshots/${T}`,I=JSON.stringify({url:y,outputPath:B,viewportWidth:O.width,viewportHeight:O.height,...p.component_name?{selector:"#codeyam-capture"}:{}});console.log(`[editor-capture-scenario] Capture ${$||"default"}: ${O.width}×${O.height} → ${T}`);const L=Date.now(),P=await bi(N,I,g),R=Date.now()-L;if(console.log(`[editor-capture-scenario] Capture ${$||"default"} ${P.success?"succeeded":"FAILED"} in ${R}ms`),!P.success){console.warn(`[editor-capture-scenario] Capture stdout: ${P.output.slice(0,500)}`),console.warn(`[editor-capture-scenario] Capture stderr: ${(P.error||"").slice(0,500)}`),M===0&&(F=P.error||"Unknown capture error");continue}if(M===0){k=Y;const E=vu(P.output);_=E,await wu(g,r,p.name,E)}$&&(j[$]=Y)}if(!k&&F)return new Response(JSON.stringify({error:"Failed to capture screenshot",details:F}),{status:500,headers:{"Content-Type":"application/json"}});if(k){try{await c.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}const M={screenshot_path:k,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")};Object.keys(j).length>0&&(M.screenshot_paths=JSON.stringify(j)),await c.updateTable("editor_scenarios").set(M).where("id","=",r).execute()}return _.length>0&&console.warn(`[editor-capture-scenario] ${_.length} client-side error(s) detected:`,_),ft.notifyChange("scenario"),new Response(JSON.stringify({success:!0,screenshotPath:k,screenshotPaths:Object.keys(j).length>0?j:null,clientErrors:_}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-capture-scenario] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const ib=Object.freeze(Object.defineProperty({__proto__:null,action:ob},Symbol.toStringTag,{value:"Module"}));async function lb({request:e,params:t}){const r=t["*"];if(!r)return new Response("Image path is required",{status:400});const s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=ee.join(s,".codeyam","editor-scenarios","screenshots",r),o=ee.resolve(a),i=ee.resolve(ee.join(s,".codeyam","editor-scenarios","screenshots"));if(!o.startsWith(i))return new Response("Invalid path",{status:403});try{const l=await Pe.stat(a),c=`"${l.mtimeMs}-${l.size}"`;if(e.headers.get("If-None-Match")===c)return new Response(null,{status:304,headers:{ETag:c,"Cache-Control":"public, max-age=300"}});const u=await Pe.readFile(a),h=ee.extname(a).toLowerCase(),m=h===".png"?"image/png":h===".jpg"||h===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(u,{status:200,headers:{"Content-Type":m,"Cache-Control":"public, max-age=300",ETag:c}})}catch{return new Response("Image not found",{status:404})}}const cb=Object.freeze(Object.defineProperty({__proto__:null,loader:lb},Symbol.toStringTag,{value:"Module"}));async function db({params:e}){const t=e["*"];if(!t)return new Response("Image path is required",{status:400});const r=process.env.CODEYAM_ROOT_PATH||process.cwd(),s=ee.join(r,".codeyam","journal","screenshots",t),a=ee.resolve(s),o=ee.resolve(ee.join(r,".codeyam","journal","screenshots"));if(!a.startsWith(o))return new Response("Invalid path",{status:403});try{const i=await Pe.readFile(s),l=ee.extname(s).toLowerCase(),c=l===".png"?"image/png":l===".jpg"||l===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(i,{status:200,headers:{"Content-Type":c,"Cache-Control":"no-store"}})}catch{return new Response("Image not found",{status:404})}}const ub=Object.freeze(Object.defineProperty({__proto__:null,loader:db},Symbol.toStringTag,{value:"Module"})),pb=["JSX","React","Element","ReactNode"],hb=new Set(["page.tsx","page.ts","index.tsx","index.ts"]);function mb(e){if(e.returnType&&pb.some(t=>e.returnType.includes(t)))return!0;if(e.filePath){const t=e.filePath.split("/").pop()||"";if(hb.has(t))return!0}return!1}function fb(e){const t=[],r=[];for(const s of e)mb(s)?t.push(s):r.push(s);return{components:t,functions:r}}function so({components:e,functions:t,scenarioCounts:r,testFileExistence:s,testResults:a,clientErrors:o,totalScenarioCounts:i,entityChangeStatus:l,analysisFailedEntities:c,testCaseCounts:p}){const u=e.map(k=>{const j=r[k.name]||0,_=(i==null?void 0:i[k.name])||0,F=l==null?void 0:l[k.name],M=o==null?void 0:o[k.name],$=j>0&&M&&M.length>0;let O;c!=null&&c.has(k.name)?O="analysis_failed":j===0?F&&_>0?O="needs_recapture":O="missing":$?O="has_errors":O="ok";let D;if(O==="missing"){const T=k.filePath.split("/").pop()||"";T==="layout.tsx"||T==="layout.ts"?D=`This is a layout file — register an app-level scenario with pageFilePath instead of componentName: codeyam editor register '{"name":"${k.name} - Default","pageFilePath":"${k.filePath}","url":"/<route>","dimensions":["Desktop"]}'`:T==="page.tsx"||T==="page.ts"?D=`This is a page file — register an app-level scenario with pageFilePath: codeyam editor register '{"name":"${k.name} - Default","pageFilePath":"${k.filePath}","url":"/<route>","dimensions":["Desktop"]}'`:D=`Register a component scenario via an isolation route: codeyam editor isolate ${k.name} then codeyam editor register '{"name":"${k.name} - Default","componentName":"${k.name}","url":"/isolated-components/${k.name}?s=Default","dimensions":["Desktop"]}'`}else O==="needs_recapture"?D=`This component's code or dependencies changed — recapture existing scenarios to update screenshots: codeyam editor recapture ${k.name}`:O==="analysis_failed"&&(D="Analysis failed for this component (likely timed out due to complex dependencies). The component has partial data but may be missing some dependency schemas. Try re-analyzing: codeyam editor analyze-imports");return{name:k.name,filePath:k.filePath,scenarioCount:O==="needs_recapture"?_:j,status:O,...$?{clientErrors:M}:{},...D?{hint:D}:{}}}),h=t.map(k=>{if(!(k.testFile?s[k.testFile]??!1:!1)){const $=k.testFile?void 0:k.filePath.replace(/\.tsx?$/,".test.ts");return{name:k.name,filePath:k.filePath,testFile:k.testFile,testFileExists:!1,status:"missing",...$?{suggestedTestFile:$}:{}}}const _=k.testFile&&a?a[k.testFile]:void 0;if(!_)return{name:k.name,filePath:k.filePath,testFile:k.testFile,testFileExists:!0,status:"ok"};let F;!_.passing&&_.errorMessage?F="runner_error":_.passing?_.hasEntityNameDescribe?F="ok":F="name_mismatch":F="failing";let M;return F==="name_mismatch"?M=`Tests pass but won't show in the CodeYam UI. Add a top-level describe("${k.name}", ...) block in ${k.testFile}`:F==="runner_error"&&_.errorMessage&&(M=`Test runner crashed (not a test failure): ${_.errorMessage}`),{name:k.name,filePath:k.filePath,testFile:k.testFile,testFileExists:!0,testsPassing:_.passing,testsVisibleInUi:_.hasEntityNameDescribe,status:F,..._.errorMessage?{errorMessage:_.errorMessage}:{},...M?{hint:M}:{},...(p==null?void 0:p[k.name])!==void 0?{testCaseCount:p[k.name]}:{}}}),m=u.filter(k=>k.status==="ok").length,f=u.filter(k=>k.status==="has_errors").length,y=u.filter(k=>k.status==="missing").length,g=u.filter(k=>k.status==="needs_recapture").length,x=u.filter(k=>k.status==="analysis_failed").length,b=h.filter(k=>k.status==="ok").length,v=h.filter(k=>k.status==="failing").length,N=h.filter(k=>k.status==="runner_error").length,w=h.filter(k=>k.status==="name_mismatch").length,C=h.filter(k=>k.status==="missing").length,S=h.filter(k=>k.status==="ok"&&k.testCaseCount!==void 0&&k.testCaseCount<3).length;return{components:u,functions:h,summary:{totalComponents:u.length,componentsOk:m,componentsMissing:y,componentsWithErrors:f,componentsNeedingRecapture:g,componentsAnalysisFailed:x,totalFunctions:h.length,functionsOk:b,functionsMissing:C,functionsFailing:v,functionsRunnerError:N,functionsNameMismatch:w,functionsThinCoverage:S,allPassing:y===0&&f===0&&x===0&&v===0&&N===0&&w===0&&C===0}}}function gb({featureStartedAt:e,entityChangeStatus:t}){return t&&Object.keys(t).length>0?{featureStartedAt:e,entityChangeStatus:t}:{featureStartedAt:null,entityChangeStatus:t}}function yb(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>!!(t[r.name]||t[r.filePath]))}async function xb(e,t,r){const a=await e.selectFrom("editor_scenarios").select(["entity_sha"]).select(e.fn.count("id").as("count")).where("project_id","=",t).where("entity_sha","is not",null).groupBy("entity_sha").execute();if(a.length===0)return[];const o=a.map(w=>w.entity_sha),i=await e.selectFrom("analyses").select("entity_sha").where("entity_sha","in",o).groupBy("entity_sha").execute(),l=new Set(i.map(w=>w.entity_sha)),c=a.filter(w=>!l.has(w.entity_sha));if(c.length===0)return[];const p=c.map(w=>w.entity_sha),u=await e.selectFrom("entities").select(["sha","name","file_path"]).where("sha","in",p).execute(),h=new Map(u.map(w=>[w.sha,w.name])),m=new Map(u.map(w=>[w.sha,w.file_path])),f=[...new Set(u.map(w=>`${w.name}::${w.file_path}`).filter(w=>!w.startsWith("::")&&!w.endsWith("::")))];let y=new Set;if(f.length>0){const w=[...new Set(u.map(S=>S.name).filter(Boolean))],C=await e.selectFrom("entities").innerJoin("analyses","analyses.entity_sha","entities.sha").select(["entities.name","entities.file_path"]).where("entities.name","in",w).groupBy(["entities.name","entities.file_path"]).execute();y=new Set(C.map(S=>`${S.name}::${S.file_path}`))}const g=c.filter(w=>{const C=w.entity_sha,S=h.get(C),k=m.get(C);if(!S)return!1;const j=`${S}::${k}`;return!y.has(j)});if(g.length===0)return[];const x=g.map(w=>w.entity_sha),b=await e.selectFrom("editor_scenarios").select(["entity_sha","component_name"]).where("project_id","=",t).where("entity_sha","in",x).where("component_name","is not",null).groupBy("entity_sha").execute(),v=new Map(b.map(w=>[w.entity_sha,w.component_name]));let N=new Set;if(r){const w=r.replace("T"," ").replace(/\.\d{3}Z$/,""),C=await e.selectFrom("editor_scenarios").select("entity_sha").where("project_id","=",t).where("entity_sha","in",x).where(S=>S.or([S("created_at",">=",w),S("updated_at",">=",w)])).groupBy("entity_sha").execute();N=new Set(C.map(S=>S.entity_sha))}return g.map(w=>{const C=w.entity_sha;return{entitySha:C,name:h.get(C)||v.get(C)||"Unknown",scenarioCount:Number(w.count),preExisting:r?!N.has(C):!1}})}async function bb(e,t,r){let s=e.selectFrom("editor_scenarios").select(["component_name","name","url"]).where("project_id","=",t).where("component_name","is not",null).where("url","is not",null);if(r){const l=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(c=>c.or([c("created_at",">=",l),c("updated_at",">=",l)]))}const o=(await s.execute()).filter(l=>l.url&&!ma(l.url));if(o.length===0)return[];const i=new Map;for(const l of o){const c=`${l.component_name}::${l.url}`,p=i.get(c);p?p.scenarioNames.push(l.name):i.set(c,{componentName:l.component_name,scenarioNames:[l.name],url:l.url})}return[...i.values()]}async function Gl(e,t,r){let s=e.selectFrom("editor_scenarios").select(["component_name"]).select(e.fn.count("id").as("count")).where("project_id","=",t).where("component_name","is not",null).groupBy("component_name");if(r){const i=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(l=>l.or([l("created_at",">=",i),l("updated_at",">=",i)]))}const a=await s.execute(),o={};for(const i of a)i.component_name&&(o[i.component_name]=Number(i.count));return o}async function ql(e,t,r){let s=e.selectFrom("editor_scenarios").select(["page_file_path"]).select(e.fn.count("id").as("count")).where("project_id","=",t).where("component_name","is",null).where("page_file_path","is not",null).groupBy("page_file_path");if(r){const i=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(l=>l.or([l("created_at",">=",i),l("updated_at",">=",i)]))}const a=await s.execute(),o={};for(const i of a)i.page_file_path&&(o[i.page_file_path]=Number(i.count));return o}async function vb(e,t,r){var i;let s=e.selectFrom("editor_scenarios").select(["component_name","component_path","page_file_path","name"]).where("project_id","=",t).where("entity_sha","is",null).where(l=>l.or([l("component_path","is not",null),l("page_file_path","is not",null)]));if(r){const l=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(c=>c.or([c("created_at",">=",l),c("updated_at",">=",l)]))}const a=await s.execute();if(a.length===0)return[];const o=new Map;for(const l of a){const c=l,p=c.component_path||c.page_file_path,u=o.get(p);if(u)u.scenarioNames.push(c.name);else{const h=c.component_name||((i=p.split("/").pop())==null?void 0:i.replace(/\.\w+$/,""))||p;o.set(p,{name:h,filePath:p,scenarioNames:[c.name]})}}return[...o.values()].map(l=>({name:l.name,filePath:l.filePath,scenarioCount:l.scenarioNames.length,scenarioNames:l.scenarioNames}))}function wb(e){const t=new Map;for(const r of e){const s=t.get(r.name);s?s.push(r):t.set(r.name,[r])}for(const[r,s]of t)s.length<=1&&t.delete(r);return t}function Pu(e){const{scenarios:t,entityChangeStatus:r}=e;if(!r||Object.keys(r).length===0)return[];const s=[];for(const a of t){if(a.updatedInSession||!a.entityName)continue;const o=r[a.entityName];o&&o.status!=="new"&&s.push({scenarioName:a.name,entityName:a.entityName,status:o})}return s}function Nb(e,t){const r={},s=new Map;for(const a of t){const o=Gt({componentName:a.componentName,pageFilePath:a.pageFilePath,url:a.url});o&&s.set(a.name,o)}for(const[,a]of Object.entries(e)){if(a.errors.length===0)continue;let o=s.get(a.scenarioName);if(!o){const i=a.scenarioName.indexOf(" - ");o=i>=0?a.scenarioName.slice(0,i):a.scenarioName}o&&(r[o]||(r[o]=[]),r[o].push(...a.errors))}return r}async function Tu(e){const{scenarios:t,codeyamRoot:r,proxyUrl:s,devUrl:a,db:o,importMetaUrl:i,onProgress:l}=e,c={recaptured:[],failed:[]};if(t.length===0)return c;const p=yi(i),u=await xi(p,r),h=H.join(r,".codeyam","editor-scenarios","screenshots");for(const m of t)try{const f=Mt(m.name);await ya({scenarioId:m.id,scenarioSlug:f,projectRoot:r}),Tn(),await new Promise(w=>setTimeout(w,300));const y=di(m.url||null,s,a);if(!y){c.failed.push({name:m.name,error:"No capture URL available"});continue}const g=H.join(h,`${m.id}.png`);let x;try{const w=m.dimensions?JSON.parse(m.dimensions):null;Array.isArray(w)&&w.length>0&&(x=w[0])}catch{}const b=ga({bodyWidth:m.viewport_width||void 0,bodyHeight:m.viewport_height||void 0,dimension:x,codeyamRoot:r}),v=JSON.stringify({url:y,outputPath:g,viewportWidth:b.width,viewportHeight:b.height,...m.component_name?{selector:"#codeyam-capture"}:{}});l==null||l(`Capturing "${m.name}"...`),console.log(`[recapture] Capturing "${m.name}" at ${b.width}x${b.height}`);const N=await bi(u,v,r);if(N.success)await o.updateTable("editor_scenarios").set({screenshot_path:`screenshots/${m.id}.png`,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")}).where("id","=",m.id).execute(),c.recaptured.push(m.name),l==null||l(`Recaptured "${m.name}"`),console.log(`[recapture] Succeeded: "${m.name}"`);else{const w=N.error||"Unknown capture error";c.failed.push({name:m.name,error:w}),l==null||l(`Failed: "${m.name}" — ${w}`),console.warn(`[recapture] Failed: "${m.name}": ${w}`)}}catch(f){const y=f instanceof Error?f.message:String(f);c.failed.push({name:m.name,error:y}),console.warn(`[recapture] Error for "${m.name}": ${y}`)}return c}const Sb=Object.freeze(Object.defineProperty({__proto__:null,recaptureScenarios:Tu},Symbol.toStringTag,{value:"Module"}));async function Cb({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ce()||process.cwd(),r=await Ye();if(!r)return Response.json({error:"No project configured"},{status:400});const{project:s}=await Re(r),a=$e(),o=process.env.CODEYAM_ROOT_PATH||process.cwd(),i=H.join(t,".codeyam","editor-step.json");let l=null;try{const C=G.readFileSync(i,"utf8");l=JSON.parse(C).featureStartedAt||null}catch{}try{await Je();const C=await Xe({})||[];await Xd(a,C.map(S=>{var k,j;return{sha:S.sha,name:S.name,filePath:S.filePath||"",isDefaultExport:((k=S.metadata)==null?void 0:k.notExported)===!1&&((j=S.metadata)==null?void 0:j.namedExport)===!1}}))}catch{}const c=await a.selectFrom("editor_scenarios").select(["id","name","component_name","component_path","page_file_path","url","display_name","dimensions","viewport_width","viewport_height","created_at","updated_at"]).where("project_id","=",s.id).orderBy("created_at","asc").execute(),p=_t(c,C=>`${C.name}::${C.url||"/"}`),u=p.map(C=>({componentName:C.component_name||null,componentPath:C.component_path||null,pageFilePath:C.page_file_path??null,url:C.url??null,displayName:C.display_name??null})),{entityChangeStatus:h}=await gr({projectRoot:t,scenarioInputs:u});if(Object.keys(h).length===0)return Response.json({type:"done",recaptured:[],failed:[],total:0,note:"No entity changes detected."});const m=l?Qr(l):null,f=p.map(C=>({name:C.name,entityName:Gt({componentName:C.component_name,pageFilePath:C.page_file_path,url:C.url}),updatedInSession:m?ci({created_at:C.created_at,updated_at:C.updated_at},m):!1})),y=Pu({scenarios:f,entityChangeStatus:h});if(y.length===0)return Response.json({type:"done",recaptured:[],failed:[],total:0,note:"All scenarios are up to date."});const g=new Set(y.map(C=>C.scenarioName)),x=p.filter(C=>g.has(C.name)).map(C=>({id:C.id,name:C.name,url:C.url,component_name:C.component_name,dimensions:C.dimensions,viewport_width:C.viewport_width,viewport_height:C.viewport_height})),b=await fi(),v=hi(),N=new Map(p.map(C=>[C.name,C])),w=new ReadableStream({async start(C){const S=j=>{C.enqueue(new TextEncoder().encode(JSON.stringify(j)+`
339
- `))};S({type:"start",total:y.length});const k=await Tu({scenarios:x,codeyamRoot:o,proxyUrl:b,devUrl:v,db:a,importMetaUrl:import.meta.url,onProgress:j=>{if(j.startsWith('Recaptured "')){const _=j.slice(12,-1);S({type:"success",name:_});const F=N.get(_);if(F)try{jx(o,F.id,`screenshots/${F.id}.png`)}catch{}}else if(j.startsWith('Failed: "')){const _=j.match(/^Failed: "(.+?)" — (.+)$/);_&&S({type:"failure",name:_[1],error:_[2]})}else if(j.startsWith('Capturing "')){const _=j.slice(11,j.indexOf('"',11));S({type:"capturing",name:_})}}});S({type:"done",recaptured:k.recaptured,failed:k.failed,total:y.length}),C.close()}});return new Response(w,{headers:{"Content-Type":"application/x-ndjson","Transfer-Encoding":"chunked"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-recapture-stale] Error:",t),Response.json({error:r},{status:500})}}const kb=Object.freeze(Object.defineProperty({__proto__:null,action:Cb},Symbol.toStringTag,{value:"Module"}));async function _b({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,name:s}=t;if(!r||!(s!=null&&s.trim()))return Response.json({error:"Missing required fields: scenarioId, name"},{status:400});const a=s.trim();await $e().updateTable("editor_scenarios").set({name:a,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")}).where("id","=",r).execute();const l=Ce()||process.cwd(),p=Ex(l).find(u=>u.id===r);return p&&Su(l,r,{...p.metadata,name:a,updatedAt:new Date().toISOString()}),Response.json({success:!0,name:a})}catch(t){return console.error("[API] Error renaming scenario:",t),Response.json({error:"Failed to rename scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const Eb=Object.freeze(Object.defineProperty({__proto__:null,action:_b},Symbol.toStringTag,{value:"Module"}));async function jb({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=t.mode||"overwrite",s=t.localStorage,a=Ce()||process.cwd(),o=ee.join(a,".codeyam"),i=ee.join(o,"active-scenario.json");if(!ue.existsSync(i))return new Response(JSON.stringify({error:"No active scenario"}),{status:400,headers:{"Content-Type":"application/json"}});const c=JSON.parse(ue.readFileSync(i,"utf-8")).scenarioId;if(!c)return new Response(JSON.stringify({error:"No active scenario ID"}),{status:400,headers:{"Content-Type":"application/json"}});const p=ee.join(o,"editor-scenarios"),u=Yr(a);let h=null;if(u){const f=ee.join(o,"tmp",`export-${Date.now()}.json`);ue.mkdirSync(ee.dirname(f),{recursive:!0});const y=await wy(u,f);if(!y.success)return new Response(JSON.stringify({error:`Export failed: ${y.error}`}),{status:500,headers:{"Content-Type":"application/json"}});try{h=JSON.parse(ue.readFileSync(f,"utf-8"))}finally{try{ue.unlinkSync(f)}catch{}}}if(!h&&!s)return new Response(JSON.stringify({error:"No data to save: no seed adapter found and no localStorage provided"}),{status:400,headers:{"Content-Type":"application/json"}});let m=c;if(r==="new"){m=cr.randomUUID();const f=ee.join(p,`${c}.json`);let y={_metadata:{type:"application"}};ue.existsSync(f)&&(y=JSON.parse(ue.readFileSync(f,"utf-8"))),h&&(y.seed=h),s&&(y.localStorage=s),ue.writeFileSync(ee.join(p,`${m}.json`),JSON.stringify(y,null,2)),h&&ue.writeFileSync(ee.join(p,`${m}.seed.json`),JSON.stringify(h,null,2))}else{const f=ee.join(p,`${c}.json`);if(ue.existsSync(f)){const y=JSON.parse(ue.readFileSync(f,"utf-8"));h&&(y.seed=h),s&&(y.localStorage=s),ue.writeFileSync(f,JSON.stringify(y,null,2))}h&&ue.writeFileSync(ee.join(p,`${c}.seed.json`),JSON.stringify(h,null,2))}return Tn(),new Response(JSON.stringify({success:!0,mode:r,scenarioId:m}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Ab=Object.freeze(Object.defineProperty({__proto__:null,action:jb},Symbol.toStringTag,{value:"Module"}));async function Pb({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});const t=await e.json(),{prompt:r}=t;if(!r)return Response.json({error:"Missing prompt"},{status:400});const s=Ce()||process.cwd(),a=H.join(s,".codeyam","tmp");G.mkdirSync(a,{recursive:!0});const o=Wo.randomUUID().slice(0,8),i=H.join(a,`scenario-prompt-${o}.md`);return G.writeFileSync(i,r,"utf8"),Response.json({promptFile:i})}const Tb=Object.freeze(Object.defineProperty({__proto__:null,action:Pb},Symbol.toStringTag,{value:"Module"}));let wn=null;async function Mb({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=Ce()||process.cwd(),c=ee.join(l,".codeyam"),p=ee.join(c,"active-scenario.json");let u=o||null;if(!u&&s){const x=ee.join(c,"editor-scenarios",`${s}.json`);try{ue.existsSync(x)&&(u=JSON.parse(ue.readFileSync(x,"utf-8")).type||null)}catch{}}let h=null;try{ue.existsSync(p)&&(h=JSON.parse(ue.readFileSync(p,"utf-8")).scenarioId||null)}catch{}const m=h===s&&s!==null;ue.mkdirSync(c,{recursive:!0}),ue.writeFileSync(p,JSON.stringify({scenarioSlug:r,scenarioName:a||null,scenarioId:s||null,type:u,dataFile:s?`.codeyam/editor-scenarios/${s}.json`:null,switchedAt:new Date().toISOString()},null,2));let f=null;const y=u==="application"||u==="user";if(y&&s&&m)console.log(`[editor-switch-scenario] Same scenario "${r}" already active — skipping seed`),f={success:!0};else if(y&&s)if(wn&&wn.scenarioId===s)console.log(`[editor-switch-scenario] Seed already in progress for "${s}" — reusing`),f=await wn.promise;else{const x=Yr(l),b=ee.join(c,"editor-scenarios",`${s}.seed.json`);if(x&&ue.existsSync(b)){console.log(`[editor-switch-scenario] Running seed adapter for ${u} scenario "${a||r}"`);const v=pi(x,b).then(N=>{const w={success:N.success,error:N.error};if(N.success){console.log(`[editor-switch-scenario] Seed adapter completed in ${N.durationMs}ms`);const C=N.sessionCookies&&N.sessionCookies.length>0,S=N.externalApis&&Object.keys(N.externalApis).length>0;if(C||S)try{const k=ee.join(c,"editor-scenarios",`${s}.json`);if(ue.existsSync(k)){const j=JSON.parse(ue.readFileSync(k,"utf-8"));C&&(j.sessionCookies=N.sessionCookies),S&&(j.externalApis={...j.externalApis,...N.externalApis}),ue.writeFileSync(k,JSON.stringify(j,null,2))}}catch{}}else console.warn(`[editor-switch-scenario] Seed adapter failed: ${N.error}`);return w});wn={scenarioId:s,promise:v};try{f=await v}finally{wn&&wn.scenarioId===s&&(wn=null)}}else x||(console.warn("[editor-switch-scenario] No seed adapter found — skipping database seeding"),f={success:!1,error:"No seed adapter found"})}Tn();const g=i?0:wi();return new Response(JSON.stringify({success:!0,scenarioSlug:r,refreshedClients:g,seeded:y,...f?{seedResult:f}:{}}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const $b=Object.freeze(Object.defineProperty({__proto__:null,action:Mb},Symbol.toStringTag,{value:"Module"}));var Ee;(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={}))})(Ee||(Ee={}));function Mu(e,t){return e?Object.values(Ee.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const $u=Mu(process.env.DEFAULT_SMALLER_MODEL,Ee.Model.OPENAI_GPT4_1_MINI),Ib=Mu(process.env.DEFAULT_LARGER_MODEL,Ee.Model.OPENAI_GPT4_1),Tt={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},ao={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},Fb={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},oo={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},rn={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},Db={[Ee.Model.OPENAI_GPT5_1]:{id:Ee.Model.OPENAI_GPT5_1,provider:Tt,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[Ee.Model.OPENAI_GPT5]:{id:Ee.Model.OPENAI_GPT5,provider:Tt,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[Ee.Model.OPENAI_GPT5_MINI]:{id:Ee.Model.OPENAI_GPT5_MINI,provider:Tt,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[Ee.Model.OPENAI_GPT5_NANO]:{id:Ee.Model.OPENAI_GPT5_NANO,provider:Tt,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[Ee.Model.OPENAI_GPT4_1]:{id:Ee.Model.OPENAI_GPT4_1,provider:Tt,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[Ee.Model.OPENAI_GPT4_1_MINI]:{id:Ee.Model.OPENAI_GPT4_1_MINI,provider:Tt,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[Ee.Model.OPENAI_GPT4_O]:{id:Ee.Model.OPENAI_GPT4_O,provider:Tt,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[Ee.Model.OPENAI_GPT4_O_MINI]:{id:Ee.Model.OPENAI_GPT4_O_MINI,provider:Tt,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[Ee.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:Ee.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:ao,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[Ee.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:Ee.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:ao,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[Ee.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:Ee.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:ao,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[Ee.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:Ee.Model.OPENAI_GPT_OSS_120B_GROQ,provider:Fb,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[Ee.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:Ee.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:rn,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[Ee.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:Ee.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:rn,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[Ee.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:Ee.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:rn,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[Ee.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:Ee.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:rn,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[Ee.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:Ee.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:rn,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[Ee.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:Ee.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:oo,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[Ee.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:Ee.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:oo,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[Ee.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:Ee.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:oo,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[Ee.Model.PHIND_CODELLAMA]:{id:Ee.Model.PHIND_CODELLAMA,provider:Tt,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[Ee.Model.GOOGLE_GEMINI_PRO]:{id:Ee.Model.GOOGLE_GEMINI_PRO,provider:rn,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[Ee.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:Ee.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:rn,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[Ee.Model.META_CODELLAMA_34B_INSTRUCT]:{id:Ee.Model.META_CODELLAMA_34B_INSTRUCT,provider:rn,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[Ee.Model.OPENAI_GPT4_PREVIEW]:{id:Ee.Model.OPENAI_GPT4_PREVIEW,provider:Tt,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function ka(e){const t=Db[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function Rb(e){return ka(e).maxCompletionTokens}function Ob(e){return ka(e).pricing}const Ql=1e6;function Lb({model:e,usage:t}){const r=Ob(e);return r?t.prompt_tokens*(r.input/Ql)+t.completion_tokens*(r.output/Ql):null}function zb({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=Lb({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 Bb({messages:{system:e,prompt:t},model:r,responseType:s,jsonSchema:a}){const o=r??$u,i=ka(o);Rb(o);const l=[];return e&&l.push({role:"system",content:e}),l.push({role:"user",content:[{type:"text",text:t}]}),{messages:l,model:i.apiModelName,response_format:s==="json_schema"&&a?{type:"json_schema",json_schema:{name:a.name,schema:a.schema,strict:a.strict!==!1}}:{type:s&&s=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}let Rr=null;function Yb(e){if(typeof process>"u"||!process.versions||!process.versions.node)return!1;try{const t=zr(e,".codeyam","secrets.json");if(Ct(t)){const s=JSON.parse(Nl(t,"utf-8"));if(s.anthropicApiKey||s.ANTHROPIC_API_KEY||s.openAiApiKey||s.OPENAI_API_KEY||s.groqApiKey||s.GROQ_API_KEY)return!0}const r=zr(em(),".codeyam","secrets.json");if(Ct(r)){const s=JSON.parse(Nl(r,"utf-8"));if(s.anthropicApiKey||s.ANTHROPIC_API_KEY||s.openAiApiKey||s.OPENAI_API_KEY||s.groqApiKey||s.GROQ_API_KEY)return!0}return!!(process.env.OPENAI_API_KEY||process.env.ANTHROPIC_API_KEY||process.env.GROQ_API_KEY)}catch{return!1}}function Wb(e){if(typeof process>"u"||!process.versions||!process.versions.node)return!1;const t=zr(e,".claude");return Ct(t)}function Y_(e){if(Yb(e))return Rr={mode:"direct-api",projectRoot:e},"direct-api";if(Wb(e))return Rr={mode:"claude-cli",projectRoot:e},"claude-cli";throw new Error(`No AI service configured. Please either:
340
- 1. Add an API key to ~/.codeyam/secrets.json (shared across projects) or .codeyam/secrets.json (project-specific), or
341
- 2. Use Claude Code CLI (detected by .claude folder)`)}function Ub(){return(Rr==null?void 0:Rr.mode)==="claude-cli"}const Ao="/tmp/codeyam-e2e-tracking";let io,lo;function Jb(){return io===void 0&&(io=process.env.CODEYAM_E2E_TRACK_DATA==="true"),io}function Hb(){return lo===void 0&&(lo=!process.env.CODEYAM_LLM_FIXTURES_DIR),lo}function Vb(){G.existsSync(Ao)||G.mkdirSync(Ao,{recursive:!0})}function Kb(e){const t=JSON.stringify(e,null,0);return Wo.createHash("md5").update(t).digest("hex")}function Gb(e,t,r){return[e].join("_")+".json"}function Iu(e,t,r,s){if(!Jb())return;Vb();const a=Gb(e),o=H.join(Ao,a),i=Kb(t);if(Hb()){const l={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:s,dataHash:i,data:t};G.writeFileSync(o,JSON.stringify(l,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(G.existsSync(o)){const l=JSON.parse(G.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=Po(l.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${l.dataHash}`),console.log(` Second run hash: ${i}`);const p=o.replace(".json","_DIFF.json");G.writeFileSync(p,JSON.stringify({checkpoint:e,entityName:r,scenarioName:s,firstRun:l.data,secondRun:t,differences:c.differences},null,2)),console.log(` Diff saved to: ${p}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function Po(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(...Po(e[o],t[o],`${r}[${o}]`));return s}if(typeof e=="object"&&typeof t=="object"){const a=Object.keys(e),o=Object.keys(t),i=Array.from(new Set([...a,...o]));for(const l of i){const c=e[l],p=t[l];l in e?l in t?s.push(...Po(c,p,`${r?r+".":""}${l}`)):s.push(`${r?r+".":""}${l}: missing in second run`):s.push(`${r?r+".":""}${l}: missing in first run`)}return s}if(e!==t){const a=JSON.stringify(e),o=JSON.stringify(t);a.length<100&&o.length<100?s.push(`${r||"root"}: ${a} vs ${o}`):s.push(`${r||"root"}: values differ (${a.length} chars vs ${o.length} chars)`)}return s}const Zl=Ho(Jo),Xl=2;function qb(e){try{return JSON.parse(e),{valid:!0}}catch(t){return{valid:!1,error:t.message}}}function Qb(e){const t=e.trim(),r=(t.match(/\{/g)||[]).length,s=(t.match(/\}/g)||[]).length,a=(t.match(/\[/g)||[]).length,o=(t.match(/\]/g)||[]).length,i=(t.match(new RegExp('(?<!\\\\)"',"g"))||[]).length;return r>s||a>o||i%2!==0||!t.endsWith("}")&&!t.endsWith("]")}async function Fu(e,t,r,s=0){try{const a=`${e}
342
-
343
- ${t}${r?`
344
-
345
- Respond with valid JSON only.`:""}`;let o="claude";try{const{stdout:c}=await Zl("which claude",{timeout:1e3});o=c.trim()}catch{const c=["/usr/local/bin/claude",`${process.env.HOME}/.nvm/versions/node/v20.16.0/bin/claude`,`${process.env.HOME}/.npm-global/bin/claude`];for(const p of c)try{await Zl(`test -x "${p}"`,{timeout:1e3}),o=p;break}catch{}}const{stdout:i,stderr:l}=await new Promise((c,p)=>{var g,x,b;const h=xt(o,["-p",a,"--output-format","json","--max-turns","1"],{env:{...process.env}});(g=h.stdin)==null||g.end();let m="",f="";(x=h.stdout)==null||x.on("data",v=>{const N=v.toString();m+=N}),(b=h.stderr)==null||b.on("data",v=>{f+=v.toString()}),h.on("error",v=>{p(v)}),h.on("close",(v,N)=>{if(v===0)c({stdout:m,stderr:f});else{const w=new Error(`Command failed with exit code ${v}. stderr: ${f.substring(0,500)}`);w.code=v,w.stdout=m,w.stderr=f,p(w)}});const y=setTimeout(()=>{h.kill("SIGTERM"),setTimeout(()=>{h.killed||h.kill("SIGKILL")},5e3),p(new Error("Claude CLI command timed out after 60 seconds"))},6e4);h.on("close",()=>clearTimeout(y))});try{const c=JSON.parse(i);let p=c.result||c.response||c.text||c.content;if(!p)throw new Error("No response content from Claude CLI");const u=p.match(/^```(?:json)?\s*\n([\s\S]*?)\n```\s*$/);if(u&&(p=u[1]),r){const h=qb(p);if(h.valid)console.log("✅ Claude CLI: JSON validation passed");else{console.log(`⚠️ Claude CLI: Invalid JSON response (attempt ${s+1}/${Xl+1})`),console.log(`⚠️ Claude CLI: JSON error: ${h.error}`),console.log(`⚠️ Claude CLI: Response length: ${p.length} bytes`);const m=Qb(p);if(console.log(`⚠️ Claude CLI: Appears truncated: ${m}`),m&&s<Xl){console.log(`🔄 Claude CLI: Attempting to recover truncated JSON (retry ${s+1})`);const f=`The previous response was truncated and incomplete. Here's what was received:
346
-
347
- \`\`\`json
348
- ${p}
349
- \`\`\`
350
-
351
- Please complete this JSON response. Make sure it's valid, complete JSON that properly closes all braces, brackets, and quotes. Return ONLY the complete, valid JSON.`;try{return await Fu(e,f,r,s+1)}catch(y){console.log(`⚠️ Claude CLI: Recovery attempt failed: ${y}`)}}console.log(`⚠️ Claude CLI: Returning invalid JSON response after ${s+1} attempts`),console.log(`⚠️ Claude CLI: Downstream parsing will likely fail. First 500 chars: ${p.substring(0,500)}`)}}return p}catch(c){if(i.trim())return i.trim();throw new Error(`Failed to parse Claude CLI response: ${c}`)}}catch(a){const o=a.message;throw o.includes("command not found")||o.includes("ENOENT")?new Error("Claude Code CLI not found. Please ensure Claude Code is installed."):o.includes("not authenticated")||o.includes("subscription")?new Error("Claude Code CLI not authenticated. Please run `claude` to authenticate."):a}}const xs=new im({concurrency:100,timeout:1200*1e3,autoStart:!0}),ec={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},sn={};async function To({type:e,systemMessage:t,prompt:r,jsonResponse:s=!0,jsonSchema:a,model:o=$u,attempts:i=0}){var k,j,_,F,M,$,O;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await Zb(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${xs.size}, running=${xs.pending}]`);const l=Date.now();let c,p=0;if(Ub()){console.log("Using Claude CLI mode for AI request");const D=await Fu(t,r,s);return{finishReason:"stop",completion:D,stats:{model:"claude-sonnet-4-5",prompt_type:e,system_message:t,prompt_text:r,response:D,input_tokens:0,output_tokens:0,cost:0}}}const u=ka(o),h=process.env[u.provider.apiKeyEnvVar];if(!h)throw new Error(`API key not found for provider ${u.provider.name}. Please set ${u.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${u.provider.name} for AI request`);const m=new om({apiKey:h,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:a?"json_schema":s?"json_object":"text",jsonSchema:a},y=Bb(f),g=await xs.add(()=>(c=Date.now(),Sl(async()=>{const D=Date.now(),T=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],B=setInterval(()=>{const Y=Math.floor((Date.now()-D)/1e3),I=Math.floor(Y/10)%T.length;kl(1,`${T[I]} [type=${e}, model=${o}, elapsed=${Y}s]`)},1e4);try{return await m.chat.completions.create(y,{timeout:300*1e3})}finally{clearInterval(B)}},{...ec,onFailedAttempt:D=>{p++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:D,prompt:r,systemMessage:t,attempts:i,retryCount:p})}})));if(!g)throw new Error("Completion call returned no result");const x=g,b=Date.now(),v=zb({chatRequest:f,chatCompletion:x,model:o});if(!v)throw new Error("Failed to get LLM call stats");v.retries=p,v.wait_ms=c-l,v.duration_ms=b-l;const N=(k=x.choices)==null?void 0:k[0];let w=null;if(N){if(!N.finish_reason)throw console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({chatCompletion:x,chatRequest:f},null,2)),new Error("completionCall(): missing finish_reason in LLM response");w=(j=N.message)==null?void 0:j.content}let C=w;w&&(C=w.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const S=s?C&&(((_=C.match(/\{[\s\S]*\}/))==null?void 0:_[0])??C):C;if(!S){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:S,rawCompletion:w,chatCompletion:x,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await To({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(S.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:w,prompt:r,systemMessage:t}),new Error("Empty completion");if(s)try{JSON.parse(S)}catch(D){if(console.log("CodeYam Error: Invalid JSON in completion",{error:D.message,model:o,completion:S.substring(0,500),rawCompletion:w==null?void 0:w.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:D.message});const T=`Your previous response contained invalid JSON with the following error:
352
-
353
- ${D.message}
354
-
355
- Here was your previous response:
356
- \`\`\`
357
- ${S}
358
- \`\`\`
359
-
360
- Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,B=await xs.add(()=>Sl(async()=>{const R=Date.now(),E=["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 K=Math.floor((Date.now()-R)/1e3),Q=Math.floor(K/10)%E.length;kl(1,`${E[Q]} [type=${e}, model=${o}, elapsed=${K}s]`)},1e4);try{return await m.chat.completions.create({...y,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:S},{role:"user",content:T}]},{timeout:300*1e3})}finally{clearInterval(J)}},{...ec,onFailedAttempt:R=>{console.log("CodeYam Error: Correction call failed",{error:R,attempts:i})}}));if(!B)throw new Error("Correction call returned no result");const Y=B,I=($=(M=(F=Y.choices)==null?void 0:F[0])==null?void 0:M.message)==null?void 0:$.content;let L=I;I&&(L=I.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const P=L&&(((O=L.match(/\{[\s\S]*\}/))==null?void 0:O[0])??L);if(!P)throw new Error("Correction attempt returned empty completion");try{JSON.parse(P),console.log("CodeYam: JSON correction successful");const R=Date.now();return v.duration_ms=R-l,{finishReason:Y.choices[0].finish_reason,completion:P,stats:v}}catch(R){return console.log("CodeYam Error: Corrected JSON still invalid",{error:R.message,correctedCompletion:P.substring(0,500)}),await To({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${D.message}`)}return Iu(`completionCall_${e}`,{completion:S,finishReason:x.choices[0].finish_reason}),{finishReason:x.choices[0].finish_reason,completion:S,stats:v}}async function Zb(e,t,r){var o,i,l,c,p;const s=await import("fs"),a=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!s.existsSync(t))throw console.log(`CodeYam Test: Fixtures directory does not exist yet: ${t}`),new Error(`No LLM fixture files found - directory does not exist: ${t}`);const u=s.readdirSync(t).filter(v=>v.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${t}`);const h={};for(const v of u)try{const N=s.readFileSync(a.join(t,v),"utf-8"),w=JSON.parse(N);h[w.prompt_type]||(h[w.prompt_type]=[]),h[w.prompt_type].push(w)}catch(N){console.warn(`Failed to parse LLM fixture file ${v}:`,N)}for(const v of Object.keys(h))h[v].sort((N,w)=>{const C=N.created_at??0,S=w.created_at??0;return C-S});const m=h[e];if(!m||m.length===0){const v=Object.keys(h).join(", ");return console.warn(`CodeYam Test: No captured LLM call found for type '${e}'. Available types: ${v}`),{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 v=r.match(/Scenario name must match exactly: "([^"]+)"/),N=v==null?void 0:v[1];if(N){const w={};for(const S of m)try{const j=((o=JSON.parse(S.props||"{}").scenario)==null?void 0:o.name)||"__NO_SCENARIO__";w[j]||(w[j]=[]),w[j].push(S)}catch{}const C=w[N];if(C&&C.length>0){const S=`${t}::${e}::${N}`;sn[S]===void 0&&(sn[S]=0);const k=sn[S];sn[S]=(k+1)%C.length,f=C[k],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${N}' [${k+1}/${C.length}]`)}else{const S=Object.keys(w).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${N}'. Available: [${S}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const v=`${t}::${e}`;sn[v]===void 0&&(sn[v]=0);const N=sn[v];sn[v]=(N+1)%m.length,f=m[N],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${N+1}/${m.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&&(((p=x.match(/\{[\s\S]*\}/))==null?void 0:p[0])??x);return Iu(`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 tc(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function Xb(e){const{propsJson:t,...r}=e,s=JSON.stringify(t,null,2),a=Uo(),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=H.join(process.env.DYNAMODB_PATH,c):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(l=H.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",c)),l)try{const u=H.dirname(l);return await Ae.mkdir(u,{recursive:!0}),await Ae.writeFile(l,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${l}`),{id:a}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const p=tc();if(!p)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,h]of Object.entries(i))typeof h>"u"&&console.log(`CodeYam Warning: LLM call ${a} property ${u} with explicit value 'undefined'`);try{return await new ta().send(new lm({TableName:tc(),Item:dm(i,{removeUndefinedValues:!0})})),{id:a}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${p}`,u),{id:"-1"}}}new ta({});new ta({});new ta({});const ev=3,tv=2,ji=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+ev*String(t).length*(1+tv)});new Go(ji());new Go(ji());new Go(ji());class nv{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 rv{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 sv{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 av{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 ov{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 iv{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 lv{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 cv{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.withReturnValues();s.addType(a,"unknown")}isComplete(){return!0}}class dv{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 uv{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 pv{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 hv{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 mv{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 fv{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown"),s.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class gv{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 yv{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 xv{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 bv{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 vv{getReturnType(){return"unknown"}addEquivalences(t,r,s){t.getLastFunctionCallSegment()}isComplete(){return!0}}class wv{getReturnType(){return"array"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(s.addType(t.withParameter(1),"function"),a&&a.args.length>0){const o=a.args[0];s.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}class Nv{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(t,"boolean")}isComplete(){return!0}}class Sv{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(t,"boolean")}isComplete(){return!0}}function Cv(){const e=new nv;return e.register("filter",new rv,"Array"),e.register("map",new hv,"Array"),e.register("flatMap",new mv,"Array"),e.register("join",new pv,"Array"),e.register("find",new ov,"Array"),e.register("findLast",new gv,"Array"),e.register("at",new fv,"Array"),e.register("reduce",new iv,"Array"),e.register("concat",new lv,"Array"),e.register("slice",new cv,"Array"),e.register("splice",new dv,"Array"),e.register("push",new uv,"Array"),e.register("some",new sv,"Array"),e.register("every",new av,"Array"),e.register("fromEntries",new yv,"Object"),e.register("split",new xv,"String"),e.register("then",new bv,"Promise"),e.register("useState",new wv,"React"),e.register("useMemo",new vv,"React"),e.register("has",new Nv),e.register("delete",new Sv),e}Cv();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 kv=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),_v=new Set(["find","findLast","at","pop","shift"]),Ev=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),jv=new Set([...kv,..._v,...Ev]),Av=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Pv=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Tv=new Set([...Av,...Pv]);[...jv,...Tv];class Mv{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 Mv({enabled:!1});function Nn(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 $v(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function bs(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let Iv=0;class Ai{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++Iv,this.enabled=(t==null?void 0:t.enabled)??!1,this.outputPath=(t==null?void 0:t.outputPath)??"/tmp/codeyam/transform-trace.json",this.enabled&&console.log(`[Tracer] Initialized (id=${this.tracerId}, output=${this.outputPath})`)}log(t){this.isEnabled()&&console.log(`[Tracer] ${t}`)}isEnabled(){const t=process.env.CODEYAM_TRACE_TRANSFORMS;return t==="1"||t==="true"?!0:this.enabled}enable(){this.enabled=!0}disable(){this.enabled=!1}setOutputPath(t){this.outputPath=t}setProjectSlug(t){this.projectSlug=t}startEntity(t){if(!this.isEnabled())return;this.currentEntity=t.name;const r=this.traces.get(t.name);if(r){this.log(`startEntity: ${t.name} already exists, preserving ${r.stages.length} stages`);return}this.log(`startEntity: ${t.name}`),this.traces.set(t.name,{entityName:t.name,entityType:t.entityType,filePath:t.filePath,stages:[],operations:[]})}snapshot(t,r,s){var c,p,u,h;if(!this.isEnabled())return;const a=this.traces.get(t);if(!a)return this.log(`snapshot: no trace for ${t}, creating one`),this.startEntity({name:t,entityType:"unknown",filePath:"unknown"}),this.snapshot(t,r,s);this.log(`snapshot: ${t} → ${r}`),this.currentStage=r;const o=JSON.parse(JSON.stringify(s)),i={stage:r,timestamp:Date.now(),data:o},l=a.stages[a.stages.length-1];if(l&&(i.diffFromPrevious={signatureSchema:Nn(l.data.signatureSchema,o.signatureSchema),returnValueSchema:Nn(l.data.returnValueSchema,o.returnValueSchema)},o.dependencySchemas||l.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const m=new Set([...Object.keys(o.dependencySchemas??{}),...Object.keys(l.data.dependencySchemas??{})]);for(const f of m){const y=(c=l.data.dependencySchemas)==null?void 0:c[f],g=(p=o.dependencySchemas)==null?void 0:p[f];for(const x of new Set([...Object.keys(y??{}),...Object.keys(g??{})])){const b=`${f}::${x}`,v=(u=y==null?void 0:y[x])==null?void 0:u.returnValueSchema,N=(h=g==null?void 0:g[x])==null?void 0:h.returnValueSchema,w=Nn(v,N);$v(w)&&(i.diffFromPrevious.dependencySchemas[b]=w)}}}a.stages.push(i)}operation(t,r){if(!this.isEnabled())return;const s=this.traces.get(t);s&&s.operations.push({...r,stage:r.stage??this.currentStage??void 0,timestamp:Date.now()})}computeFlushSummary(){var a;const t={},r=new Map;for(const[o,i]of this.traces){let l=0;for(const c of i.stages){if(!c.diffFromPrevious)continue;const u=`${((a=i.stages[i.stages.indexOf(c)-1])==null?void 0:a.stage)??"start"}→${c.stage}`;if(t[u]||(t[u]={added:0,removed:0,changed:0}),c.diffFromPrevious.signatureSchema){const h=c.diffFromPrevious.signatureSchema;t[u].added+=Object.keys(h.added).length,t[u].removed+=Object.keys(h.removed).length,t[u].changed+=Object.keys(h.changed).length,l+=bs(h)}if(c.diffFromPrevious.returnValueSchema){const h=c.diffFromPrevious.returnValueSchema;t[u].added+=Object.keys(h.added).length,t[u].removed+=Object.keys(h.removed).length,t[u].changed+=Object.keys(h.changed).length,l+=bs(h)}}r.set(o,l)}const s=[...r.entries()].sort((o,i)=>i[1]-o[1]).slice(0,10).map(([o])=>o);return{stageChangeCounts:t,entitiesWithMostChanges:s}}flush(){if(!this.isEnabled())return;if(this.traces.size===0){this.log("flush: no traces to write");return}const t=Array.from(this.traces.keys()),r=t.map(p=>`${p}(${this.traces.get(p).stages.length})`).join(", ");this.log(`flush: writing ${t.length} entities: ${r}`);const{stageChangeCounts:s,entitiesWithMostChanges:a}=this.computeFlushSummary(),o={timestamp:new Date().toISOString(),projectSlug:this.projectSlug,entityCount:this.traces.size},i={stageChangeCounts:s,entitiesWithMostChanges:a},l=H.dirname(this.outputPath);G.existsSync(l)||G.mkdirSync(l,{recursive:!0});const c=G.openSync(this.outputPath,"w");try{G.writeSync(c,`{
361
- "meta": `),G.writeSync(c,JSON.stringify(o,null,2)),G.writeSync(c,`,
362
- "summary": `),G.writeSync(c,JSON.stringify(i,null,2)),G.writeSync(c,`,
363
- "entities": {`);let p=!0;for(const[u,h]of this.traces)p||G.writeSync(c,","),G.writeSync(c,`
364
- ${JSON.stringify(u)}: `),G.writeSync(c,JSON.stringify(h,null,2)),p=!1;G.writeSync(c,`
365
- }
366
- }
367
- `),this.log(`flush: wrote trace to ${this.outputPath}`)}finally{G.closeSync(c)}}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=G.readFileSync(t,"utf-8"),s=JSON.parse(r),a=new Ai({enabled:!1});a.projectSlug=s.meta.projectSlug;for(const[o,i]of Object.entries(s.entities))a.traces.set(o,i);return a}getSummary(){var a,o,i;const t={},r=new Map;for(const[l,c]of this.traces){let p=0;for(let u=1;u<c.stages.length;u++){const h=c.stages[u],f=`${((a=c.stages[u-1])==null?void 0:a.stage)??"start"}→${h.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(o=h.diffFromPrevious)!=null&&o.signatureSchema){const y=h.diffFromPrevious.signatureSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,p+=bs(y)}if((i=h.diffFromPrevious)!=null&&i.returnValueSchema){const y=h.diffFromPrevious.returnValueSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,p+=bs(y)}}r.set(l,p)}const s=[...r.entries()].sort((l,c)=>c[1]-l[1]).slice(0,10).map(([l,c])=>({name:l,totalChanges:c}));return{entityCount:this.traces.size,stageChangeCounts:t,entitiesWithMostChanges:s}}getEntitySummary(t){const r=this.traces.get(t);return r?{entityName:t,stages:r.stages.map(s=>({stage:s.stage,diffFromPrevious:s.diffFromPrevious?{signatureSchema:s.diffFromPrevious.signatureSchema,returnValueSchema:s.diffFromPrevious.returnValueSchema}:void 0}))}:null}getOperations(t,r){const s=this.traces.get(t);return s?r?s.operations.filter(a=>a.path&&r.test(a.path)):s.operations:[]}tracePath(t,r){var o,i;const s=this.traces.get(t),a=[];if(!s)return{entityName:t,path:r,history:a};for(const l of s.stages){const c=(o=l.data.signatureSchema)==null?void 0:o[r],p=(i=l.data.returnValueSchema)==null?void 0:i[r],u=c??p;u!==void 0&&a.push({stage:l.stage,value:u})}for(const l of s.operations)l.path===r&&a.push({operation:l.operation,stage:l.stage,value:l.after??l.before,context:l.context});return{entityName:t,path:r,history:a}}getEntityTrace(t){return this.traces.get(t)}getEntityNames(){return[...this.traces.keys()]}findProperty(t,r){const s=this.traces.get(t);if(!s)return[];const a=[],o=new RegExp(`(^|\\.)${r}(\\.|\\[|$)`);for(const i of s.stages){for(const[l,c]of Object.entries(i.data.signatureSchema??{}))o.test(l)&&a.push({stage:i.stage,path:l,type:c,schemaType:"signature"});for(const[l,c]of Object.entries(i.data.returnValueSchema??{}))o.test(l)&&a.push({stage:i.stage,path:l,type:c,schemaType:"returnValue"});for(const[l,c]of Object.entries(i.data.dependencySchemas??{}))for(const[p,u]of Object.entries(c))for(const[h,m]of Object.entries(u.returnValueSchema??{}))o.test(h)&&a.push({stage:i.stage,path:`${l}/${p}::${h}`,type:m,schemaType:"dependency"})}return a}findTypeInconsistencies(t){const r=this.traces.get(t);if(!r)return[];let s=r.stages[r.stages.length-1];for(let c=r.stages.length-1;c>=0;c--)if(Object.keys(r.stages[c].data.dependencySchemas??{}).length>0){s=r.stages[c];break}if(!s)return[];const a=new Set(["length","toString","valueOf","constructor"]),o=new Map,i=(c,p)=>{const u=c.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!u)return;const h=u[1],m=u[2]==="[]";if(a.has(h))return;const f=h+(m?"[]":"");o.has(f)||o.set(f,[]),o.get(f).push({path:c,type:p})};for(const[,c]of Object.entries(s.data.dependencySchemas??{}))for(const[,p]of Object.entries(c))for(const[u,h]of Object.entries(p.returnValueSchema??{}))i(u,h);const l=[];for(const[c,p]of o)new Set(p.map(h=>h.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&l.push({propertyName:c,paths:p.map(h=>({...h,stage:s.stage}))});return l.sort((c,p)=>{const u=new Set(c.paths.map(m=>m.type)).size;return new Set(p.paths.map(m=>m.type)).size-u}),l}getStageDiffSummary(t,r,s){const a=this.traces.get(t);if(!a)return null;const o=a.stages.find(m=>m.stage===r),i=a.stages.find(m=>m.stage===s);if(!o||!i)return null;const l={added:[],removed:[],typeChanged:[]},c=o.data.returnValueSchema??{},p=i.data.returnValueSchema??{},u=new Set(Object.keys(c)),h=new Set(Object.keys(p));for(const m of h)u.has(m)?c[m]!==p[m]&&l.typeChanged.push({path:m,from:c[m],to:p[m]}):l.added.push(`${m}: ${p[m]}`);for(const m of u)h.has(m)||l.removed.push(`${m}: ${c[m]}`);return l}traceSchemaTransform(t,r,s,a,o){if(!this.enabled)return a(s),s;const i={...s};a(s);const l=Nn(i,s);for(const[c,p]of Object.entries(l.added))this.operation(t,{operation:r,path:c,before:void 0,after:p,context:{...o,changeType:"added"}});for(const[c,p]of Object.entries(l.removed))this.operation(t,{operation:r,path:c,before:p,after:void 0,context:{...o,changeType:"removed"}});for(const[c,{from:p,to:u}]of Object.entries(l.changed))this.operation(t,{operation:r,path:c,before:p,after:u,context:{...o,changeType:"changed"}});return s}traceSchemaTransformResult(t,r,s,a,o){if(!this.enabled)return;const i=Nn(s,a);for(const[l,c]of Object.entries(i.added))this.operation(t,{operation:r,path:l,before:void 0,after:c,context:{...o,changeType:"added"}});for(const[l,c]of Object.entries(i.removed))this.operation(t,{operation:r,path:l,before:c,after:void 0,context:{...o,changeType:"removed"}});for(const[l,{from:c,to:p}]of Object.entries(i.changed))this.operation(t,{operation:r,path:l,before:c,after:p,context:{...o,changeType:"changed"}})}traceDependencySchemaTransform(t,r,s,a,o="both"){if(!this.enabled){for(const i in s)for(const l in s[i]){const c=s[i][l];(o==="signature"||o==="both")&&c.signatureSchema&&a(c.signatureSchema),(o==="returnValue"||o==="both")&&c.returnValueSchema&&a(c.returnValueSchema)}return}for(const i in s)for(const l in s[i]){const c=s[i][l],p={filePath:i,dependencyName:l};(o==="signature"||o==="both")&&c.signatureSchema&&this.traceSchemaTransform(t,r,c.signatureSchema,a,{...p,schemaType:"signature"}),(o==="returnValue"||o==="both")&&c.returnValueSchema&&this.traceSchemaTransform(t,r,c.returnValueSchema,a,{...p,schemaType:"returnValue"})}}traceDependencySchemaChanges(t,r,s,a){var i;if(!this.enabled){a();return}const o={};for(const l in s){o[l]={};for(const c in s[l]){const p=s[l][c];o[l][c]={sig:{...p.signatureSchema||{}},rv:{...p.returnValueSchema||{}}}}}a();for(const l in s)for(const c in s[l]){const p=s[l][c],u=(i=o[l])==null?void 0:i[c],h={filePath:l,dependencyName:c};if(p.signatureSchema){const m=(u==null?void 0:u.sig)||{},f=Nn(m,p.signatureSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...h,schemaType:"signature",changeType:"added"}});for(const[y,{from:g,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:y,before:g,after:x,context:{...h,schemaType:"signature",changeType:"changed"}})}if(p.returnValueSchema){const m=(u==null?void 0:u.rv)||{},f=Nn(m,p.returnValueSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...h,schemaType:"returnValue",changeType:"added"}});for(const[y,{from:g,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:y,before:g,after:x,context:{...h,schemaType:"returnValue",changeType:"changed"}})}}}}function Fv(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const nc=new Ai({enabled:Fv(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{nc.isEnabled()&&nc.flush()});function Du(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 cm.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),Du(e)}return null}}function Dv({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:s}){let a="";return s&&s.length>0&&(a=`
368
- User-selected Execution Flow Values:
369
- The user has specifically requested these values be used in the scenario:
370
- ${s.map(o=>` - ${o.path}: ${o.value}${o.isCustom?" (custom value)":""}`).join(`
371
- `)}
372
-
373
- IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
374
- `),`Mock Scenario Data Structure:
375
- \`\`\`
376
- ${JSON.stringify(r,null,2)}
377
- \`\`\`
378
- Existing Mock Scenario Data:
379
- \`\`\`
380
- ${JSON.stringify(t,null,2)}
381
- \`\`\`
382
- ${a}
383
- New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
384
- `}function Rv({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}){const o=s.find(i=>i.name===sa);return`Mock Scenario Data Structure:
385
- \`\`\`
386
- ${JSON.stringify({props:a.arguments,dataVariables:a.dataForMocks},null,2)}
387
- \`\`\`
388
-
389
- Existing Mock Scenario Data:
390
- \`\`\`
391
- ${JSON.stringify(s.map(i=>({name:i.name,data:Ir(o.metadata.data,i.metadata.data)})),null,2)}
392
- \`\`\`
393
-
394
- Mock Scenario that should be edited: "${t}"
395
- ${r?`The portion of the data that should be edited:
396
- \`\`\`
397
- ${JSON.stringify(r,null,2)}
398
- \`\`\``:""}
399
-
400
- How this data should be changed: "${e}"
401
- `}async function Ov({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,flowSelections:o,model:i}){const l=t?Rv({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}):Dv({description:e,existingScenarios:s,scenariosDataStructure:a,flowSelections:o}),c=await To({type:"guessScenarioDataFromDescription",systemMessage:t?zv(r):Lv,prompt:l,model:i??Ib});await Xb({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,model:i},...c.stats});const{completion:p}=c;return p?Du(p):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const Lv=`
402
- You will be provided with a list of data secnarios for a component and the overall structure for the data. Additionally you'll receive a description for a new scenario written by the user.
403
-
404
- Your goal is to add one scenario to the list of existing scenarios by generating an english name, proper description, and a JSON data structure that describes the data that would be used in a scenario for the code.
405
-
406
- The data for the scenario will be merged with the "Default Scenario" data, so you don't need to replicate any data in the default scenario but must overwrite any data that should be different.
407
-
408
- You must respond with valid JSON following this format of this TS type definition:
409
- \`\`\`
410
- export type ScenarioData = {
411
- name: string;
412
- description: string;
413
- data: {
414
- mockData: { [key: string]: unknown };
415
- argumentsData: { [key: string]: unknown };
416
- };
417
- };
418
-
419
- \`\`\`
420
- `,zv=e=>`
421
- You will be provided with a list of data secnarios for a component and the overall structure for the data. Additionally you'll receive a description for a new scenario written by the user.
422
-
423
- Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
424
- ${e?`
425
- We only want to edit a specific portion of the data, which is provided in the "The portion of the data that should be edited" section. You should only change the data that is provided in this section.`:""}
426
-
427
- Always return the complete data structure for the scenario, with both mockData and argumentsData, even if you only changed a small portion of the data.
428
-
429
- You must respond with valid JSON following this type definition:
430
- \`\`\`
431
- {
432
- data: {
433
- mockData: { [key: string]: unknown };
434
- argumentsData: { [key: string]: unknown };
435
- }
436
- }
437
- \`\`\`
438
- `;async function Bv({request:e}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:s,scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:l}=t;if(!r&&(!l||l.length===0))return re({error:"Missing required field: description or flowSelections"},{status:400});const c=await Ov({description:r||"",existingScenarios:s??[],scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:l}),p=(c==null?void 0:c.data)||c;return re({success:!0,data:p})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),re({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const Yv=Object.freeze(Object.defineProperty({__proto__:null,action:Bv},Symbol.toStringTag,{value:"Module"}));function Wv(e,t,r=new Date){const s={"1d":1,"3d":3,"7d":7,"30d":30}[t],a=new Date(r);a.setDate(a.getDate()-s);const o=a.toISOString().split("T")[0],i=e.filter(h=>h.date>=o),l=new Set(i.map(h=>h.commitSha).filter(Boolean)),c=new Map;for(const h of i)if(h.scenarioScreenshots)for(const m of h.scenarioScreenshots){c.has(m.name)||c.set(m.name,[]);const f=c.get(m.name);f.some(y=>y.path===m.path)||f.push({path:m.path,time:h.time})}for(const h of c.values())h.sort((m,f)=>m.time.localeCompare(f.time));const p=[],u=new Map;for(const[h,m]of c){const f=h.indexOf(" - ");if(f!==-1){const y=h.slice(0,f);u.has(y)||u.set(y,[]),u.get(y).push({name:h,screenshots:m})}else p.push({name:h,screenshots:m})}return{commitCount:l.size,entryCount:i.length,appScenarios:p,componentGroups:u,totalScenarios:c.size}}function Uv(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 Jv(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 Hv(e,t){const r=e.replace(/[^a-zA-Z0-9_\-]/g,"_");return`${t.toISOString().replace(/:/g,"-").replace(/\.\d+Z$/,"")}_${r}.png`}function Vv(e){const{title:t,timeStr:r,type:s,description:a,allScenarioNames:o,screenshot:i,scenarioScreenshots:l,commitSha:c,commitMessage:p,featureName:u,userPrompt:h}=e,m=["","---","",`### ${t}`,`**Time:** ${r}`,`**Type:** ${s}`];if(u&&m.push(`**Feature:** ${u}`),h&&m.push(`**Prompt:** ${h}`),o.length>0&&m.push(`**Scenarios:** ${o.join(", ")}`),m.push(""),m.push(a),i&&(m.push(""),m.push(`![${t}](${i})`)),l.length>0){m.push(""),m.push("**Scenario Screenshots:**");for(const f of l)m.push(""),m.push(`![${f.name}](${f.path})`)}return c&&p&&(m.push(""),m.push(`**Commit:** \`${c}\` — ${p}`)),m.push(""),m.join(`
439
- `)}function Kv(e,t){return e.findIndex(r=>r.time===t)}function Gv(e){return!!e.commitSha}function qv(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 Qv(e,t,r,s){const a=`
440
- **Commit:** \`${r}\` — ${s||"no message"}
441
- `,o=`### ${t}`,i=e.lastIndexOf(o);if(i===-1)return null;const l=e.indexOf(`
442
- ---
443
- `,i+1),c=l!==-1?l:e.length;return e.slice(0,c)+a+e.slice(c)}async function Zv(e){console.log(`[editorScenarioLookup] Looking up screenshots for ${e.length} scenarios: ${e.join(", ")}`);try{const t=await Ye();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up scenarios"),[];const{project:r}=await Re(t),a=await $e().selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","page_file_path","url"]).where("project_id","=",r.id).where("name","in",e).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] DB query returned ${a.length} matching scenarios:`,a.map(c=>({name:c.name,screenshot_path:c.screenshot_path,id:c.id})));const o=a.filter(c=>!c.screenshot_path);o.length>0&&console.warn(`[editorScenarioLookup] ${o.length} scenarios have no screenshot_path:`,o.map(c=>c.name));const i=a.filter(c=>c.screenshot_path),l=_t(i,c=>c.name).map(c=>({name:c.name,screenshotPath:c.screenshot_path,scenarioId:c.id,componentName:c.component_name||null,pageFilePath:c.page_file_path||null,url:c.url||null}));return console.log(`[editorScenarioLookup] Found ${l.length} scenarios with screenshots`),l}catch(t){return console.error("[editorScenarioLookup] Failed to look up scenario screenshots:",t),[]}}async function Xv(e){console.log(`[editorScenarioLookup] Looking up screenshots by entity names: ${e.join(", ")}`);try{const t=await Ye();if(!t)return[];const{project:r}=await Re(t),a=await $e().selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","page_file_path","url"]).where("project_id","=",r.id).orderBy("created_at","asc").execute(),o=new Set(e),l=a.filter(p=>{const u=Gt({componentName:p.component_name,pageFilePath:p.page_file_path,url:p.url});return o.has(u)}).filter(p=>p.screenshot_path),c=_t(l,p=>p.name).map(p=>({name:p.name,screenshotPath:p.screenshot_path,scenarioId:p.id,componentName:p.component_name||null,pageFilePath:p.page_file_path||null,url:p.url||null}));return console.log(`[editorScenarioLookup] Found ${c.length} scenarios for ${e.length} entities`),c}catch(t){return console.error("[editorScenarioLookup] Failed to look up entity screenshots:",t),[]}}async function Ru(e){console.log("[editorScenarioLookup] Looking up session scenario screenshots",e?`(after ${e})`:"(all session)");try{const t=await Ye();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up session scenarios"),[];const{project:r}=await Re(t),s=$e(),a=Ce()||process.cwd();let o=null;const i=H.join(a,".codeyam","editor-step.json");try{const m=G.readFileSync(i,"utf8");o=JSON.parse(m).featureStartedAt||null}catch{return console.warn("[editorScenarioLookup] No editor-step.json found — cannot determine session start"),[]}if(!o)return console.warn("[editorScenarioLookup] No featureStartedAt found in editor-step.json"),[];const l=e&&e>o?e:o,c=Qr(l),p=await s.selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","page_file_path","url"]).where("project_id","=",r.id).where("created_at",">=",c).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] Query returned ${p.length} scenarios since ${l}`);const u=p.filter(m=>m.screenshot_path),h=_t(u,m=>m.name).map(m=>({name:m.name,screenshotPath:m.screenshot_path,scenarioId:m.id,componentName:m.component_name||null,pageFilePath:m.page_file_path||null,url:m.url||null}));return console.log(`[editorScenarioLookup] Found ${h.length} session scenarios with screenshots`),h}catch(t){return console.error("[editorScenarioLookup] Failed to look up session scenario screenshots:",t),[]}}async function Mo(e,t,r){const s=H.join(t,".codeyam","journal","screenshots");await Ae.mkdir(s,{recursive:!0});const a=[];for(const o of e){const i=H.join(t,".codeyam","editor-scenarios",o.screenshotPath),l=Hv(o.name,r),c=H.join(s,l);console.log(`[editorScenarioLookup] Copying scenario screenshot: "${o.name}" from ${i} → ${c}`);try{await Ae.access(i),await Ae.copyFile(i,c),a.push({name:o.name,path:`screenshots/${l}`,componentName:o.componentName,url:o.url}),console.log(`[editorScenarioLookup] Successfully copied screenshot for "${o.name}"`)}catch(p){console.warn(`[editorScenarioLookup] Scenario screenshot not found: ${i}`,p instanceof Error?p.message:p)}}return console.log(`[editorScenarioLookup] Scenario screenshot summary: ${a.length} scenarios have screenshots embedded`),a}async function ew({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=H.join(l,".codeyam","journal"),p=H.join(c,"index.json");console.log(`[editor-journal-update] Updating entry with time="${r}"`);let u={entries:[]};try{const g=await Ae.readFile(p,"utf8");u=JSON.parse(g)}catch{return new Response(JSON.stringify({error:"No journal index found"}),{status:404,headers:{"Content-Type":"application/json"}})}const h=Kv(u.entries,r);if(h===-1)return new Response(JSON.stringify({error:`No journal entry found with time "${r}"`}),{status:404,headers:{"Content-Type":"application/json"}});const m=u.entries[h];if(Gv(m))return console.log(`[editor-journal-update] Rejected: entry "${m.title}" already committed (${m.commitSha}). Create a new entry instead.`),new Response(JSON.stringify({error:`Journal entry already committed (${m.commitSha}). Create a new entry via POST /api/editor-journal-entry instead of updating.`}),{status:409,headers:{"Content-Type":"application/json"}});let f,y;if(i){const g=await Ru();g.length>0&&(f=g.map(x=>x.name),y=await Mo(g,l,new Date))}if(qv(m,{commitSha:s,commitMessage:a,description:o,scenarios:f,scenarioScreenshots:y}),u.entries[h]=m,await Ae.writeFile(p,JSON.stringify(u,null,2),"utf8"),console.log("[editor-journal-update] Updated index.json"),s)try{const g=m.date,x=H.join(c,`${g}.md`);let b="";try{b=await Ae.readFile(x,"utf8")}catch{}if(b){const v=Qv(b,m.title,s,a||null);v&&(await Ae.writeFile(x,v,"utf8"),console.log(`[editor-journal-update] Appended commit line to ${x}`))}}catch(g){console.warn("[editor-journal-update] Failed to update markdown:",g)}return ft.notifyChange("journal"),console.log(`[editor-journal-update] Done: updated entry "${m.title}"`),new Response(JSON.stringify({success:!0,entry:m}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-update] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const tw=Object.freeze(Object.defineProperty({__proto__:null,action:ew},Symbol.toStringTag,{value:"Module"}));async function nw({request:e}){var t;try{const r=process.env.CODEYAM_ROOT_PATH||process.cwd(),s=await Nu(r);let a=0;const o={};for(const[c,p]of Object.entries(s))p.errors.length>0&&(o[c]=p,a+=p.errors.length);let i=Bl();if(!i)for(let c=0;c<20&&(await new Promise(p=>setTimeout(p,500)),i=Bl(),!i);c++);const l=((t=i==null?void 0:i.errors)==null?void 0:t.length)??0;return new Response(JSON.stringify({hasErrors:a>0||l>0,totalErrors:a+l,scenarios:o,livePreview:i?{loaded:i.loaded,hasContent:i.hasContent,errors:i.errors,url:i.url,lastUpdated:i.lastUpdated}:null}),{headers:{"Content-Type":"application/json"}})}catch(r){const s=r instanceof Error?r.message:String(r);return console.error("[editor-client-errors] Error:",r),new Response(JSON.stringify({error:s}),{status:500,headers:{"Content-Type":"application/json"}})}}const rw=Object.freeze(Object.defineProperty({__proto__:null,loader:nw},Symbol.toStringTag,{value:"Module"}));async function sw({request:e}){try{const r=(await $n()||[]).filter(i=>i.analyses&&i.analyses.length>0).map(i=>{var y;const l=i.analyses[0],c=l.scenarios||[],p=!((y=l.status)!=null&&y.finishedAt),u=i.entityType||"visual",m=u==="library"||u==="functionCall"?c.some(g=>{var x;return!!((x=g.metadata)!=null&&x.executionResult)}):c.some(g=>{var x,b,v,N;return((b=(x=g.metadata)==null?void 0:x.screenshotPaths)==null?void 0:b[0])&&!((v=g.metadata)!=null&&v.noScreenshotSaved)&&!((N=g.metadata)!=null&&N.sameAsDefault)}),f=c.length;return{name:i.name,entityType:u,filePath:i.filePath||"",hasScreenshot:m,isAnalyzing:p,scenarioCount:f}}),s=r.filter(i=>i.hasScreenshot),a=r.filter(i=>!i.hasScreenshot&&!i.isAnalyzing).map(i=>i.name),o=r.filter(i=>i.isAnalyzing).length;return new Response(JSON.stringify({entities:r,summary:{total:r.length,withScreenshots:s.length,missingScreenshots:a,analyzing:o}}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-entity-status] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const aw=Object.freeze(Object.defineProperty({__proto__:null,loader:sw},Symbol.toStringTag,{value:"Module"}));async function ow({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{title:r,type:s,description:a,scenarios:o,includeSessionScenarios:i,screenshot:l,commitSha:c,commitMessage:p}=t;if(console.log(`[editor-journal-entry] Creating journal entry: title="${r}", type="${s}", scenarios=${JSON.stringify(o||[])}, includeSessionScenarios=${!!i}, screenshot=${l||"none"}`),!r||!s||!a)return console.warn("[editor-journal-entry] Missing required fields:",{title:!!r,type:!!s,description:!!a}),new Response(JSON.stringify({error:"title, type, and description are required"}),{status:400,headers:{"Content-Type":"application/json"}});const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=H.join(u,".codeyam","journal");await Ae.mkdir(h,{recursive:!0});const m=new Date,f=m.toISOString().split("T")[0],y=m.toISOString();let g=o||[];const x=H.join(h,"index.json");let b={entries:[]};try{const T=await Ae.readFile(x,"utf8");b=JSON.parse(T)}catch{}let v;i&&b.entries.length>0&&(v=b.entries[b.entries.length-1].time);const N=i?await Ru(v):o&&o.length>0?await Zv(o):[];i&&N.length>0&&(g=N.map(T=>T.name));const w=await Mo(N,u,m);let C;try{const T=Ce()||process.cwd(),B=await Ye();if(B){const{project:Y}=await Re(B),L=await $e().selectFrom("editor_scenarios").select(["name","component_name","component_path","page_file_path","url","display_name"]).where("project_id","=",Y.id).orderBy("created_at","asc").execute(),R=_t(L,J=>`${J.name}::${J.url||"/"}`).map(J=>({componentName:J.component_name||null,componentPath:J.component_path||null,pageFilePath:J.page_file_path??null,url:J.url??null,displayName:J.display_name??null})),E=await gr({projectRoot:T,scenarioInputs:R});Object.keys(E.entityChangeStatus).length>0&&(C=E.entityChangeStatus)}}catch{}if(C&&Object.keys(C).length>0){const T=new Set(N.map(Y=>Y.name)),B=Object.entries(C).filter(([,Y])=>Y.status==="impacted").map(([Y])=>Y);if(B.length>0){const Y=[],I=new Set(N.map(L=>Gt(L)));for(const L of B)I.has(L)||Y.push(L);if(Y.length>0)try{const L=await Xv(Y);if(L.length>0){const P=await Mo(L.filter(R=>!T.has(R.name)),u,m);w.push(...P),g.push(...P.map(R=>R.name))}}catch{}}}let S=w,k=g;if(!i&&C&&Object.keys(C).length>0){S=q0(w,C);const T=new Set(S.map(B=>B.name));k=g.filter(B=>T.has(B))}const j=Ca(u),_=_i(u);let F;try{const T=fr();T.length>0&&(F=T.filter(B=>B.status!=="deleted").map(B=>({path:B.path,status:B.status})))}catch{}const M=H.join(h,`${f}.md`);let $="";try{$=await Ae.readFile(M,"utf8")}catch{$=`# Development Journal — ${f}
444
- `}const O=Vv({title:r,timeStr:y,type:s,description:a,allScenarioNames:k,screenshot:l||null,scenarioScreenshots:S,commitSha:c||null,commitMessage:p||null,featureName:j,userPrompt:_});await Ae.writeFile(M,$+O,"utf8"),console.log(`[editor-journal-entry] Written daily markdown: ${M}`);const D={date:f,time:y,title:r,type:s,description:a,scenarios:k,screenshot:l||null,scenarioScreenshots:S,commitSha:c||null,commitMessage:p||null,entityChangeStatus:C,featureName:j,userPrompt:_,modifiedFiles:F};b.entries.push(D),await Ae.writeFile(x,JSON.stringify(b,null,2),"utf8"),console.log(`[editor-journal-entry] Updated index.json (now ${b.entries.length} entries)`);try{await Ae.unlink(H.join(u,"editor-user-prompt.txt"))}catch{}return ft.notifyChange("journal"),console.log(`[editor-journal-entry] Done: title="${r}", scenarioScreenshotsEmbedded=${S.length}`),new Response(JSON.stringify({success:!0,entry:D,scenarioScreenshotsFound:S.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 iw=Object.freeze(Object.defineProperty({__proto__:null,action:ow},Symbol.toStringTag,{value:"Module"}));function lw({request:e}){const t={"Content-Type":"application/json","Access-Control-Allow-Origin":"*"};try{const r=Ce()||process.cwd();let o=new URL(e.url).searchParams.get("scenarioId");if(!o){const c=H.join(r,".codeyam","active-scenario.json");if(!G.existsSync(c))return new Response(JSON.stringify({}),{headers:t});o=JSON.parse(G.readFileSync(c,"utf-8")).scenarioId||null}if(!o)return new Response(JSON.stringify({}),{headers:t});const i=H.join(r,".codeyam","editor-scenarios",`${o}.json`);if(!G.existsSync(i))return new Response(JSON.stringify({}),{headers:t});const l=G.readFileSync(i,"utf-8");return new Response(l,{headers:t})}catch{return new Response(JSON.stringify({}),{headers:t})}}const cw=Object.freeze(Object.defineProperty({__proto__:null,loader:lw},Symbol.toStringTag,{value:"Module"}));async function dw({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=Array.isArray(t.paths)?t.paths:[],s=Array.isArray(t.apiRoutes)?t.apiRoutes:[];if(r.length===0&&s.length===0)return new Response(JSON.stringify({error:'At least one entry in "paths" or "apiRoutes" is required.'}),{status:400,headers:{"Content-Type":"application/json"}});const a=globalThis.__codeyam_editor_dev_server__;if(!a||!a.url||a.status!=="running")return new Response(JSON.stringify({error:`Dev server is not running. Start it with: codeyam editor dev-server '{"action":"start"}'`}),{status:503,headers:{"Content-Type":"application/json"}});const o=a.url,i=1e4,l={},c={};let p=!0;for(const f of r)try{const y=await fetch(`${o}${f}`,{signal:AbortSignal.timeout(i)}),g=y.ok;g||(p=!1),l[f]={status:y.status,ok:g}}catch(y){p=!1,l[f]={status:0,ok:!1,error:y.message}}for(const f of s)try{const y=await fetch(`${o}${f}`,{signal:AbortSignal.timeout(i)}),g=y.ok;g||(p=!1);let x=!1,b;try{const v=await y.text();JSON.parse(v),x=!0,b=v.length>200?v.slice(0,200)+"…":v}catch{}c[f]={status:y.status,ok:g,isJSON:x,preview:b}}catch(y){p=!1,c[f]={status:0,ok:!1,isJSON:!1,error:y.message}}const u=r.length+s.length,h=Object.values(l).filter(f=>f.ok).length+Object.values(c).filter(f=>f.ok).length,m=p?`All ${u} routes OK`:`${h}/${u} routes passed`;return new Response(JSON.stringify({ok:p,routes:l,apiRoutes:c,summary:m}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-verify-routes] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const uw=Object.freeze(Object.defineProperty({__proto__:null,action:dw},Symbol.toStringTag,{value:"Module"}));async function pw(e,t){const r=Ce();if(!r)return{entityCalls:[],analysisCalls:[]};const s=H.join(r,".codeyam","llm-calls");try{await Ae.access(s)}catch{return{entityCalls:[],analysisCalls:[]}}const a=[],o=[];try{const l=(await Ae.readdir(s)).filter(b=>b.endsWith(".json")),c=`${e}_`,p=t?`${t}_`:null,u=[],h=[];for(const b of l)b.startsWith(c)||p&&b.startsWith(p)?u.push(b):h.push(b);const m=u.map(async b=>{try{const v=H.join(s,b),N=await Ae.readFile(v,"utf-8");return JSON.parse(N)}catch{return null}}),f=h.map(async b=>{try{const v=H.join(s,b),N=await Ae.readFile(v,"utf-8"),w=JSON.parse(N);return w.object_id===e||t&&w.object_id===t?w:null}catch{return null}}),[y,g]=await Promise.all([Promise.all(m),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,v)=>v.created_at-b.created_at),o.sort((b,v)=>v.created_at-b.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:a,analysisCalls:o}}async function hw({params:e,request:t}){const{entitySha:r}=e;if(!r)return re({error:"Entity SHA is required"},{status:400});const a=new URL(t.url).searchParams.get("analysisId")||void 0,o=await pw(r,a);return re(o)}const mw=Object.freeze(Object.defineProperty({__proto__:null,loader:hw},Symbol.toStringTag,{value:"Module"}));function fw(){try{const e=Ce()||process.cwd(),t=ee.join(e,".codeyam","config.json");if(!ue.existsSync(t))return Response.json({projectTitle:null,projectDescription:null,defaultScreenSize:null,screenSizes:null,projectScreenSizes:null,appFormats:null});const r=JSON.parse(ue.readFileSync(t,"utf8"));return Response.json({projectTitle:r.projectTitle||null,projectDescription:r.projectDescription||null,defaultScreenSize:r.defaultScreenSize||null,screenSizes:r.screenSizes||null,projectScreenSizes:r.projectScreenSizes||null,appFormats:r.appFormats||null,techStack:r.techStack||null})}catch{return Response.json({projectTitle:null,projectDescription:null,defaultScreenSize:null,screenSizes:null,appFormats:null,techStack:null})}}async function gw({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ce()||process.cwd(),r=ee.join(t,".codeyam","config.json");if(!ue.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(ue.readFileSync(r,"utf8"));if(s.projectTitle!==void 0&&(a.projectTitle=s.projectTitle),s.projectDescription!==void 0&&(a.projectDescription=s.projectDescription),s.defaultScreenSize!==void 0&&(a.defaultScreenSize=s.defaultScreenSize),s.screenSizes!==void 0&&(a.screenSizes=s.screenSizes),s.appFormats!==void 0&&(a.appFormats=s.appFormats),s.techStack!==void 0&&(a.techStack=s.techStack),s.projectScreenSizes!==void 0&&(a.projectScreenSizes=s.projectScreenSizes),s.screenSizes&&!s.defaultScreenSize)for(const[o,i]of Object.entries(s.screenSizes)){const l=i;if(l.default){a.defaultScreenSize={name:o,width:l.width,height:l.height},s.defaultScreenSize=a.defaultScreenSize;break}}return ue.writeFileSync(r,JSON.stringify(a,null,2)),s.defaultScreenSize&&!s.skipBroadcast&&Ni(s.defaultScreenSize),ft.notifyChange("unknown"),new Response(JSON.stringify({success:!0,projectTitle:a.projectTitle||null,projectDescription:a.projectDescription||null,defaultScreenSize:a.defaultScreenSize||null,screenSizes:a.screenSizes||null,projectScreenSizes:a.projectScreenSizes||null,appFormats:a.appFormats||null,techStack:a.techStack||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 yw=Object.freeze(Object.defineProperty({__proto__:null,action:gw,loader:fw},Symbol.toStringTag,{value:"Module"}));function Ou(e){try{const t=H.join(e,"package.json"),r=JSON.parse(G.readFileSync(t,"utf8")),s={...r.dependencies,...r.devDependencies};return s.vitest?"vitest":s.jest?"jest":null}catch{return null}}function xw(e,t){var i;const s=JSON.parse(t).testResults||[],a=[];for(const l of s)for(const c of l.assertionResults||[]){const p=c.ancestorTitles||[],u=c.title||c.fullName||"unknown",h=p.length>0?`${p.join(" > ")} > ${u}`:u;a.push({title:u,fullName:h,status:c.status==="passed"?"passed":c.status==="failed"?"failed":"skipped",duration:c.duration,failureMessages:(i=c.failureMessages)!=null&&i.length?c.failureMessages:void 0})}const o=a.some(l=>l.status==="failed");return{testFilePath:e,status:o?"failed":"passed",testCases:a}}function bw(e,t,r){var l;const a=JSON.parse(r).testResults||[],o=new Map;for(const c of a){const p=c.name||"",u=o.get(p);u?u.push(c):o.set(p,[c])}const i={};e.endsWith("/")||e+"";for(const c of t){const p=H.isAbsolute(c)?c:H.join(e,c),u=o.get(p);if(!u||u.length===0){i[c]={testFilePath:c,status:"error",testCases:[],errorMessage:`File not found in test output: ${c}`};continue}const h=[];for(const f of u)for(const y of f.assertionResults||[]){const g=y.ancestorTitles||[],x=y.title||y.fullName||"unknown",b=g.length>0?`${g.join(" > ")} > ${x}`:x;h.push({title:x,fullName:b,status:y.status==="passed"?"passed":y.status==="failed"?"failed":"skipped",duration:y.duration,failureMessages:(l=y.failureMessages)!=null&&l.length?y.failureMessages:void 0})}const m=h.some(f=>f.status==="failed");i[c]={testFilePath:c,status:m?"failed":"passed",testCases:h}}return i}function vw(e,t,r){return e==="vitest"?{cmd:"node",args:["./node_modules/.bin/vitest","run","--reporter=json","--outputFile",t,...r]}:{cmd:"./node_modules/.bin/jest",args:["--json","--outputFile",t,...r]}}async function ww(e,t){if(t.length===0)return{};const r=Ou(e);if(!r){const c={};for(const p of t)c[p]={testFilePath:p,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};return c}const s=[],a={};for(const c of t){const p=H.isAbsolute(c)?c:H.join(e,c);G.existsSync(p)?s.push(c):a[c]={testFilePath:c,status:"error",testCases:[],errorMessage:"Test file not found"}}if(s.length===0)return a;const o=H.join(Xs.tmpdir(),`codeyam-test-result-${Date.now()}.json`),{cmd:i,args:l}=vw(r,o,s);return new Promise(c=>{var m;const p=xt(i,l,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let u="";(m=p.stderr)==null||m.on("data",f=>{u+=f.toString()});const h=setTimeout(()=>{p.kill("SIGTERM");for(const f of s)a[f]={testFilePath:f,status:"error",testCases:[],errorMessage:"Test timed out after 60 seconds"};c(a)},6e4);p.on("close",()=>{clearTimeout(h);try{const f=G.readFileSync(o,"utf8");G.unlinkSync(o);const y=bw(e,s,f);Object.assign(a,y)}catch{for(const f of s)a[f]={testFilePath:f,status:"error",testCases:[],errorMessage:u.trim().slice(0,500)||"Test runner failed to produce output"}}c(a)}),p.on("error",f=>{clearTimeout(h);for(const y of s)a[y]={testFilePath:y,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${f.message}`};c(a)})})}async function Nw(e,t){const r=Ou(e);if(!r)return{testFilePath:t,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};const s=H.isAbsolute(t)?t:H.join(e,t);if(!G.existsSync(s))return{testFilePath:t,status:"error",testCases:[],errorMessage:"Test file not found"};const a=H.join(Xs.tmpdir(),`codeyam-test-result-${Date.now()}.json`);return new Promise(o=>{var h;let i,l;r==="vitest"?(l="node",i=["./node_modules/.bin/vitest","run","--reporter=json","--outputFile",a,t]):(l="./node_modules/.bin/jest",i=["--json","--outputFile",a,"--testPathPatterns",t]);const c=xt(l,i,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let p="";(h=c.stderr)==null||h.on("data",m=>{p+=m.toString()});const u=setTimeout(()=>{c.kill("SIGTERM"),o({testFilePath:t,status:"error",testCases:[],errorMessage:"Test timed out after 30 seconds"})},3e4);c.on("close",()=>{clearTimeout(u);try{const m=G.readFileSync(a,"utf8");G.unlinkSync(a),o(xw(t,m))}catch{o({testFilePath:t,status:"error",testCases:[],errorMessage:p.trim().slice(0,500)||"Test runner failed to produce output"})}}),c.on("error",m=>{clearTimeout(u),o({testFilePath:t,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${m.message}`})})})}function rc(){return{version:1,results:{}}}function Lu(e,t,r){return e.sourceHash!==t||e.testHash!==r}function Sw(e,t,r){return{testFilePath:e.testFilePath,status:e.status,testCases:e.testCases,...e.errorMessage?{errorMessage:e.errorMessage}:{},sourceHash:t,testHash:r,timestamp:new Date().toISOString()}}function Cw(e,t){return{version:1,results:{...e.results,...t}}}const zu="test-results.json";function Pi(e){const t=H.join(e,".codeyam",zu);try{const r=G.readFileSync(t,"utf8"),s=JSON.parse(r);return s&&s.version===1&&s.results?s:rc()}catch{return rc()}}function kw(e,t){const r=H.join(e,".codeyam");G.mkdirSync(r,{recursive:!0});const s=H.join(r,zu);G.writeFileSync(s,JSON.stringify(t,null,2)+`
445
- `)}function sc(e){try{const t=G.readFileSync(e);return Wo.createHash("sha256").update(t).digest("hex")}catch{return""}}function Ti(e,t){const r={};for(const s of t){const a=H.join(e,s.filePath),o=H.join(e,s.testFile);r[s.testFile]={sourceHash:sc(a),testHash:sc(o)}}return r}function Bu(e,t,r){const s=Pi(e),a=Ti(e,r),o={};for(const[l,c]of Object.entries(t)){const p=a[l];p&&(o[l]=Sw(c,p.sourceHash,p.testHash))}const i=Cw(s,o);kw(e,i)}async function _w({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=Ce()||process.cwd();try{const a=await Nw(s,r);try{const o=H.join(s,".codeyam","glossary.json"),i=G.readFileSync(o,"utf8"),c=fa(JSON.parse(i)).find(p=>p.testFile===r);c&&Bu(s,{[r]:a},[{filePath:c.filePath,testFile:r}])}catch{}return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}catch(a){const o=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({testFilePath:r,status:"error",testCases:[],errorMessage:o}),{status:500,headers:{"Content-Type":"application/json"}})}}const Ew=Object.freeze(Object.defineProperty({__proto__:null,loader:_w},Symbol.toStringTag,{value:"Module"}));function ac(e,t){var r,s;try{return((s=(r=De(`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 jw(e,t,r,s){const a=cr.createHash("sha256");return a.update(`${e}:${t}:${r}:${s}`),a.digest("hex").substring(0,16)}function Yu(){const e=Ce();if(!e)throw new Error("No project root found");const t=ee.join(e,".codeyam","cache","branch-entity-diff");return ue.existsSync(t)||ue.mkdirSync(t,{recursive:!0}),t}function Aw(e){try{const t=Yu(),r=ee.join(t,`${e}.json`);if(!ue.existsSync(r))return null;const s=ue.readFileSync(r,"utf8");return JSON.parse(s)}catch(t){return console.error("Failed to read cache:",t),null}}function Pw(e,t){try{const r=Yu(),s=ee.join(r,`${e}.json`);ue.writeFileSync(s,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function Tw(e,t,r){const s=Ys(t,e),a=Ys(r,e),o=new Map(s.map(u=>[u.name,u])),i=new Map(a.map(u=>[u.name,u])),l=[],c=[],p=[];for(const[u,h]of i){const m=o.get(u);m?m.sha!==h.sha&&c.push({name:u,baseSha:m.sha,compareSha:h.sha,entityType:h.entityType}):l.push(h)}for(const[u,h]of o)i.has(u)||p.push(h);return{filePath:e,newEntities:l,modifiedEntities:c,deletedEntities:p}}function Mw(e,t){const r=Ce();if(!r)throw new Error("No project root found");const s=ac(e,r),a=ac(t,r);if(!s||!a)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=jw(e,t,s,a),i=Aw(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const l=Cu(e,t),c=[];for(const u of l)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const h=Ps(u.path,e,t),m=Ys(h.oldContent,u.path);c.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:m})}else if(u.status==="added"){const h=Ps(u.path,e,t),m=Ys(h.newContent,u.path);c.push({filePath:u.path,newEntities:m,modifiedEntities:[],deletedEntities:[]})}else{const h=Ps(u.path,e,t),m=Tw(u.path,h.oldContent,h.newContent);(m.newEntities.length>0||m.modifiedEntities.length>0||m.deletedEntities.length>0)&&c.push(m)}const p={baseBranch:e,compareBranch:t,baseCommitSha:s,compareCommitSha:a,fileComparisons:c,cacheKey:o,computedAt:new Date().toISOString()};return Pw(o,p),p}function $w({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),s=t.searchParams.get("compare");if(!r||!s)return re({error:"Missing required parameters: base and compare"},{status:400});const a=Mw(r,s);return re(a)}catch(t){return console.error("Failed to compute branch entity diff:",t),re({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const Iw=Object.freeze(Object.defineProperty({__proto__:null,loader:$w},Symbol.toStringTag,{value:"Module"}));async function Fw({request:e}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:s,projectId:a,viewportWidth:o=1440}=t;if(!r||!s||!a)return re({error:"Missing required fields: serverUrl, scenarioId, and projectId"},{status:400});console.log(`[Capture] URL to capture: ${r}`),console.log(`[Capture] Scenario ID from request: ${s}`);const i=Ce();if(!i)return re({error:"Project root not found"},{status:500});const l=H.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),c=JSON.stringify({url:r,scenarioId:s,projectId:a,projectRoot:i,viewportWidth:o}),p=await new Promise(m=>{const f=H.join(i,".codeyam","db.sqlite3"),y=xt("npx",["tsx",l,c],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let g="",x="";y.stdout.on("data",b=>{const v=b.toString();g+=v;const N=v.trim().split(`
446
- `);for(const w of N)w.includes("[Capture]")&&console.log(w)}),y.stderr.on("data",b=>{const v=b.toString();x+=v,console.error("[Capture:Error]",v.trim())}),y.on("close",b=>{m(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),m({success:!1,output:"",error:b.message})})});if(!p.success)return re({error:"Failed to capture screenshot",details:p.error},{status:500});const u=p.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return re({error:"Failed to parse capture result"},{status:500});const h=JSON.parse(u[1]);return re(h)}catch(t){return console.error("[Capture] Error:",t),re({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const Dw=Object.freeze(Object.defineProperty({__proto__:null,action:Fw},Symbol.toStringTag,{value:"Module"}));function Rw(e){const t=e||process.cwd();try{return De("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 Ow(e){const t=e||process.cwd();try{return De("git rev-parse --git-dir",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),!0}catch{return!1}}function Lw(e){if(Ow(e))return!1;De("git init",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]});try{De('git config user.email "codeyam@local"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),De('git config user.name "CodeYam"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}catch{}return!0}function zw(e){De("git add -A",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}function Bw(e,t){return De(`git commit -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Rw(e)}function Yw(e){return/^[0-9a-f]{7,40}$/i.test(e)}function Ww(e,t){try{return De(`git cat-file -t ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"}),!0}catch{return!1}}function Uw(e,t){try{return{stashed:!De(`git stash push -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:"pipe"}).includes("No local changes")}}catch{return{stashed:!1}}}function Jw(e,t){De(`git checkout ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"})}async function Hw({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(!Yw(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}`),!Ww(s,r))return new Response(JSON.stringify({success:!1,error:`Commit ${r} not found`}),{status:400,headers:{"Content-Type":"application/json"}});const{stashed:a}=Uw(s,"codeyam: auto-stash before time travel");a&&console.log("[editor-load-commit] Stashed uncommitted changes");try{Jw(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 Vw=Object.freeze(Object.defineProperty({__proto__:null,action:Hw},Symbol.toStringTag,{value:"Module"}));async function Kw(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await Je();const s=await Vt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const a=$e(),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 ur(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=Ce();if(!c)throw new Error("Project root not found");const p=H.join(c,".codeyam","config.json"),u=JSON.parse(G.readFileSync(p,"utf8")),{projectSlug:h}=u;if(!h)throw new Error("Project slug not found in config");const{jobId:m}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:h,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${m}`),{jobId:m}}async function Gw(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await Je();const s=await Vt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const a=(u=s.scenarios)==null?void 0:u.find(h=>h.id===t);if(!a)throw console.log(`[recapture] Scenario ${t} not found in analysis ${e}`),new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${a.name}`),await ur(e,h=>{if(h&&(h.readyToBeCaptured=!0,delete h.finishedAt,h.scenarios)){const m=h.scenarios.find(f=>f.name===a.name);m&&(delete m.finishedAt,delete m.startedAt,delete m.error,delete m.errorStack,delete m.screenshotStartedAt,delete m.screenshotFinishedAt,delete m.interactiveStartedAt,delete m.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${a.name} for recapture`);const o=Ce();if(!o)throw new Error("Project root not found");const i=H.join(o,".codeyam","config.json"),l=JSON.parse(G.readFileSync(i,"utf8")),{projectSlug:c}=l;if(!c)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:c,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${p}`),{jobId:p}}async function qw({request:e,context:t}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Kt()),!r)return re({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a||!o)return re({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${a}, scenario ${o}`);const i=await Gw(a,o,r);return console.log("[API] Scenario recapture queued",i),re({success:!0,message:"Scenario recapture queued",...i})}catch(s){return console.log("[API] Error during scenario recapture:",s),re({error:"Failed to recapture scenario",details:s instanceof Error?s.message:String(s)},{status:500})}}const Qw=Object.freeze(Object.defineProperty({__proto__:null,action:qw},Symbol.toStringTag,{value:"Module"}));async function $o(e){try{return await Pe.stat(e),!0}catch{return!1}}async function Wu(){try{const e=Ce();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await Pe.readFile(t,"utf-8")).projectSlug||null}catch{return null}}function Zw(){return`/private/tmp/claude-501/-${(Ce()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const Ts="/tmp/claude-rule-markers",Xw=/<system-reminder>[\s\S]*?<\/system-reminder>/g,oc=2e3;function eN(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 tN=["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 nN(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 rN(e){if(!e)return;const t="### Session transcript",r=e.indexOf(t);if(r===-1)return;let s=e.slice(r+t.length).trim();const a=s.indexOf(`
447
- ###`);return a!==-1&&(s=s.slice(0,a).trim()),s||void 0}function sN(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const s of tN)if(r.includes(s))return!0}return!1}function aN(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 oN(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 iN(e){const t=[],r={};for(const s of e){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}const i=o.type;if(i==="progress"||i==="system"||i==="result")continue;const c=(o.message||{}).content,p=o.timestamp||"";if(i==="user"){if(typeof c=="string")t.push({type:"user_prompt",text:c,timestamp:p,agent_id:String(o.agentId||o.session_id||"unknown"),slug:String(o.slug||"")});else if(Array.isArray(c)){for(const u of c)if(typeof u=="object"&&u!==null&&u.type==="tool_result"){const h=u,m=String(h.tool_use_id||"");let f=h.content;const y=!!h.is_error;typeof f=="string"&&(f=f.replace(Xw,"").trim()),t.push({type:"tool_result",tool_use_id:m,tool_name:r[m]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:y,timestamp:p})}}}else if(i==="assistant"&&Array.isArray(c))for(const u of c){if(typeof u!="object"||u===null)continue;const h=u;if(h.type==="text"){const m=String(h.text||"").trim();m&&t.push({type:"assistant_text",text:m,timestamp:p})}else if(h.type==="tool_use"){const m=String(h.id||""),f=String(h.name||"unknown"),y=h.input||{};r[m]=f,t.push({type:"tool_call",tool_use_id:m,name:f,input:y,timestamp:p})}}}return t}function lN(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 Zn=20;async function ic(e){const r=(await Pe.readFile(e.filePath,"utf-8")).split(`
448
- `),s=iN(r);if(s.length===0)return null;const a=s.find(N=>N.type==="user_prompt"),o=e.stem,i=aN(r);let l=(a==null?void 0:a.slug)||"",c=(a==null?void 0:a.timestamp)||"";c||(c=new Date(e.mtime).toISOString());let p;if(e.filePath.endsWith(".log")){e.stem.endsWith("-stale")?l=l||"rule-reflection/stale":e.stem.endsWith("-conversation")?l=l||"rule-reflection/conversation":e.stem.endsWith("-interruption")?l=l||"rule-reflection/interruption":l=l||"rule-reflection";const N=e.filePath.replace(/\.log$/,".context");if(await $o(N))try{p=await Pe.readFile(N,"utf-8")}catch{}}const u=s.filter(N=>N.type==="tool_call").length,h=s.filter(N=>N.type==="assistant_text").length,m=s.filter(N=>N.type==="tool_result"&&N.is_error&&N.content!=="Sibling tool call errored"),f=m.length,y=m.map(N=>{const w=N.content||"Unknown error";return w.length>150?w.slice(0,150)+"...":w});for(const N of s)N.type==="tool_call"&&N.name&&N.input&&(N.summary=eN(N.name,N.input));for(const N of s)N.type==="tool_result"&&N.content&&N.content.length>oc&&(N.truncated=!0,N.fullLength=N.content.length,N.content=N.content.slice(0,oc));const g=nN(s),x=sN(s),b=rN(p),v=oN(r);return{id:o,slug:l,timestamp:c,model:i,sourceFile:e.filePath,stats:{toolCalls:u,textBlocks:h,errors:f,errorMessages:y},entries:s,context:p,conversationSnippet:b,ruleChanges:g,hasConfusion:x,sessionResult:v}}async function cN(){const e=Zw(),t=Ts,r=[];if(await $o(e)){const i=await Pe.readdir(e);for(const l of i)if(l.endsWith(".output")){const c=ee.join(e,l),p=await Pe.stat(c);r.push({filePath:c,stem:l.replace(".output",""),mtime:p.mtimeMs})}}const s=new Set,a=await Wu(),o=[];a&&o.push(ee.join(t,a)),o.push(t);for(const i of o){if(!await $o(i))continue;const l=await Pe.readdir(i);for(const c of l){if(!c.endsWith(".log")||s.has(c))continue;s.add(c);const p=ee.join(i,c),u=await Pe.stat(p);r.push({filePath:p,stem:c.replace(".log",""),mtime:u.mtimeMs})}}return r.sort((i,l)=>l.mtime-i.mtime),r}async function dN({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 cN();if(!s){const u=o.length,h=(a-1)*Zn,m=o.slice(h,h+Zn),f=[];for(const y of m){const g=await ic(y);g&&f.push(g)}return Response.json({agents:f,total:u,page:a,pageSize:Zn})}const i=[];for(const u of o){const h=await ic(u);if(!h)continue;(h.id.toLowerCase().includes(s)||h.slug.toLowerCase().includes(s)||h.entries.some(f=>lN(f,s)))&&i.push(h)}const l=i.length,c=(a-1)*Zn,p=i.slice(c,c+Zn);return Response.json({agents:p,total:l,page:a,pageSize:Zn})}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 uN=Object.freeze(Object.defineProperty({__proto__:null,loader:dN},Symbol.toStringTag,{value:"Module"})),Uu="__codeyam_editor_dev_server__",lc=30;function Mi(){return globalThis[Uu]??null}function Ju(e){globalThis[Uu]=e}function vs(e,t){const r=[ee.join(e,".next","dev","lock"),ee.join(e,"node_modules",".vite","deps","_lock")];for(const s of r)try{ue.existsSync(s)&&(ue.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=De(`lsof -ti:${t}`,{encoding:"utf8"}).trim();if(s){const a=process.pid,o=s.split(`
449
- `).filter(i=>i&&parseInt(i,10)!==a);if(o.length>0){for(const i of o)try{De(`kill ${i}`)}catch{}console.log(`[editor-dev-server] Killed orphaned process(es) on port ${t}: ${o.join(", ")}`)}}}catch{}}function pN({request:e}){const t=Mi();return t?new Response(JSON.stringify({status:t.status,url:t.url,proxyUrl:pu(),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 hN({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"?Io():r==="stop"?cc():r==="restart"?(cc(),await new Promise(s=>setTimeout(s,1e3)),Io()):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 mN(){let t=ee.dirname(new URL(import.meta.url).pathname);for(let s=0;s<5;s++){const a=ee.dirname(t);if(ee.basename(a)==="webserver"||ee.basename(t)==="webserver"){t=ee.basename(t)==="webserver"?t:a;break}t=a}const r=[ee.join(t,"scripts","codeyam-preload.mjs"),ee.join(t,"scripts","codeyam-preload.mjs")];for(const s of r)if(ue.existsSync(s))return s;return console.warn("[editor-dev-server] codeyam-preload.mjs not found, SSR fetch interception disabled"),null}function Io(e=!1){var k,j;const t=Mi();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=Ce()||process.cwd(),s=parseInt(process.env.CODEYAM_PORT||"3111",10),{proxyPort:a,devServerPort:o}=su(s),i=Ay(r,o);if("error"in i)return new Response(JSON.stringify({error:i.error}),{status:400,headers:{"Content-Type":"application/json"}});const{command:l,args:c,env:p}=i;vs(r,o),vs(r,3e3),vs(r,3001),vs(r,5173),console.log(`[editor-dev-server] Starting: ${l} ${c.join(" ")} in ${r}`);const u=mN(),h=u?`--import ${u}`:"",{NODE_OPTIONS:m,PORT:f,CODEYAM_PORT:y,...g}=process.env,x={};for(const _ of[".env",".env.local",".env.development",".env.development.local"])try{const F=ee.join(r,_);if(!ue.existsSync(F))continue;const M=ue.readFileSync(F,"utf-8");for(const $ of M.split(`
450
- `)){const O=$.trim();if(!O||O.startsWith("#"))continue;const D=O.indexOf("=");if(D===-1)continue;const T=O.slice(0,D).trim();let B=O.slice(D+1).trim();(B.startsWith('"')&&B.endsWith('"')||B.startsWith("'")&&B.endsWith("'"))&&(B=B.slice(1,-1)),T&&(x[T]=B)}}catch{}const b={};try{const _=ee.join(r,".codeyam","config.json"),F=JSON.parse(ue.readFileSync(_,"utf-8"));for(const M of F.environmentVariables||[])M.key&&M.value!==void 0&&(b[M.key]=M.value)}catch{}const v=xt(l,c,{cwd:r,stdio:["ignore","pipe","pipe"],env:{...g,...x,...b,FORCE_COLOR:"1",BROWSER:"none",...h?{NODE_OPTIONS:h}:{},CODEYAM_PROXY_URL:`http://localhost:${a}`,...p},detached:!0});v.unref();const N=e?((t==null?void 0:t.retryCount)??0)+1:0,w={process:v,url:null,status:"starting",errorMessage:null,stderrBuffer:[],pid:v.pid||0,startedAt:Date.now(),retryCount:N};Ju(w);const C=(_,F)=>{const M=_.toString(),$=M.split(`
451
- `).filter(O=>O.trim());if($.length>0&&(w.stderrBuffer.push(...$),w.stderrBuffer.length>lc&&(w.stderrBuffer=w.stderrBuffer.slice(-lc))),w.status==="starting"){const O=Ty(M);O&&(w.url=O,w.status="running",console.log(`[editor-dev-server] URL detected: ${w.url}`),Eo({port:a,targetUrl:w.url}).then(()=>Ul()))}};(k=v.stdout)==null||k.on("data",_=>C(_)),(j=v.stderr)==null||j.on("data",_=>C(_));const S=parseInt(p.PORT||"0",10);return S>0&&(async()=>{if(await new Promise(F=>setTimeout(F,1e4)),w.status!=="starting")return;console.log(`[editor-dev-server] Stdout detection timed out, polling port ${S}...`);const _=await $y(S,{intervalMs:2e3,maxAttempts:15});_&&w.status==="starting"&&(w.url=_,w.status="running",console.log(`[editor-dev-server] URL detected via polling: ${w.url}`),Eo({port:a,targetUrl:w.url}).then(()=>Ul()))})(),v.on("exit",_=>{console.log(`[editor-dev-server] Process exited with code ${_}`);const F=Date.now()-w.startedAt,M=w.status==="running",$=Iy({exitCode:_??null,uptime:F,retryCount:w.retryCount,wasRunning:M});if($.action==="retry")console.log(`[editor-dev-server] Quick failure (${F}ms), auto-retrying...`),w.status="stopped",Io(!0);else if($.action==="error"){w.status="error";const O=w.stderrBuffer.length>0?w.stderrBuffer.join(`
452
- `):"",D=M?`Dev server exited with code ${_}`:`Dev server exited (code ${_}) before it started serving`;w.errorMessage=O?`${D}
453
-
454
- ${O}`:D,console.error(`[editor-dev-server] Server failed: ${w.errorMessage}`)}else w.status="stopped"}),v.on("error",_=>{console.error("[editor-dev-server] Process error:",_),w.status="error",w.errorMessage=_.message}),new Response(JSON.stringify({status:"starting",pid:v.pid,message:`Starting ${l} ${c.join(" ")}`}),{headers:{"Content-Type":"application/json"}})}function cc(){const e=Mi();if(!e||e.status==="stopped")return new Response(JSON.stringify({status:"stopped",message:"No server to stop"}),{headers:{"Content-Type":"application/json"}});yu();try{e.process.pid&&process.kill(-e.process.pid,"SIGTERM")}catch{try{e.process.kill("SIGTERM")}catch{}}return e.status="stopped",Ju(null),new Response(JSON.stringify({status:"stopped",message:"Dev server stopped"}),{headers:{"Content-Type":"application/json"}})}const fN=Object.freeze(Object.defineProperty({__proto__:null,action:hN,loader:pN},Symbol.toStringTag,{value:"Module"}));async function gN({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=Gr(r);try{return await $r(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 yN({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=Gr(t);try{if(!Ct(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 bo(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 xN=Object.freeze(Object.defineProperty({__proto__:null,action:gN,loader:yN},Symbol.toStringTag,{value:"Module"}));function bN({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return Response.json({error:"Missing path parameter"},{status:400});const s=Ce()||process.cwd(),a=H.resolve(s,r);if(!a.startsWith(s+H.sep)&&a!==s)return Response.json({error:"Path outside project root"},{status:403});const o=ku(r,s);return Response.json(o)}const vN=Object.freeze(Object.defineProperty({__proto__:null,loader:bN},Symbol.toStringTag,{value:"Module"}));async function wN(){const e=await Ye();if(!e)return Response.json({error:"No project configured"},{status:400});const{project:t}=await Re(e),r=$e(),s=process.env.CODEYAM_PORT||"3111",a=Ce()||process.cwd(),o=await r.selectFrom("editor_scenarios").select(["id","name","component_name","component_path","url","type","screenshot_path","page_file_path","display_name"]).where("project_id","=",t.id).orderBy("created_at","asc").execute(),i=_t(o,p=>`${p.name}::${p.url||"/"}`);let l={};try{const p=i.map(h=>({componentName:h.component_name||null,componentPath:h.component_path||null,pageFilePath:h.page_file_path??null,url:h.url??null,displayName:h.display_name??null}));l=(await gr({projectRoot:a,scenarioInputs:p})).entityChangeStatus}catch{}const c=i.map(p=>{const u=p,h=Gt({componentName:p.component_name,pageFilePath:u.page_file_path,url:u.url}),m=h?l[h]:void 0;return{id:p.id,name:p.name,componentName:p.component_name||null,type:p.type||null,changeStatus:(m==null?void 0:m.status)||null,screenshotPath:p.screenshot_path||null,link:`http://localhost:${s}/editor?scenario=${p.id}&ref=link`}});return Response.json({scenarios:c})}const NN=Object.freeze(Object.defineProperty({__proto__:null,loader:wN},Symbol.toStringTag,{value:"Module"}));async function SN(e,t){var o,i,l,c,p,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await Je();const r=await Vt({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const s=(o=r.scenarios)==null?void 0:o.find(h=>h.id===t);if(!s)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${s.name}`);const a={returnValue:{status:"success",data:((c=(l=(i=s.metadata)==null?void 0:i.data)==null?void 0:l.argumentsData)==null?void 0:c[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(p=s.metadata)==null?void 0:p.data)==null?void 0:u.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),a}async function CN({request:e}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),s=t.get("scenarioId");if(!r||!s)return re({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${s}`);const a=await SN(r,s);return console.log("[API] Function execution completed successfully"),re({success:!0,result:a})}catch(t){return console.log("[API] Error during function execution:",t),re({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const kN=Object.freeze(Object.defineProperty({__proto__:null,action:CN},Symbol.toStringTag,{value:"Module"}));function _N({request:e}){return re({status:"ok"})}async function EN({request:e,context:t}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Kt()),!r)return console.error("[Interactive Mode API] Queue not initialized"),re({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("action"),o=s.get("analysisId"),i=s.get("scenarioId");if(!a||!o)return re({error:"Missing required fields: action and analysisId"},{status:400});if(a!=="start"&&a!=="stop")return re({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await Ye();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return re({error:"Project not initialized"},{status:500});if(a==="start"){const c=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:l});return re({success:!0,action:"start",message:"Interactive mode starting...",jobId:c})}else{const c=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:l});return re({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:c})}}catch(s){console.error("[Interactive Mode API] Error:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Interactive Mode API] Error stack:",o),re({error:"Failed to control interactive mode",details:a},{status:500})}}const jN=Object.freeze(Object.defineProperty({__proto__:null,action:EN,loader:_N},Symbol.toStringTag,{value:"Module"}));async function AN({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=Ce();if(a)for(const o of s){const i=ee.join(a,".codeyam","captures","screenshots",o);try{await Pe.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 Lf({ids:[r]});try{await $e().deleteFrom("editor_scenarios").where("id","=",r).execute()}catch{}try{const a=Ce()||process.cwd();Px(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 PN=Object.freeze(Object.defineProperty({__proto__:null,action:AN},Symbol.toStringTag,{value:"Module"}));class TN extends Vr{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 Fo="__codeyam_dev_mode_event_emitter__";if(!globalThis[Fo]){const e=new TN;e.setMaxListeners(20),globalThis[Fo]=e}const dc=globalThis[Fo];function MN({request:e}){const t=new ReadableStream({start(r){const s=new TextEncoder;r.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
455
-
456
- `));let a=!1;const o=()=>{if(!a){a=!0,dc.off("event",i),clearInterval(l);try{r.close()}catch{}}},i=c=>{try{r.enqueue(s.encode(`data: ${JSON.stringify(c)}
457
-
458
- `))}catch{o()}};dc.on("event",i);const l=setInterval(()=>{try{r.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
459
-
460
- `))}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 $N=Object.freeze(Object.defineProperty({__proto__:null,loader:MN},Symbol.toStringTag,{value:"Module"})),Wr="/tmp/codeyam",Do=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",Hu=500,IN=Hu*1024*1024;function Cn(e,t){try{return De(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function Ms(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Vu(e){return Cn("config user.email",e)}function FN(e){const t=H.join(e,".codeyam","debug-report.md");if(!G.existsSync(t))return null;try{return G.readFileSync(t,"utf8")}catch{return null}}function DN(e,t=20){const r=H.join(Wr,"local-dev",e,"codeyam","log.txt");if(!G.existsSync(r))return[];try{return G.readFileSync(r,"utf8").split(`
461
- `).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function RN(e){try{const t=await fetch(`${Do}/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 ON(e,t){try{De(`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 LN(e){const{projectRoot:t,projectSlug:r,outputPath:s,metadata:a,screenshot:o,onProgress:i}=e,l=i||(()=>{}),c=Date.now(),p=H.join(Wr,`delta-staging-${c}`),u=H.join(p,"delta");G.mkdirSync(u,{recursive:!0});try{const h=Cn("diff --binary HEAD",t)||"";G.writeFileSync(H.join(u,"tracked.patch"),h?h+`
462
- `:"");const m=Cn("ls-files --others --exclude-standard",t);if(m){const x=H.join(u,"untracked");G.mkdirSync(x,{recursive:!0});for(const b of m.split(`
463
- `).filter(Boolean)){const v=H.join(t,b),N=H.join(x,b);if(G.existsSync(v)){const w=H.dirname(N);G.mkdirSync(w,{recursive:!0}),G.statSync(v).isFile()&&G.copyFileSync(v,N)}}}const f=H.join(t,".codeyam");if(G.existsSync(f)){const x=H.join(u,"codeyam");G.cpSync(f,x,{recursive:!0})}G.writeFileSync(H.join(u,"meta.json"),JSON.stringify(a,null,2));const y=H.join(Wr,"local-dev",r,"codeyam","log.txt");G.existsSync(y)?G.copyFileSync(y,H.join(u,"codeyam-log.txt")):G.writeFileSync(H.join(u,"codeyam-log.txt"),`# Log file not found
464
- `);const g=H.join(t,".codeyam","debug-report.md");G.existsSync(g)&&(G.copyFileSync(g,H.join(u,"debug-report.md")),l("Debug report included")),o&&o.length>0&&(G.writeFileSync(H.join(u,"screenshot.jpg"),o),l(`Screenshot included (${Ms(o.length)})`));try{De(`tar -czf "${s}" -C "${p}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{G.rmSync(p,{recursive:!0,force:!0})}}async function zN(e){const{projectRoot:t,projectSlug:r,feedback:s,screenshot:a,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const l=Cn("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=Cn("rev-parse --abbrev-ref HEAD",t)||"unknown",p=Cn("status --porcelain",t),u=Cn("remote get-url origin",t),h=p!==null&&p.length>0,m=Bd(r),f=FN(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:h,remoteUrl:u},versions:{cli:m.cliVersion,webserver:m.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:y},x=Date.now(),b=H.join(Wr,`base-${l}-${x}.tar.gz`),v=H.join(Wr,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const N=await RN(l);let w=null;N?i("Server already has base, skipping..."):(i("Generating base archive..."),ON(t,b),w=G.statSync(b).size,i(`Base archive: ${Ms(w)}`)),i("Generating delta archive..."),LN({projectRoot:t,projectSlug:r,outputPath:v,metadata:g,screenshot:a,onProgress:o});const S=G.statSync(v).size;i(`Delta archive: ${Ms(S)}`);const k=(w||0)+S;if(k>IN)throw G.existsSync(b)&&G.unlinkSync(b),G.unlinkSync(v),new Error(`Bundle too large: ${Ms(k)} (max: ${Hu} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:N?null:b,deltaPath:v,metadata:g,baseSha:l,baseSize:w,deltaSize:S}}async function BN(e){const{basePath:t,deltaPath:r,projectSlug:s,metadata:a,baseSha:o,deltaSize:i,onProgress:l}=e,c=l||(()=>{}),p=G.statSync(r),u=t?G.statSync(t):null,h=p.size+((u==null?void 0:u.size)||0);c("Requesting upload URLs...");const m=await fetch(`${Do}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:s,fileSizeBytes:h,baseSha:o,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:a.timestamp,git:a.git,versions:a.versions,system:a.system,feedback:a.feedback}})});if(!m.ok){const N=await m.json();throw new Error(N.error||`Server returned ${m.status}`)}const{reportId:f,deltaUploadUrl:y,baseUploadUrl:g}=await m.json(),x=[];if(t&&g){c("Uploading base...");const N=G.readFileSync(t);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:N}).then(w=>{if(!w.ok)throw new Error(`Base upload failed: ${w.status}`)}))}c("Uploading delta...");const b=G.readFileSync(r);x.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:b}).then(N=>{if(!N.ok)throw new Error(`Delta upload failed: ${N.status}`)})),await Promise.all(x),c("Confirming upload...");const v=await fetch(`${Do}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!v.ok){const N=await v.json();throw new Error(N.error||`Confirm failed: ${v.status}`)}return t&&G.existsSync(t)&&G.unlinkSync(t),G.unlinkSync(r),{bundleId:f}}async function YN({request:e}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),s=t.get("description"),a=t.get("email"),o=t.get("source"),i=t.get("entitySha"),l=t.get("scenarioId"),c=t.get("analysisId"),p=t.get("currentUrl"),u=t.get("entityName"),h=t.get("entityType"),m=t.get("scenarioName"),f=t.get("errorMessage"),y=t.get("screenshot");let g=s||void 0;!g&&u&&(m?g=`Issue on ${u} scenario "${m}"`:g=`Issue on ${u}`);let x;if(y&&y.size>0){const k=await y.arrayBuffer();x=Buffer.from(k),console.log(`[Bundle] Screenshot received: ${y.size} bytes`)}const b=Ce();if(!b)return re({error:"Project root not found"},{status:500});const v=await Ye();if(!v)return re({error:"Project slug not found"},{status:500});const N={issueType:r||"other",description:g,email:a||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:l||void 0,analysisId:c||void 0,currentUrl:p||void 0,recentActivity:DN(v,20),entityName:u||void 0,entityType:h||void 0,scenarioName:m||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${v}...`),console.log(`[Bundle] Context: ${N.source}, issue: ${N.issueType}`);const w=await zN({projectRoot:b,projectSlug:v,feedback:N,screenshot:x,onProgress:k=>{console.log(`[Bundle] ${k}`)}}),C=(w.baseSize||0)+w.deltaSize;console.log(`[Bundle] Archives created: delta=${w.deltaSize} bytes${w.basePath?`, base=${w.baseSize} bytes`:" (base reused)"}`);const S=await BN({basePath:w.basePath,deltaPath:w.deltaPath,projectSlug:v,metadata:w.metadata,baseSha:w.baseSha,deltaSize:w.deltaSize,onProgress:k=>{console.log(`[Bundle] ${k}`)}});return console.log(`[Bundle] Upload complete: ${S.bundleId}`),re({success:!0,reportId:S.bundleId,size:C})}catch(t){return console.error("[Bundle] Error:",t),re({error:t.message||"Failed to generate bundle"},{status:500})}}function WN(){const e=Ce(),t=e?Vu(e):null;return re({defaultEmail:t})}const UN=Object.freeze(Object.defineProperty({__proto__:null,action:YN,loader:WN},Symbol.toStringTag,{value:"Module"}));async function JN({request:e}){try{const r=new URL(e.url).searchParams.get("date"),s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=H.join(s,".codeyam","journal","index.json");let o={entries:[]};try{const l=await Ae.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 HN=Object.freeze(Object.defineProperty({__proto__:null,loader:JN},Symbol.toStringTag,{value:"Module"}));function Ku(e){if(!G.existsSync(e))return nt.Unknown;try{const t=JSON.parse(G.readFileSync(e,"utf8")),r={...t.dependencies,...t.devDependencies};return r.next?nt.Next:r["@remix-run/node"]||r["@remix-run/react"]||r["react-router"]?nt.Remix:r["react-scripts"]?nt.CRA:r.expo?nt.Expo:r.vite?nt.Vite:nt.Unknown}catch{return nt.Unknown}}function VN(e,t){let r=e;const s=H.resolve(t);for(;;){const a=H.resolve(r);if(G.existsSync(H.join(a,"pnpm-lock.yaml")))return"pnpm";if(G.existsSync(H.join(a,"yarn.lock")))return"yarn";if(G.existsSync(H.join(a,"package-lock.json")))return"npm";if(a===s)break;const o=H.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 KN(e){const t=/cd\s+([^\s;&|]+)\s*(?:&&|;)/,r=e.match(t);return r?r[1]:null}function GN(e){const t=H.join(e,"package.json");if(!G.existsSync(t))return{isWebApp:!1};if(Ku(t)===nt.Unknown)return{isWebApp:!1};try{const a=JSON.parse(G.readFileSync(t,"utf8")).scripts||{},o=["remix","react-router","next dev","vite","react-scripts","webpack-dev-server","parcel","expo"],l=Object.keys(a).filter(c=>["dev","start","serve","build"].some(p=>c.includes(p))).filter(c=>o.some(p=>a[c].includes(p)));if(l.length===0)return{isWebApp:!1};for(const c of l){const p=a[c],u=KN(p);if(u){const h=H.join(e,u);if(G.existsSync(h)&&G.statSync(h).isDirectory())return{isWebApp:!0,actualPath:h}}}return{isWebApp:!0}}catch{return{isWebApp:!1}}}function Gu(e,t=e,r=0,s=3){if(r>s)return[];const a=[],o=GN(t);if(o.isWebApp){const l=o.actualPath||t,c=H.relative(e,l);return a.push(c||"."),a}const i=["node_modules",".git",".next","dist","build",".cache","coverage",".codeyam"];try{const l=G.readdirSync(t,{withFileTypes:!0});for(const c of l)if(c.isDirectory()&&!i.includes(c.name)){const p=H.join(t,c.name);a.push(...Gu(e,p,r+1,s))}}catch{}return a}function qN(e){const t=Gu(e);return t.length===0?[]:t.map(s=>{const a=H.join(e,s),o=H.join(a,"package.json"),i=Ku(o),l=VN(a,e);let c;if(i===nt.Remix||i===nt.Next||i===nt.Expo){const m=H.join(a,"app");G.existsSync(m)&&G.statSync(m).isDirectory()&&(c="app")}const p=QN(s,e),h=p?{command:"sh",args:["-c",`${l} run ${p} -- --port $PORT`]}:void 0;return{path:s,framework:i,packageManager:l,appDirectory:c,startCommand:h}})}function QN(e,t){const r=H.join(t,e),s=H.join(r,"package.json");if(!G.existsSync(s))return null;try{const o=JSON.parse(G.readFileSync(s,"utf8")).scripts||{},i=["dev","start","serve"];for(const l of i)if(o[l])return l;return null}catch{return null}}function ZN(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 XN({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ce()||process.cwd(),r=ee.join(t,".codeyam","config.json");let s=[];try{s=qN(t)}catch{}if(ue.existsSync(r)){const i=JSON.parse(ue.readFileSync(r,"utf8")),l=i.webapps||[];i.webapps=ZN(s,l),s=i.webapps,ue.writeFileSync(r,JSON.stringify(i,null,2))}const a=await Ye();if(a)try{await sr({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 e1=Object.freeze(Object.defineProperty({__proto__:null,action:XN},Symbol.toStringTag,{value:"Module"})),t1=[{id:"plan-project-name",label:"Define project name and description",completed:!1,autoDetect:"project-title-exists"},{id:"plan-tech-stack",label:"Review tech stack",completed:!1,autoDetect:"tech-stack-configured"},{id:"plan-design-system",label:"Create design system",completed:!1,autoDetect:"design-system-exists"},{id:"plan-screen-sizes",label:"Configure screen sizes",completed:!1,autoDetect:"screen-sizes-configured"},{id:"plan-pages-routes",label:"Define pages and routes",completed:!1},{id:"plan-initial-scenarios",label:"Create initial scenarios",completed:!1,autoDetect:"scenarios-exist"}],n1=[{id:"deploy-hosting",label:"Set up hosting provider",completed:!1},{id:"deploy-env-vars",label:"Configure environment variables",completed:!1},{id:"deploy-cicd",label:"Set up CI/CD pipeline",completed:!1},{id:"deploy-domain",label:"Configure custom domain",completed:!1},{id:"deploy-production",label:"Deploy to production",completed:!1}];function qu(){return{plan:t1.map(e=>({...e})),deploy:n1.map(e=>({...e}))}}function Qu(e){return ee.join(e,".codeyam","roadmap.json")}function Zu(e){try{const t=ue.readFileSync(Qu(e),"utf8");return s1(JSON.parse(t))}catch{return qu()}}function r1(e,t){const r=Qu(e),s=ee.dirname(r);ue.existsSync(s)||ue.mkdirSync(s,{recursive:!0}),ue.writeFileSync(r,JSON.stringify(t,null,2))}function uc(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.id!="string"||typeof t.label!="string"?null:{id:t.id,label:t.label,completed:t.completed===!0,...typeof t.completedAt=="string"?{completedAt:t.completedAt}:{},...typeof t.autoDetect=="string"?{autoDetect:t.autoDetect}:{},...t.userCreated===!0?{userCreated:!0}:{}}}function pc(e,t){const r=new Set(e.map(o=>o.id)),s=t.filter(o=>!r.has(o.id));if(s.length===0)return e;const a=[...e];for(const o of s){const i=t.indexOf(o),l=t[i-1];if(l){const c=a.findIndex(p=>p.id===l.id);a.splice(c+1,0,{...o})}else a.unshift({...o})}return a}function s1(e){const t=qu();if(typeof e!="object"||e===null)return t;const r=e,s=Array.isArray(r.plan)?pc(r.plan.map(uc).filter(Boolean),t.plan):t.plan,a=Array.isArray(r.deploy)?pc(r.deploy.map(uc).filter(Boolean),t.deploy):t.deploy;return{plan:s,deploy:a}}const a1={"project-title-exists":e=>{try{const t=ee.join(e,".codeyam","config.json");return!!JSON.parse(ue.readFileSync(t,"utf8")).projectTitle}catch{return!1}},"tech-stack-configured":e=>{try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(ue.readFileSync(t,"utf8"));return r.techStack&&typeof r.techStack=="object"&&Object.values(r.techStack).some(a=>Array.isArray(a)&&a.length>0)?!0:Array.isArray(r.webapps)&&r.webapps.length>0}catch{return!1}},"webapps-configured":e=>{try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(ue.readFileSync(t,"utf8"));return Array.isArray(r.webapps)&&r.webapps.length>0}catch{return!1}},"design-system-exists":e=>ue.existsSync(ee.join(e,".codeyam","design-system.md")),"screen-sizes-configured":e=>{try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(ue.readFileSync(t,"utf8"));return r.screenSizes!=null&&Object.keys(r.screenSizes).length>0}catch{return!1}},"scenarios-exist":e=>{const t=ee.join(e,".codeyam","editor-scenarios");try{return ue.readdirSync(t).some(s=>s.endsWith(".json"))}catch{return!1}}};function o1(e,t){return t.map(r=>{if(!r.autoDetect)return r;const s=a1[r.autoDetect];if(!s)return r;const a=s(e);if(a&&!r.completed)return{...r,completed:!0,completedAt:new Date().toISOString()};if(!a&&r.completed&&!r.userCreated){const{completedAt:o,...i}=r;return{...i,completed:!1}}return r})}function i1(e){try{const t=ee.join(e,".codeyam","journal","index.json"),r=ue.readFileSync(t,"utf8"),s=JSON.parse(r);return Array.isArray(s.entries)?s.entries.length:0}catch{return 0}}function l1(e,t=3){try{const r=ee.join(e,".codeyam","journal","index.json"),s=ue.readFileSync(r,"utf8"),a=JSON.parse(s);return Array.isArray(a.entries)?a.entries.slice().reverse().slice(0,t).map(o=>({title:o.title,time:o.time,type:o.type||"feature"})):[]}catch{return[]}}function c1(){try{const e=Ce()||process.cwd(),t=Zu(e),r=o1(e,t.plan),s=t.deploy,a=i1(e),o=l1(e,3),i=Ca(e),l=Ci(e);let c=null,p=null,u=[],h=null,m=null,f=null,y=null,g=null;try{const x=ee.join(e,".codeyam","config.json"),b=JSON.parse(ue.readFileSync(x,"utf8"));c=b.projectTitle||null,p=b.projectDescription||null,Array.isArray(b.webapps)&&(u=b.webapps.map(v=>({path:v.path||".",framework:v.framework||"Unknown"}))),b.techStack&&typeof b.techStack=="object"&&(h=b.techStack),b.screenSizes&&typeof b.screenSizes=="object"&&(m=b.screenSizes),b.projectScreenSizes&&typeof b.projectScreenSizes=="object"&&(f=b.projectScreenSizes),y=b.defaultScreenSize||null,Array.isArray(b.appFormats)&&(g=b.appFormats)}catch{}return g||(g=ki(e)),Response.json({plan:r,deploy:s,buildSessionCount:a,recentEntries:o,featureName:i,editorStep:(l==null?void 0:l.step)??null,editorStepLabel:(l==null?void 0:l.label)??null,projectTitle:c,projectDescription:p,webapps:u,techStack:h,screenSizes:m,projectScreenSizes:f,defaultScreenSize:y,appFormats:g})}catch{return Response.json({plan:[],deploy:[],buildSessionCount:0,recentEntries:[],featureName:null,editorStep:null,editorStepLabel:null,projectTitle:null,projectDescription:null,webapps:[],techStack:null,screenSizes:null,projectScreenSizes:null,defaultScreenSize:null,appFormats:null})}}async function d1({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ce()||process.cwd(),r=await e.json(),s=Zu(t);return Array.isArray(r.plan)&&(s.plan=r.plan),Array.isArray(r.deploy)&&(s.deploy=r.deploy),r1(t,s),ft.notifyChange("unknown"),Response.json({success:!0,...s})}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 u1=Object.freeze(Object.defineProperty({__proto__:null,action:d1,loader:c1},Symbol.toStringTag,{value:"Module"}));async function p1({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=Ce()||process.cwd();if(t.action==="clear"){ay(r);try{G.unlinkSync(H.join(r,".codeyam","claude-session-id.txt"))}catch{}return new Response(JSON.stringify({success:!0,message:"Editor state cleared"}),{headers:{"Content-Type":"application/json"}})}return new Response(JSON.stringify({error:"Unknown action"}),{status:400,headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const h1=Object.freeze(Object.defineProperty({__proto__:null,action:p1},Symbol.toStringTag,{value:"Module"}));function _n(){const e=process.memoryUsage(),t=um.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(vo.totalmem()/1024/1024),freeMemory:Math.round(vo.freemem()/1024/1024)}}}function m1(){const e=_n();console.log(`
465
- [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 f1(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=_n();global.gc();const t=_n(),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 g1(){const e=_n(),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 y1({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=f1(),a=_n();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=m1();return Response.json({success:!0,stats:s})}case"leaks":{const s=g1(),a=_n();return Response.json({success:!0,leakCheck:s,stats:a})}default:{const s=_n();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 x1=Object.freeze(Object.defineProperty({__proto__:null,loader:y1},Symbol.toStringTag,{value:"Module"})),ws=Ho(Jo);async function b1({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=v1(o),l=i?await w1(o):null;return{pid:o,isRunning:i,processName:l}}));return Response.json({processes:a})}function v1(e){try{return process.kill(e,0),!0}catch{return!1}}async function w1(e){if(process.platform==="win32")try{const{stdout:r}=await ws(`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 ws(`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 ws(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:s}=await ws(`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 N1=Object.freeze(Object.defineProperty({__proto__:null,loader:b1},Symbol.toStringTag,{value:"Module"})),S1=ea(import.meta.url),C1=H.dirname(S1);function k1({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=pa(),r=Ce()||(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=H.join(C1,"..","..","..","..","webserver","bootstrap.js"),o=H.join(r,".codeyam","logs");G.existsSync(o)||G.mkdirSync(o,{recursive:!0});const i=G.openSync(H.join(o,"background-server.log"),"a"),l=G.openSync(H.join(o,"background-server-error.log"),"a"),c=new Date().toISOString();G.appendFileSync(H.join(o,"background-server.log"),`
466
- [${c}] Server restart requested via dashboard
467
- `),oi();const p=xt("node",[a],{detached:!0,stdio:["ignore",i,l],env:{...process.env,CODEYAM_PORT:s.toString(),CODEYAM_ROOT_PATH:r,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});p.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${p.pid})`);const u=new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}});return setTimeout(()=>{console.log("[api.restart-server] Exiting old server process"),process.exit(0)},100),u}catch(t){return console.error("[api.restart-server] Error restarting server:",t),new Response(JSON.stringify({success:!1,error:t instanceof Error?t.message:"Unknown error"}),{status:500,headers:{"Content-Type":"application/json"}})}}const _1=Object.freeze(Object.defineProperty({__proto__:null,action:k1},Symbol.toStringTag,{value:"Module"}));async function E1({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:s}=t;if(!r||!s)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${r.id}`),console.log(`[API] Received ${s.length} scenarios to save`),s.forEach((l,c)=>{var h,m,f,y,g;const p=(m=(h=l.metadata)==null?void 0:h.data)==null?void 0:m.argumentsData,u=Array.isArray(p)&&p.length>0?JSON.stringify(p[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${c}: ${l.name}`,{id:l.id,projectId:l.projectId,analysisId:l.analysisId,hasMetadata:!!l.metadata,hasData:!!((f=l.metadata)!=null&&f.data),mockDataKeys:(g=(y=l.metadata)==null?void 0:y.data)!=null&&g.mockData?Object.keys(l.metadata.data.mockData):[],argumentsDataLength:Array.isArray(p)?p.length:"not-array",argumentsDataPreview:u})});const a=s.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),o=await tg(a);if(!o||o.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${o.length} scenarios to database`),o.forEach((l,c)=>{var u,h;const p=(h=(u=l.metadata)==null?void 0:u.data)==null?void 0:h.argumentsData;console.log(`[API] Saved scenario ${c}: ${l.name}`,{id:l.id,argumentsDataLength:Array.isArray(p)?p.length:"not-array"})});const i={...r,scenarios:o};return Response.json({success:!0,analysis:i})}catch(t){return console.error("[API] Error saving scenarios:",t),Response.json({error:"Failed to save scenarios",details:t instanceof Error?t.message:String(t)},{status:500})}}const j1=Object.freeze(Object.defineProperty({__proto__:null,action:E1},Symbol.toStringTag,{value:"Module"})),A1=()=>[{title:"Agent Transcripts - CodeYam"},{name:"description",content:"View background agent transcripts and tool call history"}];async function P1({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("search")||"",s=t.searchParams.get("page")||"1",a=new URLSearchParams;r&&a.set("search",r),s!=="1"&&a.set("page",s);const o=a.toString(),i=new URL(`/api/agent-transcripts${o?`?${o}`:""}`,e.url),c=await(await fetch(i.toString())).json();if(c.error)return re({agents:[],error:c.error,search:r,page:1,totalPages:1});const p=c.total??(c.agents||[]).length,u=c.pageSize??20;return re({agents:c.agents||[],error:null,search:r,page:c.page??parseInt(s,10),totalPages:Math.max(1,Math.ceil(p/u))})}catch(t){return console.error("Failed to load agent transcripts:",t),re({agents:[],error:"Failed to load agent transcripts",search:"",page:1,totalPages:1})}}function T1(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 M1(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 $1(e){return e.includes("opus")?"Opus":e.includes("sonnet")?"Sonnet":e.includes("haiku")?"Haiku":e}function $s({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 I1({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 F1({content:e,truncated:t,fullLength:r}){const[s,a]=A(!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 D1({entry:e,pairedResult:t}){const[r,s]=A(!1),a=T1(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($s,{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($s,{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(kt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n(pn,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n($s,{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(I1,{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(F1,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function R1({context:e}){const[t,r]=A(!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(kt,{className:"w-3 h-3 text-gray-400"}):n(pn,{className:"w-3 h-3 text-gray-400"}),n($s,{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 O1({snippet:e}){const[t,r]=A(!1),s=e.split(`
468
- `).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(Th,{className:"w-3.5 h-3.5 text-blue-600"}),n("span",{className:"text-xs font-bold text-blue-800",children:"Source Conversation"}),d("span",{className:"text-[10px] text-blue-500",children:[s.length," message",s.length!==1?"s":""]})]}),n("div",{className:"space-y-1",children:i.map((l,c)=>{const p=l.match(/^\[(\w+)\]:\s*(.*)/);if(!p)return null;const[,u,h]=p,m=u==="user";return d("div",{className:"text-xs",children:[d("span",{className:`font-bold ${m?"text-blue-700":"text-gray-500"}`,children:[m?"User":"Assistant",":"]})," ",n("span",{className:"text-gray-700",children:h.length>200?h.slice(0,200)+"...":h})]},c)})}),o&&n("button",{onClick:()=>r(!t),className:"text-[11px] text-blue-600 hover:text-blue-800 mt-2 font-mono cursor-pointer",children:t?"Show less":`Show all ${s.length} messages`})]})}function L1({change:e}){const[t,r]=A(!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(kt,{className:"w-3 h-3 inline flex-shrink-0"}):n(pn,{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 z1({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(L1,{change:i},l)),t.length>0&&d("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function B1({result:e}){const t=e.is_error,r=t?"bg-red-50 border-red-200":"bg-green-50 border-green-200",s=t?"text-red-800":"text-green-800",a=t?"text-red-700":"text-green-700",o=e.subtype.replace(/^error_/,"").replace(/_/g," "),i=c=>c>=6e4?`${(c/6e4).toFixed(1)}m`:`${(c/1e3).toFixed(1)}s`,l=c=>c>=1e3?`${(c/1e3).toFixed(1)}k`:String(c);return d("div",{className:`my-2 border rounded-md p-3 ${r}`,children:[d("div",{className:`text-xs font-bold mb-1 ${s}`,children:["Session Result: ",o]}),d("div",{className:`text-xs ${a} font-mono space-y-0.5`,children:[d("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5",children:[e.duration_ms!=null&&d("span",{children:["Duration: ",i(e.duration_ms)]}),e.duration_api_ms!=null&&d("span",{children:["API time: ",i(e.duration_api_ms)]}),e.num_turns!=null&&d("span",{children:["Turns: ",e.num_turns]}),e.total_cost_usd!=null&&d("span",{children:["Cost: $",e.total_cost_usd.toFixed(4)]})]}),e.usage&&d("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5 mt-1",children:[e.usage.input_tokens!=null&&d("span",{children:["Input: ",l(e.usage.input_tokens)]}),e.usage.output_tokens!=null&&d("span",{children:["Output: ",l(e.usage.output_tokens)]}),e.usage.cache_read_input_tokens!=null&&d("span",{children:["Cache read: ",l(e.usage.cache_read_input_tokens)]}),e.usage.cache_creation_input_tokens!=null&&d("span",{children:["Cache write:"," ",l(e.usage.cache_creation_input_tokens)]})]}),e.errors&&e.errors.length>0&&n("div",{className:"mt-1",children:e.errors.map((c,p)=>n("div",{className:"text-red-700 break-words",children:c},p))})]})]})}function Y1({agent:e,defaultOpen:t,isAdmin:r}){var C,S,k;const[s,a]=A(t),[o,i]=A(!1),[l,c]=A(null),[p,u]=A(!1),h=le(()=>{const j={};for(const _ of e.entries)_.type==="tool_result"&&_.tool_use_id&&(j[_.tool_use_id]=_);return j},[e.entries]),m=le(()=>{const j=new Set;for(const _ of e.entries)_.type==="tool_call"&&_.tool_use_id&&h[_.tool_use_id]&&j.add(_.tool_use_id);return j},[e.entries,h]),f=j=>{j.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(j=>j.action!=="touched"),g=y.filter(j=>j.action==="created"),x=y.filter(j=>j.action==="modified"),b=(e.ruleChanges||[]).filter(j=>j.action==="touched"),v=y.length>0,N=b.length>0,w=v||N;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(kt,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n(pn,{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:$1(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(Rs,{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(Rs,{className:"w-3 h-3"}),x.length," rule",x.length!==1?"s":""," ","modified"]}),!v&&N&&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(Ds,{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",((C=e.sessionResult)==null?void 0:C.duration_ms)!=null&&d(ve,{children:[" · ",e.sessionResult.duration_ms>=6e4?`${(e.sessionResult.duration_ms/6e4).toFixed(1)}m`:`${(e.sessionResult.duration_ms/1e3).toFixed(1)}s`]}),((S=e.sessionResult)==null?void 0:S.total_cost_usd)!=null&&d(ve,{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:[M1(e.timestamp),r&&v&&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(Ph,{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:j=>{j.stopPropagation(),navigator.clipboard.writeText(e.sourceFile),u(!0),setTimeout(()=>u(!1),2e3)},className:"p-0.5 rounded text-gray-400 hover:text-gray-600 cursor-pointer transition-colors flex-shrink-0",title:"Copy file path",children:p?n(Et,{className:"w-3.5 h-3.5 text-green-500"}):n(It,{className:"w-3.5 h-3.5"})})]}),e.sessionResult&&n(B1,{result:e.sessionResult}),e.stats.errors>0&&((k=e.stats.errorMessages)==null?void 0:k.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((j,_)=>n("li",{className:"break-words",children:j},_))})]}),e.conversationSnippet&&n(O1,{snippet:e.conversationSnippet}),w&&n(z1,{changes:e.ruleChanges}),e.context&&n(R1,{context:e.context}),e.entries.map((j,_)=>{if(j.type==="tool_result"&&j.tool_use_id&&m.has(j.tool_use_id))return null;const F=j.type==="tool_call"&&j.tool_use_id?h[j.tool_use_id]:void 0;return n(D1,{entry:j,pairedResult:F},`${e.id}-${_}`)})]})]})}function co(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 W1=et(function(){const{agents:t,error:r,search:s,page:a,totalPages:o}=ot(),i=Dt(),l=nd("root"),c=(l==null?void 0:l.isAdmin)??!1,[p,u]=A(s),[h,m]=A(!1),[f,y]=A(0);Ot({source:"agent-transcripts-page"});const g=b=>{b.preventDefault(),window.location.href=co(1,p)},x=()=>{m(!h),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(jh,{className:"w-5 h-5"})}),n(Os,{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(Hr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:p,onChange:b=>u(b.target.value),placeholder:"Search transcripts...",className:"w-full pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),n("button",{onClick:x,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:h?"Collapse All":"Expand All"})]}),d("div",{className:"text-sm text-gray-500 mb-4",children:["Page ",a," of ",o,s&&d("span",{children:[" ","matching “",s,"”",n(ke,{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(Os,{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(Y1,{agent:b,defaultOpen:h,isAdmin:c},b.id))},f),o>1&&d("div",{className:"flex items-center justify-center gap-3 mt-8",children:[d("a",{href:a>1?co(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(Ah,{className:"w-4 h-4"}),"Prev"]}),d("span",{className:"text-sm text-gray-500 font-mono",children:[a," / ",o]}),d("a",{href:a<o?co(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(pn,{className:"w-4 h-4"})]})]})]})})}),U1=Object.freeze(Object.defineProperty({__proto__:null,default:W1,loader:P1,meta:A1},Symbol.toStringTag,{value:"Module"}));async function J1({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=Lw(s);a&&console.log("[editor-commit] Initialized new git repository"),zw(s),console.log("[editor-commit] Staged all changes");const o=Bw(s,r);console.log(`[editor-commit] Created commit: ${o}`);try{const{broadcastHideResults:i}=await Promise.resolve().then(()=>Mx);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 H1=Object.freeze(Object.defineProperty({__proto__:null,action:J1},Symbol.toStringTag,{value:"Module"}));function V1(){const e={"Content-Type":"application/json","Access-Control-Allow-Origin":"*"};try{const t=Ce()||process.cwd(),r=H.join(t,".codeyam","data-structure.json");if(G.existsSync(r))try{const o=JSON.parse(G.readFileSync(r,"utf-8")),i=Array.isArray(o)?o:[];return i.sort((l,c)=>(l.order??99)-(c.order??99)),new Response(JSON.stringify({dataStructures:i,source:"explicit"}),{headers:e})}catch{}const s=H.join(t,"prisma","schema.prisma");if(G.existsSync(s)){const o=G.readFileSync(s,"utf-8"),i=K1(o);return new Response(JSON.stringify({models:i,source:"prisma"}),{headers:e})}const a=G1(t);return a.length>0?new Response(JSON.stringify({models:a,source:"typescript"}),{headers:e}):new Response(JSON.stringify({models:[],source:null}),{headers:e})}catch{return new Response(JSON.stringify({models:[],source:null}),{headers:e})}}function K1(e){const t=[],r=/model\s+(\w+)\s*\{([^}]+)\}/g,s=new Set;let a;const o=/model\s+(\w+)\s*\{/g;for(;(a=o.exec(e))!==null;)s.add(a[1]);let i;for(;(i=r.exec(e))!==null;){const l=i[1],c=i[2],p=[];for(const u of c.split(`
469
- `)){const h=u.trim();if(!h||h.startsWith("//")||h.startsWith("@@"))continue;const m=h.match(/^(\w+)\s+([\w[\]?]+)\??(\s+.*)?$/);if(!m)continue;const f=m[1];let y=m[2];const g=m[3]||"",x=y.endsWith("[]"),b=y.endsWith("?")||h.includes("?");y=y.replace(/[[\]?]/g,"");const v=s.has(y),N=g.includes("@id");p.push({name:f,type:y,isRelation:v,isOptional:b,isList:x,isId:N,...v?{relatedModel:y}:{}})}t.push({name:l,fields:p})}return t}function G1(e){const t=H.join(e,"src");if(!G.existsSync(t))return[];const r=[],s=new Set,a=[],o=["src","src/lib","src/types","src/utils","src/models"];for(const i of o){const l=H.join(e,i);if(G.existsSync(l))try{for(const c of G.readdirSync(l))c.endsWith(".ts")&&!c.endsWith(".test.ts")&&!c.endsWith(".spec.ts")&&a.push(H.join(l,c))}catch{}}for(const i of a){const l=G.readFileSync(i,"utf-8"),c=/export\s+interface\s+(\w+)/g;let p;for(;(p=c.exec(l))!==null;)s.add(p[1])}for(const i of a){const l=G.readFileSync(i,"utf-8"),c=/export\s+interface\s+(\w+)\s*\{([^}]+)\}/g;let p;for(;(p=c.exec(l))!==null;){const u=p[1],h=p[2],m=[];for(const f of h.split(`
470
- `)){const y=f.trim();if(!y||y.startsWith("//"))continue;const g=y.match(/^(\w+)(\?)?:\s*([^;/]+)/);if(!g)continue;const x=g[1],b=!!g[2];let v=g[3].trim();const N=v.endsWith("[]");v=v.replace(/\[\]$/,"");const w=s.has(v);m.push({name:x,type:v,isRelation:w,isOptional:b,isList:N,isId:x==="id",...w?{relatedModel:v}:{}})}r.push({name:u,fields:m})}}return r}const q1=Object.freeze(Object.defineProperty({__proto__:null,loader:V1},Symbol.toStringTag,{value:"Module"}));async function Q1({request:e}){const r=new URL(e.url).searchParams.get("skipTests")==="true",s=Ce()||process.cwd(),a=H.join(s,".codeyam","glossary.json");let o;try{const D=G.readFileSync(a,"utf8");o=fa(JSON.parse(D))}catch{return Response.json(so({components:[],functions:[],scenarioCounts:{},testFileExistence:{}}))}if(o.length===0)return Response.json(so({components:[],functions:[],scenarioCounts:{},testFileExistence:{}}));const i=H.join(s,".codeyam","editor-step.json");let l=null;try{const D=G.readFileSync(i,"utf8");l=JSON.parse(D).featureStartedAt||null}catch{}let c,p=[];const u=await Ye();if(u)try{const{project:D}=await Re(u),B=await $e().selectFrom("editor_scenarios").select(["name","component_name","component_path","page_file_path","url","display_name"]).where("project_id","=",D.id).orderBy("created_at","asc").execute(),Y=_t(B,P=>`${P.name}::${P.url||"/"}`),I=Y.map(P=>({componentName:P.component_name||null,componentPath:P.component_path||null,pageFilePath:P.page_file_path??null,url:P.url??null,displayName:P.display_name??null}));p=Y.map(P=>({name:P.name,componentName:P.component_name||null,pageFilePath:P.page_file_path??null,url:P.url??null}));const L=await gr({projectRoot:s,scenarioInputs:I});Object.keys(L.entityChangeStatus).length>0&&(c=L.entityChangeStatus)}catch{}const h=gb({featureStartedAt:l,entityChangeStatus:c});l=h.featureStartedAt,c=h.entityChangeStatus;const m=yb(o,c),{components:f,functions:y}=fb(m);let g={},x={};if(u)try{const{project:D}=await Re(u),T=$e();g=await Gl(T,D.id,l);const B=await ql(T,D.id,l);for(const[Y,I]of Object.entries(B)){const L=m.find(P=>P.filePath===Y);L&&(g[L.name]=(g[L.name]||0)+I)}if(l&&c){const Y=await Gl(T,D.id,null),I=await ql(T,D.id,null);x={...Y};for(const[L,P]of Object.entries(I)){const R=m.find(E=>E.filePath===L);R&&(x[R.name]=(x[R.name]||0)+P)}}}catch{}let b={};try{const D=process.env.CODEYAM_ROOT_PATH||process.cwd(),T=await Nu(D);b=Nb(T,p)}catch{}const v={};for(const D of y)D.testFile&&(v[D.testFile]=G.existsSync(H.join(s,D.testFile)));const N={},w={};if(!r){const D=y.filter(B=>B.testFile&&v[B.testFile]).map(B=>B.testFile),T=[...new Set(D)];if(T.length>0){const B=Pi(s),Y=y.filter(E=>!!E.testFile&&v[E.testFile]).map(E=>({filePath:E.filePath,testFile:E.testFile})),I=Ti(s,Y),L=new Set(c?Object.entries(c).filter(([,E])=>E.status==="impacted").map(([E])=>E):[]),P=[],R={};for(const E of T){const J=B.results[E],K=I[E],Q=y.some(q=>q.testFile===E&&L.has(q.name));J&&K&&!Lu(J,K.sourceHash,K.testHash)&&!Q?R[E]={testFilePath:J.testFilePath,status:J.status,testCases:J.testCases,...J.errorMessage?{errorMessage:J.errorMessage}:{}}:P.push(E)}try{const E=P.length>0?await ww(s,P):{},J={...R,...E};try{Bu(s,E,Y)}catch{}for(const K of y){if(!K.testFile||!v[K.testFile])continue;const Q=J[K.testFile];if(!Q)continue;const q=Q.status==="passed",U=Q.testCases.some(z=>z.fullName.startsWith(K.name));w[K.name]=Q.testCases.filter(z=>z.fullName.startsWith(K.name)&&z.status!=="skipped").length,N[K.testFile]={passing:q,hasEntityNameDescribe:U,...Q.status==="error"&&Q.errorMessage?{errorMessage:Q.errorMessage}:{}}}}catch(E){for(const J of T)N[J]={passing:!1,hasEntityNameDescribe:!1,errorMessage:E.message||"Unknown test runner error"}}}}const C=new Set(o.map(D=>D.filePath)),S=[];if(u)try{const{project:D}=await Re(u),B=await $e().selectFrom("editor_scenarios").select(["component_name","component_path","page_file_path"]).where("project_id","=",D.id).execute(),Y=new Map;for(const I of B){const L=I,P=L.component_path||L.page_file_path;if(!P)continue;const R=Y.get(P);R?R.count++:Y.set(P,{name:L.component_name||H.basename(P,H.extname(P)),count:1})}for(const[I,L]of Y)C.has(I)||S.push({name:L.name,filePath:I,scenarioCount:L.count})}catch{}const k=so({components:f,functions:y,scenarioCounts:g,testFileExistence:v,testResults:N,clientErrors:b,totalScenarioCounts:x,entityChangeStatus:c,testCaseCounts:w});k.missingFromGlossary=S,S.length>0&&(k.summary.allPassing=!1,k.summary.missingFromGlossary=S.length);let j=[];if(u)try{const{project:D}=await Re(u),T=$e();j=await xb(T,D.id,l)}catch{}if(k.incompleteEntities=j,j.length>0){k.summary.allPassing=!1,k.summary.incompleteEntities=j.length;const D=j.filter(T=>T.preExisting).length;D>0&&(k.summary.preExistingIncompleteEntities=D)}let _=[];if(u)try{const{project:D}=await Re(u),T=$e();_=await bb(T,D.id,l)}catch{}k.miscategorizedScenarios=_,_.length>0&&(k.summary.allPassing=!1,k.summary.miscategorizedScenarios=_.length);let F=[];if(u)try{const{project:D}=await Re(u),T=$e();F=await vb(T,D.id,l)}catch{}k.unassociatedScenarios=F,F.length>0&&(k.summary.allPassing=!1,k.summary.unassociatedScenarios=F.length);let M=[];if(u&&c&&Object.keys(c).length>0)try{const{project:D}=await Re(u),B=await $e().selectFrom("editor_scenarios").select(["editor_scenarios.name","editor_scenarios.component_name","editor_scenarios.page_file_path","editor_scenarios.url","editor_scenarios.created_at","editor_scenarios.updated_at"]).where("editor_scenarios.project_id","=",D.id).execute(),Y=l?Qr(l):null,I=B.map(L=>({name:L.name,entityName:Gt({componentName:L.component_name,pageFilePath:L.page_file_path,url:L.url}),updatedInSession:Y?ci({created_at:L.created_at,updated_at:L.updated_at},Y):!1}));M=Pu({scenarios:I,entityChangeStatus:c})}catch{}k.scenariosNeedingRecapture=M,M.length>0&&(k.summary.allPassing=!1,k.summary.scenariosNeedingRecapture=M.length);const $=[],O=wb(o);for(const[D,T]of O)$.push({name:D,filePaths:T.map(B=>B.filePath)});return k.duplicateNames=$,Response.json(k)}const Z1=Object.freeze(Object.defineProperty({__proto__:null,loader:Q1},Symbol.toStringTag,{value:"Module"}));async function X1({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(!hc(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,s)}catch(u){return Response.json({error:"Failed to kill process",pid:r,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,l=500,c=Date.now();let p=!0;for(;p&&Date.now()-c<i;)await new Promise(u=>setTimeout(u,l)),p=hc(r);if(p){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${r}:`,u)}}if(a)try{await an({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 hc(e){try{return process.kill(e,0),!0}catch{return!1}}const eS=Object.freeze(Object.defineProperty({__proto__:null,action:X1},Symbol.toStringTag,{value:"Module"})),tS=ea(import.meta.url),nS=ee.dirname(tS),rS=ee.resolve(nS,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function sS(e){const t=[],r=new Set;for(const s of e.split(`
471
- `)){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}if(o.type!=="assistant")continue;const i=o.message;if(!(!i||!Array.isArray(i.content)))for(const l of i.content){if(typeof l!="object"||l===null)continue;const c=l;if(c.type!=="tool_use")continue;const p=String(c.name||""),u=c.input||{};if(p==="Write"||p==="Edit"){const h=String(u.file_path||"");if(h.includes(".claude/rules/")){const m=h.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${p}:${m}`;r.has(f)||(r.add(f),t.push({action:p==="Write"?"created":"modified",filePath:m}))}}else if(p==="Bash"){const h=String(u.command||"");if(h.includes("codeyam memory touch")){const m=`touch:${h}`;r.has(m)||(r.add(m),t.push({action:"touched",filePath:h}))}}}}return t}async function aS({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 Wu(),a=s?ee.join(Ts,s):null;let o=a?ee.join(a,`${r}.log`):"";if((!o||!Ct(o))&&(o=ee.join(Ts,`${r}.log`)),!Ct(o))return Response.json({error:`Log file not found: ${r}.log`},{status:404});const i=await bo(o,"utf-8");let l=a?ee.join(a,`${r}.context`):"";(!l||!Ct(l))&&(l=ee.join(Ts,`${r}.context`));let c=null;if(Ct(l))try{c=await bo(l,"utf-8")}catch{}const p=sS(i),h=c?["no,","no ","that's not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","shouldn't","try again","that broke","that failed","error","bug"].some(x=>c.toLowerCase().includes(x)):!1,m=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":r.endsWith("-interruption")?"-int":"",f=r.slice(0,8)+m,y=ee.join(rS,f);await Xh(y,{recursive:!0}),await $r(ee.join(y,"agent-log.jsonl"),i),c&&await $r(ee.join(y,"context.md"),c),await $r(ee.join(y,"rule-changes.json"),JSON.stringify(p,null,2)),await $r(ee.join(y,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:h,ruleChangeCount:p.length},null,2));const g=ee.relative(process.cwd(),y);return console.log(`[api.save-fixture] Saved fixture to ${g}`),Response.json({success:!0,fixturePath:g})}catch(t){return console.error("[api.save-fixture] Error:",t),Response.json({error:"Failed to save fixture",details:t instanceof Error?t.message:String(t)},{status:500})}}const oS=Object.freeze(Object.defineProperty({__proto__:null,action:aS},Symbol.toStringTag,{value:"Module"}));async function iS({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=Ce();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const s=ee.join(r,".codeyam","captures","screenshots",t);try{await Pe.access(s);const a=await Pe.readFile(s),o=ee.extname(s).toLowerCase(),i=o===".png"?"image/png":o===".jpg"||o===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(a,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const lS=Object.freeze(Object.defineProperty({__proto__:null,loader:iS},Symbol.toStringTag,{value:"Module"})),mc={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 $i({type:e,className:t=""}){const r=mc[e]||mc.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 cS={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 Ns({variant:e,pid:t,label:r,className:s=""}){const a=cS[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 fc=!1;function dS(){if(fc)return;const e=document.createElement("style");e.textContent=`
472
- @keyframes strongPulse {
473
- 0%, 100% { opacity: 0.2; }
474
- 50% { opacity: 1; }
475
- }
476
- `,document.head.appendChild(e),fc=!0}function Ii({size:e="medium",className:t=""}){typeof document<"u"&&dS();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 uS=()=>[{title:"Activity - CodeYam"},{name:"description",content:"View analysis activity and queue status"}];async function pS({request:e,context:t,params:r}){var L,P,R,E,J,K,Q,q;let s=t.analysisQueue;s||(s=await Kt());const a=new URL(e.url),o=parseInt(a.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!s)return re({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:l,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const c=s.getState(),p=await Ye();let u=null;if(p&&((L=c==null?void 0:c.currentlyExecuting)!=null&&L.commitSha)){const{project:U,branch:z}=await Re(p),W=await Ws({projectId:U.id,branchId:z.id,shas:[c.currentlyExecuting.commitSha]});u=W&&W.length>0?W[0]:null}else u=await pr();const h=async U=>{const z=await Pn(U);if(!z)return null;const{getAnalysesForEntity:W}=await Promise.resolve().then(()=>Sg),V=await W(U,!1);return{...z,analyses:V||[]}},m=await Promise.all(((c==null?void 0:c.jobs)||[]).map(async U=>{const z=[];if(U.entityShas&&U.entityShas.length>0){const W=U.entityShas.map(ae=>h(ae)),V=await Promise.all(W);z.push(...V.filter(ae=>ae!==null))}return{...U,entities:z}}));let f=null;if(c!=null&&c.currentlyExecuting){const U=c.currentlyExecuting,z=[];if(U.entityShas&&U.entityShas.length>0){const W=U.entityShas.map(ae=>h(ae)),V=await Promise.all(W);z.push(...V.filter(ae=>ae!==null))}f={...U,entities:z}}const y=f?m.filter(U=>U.id!==f.id):m,g=((R=(P=u==null?void 0:u.metadata)==null?void 0:P.currentRun)==null?void 0:R.currentEntityShas)||[],b=(await Promise.all(g.map(U=>h(U)))).filter(U=>U!==null),v=[];if(p)try{const{project:U,branch:z}=await Re(p),W=await Ws({projectId:U.id,branchId:z.id,limit:100});for(const V of W){const ae=((E=V.metadata)==null?void 0:E.historicalRuns)||[];v.push(...ae)}}catch(U){console.error("[activity.tsx] Failed to load historical runs from commits:",U)}const N=[...v].sort((U,z)=>{const W=U.lastCaptureAt||U.analysisCompletedAt||U.archivedAt||U.createdAt||"";return(z.lastCaptureAt||z.analysisCompletedAt||z.archivedAt||z.createdAt||"").localeCompare(W)}),w=(o-1)*i,C=w+i,S=N.slice(w,C),k=Math.ceil(N.length/i),j=await Promise.all(S.map(async U=>{const z=U.currentEntityShas||[];if(z.length===0)return{...U,entities:[]};const W=await Promise.all(z.map(V=>h(V)));return{...U,entities:W.filter(V=>V!==null)}})),_=!!f,F=y.length,M=N.filter(U=>{const z=!!U.failedAt,W=U.readyToBeCaptured,V=U.capturesCompleted??0,ae=W===void 0?!0:W===0||V>=W;return!z&&!!U.analysisCompletedAt&&ae}),$=new Set(((J=f==null?void 0:f.entities)==null?void 0:J.map(U=>U.sha))||[]),O=M.filter(U=>!(U.currentEntityShas||[]).some(W=>$.has(W))),T=(await Promise.all(O.slice(0,3).map(async U=>{const z=U.currentEntityShas||[];if(z.length===0)return{run:U,entities:[]};const W=await Promise.all(z.map(V=>h(V)));return{run:U,entities:W.filter(V=>V!==null)}}))).flatMap(({run:U,entities:z})=>z.map(W=>({...W,runId:U.id,completedAt:U.lastCaptureAt||U.analysisCompletedAt||U.archivedAt||U.createdAt})));let B=[],Y=null,I=null;if((Q=(K=u==null?void 0:u.metadata)==null?void 0:K.currentRun)!=null&&Q.analysisCompletedAt&&b.length>0){const U=b[0].sha;Y=b[0];const z=await aa(U);z&&z.length>0&&z[0].scenarios&&(B=z[0].scenarios,I=z[0].status)}return re({state:{...c,jobs:y,currentlyExecuting:f},currentRun:(q=u==null?void 0:u.metadata)==null?void 0:q.currentRun,historicalRuns:j,totalHistoricalRuns:N.length,currentPage:o,totalPages:k,projectSlug:p,commitSha:u==null?void 0:u.sha,queueJobs:y,currentlyExecuting:f,currentEntities:b,tab:l,hasCurrentActivity:_,queuedCount:F,recentCompletedEntities:T,hasMoreCompletedRuns:O.length>3,currentEntityScenarios:B,currentEntityForScenarios:Y,currentAnalysisStatus:I})}function hS({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(ke,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
477
- relative pb-4 px-2 text-sm transition-colors cursor-pointer
478
- ${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
479
- `,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:`
480
- inline-block w-2 h-2 rounded-full
481
- ${i?"":"bg-gray-400"}
482
- `,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function mS({currentlyExecuting:e,currentRun:t,state:r,projectSlug:s,commitSha:a,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:l,currentEntityScenarios:c,currentEntityForScenarios:p,currentAnalysisStatus:u}){var D,T,B,Y;const[h,m]=A({}),[f,y]=A({isKilling:!1,current:0,total:0}),g=Rt(),x=!!e,b=(e==null?void 0:e.entities)||[],v=!!(t!=null&&t.analysisCompletedAt),N=v&&!!(t!=null&&t.capturePid),w=!v,C=x,S=c||[],{lastLine:k}=Jt(s,C);ne(()=>{if(!t)return;const I=[t.analyzerPid,t.capturePid].filter(E=>!!E);if(I.length===0)return;let L=!0;const P=async()=>{try{const J=await(await fetch(`/api/process-status?pids=${I.join(",")}`)).json();if(J.processes&&L){const K={};J.processes.forEach(Q=>{K[Q.pid]={isRunning:Q.isRunning,processName:Q.processName}}),m(K)}}catch(E){L&&console.error("Failed to fetch process statuses:",E)}};P();const R=setInterval(()=>void P(),5e3);return()=>{L=!1,clearInterval(R)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[j,_]=A(!1),[F,M]=A(!1);ne(()=>{b.length<=3&&j&&_(!1)},[b.length,j]),ne(()=>{i.length<=3&&F&&M(!1)},[i.length,F]);const $=j?b:b.slice(0,3),O=b.length>3;return d("div",{className:"flex flex-col gap-[45px]",children:[C?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($t,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:N?"Capturing...":"Analyzing..."})]}),$.map(I=>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(gt,{type:I.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col gap-[1px]",children:[d("div",{className:"flex items-center gap-[14px]",children:[n(ke,{to:`/entity/${I.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:I.name}),I.entityType&&n($i,{type:I.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:I.filePath,children:I.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"})]},I.sha)),O&&!j&&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"]}),j&&O&&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"}),N&&S&&S.length>0&&p&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:S.map(I=>{var Q,q,U,z;if(!I.id)return null;const L=(q=(Q=I.metadata)==null?void 0:Q.screenshotPaths)==null?void 0:q[0],P=(U=I.metadata)==null?void 0:U.noScreenshotSaved,R=L&&!P,E=(z=u==null?void 0:u.scenarios)==null?void 0:z.find(W=>W.name===I.name),K=E&&E.screenshotStartedAt&&!E.screenshotFinishedAt||!R&&!P;return n(ke,{to:`/entity/${p.sha}/scenarios/${I.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:K?"#f9f9f9":void 0,borderColor:K?"#efefef":"#ccc"},children:R?n(dt,{screenshotPath:L,alt:I.name,className:"w-full h-full object-contain bg-gray-100"}):K?n("div",{className:"w-full h-full flex items-center justify-center",children:n(Ii,{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"})},I.id)})}),k&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:k}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.capturePid))&&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(Ns,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(w||((D=h[t.analyzerPid])==null?void 0:D.isRunning))&&n(Ns,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(Ns,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(N||((T=h[t.capturePid])==null?void 0:T.isRunning))&&n(Ns,{variant:"running"})]}),(((B=h[t==null?void 0:t.analyzerPid])==null?void 0:B.isRunning)||((Y=h[t==null?void 0:t.capturePid])==null?void 0:Y.isRunning))&&n("button",{onClick:()=>{const I=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(R=>{var E;return!!R&&((E=h[R])==null?void 0:E.isRunning)});if(I.length===0)return;const L=I.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${L})?`))return;y({isKilling:!0,current:1,total:I.length}),(async()=>{for(let R=0;R<I.length;R++){const E=I[R];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:E,commitSha:a||""})})}catch(J){console.error(`Failed to kill process ${E}:`,J)}R<I.length-1&&y({isKilling:!0,current:R+2,total:I.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(od,{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(ke,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(ke,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),d(ke,{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:[(F?i:i.slice(0,3)).map(I=>{var R;const L=(R=I.analyses)==null?void 0:R[0],P=(L==null?void 0:L.scenarios)||[];return L==null||L.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(gt,{type:I.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(ke,{to:`/entity/${I.sha}`,className:"hover:underline cursor-pointer",title:I.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:I.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:I.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:I.filePath,children:I.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:E=>{E.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:E=>{E.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),P.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:P.map(E=>{var q,U,z;if(!E.id)return null;const J=(U=(q=E.metadata)==null?void 0:q.screenshotPaths)==null?void 0:U[0],K=(z=E.metadata)==null?void 0:z.noScreenshotSaved,Q=J&&!K;return d("div",{className:"shrink-0 flex flex-col gap-2",children:[n(ke,{to:`/entity/${I.sha}/scenarios/${E.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:W=>{Q&&(W.currentTarget.style.borderColor="#005C75",W.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:W=>{W.currentTarget.style.borderColor=Q?"#d1d5db":"#BCCDD3",W.currentTarget.style.boxShadow="none"},children:Q?n(dt,{screenshotPath:J,alt:E.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:E.name})]},E.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},I.sha)}),i.length>3&&!F&&d("button",{onClick:()=>M(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",i.length-3," more"," ",i.length-3===1?"entity":"entities"]}),F&&i.length>3&&n("button",{onClick:()=>M(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})]})}function fS({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(Mh,{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(ke,{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]=A(null),[o,i]=A(null),[l,c]=A(null),[p,u]=A(!1),[h,m]=A(!1),[f,y]=A(new Set),g=Rt();ne(()=>{e.length<=3&&h&&m(!1)},[e.length,h]);const x=S=>{a(S)},b=(S,k)=>{S.preventDefault(),i(k)},v=async(S,k)=>{if(S.preventDefault(),!s){i(null);return}const j=e.findIndex(M=>M.id===s);if(j===-1){a(null),i(null);return}if(j===k){a(null),i(null);return}const _=j<k?"down":"up",F=Math.abs(k-j);u(!0);try{for(let M=0;M<F;M++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:s,direction:_})});g.revalidate()}catch(M){console.error("Failed to reorder job:",M)}finally{u(!1),a(null),i(null)}},N=()=>{p||(a(null),i(null))},w=async S=>{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:S})}),window.location.reload()}catch(k){console.error("Failed to cancel job:",k)}},C=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(S){console.error("Failed to cancel jobs:",S)}};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 C(),className:"px-[10px] py-0 rounded transition-colors cursor-pointer hover:bg-red-300",style:{backgroundColor:"#ffdcd9",color:"#ef4444",fontSize:"12px",fontWeight:500,height:"29px"},children:"Cancel All"})]}),d("div",{className:"flex flex-col gap-3",children:[(h?e:e.slice(0,3)).map(S=>{var O,D,T,B;const k=e.findIndex(Y=>Y.id===S.id),j=l===k,_=s===S.id,F=o===k,M=f.has(S.id),$=((O=S.entities)==null?void 0:O.length)>0?M?S.entities:S.entities.slice(0,3):[];return d("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:_||p?.5:1,transform:F&&s!==null&&!_?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:p?"not-allowed":_?"grabbing":"grab"},onMouseEnter:()=>c(k),onMouseLeave:()=>c(null),draggable:!p,onDragStart:Y=>{x(S.id),Y.dataTransfer.effectAllowed="move"},onDragOver:Y=>b(Y,k),onDrop:Y=>void v(Y,k),onDragEnd:N,children:[d("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n($h,{size:16,style:{color:"#005C75"}}),d("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",k+1]})]}),d("div",{className:"flex flex-col gap-2 mt-8",children:[$.length>0?d(ve,{children:[$.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(gt,{type:Y.entityType||"other",size:"large"})}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(ke,{to:`/entity/${Y.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:Y.name}),Y.entityType&&n($i,{type:Y.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:Y.filePath})]})]})})},Y.sha)),((D=S.entities)==null?void 0:D.length)>3&&n("button",{onClick:()=>{y(Y=>{const I=new Set(Y);return I.has(S.id)?I.delete(S.id):I.add(S.id),I})},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:M?"Show less":`+${S.entities.length-3} more ${S.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(Ls,{size:18,style:{color:"#8e8e8e"}})}),d("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((T=S.entityNames)==null?void 0:T[0])||(S.type==="analysis"?"Analysis Job":S.type==="recapture"?"Recapture Job":S.type==="debug-setup"?"Debug Setup":S.type.charAt(0).toUpperCase()+S.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((B=S.filePaths)==null?void 0:B[0])||(S.filePaths&&S.filePaths.length>1?`${S.filePaths.length} files`:S.entityShas&&S.entityShas.length>0?`${S.entityShas.length} ${S.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),d("div",{className:"flex items-center justify-end gap-2 mt-1",children:[j&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(Ih,{size:20})}),n("button",{onClick:()=>void w(S.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"})]})]})]},S.id)}),e.length>3&&!h&&d("button",{onClick:()=>m(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",e.length-3," more"," ",e.length-3===1?"job":"jobs"]}),h&&e.length>3&&n("button",{onClick:()=>m(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})}function gS({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(Fh,{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(ke,{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]=A(!1),c=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(h=>{c.push({...h,runCreatedAt:u.createdAt})})});const p=i?c:c.slice(0,3);return d("div",{className:"flex flex-col gap-4",children:[p.map(u=>{var y;const h=(y=u.analyses)==null?void 0:y[0],m=(h==null?void 0:h.scenarios)||[],f=!u.isUncommitted;return d("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[d("div",{className:"flex items-start justify-between mb-3",children:[d("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{children:n(gt,{type:u.entityType||"other",size:"large"})}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(ke,{to:`/entity/${u.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:u.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:f?"#e8ffe6":"#fef3cd",color:f?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:f?"Up to date":"Out of date"})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},title:u.filePath,children:u.filePath})]})]}),n("button",{onClick:o,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),m.length>0&&d("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[m.slice(0,8).map(g=>{var N,w,C;if(!g.id)return null;const x=(w=(N=g.metadata)==null?void 0:N.screenshotPaths)==null?void 0:w[0],b=(C=g.metadata)==null?void 0:C.noScreenshotSaved,v=x&&!b;return n(ke,{to:`/entity/${u.sha}/scenarios/${g.id}`,className:"border rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px",borderColor:v?"#ccc":"#BCCDD3",borderStyle:v?"solid":"dashed"},children:v?n(dt,{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)}),m.length>8&&d("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",m.length-8," more"]})]})]},`${u.sha}-${u.runCreatedAt}`)}),c.length>3&&!i&&d("button",{onClick:()=>l(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",c.length-3," more"," ",c.length-3===1?"entity":"entities"]}),i&&c.length>3&&n("button",{onClick:()=>l(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})}const yS=et(function(){const t=ot(),r=rd(),[s,a]=A(!1);Ot({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(hS,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(mS,{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(fS,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(gS,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>a(!0)}),s&&t.projectSlug&&n(on,{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..."})})})}),xS=Object.freeze(Object.defineProperty({__proto__:null,default:yS,loader:pS,meta:uS},Symbol.toStringTag,{value:"Module"}));async function Xu(e,t,r){var w,C;await Je();const s=await Vt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const a=Ce();if(!a)throw new Error("Project root not found");const o=H.join(a,".codeyam","config.json"),i=JSON.parse(G.readFileSync(o,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const c=Gr(l);try{G.writeFileSync(c,"","utf8")}catch{}const{project:p}=await Re(l),u=((w=p.metadata)==null?void 0:w.packageManager)||"npm",h=3112,m=Ft(l),f=((C=p.metadata)==null?void 0:C.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const y=i.environmentVariables||[],g=Df({filePath:s.filePath,webapps:f,environmentVariables:y,port:h,packageManager:u});await ur(e,S=>{if(S&&(S.readyToBeCaptured=!0,S.scenarios))for(const k of S.scenarios)(!t||k.name===t)&&(delete k.screenshotStartedAt,delete k.screenshotFinishedAt,delete k.interactiveStartedAt,delete k.interactiveFinishedAt,delete k.error,delete k.errorStack)});const{jobId:x}=r.enqueue({type:"debug-setup",commitSha:s.commit.sha,projectSlug:l,analysisId:e,scenarioId:t,prepOnly:!0}),b=g.startCommand,v={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:m}]},{heading:"What's Happening",items:[{content:"1. Preparing analyzer and dependencies"},{content:"2. Syncing project files"},{content:"3. Setting up mock environment"}]},{heading:"Next Steps (Once Complete)",items:[{label:"1. Open the project directory",content:`code ${m}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:b,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${h}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:m,projectSlug:l,port:h,packageManager:u,framework:g.framework,instructions:v}}async function bS({request:e,context:t}){const r=new URL(e.url),s=r.searchParams.get("analysisId"),a=r.searchParams.get("scenarioId")||void 0;if(!s)return re({error:"Missing analysisId parameter",usage:"GET /api/debug-setup?analysisId=<uuid>&scenarioId=<uuid>",example:'curl "http://localhost:3111/api/debug-setup?analysisId=f35509cb-b8f1-4d86-998e-fc24201ae2c7"'},{status:400});let o=t.analysisQueue;if(o||(o=await Kt()),!o)return re({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:s,scenarioId:a});try{const i=await Xu(s,a,o);return re({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),re({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function vS({request:e,context:t}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Kt()),!r)return re({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a)return re({error:"Missing required field: analysisId"},{status:400});const i=await Xu(a,o,r);return re({...i,success:!0,message:"Debug setup queued"})}catch(s){console.error("[Debug Setup API] Error during debug setup:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Debug Setup API] Error stack:",o),re({error:"Failed to setup debug environment",details:a},{status:500})}}const wS=Object.freeze(Object.defineProperty({__proto__:null,action:vS,loader:bS},Symbol.toStringTag,{value:"Module"}));function NS({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return new Response("Missing path parameter",{status:400});const s=Ce()||process.cwd(),a=H.resolve(s,r);if(!a.startsWith(s+H.sep)&&a!==s)return new Response("Path outside project root",{status:403});try{const o=G.readFileSync(a,"utf8");return new Response(o,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch{return new Response("File not found",{status:404})}}const SS=Object.freeze(Object.defineProperty({__proto__:null,loader:NS},Symbol.toStringTag,{value:"Module"})),CS=process.env.LABS_UNLOCK_SALT||"codeyam-labs-default-salt";function ep(e){const t=nm("sha256",CS);return t.update(e),`CY-${t.digest("hex").slice(0,16)}`}function kS(e,t){return t===ep(e)}async function _S({request:e}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});try{const r=(await e.formData()).get("unlockCode");if(!r)return re({success:!1,error:"Unlock code is required"},{status:400});const s=await Ye();return s?kS(s,r)?(await sr({projectSlug:s,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),re({success:!0})):re({success:!1,error:"Invalid unlock code"},{status:400}):re({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("[Labs Unlock] Error:",t),re({success:!1,error:"Failed to validate unlock code. Please try again."},{status:500})}}const ES=Object.freeze(Object.defineProperty({__proto__:null,action:_S},Symbol.toStringTag,{value:"Module"}));async function jS({request:e,context:t}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Kt()),!r)return re({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("defaultWidth");if(!a||!o)return re({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return re({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${a} with width ${i}`);const l=await Kw(a,i,r);return console.log("[API] Recapture queued",l),re({success:!0,message:"Recapture queued",...l})}catch(s){return console.log("[API] Error during recapture:",s),re({error:"Failed to recapture screenshots",details:s instanceof Error?s.message:String(s)},{status:500})}}const AS=Object.freeze(Object.defineProperty({__proto__:null,action:jS},Symbol.toStringTag,{value:"Module"}));function PS(e){if(e.length===0)throw new Error("paths array must not be empty");return e.map(TS).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 TS(e){const r=e.replace(/\/+$/,"").split("/");for(;r.length>0;){const s=r[r.length-1];if(MS(s))r.pop();else break}return r.join("/")}function MS(e){return!!(e.includes("*")||/\.\w+$/.test(e))}function $S({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=PS(r),a=s?`.claude/rules/${s}/`:".claude/rules/";return Response.json({result:a})}const IS=Object.freeze(Object.defineProperty({__proto__:null,loader:$S},Symbol.toStringTag,{value:"Module"}));function FS(e,t){var i,l,c,p,u;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,s=e.analyses&&e.analyses.length>0&&e.analyses.some(h=>h.scenarios&&h.scenarios.length>0);if(!r){const h=!!((l=e.metadata)!=null&&l.previousVersionWithAnalyses),m=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return h||m?s?{state:"committed_no_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Committed - Simulations Outdated",color:"text-orange-700",bgColor:"bg-orange-50",borderColor:"border-orange-300",icon:"⚠"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Yet Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}:s?{state:"committed_with_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up to date",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"✓"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}const a=!!((c=e.metadata)!=null&&c.previousCommittedSha);if(!!((p=e.metadata)!=null&&p.previousVersionWithAnalyses)||a){const h=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return s&&!h?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:s?{state:"uncommitted_outdated_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Edited - Simulations Outdated",color:"text-amber-700",bgColor:"bg-amber-50",borderColor:"border-amber-300",icon:"⚠"}}:{state:"uncommitted_outdated_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}else return s?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:{state:"uncommitted_no_previous_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"New",color:"text-purple-700",bgColor:"bg-purple-50",borderColor:"border-purple-200",icon:"+"}}}function DS(e){return FS(e).hasOutdatedSimulations}function _a(e,t,r,s,a){var Y,I,L,P,R,E,J,K;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),p=!!(o!=null&&o.finishedAt),u=1800*1e3,h=l&&!c&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,m=!!((L=(I=e.metadata)==null?void 0:I.screenshotPaths)!=null&&L[0])||!!((P=e.metadata)!=null&&P.executionResult),f=l&&!c,y=o==null?void 0:o.error,g=(E=(R=e.metadata)==null?void 0:R.executionResult)==null?void 0:E.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const Q of t.errors)x.push({source:`${Q.phase} phase`,message:Q.message});if(t!=null&&t.steps)for(const Q of t.steps)Q.error&&x.push({source:Q.name,message:Q.error});const b=!m&&!y&&!g&&x.length>0,v=!!(y||g||h||b),N=h?"Capture timed out after 30 minutes":(typeof y=="string"?y:null)||(g==null?void 0:g.message)||(b?`Analysis error: ${x[0].message}`:null),w=h?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(o==null?void 0:o.errorStack)||(g==null?void 0:g.stack)||null,S=(s&&a?a.jobs.some(Q=>{var q;return((q=Q.entityShas)==null?void 0:q.includes(s))||Q.type==="analysis"&&Q.entityShas&&Q.entityShas.length===0})||((K=(J=a.currentlyExecuting)==null?void 0:J.entityShas)==null?void 0:K.includes(s)):!1)&&!i&&!v||!!(o!=null&&o.analyzing)&&!i&&!v,k=i&&!l&&!p&&!v,j=(S||k||f)&&!v,_=(S||k)&&r===!1&&!m;let F;_?F="crashed":v?F="error":m||p?F="completed":f?F="capturing":k?F="starting":S?F="queued":F="pending";let M="📷",$="pending",O=!1,D=`Not captured: ${e.name}`;const T="border-gray-300",B=v||_?"bg-red-50":"bg-white";return v||_?(M="⚠️",$="error",D=`Error: ${_?"Analysis process crashed":N||"Unknown error"}`):S?(M="⋯",$="queued",D=`Queued: ${e.name}`):k?(M="⋯",$="starting",O=!0,D=`Starting server for ${e.name}...`):f&&!v?(M="⋯",$="capturing",O=!0,D=`Capturing ${e.name}...`):m&&(M="✓",$="completed",D=e.name),{hasError:v||_,errorMessage:_?"Analysis process crashed":N,errorStack:_?"Process terminated unexpectedly before completing analysis":w,isCapturing:f,isCaptured:m,hasCrashed:_,isAnalyzing:j,isQueued:S,isServerStarting:k,status:F,icon:M,iconType:$,shouldSpin:O,title:D,borderColor:T,bgColor:B}}function tp({scenario:e,entitySha:t,size:r="medium",showBorder:s=!0,isOutdated:a=!1}){var w,C,S,k,j,_;const o=_a(e,void 0,void 0,t,void 0),i=(w=e.metadata)==null?void 0:w.executionResult,l=!!i,p=(((S=(C=e.metadata)==null?void 0:C.data)==null?void 0:S.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,h=((j=(k=i==null?void 0:i.sideEffects)==null?void 0:k.consoleOutput)==null?void 0:j.length)||0,m=((_=i==null?void 0:i.timing)==null?void 0:_.duration)||0;let f=0;p>0&&f++,p>2&&f++,u&&f++,h>0&&f++,f=Math.min(3,f);const y=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},x=o.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}: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}`:"",v=Array.from({length:3},(F,M)=>n("div",{className:`w-1 h-1 rounded-full ${M<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},M)),N=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:l?`${e.name}
483
- ${p} args → ${u?"value":"void"}${h>0?` (${h} logs)`:""}
484
- ${m}ms`:`Not executed: ${e.name}`;return d(ke,{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:N,onClick:F=>F.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:p}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),l&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:v}),l&&!o.hasError&&m>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:m>1e3?`${Math.round(m/1e3)}s`:`${m}ms`}),l&&!o.hasError&&h>0&&r==="medium"&&d("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",h]})]})}function Ro({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 gc({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(tp,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=_a(e,r,a,t.sha,s),h=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},m=`relative ${h.containerClass} ${l}`,f=()=>{const b=`/entity/${t.sha}/scenarios/${e.id}`;return c?`${b}/${c}`:b};if(u.isCaptured){const b=(x=(g=e.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return n(ke,{to:f(),className:`${m} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(dt,{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},v=n(Ii,{size:o});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return v;switch(u.iconType){case"starting":case"capturing":return v;case"error":return d("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(Ro,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(Dh,{...b});default:return v}};return n(ke,{to:f(),className:`${m} ${u.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:u.title,children:n("div",{className:h.iconSize,children:y()})})}const Xn=70;function RS({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:s,entitySha:a,cacheBuster:o,activeTab:i,entityType:l,entity:c,queueState:p,processIsRunning:u,isEntityAnalyzing:h,areScenariosStale:m,viewMode:f,setViewMode:y,isBreakdownView:g,onCreateScenario:x}){var D,T,B,Y,I,L;const b=ye(null),[v,N]=A(new Set),[w,C]=A(!1);ne(()=>{b.current&&i==="scenarios"&&b.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[s==null?void 0:s.id,i]);const S=P=>`/entity/${a}/scenarios/${P}`,k=P=>{N(R=>{const E=new Set(R);return E.has(P)?E.delete(P):E.add(P),E})},j=(P,R=2)=>{const J=P.split(`
485
- `).slice(0,R).join(" ").trim();return J.length>Xn?J.substring(0,Xn-3):(P.split(`
486
- `).length>R||P.length>J.length,J)},_=le(()=>{var R;if(!((R=r==null?void 0:r.metadata)!=null&&R.executionFlows)||!(r!=null&&r.scenarios))return null;const P=r.scenarios.filter(E=>{var J;return!((J=E.metadata)!=null&&J.sameAsDefault)});return Ei(r.metadata.executionFlows,P)},[r]),F=(_==null?void 0:_.totalFlows)||0,M=(_==null?void 0:_.coveredFlows)||0,$=(_==null?void 0:_.coveragePercentage)||0;(D=c==null?void 0:c.metadata)!=null&&D.defaultWidth||(T=r==null?void 0:r.metadata)!=null&&T.defaultWidth;const O=(B=r==null?void 0:r.status)!=null&&B.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(ke,{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:[Math.round($),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),d(ke,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((I=e[0])==null?void 0:I.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:[M,"/",F]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),d(ke,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((L=e[0])==null?void 0:L.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("button",{onClick:x,className:"w-full px-3 py-2 bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[11px] font-medium font-mono cursor-pointer transition-colors hover:bg-[#004a5e] flex items-center justify-center gap-1",children:"+ Create New Scenario"})}),e.length>0&&d("div",{className:"py-3 flex items-center justify-between",children:[d("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),O&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:O})]}),h&&(m||e.length===0)?d("div",{className:"",children:[d("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[d("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}),n("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):e.length===0?n("div",{className:"",children:n("p",{className:"text-[#8e8e8e] text-xs font-medium m-0 text-left leading-5",children:"No Scenarios"})}):n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"flex flex-col gap-[11.6px]",children:e.map((P,R)=>{const E=!g&&(s==null?void 0:s.id)===P.id,J=v.has(P.id||"");return P.id?d(ke,{to:S(P.id),ref:E?b:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${E?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[n("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:n(gc,{scenario:P,entity:{sha:a,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:p,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),d("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${J?"":"line-clamp-1"}`,children:P.name}),P.description&&n("div",{className:"mt-2",children:d("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[J?P.description:j(P.description),!J&&P.description.length>Xn&&d(ve,{children:["...",n("button",{onClick:K=>{K.preventDefault(),K.stopPropagation(),k(P.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),J&&P.description.length>Xn&&n("button",{onClick:K=>{K.preventDefault(),K.stopPropagation(),k(P.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},R):null})})}),t.length>0&&!(h&&m)&&d("div",{className:"border-t border-[#e1e1e1] pt-3",children:[d("button",{onClick:()=>C(!w),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 ${w?"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,")"]}),w&&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((P,R)=>{const E=!g&&(s==null?void 0:s.id)===P.id,J=v.has(P.id||"");return P.id?d(ke,{to:`/entity/${a}/scenarios/${P.id}`,ref:E?b:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${E?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[n("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:n(gc,{scenario:P,entity:{sha:a,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:p,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),d("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${J?"":"line-clamp-1"}`,children:P.name}),P.description&&n("div",{className:"mt-2",children:d("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[J?P.description:j(P.description),!J&&P.description.length>Xn&&d(ve,{children:["...",n("button",{onClick:K=>{K.preventDefault(),K.stopPropagation(),k(P.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),J&&P.description.length>Xn&&n("button",{onClick:K=>{K.preventDefault(),K.stopPropagation(),k(P.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},R):null})})]})]})]})}function OS({scenario:e,entitySha:t,onApply:r,onSave:s,onEditMockData:a,onDelete:o,isApplying:i=!1,isSaving:l=!1,saveMessage:c=null,showDeleteConfirm:p=!1,onShowDeleteConfirm:u,isDeleting:h=!1,deleteError:m=null}){const[f,y]=A(""),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(ke,{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(ke,{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(ve,{children:[p?d("div",{className:"flex flex-col gap-1",children:[d("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),d("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void o(),disabled:h,className:"flex-1 h-[22px] bg-red-600 text-white rounded text-[10px] font-normal hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors flex items-center justify-center cursor-pointer",children:h?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>u==null?void 0:u(!1),disabled:h,className:"flex-1 h-[22px] bg-gray-100 text-gray-700 border border-gray-300 rounded text-[10px] font-normal hover:bg-gray-200 disabled:opacity-50 transition-colors flex items-center justify-center cursor-pointer",children:"Cancel"})]})]}):n("button",{onClick:()=>u==null?void 0:u(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),m&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:m})]})]})]})}function LS({scenario:e,analysis:t,entity:r}){var i,l,c;const s=((i=e.metadata)==null?void 0:i.executionResult)||null,a=((c=(l=e.metadata)==null?void 0:l.data)==null?void 0:c.argumentsData)||[],o=p=>{var y,g,x;if(!p)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const u=[],h=((y=p.sideEffects)==null?void 0:y.consoleOutput)||[];h.length>0&&(u.push(`Console Output: ${h.length} log ${h.length===1?"entry":"entries"} captured`),h.forEach(b=>{u.push(` [${b.level.toUpperCase()}] ${b.args.join(" ")}`)}));const m=((g=p.sideEffects)==null?void 0:g.fileWrites)||[];m.length>0&&(u.push(`
487
- File System Operations: ${m.length} ${m.length===1?"operation":"operations"} detected`),m.forEach(b=>{u.push(` ${b.operation}: ${b.path}${b.size?` (${b.size} bytes)`:""}`)}));const f=((x=p.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(u.push(`
488
- API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(b=>{u.push(` ${b.method} ${b.url}${b.status?` → ${b.status}`:""}${b.duration?` (${b.duration}ms)`:""}`)})),p.error&&u.push(`
489
- Error: ${p.error.name||"Error"}: ${p.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
490
- `)};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 Sn={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function Ss({scenarioId:e,analysisId:t}){const[r,s]=A(!1),[a,o]=A(!1),[i,l]=A(null),[c,p]=A(!1),u=e||t;if(!u)return null;const h=`/codeyam-diagnose ${u}`,m=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(ve,{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:Sn.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:Sn.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:Sn.commandBoxBg,borderColor:Sn.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:Sn.commandBoxText},children:h}),n("button",{onClick:y=>{y.stopPropagation(),navigator.clipboard.writeText(h),p(!0),setTimeout(()=>p(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:c?"#22c55e":Sn.commandBoxText},title:c?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:c?n(Et,{size:14}):n(It,{size:14})})]}),d("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",n("button",{onClick:()=>void m(),disabled:a,className:"underline cursor-pointer bg-transparent border-none p-0 font-normal hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:Sn.link},children:a?"capturing...":"please do so here"}),"."]})]}),n(hd,{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 yc=1440,Cs=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],Yt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function np({selectedScenario:e,analysis:t,entity:r,viewMode:s,cacheBuster:a,hasScenarios:o,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:c=!0,processIsRunning:p,queueState:u}){var V,ae,pe,xe,ie,me,we,Te,Ne,_e,Z;const h=Ge(),[m,f]=A(!1),[y,g]=A(!1),[x,b]=A({name:"Desktop",width:yc,height:900}),[v,N]=A(yc),[w,C]=A(1),{customSizes:S,addCustomSize:k,removeCustomSize:j}=ha(l),_=le(()=>[...Cs,...S],[S]),F=(he,te)=>{N(he);const se=_.find(ce=>ce.width===he&&ce.height===te);b({name:(se==null?void 0:se.name)||"Custom",width:he,height:te})},M=he=>{N(he.width),b({name:he.name,width:he.width,height:he.height})},$=he=>{k(he,x.width,x.height??900),g(!1),b(te=>({...te,name:he}))},O=(he,te)=>{N(he);const se=_.find(ce=>ce.width===he&&ce.height===te);b(ce=>({name:(se==null?void 0:se.name)||"Custom",width:he,height:ce.height}))},D=(ae=(V=e==null?void 0:e.metadata)==null?void 0:V.screenshotPaths)==null?void 0:ae[0],T=le(()=>e?_a(e,t==null?void 0:t.status,p,r==null?void 0:r.sha,u):null,[e,t==null?void 0:t.status,p,r==null?void 0:r.sha,u]),B=le(()=>{var te,se;const he=[];if((te=t==null?void 0:t.status)!=null&&te.errors&&t.status.errors.length>0)for(const ce of t.status.errors)he.push({source:`${ce.phase} phase`,message:ce.message,stack:ce.stack});if((se=t==null?void 0:t.status)!=null&&se.steps)for(const ce of t.status.steps)ce.error&&he.push({source:ce.name,message:ce.error,stack:ce.errorStack});return he},[(pe=t==null?void 0:t.status)==null?void 0:pe.errors,(xe=t==null?void 0:t.status)==null?void 0:xe.steps]),Y=(T==null?void 0:T.errorMessage)||null,I=(T==null?void 0:T.errorStack)||null,{interactiveServerUrl:L,isStarting:P,isLoading:R,showIframe:E,iframeKey:J,onIframeLoad:K}=In({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=le(()=>L||null,[L]),q=!i&&o&&e&&!((me=(ie=e.metadata)==null?void 0:ie.screenshotPaths)!=null&&me[0])&&((Te=(we=t==null?void 0:t.status)==null?void 0:we.scenarios)==null?void 0:Te.some(he=>he.name===e.name&&he.screenshotStartedAt&&!he.screenshotFinishedAt)),{lastLine:U}=Jt(l,i||s==="interactive"||q||!1);if(!e){if(i&&r)return d(ve,{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:q?"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."}),U&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:U}),l&&n("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})}),m&&l&&n(on,{projectSlug:l,onClose:()=>f(!1)})]});if(!o&&r&&!i){if(B.length>0){const he=B.length===1?((Ne=B[0])==null?void 0:Ne.message)||"An error occurred during analysis.":`${B.length} errors occurred during analysis.`;return d(ve,{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:Yt.background,border:`2px solid ${Yt.border}`},role:"alert",children:d("div",{className:"flex items-center gap-3",children:[n(Ro,{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:Yt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",he," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:Yt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Ss,{analysisId:t==null?void 0:t.id})})]})}),m&&l&&n(on,{projectSlug:l,onClose:()=>f(!1)})]})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:d("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{h.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:h.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:h.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return d(ve,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
491
- linear-gradient(45deg, #ebebeb 25%, transparent 25%),
492
- linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
493
- linear-gradient(45deg, transparent 75%, #ebebeb 75%),
494
- linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
495
- `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||q&&!D)&&!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:q?`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:q?`Taking screenshots for ${((_e=t==null?void 0:t.scenarios)==null?void 0:_e.length)||0} scenario${((Z=t==null?void 0:t.scenarios)==null?void 0:Z.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]})]}),U&&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:U,children:U})]})]})}),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"&&(D||Y)||s==="interactive"&&(Q||P)||s==="data"?d(ve,{children:[Y&&!D&&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:Yt.background,border:`2px solid ${Yt.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:Yt.text},children:[n(Ro,{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:Yt.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:Yt.text},children:Y})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Ss,{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(lx,{presets:[...Cs],customSizes:S,currentWidth:x.width,currentHeight:x.height??900,scale:w,onSizeChange:F,onSaveCustomSize:()=>g(!0),onRemoveCustomSize:j}),e&&r&&d(ke,{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:`${Cs[Cs.length-1].width}px`,width:"100%"},children:n(ii,{currentViewportWidth:v,currentPresetName:x.name,onDevicePresetClick:M,devicePresets:_})})}),n(Sa,{scenarioId:e.id,scenarioName:e.name,iframeUrl:Q,isStarting:P,isLoading:R,showIframe:E,iframeKey:J,onIframeLoad:K,onScaleChange:C,onDimensionChange:O,projectSlug:l,defaultWidth:x.width,defaultHeight:x.height})]}):s==="data"?n("div",{className:"flex-1 min-h-0",children:n(LS,{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:`${v}px`},children:(D||!Y)&&n(dt,{screenshotPath:D,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&&!D?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."]}),U&&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:U})]}),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(ke,{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})})]}),I&&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:I})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Ss,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):B.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:B,title:"Analysis Error",description:B.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${B.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(Ss,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):d("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),m&&l&&n(on,{projectSlug:l,onClose:()=>f(!1)}),y&&n(li,{width:x.width,height:x.height??900,onSave:$,onCancel:()=>g(!1)})]})}function zS({analysis:e,entitySha:t,onCreateScenario:r}){Rt();const[s,a]=A(e);ne(()=>{a(e)},[e]);const[o,i]=A(null),l=le(()=>{var m;if(!((m=s==null?void 0:s.metadata)!=null&&m.executionFlows)||!(s!=null&&s.scenarios))return null;const h=s.scenarios.filter(f=>{var y;return!((y=f.metadata)!=null&&y.sameAsDefault)});return Ei(s.metadata.executionFlows,h)},[s]),c=le(()=>l?Xx(l):[],[l]),p=le(()=>s!=null&&s.scenarios?s.scenarios.filter(h=>{var m;return!((m=h.metadata)!=null&&m.sameAsDefault)}):[],[s]),u=h=>{var f;const m=((f=h.metadata)==null?void 0:f.coveredFlows)||[];return l?l.executionFlows.filter(y=>m.includes(y.id)):[]};return s?!l||l.executionFlows.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:d("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:d("div",{className:"p-6 space-y-6",children:[d("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),d("div",{className:"grid grid-cols-4 gap-4 text-center",children:[d("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:p.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:l.executionFlows.length}),n("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[d("div",{className:"text-2xl font-bold text-gray-900",children:[l.coveredFlows,"/",l.totalFlows]}),n("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[d("div",{className:`text-2xl font-bold ${l.coveragePercentage===100?"text-green-600":l.coveragePercentage>=50?"text-amber-600":"text-red-600"}`,children:[l.coveragePercentage.toFixed(0),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),d("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:d("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",p.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:p.length===0?d("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",n("button",{onClick:r,className:"text-blue-600 hover:underline bg-transparent border-none cursor-pointer p-0 text-sm",children:"Create one"})]}):p.map(h=>{var y,g,x;const m=(g=(y=h.metadata)==null?void 0:y.screenshotPaths)==null?void 0:g[0],f=u(h);return d("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(dt,{screenshotPath:m,alt:h.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),d("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:d("div",{children:[n(ke,{to:`/entity/${t}/scenarios/${h.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:h.name}),((x=h.metadata)==null?void 0:x.error)&&n("span",{className:"ml-2 text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"Error"})]})}),n("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:h.description}),f.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:f.map(b=>n("span",{className:`text-xs px-1.5 py-0.5 rounded ${b.isError?"bg-red-50 text-red-700":b.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:b.name},b.id))})]})]},h.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:d("button",{onClick:r,className:"w-full px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 flex items-center justify-center gap-2 border-none cursor-pointer",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),c.length>0&&d("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[d("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[c.length," uncovered execution flow",c.length>1?"s":""," — consider adding scenarios to cover these"]}),d("div",{className:"flex flex-wrap gap-1",children:[c.slice(0,10).map(h=>d("span",{className:`text-xs px-2 py-0.5 rounded ${h.impact==="high"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[h.name,h.impact==="high"&&" (high impact)"]},h.id)),c.length>10&&d("span",{className:"text-xs text-amber-600",children:["+",c.length-10," more"]})]})]}),d("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:d("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",l.executionFlows.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:l.executionFlows.map(h=>{const m=o===h.id,f=h.usedInScenarios.length>0;return d("div",{children:[n("button",{onClick:()=>i(m?null:h.id),className:"w-full px-4 py-3 flex items-start justify-between text-left bg-transparent border-none cursor-pointer hover:bg-gray-50",children:d("div",{className:"flex items-start gap-3 flex-1",children:[n("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:m?"▼":"▶"}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-medium text-sm text-gray-900",children:h.name}),f?n("span",{className:"text-xs px-2 py-0.5 rounded bg-green-100 text-green-700",children:"Covered"}):n("span",{className:"text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700",children:"Uncovered"}),h.blocksOtherFlows&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),h.impact==="high"&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),h.isError&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),h.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:h.description})]})]})}),m&&d("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[h.requiredValues.length>0&&d("div",{className:"mb-4",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),n("div",{className:"space-y-1",children:h.requiredValues.map((y,g)=>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:y.attributePath}),n("span",{className:"text-gray-400",children:y.comparison}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:y.value})]},g))})]}),f&&d("div",{children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),n("div",{className:"flex flex-wrap gap-1",children:h.usedInScenarios.map(y=>n("span",{className:"text-xs px-1.5 py-0.5 bg-green-50 text-green-700 rounded",children:y.name},y.id))})]}),h.codeSnippet&&d("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:h.codeSnippet})})]})]})]},h.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:d("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function xc({hasIndirectBadge:e,onAnalyze:t}){return d(ve,{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 BS({entity:e,history:t}){const[r,s]=A("entity"),[a,o]=A(new Set),i=t.filter(u=>u.analyses.length>0).length,l=le(()=>{const u=new Map;return t.forEach(h=>{h.analyses.forEach(m=>{(m.scenarios??[]).filter(y=>{var g;return!((g=y.metadata)!=null&&g.sameAsDefault)}).forEach(y=>{u.has(y.name)||u.set(y.name,[]),u.get(y.name).push({version:h,analysis:m,scenario:y})})})}),Array.from(u.entries()).map(([h,m])=>{var f;return{name:h,description:((f=m[0])==null?void 0:f.scenario.description)||"",versions:m.sort((y,g)=>{const x=new Date(y.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-x})}})},[t]),c=l.length,p=u=>{o(h=>{const m=new Set(h);return m.has(u)?m.delete(u):m.add(u),m})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:d("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:d("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[d("button",{onClick:()=>s("entity"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="entity"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-semibold leading-6",children:"Entity History"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="entity"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:i})]}),d("button",{onClick:()=>s("scenarios"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="scenarios"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-normal leading-6",children:"Scenario Changes"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="scenarios"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:c})]})]})}),t.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):r==="entity"?d("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((u,h)=>d("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center gap-3",children:[u.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),d(ke,{to:`/entity/${u.sha}/scenarios`,className:"text-xs font-mono text-[#646464] leading-5 hover:text-[#005c75] transition-colors",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:u.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:u.createdAt&&new Date(u.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),u.analyses.length>0?n("div",{children:u.analyses.map((m,f)=>{var g;const y=(m.scenarios??[]).filter(x=>{var b;return!((b=x.metadata)!=null&&b.sameAsDefault)});return n("div",{children:y.length===0?n(xc,{hasIndirectBadge:m.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):d(ve,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:d("div",{className:"flex items-center justify-end gap-2",children:[m.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),d("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[y.length," scenario",y.length!==1?"s":""]})]})}),((g=m.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:"," "]}),m.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 w,C;const v=(C=(w=x.metadata)==null?void 0:w.screenshotPaths)==null?void 0:C[0],N=`${x.name}-${b}`;return d(ke,{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:v?n(dt,{screenshotPath:v,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})})]},N)})})})]})},m.id||f)})}):n(xc,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:l.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):l.map((u,h)=>{const m=a.has(u.name),f=m?u.versions:u.versions.slice(0,1),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 k,j;const{version:v,analysis:N,scenario:w}=x,C=(j=(k=w.metadata)==null?void 0:k.screenshotPaths)==null?void 0:j[0],S=b===0;return d("div",{className:`flex gap-5 items-start ${S?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(ke,{to:`/entity/${v.sha}/scenarios/${w.id}`,className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0 hover:border-[#005c75] hover:shadow-sm transition-all",children:C?n(dt,{screenshotPath:C,alt:w.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:[v.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"}),S&&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(ke,{to:`/entity/${v.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:v.sha.substring(0,8)})]}),N.createdAt&&d("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(N.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),N.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${v.sha}-${b}`)}),y>0&&d("button",{onClick:()=>p(u.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${m?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),m?"Hide":`${y} previous version${y!==1?"s":""}`]})]})]})]},u.name)})})]})})}function bc({entity:e,analysisInfo:t,from:r}){const s=Ge(),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(ke,{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(dt,{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(gt,{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(gt,{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(ve,{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(ve,{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 vc=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 YS({importedEntities:e,importingEntities:t}){const[r]=ir(),s=r.get("from"),a=Ge(),o=a.state!=="idle",i=e.length>0,l=t.length>0,c=m=>m.filter(f=>f.entityType==="visual"||f.entityType==="library"),p=m=>{const f=c(m);f.length!==0&&a.submit({entityShas:f.map(y=>y.sha).join(",")},{method:"post",action:"/api/analyze"})},u=c(e).length>0,h=c(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-6 py-4 flex items-start justify-between",children:[d("div",{children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&n("button",{onClick:()=>p(e),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(m=>n(bc,{entity:m,analysisInfo:vc(m),from:s},m.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-6 py-4 flex items-start justify-between",children:[d("div",{children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),h&&n("button",{onClick:()=>p(t),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),l?n("div",{className:"p-6 space-y-4",children:t.map(m=>n(bc,{entity:m,analysisInfo:vc(m),from:s},m.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px] text-center",children:"Not imported by any entity."})})]})]})})}function WS({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(YS,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function US({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(Ur,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function Ur({data:e,depth:t,defaultExpanded:r,maxDepth:s,objectKey:a,showInlineToggle:o=!1}){const[i,l]=A(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(ve,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((p,u)=>n("div",{className:"py-0.5",children:n(Ur,{data:p,depth:t+1,defaultExpanded:r,maxDepth:s})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(c==="object"){const p=Object.keys(e);if(p.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=m=>m!==null&&typeof m=="object"&&!Array.isArray(m)&&Object.keys(m).length>0,h=m=>Array.isArray(m)&&m.length>0;return d("span",{children:[d("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[d("span",{children:[i?"▼":"▶"," ","{"]}),!i&&d("span",{children:[p.length,"}"]})]}),i?d(ve,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:p.map(m=>{const f=e[m],y=u(f),g=h(f);return n("div",{className:"py-0.5",children:y?n(Fi,{propertyKey:m,value:f,depth:t,defaultExpanded:r,maxDepth:s}):g?n(Di,{propertyKey:m,value:f,depth:t,defaultExpanded:r,maxDepth:s}):d(ve,{children:[d("span",{className:"text-orange-600",children:[m,": "]}),n(Ur,{data:f,depth:t+1,defaultExpanded:r,maxDepth:s})]})},m)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function Fi({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=A(s||r<2),l=Object.keys(t);return ne(()=>{i(s||r<2)},[s,r]),d(ve,{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(ve,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:l.map(c=>{const p=t[c],u=p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,h=Array.isArray(p)&&p.length>0;return n("div",{className:"py-0.5",children:u?n(Fi,{propertyKey:c,value:p,depth:r+1,defaultExpanded:s,maxDepth:a}):h?n(Di,{propertyKey:c,value:p,depth:r+1,defaultExpanded:s,maxDepth:a}):d(ve,{children:[d("span",{className:"text-orange-600",children:[c,": "]}),n(Ur,{data:p,depth:r+2,defaultExpanded:s,maxDepth:a})]})},c)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function Di({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=A(s||r<2);return ne(()=>{i(s||r<2)},[s,r]),d(ve,{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(ve,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((l,c)=>{const p=l!==null&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,u=Array.isArray(l)&&l.length>0;return n("div",{className:"py-0.5",children:p?n(Fi,{propertyKey:c.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:a}):u?n(Di,{propertyKey:c.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:a}):n(Ur,{data:l,depth:r+2,defaultExpanded:s,maxDepth:a})},c)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function uo({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 wc({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 Nc({call:e,scenarioName:t}){const[r,s]=A(!1),[a,o]=A("system"),i=m=>new Date(m).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),l=m=>m?`$${m.toFixed(4)}`:null,c=(m,f)=>{if(!m&&!f)return null;const y=[];return m&&y.push(`${m.toLocaleString()} in`),f&&y.push(`${f.toLocaleString()} out`),y.join(" / ")},p=le(()=>{var m,f,y,g,x;try{const b=JSON.parse(e.response);return(y=(f=(m=b.choices)==null?void 0:m[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=le(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),h=le(()=>{var m;if(t)return t;try{const f=JSON.parse(e.props);return((m=f==null?void 0:f.scenario)==null?void 0:m.name)||null}catch{return null}},[e.props,t]);return d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>s(!r),children:d("div",{className:"flex items-start justify-between gap-4",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),h&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:h}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),d("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),c(e.input_tokens,e.output_tokens)&&n("span",{children:c(e.input_tokens,e.output_tokens)}),l(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:l(e.cost)})]}),d("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.object_id,"_",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&d("div",{className:"border-t border-[#e1e1e1]",children:[d("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>o("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>o("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>o("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),a&&d("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[a==="system"&&n("div",{children:e.system_message?n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.system_message}):n("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),a==="prompt"&&n("div",{children:n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.prompt_text})}),a==="response"&&d("div",{children:[e.error&&d("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:p})]}),a==="props"&&n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),e.error&&!a&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:d("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const Sc=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function JS({entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a}){var N,w,C,S,k,j,_,F,M;const[o,i]=A("entity"),[l,c]=A("analysis"),[p,u]=A(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[h,m]=A("entity"),{entityLlmCalls:f,scenarioLlmCalls:y,totalLlmCalls:g}=le(()=>{if(!a)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const $=[...a.entityCalls,...a.analysisCalls],O=$.filter(T=>T.object_type==="entity"||Sc.includes(T.prompt_type)),D=$.filter(T=>T.object_type!=="entity"&&!Sc.includes(T.prompt_type));return O.sort((T,B)=>B.created_at-T.created_at),D.sort((T,B)=>B.created_at-T.created_at),{entityLlmCalls:O,scenarioLlmCalls:D,totalLlmCalls:$.length}},[a]),x=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(N=e==null?void 0:e.metadata)==null?void 0:N.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(w=t==null?void 0:t.metadata)==null?void 0:w.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(S=(C=e==null?void 0:e.metadata)==null?void 0:C.isolatedDataStructure)==null?void 0:S.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(k=t==null?void 0:t.metadata)==null?void 0:k.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(j=e==null?void 0:e.metadata)==null?void 0:j.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:(F=t==null?void 0:t.metadata)==null?void 0:F.scenariosDataStructure,description:"Structure template used across all scenarios"}],b=x.filter($=>$.data!==void 0&&$.data!==null).length;let v=null;if(o==="entity"){const $=x.find(O=>O.id===l);$&&$.data!==void 0&&$.data!==null&&(v={title:$.title,description:$.description,data:$.data})}else if(o==="scenarios"&&p){const $=r.find(O=>(O.id||O.name)===p.scenarioId);$&&(v={title:$.name,description:$.description||"Scenario data and configuration",data:$.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(uo,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(uo,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(uo,{label:"LLM Calls",count:g,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((M=t==null?void 0:t.metadata)==null?void 0:M.analyzerVersion)&&d("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?d("div",{className:"flex-1 min-h-0",children:[d("div",{className:"flex gap-4 mb-4",children:[d("button",{onClick:()=>m("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${h==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),d("button",{onClick:()=>m("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${h==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",y.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:h==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map($=>n(Nc,{call:$},$.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($=>n(Nc,{call:$},$.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(ve,{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($=>{const O=$.data!==void 0&&$.data!==null;return n(wc,{label:$.title,isActive:l===$.id,onClick:()=>c($.id),disabled:!O},$.id)})})]}):d(ve,{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($=>{const O=$.id||$.name,D=(p==null?void 0:p.scenarioId)===O;return n(wc,{label:$.name,isActive:D,onClick:()=>u({scenarioId:O})},O)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:v?n(HS,{title:v.title,description:v.description,data:v.data}):o==="scenarios"&&r.length===0?n(Cc,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:s}):o==="entity"?n(Cc,{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 Cc({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 HS({title:e,description:t,data:r}){const[s,a]=A(!0);return d(ve,{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(pt,{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(US,{data:r,defaultExpanded:s,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function VS({entity:e,analysis:t,scenarios:r,onAnalyze:s}){const a=Ge();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(JS,{entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a.data})})}const KS={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},GS={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},qS=2e3,QS=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 ZS({entity:e,entityCode:t}){const r=Jr(),s=ye(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(pt,{content:t,label:"Copy Code",duration:qS,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(pm,{language:QS(e==null?void 0:e.filePath),style:hm,showLineNumbers:!0,customStyle:KS,lineNumberStyle:GS,wrapLines:!0,lineProps:a=>({"data-line-number":a,style:{display:"block"}}),children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}function un({prompt:e,height:t=300,onClose:r,hideHeader:s}){const a=ye(null),o=ye(null),i=ye(null),l=ye(!1),c=ye(e);ne(()=>{const u=a.current;if(!u)return;let h=!1,m=null;async function f(){const[y,g]=await Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit")]);if(h)return;{let _=document.getElementById("xterm-css");_||(_=document.createElement("style"),_.id="xterm-css",document.head.appendChild(_)),_.textContent=`
496
- .xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
497
- .xterm.focus, .xterm:focus { outline: none; }
498
- .xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
499
- .xterm .xterm-helper-textarea { padding: 0; border: 0; margin: 0; position: absolute; opacity: 0; left: -9999em; top: 0; width: 0; height: 0; z-index: -5; white-space: nowrap; overflow: hidden; resize: none; caret-color: transparent !important; clip-path: inset(100%) !important; }
500
- .xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
501
- .xterm .composition-view.active { display: block; }
502
- .xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
503
- .xterm .xterm-screen { position: relative; }
504
- .xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
505
- .xterm .xterm-scroll-area { visibility: hidden; }
506
- .xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
507
- .xterm.enable-mouse-events { cursor: default; }
508
- .xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
509
- .xterm.column-select.focus { cursor: crosshair; }
510
- .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; }
511
- .xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
512
- .xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
513
- .xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
514
- .xterm-dim { opacity: 1 !important; }
515
- .xterm-underline-1 { text-decoration: underline; }
516
- .xterm-underline-2 { text-decoration: double underline; }
517
- .xterm-underline-3 { text-decoration: wavy underline; }
518
- .xterm-underline-4 { text-decoration: dotted underline; }
519
- .xterm-underline-5 { text-decoration: dashed underline; }
520
- .xterm-overline { text-decoration: overline; }
521
- .xterm-strikethrough { text-decoration: line-through; }
522
- .xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
523
- .xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
524
- .xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
525
- .xterm-decoration-top { z-index: 2; position: relative; }
526
- `}const x=new y.Terminal({theme:{background:"#1a1a1a",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78"},fontSize:12,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",cursorBlink:!0,scrollback:5e3,allowProposedApi:!0}),b=new g.FitAddon;x.loadAddon(b),x.open(u),requestAnimationFrame(()=>{try{b.fit()}catch{}}),i.current=x;let v=null;try{const _=await fetch("/api/editor-scenario-prompt",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:c.current})});_.ok&&(v=(await _.json()).promptFile)}catch{}if(h)return;const N=window.location.protocol==="https:"?"wss:":"ws:",w=window.location.host,C=new URLSearchParams;C.set("entityName","inline-claude");const S=`${N}//${w}/ws/terminal?${C.toString()}`,k=new WebSocket(S);o.current=k,k.onopen=()=>{k.send(JSON.stringify({type:"resize",cols:x.cols,rows:x.rows}))};let j=!1;k.onmessage=_=>{try{const F=JSON.parse(_.data);if(F.type==="session-id"&&!j){j=!0,setTimeout(()=>{const M=v?`claude "Read the file at '${v.replace(/'/g,"'\\''")}' for your instructions."`:"claude";k.send(JSON.stringify({type:"input",data:M+"\r"}))},300);return}if(F.type==="output"&&F.data){x.write(F.data);return}}catch{x.write(_.data)}},k.onclose=()=>{l.current||x.write(`\r
527
- \x1B[90m--- Session ended ---\x1B[0m\r
528
- `)},k.onerror=()=>{x.write(`\r
529
- \x1B[31mConnection error\x1B[0m\r
530
- `)},x.onData(_=>{k.readyState===WebSocket.OPEN&&k.send(JSON.stringify({type:"input",data:_}))}),m=new ResizeObserver(()=>{try{b.fit(),k.readyState===WebSocket.OPEN&&k.send(JSON.stringify({type:"resize",cols:x.cols,rows:x.rows}))}catch{}}),m.observe(u)}return f(),()=>{var y,g;h=!0,l.current=!0,m==null||m.disconnect(),((y=o.current)==null?void 0:y.readyState)===WebSocket.OPEN&&o.current.close(),(g=i.current)==null||g.dispose()}},[]);const p=t==="100%";return d("div",{className:s?"":"border-t border-[#2d2d2d]",style:p?{height:"100%",display:"flex",flexDirection:"column"}:void 0,children:[!s&&d("div",{className:"flex items-center justify-between px-3 py-1.5 bg-[#1e1e1e]",children:[n("span",{className:"text-[10px] font-medium text-[#00a0c4]",children:"Claude"}),r&&n("button",{onClick:r,className:"text-gray-500 hover:text-gray-300 text-[10px] bg-transparent border-none cursor-pointer",children:"Close"})]}),n("div",{ref:a,style:{height:p?void 0:t,flex:p?1:void 0,background:"#1a1a1a",padding:"4px 0",position:"relative",overflow:"hidden"}})]})}const XS=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function eC({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 tC({params:e,request:t,context:r}){const{sha:s}=e;if(!s)throw new Response("Entity SHA is required",{status:400});const o=new URL(t.url).searchParams.get("from"),l=(e["*"]||"").split("/").filter(Boolean),c=l[0]||"scenarios",p=l[1]||null,u=l[2]||null,h=r.analysisQueue,m=h?h.getState():{paused:!1,jobs:[]},[f,y,g,x]=await Promise.all([Pn(s),Ye(),pr(),kg(Ce()||process.cwd())]),b=f?await oa(f):null,v=f?await jd(f.sha):null;let N={importedEntities:[],importingEntities:[]},w=null,C=[];f&&(N=await Ad(f),w=await Pd(f),C=await Md(f));const S=!!(f&&C.length>0&&C[0].sha!==f.sha),k=C.length>0?C[0].sha:null,j=!!(C.length>0&&C[0].analyses&&C[0].analyses.length>0),_=f?await Td(f):!1;return re({entity:f??void 0,analysis:b??void 0,currentEntityAnalysis:v??void 0,projectSlug:y,from:o,relatedEntities:N,entityCode:w??void 0,hasNewerVersion:S,newestEntitySha:k,newestVersionHasAnalysis:j,fileModifiedSinceEntity:_,history:C,tab:c,scenarioId:p,viewModeFromUrl:u,currentCommit:g,hasAnApiKey:x,queueState:m})}const nC=et(function(){var gn,Nr,Sr,Cr,es,ts,ns,Bn,rs,ss,as,Yn,Wn,os,kr;const t=ot(),a=(rd()["*"]||"").split("/").filter(Boolean),o=a[0]||"scenarios",i=a[1]||null,l=a[2]||null,c=t.entity,p=t.analysis,u=t.currentEntityAnalysis,h=u||p,m=t.projectSlug;t.from;const f=t.relatedEntities,y=t.entityCode,g=t.hasNewerVersion,x=t.newestEntitySha,b=t.newestVersionHasAnalysis,v=t.fileModifiedSinceEntity,N=t.history,w=t.currentCommit,C=t.hasAnApiKey,S=t.queueState;(gn=h==null?void 0:h.status)==null||gn.errors;const k=(h==null?void 0:h.scenarios)||[],j=k.filter(fe=>{var Me;return!((Me=fe.metadata)!=null&&Me.sameAsDefault)}),_=k.filter(fe=>{var Me;return(Me=fe.metadata)==null?void 0:Me.sameAsDefault}),F=Dt(),M=ye(null);ne(()=>{M.current===null&&(M.current=window.history.length)},[]);const $=()=>{if(typeof window>"u")return;const fe=window.history.state;if(fe===null||(fe==null?void 0:fe.idx)===void 0||(fe==null?void 0:fe.idx)===0)F("/");else{const Me=window.history.length,tt=M.current;if(tt!==null&&Me>tt){const We=Me-tt+1;F(-We)}else F(-1)}},O=!!S.currentlyExecuting,D=o,T=(Nr=w==null?void 0:w.metadata)==null?void 0:Nr.currentRun,B=!!(T!=null&&T.createdAt)&&!(T!=null&&T.analysisCompletedAt),Y=!!(c!=null&&c.sha&&((Sr=T==null?void 0:T.currentEntityShas)!=null&&Sr.includes(c.sha))),I=!!(c!=null&&c.sha&&((es=(Cr=S.currentlyExecuting)==null?void 0:Cr.entityShas)!=null&&es.includes(c.sha))),L=!!(c!=null&&c.sha&&((ts=S.jobs)!=null&&ts.some(fe=>{var Me;return(Me=fe.entityShas)==null?void 0:Me.includes(c.sha)}))),P=Y||I||L,R=P&&((ns=h==null?void 0:h.status)==null?void 0:ns.finishedAt)!=null&&j.length>0&&h.entitySha!==(c==null?void 0:c.sha),E=le(()=>{if(D!=="scenarios")return null;if(i){const fe=j.find(Me=>Me.id===i);if(fe)return fe}return j.length>0&&!P?j[0]:null},[D,i,j,P]),J=((ss=(rs=(Bn=E==null?void 0:E.metadata)==null?void 0:Bn.executionResult)==null?void 0:rs.error)==null?void 0:ss.message)||((Wn=(Yn=(as=h==null?void 0:h.status)==null?void 0:as.errors)==null?void 0:Yn[0])==null?void 0:Wn.message);Ot({source:E?"scenario-page":"entity-page",entitySha:c==null?void 0:c.sha,scenarioId:E==null?void 0:E.id,analysisId:h==null?void 0:h.id,entityName:c==null?void 0:c.name,entityType:c==null?void 0:c.entityType,scenarioName:E==null?void 0:E.name,errorMessage:J});const[K,Q]=A(()=>l&&l!=="edit"?l:(c==null?void 0:c.entityType)==="library"?"data":"screenshot");ne(()=>{l&&l!==K&&l!=="edit"&&Q(l)},[l]);const q=l==="edit",[U,z]=A(!1),[W,V]=A(!1),[ae,pe]=A(null),[xe,ie]=A(!1),[me,we]=A(!1),[Te,Ne]=A(null),[_e,Z]=A(null),[he,te]=A(0),{interactiveServerUrl:se,isStarting:ce,isLoading:je,showIframe:ge,iframeKey:ze,onIframeLoad:Ve}=In({analysisId:h==null?void 0:h.id,scenarioId:E==null?void 0:E.id,scenarioName:E==null?void 0:E.name,projectSlug:m,enabled:q&&!!E,refreshTrigger:he}),[it,Le]=A(!1),[lt,Xr]=A(""),[fn,At]=A(!1),[Fn,Dn]=A(Date.now()),[Rn,vt]=A(!1),[On,zt]=A(!1),wt=Ge(),Bt=Ge(),rt=Ge(),Fe=Rt(),qt=S.jobs.some(fe=>{var Me;return(c==null?void 0:c.sha)&&((Me=fe.entityShas)==null?void 0:Me.includes(c.sha))||fe.type==="analysis"&&fe.commitSha===(w==null?void 0:w.sha)&&fe.entityShas&&fe.entityShas.length===0}),Ln=P,yr=((os=c==null?void 0:c.metadata)==null?void 0:os.defaultWidth)||((kr=h==null?void 0:h.metadata)==null?void 0:kr.defaultWidth)||1440,ct=Math.round(yr*(900/1440));wt.state==="submitting"||wt.state,le(()=>{var fe;return!!((fe=E==null?void 0:E.metadata)!=null&&fe.interactiveExamplePath)},[E]);const{isCompleted:xr}=Jt(m,fn);ne(()=>{wt.state==="idle"&&wt.data&&(wt.data.success?setTimeout(()=>{Dn(Date.now()),Fe.revalidate(),At(!1)},1500):wt.data.error&&(At(!1),alert(`Recapture failed: ${wt.data.error}`)))},[wt.state,wt.data,Fe]),ne(()=>{fn&&xr&&setTimeout(()=>{Dn(Date.now()),Fe.revalidate(),At(!1)},1500)},[fn,xr,Fe]),ne(()=>{Bt.state==="idle"&&Bt.data&&(Bt.data.success?setTimeout(()=>{Dn(Date.now()),Fe.revalidate(),At(!1)},1500):Bt.data.error&&(At(!1),alert(`Recapture failed: ${Bt.data.error}`)))},[Bt.state,Bt.data,Fe]);const Aa=le(()=>{var tt;if(!c)return"";const fe=[];if(fe.push(`# Create a New Scenario for "${c.name}"`),fe.push(""),fe.push(`**Entity**: ${c.name}`),fe.push(`**Type**: ${c.entityType}`),c.filePath&&fe.push(`**File**: ${c.filePath}`),fe.push(""),j.length>0){fe.push("## Existing Scenarios");for(const We of j)fe.push(`- **${We.name}**${We.description?`: ${We.description}`:""}`);fe.push("")}const Me=(tt=h==null?void 0:h.metadata)==null?void 0:tt.executionFlows;if(Me&&Me.length>0){fe.push("## Execution Flows");const We=new Set(j.flatMap(He=>{var st;return((st=He.metadata)==null?void 0:st.coveredFlows)||[]})),Ke=Me.filter(He=>!We.has(He.id)),Pt=Me.filter(He=>We.has(He.id));if(Pt.length>0){fe.push(`### Covered (${Pt.length})`);for(const He of Pt)fe.push(`- ${He.name}${He.description?`: ${He.description}`:""}`);fe.push("")}if(Ke.length>0){fe.push(`### Uncovered (${Ke.length}) — gaps to consider`);for(const He of Ke)fe.push(`- ${He.name}${He.description?`: ${He.description}`:""}${He.impact==="high"?" **(high impact)**":""}`);fe.push("")}}return fe.push("## Your Task"),fe.push("Ask the user what scenario they would like to create. Offer two options:"),fe.push("1. **Describe a scenario** — the user tells you what they want and you create it"),fe.push("2. **Analyze gaps** — you review the existing scenarios and execution flows to suggest scenarios that would improve coverage"),fe.push(""),fe.push("Once you know what scenario to create, use the `codeyam editor register` CLI command to register it. Write the scenario JSON to `.codeyam/tmp/scenario.json` first, then run `codeyam editor register @.codeyam/tmp/scenario.json`."),fe.join(`
531
- `)},[c,j,h]),br=()=>{zt(!0)},vr=()=>{c&&(g&&x&&x!==c.sha?(F(`/entity/${x}/scenarios`),setTimeout(()=>{rt.submit({entitySha:x,filePath:c.filePath||""},{method:"post",action:"/api/analyze"})},100)):rt.submit({entitySha:c.sha,filePath:c.filePath||""},{method:"post",action:"/api/analyze"}))};ne(()=>{rt.state==="idle"&&rt.data&&(rt.data.success?Fe.revalidate():rt.data.error&&alert(`Analysis failed: ${rt.data.error}`))},[rt.state,rt.data,c==null?void 0:c.sha,Fe]),ne(()=>{const fe=setTimeout(()=>{Fe.revalidate()},500);return()=>clearTimeout(fe)},[]),ne(()=>{if(B||Ln){const fe=setInterval(()=>{Fe.revalidate()},3e3);return()=>clearInterval(fe)}},[B,Ln,Fe]);const Qe=(fe,Me)=>fe==="scenarios"?`/entity/${c==null?void 0:c.sha}/scenarios`:`/entity/${c==null?void 0:c.sha}/${fe}`,ut=(fe,Me)=>`/entity/${c==null?void 0:c.sha}/scenarios/${fe}/${Me}`,wr=fe=>{Q(fe),E!=null&&E.id&&(fe==="interactive"?F(`/entity/${c==null?void 0:c.sha}/scenarios/${E.id}/fullscreen`,{replace:!0}):F(ut(E.id,fe),{replace:!0}))},Pa=async fe=>{var Me,tt;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:fe,hasSelectedScenario:!!E,hasAnalysis:!!h}),!E||!h){const We="Error: No scenario or analysis available";console.error("[EntityDetail]",We),pe(We);return}z(!0),pe(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:fe,scenarioId:E.id,scenarioName:E.name,currentData:E.data});try{const We=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:fe,existingScenarios:h.scenarios,scenariosDataStructure:(Me=h.metadata)==null?void 0:Me.scenariosDataStructure,editingMockName:E.name,editingMockData:_e||((tt=E.metadata)==null?void 0:tt.data)})}),Ke=await We.json();if(!We.ok||!Ke.success)throw new Error(Ke.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",Ke.data),Z(Ke.data);const Pt=(h.scenarios||[]).map(at=>at.id===E.id?{...at,metadata:{...at.metadata,data:Ke.data}}:at),He=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:h,scenarios:Pt})}),st=await He.json();if(!He.ok||!st.success)throw console.error("[EntityDetail] Temp save failed:",st),new Error(st.error||"Failed to apply preview");if(pe("Generating preview. Capturing screenshot..."),se){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:se});const at=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:se,scenarioId:E.id,projectId:h.projectId,viewportWidth:1440})}),Xt=await at.json();!at.ok||!Xt.success?(console.error("[EntityDetail] Direct capture failed:",Xt),pe("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),pe('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const at=new FormData;at.append("analysisId",h.id||""),at.append("scenarioId",E.id||"");const Xt=await fetch("/api/recapture-scenario",{method:"POST",body:at}),Un=await Xt.json();!Xt.ok||!Un.success?(console.warn("[EntityDetail] Recapture failed:",Un.error),pe("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",Un.jobId),pe('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}te(at=>at+1),Fe.revalidate()}catch(We){console.error("Error applying changes:",We),pe(`Error: ${We instanceof Error?We.message:String(We)}`)}finally{z(!1)}},Ta=async(fe,Me)=>{var tt;if(!E||!h){pe("Error: No scenario or analysis available");return}V(!0),pe(null),console.log("[EntityDetail] Saving scenario to database",{description:fe,saveAsNew:Me});try{const We=_e||((tt=E.metadata)==null?void 0:tt.data);let Ke;if(Me){const st={...E,id:`${E.name}-${Date.now()}`,name:`${E.name} (Copy)`,metadata:{...E.metadata,data:We},description:fe||E.description};Ke=[...h.scenarios||[],st]}else Ke=(h.scenarios||[]).map(st=>st.id===E.id?{...st,metadata:{...st.metadata,data:We},description:fe||st.description}:st);const Pt=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:h,scenarios:Ke})}),He=await Pt.json();if(!Pt.ok||!He.success)throw new Error(He.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),pe(Me?"New scenario created successfully":"Scenario saved successfully"),Z(null),Fe.revalidate()}catch(We){console.error("Error saving scenario:",We),pe(`Error: ${We instanceof Error?We.message:String(We)}`)}finally{V(!1)}},Ma=()=>{E!=null&&E.id&&(c!=null&&c.sha)&&F(`/entity/${c.sha}/scenarios/${E.id}/dev`)},Qt=async()=>{var fe;if(!(E!=null&&E.id)){Ne("Cannot delete scenario without ID");return}ie(!0),Ne(null);try{const Me=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:E.id,screenshotPaths:((fe=E.metadata)==null?void 0:fe.screenshotPaths)||[]})}),tt=await Me.json();if(!Me.ok||!tt.success)throw new Error(tt.error||"Failed to delete scenario");F(`/entity/${c==null?void 0:c.sha}/scenarios`)}catch(Me){console.error("[EntityDetail] Error deleting scenario:",Me),Ne(Me instanceof Error?Me.message:"Failed to delete scenario"),we(!1)}finally{ie(!1)}},Zt=h&&c&&h.entitySha!==c.sha,zn=c?DS(c):!1;return n(Na,{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:$,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:j.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(fe=>n(ke,{to:Qe(fe.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${D===fe.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:D===fe.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:d("span",{className:"flex items-center gap-2",children:[fe.label,fe.count!==void 0&&fe.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${D===fe.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:fe.count})]})},fe.id))})]})}),(g||Zt&&!u||v&&zn)&&!P&&!qt&&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:Zt&&!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.":Zt?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),g&&x&&b?n(ke,{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:fe=>{fe.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:fe=>{fe.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:vr,disabled:rt.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:fe=>{rt.state==="idle"&&(fe.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:fe=>{rt.state==="idle"&&(fe.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),d("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[D==="scenarios"&&d(ve,{children:[q&&E?n(OS,{scenario:E,entitySha:(c==null?void 0:c.sha)||"",onApply:Pa,onSave:Ta,onEditMockData:Ma,onDelete:Qt,isApplying:U,isSaving:W,saveMessage:ae,showDeleteConfirm:me,onShowDeleteConfirm:we,isDeleting:xe,deleteError:Te}):n(RS,{scenarios:j,hiddenScenarios:_,analysis:h,selectedScenario:E,entitySha:(c==null?void 0:c.sha)||"",cacheBuster:Fn,activeTab:D,entityType:c==null?void 0:c.entityType,entity:c,queueState:S,processIsRunning:O,isEntityAnalyzing:P,areScenariosStale:R,viewMode:K,setViewMode:wr,isBreakdownView:i==="breakdown",onCreateScenario:br}),On?d("div",{className:"flex flex-col flex-1 min-h-0",children:[d("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:"Create New Scenario"}),n("button",{onClick:()=>zt(!1),className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors",children:"Close"})]}),n("div",{className:"flex-1 min-h-0",children:n(un,{prompt:Aa,height:"100%",hideHeader:!0})})]}):i==="breakdown"?n(zS,{analysis:h??null,entitySha:(c==null?void 0:c.sha)||"",onCreateScenario:br}):q&&E?n(Sa,{scenarioId:E.id||E.name,scenarioName:E.name,iframeUrl:se,isStarting:ce,isLoading:je,showIframe:ge,iframeKey:ze,onIframeLoad:Ve,projectSlug:m,defaultWidth:1440,defaultHeight:900}):d("div",{className:"flex flex-col flex-1 min-h-0",children:[E&&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:E.name}),d("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[yr," × ",ct]})]}),d("div",{className:"flex items-center gap-2",children:[n(ke,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${E.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(ke,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${E.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(ke,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${E.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(np,{selectedScenario:E,analysis:h,entity:c,viewMode:K,cacheBuster:Fn,hasScenarios:j.length>0,isAnalyzing:Ln,projectSlug:m,hasAnApiKey:C,processIsRunning:O,queueState:S})]})]}),D==="related"&&n(WS,{relatedEntities:f}),D==="data"&&n(VS,{entity:c,analysis:h,scenarios:j,onAnalyze:vr}),D==="code"&&n(ZS,{entity:c,entityCode:y}),D==="history"&&n(BS,{entity:c,history:N})]}),Rn&&m&&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:fe=>fe.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(on,{projectSlug:m,onClose:()=>vt(!1)})})]})})]})})}),rC=Object.freeze(Object.defineProperty({__proto__:null,default:nC,loader:tC,meta:XS,shouldRevalidate:eC},Symbol.toStringTag,{value:"Module"}));async function sC(e){const{entityShas:t,filePaths:r,context:s,scenarioCount:a,queue:o}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await Je();const i=Ce();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=ee.join(i,".codeyam","config.json"),c=JSON.parse(await Pe.readFile(l,"utf8")),{projectSlug:p,branchId:u}=c;if(!p||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${p}, Branch: ${u}`);const h=Gr(p);try{await Pe.writeFile(h,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:m,branch:f}=await Re(p);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const y=await Xe({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(v=>v.filePath).filter(v=>!!v))],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 vg(m,f,g);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await an({commitSha:x.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:v=>{if(!v)return;const N=v.currentRun;if(N&&N.id&&N.archivedAt)return;N&&(N.analysesCompleted&&N.analysesCompleted>0||N.capturesCompleted&&N.capturesCompleted>0)&&$g(v)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:b}=o.enqueue({type:"analysis",commitSha:x.sha,projectSlug:p,filePaths:g,entityShas:t,entityNames:y.map(v=>v.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 aC({request:e,context:t}){if(e.method!=="POST")return re({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Kt()),!r)return re({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("entitySha"),o=s.get("entityShas"),i=s.get("filePath"),l=s.get("context"),c=s.get("scenarioCount");let p;if(o)p=o.split(",").filter(Boolean);else if(a)p=[a];else return re({error:"Missing required field: entitySha or entityShas"},{status:400});if(p.length===0)return re({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${p.length} entity(ies)`);const u=await Xe({shas:p}),m=[...new Set(u.map(y=>y.filePath).filter(y=>!!y))].length,{jobId:f}=await sC({entityShas:p,filePaths:i?[i]:void 0,context:l||void 0,scenarioCount:c?parseInt(c,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),re({success:!0,message:`Analysis queued for ${p.length} entity(ies)`,entityCount:p.length,fileCount:m,jobId:f})}catch(s){return console.error("[API] Error starting analysis:",s),re({error:"Failed to start analysis",details:s.message},{status:500})}}const oC=Object.freeze(Object.defineProperty({__proto__:null,action:aC},Symbol.toStringTag,{value:"Module"}));function iC(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 rp(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 Nt(e,t=[],r=!1){var u,h;if(t.some(m=>{var f,y;return!!((f=m.entityShas)!=null&&f.includes(e.sha)||(y=m.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(m=>m.screenshotFinishedAt||m.finishedAt))||a.entitySha!==e.sha)return"not-analyzed";const i=a.createdAt?new Date(a.createdAt).getTime():0,l=(h=e.metadata)!=null&&h.editedAt?new Date(e.metadata.editedAt).getTime():0,c=a.scenarios||[],p=c.some(m=>{var f,y,g;return((y=(f=m.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||((g=m.metadata)==null?void 0:g.executionResult)});return i>=l?c.length>0&&p?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 lC=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function cC({request:e,context:t}){try{const r=t.analysisQueue,s=r?r.getState():{paused:!1,jobs:[]},a=await $n();return re({entities:a||[],queueState:s})}catch(r){return console.error("Failed to load simulations:",r),re({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const dC=et(function(){const t=ot(),r=t.entities,s=t.queueState;Ot({source:"simulations-page"});const[a,o]=A(""),[i,l]=A("visual"),c=le(()=>{const g=[];return r.forEach(x=>{var v;const b=(v=x.analyses)==null?void 0:v[0];if(b!=null&&b.scenarios){const N=b.scenarios.filter(w=>{var C;return!((C=w.metadata)!=null&&C.sameAsDefault)}).map(w=>{var M,$,O,D,T;const C=($=(M=w.metadata)==null?void 0:M.screenshotPaths)==null?void 0:$[0],S=(O=w.metadata)==null?void 0:O.noScreenshotSaved,k=C&&!S,j=(T=(D=b.status)==null?void 0:D.scenarios)==null?void 0:T.find(B=>B.name===w.name),_=j&&j.screenshotStartedAt&&!j.screenshotFinishedAt;let F;return k?F="completed":_?F="capturing":F="error",{scenarioName:w.name,scenarioDescription:w.description||"",screenshotPath:C||"",scenarioId:w.id,state:F}}).filter(w=>w.state==="completed"||w.state==="capturing");N.length>0&&g.push({entity:x,screenshots:N,createdAt:b.createdAt||""})}}),g.sort((x,b)=>new Date(b.createdAt).getTime()-new Date(x.createdAt).getTime()),g},[r]),p=le(()=>r.filter(g=>{var v,N;const x=(v=g.analyses)==null?void 0:v[0];return!((N=x==null?void 0:x.scenarios)==null?void 0:N.some(w=>{var C,S;return(S=(C=w.metadata)==null?void 0:C.screenshotPaths)==null?void 0:S[0]}))}),[r]),u=le(()=>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]),h=le(()=>p.filter(g=>{const x=!a||g.name.toLowerCase().includes(a.toLowerCase()),b=i==="all"||g.entityType===i;return x&&b}),[p,a,i]),m=oe(g=>{o(g.target.value)},[]),f=oe(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(kt,{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(Hr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-3 text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:a,onChange:m})]})]})]}),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(ve,{children:u.map(({entity:g,screenshots:x})=>n(uC,{entity:g,screenshots:x,queueJobs:(s==null?void 0:s.jobs)||[]},g.sha))})),!y&&(h.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No components found matching your filters."}):h.map(g=>n(pC,{entity:g},g.sha)))]})]})})});function uC({entity:e,screenshots:t,queueJobs:r}){var f,y,g;const s=Dt(),a=Ge(),[o,i]=A(!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`)},p=()=>{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=Nt(e,r),h=iC(u),m=u==="out-of-date";return n("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:d("div",{className:"flex flex-col",children:[d("div",{className:"flex items-center px-[15px] py-[15px]",children:[n("div",{className:"flex-shrink-0",children:n(gt,{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(ke,{to:`/entity/${e.sha}`,className:"hover:underline cursor-pointer",title:e.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:[e.name," (",l,")"]}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:h.bgColor,color:h.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:h.text})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),d("div",{className:"flex-shrink-0 flex items-center gap-2",children:[m&&n(ve,{children:o||a.state!=="idle"?d("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[n($t,{size:14,className:"animate-spin",style:{color:"#be185d"}}),n("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):n("button",{onClick:p,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#005c75",color:"#ffffff",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#004d5e"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#005c75"},children:"Re-analyze"})}),n("button",{onClick:()=>void s(`/entity/${e.sha}/logs`),className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})]})]}),n("div",{className:"border-t border-gray-200"}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:t.length>0?t.map(x=>d("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>c(x.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:x.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:x.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:b=>{x.state==="completed"&&(b.currentTarget.style.borderColor="#005C75",b.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:b=>{b.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",b.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(dt,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(Ii,{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(ve,{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 pC({entity:e}){const t=Ge(),[r,s]=A(!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(gt,{type:e.entityType}),d("div",{className:"min-w-0",children:[d("div",{className:"flex items-center gap-3 mb-0.5",children:[n(ke,{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:rp(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($t,{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 hC=Object.freeze(Object.defineProperty({__proto__:null,default:dC,loader:cC,meta:lC},Symbol.toStringTag,{value:"Module"}));function mC({request:e,context:t}){const r=t.dbNotifier||ft;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"})}
532
-
533
- `)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",c),clearInterval(p);try{a.close()}catch{}}},c=u=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
534
-
535
- `))}catch{l()}};r.on("change",c);const p=setInterval(()=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
536
-
537
- `))}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 fC=Object.freeze(Object.defineProperty({__proto__:null,loader:mC},Symbol.toStringTag,{value:"Module"}));function gC(){return new Response(JSON.stringify({status:"ok",version:ri,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const yC=Object.freeze(Object.defineProperty({__proto__:null,loader:gC},Symbol.toStringTag,{value:"Module"}));function Ri(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(`
538
- `).filter(p=>p.trim().startsWith("-")).map(p=>p.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean):l&&(o.paths=l[1].split(",").map(p=>p.replace(/['"]/g,"").trim()).filter(Boolean));const c=s.match(/^category:\s*(.+)$/m);return c&&(o.category=c[1].replace(/['"]/g,"").trim()),{frontmatter:o,body:a}}async function Ea(e,t=""){const r=[];try{const s=await Pe.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){const i=await Ea(ee.join(e,a.name),o);r.push(...i)}else a.isFile()&&a.name.endsWith(".md")&&r.push(o)}}catch{}return r}async function Zr(e){const t=await Ea(e),r=[];for(const s of t){const a=ee.join(e,s);try{const o=await Pe.readFile(a,"utf-8"),{frontmatter:i,body:l}=Ri(o);r.push({filePath:s,absolutePath:a,frontmatter:i,body:l})}catch{}}return r}function sp(e){const t=ee.posix.dirname(e.filePath);return!t||t==="."?null:`${t}/**`}function ap(e,t){if(t.frontmatter.paths&&t.frontmatter.paths.length>0)return t.frontmatter.paths.some(s=>wo(e,s,{matchBase:!0}));const r=sp(t);return r?wo(e,r,{matchBase:!0}):!1}function xC(e,t){return(!e.frontmatter.paths||e.frontmatter.paths.length===0)&&!sp(e)?[]:t.filter(r=>ap(r,e))}const bC=new Set(["node_modules",".git","dist",".codeyam",".claude","build","coverage"]);async function Oi(e){const t=[];async function r(s,a){try{const o=await Ae.readdir(s,{withFileTypes:!0});for(const i of o){const l=H.join(s,i.name),c=a?`${a}/${i.name}`:i.name;i.isDirectory()&&bC.has(i.name)||(i.isDirectory()?await r(l,c):i.isFile()&&t.push(c))}}catch{}}return await r(e,""),t}const vC="codeyam-rule-state.json",po=1;function op(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return cr.createHash("sha256").update(t).digest("hex")}function ip(e){return ee.join(e,".claude",vC)}async function lp(e){const t=ip(e);try{const r=await Pe.readFile(t,"utf-8"),s=JSON.parse(r);return s.version!==po?(console.warn(`[ruleState] Unknown version ${s.version}, using empty state`),{version:po,rules:{}}):s}catch{return{version:po,rules:{}}}}async function cp(e,t){const r=ip(e),s=ee.dirname(r);await Pe.mkdir(s,{recursive:!0}),await Pe.writeFile(r,JSON.stringify(t,null,2)+`
539
- `,"utf-8")}async function Li(e,t){const r=await lp(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 Pe.readFile(a.absolutePath,"utf-8"),i=op(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 cp(e,r),r}async function kc(e,t,r,s){const a=await lp(e);if(r){const o=ee.join(e,".claude","rules"),i=ee.join(o,t),l=await Pe.readFile(i,"utf-8"),c=op(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 cp(e,a)}function zi(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function dp(e,t=""){const r=[],s=await Pe.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;a.isDirectory()?r.push(...await dp(ee.join(e,a.name),o)):a.name.endsWith(".md")&&r.push(o)}return r}function Ks(e){if(!e||e==="(diff not available)")return!1;const t=e.split(`
540
- `).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 wC({request:e}){const t=Ce();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=new URL(e.url),s=r.searchParams.get("action"),a=ee.join(t,".claude","rules");if(s==="recent-changes")return SC(t,a);if(s==="reviewed-status")return kC(t,a);if(s==="audit")return _C(t,a);if(s==="source-files")return EC(t);if(s==="rule-coverage")return jC(t,a);if(s==="rule-diff"){const o=r.searchParams.get("filePath");return o?CC(t,o):Response.json({error:"Missing required parameter: filePath"},{status:400})}if(s==="rules-for-path"){const o=r.searchParams.get("path");return o?AC(a,o):Response.json({error:"Missing required parameter: path"},{status:400})}try{const o=await Ea(a),i=[];for(const u of o){const h=ee.join(a,u);try{const m=await Pe.readFile(h,"utf-8"),f=await Pe.stat(h),{frontmatter:y,body:g}=Ri(m);i.push({filePath:u,content:m,frontmatter:y,body:g,lastModified:f.mtime.toISOString()})}catch{}}i.sort((u,h)=>new Date(h.lastModified).getTime()-new Date(u.lastModified).getTime());let l=i.length>0;if(!l)try{await Pe.access(ee.join(t,".claude","codeyam-rule-state.json")),l=!0}catch{}const c=await Zr(a),p={};if(c.length>0){const u=await Li(t,c);for(const h of c)p[h.filePath]=zi(u,h.filePath)}return Response.json({memories:i,memoryInitialized:l,reviewedStatus:p})}catch(o){return console.error("[API] Error loading memories:",o),Response.json({error:"Failed to load memories",details:o instanceof Error?o.message:String(o),memoryInitialized:!1},{status:500})}}async function NC(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(`
541
- `).filter(Boolean)){const o=a.substring(0,2);let i=a.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const l=o[0],c=o[1];let p=[i];if(i.endsWith("/")&&l==="?"){const u=ee.join(e,i);try{p=(await dp(u)).map(m=>i+m)}catch{continue}}for(const u of p){if(u.endsWith("/"))continue;const h=u.replace(".claude/rules/","");let m="modified";l==="A"||l==="?"?m="added":l==="D"||c==="D"?m="deleted":(l==="M"||c==="M")&&(m="modified");let f="";try{if(m==="deleted")f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(m==="added"&&l==="?"){const y=`${e}/${u}`;try{const g=await Pe.readFile(y,"utf-8");f=`diff --git a/${u} b/${u}
542
- new file mode 100644
543
- --- /dev/null
544
- +++ b/${u}
545
- @@ -0,0 +1,${g.split(`
546
- `).length} @@
547
- ${g.split(`
548
- `).map(x=>"+"+x).join(`
549
- `)}`}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)+`
550
- ... (truncated)`)}catch{f="(diff not available)"}m==="modified"&&Ks(f)||r.push({filePath:h,changeType:m,diff:f})}}}catch{}return r}async function SC(e,t){try{const{execSync:r}=await import("child_process"),s=[],a=await Zr(t),o={};if(a.length>0){const u=await Li(e,a);for(const h of a)o[h.filePath]=zi(u,h.filePath)}const l=(await NC(e,r)).filter(u=>!o[u.filePath]);l.length>0&&s.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:l});const p=r('git log --format="%H|%aI|%s" --since="60 days ago" -- .claude/rules/ 2>/dev/null || true',{cwd:e,encoding:"utf-8",maxBuffer:10*1024*1024}).split(`
551
- `).filter(Boolean).slice(0,20);for(const u of p){const[h,m,...f]=u.split("|"),y=f.join("|");if(!h||!m)continue;const g=r(`git diff-tree --no-commit-id --name-status -r ${h} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),x=[];for(const b of g.split(`
552
- `).filter(Boolean)){const[v,N]=b.split(" ");if(!N||!N.startsWith(".claude/rules/"))continue;const w=N.replace(".claude/rules/","");let C="modified";if(v==="A"?C="added":v==="D"&&(C="deleted"),o[w])continue;let S="";try{S=r(`git show ${h} --format="" -- "${N}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),S.length>5e3&&(S=S.substring(0,5e3)+`
553
- ... (truncated)`)}catch{S="(diff not available)"}C==="modified"&&Ks(S)||x.push({filePath:w,changeType:C,diff:S})}x.length>0&&s.push({commitHash:h.substring(0,8),date:m,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 CC(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(Ks(i))return Response.json({diff:null});const g=i.length>5e3?i.substring(0,5e3)+`
554
- ... (truncated)`:i;return Response.json({diff:{diff:g,commitMessage:"Uncommitted changes",date:new Date().toISOString(),isUncommitted:!0,commitCount:o}})}if(r(`git status --porcelain -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim().startsWith("?")){const g=ee.join(e,s);try{const x=await Pe.readFile(g,"utf-8"),b=`diff --git a/${s} b/${s}
555
- new file mode 100644
556
- --- /dev/null
557
- +++ b/${s}
558
- @@ -0,0 +1,${x.split(`
559
- `).length} @@
560
- ${x.split(`
561
- `).map(v=>"+"+v).join(`
562
- `)}`;return Response.json({diff:{diff:b.length>5e3?b.substring(0,5e3)+`
563
- ... (truncated)`:b,commitMessage:"New file (untracked)",date:new Date().toISOString(),isUncommitted:!0,commitCount:0}})}catch{}}const p=r(`git log -1 --format="%H|%aI|%s" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim();if(!p)return Response.json({diff:null});const[u,h,...m]=p.split("|"),f=m.join("|");if(!u||!h)return Response.json({diff:null});let y=r(`git show ${u} --format="" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});return y.trim()?Ks(y)?Response.json({diff:null}):(y.length>5e3&&(y=y.substring(0,5e3)+`
564
- ... (truncated)`),Response.json({diff:{diff:y,commitMessage:f,date:h,isUncommitted:!1,commitCount:o}})):Response.json({diff:null})}catch(r){return console.error("[API] Error getting rule diff:",r),Response.json({diff:null})}}async function kC(e,t){try{const r=await Zr(t),s={};if(r.length>0){const a=await Li(e,r);for(const o of r)s[o.filePath]=zi(a,o.filePath)}return Response.json({reviewedStatus:s})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function _C(e,t){try{const r=await Zr(t),s=await Oi(e),a=[];for(const o of s){const i=r.filter(l=>ap(o,l));if(i.length>0){const l=i.reduce((c,p)=>c+p.body.length,0);a.push({filePath:o,matchingRules:i.map(c=>({filePath:c.filePath,patterns:c.frontmatter.paths||[],bodyLength:c.body.length})),totalTextLength:l})}}return a.sort((o,i)=>i.totalTextLength-o.totalTextLength),Response.json({topPaths:a,totalFilesWithCoverage:a.length,allSourceFiles:s})}catch(r){return console.error("[API] Error getting audit data:",r),Response.json({error:"Failed to get audit data",details:r instanceof Error?r.message:String(r)},{status:500})}}async function EC(e){try{const t=await Oi(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 jC(e,t){try{const[r,s]=await Promise.all([Zr(t),Oi(e)]),a={};for(const o of r)a[o.filePath]=xC(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 AC(e,t){try{const r=await Ea(e),s=[];for(const o of r){const i=ee.join(e,o);try{const l=await Pe.readFile(i,"utf-8"),c=await Pe.stat(i),{frontmatter:p,body:u}=Ri(l);p.paths&&p.paths.some(h=>wo(t,h,{matchBase:!0}))&&s.push({filePath:o,content:l,frontmatter:p,body:u,lastModified:c.mtime.toISOString()})}catch{}}const a=s.reduce((o,i)=>o+i.body.length,0);return Response.json({rules:s,totalTextLength:a})}catch(r){return console.error("[API] Error getting rules for path:",r),Response.json({error:"Failed to get rules for path",details:r instanceof Error?r.message:String(r)},{status:500})}}async function PC({request:e}){const t=Ce();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=ee.join(t,".claude","rules");try{const s=await e.json(),{action:a,filePath:o,content:i,lastModified:l}=s;if(!o)return Response.json({error:"Missing required field: filePath"},{status:400});if(a==="mark-reviewed")return await kc(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 kc(t,o,!1),console.log(`[API] Rule marked as unreviewed: ${o}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:o});const c=ee.normalize(o);if(c.includes("..")||ee.isAbsolute(c))return Response.json({error:"Invalid file path"},{status:400});const p=ee.join(r,c);switch(a){case"create":case"update":return i?(await Pe.mkdir(ee.dirname(p),{recursive:!0}),await Pe.writeFile(p,i,"utf-8"),console.log(`[API] Memory ${a}d: ${o}`),Response.json({success:!0,message:`Memory ${a}d successfully`,filePath:o})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await Pe.unlink(p),console.log(`[API] Memory deleted: ${o}`);const u=ee.dirname(p);try{(await Pe.readdir(u)).length===0&&u!==r&&await Pe.rmdir(u)}catch{}return Response.json({success:!0,message:"Memory deleted successfully"})}catch(u){if(u.code==="ENOENT")return Response.json({error:"Memory not found"},{status:404});throw u}default:return Response.json({error:"Invalid action. Must be create, update, or delete"},{status:400})}}catch(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 TC=Object.freeze(Object.defineProperty({__proto__:null,action:PC,loader:wC},Symbol.toStringTag,{value:"Module"}));async function MC({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await Kt()),!r)return re({error:"Queue not initialized"},{status:500});const s=new URL(e.url),a=s.searchParams.get("queryType");if(!a)return re({error:"Missing queryType parameter for GET request"},{status:400});if(a==="job"){const i=s.searchParams.get("jobId");if(!i)return re({error:"Missing jobId parameter for job query"},{status:400});const l=r.getState();if(((o=l.currentlyExecuting)==null?void 0:o.id)===i)return re({jobId:i,status:"running",job:l.currentlyExecuting});const c=l.jobs.find(u=>u.id===i);if(c){const u=l.jobs.indexOf(c);return re({jobId:i,status:"queued",position:u,job:c})}const p=r.getJobResult(i);return p?re({jobId:i,status:p.status==="error"?"failed":"completed",error:p.error}):re({jobId:i,status:"completed"})}if(a==="full"){const i=r.getState(),l=await Promise.all(i.jobs.map(async p=>{const u=[];if(p.entityShas&&p.entityShas.length>0){const h=p.entityShas.map(f=>Pn(f)),m=await Promise.all(h);u.push(...m.filter(f=>f!==null))}return{id:p.id,type:p.type,commitSha:p.commitSha,projectSlug:p.projectSlug,queuedAt:p.queuedAt,entities:u,filePaths:p.filePaths}}));let c;if(i.currentlyExecuting){const p=i.currentlyExecuting,u=[];if(p.entityShas&&p.entityShas.length>0){const h=p.entityShas.map(f=>Pn(f)),m=await Promise.all(h);u.push(...m.filter(f=>f!==null))}c={id:p.id,type:p.type,commitSha:p.commitSha,projectSlug:p.projectSlug,queuedAt:p.queuedAt,entities:u,filePaths:p.filePaths}}return re({state:{...i,jobsWithEntities:l,currentlyExecutingWithEntities:c}})}return re({error:"Unknown queryType"},{status:400})}async function $C({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 Kt(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),re({error:"Queue not initialized"},{status:500});const s=await e.json(),{action:a,...o}=s;if(console.log("[Queue API] Action:",a,"Params:",Object.keys(o)),a==="enqueue"){const{jobId:i,completion:l}=r.enqueue(o);return l.catch(c=>{console.error(`[Queue API] Job ${i} failed:`,c)}),re({jobId:i,status:"queued"})}if(a==="resume")return r.resume(),re({status:"resumed"});if(a==="pause")return r.pause(),re({status:"paused"});if(a==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?re({status:"removed",jobId:i}):re({error:"Job not found in queue"},{status:404}):re({error:"Missing jobId parameter"},{status:400})}if(a==="clear"){const i=r.clearQueue();return re({status:"cleared",count:i})}if(a==="reorder"){const{jobId:i,direction:l}=o;return!i||!l?re({error:"Missing jobId or direction parameter"},{status:400}):l!=="up"&&l!=="down"?re({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,l)?re({status:"reordered",jobId:i,direction:l}):re({error:"Could not reorder job (not found or at boundary)"},{status:400})}return re({error:"Unknown action"},{status:400})}const IC=Object.freeze(Object.defineProperty({__proto__:null,action:$C,loader:MC},Symbol.toStringTag,{value:"Module"})),FC=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],DC=et(function(){return Ge(),n(Na,{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(np,{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})]})]})})}),RC=Object.freeze(Object.defineProperty({__proto__:null,default:DC,meta:FC},Symbol.toStringTag,{value:"Module"})),OC=()=>[{title:"Settings - CodeYam"},{name:"description",content:"Configure project settings"}];async function LC({request:e}){var t,r;try{const s=await ia();if(!s)return re({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Project configuration not found"});let a=!1;try{const c=await Ye();if(c){const{project:p}=await Re(c);a=((r=(t=p.metadata)==null?void 0:t.labs)==null?void 0:r.simulations)===!0}}catch{}const o=Ce()||process.cwd(),i=await la(o),l=Bd(s.projectSlug);return re({config:s,secrets:{GROQ_API_KEY:i.GROQ_API_KEY||"",ANTHROPIC_API_KEY:i.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:i.OPENAI_API_KEY||""},versionInfo:l,simulationsEnabled:a,error:null})}catch(s){return console.error("Failed to load config:",s),re({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Failed to load configuration"})}}function zC(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 BC({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),s=t.get("startCommands"),a=t.get("groqApiKey"),o=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),l=t.get("pathsToIgnore"),c=t.get("memorySettings");let p;if(r)try{p=JSON.parse(r)}catch{return re({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let u;if(s)try{u=JSON.parse(s)}catch{return re({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let h;l&&(h=l.split(",").map(x=>x.trim()).map(x=>x.startsWith('"')&&x.endsWith('"')||x.startsWith("'")&&x.endsWith("'")?x.slice(1,-1):x).filter(x=>x.length>0));let m;if(c)try{m=JSON.parse(c)}catch{return re({success:!1,error:"Invalid memorySettings JSON format",requiresRestart:!1},{status:400})}let f;if(u){const x=await ia();x!=null&&x.webapps&&(f=x.webapps.map((b,v)=>{if(u[v]!==void 0){const N=zC(u[v]);return{...b,startCommand:N}}return b}))}if(!await $d({universalMocks:p,pathsToIgnore:h,webapps:f,memory:m}))return re({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=Ce()||process.cwd(),b=await la(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 Cg(x,{...b,GROQ_API_KEY:a||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return re({success:!0,error:null,requiresRestart:g})}catch(t){return console.log("[Settings Action] Failed to save config:",t),re({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function _c(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Ec({mock:e,onSave:t,onCancel:r}){const[s,a]=A(e.entityName),[o,i]=A(e.filePath),[l,c]=A(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 YC(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const WC=et(function(){var Te,Ne,_e,Z,he;const{config:t,secrets:r,versionInfo:s,simulationsEnabled:a,error:o}=ot(),i=lh(),l=Ge(),c=Rt(),[p,u]=A(a?"project-metadata":"memory");Ot({source:"settings-page"});const[h,m]=A((t==null?void 0:t.universalMocks)||[]),[f,y]=A(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,x]=A(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[b,v]=A((r==null?void 0:r.GROQ_API_KEY)||""),[N,w]=A((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[C,S]=A((r==null?void 0:r.OPENAI_API_KEY)||""),[k,j]=A(!1),[_,F]=A(!1),[M,$]=A(!1),[O,D]=A(!1),[T,B]=A(!1),[Y,I]=A(!1),[L,P]=A(null),[R,E]=A(!1),[J,K]=A({}),[Q,q]=A(((Te=t==null?void 0:t.memory)==null?void 0:Te.conversationReflection)??!0),[U,z]=A(((Ne=t==null?void 0:t.memory)==null?void 0:Ne.ruleMaintenance)??!0),[W,V]=A(((_e=t==null?void 0:t.memory)==null?void 0:_e.promptModel)??"haiku");ne(()=>{var te,se,ce,je;if(t){m(t.universalMocks||[]);const ge=(t.pathsToIgnore||[]).join(", ");y(ge),x(ge);const ze={};(te=t.webapps)==null||te.forEach((Ve,it)=>{Ve.startCommand&&(ze[it]=_c(Ve.startCommand))}),K(ze),q(((se=t.memory)==null?void 0:se.conversationReflection)??!0),z(((ce=t.memory)==null?void 0:ce.ruleMaintenance)??!0),V(((je=t.memory)==null?void 0:je.promptModel)??"haiku")}r&&(v(r.GROQ_API_KEY||""),w(r.ANTHROPIC_API_KEY||""),S(r.OPENAI_API_KEY||""))},[t,r]),ne(()=>{if(i!=null&&i.success){D(!0);const te=setTimeout(()=>D(!1),3e3);return()=>clearTimeout(te)}},[i]),ne(()=>{if(l.state==="idle"&&l.data&&!Y){console.log("[Settings] Fetcher data:",l.data);const te=l.data;if(te.success){console.log("[Settings] Save successful, revalidating..."),D(!0),I(!0),(f!==g||te.requiresRestart)&&B(!0),c.revalidate();const se=setTimeout(()=>{D(!1),I(!1)},3e3);return()=>clearTimeout(se)}}},[l.state,l.data,Y,c,f,g]);const ae=te=>{te.preventDefault();const se=new FormData(te.currentTarget);se.set("universalMocks",JSON.stringify(h)),se.set("startCommands",JSON.stringify(J)),se.set("memorySettings",JSON.stringify({conversationReflection:Q,ruleMaintenance:U,promptModel:W})),console.log("[Settings] Submitting form data:",{universalMocks:se.get("universalMocks"),startCommands:se.get("startCommands"),openAiApiKey:se.get("openAiApiKey")?"***":"(empty)"}),l.submit(se,{method:"post"})},pe=te=>{m([...h,te]),E(!1)},xe=(te,se)=>{const ce=[...h];ce[te]=se,m(ce),P(null)},ie=te=>{m(h.filter((se,ce)=>ce!==te))};if(o)return d("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:o})})]});const me=[{id:"project-metadata",label:"Project Metadata"},{id:"ai-provider",label:"AI Provider Configuration"},{id:"commands",label:"Commands"},{id:"paths-to-ignore",label:"Paths To Ignore"},{id:"universal-mocks",label:"Universal Mocks"},{id:"memory",label:"Memory"},{id:"current-configuration",label:"Current Configuration"}],we=a?me:me.filter(te=>te.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"})]}),(O||T||(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:[O&&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!"}),T&&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(pt,{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 te=l.data;return typeof te.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:te.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:we.map(te=>n("li",{children:n("button",{type:"button",onClick:()=>u(te.id),className:`w-full text-left px-3 lg:px-0 py-2.5 text-sm transition-colors cursor-pointer whitespace-nowrap ${p===te.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:te.label})},te.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:d("form",{id:"settings-form",onSubmit:ae,className:"space-y-6",children:[p==="project-metadata"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),d("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((te,se)=>{var ce;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:te.path==="."?"Root":te.path})]}),te.appDirectory&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:te.appDirectory})]}),d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:te.framework})]}),te.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:[te.startCommand.command," ",(ce=te.startCommand.args)==null?void 0:ce.join(" ")]})]})]})},se)})}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"}),n("p",{className:"mt-2 text-sm text-gray-600",children:"Web applications are detected during initialization. To modify, edit `.codeyam/config.json` or re-run `codeyam init`."})]})]}),p==="ai-provider"&&d("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),d("div",{className:"space-y-6",children:[d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),d("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:k?"text":"password",id:"groqApiKey",name:"groqApiKey",value:b,onChange:te=>v(te.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:()=>j(!k),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:k?"Hide":"Show"})]})]})]}),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:N,onChange:te=>w(te.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:()=>F(!_),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:M?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:C,onChange:te=>S(te.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:()=>$(!M),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:M?"Hide":"Show"})]})]})]})]})]}),p==="commands"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((te,se)=>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:te.path==="."?"Root":te.path}),n("div",{className:"text-sm text-gray-600",children:te.framework})]}),d("div",{children:[n("label",{htmlFor:`startCommand-${se}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${se}`,name:`startCommand-${se}`,value:J[se]||"",onChange:ce=>K({...J,[se]:ce.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"})]})]},se))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),p==="paths-to-ignore"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:f,onChange:te=>y(te.target.value),placeholder:"e.g., __tests__, \\.test\\.ts$, ^background (no quotes needed)",className:"w-full px-3 py-3 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-2 focus:ring-[#005C75]/10"}),d("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),p==="universal-mocks"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),h.length===0?d("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>E(!0),className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}):n("div",{className:"space-y-3",children:h.map((te,se)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:L===se?n(Ec,{mock:te,onSave:ce=>xe(se,ce),onCancel:()=>P(null)}):n(ve,{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:te.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:te.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:te.content})]}),d("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>P(se),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:()=>ie(se),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},se))}),h.length>0&&n("button",{type:"button",onClick:()=>E(!0),className:"mt-4 px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}),p==="memory"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Memory"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure how CodeYam reflects on conversations and maintains rules between sessions."}),d("div",{className:"space-y-6",children:[n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Conversation Reflection"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent reviews the session for architectural decisions, tribal knowledge, confusion, or corrections that future sessions would benefit from knowing. It creates or updates Claude Rules based on what it learns."})]}),n("button",{type:"button",role:"switch","aria-checked":Q,onClick:()=>q(!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":U,onClick:()=>z(!U),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 ${U?"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 ${U?"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(te=>d("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${W===te.value?"border-[#005C75] bg-[#005C75]/5":"border-gray-200 hover:border-gray-300"}`,children:[n("input",{type:"radio",name:"promptModel",value:te.value,checked:W===te.value,onChange:()=>V(te.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:te.label}),te.badge&&n("span",{className:"px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:te.badge})]}),n("p",{className:"text-sm text-gray-600 mt-0.5",children:te.description})]})]},te.value))})]})]})]}),p==="current-configuration"&&d("div",{className:"space-y-6",children:[t&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:d("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&d("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((te,se)=>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:te.path==="."?"Root":te.path})]}),te.appDirectory&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:te.appDirectory})]}),d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:te.framework})]}),te.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:_c(te.startCommand)})]})]})},se))})]})]}),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||((Z=s.templateVersion.gitCommit)==null?void 0:Z.slice(0,7))||"unknown"}),s.templateVersion.buildTimestamp&&d("span",{className:"text-gray-500 ml-2",children:["(built"," ",YC(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||((he=s.cachedAnalyzerVersion.gitCommit)==null?void 0:he.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"})]})]})})]})]})]})})]}),R&&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(Ec,{mock:{entityName:"",filePath:"",content:""},onSave:pe,onCancel:()=>E(!1)})]})})]})})}),UC=Object.freeze(Object.defineProperty({__proto__:null,action:BC,default:WC,loader:LC,meta:OC},Symbol.toStringTag,{value:"Module"}));async function JC({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=Ce();if(!r)return new Response("Project root not found",{status:500});const a=ee.extname(t)!==""?t:`${t}.html`,o=ee.join(r,".codeyam","captures","static",a);try{await Pe.access(o);let i=await Pe.readFile(o);const l=ee.extname(o).toLowerCase();let c="application/octet-stream";if(l===".html"){c="text/html";let p=i.toString("utf-8");const u=p.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const m=u[1].match(/=\s*(\{[\s\S]*\})/);if(m){const f=JSON.parse(m[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const y=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;p=p.replace(u[0],y)}}catch(h){console.error("[Static] Failed to parse Remix context:",h)}i=Buffer.from(p,"utf-8")}else l===".js"||l===".mjs"?c="application/javascript":l===".css"?c="text/css":l===".json"?c="application/json":l===".png"?c="image/png":l===".jpg"||l===".jpeg"?c="image/jpeg":l===".svg"?c="image/svg+xml":l===".woff"?c="font/woff":l===".woff2"?c="font/woff2":l===".ttf"&&(c="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":c,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const HC=Object.freeze(Object.defineProperty({__proto__:null,loader:JC},Symbol.toStringTag,{value:"Module"}));function VC(e,t,r=10){var c;const s=new Map,a=p=>p.entityType==="visual"||p.entityType==="library";for(const p of e)a(p)&&s.set(p.sha,{entity:p,depth:0});const o=new Map;for(const p of t){const u=(c=p.metadata)==null?void 0:c.importedBy;if(u)for(const h of Object.keys(u))for(const m of Object.keys(u[h])){const{shas:f}=u[h][m];for(const y of f)o.has(p.sha)||o.set(p.sha,new Set),o.get(p.sha).add(y)}}const i=[],l=new Set;for(const p of e)i.push({sha:p.sha,depth:0}),l.add(p.sha);for(;i.length>0;){const{sha:p,depth:u}=i.shift();if(u>=r)continue;const h=o.get(p);if(h)for(const m of h){if(l.has(m))continue;l.add(m);const f=t.find(y=>y.sha===m);if(f){if(a(f)){const y=u+1,g=s.get(m);(!g||y<g.depth)&&s.set(m,{entity:f,depth:y})}i.push({sha:m,depth:u+1})}}}return Array.from(s.values()).sort((p,u)=>p.depth!==u.depth?p.depth-u.depth:p.entity.name.localeCompare(u.entity.name))}function Gs(e){const t=new Map;for(const s of e)t.has(s.name)||t.set(s.name,[]),t.get(s.name).push(s);const r=[];for(const s of t.values())if(s.length===1)r.push(s[0]);else{const a=s.sort((o,i)=>{var p,u;const l=((p=o.metadata)==null?void 0:p.editedAt)||o.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(l)});r.push(a[0])}return r}function up(e,t){const r=new Map,s=new Set(e.map(a=>a.path));for(const a of e)a.status==="renamed"&&a.oldPath&&s.add(a.oldPath);for(const a of e){const o=t.filter(c=>c.filePath===a.path||a.status==="renamed"&&a.oldPath&&c.filePath===a.oldPath),i=o.filter(c=>{var p,u;return s.has(c.filePath)&&((p=c.metadata)==null?void 0:p.isUncommitted)&&!((u=c.metadata)!=null&&u.isSuperseded)}),l=Gs(i);r.set(a.path,{status:a,entities:o,editedEntities:l})}return r}function KC(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=Gs(i);s.set(o.path,{status:o,entities:l})}return s}const a=new Map;for(const o of r.fileComparisons){const i=new Set;for(const l of o.newEntities)i.add(l.name);for(const l of o.modifiedEntities)i.add(l.name);for(const l of o.deletedEntities)i.add(l.name);i.size>0&&a.set(o.filePath,i)}for(const o of e){const i=a.get(o.path);if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const l=i?t.filter(p=>(p.filePath===o.path||o.status==="renamed"&&o.oldPath&&p.filePath===o.oldPath)&&i.has(p.name)):[],c=Gs(l);s.set(o.path,{status:o,entities:c})}}return s}function GC(e,t){const r=new Map,s=pp(e,t);for(const a of s){const i=VC([a],t).filter(({depth:l})=>l>0);r.set(a.sha,i)}return r}function pp(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 Gs(s)}function qC({recentSimulations:e}){const t=le(()=>{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(ve,{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(Lr,{size:16,style:{color:"#8B5CF6"}})}),n(ke,{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(ke,{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(dt,{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(ke,{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(Lr,{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(ke,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(ke,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const QC="/assets/codeyam-name-logo-CvKwUgHo.svg",ZC=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function XC({request:e,context:t}){var r,s,a,o,i;try{const l=await Ye();if(l){const{project:O}=await Re(l),D=((r=O.metadata)==null?void 0:r.editorMode)??!1;if(!(((a=(s=O.metadata)==null?void 0:s.labs)==null?void 0:a.simulations)??!1)||D)return ch("/memory")}const c=t.analysisQueue,p=c?c.getState():{paused:!1,jobs:[]},[u,h]=await Promise.all([$n(),pr()]),m=fr(),f=u?up(m,u):new Map,y=Array.from(f.entries()).sort((O,D)=>O[0].localeCompare(D[0])),g=(u==null?void 0:u.length)||0,x=(u==null?void 0:u.filter(O=>O.entityType==="visual").length)||0,b=(u==null?void 0:u.filter(O=>O.entityType==="library").length)||0,v=u?pp(m,u):[],N=v.length,w=(u==null?void 0:u.filter(O=>(O.analyses??[]).filter(D=>D.scenarios&&D.scenarios.length>0).length>0).length)||0,C=(u==null?void 0:u.reduce((O,D)=>{var B,Y,I;const T=((I=(Y=(B=D.analyses)==null?void 0:B[0])==null?void 0:Y.scenarios)==null?void 0:I.length)||0;return O+T},0))||0,S=(u==null?void 0:u.reduce((O,D)=>{var Y,I;const B=(((I=(Y=D.analyses)==null?void 0:Y[0])==null?void 0:I.scenarios)||[]).filter(L=>{var P,R;return(R=(P=L.metadata)==null?void 0:P.screenshotPaths)==null?void 0:R[0]}).length;return O+B},0))||0,k=[];u==null||u.forEach(O=>{var T;const D=(T=O.analyses)==null?void 0:T[0];D!=null&&D.scenarios&&D.scenarios.filter(Y=>{var I;return!((I=Y.metadata)!=null&&I.sameAsDefault)}).forEach(Y=>{var L,P;const I=(P=(L=Y.metadata)==null?void 0:L.screenshotPaths)==null?void 0:P[0];I&&k.push({entitySha:O.sha,entityName:O.name,scenarioId:Y.id,scenarioName:Y.name,screenshotPath:I,createdAt:D.createdAt||""})})}),k.sort((O,D)=>new Date(D.createdAt).getTime()-new Date(O.createdAt).getTime());const j=k.slice(0,16),_=(u==null?void 0:u.filter(O=>O.entityType==="visual").filter(O=>{var B,Y;const D=(B=O.analyses)==null?void 0:B[0];return!((Y=D==null?void 0:D.scenarios)==null?void 0:Y.some(I=>{var L,P;return(P=(L=I.metadata)==null?void 0:L.screenshotPaths)==null?void 0:P[0]}))}).slice(0,8))||[],F=(o=h==null?void 0:h.metadata)==null?void 0:o.currentRun,M=((i=F==null?void 0:F.currentEntityShas)==null?void 0:i.length)||0,$=p.jobs.length||0;return re({stats:{totalEntities:g,visualEntities:x,libraryEntities:b,uncommittedEntities:N,entitiesWithAnalyses:w,totalScenarios:C,capturedScreenshots:S,currentlyAnalyzing:M,filesOnQueue:$},uncommittedFiles:y,uncommittedEntitiesList:v,recentSimulations:j,visualEntitiesForSimulation:_,projectSlug:l,queueState:p,currentCommit:h})}catch(l){return console.error("Failed to load dashboard data:",l),re({stats:{totalEntities:0,visualEntities:0,libraryEntities:0,uncommittedEntities:0,entitiesWithAnalyses:0,totalScenarios:0,capturedScreenshots:0,currentlyAnalyzing:0,filesOnQueue:0},uncommittedFiles:[],uncommittedEntitiesList:[],recentSimulations:[],visualEntitiesForSimulation:[],projectSlug:null,queueState:{paused:!1,jobs:[]},currentCommit:null,error:"Failed to load dashboard data"})}}const e2=et(function(){var L,P;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:s,recentSimulations:a,visualEntitiesForSimulation:o,projectSlug:i,queueState:l,currentCommit:c}=ot(),p=Ge(),u=Rt(),{showToast:h}=Qo();Ot({source:"dashboard"});const[m,f]=A(new Set),[y,g]=A(null),[x,b]=A(!1),[v,N]=A(!1),{lastLine:w,isCompleted:C}=Jt(i,!!y),{simulatingEntity:S,scenarios:k,scenarioStatuses:j,allScenariosCaptured:_}=le(()=>{var z,W;const R={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!y)return R;const E=o==null?void 0:o.find(V=>V.sha===y);if(!E)return R;const J=(z=E.analyses)==null?void 0:z[0],K=(J==null?void 0:J.scenarios)||[],Q=((W=J==null?void 0:J.status)==null?void 0:W.scenarios)||[],q=Q.filter(V=>V.screenshotFinishedAt).length,U=K.length>0&&q===K.length;return{simulatingEntity:E,scenarios:K,scenarioStatuses:Q,allScenariosCaptured:U}},[y,o]);ne(()=>{(C||_)&&g(null)},[C,_]);const F=(L=c==null?void 0:c.metadata)==null?void 0:L.currentRun,M=new Set((F==null?void 0:F.currentEntityShas)||[]),$=new Set(l.jobs.flatMap(R=>R.entityShas||[])),O=new Set(((P=l.currentlyExecuting)==null?void 0:P.entityShas)||[]),D=s.filter(R=>R.entityType==="visual"||R.entityType==="library"),T=D.filter(R=>!M.has(R.sha)&&!$.has(R.sha)&&!O.has(R.sha)),B=()=>{if(T.length===0){h("All entities are already queued or analyzing","info",3e3);return}const R=T.map(E=>E.sha);N(!0),h(`Starting analysis for ${T.length} entities...`,"info",3e3),p.submit({entityShas:R.join(",")},{method:"post",action:"/api/analyze"})};ne(()=>{if(p.state==="idle"&&p.data){const R=p.data;R.success?(console.log("[Analyze All] Success:",R.message),h(`Analysis started for ${R.entityCount} entities in ${R.fileCount} files. Watch the logs for progress.`,"success",6e3),N(!1)):R.error&&(console.error("[Analyze All] Error:",R.error),h(`Error: ${R.error}`,"error",8e3),N(!1))}},[p.state,p.data,h]);const Y=R=>{f(E=>{const J=new Set(E);return J.has(R)?J.delete(R):J.add(R),J})},I=[{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:QC,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,R=>R.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:I.map((R,E)=>n(ke,{to:R.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 ${R.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:R.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:[R.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:R.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:`${R.color}15`},children:[R.iconType==="folder"&&n(Rh,{size:20,style:{color:R.color}}),R.iconType==="check"&&n(Bo,{size:20,style:{color:R.color}}),R.iconType==="image"&&n(Lr,{size:20,style:{color:R.color}}),R.iconType==="code-xml"&&n(Oh,{size:20,style:{color:R.color}})]}),n("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:R.value.toLocaleString("en-US")})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:R.color},children:"View All →"})]})]})},E))}),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"})]}),D.length>0&&n("button",{onClick:B,disabled:p.state!=="idle"||v||T.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:R=>R.currentTarget.style.backgroundColor="#004560",onMouseLeave:R=>R.currentTarget.style.backgroundColor="#005C75",children:p.state!=="idle"||v?"Starting analysis...":T.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([R,E])=>{const J=m.has(R),K=E.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(R),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:R}),d("span",{className:"text-xs text-gray-500",children:[K.length," entit",K.length!==1?"ies":"y"]})]})]})}),J&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:K.length>0?K.map(Q=>{const q=M.has(Q.sha),U=$.has(Q.sha)||O.has(Q.sha);return d(ke,{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:z=>z.currentTarget.style.borderColor="#005C75",onMouseLeave:z=>z.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(Lr,{size:16,style:{color:"#8B5CF6"}}),Q.entityType==="library"&&n(ad,{size:16,className:"text-white"}),Q.entityType==="other"&&n(Lh,{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:[q&&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($t,{size:14,className:"animate-spin"}),"Analyzing..."]}),!q&&U&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!q&&!U&&n("button",{onClick:z=>{z.preventDefault(),z.stopPropagation(),h(`Starting analysis for ${Q.name}...`,"info",3e3),p.submit({entityShas:Q.sha},{method:"post",action:"/api/analyze"})},disabled:p.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:z=>z.currentTarget.style.backgroundColor="#004560",onMouseLeave:z=>z.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"})})]},R)})}):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(qC,{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:[S&&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(gt,{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 ",S.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:S.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 (",k.length," scenario",k.length!==1?"s":"",")"]})]}):w?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($t,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:w,children:w}),i&&n("button",{onClick:()=>b(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):p.state!=="idle"?d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n($t,{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($t,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),k.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:k.slice(0,8).map((R,E)=>{var W,V,ae;const J=(W=S==null?void 0:S.analyses)==null?void 0:W[0],K=_a(R,J==null?void 0:J.status,void 0,y||void 0,void 0),Q=(ae=(V=R.metadata)==null?void 0:V.screenshotPaths)==null?void 0:ae[0],q=K.isCaptured,U=K.status==="capturing"||K.status==="starting",z=K.hasError;return q?n(ke,{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(dt,{screenshotPath:Q,alt:R.name,title:R.name,className:"max-w-full max-h-full object-contain object-center"})},E):z?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:K.errorMessage||"Capture error",children:n("span",{className:"text-red-500",children:"⚠️"})},E):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:`${U?"Capturing":"Pending"} ${R.name}...`,children:n("span",{className:U?"animate-pulse":"text-gray-400",children:U?"⋯":"⏹️"})},E)})})]})]})]}),x&&i&&n(on,{projectSlug:i,onClose:()=>b(!1)})]})})}),t2=Object.freeze(Object.defineProperty({__proto__:null,default:e2,loader:XC,meta:ZC},Symbol.toStringTag,{value:"Module"}));function hp({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(fm,{remarkPlugins:[gm],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(ve,{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 mp(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 fp(e){let t=e.memories.length;for(const r of e.children.values())t+=fp(r);return t}function ja(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 Or(e){return Math.round(e/3.5)}function nr(e){const t=new Date(e),r=new Date;if(t.toDateString()===r.toDateString()){const c=r.getTime()-t.getTime(),p=Math.floor(c/(1e3*60)),u=Math.floor(c/(1e3*60*60));return p<3?"Just now":p<60?`${p}min ago`:u===1?"1h ago":`${u}h ago`}const a=t.toLocaleDateString("en-US",{month:"short"}),o=t.getDate(),i=t.getFullYear(),l=r.getFullYear();return i===l?`${a} ${o}`:`${a} ${o}, ${i}`}function n2({rule:e,onEdit:t,onDelete:r,onView:s,isReviewed:a,onToggleReviewed:o,changeType:i,isUncommitted:l,changeDate:c,diff:p,isFadingOut:u,showLeftBorder:h}){const[m,f]=A(!1),[y,g]=A(!1),x=le(()=>ja(e.body,e.filePath),[e.body,e.filePath]),b=Or(e.body.length),v=m?"#3e3e3e":l?"#d97706":"#c7c7c7",N=`rounded-lg border overflow-hidden transition-all ease-in-out ${l?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,w={...u&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return d("div",{className:N,style:w,children:[n("div",{className:`p-4 cursor-pointer ${l?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>s?s(e):f(!m),children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:m?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:v})})}),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(ve,{children:[e.frontmatter.paths.slice(0,2).map((C,S)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:C},S)),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:nr(c)}),o&&n("button",{onClick:C=>{C.stopPropagation(),o(e.filePath,e.lastModified,a??!1)},className:`w-5 h-5 rounded-full border-2 flex items-center justify-center cursor-pointer transition-colors ${a?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,title:a?"Mark as unreviewed":"Mark as reviewed",children:a&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}),m&&d("div",{className:`border-t ${l?"border-amber-200":"border-gray-100"}`,children:[d("div",{className:`px-4 py-3 flex items-center justify-between ${l?"bg-amber-50":"bg-white"}`,children:[n("div",{className:"flex items-center gap-2",children:i==="modified"&&p&&d("button",{onClick:C=>{C.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(Os,{className:"w-3 h-3"}),y?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&d("div",{className:"flex items-center gap-2",children:[d("button",{onClick:C=>{C.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(zh,{className:"w-3 h-3"}),"Edit"]}),d("button",{onClick:C=>{C.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(Bh,{className:"w-3 h-3"}),"Delete"]})]})]}),y&&p&&n("pre",{className:"mx-4 mb-4 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:p.split(`
565
- `).map((C,S)=>{let k="";return C.startsWith("+")&&!C.startsWith("+++")?k="text-green-400":C.startsWith("-")&&!C.startsWith("---")?k="text-red-400":C.startsWith("@@")&&(k="text-cyan-400"),n("div",{className:k,children:C},S)})}),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(pt,{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((C,S)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:C},S))})]}),!y&&n("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[500px] overflow-auto bg-white border-gray-200",children:n(hp,{content:e.body})})]})]})}function r2(){return new Date().toISOString().split(".")[0]+"",`---
566
- paths:
567
- - '**/*.ts'
568
- ---
569
-
570
- ## Title
571
-
572
- Description here.
573
- `}function s2({rule:e,onSave:t,onCancel:r}){const[s,a]=A(e?`.claude/rules/${e.filePath}`:""),[o,i]=A((e==null?void 0:e.content)||r2()),[l,c]=A(!!e),[p,u]=A(!1),h=!e;return d("div",{className:"p-6",children:[d("div",{className:"flex items-center justify-between mb-4",children:[n("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),n("button",{onClick:r,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:n(lr,{className:"w-5 h-5"})})]}),h&&d("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:d("div",{className:"flex items-start gap-3",children:[n(Os,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),d("div",{children:[n("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),n("p",{className:"text-sm text-[#0369a1] mb-2",children:"Run this command in Claude Code to create a properly formatted rule with the right file location and paths:"}),d("div",{className:"relative",children:[n("code",{className:"block bg-white px-3 py-2 pr-9 rounded border border-[#bae6fd] font-mono text-sm text-[#0c4a6e]",children:"/codeyam-new-rule"}),n("button",{onClick:()=>{navigator.clipboard.writeText("/codeyam-new-rule"),u(!0),setTimeout(()=>u(!1),2e3)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[#0284c7] hover:text-[#0c4a6e] cursor-pointer transition-colors",title:"Copy command",children:p?n(Et,{className:"w-4 h-4 text-green-500"}):n(It,{className:"w-4 h-4"})})]})]})]})}),d("button",{onClick:()=>c(!l),className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:l?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:l?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(l||!h)&&d("div",{className:"space-y-4",children:[d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),d("div",{className:"relative",children:[n("input",{type:"text",value:s,onChange:m=>a(m.target.value),placeholder:"e.g., src/webserver/architecture.md",className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm",disabled:!!e}),n("button",{onClick:()=>{navigator.clipboard.writeText(s)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy path",children:n(It,{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(It,{className:"w-4 h-4"})})]})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:o,onChange:m=>i(m.target.value),rows:20,className:"w-full px-3 py-2 border border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm bg-gray-900 text-gray-100 [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-track]:bg-gray-800 [&::-webkit-scrollbar-thumb]:bg-gray-600 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:hover:bg-gray-500 [&::-webkit-resizer]:bg-gray-700"})]}),d("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-[#001f3f] hover:text-[#001530] rounded-md cursor-pointer font-mono uppercase text-xs font-semibold",children:"Cancel"}),n("button",{onClick:()=>t(s.replace(/^\.claude\/rules\//,""),o),disabled:!s.trim()||!o.trim(),className:"px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer font-mono uppercase text-xs font-semibold",children:"Save"})]})]})]})}function a2({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:s,onToggleFolder:a}){const o=le(()=>mp(e),[e]),i=(p,u,h)=>{if(p.target.closest(".chevron-toggle")){h&&a(u||"root");return}const f=u||null;r(t===f?null:f),h&&!s.has(u||"root")&&a(u||"root")},l=p=>{r(t===p?null:p)},c=(p,u=0)=>{const h=s.has(p.path||"root"),m=fp(p),f=p.children.size>0,y=p.name==="root"?"(root)":p.name,g=p.memories.length>0||f,x=p.path||"",b=t===x||t===null&&x==="";return d("div",{children:[d("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${b?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${u*12+8}px`},onClick:v=>i(v,p.path,g),children:[g&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:v=>{v.stopPropagation(),a(p.path||"root")},children:n(pn,{className:`w-3 h-3 text-gray-500 transition-transform ${h?"rotate-90":""}`})}),!g&&n("div",{className:"w-3"}),n(id,{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:[m," rules"]})]}),h&&d("div",{className:"relative",children:[(p.memories.length>0||f)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${u*12+8+6}px`}}),p.memories.length>0&&n("div",{style:{paddingLeft:`${(u+1)*12+8}px`},children:p.memories.map(v=>{var w;const N=t===v.filePath;return n("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${N?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>l(v.filePath),children:n("span",{className:"text-xs",children:(w=v.filePath.split("/").pop())==null?void 0:w.replace(".md","")})},v.filePath)})}),f&&n("div",{children:Array.from(p.children.values()).sort((v,N)=>v.name.localeCompare(N.name)).map(v=>c(v,u+1))})]})]},p.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:c(o)})}function o2({memories:e,onEdit:t,onDelete:r,expandedFolders:s,onToggleFolder:a,reviewedStatus:o,onMarkReviewed:i,onMarkUnreviewed:l,onViewRule:c}){const[p,u]=A({});ne(()=>{u({})},[o]);const h=le(()=>({...o,...p}),[o,p]),m=le(()=>mp(e),[e]),f=(g,x,b)=>{u(v=>({...v,[g]:!b})),b?l(g):i(g,x)},y=(g,x=0)=>{const b=s.has(g.path||"root"),v=g.children.size>0,N=g.name==="root"?"root":g.name,w=g.memories.length>0||v;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:()=>w&&a(g.path||"root"),children:[w&&n(pn,{className:`w-4 h-4 text-gray-500 transition-transform ${b?"rotate-90":""}`}),!w&&n("div",{className:"w-4"}),n(id,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:N})]}),b&&d("div",{className:"ml-10 space-y-4 relative",children:[(g.memories.length>0||v)&&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(C=>n(n2,{rule:C,onEdit:t,onDelete:r,onView:c,isReviewed:h[C.filePath]??!1,onToggleReviewed:f},C.filePath))}),v&&n("div",{className:"space-y-4",children:Array.from(g.children.values()).sort((C,S)=>C.name.localeCompare(S.name)).map(C=>y(C,x+1))})]})]},g.path||"root")};return n("div",{children:y(m)})}function i2({memories:e,reviewedStatus:t,onViewRule:r,refreshKey:s}){const[a,o]=A("unreviewed"),[i,l]=A("by-date"),[c,p]=A(null),[u,h]=A(!0),[m,f]=A(new Map),y=ye(t),g=ye([]);ne(()=>()=>{g.current.forEach(clearTimeout)},[]),ne(()=>{(async()=>{h(!0);try{const S=await(await fetch("/api/memory?action=rule-coverage")).json();p(S.coverage??null)}catch{p(null)}finally{h(!1)}})()},[s]),ne(()=>{const w=y.current,C=[];for(const[S,k]of Object.entries(t))k&&!w[S]&&C.push(S);y.current=t,C.length!==0&&(f(S=>{const k=new Map(S);return C.forEach(j=>k.set(j,"approved")),k}),g.current.push(setTimeout(()=>{f(S=>{const k=new Map(S);return C.forEach(j=>k.set(j,"fading")),k})},1500)),g.current.push(setTimeout(()=>{f(S=>{const k=new Map(S);return C.forEach(j=>k.delete(j)),k})},2500)))},[t]);const x=le(()=>{const w=[...e];return i==="by-impact"&&c!==null?w.sort((C,S)=>{const k=c[C.filePath]??0,j=c[S.filePath]??0;return j!==k?j-k:new Date(S.lastModified).getTime()-new Date(C.lastModified).getTime()}):w.sort((C,S)=>new Date(S.lastModified).getTime()-new Date(C.lastModified).getTime()),w},[e,i,c]),b=le(()=>x.filter(w=>!t[w.filePath]).length,[x,t]),v=le(()=>a==="unreviewed"?x.filter(w=>!t[w.filePath]||m.has(w.filePath)):x,[x,a,t,m]),N=!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:()=>N&&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 ${N?"cursor-pointer hover:text-gray-600":"cursor-default"} ${i==="by-impact"?"text-[#005C75]":"text-gray-400"}`,children:["Src Files",i==="by-impact"&&n(kt,{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(kt,{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(xo,{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:v.map(w=>{const C=t[w.filePath]??!1,S=m.get(w.filePath),k=ja(w.body,w.filePath),j=(c==null?void 0:c[w.filePath])??0;return n("div",{className:`border-b border-gray-50 transition-all ${S==="fading"?"duration-1000":"duration-300"}`,style:{opacity:S==="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 ${S==="approved"?"bg-[#f0fdf4]":"hover:bg-gray-50"}`,onClick:()=>r(w),children:[n("div",{className:"flex items-center gap-2 min-w-0",children:n("span",{className:"text-sm text-gray-900 truncate",children:k})}),n("span",{className:"text-xs text-center",children:u?n("span",{className:"inline-block w-6 h-3 bg-gray-100 rounded animate-pulse"}):c!==null?n("span",{className:j>0?"text-gray-700 font-medium":"text-gray-300",children:j}):n("span",{className:"text-gray-300",children:"—"})}),n("span",{className:"text-xs text-gray-500 text-center",children:nr(w.lastModified)}),n("div",{className:"flex justify-center",children:n("div",{className:`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors duration-300 ${C?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:C&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})})]})},w.filePath)})}),v.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 l2(e,t){const r=t.map(s=>`- \`${s}\``).join(`
574
- `);return`Please audit the following Claude Rules that apply to the file \`${e}\`:
575
-
576
- ${r}
577
-
578
- Please review these rules in conjunction with one another as they all apply to this file.
579
-
580
- Review each rule with the other rules in mind:
581
- - Necessary: Is this rule really necessary to avoid confusion in future work sessions?
582
- - Efficiency: Are the rules concise and well-structured?
583
- - Effectiveness: Does the rules provide clear, actionable guidance?
584
- - Context window impact: Can the rules be shortened without losing important information?
585
- - Overlap: Is there any redundant information across the rules that can be consolidated?
586
- - Duplication: Are there any rules that are nearly identical that can be merged or removed?
587
-
588
- Remember that documenting past confusion isn't helpul unless that confusion will likely happen again.
589
-
590
- 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 c2({filePath:e,rulePaths:t,onClose:r}){const[s,a]=A(!1),o=l2(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(lr,{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(ve,{children:[n(Et,{className:"w-4 h-4"}),"Copied!"]}):d(ve,{children:[n(It,{className:"w-4 h-4"}),"Copy Prompt"]})})})]})})}function d2({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:s}){const[a,o]=A("unreviewed"),[i,l]=A(null),[c,p]=A(""),[u,h]=A(0),[m,f]=A(!1),[y,g]=A(null),[x,b]=A(null),v=ye(null),N=ye(null),[w,C]=A({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[S,k]=A(!0);ne(()=>{(async()=>{k(!0);try{const Y=await(await fetch("/api/memory?action=audit")).json();C({topPaths:Y.topPaths||[],totalFilesWithCoverage:Y.totalFilesWithCoverage||0,allSourceFiles:Y.allSourceFiles||[]})}catch(B){console.error("Failed to load audit data:",B)}finally{k(!1)}})()},[e]);const j=le(()=>a==="all"?w.topPaths:w.topPaths.filter(T=>T.matchingRules.some(B=>!t[B.filePath])),[w.topPaths,a,t]);le(()=>w.topPaths.filter(T=>T.matchingRules.some(B=>!t[B.filePath])).length,[w.topPaths,t]);const _=T=>T.split("/").pop()||T,F=le(()=>{const T=new Map;for(const B of w.topPaths)T.set(B.filePath,B);return T},[w.topPaths]),M=le(()=>{if(!c.trim())return[];const T=c.toLowerCase(),B=[],Y=[];for(const I of w.allSourceFiles){const L=I.toLowerCase();if(!L.includes(T))continue;const P=F.get(I)||{filePath:I,matchingRules:[],totalTextLength:0};L.startsWith(T)?B.push(P):Y.push(P)}return B.sort((I,L)=>I.filePath.localeCompare(L.filePath)),Y.sort((I,L)=>I.filePath.localeCompare(L.filePath)),[...B,...Y].slice(0,8)},[c,w.allSourceFiles,F]),$=oe(T=>{var B;g(T),l(T.filePath),p(T.filePath),f(!1),(B=v.current)==null||B.blur()},[]),O=oe(()=>{var T;p(""),g(null),l(null),(T=v.current)==null||T.focus()},[]),D=oe(T=>{var B;!m||M.length===0||(T.key==="ArrowDown"?(T.preventDefault(),h(Y=>Math.min(Y+1,M.length-1))):T.key==="ArrowUp"?(T.preventDefault(),h(Y=>Math.max(Y-1,0))):T.key==="Enter"?(T.preventDefault(),$(M[u])):T.key==="Escape"&&(f(!1),(B=v.current)==null||B.blur()))},[m,M,u,$]);return ne(()=>{h(0)},[M]),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(Hr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),n("input",{ref:v,type:"text",value:c,onChange:T=>{p(T.target.value),f(!0)},onFocus:()=>{c.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:D,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:T=>{T.preventDefault(),O()},className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center text-gray-400 hover:text-gray-600 cursor-pointer",children:n("svg",{viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"w-3 h-3",children:n("path",{d:"M1 1l12 12M13 1L1 13"})})}),m&&M.length>0&&n("div",{ref:N,className:"absolute left-0 top-full mt-0.5 bg-white border border-gray-200 rounded-md shadow-lg z-10 max-h-75 overflow-y-auto min-w-75 max-w-120",children:M.map((T,B)=>d("div",{onMouseDown:Y=>{Y.preventDefault(),$(T)},onMouseEnter:()=>h(B),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${B===u?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(Ls,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:T.filePath,children:(()=>{const Y=T.filePath.toLowerCase().indexOf(c.toLowerCase());if(Y===-1)return T.filePath;const I=T.filePath.slice(0,Y),L=T.filePath.slice(Y,Y+c.length),P=T.filePath.slice(Y+c.length);return d(ve,{children:[I,n("span",{className:"font-semibold text-[#005C75]",children:L}),P]})})()}),d("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[T.matchingRules.length," rule",T.matchingRules.length!==1?"s":""]})]},T.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(xo,{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(xo,{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"})]})]})]}),S&&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"})]})}),!S&&(j.length>0||y)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(y?[y,...j.filter(B=>B.filePath!==y.filePath)].slice(0,8):j.slice(0,8)).map((T,B)=>{const Y=T.matchingRules.length,I=T.matchingRules.filter(K=>!t[K.filePath]),L=I.length,P=I.reduce((K,Q)=>K+Q.bodyLength,0),R=L>0,E=i===T.filePath,J=(y==null?void 0:y.filePath)===T.filePath;return d("div",{children:[d("div",{onClick:()=>l(E?null:T.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:[E?n(kt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n(pn,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(Ls,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:T.filePath,children:J?T.filePath:_(T.filePath)})]}),d("span",{className:"text-sm text-center",children:[n("span",{className:R?"font-semibold text-[#1A5276]":"text-gray-400",children:L}),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:R?"font-semibold text-[#1A5276]":"text-gray-400",children:Or(P).toLocaleString()}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:Or(T.totalTextLength).toLocaleString()})]})]}),E&&d("div",{className:"bg-gray-50 border-b border-gray-100",children:[T.matchingRules.map(K=>{const Q=r.find(U=>U.filePath===K.filePath),q=t[K.filePath]??!1;return d("div",{onClick:U=>{U.stopPropagation(),Q&&s(Q)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(Rs,{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?ja(Q.body,Q.filePath):K.filePath}),d("span",{className:"text-xs text-gray-400 flex-shrink-0",children:[Or(K.bodyLength).toLocaleString()," ","tokens"]}),n("div",{className:`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${q?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:q&&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"})})})]},K.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:K=>{K.stopPropagation(),b({filePath:T.filePath,rulePaths:T.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"})]})]})]},T.filePath)})}),!S&&j.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(c2,{filePath:x.filePath,rulePaths:x.rulePaths,onClose:()=>b(null)})]})}function u2({rule:e,changeInfo:t,isReviewed:r,onApprove:s,onEdit:a,onDelete:o,onClose:i}){const l=ja(e.body,e.filePath),c=Or(e.body.length),p=e.frontmatter.category,u=`.claude/rules/${e.filePath}`,[h,m]=A(null),f=(t==null?void 0:t.changeType)==="added"||h!=null&&h.commitCount!=null&&h.commitCount<=1&&!(h.commitCount===1&&h.isUncommitted);return ne(()=>{m(null),fetch(`/api/memory?action=rule-diff&filePath=${encodeURIComponent(e.filePath)}`).then(y=>y.json()).then(y=>{y.diff&&m(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(ve,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:nr(t.date)}),n("span",{className:`flex-shrink-0 text-[11px] uppercase font-semibold tracking-wider ${t.changeType==="added"?"text-green-600":t.changeType==="modified"?"text-orange-600":"text-red-600"}`,children:t.changeType})]})]}),p&&d("div",{className:"flex items-center gap-2 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"TYPE:"}),n("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase font-semibold tracking-wider bg-[#E0F2F1] text-[#00796B]",children:p})]}),d("div",{className:"flex items-center gap-1.5 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"FILE:"}),n("code",{className:"text-[11px] text-gray-600 font-mono",children:u}),n(pt,{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(Et,{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(lr,{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,v=x.length>0?x.join("/")+"/":"";return d("div",{className:"flex items-center gap-2 text-[13px] font-mono",children:[n(Ls,{className:"w-4 h-4 text-[#005C75] flex-shrink-0"}),d("span",{children:[v&&n("span",{className:"text-gray-500",children:v}),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?nr(t.date):h!=null&&h.date?nr(h.date):"recently"]})}):h&&n("div",{className:"px-6 pb-4",children:d("details",{children:[d("summary",{className:"text-[13px] text-gray-700 font-semibold cursor-pointer",children:["Recent change: ",h.commitMessage," —"," ",nr(h.date)]}),n("pre",{className:"mt-2 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:h.diff.split(`
591
- `).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(hp,{content:e.body})})]})]})})}function p2(){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 h2(){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 m2(){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(jc,{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(jc,{value:"/codeyam-memory"}),n("span",{className:"text-white text-[15px] font-medium",children:"in Claude Code to get started"})]})]})})}function jc({value:e}){const[t,r]=A(!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(Et,{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 ks({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 f2({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(p2,{}),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(Hr,{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(Yo,{className:"w-4 h-4"}),"New Rule"]})]})]}),d("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[n(ks,{label:"Total Rules",count:a.total,icon:n(h2,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(ks,{label:"Unreviewed",count:a.unreviewed,icon:n(Yh,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(ks,{label:"Reviewed",count:a.reviewed,icon:n(Et,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(ks,{label:"Stale",count:a.stale,icon:n(od,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]})}function g2({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(lr,{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(Yo,{className:"w-4 h-4"}),"New Rule"]})})]})})}function y2({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 Ac="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!",Pc="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function Tc({text:e}){const[t,r]=A(!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(ve,{children:[n(Et,{className:"w-4 h-4"}),"Copied!"]}):d(ve,{children:[n(It,{className:"w-4 h-4"}),"Copy Prompt"]})})}function x2({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(lr,{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:Ac,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(Tc,{text:Ac})}),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:Pc,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(Tc,{text:Pc})})]})]})})}function b2(){const[e,t]=A(!1);return d(ve,{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(x2,{onClose:()=>t(!1)})]})}function v2(e){return`Can you help me review my unreviewed rules? The following rules in \`.claude/rules\` have not been reviewed yet:
592
-
593
- ${e.map(r=>`- \`.claude/rules/${r}\``).join(`
594
- `)}
595
-
596
- 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 Mc="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function $c({text:e}){const[t,r]=A(!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(ve,{children:[n(Et,{className:"w-4 h-4"}),"Copied!"]}):d(ve,{children:[n(It,{className:"w-4 h-4"}),"Copy Prompt"]})})}function w2({onClose:e,unreviewedRulePaths:t}){const r=v2(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(lr,{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($c,{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:Mc,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($c,{text:Mc})})]})]})})}function N2({unreviewedRulePaths:e}){const[t,r]=A(!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(ve,{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(w2,{onClose:()=>r(!1),unreviewedRulePaths:e})]})}const S2=()=>[{title:"Memory - CodeYam"},{name:"description",content:"Manage Claude Memory documentation"}];async function C2({request:e}){try{const r=await(await fetch(new URL("/api/memory",e.url).toString())).json();return r.error?re({memories:[],reviewedStatus:{},memoryInitialized:r.memoryInitialized??!1,error:r.error}):r.memoryInitialized??!1?re({memories:r.memories||[],reviewedStatus:r.reviewedStatus||{},memoryInitialized:!0,error:null}):re({memories:[],reviewedStatus:{},memoryInitialized:!1,error:null})}catch(t){return console.error("Failed to load memories:",t),re({memories:[],reviewedStatus:{},memoryInitialized:!1,error:"Failed to load memories"})}}const k2=et(function(){const{memories:t,reviewedStatus:r,memoryInitialized:s,error:a}=ot(),o=Ge(),i=Rt(),[l,c]=A(""),[p,u]=A(null),[h,m]=A(new Set(["root"])),[f,y]=A(null),[g,x]=A(!1),[b,v]=A(null),[N,w]=A(0),[C,S]=A(!1),[k,j]=A(null),[_,F]=A(null),[M,$]=A({}),O=U=>{m(z=>{const W=new Set(z);return W.has(U)?W.delete(U):W.add(U),W})};Ot({source:"memory-page"});const D=le(()=>({...r,...M}),[r,M]),T=ye(o.state);ne(()=>{const U=T.current==="loading"||T.current==="submitting",z=o.state==="idle";U&&z&&o.data&&(i.revalidate(),y(null),x(!1),w(W=>W+1)),T.current=o.state},[o.state,o.data,i]),ne(()=>{$(U=>{const z={};for(const[W,V]of Object.entries(U))r[W]!==V&&(z[W]=V);return Object.keys(z).length===Object.keys(U).length?U:z})},[r]);const B=(U,z)=>{$(W=>({...W,[U]:!0})),o.submit({action:"mark-reviewed",filePath:U,lastModified:z},{method:"POST",action:"/api/memory",encType:"application/json"})},Y=U=>{$(z=>({...z,[U]:!1})),o.submit({action:"mark-unreviewed",filePath:U},{method:"POST",action:"/api/memory",encType:"application/json"})},I=(U,z)=>{j(U),F(z??null)},L=le(()=>{let U=t;if(l.trim()){const z=l.toLowerCase();U=U.filter(W=>{var ae;return(((ae=W.filePath.split("/").pop())==null?void 0:ae.replace(".md",""))||"").toLowerCase().includes(z)||W.body.toLowerCase().includes(z)})}return U},[t,l]),P=le(()=>p?L.some(z=>z.filePath===p)?L.filter(z=>z.filePath===p):L.filter(z=>z.filePath.startsWith(p+"/")||z.filePath===p):L,[L,p]),R=(U,z)=>{const W=f?"update":"create";o.submit({action:W,filePath:U,content:z},{method:"POST",action:"/api/memory",encType:"application/json"})},E=U=>{o.submit({action:"delete",filePath:U.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),v(null)},J=le(()=>{const U=t.filter(z=>D[z.filePath]).length;return{total:t.length,reviewed:U,unreviewed:t.length-U,stale:0}},[t,D]),K=le(()=>{const U=new Set(["root"]);for(const z of L){const W=z.filePath.split("/");W.pop();let V="";for(const ae of W)V=V?`${V}/${ae}`:ae,U.add(V)}return U},[L]),Q=K.size===h.size&&[...K].every(U=>h.has(U)),q=()=>{m(Q?new Set(["root"]):new Set(K))};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(f2,{searchFilter:l,onSearchChange:c,onCreateNew:()=>x(!0),onLearnMore:()=>S(!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:U=>U.stopPropagation(),children:n(s2,{rule:f,onSave:R,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(i2,{memories:L,reviewedStatus:D,onViewRule:I,refreshKey:N}),n(d2,{onEditRule:y,onDeleteRule:v,refreshKey:N,reviewedStatus:D,onMarkReviewed:B,onMarkUnreviewed:Y,memories:t,onViewRule:I})]}),d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(N2,{unreviewedRulePaths:t.filter(U=>!D[U.filePath]).map(U=>U.filePath)}),n(b2,{})]}),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:K.size>1&&n("button",{onClick:q,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(a2,{memories:L,selectedPath:p,onSelectPath:u,expandedFolders:h,onToggleFolder:O})}),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(Wh,{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(Yo,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):d("div",{children:[p&&d("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:["Showing rules in"," ",n("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:p||"(root)"}),n("button",{onClick:()=>u(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(o2,{memories:P,onEdit:y,onDelete:v,expandedFolders:h,onToggleFolder:O,reviewedStatus:D,onMarkReviewed:B,onMarkUnreviewed:Y,onViewRule:I})]})})]}),n("div",{className:"mt-8 mb-8",children:n(ke,{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"})]})]})})}),k&&!f&&(()=>{const U=t.find(z=>z.filePath===k.filePath)??k;return n(u2,{rule:U,changeInfo:_??void 0,isReviewed:D[U.filePath]??!1,onApprove:()=>{D[U.filePath]??!1?Y(U.filePath):B(U.filePath,U.lastModified),j(null)},onEdit:()=>{y(U)},onDelete:()=>{v(U),j(null)},onClose:()=>j(null)})})(),C&&n(g2,{onClose:()=>S(!1),onCreateNew:()=>{S(!1),x(!0)}}),b&&n(y2,{rule:b,onConfirm:E,onCancel:()=>v(null)})]})}):n(m2,{})}),_2=Object.freeze(Object.defineProperty({__proto__:null,default:k2,loader:C2,meta:S2},Symbol.toStringTag,{value:"Module"}));function ho(e){return`${e.filePath||""}::${e.name}`}function gp(e,t){const r=Ge(),{showToast:s}=Qo(),[a,o]=A(new Map);ne(()=>{if(r.state==="idle"&&r.data){const m=r.data;m!=null&&m.error&&s(`Error: ${m.error}`,"error",6e3)}},[r.state,r.data,s]),ne(()=>{var f;if(a.size===0)return;const m=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,v)=>{b===x&&m.add(v)})})}),e==null||e.forEach(y=>{a.forEach((g,x)=>{g===y&&m.add(x)})}),m.size>0&&o(y=>{const g=new Map(y);return m.forEach(x=>g.delete(x)),g})},[t,e,a]);const i=oe(m=>{console.log("Generate analysis clicked for entity:",m.sha,m.name);const f=ho(m);o(g=>new Map(g).set(f,m.sha));const y=new FormData;y.append("entitySha",m.sha),y.append("filePath",m.filePath||""),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),l=oe(m=>{const f=m.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(x=>{const b=new Map(x);return f.forEach(v=>b.set(ho(v),v.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=oe(m=>(e==null?void 0:e.includes(m))??!1,[e]),p=oe(m=>{const f=ho(m);return a.has(f)},[a]),u=oe(m=>{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(m)}))??!1},[t]),h=le(()=>Array.from(a.keys()),[a]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:l,isEntityBeingAnalyzed:c,isEntityPending:p,isEntityInQueue:u,pendingEntityKeys:h}}function Bi({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 E2({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 Yi({filePath:e,isExpanded:t,onToggle:r,fileStatus:s,simulationPreviews:a,entityCount:o,state:i,lastModified:l,actionButton:c,uncommittedCount:p,children:u,isNotAnalyzable:h=!1,isUncommitted:m=!1}){return d("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[d("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${h?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[d("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(fd,{filePath:e}),s&&n(E2,{status:typeof s=="string"?s:s.status,variant:"full"}),m&&i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(m||i==="out-of-date")&&d("div",{className:"flex gap-1.5 items-center",children:[m&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&!m&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:a}),d("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:d("span",{className:"text-[13px] text-[#3e3e3e]",children:[o," ",o===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:rp(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 Wi({entities:e,maxPreviews:t=3}){var s,a,o,i,l;const r=[];for(const c of e){if(r.length>=t)break;const p=((a=(s=c.analyses)==null?void 0:s[0])==null?void 0:a.scenarios)||[];if(c.entityType==="library"){const u=p.find(h=>{var m,f;return((m=h.metadata)==null?void 0:m.executionResult)||((f=h.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:c.sha})}else if(c.entityType==="visual"){const u=p.find(h=>{var m,f;return(f=(m=h.metadata)==null?void 0:m.screenshotPaths)==null?void 0:f[0]});if(u){const h=(i=(o=u.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],m=!!((l=u.metadata)!=null&&l.error);h&&r.push({type:"screenshot",screenshot:h,hasError:m,scenario:u,entitySha:c.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(ve,{children:r.map((c,p)=>{if(c.type==="screenshot"&&c.screenshot){const u=c.hasError?"border-red-400":"border-gray-200";return d(ke,{to:c.scenario?`/entity/${c.entitySha}/scenarios/${c.scenario.id}`:`/entity/${c.entitySha}`,className:`relative w-[50px] h-[38px] border ${u} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:h=>h.stopPropagation(),children:[n(dt,{screenshotPath:c.screenshot,alt:`Preview ${p+1}`,className:"max-w-full max-h-full object-contain object-center"}),c.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(Ds,{size:12,color:"white"})})]},`screenshot-${p}`)}return c.type==="library"&&c.scenario&&c.entitySha?n(tp,{scenario:c.scenario,entitySha:c.entitySha,size:"small",showBorder:!0},`library-${p}`):null})})}function Ui({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:s}){var u,h;const a=t||r?[{entityShas:[e.sha]}]:[],o=Nt(e,a,t),i=e.entityType==="visual"||e.entityType==="library",l=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,p=(((h=(u=e.analyses)==null?void 0:u[0])==null?void 0:h.scenarios)||[]).filter(m=>{var f,y;return(y=(f=m.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0]});return d("div",{className:"bg-white rounded-lg",children:[d(ke,{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(gt,{type:"type"})})}):n(gt,{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($i,{type:e.entityType||"other"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),d("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?o==="queued"?d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):o==="analyzing"?d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):o==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):o==="out-of-date"?n("button",{onClick:m=>{m.preventDefault(),m.stopPropagation(),s(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):l&&n("button",{onClick:m=>{m.preventDefault(),m.stopPropagation(),s(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"})})]})]})]}),p.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:p.map((m,f)=>{var g,x;const y=(x=(g=m.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return y?n(ke,{to:`/entity/${e.sha}?scenario=${m.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:b=>b.stopPropagation(),children:n(dt,{screenshotPath:y,alt:m.name,className:"max-w-full max-h-full object-contain object-center"})},m.id):null})})]})}function j2({entities:e,page:t,itemsPerPage:r=50,currentRun:s,filter:a,entityType:o,queueState:i,isEntityPending:l,pendingEntityKeys:c,onGenerateSimulation:p,onGenerateAllSimulations:u,totalFilesCount:h,totalEntitiesCount:m,uncommittedFilesCount:f,showOnlyUncommitted:y,onToggleUncommitted:g}){const[x,b]=ir(),[v,N]=A(new Set),[w,C]=A(""),[S,k]=A(!1),[j,_]=A("all"),[F,M]=A("desc"),$=o||"all",O=le(()=>{let E=e;return $!=="all"&&(E=E.filter(J=>J.entityType===$)),a==="analyzed"&&(E=E.filter(J=>J.analyses&&J.analyses.length>0)),E},[e,$,a]),D=le(()=>{const E=new Map,J=new Map,K=new Map;O.forEach(z=>{var ae,pe;const W=`${z.filePath}::${z.name}`,V=J.get(W);if(!V)J.set(W,z),K.set(W,[]);else{const xe=((ae=V.metadata)==null?void 0:ae.editedAt)||V.createdAt||"",ie=((pe=z.metadata)==null?void 0:pe.editedAt)||z.createdAt||"";let me=!1;if(ie>xe)me=!0;else if(ie===xe){const we=V.createdAt||"";me=(z.createdAt||"")>we}me?(K.get(W).push(V),J.set(W,z)):K.get(W).push(z)}}),J.forEach((z,W)=>{var ae;if(!(z.analyses&&z.analyses.length>0)&&((ae=z.metadata)!=null&&ae.previousVersionWithAnalyses)){const xe=(K.get(W)||[]).find(ie=>{var me;return ie.sha===((me=z.metadata)==null?void 0:me.previousVersionWithAnalyses)});xe&&xe.analyses&&xe.analyses.length>0&&(z.analyses=xe.analyses)}}),Array.from(J.values()).sort((z,W)=>{var pe,xe,ie,me;const V=!((pe=z.metadata)!=null&&pe.notExported)&&!((xe=z.metadata)!=null&&xe.namedExport),ae=!((ie=W.metadata)!=null&&ie.notExported)&&!((me=W.metadata)!=null&&me.namedExport);return V&&!ae?-1:!V&&ae?1:0}).forEach(z=>{var xe,ie,me,we,Te;const W=z.filePath??"No File Path";E.has(W)||E.set(W,{filePath:W,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const V=E.get(W);V.entities.push(z),V.totalCount++,(xe=z.metadata)!=null&&xe.isUncommitted&&V.uncommittedCount++;const ae=((we=(me=(ie=z.analyses)==null?void 0:ie[0])==null?void 0:me.scenarios)==null?void 0:we.length)||0;V.simulationCount+=ae;const pe=((Te=z.metadata)==null?void 0:Te.editedAt)||z.updatedAt;pe&&(!V.lastUpdated||new Date(pe)>new Date(V.lastUpdated))&&(V.lastUpdated=pe)});const Q=(i==null?void 0:i.jobs)||[],q=z=>{const W=`${z.filePath||""}::${z.name}`;return(c==null?void 0:c.includes(W))||!1};E.forEach(z=>{const W=z.entities.map(V=>q(V)?"queued":Nt(V,Q));W.includes("analyzing")||W.includes("queued")?z.state="analyzing":W.includes("incomplete")?z.state="incomplete":W.includes("out-of-date")?z.state="out-of-date":W.includes("not-analyzed")?z.state="not-analyzed":z.state="up-to-date"}),E.forEach(z=>{var W,V,ae,pe,xe;for(const ie of z.entities){if(z.previewScreenshots.length+z.previewLibraryScenarios.length>=3)break;const we=((V=(W=ie.analyses)==null?void 0:W[0])==null?void 0:V.scenarios)||[];if(ie.entityType==="library"){const Te=we.find(Ne=>{var _e,Z;return((_e=Ne.metadata)==null?void 0:_e.executionResult)||((Z=Ne.metadata)==null?void 0:Z.error)});Te&&z.previewLibraryScenarios.push({scenario:Te,entitySha:ie.sha})}else{const Te=we.find(Ne=>{var _e,Z;return(Z=(_e=Ne.metadata)==null?void 0:_e.screenshotPaths)==null?void 0:Z[0]});if(Te){const Ne=(pe=(ae=Te.metadata)==null?void 0:ae.screenshotPaths)==null?void 0:pe[0],_e=!!((xe=Te.metadata)!=null&&xe.error);Ne&&!z.previewScreenshots.includes(Ne)&&(z.previewScreenshots.push(Ne),z.previewScreenshotErrors.push(_e))}}}});const U=Array.from(E.values());return U.sort((z,W)=>{if(a==="analyzed"){const pe=Math.max(...z.entities.filter(ie=>{var me,we;return(we=(me=ie.analyses)==null?void 0:me[0])==null?void 0:we.createdAt}).map(ie=>new Date(ie.analyses[0].createdAt).getTime()),0),xe=Math.max(...W.entities.filter(ie=>{var me,we;return(we=(me=ie.analyses)==null?void 0:me[0])==null?void 0:we.createdAt}).map(ie=>new Date(ie.analyses[0].createdAt).getTime()),0);return F==="desc"?xe-pe:pe-xe}if(z.uncommittedCount>0&&W.uncommittedCount===0)return-1;if(z.uncommittedCount===0&&W.uncommittedCount>0)return 1;const V=z.lastUpdated?new Date(z.lastUpdated).getTime():0,ae=W.lastUpdated?new Date(W.lastUpdated).getTime():0;return F==="desc"?ae-V:V-ae}),U},[O,a,F,i,c]),T=le(()=>{let E=D;if(j!=="all"&&(E=E.filter(J=>J.state===j)),w.trim()){const J=w.toLowerCase();E=E.filter(K=>K.filePath.toLowerCase().includes(J))}return E},[D,w,j]),B=(t-1)*r,Y=B+r,I=T.slice(B,Y),L=Math.ceil(T.length/r),P=E=>{N(J=>{const K=new Set(J);return K.has(E)?K.delete(E):K.add(E),K})},R=()=>{M(E=>E==="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:$,onChange:E=>{const J=E.target.value,K=new URLSearchParams(x);J==="all"?K.delete("entityType"):K.set("entityType",J),K.set("page","1"),b(K)},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(kt,{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:j,onChange:E=>_(E.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(kt,{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(Hr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",value:w,onChange:E=>C(E.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),h!==void 0&&m!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center",children:[d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:T.length})," ",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:T.reduce((E,J)=>E+J.totalCount,0)})," ",T.reduce((E,J)=>E+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:[T.filter(E=>E.uncommittedCount>0).length," ","uncommitted"," ",T.filter(E=>E.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"]})]}),I.length>0&&d("div",{className:"flex gap-6",children:[d("button",{onClick:()=>{N(new Set(I.map(E=>E.filePath))),k(!0)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(ld,{className:"w-3.5 h-3.5"}),"Expand All"]}),d("button",{onClick:()=>{N(new Set),k(!1)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(cd,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(Bi,{showActions:!0,sortOrder:F,onSortChange:R}),n("div",{className:"flex flex-col gap-[3px]",children:I.map(E=>{const J=v.has(E.filePath),Q=E.entities.filter(W=>(W.entityType==="visual"||W.entityType==="library")&&(Nt(W,(i==null?void 0:i.jobs)||[])==="not-analyzed"||Nt(W,(i==null?void 0:i.jobs)||[])==="out-of-date"||Nt(W,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,q=W=>{var V;return((V=s==null?void 0:s.currentEntityShas)==null?void 0:V.includes(W))||!1},U=W=>{var V;return l!=null&&l(W)?!0:((V=i==null?void 0:i.jobs)==null?void 0:V.some(ae=>{var pe;return(pe=ae.entityShas)==null?void 0:pe.includes(W.sha)}))||!1},z=W=>{p==null||p(W)};return n(Yi,{filePath:E.filePath,isExpanded:J,onToggle:()=>P(E.filePath),simulationPreviews:n(Wi,{entities:E.entities,maxPreviews:1}),entityCount:E.totalCount,state:E.state,lastModified:E.lastUpdated,uncommittedCount:E.uncommittedCount,isUncommitted:E.uncommittedCount>0,actionButton:Q?n("button",{onClick:W=>{W.stopPropagation();const V=E.entities.filter(ae=>(ae.entityType==="visual"||ae.entityType==="library")&&(Nt(ae,(i==null?void 0:i.jobs)||[])==="not-analyzed"||Nt(ae,(i==null?void 0:i.jobs)||[])==="out-of-date"||Nt(ae,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(V)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:E.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:E.entities.sort((W,V)=>{var me,we,Te,Ne;const ae=!((me=W.metadata)!=null&&me.notExported)&&!((we=W.metadata)!=null&&we.namedExport),pe=!((Te=V.metadata)!=null&&Te.notExported)&&!((Ne=V.metadata)!=null&&Ne.namedExport);if(ae&&!pe)return-1;if(!ae&&pe)return 1;const xe=W.entityType==="visual"||W.entityType==="library",ie=V.entityType==="visual"||V.entityType==="library";return xe&&!ie?-1:!xe&&ie?1:W.name.localeCompare(V.name)}).map(W=>n(Ui,{entity:W,isActivelyAnalyzing:q(W.sha),isQueued:U(W),onGenerateSimulation:z},W.sha))},E.filePath)})}),L>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 ",L]}),t<L&&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 A2=()=>[{title:"Files & Entities - CodeYam"},{name:"description",content:"Browse your codebase files and entities"}];async function P2({request:e,context:t}){try{const r=new URL(e.url),s=parseInt(r.searchParams.get("page")||"1"),a=r.searchParams.get("filter")||null,o=r.searchParams.get("entityType"),i=t.analysisQueue,l=i?i.getState():{paused:!1,jobs:[]},[c,p]=await Promise.all([$n(),pr()]);return re({entities:c,currentCommit:p,page:s,filter:a,entityType:o,queueState:l})}catch(r){return console.error("Failed to load entities:",r),re({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const T2=et(function(){var w,C,S;const{entities:t,currentCommit:r,page:s,filter:a,entityType:o,queueState:i,error:l}=ot();Rt();const[c,p]=ir(),[u,h]=A(!1);Ot({source:"files-page"});const{handleGenerateSimulation:m,handleGenerateAllSimulations:f,isEntityPending:y,pendingEntityKeys:g}=gp((C=(w=r==null?void 0:r.metadata)==null?void 0:w.currentRun)==null?void 0:C.currentEntityShas,i),x=t||[],b=le(()=>{const k=new Set([]);for(const j of x)k.add(j.filePath??"No File Path");return Array.from(k)},[x]),v=le(()=>{let k=x;return u&&(k=k.filter(j=>{var _;return(_=j.metadata)==null?void 0:_.isUncommitted})),k.sort((j,_)=>{var F,M,$,O,D,T;return(F=j.metadata)!=null&&F.isUncommitted&&!((M=_.metadata)!=null&&M.isUncommitted)?-1:!(($=j.metadata)!=null&&$.isUncommitted)&&((O=_.metadata)!=null&&O.isUncommitted)?1:new Date(((D=_.metadata)==null?void 0:D.editedAt)||0).getTime()-new Date(((T=j.metadata)==null?void 0:T.editedAt)||0).getTime()})},[x,u]),N=le(()=>{var j;const k=new Set([]);for(const _ of x)(j=_.metadata)!=null&&j.isUncommitted&&k.add(_.filePath??"No File Path");return Array.from(k)},[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(j2,{entities:v,page:s,itemsPerPage:50,currentRun:(S=r==null?void 0:r.metadata)==null?void 0:S.currentRun,filter:a,entityType:o,queueState:i,isEntityPending:y,pendingEntityKeys:g,onGenerateSimulation:m,onGenerateAllSimulations:f,totalFilesCount:b.length,totalEntitiesCount:x.length,uncommittedFilesCount:N.length,showOnlyUncommitted:u,onToggleUncommitted:()=>h(!u)})]})})}),M2=Object.freeze(Object.defineProperty({__proto__:null,default:T2,loader:P2,meta:A2},Symbol.toStringTag,{value:"Module"})),$2=()=>[{title:"Labs - CodeYam"},{name:"description",content:"Experimental features"}];async function I2({request:e}){var t;try{const r=await Ye();if(!r)return re({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Project not found"});const{project:s}=await Re(r),a=Ce()||process.cwd(),o=Vu(a)||"";let i="";try{const c=await ia();if(c!=null&&c.webapps&&Array.isArray(c.webapps)){const p=c.webapps.map(u=>u.framework).filter(Boolean);p.length>0&&(i=p.join(", "))}}catch{}const l=ep(r);return re({labs:((t=s.metadata)==null?void 0:t.labs)??null,projectSlug:r,defaultEmail:o,detectedTechStack:i,unlockCode:l,error:null})}catch(r){return console.error("Failed to load labs config:",r),re({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Failed to load labs configuration"})}}async function F2({request:e}){try{const t=await e.formData(),r=t.get("feature"),s=t.get("enabled")==="true";if(!r)return re({success:!1,error:"Missing feature name"},{status:400});const a=await Ye();return a?(r==="clearAccess"?await sr({projectSlug:a,metadataUpdate:{labs:{accessGranted:!1,simulations:!1}}}):await sr({projectSlug:a,metadataUpdate:{labs:{[r]:s}}}),re({success:!0,error:null})):re({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),re({success:!1,error:"Failed to save labs configuration"},{status:500})}}const D2=[{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}],Ic="https://docs.google.com/forms/d/e/1FAIpQLSfopqQOQsjY9S4Ns0l3xDLzGl7iYNpKa2Wn2Xzmtxj8CR1sMA/viewform",R2=[{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 O2({onClose:e}){const t=ye(null),r=ye(0);return ne(()=>{const s=t.current;if(!s)return;const a=100,o=2e3,i=500;let l=null,c=!1;const p=()=>{r.current=Date.now(),!l&&!c&&(l=setInterval(()=>{const u=Date.now()-r.current,h=s.scrollTop>a,m=u>o;h&&m&&(s.scrollTo({top:0,behavior:"smooth"}),c=!0,l&&(clearInterval(l),l=null))},i))};return s.addEventListener("scroll",p,{passive:!0}),()=>{s.removeEventListener("scroll",p),l&&clearInterval(l)}},[]),d("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:s=>{s.target===s.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),d("div",{className:"relative bg-white rounded-xl max-w-3xl w-full mx-4 max-h-[90vh] overflow-hidden",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none z-10",children:"×"}),d("div",{ref:t,className:"overflow-y-auto max-h-[90vh] p-4 md:p-6",children:[d("div",{className:"mb-4",children:[n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Request Early Access"}),n("p",{className:"text-sm text-gray-500",children:"Complete the form below to join the waitlist for CodeYam Labs."})]}),n("div",{className:"bg-white rounded-lg overflow-hidden",children:n("iframe",{src:`${Ic}?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:Ic,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"open the form directly"})]})]})})})})]})]})]})}function L2({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 z2=et(function(){const{labs:t,unlockCode:r,error:s}=ot(),a=Ge(),o=Ge(),i=Ge(),[l,c]=A(""),[p,u]=A(!1),[h,m]=A(!1);Ot({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:D2.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:[p&&n(O2,{onClose:()=>u(!1)}),h&&n(L2,{onClose:()=>m(!1),unlockCodeInput:l,setUnlockCodeInput:c,unlockFetcher:a}),d("div",{className:"flex flex-wrap justify-between items-center gap-3 px-6 sm:px-12 pt-8 pb-4",children:[n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"}),d("div",{className:"flex flex-wrap items-center gap-3",children:[n("button",{onClick:()=>m(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cygray-30 bg-transparent text-cygray-50 cursor-pointer transition-colors hover:border-cyblack-100 hover:text-cyblack-100",children:"Have a Code?"}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cyblack-100 bg-transparent text-cyblack-100 cursor-pointer transition-colors hover:bg-cyblack-100 hover:text-white",children:"Apply for Early Access"})]})]}),d("div",{className:"px-6 sm:px-12 pt-12 pb-8",children:[n("h2",{className:"font-serif text-[24px] sm:text-[32px] leading-snug text-cyblack-100 max-w-xl mb-4 font-normal",children:"Powerful tools for the AI coding era."}),d("p",{className:"text-base sm:text-lg text-cygray-50 leading-relaxed max-w-xl mb-8",children:["We're opening early access to"," ",n("strong",{className:"text-cyblack-100",children:"experimental features"})," to a small group of developers and teams."]}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded bg-primary-200 text-white border-none cursor-pointer transition-colors hover:bg-primary-100",children:"Apply for Early Access"})]}),n("div",{className:"px-6 sm:px-12 py-8",children:n("hr",{className:"border-t border-cygray-30 m-0"})}),d("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:[n("h3",{className:"font-serif text-[22px] sm:text-[28px] text-cyblack-100 mb-10 font-normal text-center",children:"In The Works"}),n("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5 max-w-4xl mx-auto",children:R2.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."})]})})]})}),B2=Object.freeze(Object.defineProperty({__proto__:null,action:F2,default:z2,loader:I2,meta:$2},Symbol.toStringTag,{value:"Module"}));function Y2(e,t,r){const[s,a]=A(()=>new Set),[o,i]=A(()=>new Set),l=ye([]),c=ye([]);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 v=new Set(b);return v.has(y)?v.delete(y):v.add(y),v})},expandAllUncommitted:()=>{a(new Set(t))},collapseAllUncommitted:()=>{a(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function W2(e,t,r){const[s,a]=A(null),[o,i]=A(null),l=Ge();ne(()=>{var h,m;((h=l.data)==null?void 0:h.oldContent)!==void 0&&((m=l.data)==null?void 0:m.newContent)!==void 0&&i({oldContent:l.data.oldContent,newContent:l.data.newContent,fileName:l.data.fileName})},[l.data]);const c=h=>{a({type:"file",path:h}),i(null);const m=new FormData;m.append("actionType","getDiff"),m.append("filePath",h),m.append("diffType","branch"),m.append("baseBranch",e),m.append("currentBranch",t||""),l.submit(m,{method:"post"})},p=(h,m)=>{a({type:"entity",path:h,entitySha:m}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",h),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",m),l.submit(f,{method:"post"})},u=()=>{a(null),i(null)};return{diffView:s,diffContent:o,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:c,handleShowEntityDiff:p,handleCloseDiff:u}}function U2({diffView:e,diffContent:t,isLoading:r,entities:s,onClose:a}){var p;const[o,i]=A(!1),[l,c]=A(!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:"," ",((p=s.find(u=>u.sha===e.entitySha))==null?void 0:p.name)||e.entitySha]})]}),d("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick:a,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:l&&n(ym,{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 J2({files:e,currentBranch:t,defaultBranch:r,baseBranch:s,allBranches:a,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:l,sortOrder:c,onToggleFile:p,onBranchChange:u,onGenerateSimulation:h,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=e.flatMap(([N,{entities:w}])=>{const C=w.filter(S=>i(S.sha)||l(S)).map(S=>S.sha);return C.length>0?[{entityShas:C}]:[]}),b=N=>{const w=N.map(C=>Nt(C,x));return w.includes("analyzing")||w.includes("queued")?"analyzing":w.includes("out-of-date")?"out-of-date":w.includes("not-analyzed")?"not-analyzed":"up-to-date"},v=le(()=>[...e].sort((N,w)=>{const C=N[1].entities.reduce((_,F)=>{var $;const M=(($=F.metadata)==null?void 0:$.editedAt)||F.updatedAt;return M?_?new Date(M)>new Date(_)?M:_:M:_},null),S=w[1].entities.reduce((_,F)=>{var $;const M=(($=F.metadata)==null?void 0:$.editedAt)||F.updatedAt;return M?_?new Date(M)>new Date(_)?M:_:M:_},null);if(!C&&!S)return 0;if(!C)return 1;if(!S)return-1;const k=new Date(C).getTime(),j=new Date(S).getTime();return c==="desc"?j-k:k-j}),[e,c]);return n("div",{children:e.length>0?d("div",{children:[n(Bi,{showActions:!0,sortOrder:c,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:v.map(([N,{status:w,entities:C,isUncommitted:S}])=>{const k=o.has(N),j=b(C),_=C.reduce((O,D)=>{var B;const T=((B=D.metadata)==null?void 0:B.editedAt)||D.updatedAt;return T?O?new Date(T)>new Date(O)?T:O:T:O},null),M=C.filter(O=>O.entityType==="visual"||O.entityType==="library").length===0;let $;return M?$=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):j==="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..."]}):j==="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"}):j==="out-of-date"?$=n("button",{onClick:O=>{O.stopPropagation(),C.filter(D=>(D.entityType==="visual"||D.entityType==="library")&&!i(D.sha)&&!l(D)).forEach(D=>h(D))},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"}):j==="not-analyzed"&&($=n("button",{onClick:O=>{O.stopPropagation(),C.filter(D=>(D.entityType==="visual"||D.entityType==="library")&&!i(D.sha)&&!l(D)).forEach(D=>h(D))},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(Yi,{filePath:N,isExpanded:k,onToggle:()=>p(N),fileStatus:w,isUncommitted:S,simulationPreviews:n(Wi,{entities:C,maxPreviews:1}),entityCount:C.length,state:j,lastModified:_,isNotAnalyzable:M,actionButton:$,children:C.sort((O,D)=>{const T=O.entityType==="visual"||O.entityType==="library",B=D.entityType==="visual"||D.entityType==="library";return T&&!B?-1:!T&&B?1:0}).map(O=>n(Ui,{entity:O,isActivelyAnalyzing:i(O.sha),isQueued:l(O),onGenerateSimulation:h},O.sha))},N)})})]}):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 H2({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:s,isEntityQueued:a,projectSlug:o,baseBranch:i,currentBranch:l,sortOrder:c,onToggleFile:p,onShowFileDiff:u,onGenerateSimulation:h,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=le(()=>{const N=[];return e.forEach(([w,{editedEntities:C}])=>{const S=C.filter(k=>s(k.sha)||a(k)).map(k=>k.sha);S.length>0&&N.push({entityShas:S})}),N},[e,s,a]),b=le(()=>{const N=new Map;return e.forEach(([w,{editedEntities:C}])=>{const S=C.map(F=>Nt(F,x));let k;S.includes("analyzing")||S.includes("queued")?k="analyzing":S.includes("out-of-date")?k="out-of-date":S.includes("not-analyzed")?k="not-analyzed":k="up-to-date";const j=C.reduce((F,M)=>{var O;const $=((O=M.metadata)==null?void 0:O.editedAt)||M.updatedAt;return $&&(!F||new Date($)>new Date(F))?$:F},null),_=C.filter(F=>F.entityType==="visual"||F.entityType==="library").length;N.set(w,{state:k,lastModified:j,analyzableCount:_})}),N},[e,x]),v=le(()=>[...e].sort((N,w)=>{const C=b.get(N[0]),S=b.get(w[0]),k=C==null?void 0:C.lastModified,j=S==null?void 0:S.lastModified;if(!k&&!j)return 0;if(!k)return 1;if(!j)return-1;const _=new Date(k).getTime(),F=new Date(j).getTime();return c==="desc"?F-_:_-F}),[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(Bi,{showActions:!0,sortOrder:c,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:v.map(([N,{status:w,editedEntities:C}])=>{const S=r.has(N),k=b.get(N),{state:j,lastModified:_,analyzableCount:F}=k,M=F===0;let $;return M?$=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):j==="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..."]}):j==="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"}):j==="out-of-date"?$=n("button",{onClick:O=>{O.stopPropagation(),C.filter(D=>(D.entityType==="visual"||D.entityType==="library")&&!s(D.sha)&&!a(D)).forEach(D=>h(D))},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"}):j==="not-analyzed"&&($=n("button",{onClick:O=>{O.stopPropagation(),C.filter(D=>(D.entityType==="visual"||D.entityType==="library")&&!s(D.sha)&&!a(D)).forEach(D=>h(D))},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(Yi,{filePath:N,isExpanded:S,onToggle:()=>p(N),fileStatus:w,simulationPreviews:n(Wi,{entities:C,maxPreviews:1}),entityCount:C.length,state:j,lastModified:_,isNotAnalyzable:M,isUncommitted:!0,actionButton:$,children:C.sort((O,D)=>{const T=O.entityType==="visual"||O.entityType==="library",B=D.entityType==="visual"||D.entityType==="library";return T&&!B?-1:!T&&B?1:0}).map(O=>n(Ui,{entity:O,isActivelyAnalyzing:s(O.sha),isQueued:a(O),onGenerateSimulation:h},O.sha))},N)})})]})}function V2({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 K2=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function G2({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=Ps(s,o,i):c=Wx(s),re({...c,entitySha:l})}return re({error:"Unknown action"},{status:400})}async function q2({request:e,context:t}){try{const r=new URL(e.url),s=r.searchParams.get("compare"),a=r.searchParams.get("viewBranch"),o=t.analysisQueue,i=o?o.getState():{paused:!1,jobs:[]},[l,c,p]=await Promise.all([$n(),pr(),Ye()]),u=fr(),h=Lx(),m=zx(),f=Bx(),y=a||h,g=s||m;let x=[];return y&&y!==g&&(x=Cu(g,y)),re({entities:l||[],gitStatus:u,currentBranch:y,actualCurrentBranch:h,defaultBranch:m,allBranches:f,baseBranch:g,branchDiff:x,currentCommit:c,projectSlug:p,queueState:i})}catch(r){return console.error("Failed to load git data:",r),re({entities:[],gitStatus:[],currentBranch:null,actualCurrentBranch:null,defaultBranch:"main",allBranches:[],baseBranch:"main",branchDiff:[],currentCommit:null,projectSlug:null,queueState:{paused:!1,jobs:[]},error:"Failed to load git data"})}}const Q2=et(function(){var ce,je;const{entities:t,gitStatus:r,currentBranch:s,actualCurrentBranch:a,defaultBranch:o,allBranches:i,baseBranch:l,branchDiff:c,currentCommit:p,projectSlug:u,queueState:h}=ot();Ot({source:"git-page"});const[m,f]=ir(),[y,g]=A(null),[x,b]=A("desc"),[v,N]=A("branch"),w=m.get("expanded")==="true",C=()=>{b(ge=>ge==="desc"?"asc":"desc")},S=Ge(),k=S.data;ne(()=>{s&&l&&s!==l&&S.state==="idle"&&!k&&S.load(`/api/branch-entity-diff?base=${encodeURIComponent(l)}&compare=${encodeURIComponent(s)}`)},[s,l,S,k]);const j=le(()=>{const ge=up(r,t);return Array.from(ge.entries()).sort((ze,Ve)=>ze[0].localeCompare(Ve[0]))},[r,t]),_=le(()=>{const ge=KC(c,t,k);return Array.from(ge.entries()).sort((ze,Ve)=>ze[0].localeCompare(Ve[0]))},[c,t,k]),F=le(()=>GC(r,t),[r,t]),M=le(()=>v==="uncommitted"?j:_,[v,j,_]),$=le(()=>M.map(([ge])=>ge),[M]),{expandedUncommitted:O,setExpandedUncommitted:D,toggleFile:T,expandAllUncommitted:B,collapseAllUncommitted:Y}=Y2(w,$,[]),{diffView:I,diffContent:L,isLoading:P,handleShowFileDiff:R,handleCloseDiff:E}=W2(l,s),J=(ce=p==null?void 0:p.metadata)==null?void 0:ce.currentRun,K=new Set((J==null?void 0:J.currentEntityShas)||[]),Q=new Set(h.jobs.flatMap(ge=>ge.entityShas||[])),q=new Set(((je=h.currentlyExecuting)==null?void 0:je.entityShas)||[]),{isAnalyzing:U,handleGenerateSimulation:z,handleGenerateAllSimulations:W,isEntityBeingAnalyzed:V,isEntityPending:ae}=gp(J==null?void 0:J.currentEntityShas,h),pe=ge=>ae(ge)||Q.has(ge.sha)||q.has(ge.sha),xe=ge=>{ge===(a||s)?m.delete("viewBranch"):m.set("viewBranch",ge),f(m)},ie=ge=>{ge===o?m.delete("compare"):m.set("compare",ge),f(m)},me=()=>{const ze=M.flatMap(([Ve,it])=>it.editedEntities||it.entities||[]).filter(Ve=>!K.has(Ve.sha)&&!Q.has(Ve.sha)&&!q.has(Ve.sha)&&!ae(Ve));W(ze)},we=j.length,Te=_.length,Ne=M.flatMap(([ge,ze])=>ze.editedEntities||ze.entities||[]),_e=Ne.filter(ge=>ge.entityType==="visual"||ge.entityType==="library"),Z=_e.length>0&&_e.every(ge=>K.has(ge.sha)),he=_e.length>0&&!Z&&_e.every(ge=>Q.has(ge.sha)||q.has(ge.sha)),te=U||Z||he,se=Z?"Analyzing...":he?"Queued...":U?"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(V2,{activeTab:v,onTabChange:N,uncommittedCount:we,branchCount:Te})}),s&&v==="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=>xe(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=>ie(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:M.length})," ","modified ",M.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:Ne.length})," ",Ne.length===1?"entity":"entities"]})]}),M.length>0&&d("div",{className:"flex gap-6",children:[d("button",{onClick:B,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(ld,{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(cd,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),d("div",{className:"overflow-hidden",children:[v==="branch"&&s&&n(J2,{files:_,currentBranch:s,defaultBranch:o,baseBranch:l,allBranches:i,expandedFiles:O,isEntityBeingAnalyzed:V,isEntityQueued:pe,sortOrder:x,onToggleFile:ge=>T(ge,O,D),onBranchChange:ie,onGenerateSimulation:z,onSortChange:C,onAnalyzeAll:me,analyzeAllDisabled:te,analyzeAllText:se}),v==="uncommitted"&&n(H2,{files:j,entityImpactMap:F,expandedFiles:O,isEntityBeingAnalyzed:V,isEntityQueued:pe,projectSlug:u,baseBranch:l,currentBranch:s,sortOrder:x,onToggleFile:ge=>T(ge,O,D),onShowFileDiff:R,onGenerateSimulation:z,onSortChange:C,onAnalyzeAll:me,analyzeAllDisabled:te,analyzeAllText:se})]}),I&&n(U2,{diffView:I,diffContent:L,isLoading:P,entities:t,onClose:E}),y&&u&&n(on,{projectSlug:u,onClose:()=>g(null)})]})})}),Z2=Object.freeze(Object.defineProperty({__proto__:null,action:G2,default:Q2,loader:q2,meta:K2},Symbol.toStringTag,{value:"Module"}));function Is(e){const t=e.name.toLowerCase();if(e.name==="Desktop"||e.name==="Full HD"||e.name==="HD")return"desktop";if(e.name==="Laptop"||e.name==="Small Laptop")return"laptop";if(e.name==="Tablet")return"tablet";if(e.name==="Mobile"||t.includes("iphone")||t.includes("pixel")||t.includes("galaxy")||t.includes("phone"))return"mobile";if(t.includes("ipad")||t.includes("tablet"))return"tablet";if(t.includes("laptop"))return"laptop";if(t.includes("desktop"))return"desktop";const r=e.height>e.width;return r&&e.width>=700?"tablet":r?"mobile":e.width>1200?"desktop":"laptop"}const X2=[{name:"Desktop",width:1440,height:900},{name:"Laptop",width:1024,height:768},{name:"Tablet",width:768,height:1024},{name:"Mobile",width:375,height:667}],e5=[{name:"iPhone 16",width:393,height:852},{name:"iPhone 16 Pro Max",width:430,height:932},{name:"iPhone SE",width:375,height:667},{name:"Pixel 8",width:412,height:915},{name:"iPad mini",width:744,height:1133}],yp=[{category:"Desktop",presets:[{name:"Full HD",width:1920,height:1080},{name:"Desktop",width:1440,height:900},{name:"HD",width:1280,height:720}]},{category:"Laptop",presets:[{name:"Laptop",width:1366,height:768},{name:"Small Laptop",width:1024,height:768}]},{category:"Tablet",presets:[{name:'iPad Pro 12.9"',width:1024,height:1366},{name:"iPad Air",width:820,height:1180},{name:"Tablet",width:768,height:1024},{name:"iPad mini",width:744,height:1133}]},{category:"Mobile",presets:[{name:"iPhone 16 Pro Max",width:430,height:932},{name:"iPhone 16",width:393,height:852},{name:"iPhone 14",width:390,height:844},{name:"Mobile",width:375,height:667},{name:"Pixel 8",width:412,height:915},{name:"Galaxy S",width:360,height:800}]}];function xp(e,t){if(e&&Object.keys(e).length>0&&Object.values(e).some(l=>"default"in l))return Object.entries(e).map(([l,c])=>({name:l,width:c.width,height:c.height}));const r=(t==null?void 0:t.includes("mobile-app"))??!1,s=r?e5:X2,a=s.map(l=>{const c=e==null?void 0:e[l.name];return c?{...l,width:c.width,height:c.height}:l});if(!e||r)return a;const o=new Set(s.map(l=>l.name)),i=Object.entries(e).filter(([l])=>!o.has(l)).map(([l,c])=>({name:l,width:c.width,height:c.height}));return[...a,...i]}const _s={width:24,height:76};function t5({width:e,height:t,enabled:r=!0,children:s}){if(!r)return n(ve,{children:s});const a=12,o=48,i=28,l=e+a*2,c=t+o+i;return d("div",{style:{width:`${l}px`,height:`${c}px`,background:"#1a1a1a",borderRadius:"44px",padding:`${o}px ${a}px ${i}px`,position:"relative",boxShadow:"0 0 0 1px rgba(255,255,255,0.08), 0 8px 32px rgba(0,0,0,0.4)"},children:[n("div",{style:{position:"absolute",top:"14px",left:"50%",transform:"translateX(-50%)",width:"100px",height:"24px",background:"#000",borderRadius:"12px"}}),n("div",{style:{width:`${e}px`,height:`${t}px`,borderRadius:"6px",overflow:"hidden",position:"relative"},children:s}),n("div",{style:{position:"absolute",bottom:"10px",left:"50%",transform:"translateX(-50%)",width:"120px",height:"4px",background:"rgba(255,255,255,0.25)",borderRadius:"2px"}})]})}function n5({featureName:e,editorStep:t,editorStepLabel:r,onContinue:s,onStartFresh:a}){const o=oe(i=>{i.key==="Enter"&&(i.preventDefault(),s())},[s]);return ne(()=>(window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)),[o]),n("div",{className:"flex items-center justify-center h-full bg-[#1e1e1e] text-[#d4d4d4]",children:d("div",{className:"max-w-md w-full mx-4 p-6 bg-[#252526] border border-[#3d3d3d] rounded-lg",children:[n("h2",{className:"text-lg font-semibold mb-3 text-white",children:"Resume Previous Session?"}),n("p",{className:"text-sm text-[#999] mb-4",children:"An editor session is still in progress:"}),d("div",{className:"bg-[#1e1e1e] rounded p-3 mb-5 text-sm",children:[e&&d("div",{className:"mb-1",children:[n("span",{className:"text-[#999]",children:"Feature:"})," ",n("span",{className:"text-white",children:e})]}),t!=null&&r&&d("div",{children:[n("span",{className:"text-[#999]",children:"Step:"})," ",d("span",{className:"text-white",children:[t," (",r,")"]})]})]}),n("button",{onClick:s,className:"w-full px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-[#005c75] text-white font-medium hover:bg-[#004d63] ring-2 ring-white/50",children:"Continue Session"}),a&&n("button",{onClick:a,className:"w-full mt-2 px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-transparent text-[#999] hover:text-white hover:bg-[#3d3d3d] border border-[#3d3d3d]",children:"Start Fresh"})]})})}function r5({onStartNextFeature:e,onContinueInSession:t}){const r=oe(s=>{s.key==="Enter"&&(s.preventDefault(),e())},[e]);return ne(()=>(window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)),[r]),n("div",{className:"absolute inset-0 flex items-center justify-center bg-[#1e1e1e]/90 z-10",children:d("div",{className:"max-w-md w-full mx-4 p-6 bg-[#252526] border border-[#3d3d3d] rounded-lg",children:[n("h2",{className:"text-lg font-semibold mb-3 text-white",children:"Feature Complete!"}),n("p",{className:"text-sm text-[#999] mb-5",children:"Your feature has been pushed. What would you like to do next?"}),n("button",{onClick:e,className:"w-full px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-[#005c75] text-white font-medium hover:bg-[#004d63] ring-2 ring-white/50",children:"Start Next Feature"}),n("button",{onClick:t,className:"w-full mt-2 px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-transparent text-[#999] hover:text-white hover:bg-[#3d3d3d] border border-[#3d3d3d]",children:"Continue in Current Session"}),n("p",{className:"text-xs text-[#666] mt-3 text-center",children:"Press Enter to start a new feature with a fresh context"})]})})}const s5={1:"Plan",2:"Prepare",3:"Prototype",4:"Verify Prototype",5:"Confirm",6:"Deconstruct",7:"Extract",8:"Glossary",9:"Analyze",10:"App Scenarios",11:"User Scenarios",12:"Verify",13:"Journal",14:"Review",15:"Present",16:"Commit",17:"Finalize",18:"Push"},a5={1:"Plan the feature and confirm the approach with the user before writing any code.",2:"Prepare the project environment and dependencies for prototyping.",3:"Build a working prototype quickly to validate the concept.",4:"Verify the prototype works correctly and fix any issues.",5:"Confirm the prototype looks right and get user approval to proceed.",6:"Read the code and plan all component and function extractions.",7:"Extract components and functions via TDD — components first, then functions.",8:"Record all extracted functions and components in the glossary.",9:"Analyze imports and verify all components are captured correctly.",10:"Create app-level scenarios that show full pages with realistic data.",11:"Create user-persona scenarios that exercise the app from different perspectives.",12:"Review all screenshots and check for visual errors or regressions.",13:"Create or update the journal entry documenting what was built.",14:"Final review of screenshots, audit for completeness.",15:"Present a summary of all work to the user for approval.",16:"Commit all changes to git.",17:"Update the journal with final details and amend the commit.",18:"Push the branch to the remote repository."},o5={1:"Survey",2:"App Scenarios",3:"Component Scenarios",4:"Preview",5:"Discuss",6:"Decompose",7:"Extract",8:"Recapture",9:"Journal",10:"Present"},i5={1:"Survey the existing codebase to understand pages, components, and dependencies.",2:"Create app-level scenarios showing full pages with realistic data.",3:"Create component-level scenarios for isolated component previews.",4:"Preview all captured scenarios and verify they look correct.",5:"Discuss the migration plan and prioritize which pages to decompose.",6:"Plan the decomposition of pages into clean, reusable components.",7:"Extract components and functions with tests via TDD.",8:"Recapture scenarios after extraction to verify nothing broke.",9:"Document the migration progress in a journal entry.",10:"Present the migration results for review and approval."},l5=18,c5=10;function d5({projectTitle:e,featureName:t,editorStep:r,editorStepLabel:s,migrationMode:a}){const[o,i]=A(!1),[l,c]=A(null),p=ye(null);ne(()=>{if(!o)return;const b=v=>{p.current&&!p.current.contains(v.target)&&i(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[o]);const u=t&&r!=null,h=a==="active",m=h?o5:s5,f=h?i5:a5,y=h?c5:l5,g=u?s||m[r]||"?":null;return d("div",{className:"h-8 shrink-0 flex items-center justify-between px-3 bg-[#2a2a2a] border-b border-[#333] text-xs select-none",children:[d("div",{className:"flex items-center gap-1.5 min-w-0",children:[n("span",{className:"text-[#888] truncate",children:e||"New Project"}),n("span",{className:"text-[#555]",children:">"}),n("span",{className:"text-[#ccc] font-medium truncate",children:t||"New Working Session"})]}),u&&d("div",{className:"relative",ref:p,children:[d("button",{onClick:()=>i(b=>!b),className:"flex items-center gap-1.5 text-[#ccc] hover:text-white transition-colors cursor-pointer",children:[n("span",{className:"text-[#555]",children:"::"}),d("span",{children:["Step ",r,d("span",{className:"text-[#888]",children:[" / ",y]}),":"," ",g]}),n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",className:`transition-transform ${o?"rotate-180":""}`,children:n("path",{d:"M2 4l3 3 3-3"})})]}),o&&n("div",{className:"absolute right-0 top-full mt-1 w-48 bg-[#2d2d2d] border border-[#444] rounded-lg shadow-lg z-30 py-1",children:Array.from({length:y},(b,v)=>v+1).map(b=>{const v=b===r,N=b<r,w=l===b,C=f[b];return d("div",{onClick:()=>c(w?null:b),className:"cursor-pointer",children:[d("div",{className:`w-full px-3 py-1 flex items-center gap-2 text-left transition-colors hover:bg-[#383838] ${v?"text-cygreen font-medium":N?"text-[#ccc]":"text-[#999]"}`,children:[d("span",{className:"w-5 text-right tabular-nums shrink-0",children:[b,"."]}),n("span",{className:"flex-1",children:m[b]||`Step ${b}`}),C&&n("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",className:`shrink-0 opacity-40 transition-transform ${w?"rotate-180":""}`,children:n("path",{d:"M2 4l3 3 3-3"})})]}),w&&C&&n("div",{className:"px-3 pb-1.5 pl-10",children:n("p",{className:"text-[10px] text-[#888] m-0 leading-relaxed",children:C})})]},b)})})]})]})}function Ji(e,t){const[r,s]=A(t??null),[a,o]=A(!1),[i,l]=A((t==null?void 0:t.stale)??!1),c=oe(()=>{e&&(o(!0),fetch(`/api/editor-test-results?testFile=${encodeURIComponent(e)}`).then(p=>p.json()).then(p=>{s(p),l(!1),o(!1)}).catch(()=>{s({testFilePath:e,status:"error",testCases:[],errorMessage:"Failed to fetch test results"}),l(!1),o(!1)}))},[e]);return{results:r,isRunning:a,runTests:c,stale:i}}function or({scenarioId:e,screenshotPath:t,updatedAt:r,alt:s,className:a="",imgClassName:o=""}){const[i,l]=A(!1),p=`/api/editor-scenario-image/${t?t.replace(/^screenshots\//,""):`${e}.png`}${r?`?v=${encodeURIComponent(r)}`:""}`;return ne(()=>{l(!1)},[e,t]),i?n("div",{className:`flex items-center justify-center ${a}`,children:n("span",{className:"text-[8px] text-gray-500",children:"No img"})}):n("div",{className:a,children:n("img",{src:p,alt:s,className:o,loading:"lazy",onError:()=>l(!0)})})}function cn(e){return e.flatMap(t=>{const r=t.screenshotPaths;return r&&Object.keys(r).length>1?Object.entries(r).map(([s,a])=>({scenario:t,dimensionLabel:s,screenshotPath:a,key:`${t.id}--${s}`})):[{scenario:t,dimensionLabel:null,screenshotPath:t.screenshotPath,key:t.id}]})}function Tr({scenarioId:e,screenshotPath:t,updatedAt:r,hasScreenshot:s,imgSrc:a,name:o,dimensionLabel:i,isActive:l,onSelect:c}){const p=e&&s,u=!e&&a;return d("button",{onClick:c,className:"flex flex-col items-center gap-1 cursor-pointer group w-full",title:i?`${o} (${i})`:o,children:[d("div",{className:`w-full aspect-[16/10] rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] relative ${l?"border-[#D7FF63]/40 ring-1 ring-[#D7FF63]/20":"border-transparent hover:border-[#4d4d4d]"}`,children:[p?n(or,{scenarioId:e,screenshotPath:t,updatedAt:r,alt:i?`${o} (${i})`:o,className:"w-full h-full",imgClassName:"w-full h-full object-contain"}):u?n("img",{src:a,alt:o,className:"w-full h-full object-contain",loading:"lazy"}):n("div",{className:"w-full h-full bg-[#1a1a1a] flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})}),i&&n("span",{className:"absolute bottom-1 right-1 text-[8px] font-medium bg-black/60 text-white px-1 py-0.5 rounded",children:i})]}),n("span",{className:`text-[10px] leading-tight text-center truncate w-full ${l?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:i?`${o} (${i})`:o})]})}function mo({testFile:e,entityName:t,cachedResult:r}){const{results:s,isRunning:a,runTests:o,stale:i}=Ji(e,r);if(a&&!s)return d("div",{className:"px-2 pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!s)return null;if(s.status==="error")return n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-red-400",children:s.errorMessage})});const l=t?s.testCases.filter(u=>u.fullName.startsWith(t)):s.testCases,c=l.length>0?l:s.testCases;if(c.length===0)return null;const p=t?`${t} > `:"";return d("div",{className:"px-2 pt-1 space-y-0.5",children:[c.map(u=>{var m;const h=p&&u.fullName.startsWith(p)?u.fullName.slice(p.length):u.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[u.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):u.status==="failed"?n("span",{className:"text-red-400 text-[10px]",children:"✗"}):n("span",{className:"text-gray-500 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${u.status==="passed"?"text-green-400":u.status==="failed"?"text-red-400":"text-gray-500"}`,children:h})]}),u.status==="failed"&&((m=u.failureMessages)==null?void 0:m.map((f,y)=>n("div",{className:"pl-4 text-[9px] text-red-300/70 truncate max-w-full",title:f,children:f.split(`
597
- `)[0]},y)))]},u.fullName)}),d("div",{className:"flex items-center gap-2 mt-1",children:[n("button",{onClick:o,disabled:a,className:"text-[10px] text-[#00a0c4] hover:text-[#00c4ee] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:a?"Running...":i?"Re-run (stale)":"Re-run"}),i&&!a&&n("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0",title:"Source or test file changed since last run"})]})]})}function Mr({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(pt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function u5({scenarios:e,projectRoot:t,activeScenarioId:r,onScenarioSelect:s,zoomComponent:a,focusedEntity:o,onZoomChange:i,analyzedEntities:l=[],glossaryFunctions:c=[],cachedTestResults:p={},activeAnalyzedScenarioId:u,onAnalyzedScenarioSelect:h,entityImports:m,pageFilePaths:f={},onSwitchToBuild:y,entityShaMap:g,structureTab:x="application",onStructureTabChange:b}){const[v,N]=A(""),[w,C]=A(x),S=b?x:w,k=b||C,{pageGroups:j,componentGroups:_}=le(()=>{var R;const I=new Map,L=new Map;for(const E of e)if(E.componentName){const J=L.get(E.componentName)||[];J.push(E),L.set(E.componentName,J)}else if(ma(E.url)){const J=(R=E.url)==null?void 0:R.match(/[?&]c=([^&]+)/),K=J?decodeURIComponent(J[1]):"Isolated",Q=L.get(K)||[];Q.push(E),L.set(K,Q)}else{const J=E.pageFilePath?Lt(jt(E.pageFilePath)):yt(E.url),K=I.get(J)||[];K.push(E),I.set(J,K)}const P=new Map([...L.entries()].sort(([E],[J])=>E.localeCompare(J)));return{pageGroups:I,componentGroups:P}},[e]),F=le(()=>{const I=new Set((l||[]).filter(P=>P.entityType==="visual").map(P=>P.name)),L=new Map;for(const[P,R]of _)I.has(P)||L.set(P,R);return L},[_,l]),{visualEntities:M,libraryEntities:$}=le(()=>{const I=l.filter(P=>P.entityType==="visual").sort((P,R)=>P.name.localeCompare(R.name)),L=l.filter(P=>P.entityType==="library"||P.entityType==="functionCall").sort((P,R)=>P.name.localeCompare(R.name));return{visualEntities:I,libraryEntities:L}},[l]),O=le(()=>{const I=new Set($.map(L=>L.name));return c.filter(L=>!I.has(L.name)).sort((L,P)=>L.name.localeCompare(P.name))},[c,$]),D=l.some(I=>I.isAnalyzing),T=ye(null),B=ye(0),Y=oe(()=>{T.current&&(B.current=T.current.scrollTop)},[]);if(ne(()=>{T.current&&B.current>0&&(T.current.scrollTop=B.current)}),e.length===0&&l.length===0&&O.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:d("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No scenarios yet"}),n("p",{className:"text-xs",children:"Scenarios will appear here as Claude creates them alongside your code. Each scenario represents a different state of your app's data."})]})});if(a&&o){const I=o.name,L=o.filePath,P=o.sha,R=e.filter(q=>q.componentName===I||q.componentPath===L||!q.componentName&&(q.pageFilePath===L||P&&q.entitySha===P)),E=new Set((m==null?void 0:m[I])||[]),J=E.size>0,K=J?M.filter(q=>E.has(q.name)):[],Q=J?$.filter(q=>E.has(q.name)):[];return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-1",children:[d("button",{onClick:()=>i(void 0),className:"w-full flex items-center gap-2 px-3 py-1.5 text-xs text-gray-400 hover:text-white transition-colors cursor-pointer",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M7.5 9L4.5 6L7.5 3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"All scenarios"]}),n("div",{className:"px-3 py-1.5",children:n("span",{className:"text-xs font-semibold text-white uppercase tracking-wider",children:o.displayName})}),n("div",{className:"flex flex-wrap gap-2 px-2",children:R.length===0?n("div",{className:"px-3 py-2 text-xs text-gray-500",children:"No scenarios for this component"}):cn(R).map(({scenario:q,dimensionLabel:U,screenshotPath:z,key:W})=>n(Tr,{scenarioId:q.id,screenshotPath:z,updatedAt:q.updatedAt,hasScreenshot:!!z,name:q.name,dimensionLabel:U,isActive:q.id===r,onSelect:()=>s(q,U??void 0)},W))}),K.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"})}),K.map(q=>d("div",{className:"mt-2",children:[n("div",{className:"flex items-center gap-2 px-2 py-1",children:n("button",{onClick:()=>i(q.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:q.name})}),n(Mr,{filePath:q.filePath,projectRoot:t}),(q.scenarios.length>0||q.pendingScenarios.length>0)&&n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:q.scenarios.map(U=>n(Tr,{imgSrc:U.screenshotPath?`/api/screenshot/${U.screenshotPath}`:null,name:U.name,isActive:U.id===u,onSelect:()=>h==null?void 0:h({analysisId:q.analysisId,scenarioId:U.id,scenarioName:U.name,entitySha:q.sha,entityName:q.name})},U.id))})]},q.sha))]}),Q.length>0&&d("div",{className:"pt-2 mt-1",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),Q.map(q=>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:q.name})}),n(Mr,{filePath:q.filePath,projectRoot:t}),q.testFile&&n(mo,{testFile:q.testFile,entityName:q.name,cachedResult:p[q.testFile]})]},q.sha))]})]})})}return n("div",{ref:T,onScroll:Y,className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:d("div",{className:"p-4 space-y-4",children:[d("div",{className:"flex items-center gap-3 font-['IBM_Plex_Mono']",children:[n("button",{onClick:()=>k("application"),className:`text-xs font-bold uppercase tracking-wider shrink-0 bg-transparent border-none cursor-pointer p-0 transition-colors ${S==="application"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:"Application"}),n("button",{onClick:()=>k("components"),className:`text-xs font-bold uppercase tracking-wider shrink-0 bg-transparent border-none cursor-pointer p-0 transition-colors ${S==="components"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:"Components"}),n("div",{className:"flex-1"}),d("div",{className:"relative",style:{width:170},children:[d("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"11",cy:"11",r:"8"}),n("path",{d:"M21 21l-4.35-4.35"})]}),n("input",{type:"text",placeholder:"SEARCH...",value:v,onChange:I=>N(I.target.value),className:"w-full pl-9 pr-3 py-2 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded-md text-gray-300 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors tracking-wider"})]}),y&&d("button",{onClick:y,className:"flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer shrink-0 uppercase tracking-wider",children:[n("span",{children:"+"})," New Feature"]})]}),n("div",{className:"border-b border-[#2d2d2d]"}),S==="application"&&j.size>0&&n("div",{children:[...j.entries()].sort(([I],[L])=>I==="Home"?-1:L==="Home"?1:I.localeCompare(L)).filter(([I])=>v.trim()?I.toLowerCase().includes(v.trim().toLowerCase()):!0).map(([I,L])=>{const P=L.some(R=>R.id===r&&!u);return d("div",{className:"mt-3",children:[d("div",{className:"flex items-center gap-1.5 py-1",children:[d("button",{onClick:()=>i(I,g==null?void 0:g.get(I)),className:`flex items-center gap-1.5 text-sm font-normal cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0 ${P?"text-[#D7FF63]":"text-gray-300"}`,children:[I,d("span",{className:`text-xs ${P?"text-[#D7FF63]/60":"text-gray-500"}`,children:["(",L.length,")"]}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:P?"text-[#D7FF63]/60":"text-gray-500",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),P&&d("div",{className:"flex items-center gap-1 ml-auto",children:[n("button",{onClick:()=>i(I,g==null?void 0:g.get(I)),className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Edit scenarios",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),y&&n("button",{onClick:y,className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Add scenario",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]})]}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:cn(L).map(({scenario:R,dimensionLabel:E,screenshotPath:J,key:K})=>n(Tr,{scenarioId:R.id,screenshotPath:J,updatedAt:R.updatedAt,hasScreenshot:!!J,name:R.name,dimensionLabel:E,isActive:R.id===r&&!u,onSelect:()=>s(R,E??void 0)},K))})]},I)})}),S==="components"&&F.size>0&&n("div",{children:[...F.entries()].filter(([I])=>v.trim()?I.toLowerCase().includes(v.trim().toLowerCase()):!0).map(([I,L])=>{const P=L.some(R=>R.id===r&&!u);return d("div",{className:"mt-3",children:[d("div",{className:"flex items-center gap-1.5 py-1",children:[d("button",{onClick:()=>i(I,g==null?void 0:g.get(I)),className:`flex items-center gap-1.5 text-sm font-normal cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0 ${P?"text-[#D7FF63]":"text-gray-300"}`,children:[I,d("span",{className:`text-xs ${P?"text-[#D7FF63]/60":"text-gray-500"}`,children:["(",L.length,")"]}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:P?"text-[#D7FF63]/60":"text-gray-500",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),P&&d("div",{className:"flex items-center gap-1 ml-auto",children:[n("button",{onClick:()=>i(I,g==null?void 0:g.get(I)),className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Edit scenarios",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),y&&n("button",{onClick:y,className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Add scenario",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]})]}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:cn(L).map(({scenario:R,dimensionLabel:E,screenshotPath:J,key:K})=>n(Tr,{scenarioId:R.id,screenshotPath:J,updatedAt:R.updatedAt,hasScreenshot:!!J,name:R.name,dimensionLabel:E,isActive:R.id===r&&!u,onSelect:()=>s(R,E??void 0)},K))})]},I)})}),M.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"}),D&&e.length===0&&l.every(I=>I.scenarioCount===0)&&n("span",{className:"ml-2 text-[10px] text-gray-500",children:"— Entities are being analyzed..."})]}),M.map(I=>d("div",{className:"mt-2",children:[d("div",{className:"flex items-center gap-2 px-2 py-1",children:[n("button",{onClick:()=>i(I.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:I.name}),I.isAnalyzing&&I.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(Mr,{filePath:I.filePath,projectRoot:t}),(I.scenarios.length>0||I.pendingScenarios.length>0)&&d("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:[I.scenarios.map(L=>n(Tr,{imgSrc:L.screenshotPath?`/api/screenshot/${L.screenshotPath}`:null,name:L.name,isActive:L.id===u,onSelect:()=>h==null?void 0:h({analysisId:I.analysisId,scenarioId:L.id,scenarioName:L.name,entitySha:I.sha,entityName:I.name})},L.id)),I.pendingScenarios.map(L=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:L,children:L},L))]})]},I.sha))]}),($.length>0||O.length>0)&&d("div",{className:`pt-2 mt-1 ${M.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"})}),$.map(I=>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:I.name}),I.isAnalyzing&&I.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(Mr,{filePath:I.filePath,projectRoot:t}),I.testFile?n(mo,{testFile:I.testFile,entityName:I.name,cachedResult:p[I.testFile]}):n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},I.sha)),O.map(I=>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:I.name})}),n(Mr,{filePath:I.filePath,projectRoot:t}),n(mo,{testFile:I.testFile,entityName:I.name,cachedResult:p[I.testFile]})]},I.name))]})]})})}function bp(e){const t={};for(const[r,s]of Object.entries(e))if(typeof s=="string")try{const a=JSON.parse(s);Array.isArray(a)?t[r]=a:typeof a=="object"&&a!==null&&(t[r]=[a])}catch{}else Array.isArray(s)&&(t[r]=s);return t}function vp(e,t){return e.length===0||t.length===0?!1:e.filter(s=>t.includes(s)).length>=Math.min(e.length,t.length)*.5}function p5(e,t){const{_metadata:r,...s}=t,a=s.localStorage&&typeof s.localStorage=="object"&&!Array.isArray(s.localStorage)?bp(s.localStorage):{},o={};if(s.seed&&typeof s.seed=="object"&&!Array.isArray(s.seed))for(const[h,m]of Object.entries(s.seed))Array.isArray(m)&&(o[h]=m);const i={},l=[],c=new Set,p=new Set,u=new Set;for(const h of e){const m=h.fields.filter(b=>!b.isRelation),f=m.map(b=>b.name),y=h.name.charAt(0).toLowerCase()+h.name.slice(1);let g=null,x=[];for(const b of[h.name,y,`${y}s`])if(b in s&&Array.isArray(s[b])){g=b,x=s[b],p.add(b);break}if(!g){for(const b of[h.name,y,`${y}s`])if(b in o){g=b,x=o[b],u.add(b),b in a&&c.add(b);break}}if(!g){for(const b of[h.name,y,`${y}s`])if(b in a){g=y,x=a[b],c.add(b);break}}if(!g){for(const[b,v]of Object.entries(a))if(!c.has(b)&&v.length>0&&vp(f,Object.keys(v[0]))){g=y,x=v,c.add(b);break}}g||(g=y),i[g]=x,l.push({label:h.name,dataKey:g,schemaFields:m.map(b=>({name:b.name,type:b.type,isId:b.isId}))})}for(const[h,m]of Object.entries(s))h==="_metadata"||h==="localStorage"||h==="seed"||h==="type"||p.has(h)||Array.isArray(m)&&(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(o))u.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(a))c.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));return{data:i,tabs:l}}function h5(e){return e==null?"null":typeof e=="number"?Number.isInteger(e)?"int4":"float":typeof e=="boolean"?"bool":typeof e=="object"?Array.isArray(e)?"array":"json":"text"}function m5(e,t){return e.length>0?Object.keys(e[0]):t?t.map(r=>r.name):[]}function f5(e,t,r){const s=new Map((r||[]).map(o=>[o.name,o.type])),a={};for(const o of e)a[o]=s.get(o)||(t.length>0?h5(t[0][o]):"text");return a}function g5(e,t){var r;return((r=t==null?void 0:t.find(s=>s.isId))==null?void 0:r.name)||e.find(s=>s==="id")||null}function y5(e,t){const{_metadata:r,...s}=t,a=s.localStorage&&typeof s.localStorage=="object"&&!Array.isArray(s.localStorage)?bp(s.localStorage):{},o={};if(s.seed&&typeof s.seed=="object"&&!Array.isArray(s.seed))for(const[h,m]of Object.entries(s.seed))Array.isArray(m)&&(o[h]=m);const i={},l=[],c=new Set,p=new Set,u=new Set;for(const h of e){const m=h.name.charAt(0).toLowerCase()+h.name.slice(1),f=h.fields.map(x=>x.name);let y=null,g=[];for(const x of[h.name,m,`${m}s`])if(x in s&&Array.isArray(s[x])){y=x,g=s[x],p.add(x);break}if(!y){for(const x of[h.name,m,`${m}s`])if(x in o){y=x,g=o[x],u.add(x),x in a&&c.add(x);break}}if(!y){for(const x of[h.name,m,`${m}s`])if(x in a){y=m,g=a[x],c.add(x);break}}if(!y){for(const[x,b]of Object.entries(a))if(!c.has(x)&&b.length>0&&vp(f,Object.keys(b[0]))){y=m,g=b,c.add(x);break}}y||(y=m),i[y]=g,l.push({label:h.name,dataKey:y,category:h.category,description:h.description,schemaFields:h.fields.map(x=>({name:x.name,type:x.type,isId:x.isId??!1}))})}for(const[h,m]of Object.entries(s))h==="_metadata"||h==="localStorage"||h==="seed"||h==="type"||p.has(h)||Array.isArray(m)&&(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(o))u.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(a))c.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));return{data:i,tabs:l}}function Hi(e){var a,o;const t=new Map,r=new Map;for(const i of e)if(i.componentName){const l=r.get(i.componentName)||[];l.push(i),r.set(i.componentName,l)}else if(ma(i.url)){const l=(a=i.url)==null?void 0:a.match(/[?&]c=([^&]+)/),c=l?decodeURIComponent(l[1]):"Isolated",p=r.get(c)||[];p.push(i),r.set(c,p)}else{const l=i.displayName||((o=i.pageFilePath)!=null&&o.startsWith("app/")?Lt(jt(i.pageFilePath)):yt(i.url)),c=t.get(l)||[];c.push(i),t.set(l,c)}const s=new Map([...r.entries()].sort(([i],[l])=>i.localeCompare(l)));return{pageGroups:t,componentGroups:s}}function wp(e,t){var s,a;const r=new Map;for(const[o,i]of e){const l=(s=i.find(c=>c.entitySha))==null?void 0:s.entitySha;l&&r.set(o,l)}for(const[o,i]of t){const l=(a=i.find(c=>c.entitySha))==null?void 0:a.entitySha;l&&r.set(o,l)}return r}function x5(e){const t=new Set;for(const[r,s]of Object.entries(e)){t.add(r);for(const a of s)t.add(a)}return t}function b5(e,t,r,s){if(t.has(e))return!0;const a=r.find(o=>o.sha===e);return a?s.has(a.name):!1}function v5(e,t,r,s){const a=[];for(const[o,i]of e){const l=r.get(o);l?s(l)||a.push({name:o,scenarios:i,reason:"incomplete"}):a.push({name:o,scenarios:i,reason:"missing"})}for(const[o,i]of t){const l=r.get(o);l?s(l)||a.push({name:o,scenarios:i,reason:"incomplete"}):a.push({name:o,scenarios:i,reason:"missing"})}return a}function Fc(e,t,r){if(!e)return null;const s=t.find(a=>a.sha===e);return s?{sha:e,name:s.name,filePath:s.filePath,entityType:s.entityType,displayName:s.name}:null}const Dc=120;function Np({text:e,theme:t}){const[r,s]=A(!1),a=e.length>Dc,o=a&&!r?e.slice(0,Dc)+"…":e,i=t==="light";return d("div",{className:`px-4 py-2 ${i?"border-b border-gray-200 bg-gray-50":"border-b border-[#3d3d3d] bg-[#252525]"}`,children:[n("span",{className:"text-[9px] font-semibold uppercase tracking-wider text-gray-500",children:"User Prompt"}),d("p",{className:`text-[11px] mt-0.5 mb-0 leading-relaxed ${i?"text-gray-600":"text-gray-400"}`,children:[o,a&&n("button",{onClick:()=>s(!r),className:`ml-1 text-[11px] font-medium bg-transparent border-none p-0 cursor-pointer ${i?"text-blue-500 hover:text-blue-700":"text-[#00a0c4] hover:text-[#00c0e8]"}`,children:r?"Show less":"Read more…"})]})]})}const Rc={new:0,edited:1,impacted:2};function Oc({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 Lc({filePath:e}){const[t,r]=A(null),[s,a]=A(!0),[o,i]=A(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 zc({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(ve,{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(ve,{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 Bc({scenarioId:e,screenshotPath:t,name:r,dimensionLabel:s,isActive:a,onSelect:o,updatedAt:i}){const l=ye(null);return ne(()=>{a&&l.current&&l.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[a]),d("button",{ref:l,onClick:o,className:"flex flex-col items-center gap-1.5 cursor-pointer group",title:s?`${r} (${s})`:r,children:[d("div",{className:`w-32 h-32 rounded-lg overflow-hidden border-2 transition-all relative ${a?"border-[#0ea5e9] ring-2 ring-[#0ea5e9]/40 shadow-lg shadow-[#0ea5e9]/20":"border-gray-200 hover:border-gray-400 shadow-sm"}`,children:[n(or,{scenarioId:e,screenshotPath:t,updatedAt:i,alt:s?`${r} (${s})`:r,className:"w-full h-full bg-white",imgClassName:"w-full h-full object-contain bg-white"}),s&&n("span",{className:"absolute bottom-1 right-1 text-[9px] font-medium bg-black/60 text-white px-1.5 py-0.5 rounded",children:s})]}),n("span",{className:`text-[11px] leading-tight text-center truncate w-32 font-medium ${a?"text-gray-900":"text-gray-600 group-hover:text-gray-900"}`,children:s?`${r} (${s})`:r})]})}function w5({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(pt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-400 hover:text-gray-600 transition-colors"})]}):null}function Oo({testFile:e,entityName:t,cachedResult:r}){const{results:s,isRunning:a,runTests:o,stale:i}=Ji(e,r);if(a&&!s)return d("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#0ea5e9] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!s)return null;if(s.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-500",children:s.errorMessage})});const l=t?s.testCases.filter(u=>u.fullName.startsWith(t)):s.testCases,c=l.length>0?l:s.testCases;if(c.length===0)return null;const p=t?`${t} > `:"";return d("div",{className:"pt-1 space-y-0.5",children:[c.map(u=>{var m;const h=p&&u.fullName.startsWith(p)?u.fullName.slice(p.length):u.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[u.status==="passed"?n("span",{className:"text-green-600 text-[10px]",children:"✓"}):u.status==="failed"?n("span",{className:"text-red-500 text-[10px]",children:"✗"}):n("span",{className:"text-gray-400 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${u.status==="passed"?"text-green-600":u.status==="failed"?"text-red-500":"text-gray-400"}`,children:h})]}),u.status==="failed"&&((m=u.failureMessages)==null?void 0:m.map((f,y)=>n("div",{className:"pl-4 text-[9px] text-red-400 truncate max-w-full",title:f,children:f.split(`
598
- `)[0]},y)))]},u.fullName)}),d("div",{className:"flex items-center gap-2 mt-1",children:[n("button",{onClick:o,disabled:a,className:"text-[10px] text-[#0ea5e9] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:a?"Running...":i?"Re-run (stale)":"Re-run"}),i&&!a&&n("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0",title:"Source or test file changed since last run"})]})]})}function Yc(e){const t=e.indexOf(" - ");return t!==-1?e.slice(t+3):e}function Wc(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=(Rc[a]??2)-(Rc[o]??2);return i!==0?i:r.localeCompare(s)})}function N5({scenarios:e,allScenarios:t=[],glossaryFunctions:r=[],cachedTestResults:s={},projectRoot:a,activeScenarioId:o,onScenarioSelect:i,onClose:l,entityChangeStatus:c={},modifiedFiles:p=[],featureName:u,userPrompt:h}){const m=le(()=>{if(t.length===0||Object.keys(c).length===0)return e;const F=new Set(e.map($=>$.id)),M=t.filter($=>{var D,T;if(F.has($.id))return!1;const O=$.componentName||$.displayName||((D=$.pageFilePath)!=null&&D.startsWith("app/")?Lt(jt($.pageFilePath)):yt($.url));return((T=c[O])==null?void 0:T.status)==="impacted"});return M.length===0?e:[...e,...M]},[e,t,c]),f=le(()=>Object.entries(c).filter(([,F])=>F.status==="new"||F.status==="edited").map(([F,M])=>({name:F,status:M.status})),[c]),[y,g]=A(null),x=oe(F=>{g(M=>M===F?null:F)},[]),{pageGroups:b,componentGroups:v}=le(()=>Hi(m),[m]),N=le(()=>Wc([...b.entries()],c),[b,c]),w=le(()=>Wc([...v.entries()],c),[v,c]),C=N,S=w,k=le(()=>G0(r,c),[r,c]),j=le(()=>{const F=[];for(const[,M]of C)F.push(...M);for(const[,M]of S)F.push(...M);return F},[C,S]),_=ye(!1);return ne(()=>{_.current||j.length!==0&&(_.current=!0,console.log("[ResultsPanel] Auto-selecting first scenario: %s",j[0].name),i(j[0]))},[j,i]),ne(()=>{if(j.length===0)return;const F=M=>{if(M.key!=="ArrowLeft"&&M.key!=="ArrowRight")return;const $=M.target,O=$==null?void 0:$.tagName;if(O==="INPUT"||O==="SELECT"||O==="TEXTAREA"&&!$.classList.contains("xterm-helper-textarea"))return;M.preventDefault();const D=j.findIndex(B=>B.id===o);let T;M.key==="ArrowLeft"?T=D<=0?j.length-1:D-1:T=D>=j.length-1?0:D+1,i(j[T])};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[j,o,i]),m.length===0&&r.length===0?d("div",{className:"h-full bg-white flex items-center justify-center relative",children:[n("button",{onClick:l,className:"absolute top-2 right-3 text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none",title:"Close results",children:"×"}),n("span",{className:"text-sm text-gray-400",children:"No scenarios registered yet"})]}):d("div",{className:"h-full bg-white flex flex-col overflow-hidden",children:[d("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-gray-200 shrink-0",children:[d("div",{className:"min-w-0",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Working Session Results"}),u&&n("div",{className:"text-[11px] text-gray-400 truncate",title:u,children:u})]}),n("button",{onClick:l,className:"text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none shrink-0",title:"Close results",children:"×"})]}),h&&n(Np,{text:h,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(([F,M])=>{var T;const $=c[F],O=y===F,D=(T=M[0])==null?void 0:T.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:F}),$&&n(Oc,{status:$,onClick:()=>x(F)})]}),O&&($==null?void 0:$.status)==="edited"&&D&&n(Lc,{filePath:D}),O&&($==null?void 0:$.status)==="impacted"&&n(zc,{impactedBy:$.impactedBy,changedEntities:f}),n("div",{className:"flex flex-wrap gap-3",children:cn(M).map(({scenario:B,dimensionLabel:Y,screenshotPath:I,key:L})=>n(Bc,{scenarioId:B.id,screenshotPath:I,name:Yc(B.name),dimensionLabel:Y,isActive:B.id===o,onSelect:()=>i(B,Y??void 0),updatedAt:B.updatedAt},L))})]},F)})})]}),S.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:S.map(([F,M])=>{var T;const $=c[F],O=y===F,D=(T=M[0])==null?void 0:T.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:F}),$&&n(Oc,{status:$,onClick:()=>x(F)})]}),O&&($==null?void 0:$.status)==="edited"&&D&&n(Lc,{filePath:D}),O&&($==null?void 0:$.status)==="impacted"&&n(zc,{impactedBy:$.impactedBy,changedEntities:f}),n("div",{className:"flex flex-wrap gap-3",children:cn(M).map(({scenario:B,dimensionLabel:Y,screenshotPath:I,key:L})=>n(Bc,{scenarioId:B.id,screenshotPath:I,name:Yc(B.name),dimensionLabel:Y,isActive:B.id===o,onSelect:()=>i(B,Y??void 0),updatedAt:B.updatedAt},L))})]},F)})})]}),k.length>0&&d("div",{className:C.length>0||S.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),n("div",{className:"space-y-2 pl-1",children:k.map(F=>d("div",{children:[n("div",{className:"flex items-center gap-2",children:n("span",{className:"text-[11px] font-medium text-gray-700",children:F.name})}),n(w5,{filePath:F.filePath,projectRoot:a}),F.testFile?n(Oo,{testFile:F.testFile,entityName:F.name,cachedResult:s[F.testFile]}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-400",children:"No test file"})})]},F.name))})]}),p.length>0&&d("div",{className:C.length>0||S.length>0||k.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:d("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:["Modified Files (",p.length,")"]})}),n("div",{className:"space-y-0.5 pl-1 max-h-[200px] overflow-auto",children:p.map(F=>d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold uppercase w-[14px] text-center ${F.status==="added"||F.status==="untracked"?"text-green-600":F.status==="modified"?"text-blue-600":F.status==="renamed"?"text-purple-600":"text-gray-400"}`,children:F.status==="added"||F.status==="untracked"?"A":F.status==="modified"?"M":F.status==="renamed"?"R":"?"}),n("span",{className:"text-[10px] text-gray-500 truncate font-mono",children:F.path})]},F.path))})]})]})})]})}function Uc(e,t,r,s){var c;const a=s.length>0?s.map(p=>`- "${p.name}" (ID: ${p.id})${p.url?` — URL: ${p.url}`:""}`).join(`
599
- `):"(no scenarios yet)",o=t.endsWith("/page.tsx")||t.endsWith("/page.js"),i=((c=s.find(p=>p.url))==null?void 0:c.url)||"/",l=[`You are helping edit scenarios for the "${e}" entity in a CodeYam project.`,"","## Entity",`- **Name:** ${e}`,`- **File:** ${t}`,`- **Type:** ${o?"Page (application scenario with seed data)":"Component (component scenario with mock props)"}`,"","## Existing Scenarios",a,""];return o?l.push("## How Seed Data Works","","Application scenarios use `seed` data to populate the database before the page is captured.","The seed is a JSON object where each key is a Prisma model name in camelCase singular (matching the Prisma client accessor name) and the value is an array of records.","","### Seed Key Naming Convention","The key must be the camelCase singular form of the Prisma model name:",'- `model User` → key `"user"`','- `model BlogPost` → key `"blogPost"`','- `model Feedback` → key `"feedback"`',"",'**WARNING:** Do NOT use plural forms like "users", "blogPosts", or "feedbacks" — the seed adapter will silently fail to match them.',"","To understand the data models, read the Prisma schema at `prisma/schema.prisma`.","To see examples of existing seed data, look at `.codeyam/editor-scenarios/*.seed.json` files.","",`Also read the source file at \`${t}\` to understand what data the page queries and renders.`,"","## Registering a Scenario","","For small seed data, pass it inline:","```",`codeyam editor register '{"name":"Scenario Name","type":"application","url":"${i}","dimensions":["Laptop"],"seed":{"user":[...],"feedback":[...]}}'`,"```","","For large seed data, write it to a temp file and use @file syntax:","```","# Write JSON to a temp file","cat > .codeyam/tmp/scenario.json << 'SCENARIO_EOF'",`{"name":"Scenario Name","type":"application","url":"${i}","dimensions":["Laptop"],"seed":{"user":[...],"feedback":[...]}}`,"SCENARIO_EOF","codeyam editor register @.codeyam/tmp/scenario.json","```"):l.push("## Registering a Scenario","",`Read the source file at \`${t}\` to understand what props the component expects.`,"","```",`codeyam editor register '{"name":"Scenario Name","type":"component","componentName":"${e}","componentPath":"${t}","dimensions":["Laptop"],"mockData":{"propName":"value"}}'`,"```"),l.push("","## Deleting a Scenario","","To delete a scenario, use its ID from the list above:","```","codeyam editor delete <scenarioId>","```","","## Validating Seed Data","","Before registering, you can validate seed data structure and check that keys match Prisma models:","```",`codeyam editor validate-seed '{"user":[...]}'`,"```"),l.push("","## Recapturing Scenarios After Code Changes","",`If the user asks you to modify the code for this ${o?"page":"component"} (CSS, layout, logic, etc.), you MUST re-register all existing scenarios after the code change so their screenshots are updated.`,"","Re-registering a scenario with the same name overwrites it and captures a fresh screenshot.","","To recapture, re-register each existing scenario using `codeyam editor register` with its current configuration. You can read the scenario JSON files in `.codeyam/editor-scenarios/` to get the exact registration data for each scenario."),l.push("","## Important","- DO NOT take any action until the user tells you what they want","- Start by briefly listing the existing scenarios",'- Then ask: "Would you like to modify an existing scenario or add a new one?"',"- Wait for the user's answer before proceeding",'- Keep scenario names descriptive: "Empty State", "With Comments", "Admin View", etc.',`- Each scenario should capture a distinct, meaningful state of the ${o?"page":"component"}`),l.join(`
600
- `)}function Sp(e,t){var a;const r=t.some(o=>!o.componentName),s=t.map(o=>`'${o.id}'`).join(", ");if(r){const o=((a=t.find(l=>l.url))==null?void 0:a.url)||null,i=t.map(l=>`.codeyam/editor-scenarios/${l.id}.json`).join(", ");return[`### Page: "${e}" (${t.length} scenario(s))`,...o?["",`Scenario URL: \`${o}\``]:[],"",...o?["Step A: Find the source file that renders this page. In Next.js App Router, URLs map to page.tsx files:"," - `/` → `app/page.tsx`"," - `/about` → `app/about/page.tsx`"," - `/c/my-slug` → `app/c/[slug]/page.tsx` (dynamic segment)","",`Based on the URL \`${o}\`, find the corresponding page.tsx file. Confirm it exists with \`cat <filepath> | head -5\`.`]:["Step A: Find the source file that renders this page by running:",' find src app -name "App.tsx" -o -name "App.jsx" -o -name "page.tsx" -o -name "page.jsx" -o -name "index.tsx" 2>/dev/null',"","Pick the file that is the main app entry point or the page component for this route. Confirm it exists with `cat <filepath> | head -5`."],"","Step B: Set page_file_path on all scenarios for this page (replace PAGE_FILE_PATH with the path from Step A):",` sqlite3 .codeyam/db.sqlite3 "UPDATE editor_scenarios SET page_file_path = 'PAGE_FILE_PATH' WHERE id IN (${s});"`,"","Step C: Get the entity SHA (after running analyze-imports in the shared step above):",` sqlite3 .codeyam/db.sqlite3 "SELECT sha FROM entities WHERE file_path = 'PAGE_FILE_PATH' ORDER BY created_at DESC LIMIT 1;"`,"","If no rows appear, the path was wrong — go back to Step A.","","Step D: Set entity_sha and display_name on all scenarios (replace ENTITY_SHA with the SHA from Step C):",` sqlite3 .codeyam/db.sqlite3 "UPDATE editor_scenarios SET entity_sha = 'ENTITY_SHA', display_name = '${e}' WHERE id IN (${s});"`,"","Step E: Add pageFilePath to the scenario JSON files so this fix persists across clones.",`For each file (${i}), read it and add \`"pageFilePath": "PAGE_FILE_PATH"\` to the \`_metadata\` object (after the \`"type"\` field). Then commit the updated JSON files.`].join(`
601
- `)}else return[`### Component: "${e}" (${t.length} scenario(s))`,"","Step A: Get the entity SHA (after running analyze-imports in the shared step above):",` sqlite3 .codeyam/db.sqlite3 "SELECT sha FROM entities WHERE name = '${e}' ORDER BY created_at DESC LIMIT 1;"`,"","If no rows appear, check that .codeyam/glossary.json contains an entry for this component.","","Step B: Set entity_sha and display_name on all scenarios (replace ENTITY_SHA with the SHA from Step A):",` sqlite3 .codeyam/db.sqlite3 "UPDATE editor_scenarios SET entity_sha = 'ENTITY_SHA', display_name = '${e}' WHERE id IN (${s});"`].join(`
602
- `)}function Fs({scenarioId:e,screenshotPath:t,updatedAt:r,hasScreenshot:s,imgSrc:a,name:o,dimensionLabel:i,isActive:l,onSelect:c}){const p=e&&s,u=!e&&a;return d("button",{onClick:c,className:"flex flex-col items-center gap-1 cursor-pointer group w-full",title:i?`${o} (${i})`:o,children:[d("div",{className:`w-full aspect-[16/10] rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] relative ${l?"border-[#D7FF63]/40 ring-1 ring-[#D7FF63]/20":"border-transparent hover:border-[#4d4d4d]"}`,children:[p?n(or,{scenarioId:e,screenshotPath:t,updatedAt:r,alt:i?`${o} (${i})`:o,className:"w-full h-full",imgClassName:"w-full h-full object-contain"}):u?n("img",{src:a,alt:o,className:"w-full h-full object-contain",loading:"lazy"}):n("div",{className:"w-full h-full bg-[#1a1a1a] flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})}),i&&n("span",{className:"absolute bottom-1 right-1 text-[8px] font-medium bg-black/60 text-white px-1 py-0.5 rounded",children:i})]}),n("span",{className:`text-[10px] leading-tight text-center truncate w-full ${l?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:i?`${o} (${i})`:o})]})}function Es({filePath:e}){return e?d("div",{className:"flex items-center gap-1.5 mt-0.5",children:[d("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1.5 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-sm truncate font-['IBM_Plex_Mono']",children:e}),n("svg",{className:"shrink-0",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(pt,{content:e,icon:!0,iconSize:12,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function Cp({name:e,scenarios:t,reason:r="missing"}){var o,i;const s=((o=t[0])==null?void 0:o.componentPath)||((i=t[0])==null?void 0:i.pageFilePath)||null,a=r==="incomplete"?[`The "${e}" entity exists but has not been fully analyzed — its components and functions cannot be displayed.`,"","Follow these steps:","",`Step 1: Check if "${e}" is in the glossary:`,` cat .codeyam/glossary.json | grep "${e}"`,"","If not found, add an entry to .codeyam/glossary.json:",` { "name": "${e}", "filePath": "${s||"FILL_IN_PATH"}", "description": "...", "returnType": "JSX.Element" }`,"","Step 2: Run: codeyam editor analyze-imports","","Step 3: Reload the editor page and verify components/functions appear."].join(`
603
- `):[`The "${e}" ${t.some(l=>!l.componentName)?"page":"component"} is missing entity data in the CodeYam database. Its scenarios are hidden until this is fixed.`,"","IMPORTANT: Do NOT re-register scenarios — that would overwrite their screenshots. Instead, update the database and scenario JSON files directly.","","Follow these steps EXACTLY:","","Step 1: Run: codeyam editor analyze-imports","","Step 2: Fix this entity:","",Sp(e,t),"","Step 3: Reload the editor page in the browser and verify the scenarios appear."].join(`
604
- `);return n(pt,{content:a,label:"Copy Fix Prompt",copiedLabel:"Copied!",className:"text-[10px] text-[#E0D400] hover:text-[#E0D400]/80 bg-transparent border border-[#E0D400]/30 rounded px-2 py-0.5 cursor-pointer transition-colors ml-2"})}function S5({brokenEntities:e}){const[t,r]=A(!1),s=oe(c=>{navigator.clipboard.writeText(c).then(()=>{r(!0),setTimeout(()=>r(!1),2e3)})},[]);if(e.length===0)return null;const a=e.reduce((c,p)=>c+p.scenarios.length,0),o=e.filter(c=>c.reason==="incomplete"),i=e.filter(c=>c.reason==="missing"),l=[`${e.length} entities are missing data in the CodeYam database. ${a} total scenario(s) are hidden until this is fixed.`,"","IMPORTANT: Do NOT re-register scenarios — that would overwrite their screenshots. Instead, update the database and scenario JSON files directly.","","Follow these steps EXACTLY:","",...o.length>0?["## Step 1: Add missing entries to the glossary","","Read `.codeyam/glossary.json` and check if these entities have entries. For each one that is missing, add an entry:","",...o.map(c=>{var u,h;const p=((u=c.scenarios[0])==null?void 0:u.componentPath)||((h=c.scenarios[0])==null?void 0:h.pageFilePath)||"FILL_IN_PATH";return`- "${c.name}" (filePath: "${p}")`}),"",'Each glossary entry needs: name, filePath, description, returnType (use "JSX.Element" for components/pages).',""]:["## Step 1: No glossary changes needed",""],"## Step 2: Run import analysis"," codeyam editor analyze-imports","",...i.length>0?["## Step 3: Fix missing entity associations","",...i.map(c=>Sp(c.name,c.scenarios)),""]:[],`## Step ${i.length>0?"4":"3"}: Reload the editor page in the browser and verify all scenarios appear. Then commit the updated scenario JSON files so the fix persists across clones.`].join(`
605
- `);return n("div",{className:"p-4 rounded-lg border border-[#E0D400]/40 bg-[#E0D400]/8",children:d("div",{className:"flex items-center gap-3",children:[d("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#E0D400",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),d("p",{className:"flex-1 min-w-0 text-sm text-[#E0D400]/90 m-0 leading-snug font-['IBM_Plex_Sans']",children:[e.length," ",e.length===1?"entity is":"entities are"," missing data, resulting in ",a," hidden scenario",a!==1?"s":"","."," ",n("button",{type:"button",className:"font-bold underline bg-transparent border-none text-[#E0D400] cursor-pointer p-0 text-sm inline hover:text-[#E0D400]/70 transition-colors",onClick:()=>s(l),children:t?d("span",{className:"inline-flex items-center gap-1",children:["Copied",n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"inline",children:n("polyline",{points:"20 6 9 17 4 12"})})]}):"Copy this prompt"})," ","into Claude to fix them all at once."]}),n(pt,{content:l,label:d("span",{className:"flex items-center gap-2",children:["COPY PROMPT",d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]}),copiedLabel:d("span",{className:"flex items-center gap-2",children:[n("span",{className:"invisible",children:"COPY PROMPT"}),n("span",{className:"absolute inset-0 flex items-center justify-center",children:"COPIED!"}),n("span",{className:"invisible",children:n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",children:n("rect",{x:"9",y:"9",width:"13",height:"13"})})})]}),className:"relative text-xs font-semibold text-[#1e1e1e] bg-[#E0D400] hover:bg-[#E0D400]/80 border-none rounded px-4 py-2 cursor-pointer transition-colors shrink-0 tracking-wide font-['IBM_Plex_Mono']"})]})})}function kp({focusedEntity:e,breadcrumbItems:t,onZoomChange:r,projectRoot:s,scenarios:a,analyzedEntities:o,activeScenarioId:i,onScenarioSelect:l,onAnalyzedScenarioSelect:c,onSwitchToBuild:p,entityImports:u,glossaryFunctions:h,cachedTestResults:m={},glossaryEntries:f,entityShaMap:y,componentGroups:g,visualEntities:x,isEntityComplete:b,onReseedPreview:v}){var _e;const N=e.filePath,w=e.name,[C,S]=A("scenarios"),[k,j]=A(null),[_,F]=A(""),[M,$]=A(!1),[O,D]=A(null),[T,B]=A(!1),[Y,I]=A(!1),[L,P]=A(null);ne(()=>{S("scenarios"),j(null),B(!1),I(!1),P(null)},[e.sha]);const R=le(()=>{const Z=new Map;for(const he of h)Z.set(he.name,he);return Z},[h]),E=o.some(Z=>Z.sha===e.sha||Z.filePath===N),J=!!((_e=u==null?void 0:u[w])!=null&&_e.length),K=oe(async Z=>{if(!(!_.trim()||M)){$(!0);try{(await fetch("/api/editor-rename-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:Z,name:_.trim()})})).ok&&j(null)}catch{}finally{$(!1)}}},[_,M]),Q=oe(async Z=>{if(confirm(`Delete scenario "${Z.name}"?`)){D(Z.id);try{const he=Z.screenshotPaths?Object.values(Z.screenshotPaths):Z.screenshotPath?[Z.screenshotPath]:[];await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:Z.id,screenshotPaths:he})})}catch{}finally{D(null)}}},[]);if(!E&&!J){const Z=a.filter(te=>te.entitySha===e.sha),he=[`The "${e.displayName}" entity (${N}) exists in the database but has not been fully analyzed. Its components and functions cannot be shown until it has import metadata.`,"","Follow these steps:","",`Step 1: Add "${w}" to the glossary if it's not already there:`,` Check: cat .codeyam/glossary.json | grep "${w}"`,"",` If not found, add an entry with name "${w}" and filePath "${N}" to .codeyam/glossary.json`,"","Step 2: Run import analysis:"," codeyam editor analyze-imports","","Step 3: Reload the editor page and verify components/functions appear."].join(`
606
- `);return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-4 space-y-3",children:[d("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>{if(t.length>1){const te=t[t.length-2];r(te.componentName,te.entitySha)}else r()},className:"text-gray-400 hover:text-white transition-colors cursor-pointer bg-transparent border-none p-0 shrink-0 text-lg",title:"Go back",children:"←"}),n("h2",{className:"text-lg font-medium text-white m-0 font-['IBM_Plex_Sans']",children:e.displayName})]}),N&&n(Es,{filePath:N,projectRoot:s}),d("div",{className:"py-2",children:[n("p",{className:"text-[11px] text-amber-400/80 m-0 leading-relaxed",children:"This entity has not been fully analyzed. Its components and functions cannot be displayed. Please copy and paste this prompt into Claude to fix the data."}),n("div",{className:"mt-2",children:n(pt,{content:he,label:"Copy Fix Prompt",copiedLabel:"Copied!",className:"text-[10px] text-amber-400 hover:text-amber-300 bg-transparent border border-amber-400/30 rounded px-2 py-1 cursor-pointer transition-colors"})})]}),Z.length>0&&n("div",{className:"grid grid-cols-3 gap-2",children:cn(Z).map(({scenario:te,dimensionLabel:se,screenshotPath:ce,key:je})=>n(Fs,{scenarioId:te.id,screenshotPath:ce,updatedAt:te.updatedAt,hasScreenshot:!!ce,name:te.name,dimensionLabel:se,isActive:te.id===i,onSelect:()=>l(te,se??void 0)},je))})]})})}const q=e.sha,U=a.filter(Z=>!Z.componentName&&(Z.pageFilePath===N||q&&Z.entitySha===q)),z=a.filter(Z=>Z.componentName===w||Z.componentPath===N),W=x.find(Z=>Z.filePath===N||Z.name===w),V=R.get(w)||h.find(Z=>Z.filePath===N),ae=[...U,...z],pe=le(()=>{const Z=[];if(Z.push(`# Create a New Scenario for "${e.displayName}"`),Z.push(""),Z.push(`**Entity**: ${e.displayName}`),Z.push(`**Type**: ${e.entityType}`),Z.push(`**File**: ${N}`),Z.push(""),ae.length>0){Z.push("## Existing Scenarios");for(const he of ae)Z.push(`- **${he.name}**${he.url?` — URL: ${he.url}`:""}`);Z.push("")}return Z.push("## Your Task"),Z.push("Ask the user what scenario they would like to create. Offer two options:"),Z.push("1. **Describe a scenario** — the user tells you what they want and you create it"),Z.push("2. **Analyze gaps** — you review the existing scenarios and source code to suggest scenarios that would improve coverage"),Z.push(""),Z.push("Once you know what scenario to create, use the `codeyam editor register` CLI command to register it. Write the scenario JSON to `.codeyam/tmp/scenario.json` first, then run `codeyam editor register @.codeyam/tmp/scenario.json`."),Z.join(`
607
- `)},[e.displayName,e.entityType,N,ae]),xe=new Set((u==null?void 0:u[w])||[]),ie=J?[...g.entries()].filter(([Z])=>xe.has(Z)):[],me=J?x.filter(Z=>xe.has(Z.name)&&!ie.some(([he])=>he===Z.name)):[],we=J?f.filter(Z=>xe.has(Z.name)&&Z.returnType!=="JSX.Element"&&Z.returnType!=="React.ReactNode").map(Z=>({name:Z.name,filePath:Z.filePath,description:Z.description||"",testFile:Z.testFile,feature:Z.feature})):[],Te=ie.length>0||me.length>0,Ne=we.length>0;return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-5",children:[d("div",{className:"mb-5",children:[d("div",{className:"flex items-center gap-2.5",children:[n("button",{onClick:()=>{if(t.length>1){const Z=t[t.length-2];r(Z.componentName,Z.entitySha)}else r()},className:"text-gray-400 hover:text-white transition-colors cursor-pointer bg-transparent border-none p-0 shrink-0 text-xl",title:"Go back",children:"←"}),n("h2",{className:"text-xl font-medium text-white m-0 font-['IBM_Plex_Sans']",children:e.displayName})]}),e.filePath&&n("div",{className:"mt-1.5 ml-7",children:n(Es,{filePath:e.filePath,projectRoot:s})})]}),n("div",{className:"-mx-5 px-5 border-t border-b border-[#3d3d3d] flex items-center gap-6",children:[["scenarios","Scenarios"],["components","Components"],["functions","Functions"],["data-structure","Data Structure"]].map(([Z,he])=>n("button",{onClick:()=>S(Z),className:`text-xs font-normal uppercase tracking-wider transition-colors bg-transparent border-none cursor-pointer px-0 font-['IBM_Plex_Mono'] border-b-2 leading-none ${C===Z?"text-[#D7FF63] border-b-[#D7FF63]":"text-gray-500 hover:text-gray-300 border-b-transparent"}`,style:{marginBottom:-1,paddingTop:16,paddingBottom:14},children:he},Z))}),C==="scenarios"&&d("div",{className:"space-y-3 mt-5",children:[ae.map(Z=>{const he=Z.id===i,te=k===Z.id;return d("div",{children:[d("div",{onClick:()=>{te||l(Z)},className:`flex items-center gap-4 p-3 rounded-lg cursor-pointer transition-colors ${he?"bg-[#1a2e1a] border border-[#D7FF63]/40":"bg-[#252525] hover:bg-[#2a2a2a] border border-transparent"}`,style:{opacity:O===Z.id?.4:1},children:[Z.screenshotPaths&&Object.keys(Z.screenshotPaths).length>1?n("div",{className:"flex gap-2 shrink-0",children:Object.entries(Z.screenshotPaths).map(([se,ce])=>d("div",{className:"relative",children:[n(or,{scenarioId:Z.id,screenshotPath:ce,updatedAt:Z.updatedAt,alt:se,className:"rounded w-[120px] h-[75px] overflow-hidden border border-[#3d3d3d]",imgClassName:"w-full h-full object-cover"}),n("span",{className:"absolute bottom-1 right-1 text-[8px] font-medium bg-black/60 text-white px-1 py-0.5 rounded",children:se})]},se))}):Z.screenshotPath?n(or,{scenarioId:Z.id,screenshotPath:Z.screenshotPath,updatedAt:Z.updatedAt,alt:"",className:"rounded w-[160px] h-[100px] shrink-0 overflow-hidden border border-[#3d3d3d]",imgClassName:"w-full h-full object-cover"}):n("div",{className:"rounded bg-[#1a1a1a] w-[160px] h-[100px] shrink-0 flex items-center justify-center border border-[#3d3d3d]",children:n("span",{className:"text-[10px] text-gray-600",children:"No image"})}),n("div",{className:"flex-1 min-w-0",children:te?d("form",{className:"flex items-center gap-1.5",onSubmit:se=>{se.preventDefault(),K(Z.id)},onClick:se=>se.stopPropagation(),children:[n("input",{type:"text",value:_,onChange:se=>F(se.target.value),className:"flex-1 px-2 py-1 text-xs bg-[#1e1e1e] text-white border border-[#3d3d3d] rounded outline-none focus:border-[#005c75] min-w-0",autoFocus:!0,disabled:M}),n("button",{type:"submit",disabled:M||!_.trim(),className:"px-2 py-1 text-[10px] bg-[#005c75] text-white rounded hover:bg-[#004d63] disabled:opacity-40 cursor-pointer border-none",children:M?"...":"Save"}),n("button",{type:"button",onClick:()=>j(null),className:"px-2 py-1 text-[10px] text-gray-400 hover:text-white cursor-pointer bg-transparent border-none",children:"Cancel"})]}):d(ve,{children:[n("span",{className:"text-xs text-gray-300 truncate block",children:Z.name}),he&&d("div",{className:"flex items-center gap-3 mt-1.5",children:[n("button",{onClick:se=>{se.stopPropagation(),P(L===Z.id?null:Z.id)},className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 cursor-pointer bg-transparent border-none p-0",children:"View Data"}),n("button",{onClick:se=>{se.stopPropagation(),I(!1),B(!0)},className:"text-[10px] text-gray-400 hover:text-white cursor-pointer bg-transparent border-none p-0",children:"Edit with Claude"}),n("button",{onClick:se=>{se.stopPropagation(),j(Z.id),F(Z.name)},className:"text-[10px] text-gray-400 hover:text-white cursor-pointer bg-transparent border-none p-0",children:"Rename"}),n("button",{onClick:se=>{se.stopPropagation(),Q(Z)},disabled:O===Z.id,className:"text-[10px] text-red-400/60 hover:text-red-400 cursor-pointer bg-transparent border-none p-0",children:"Delete"})]})]})})]}),L===Z.id&&n(C5,{scenarioId:Z.id,onClose:()=>P(null),editPrompt:Uc(e.displayName,e.filePath,e.entityType,ae),onReseedPreview:v})]},Z.id)}),W&&(W.scenarios.length>0||W.pendingScenarios.length>0)&&d("div",{className:"space-y-1 mt-2",children:[W.scenarios.map(Z=>d("div",{onClick:()=>c({analysisId:W.analysisId,scenarioId:Z.id,scenarioName:Z.name,entitySha:W.sha,entityName:W.name}),className:"flex items-center gap-3 p-2 rounded cursor-pointer transition-colors hover:bg-[#252525] border border-transparent",children:[Z.screenshotPath?n("img",{src:`/api/screenshot/${Z.screenshotPath}`,alt:Z.name,className:"rounded w-[48px] h-[48px] shrink-0 object-cover",loading:"lazy"}):n("div",{className:"rounded bg-[#1a1a1a] w-[48px] h-[48px] shrink-0 flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})}),n("span",{className:"text-xs text-gray-300 truncate",children:Z.name})]},Z.id)),W.pendingScenarios.map(Z=>d("div",{className:"flex items-center gap-3 p-2",children:[n("div",{className:"rounded bg-[#1a1a1a] w-[48px] h-[48px] shrink-0 flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"..."})}),n("span",{className:"text-xs text-gray-500 truncate",children:Z})]},Z))]}),ae.length===0&&!W&&!V&&n("div",{className:"text-xs text-gray-500 py-2",children:"No scenarios for this entity"}),d("button",{onClick:()=>{B(!1),I(!0)},className:"flex items-center gap-2.5 mt-4 text-xs text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none cursor-pointer p-0 font-normal uppercase tracking-wider font-['IBM_Plex_Mono'] transition-colors",children:[d("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("line",{x1:"12",y1:"8",x2:"12",y2:"16"}),n("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]}),"Create New Scenario"]}),Y&&n("div",{className:"mt-2 border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(un,{prompt:pe,height:500,onClose:()=>I(!1)})}),T&&ae.length>0&&n("div",{className:"mt-2 border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(un,{prompt:Uc(e.displayName,e.filePath,e.entityType,ae),height:500,onClose:()=>B(!1)})})]}),C==="components"&&n("div",{className:"space-y-3",children:Te?d(ve,{children:[ie.map(([Z,he])=>n("div",{children:y.has(Z)?d(ve,{children:[n("div",{className:"py-1",children:n("button",{onClick:()=>r(Z,y.get(Z)),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:Z})}),he.length>0&&n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:cn(he).map(({scenario:te,dimensionLabel:se,screenshotPath:ce,key:je})=>n(Fs,{scenarioId:te.id,screenshotPath:ce,updatedAt:te.updatedAt,hasScreenshot:!!ce,name:te.name,dimensionLabel:se,isActive:te.id===i,onSelect:()=>l(te,se??void 0)},je))})]}):d("div",{className:"py-2",children:[n("span",{className:"text-[11px] font-medium text-gray-500",children:Z}),n("p",{className:"text-[10px] text-amber-400/80 m-0 mt-1.5 leading-relaxed",children:"There is data missing that is required to show the scenarios for this component. Please copy and paste this prompt into Claude to ask Claude to fix the data."}),n("div",{className:"mt-1.5",children:n(Cp,{name:Z,scenarios:he})})]})},Z)),me.map(Z=>d("div",{children:[n("div",{className:"py-1",children:n("button",{onClick:()=>r(Z.name,Z.sha),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:Z.name})}),(Z.scenarios.length>0||Z.pendingScenarios.length>0)&&d("div",{className:"grid grid-cols-3 gap-2 pt-1",children:[Z.scenarios.map(he=>n(Fs,{imgSrc:he.screenshotPath?`/api/screenshot/${he.screenshotPath}`:null,name:he.name,isActive:!1,onSelect:()=>c({analysisId:Z.analysisId,scenarioId:he.id,scenarioName:he.name,entitySha:Z.sha,entityName:Z.name})},he.id)),Z.pendingScenarios.map(he=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:he,children:he},he))]})]},Z.sha))]}):n("div",{className:"text-xs text-gray-500 py-2",children:"No component dependencies"})}),C==="functions"&&d("div",{className:"space-y-3",children:[V&&V.testFile&&d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] text-gray-500",children:"Tests:"}),n(Es,{filePath:V.testFile,projectRoot:s})]}),n(Oo,{testFile:V.testFile,entityName:w,cachedResult:m[V.testFile]})]}),Ne?n("div",{children:we.map(Z=>d("div",{className:"mt-2",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>r(Z.name,y.get(Z.name)),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:Z.name})}),n(Es,{filePath:Z.filePath,projectRoot:s}),Z.testFile&&d("div",{className:"mt-0.5",children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[9px] text-gray-600",children:"test:"}),n("span",{className:"text-[9px] text-gray-500 truncate",children:Z.testFile})]}),n(Oo,{testFile:Z.testFile,entityName:Z.name,cachedResult:m[Z.testFile]})]})]},Z.name))}):V!=null&&V.testFile?null:n("div",{className:"text-xs text-gray-500 py-2",children:"No function dependencies"})]}),C==="data-structure"&&n(k5,{})]})})}function C5({scenarioId:e,onClose:t,editPrompt:r,onReseedPreview:s}){const[a,o]=A(null),[i,l]=A([]),[c,p]=A(!0),[u,h]=A(null),[m,f]=A(null),[y,g]=A(!1),[x,b]=A(null),[v,N]=A(""),[w,C]=A(""),[S,k]=A(0),[j,_]=A(!1),[F,M]=A(!1),$=ye(null);if(ne(()=>{p(!0),h(null),Promise.all([fetch("/api/editor-schema").then(P=>P.json()).catch(()=>({models:[]})),fetch(`/api/editor-scenario-data?scenarioId=${e}`).then(P=>P.json())]).then(([P,R])=>{const E=P.source==="explicit"?y5(P.dataStructures||[],R):p5(P.models||[],R);o(E.data),l(E.tabs),E.tabs.length>0&&!m&&f(E.tabs[0].dataKey)}).catch(()=>h("Failed to load scenario data")).finally(()=>p(!1))},[e,S]),c)return n("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg p-4 text-xs text-gray-400",children:"Loading mock data..."});if(u||!a)return n("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg p-4 text-xs text-red-400",children:u||"No data available"});if(i.length===0)return d("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg p-4 text-xs text-gray-500",children:["No mock data found for this scenario.",n("button",{onClick:t,className:"ml-2 text-gray-400 hover:text-white bg-transparent border-none cursor-pointer text-[10px]",children:"Dismiss"})]});const O=i.find(P=>P.dataKey===m)||i[0],D=m?a[m]||[]:[],T=m5(D,O.schemaFields),B=f5(T,D,O.schemaFields),Y=g5(T,O.schemaFields);return d("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg overflow-hidden",children:[d("div",{className:"flex items-center gap-1.5 px-2 py-1.5 bg-[#252525] border-b border-[#3d3d3d] flex-wrap",children:[i.map(P=>{const R=m===P.dataKey,E=P.category==="datastore"?R?"text-[#D7FF63] bg-[#D7FF63]/15 border-[#D7FF63]/40":"text-[#D7FF63]/60 bg-transparent border-transparent hover:text-[#D7FF63]/80":P.category==="mock-api"?R?"text-blue-400 bg-blue-400/15 border-blue-400/40":"text-blue-400/60 bg-transparent border-transparent hover:text-blue-400/80":R?"text-white bg-[#3d3d3d] border-[#4d4d4d]":"text-gray-500 bg-transparent border-transparent hover:text-gray-300";return n("button",{onClick:()=>f(P.dataKey),className:`px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider rounded cursor-pointer border transition-colors ${E}`,children:P.label},P.dataKey)}),n("div",{className:"flex-1"}),n("button",{onClick:t,className:"w-5 h-5 flex items-center justify-center text-gray-500 hover:text-white bg-[#3d3d3d] hover:bg-[#4d4d4d] rounded-full border-none cursor-pointer text-xs transition-colors",title:"Close",children:"×"})]}),(O.description||O.category)&&d("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-[#1e1e1e] border-b border-[#2d2d2d]",children:[O.category&&n("span",{className:`text-[9px] rounded px-1.5 py-0 border ${O.category==="datastore"?"text-[#D7FF63]/80 bg-[#D7FF63]/10 border-[#D7FF63]/30":O.category==="mock-api"?"text-blue-400/80 bg-blue-400/10 border-blue-400/30":"text-gray-400 bg-gray-700/30 border-gray-600/30"}`,children:O.category==="mock-api"?"API Mock":O.category}),O.description&&n("span",{className:"text-[10px] text-gray-500",children:O.description})]}),T.length===0?n("div",{className:"px-3 py-4 text-[10px] text-gray-500 text-center",children:"No columns defined for this table"}):n("div",{className:"overflow-x-auto max-h-[300px] overflow-y-auto",children:d("table",{className:"w-full text-[10px] border-collapse table-fixed",children:[n("thead",{children:d("tr",{className:"bg-[#1e1e1e] sticky top-0 z-10",children:[n("th",{className:"text-right text-gray-600 font-normal px-2 py-1.5 border-b border-[#3d3d3d] w-8",children:"#"}),T.map(P=>d("th",{className:"text-left px-2 py-1.5 border-b border-[#3d3d3d] whitespace-nowrap overflow-hidden",children:[P===Y&&n("span",{className:"inline-block text-[8px] font-bold text-white bg-[#D7FF63] rounded px-1 py-0 mr-1.5 align-middle",children:"PK"}),n("span",{className:"text-gray-300 font-medium",children:P}),n("span",{className:"text-gray-600 font-normal ml-1",children:B[P]})]},P))]})}),n("tbody",{children:D.map((P,R)=>d("tr",{className:"border-b border-[#2d2d2d] hover:bg-[#252525] group/row",children:[n("td",{className:"text-right text-gray-600 px-2 py-1.5 w-8 select-none",children:R+1}),T.map(E=>d("td",{className:`px-2 py-1.5 overflow-hidden relative group/cell ${E===Y?"text-[#D7FF63] font-medium":"text-gray-300"}`,title:String(P[E]??""),children:[n("span",{className:"truncate block whitespace-nowrap",children:P[E]===null?n("span",{className:"text-gray-600 italic",children:"null"}):typeof P[E]=="object"?n("span",{className:"text-gray-500",children:JSON.stringify(P[E])}):typeof P[E]=="number"?n("span",{className:"text-amber-400",children:String(P[E])}):String(P[E])}),n("button",{onClick:J=>{J.stopPropagation(),b({row:R,col:E});const K=P[E]===null?"":typeof P[E]=="object"?JSON.stringify(P[E]):String(P[E]);N(K),C(K)},className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover/cell:opacity-100 text-gray-500 hover:text-white bg-[#252525] border border-[#4d4d4d] rounded cursor-pointer p-0.5 transition-opacity",title:"Edit",children:d("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]},E))]},R))})]})}),x&&d("div",{className:"border-t border-[#3d3d3d] bg-[#1e1e1e] px-3 py-2",children:[n("div",{className:"flex items-center gap-2 mb-1.5",children:d("span",{className:"text-[10px] text-gray-400",children:["Editing"," ",n("strong",{className:"text-gray-200",children:x.col})," in row ",x.row+1]})}),n("textarea",{value:v,onChange:P=>{const R=P.target.value;N(R),$.current&&clearTimeout($.current),$.current=setTimeout(()=>{L(O.dataKey,x.row,x.col,R)},600)},className:"w-full px-2 py-1.5 text-[11px] bg-[#252525] text-white border border-[#4d4d4d] rounded outline-none focus:border-[#D7FF63]/50 resize-y min-h-[60px] max-h-[200px] font-mono",autoFocus:!0,rows:v.length>100?4:2,onKeyDown:P=>{P.key==="Escape"&&I(),P.key==="Enter"&&(P.metaKey||P.ctrlKey)&&($.current&&clearTimeout($.current),L(O.dataKey,x.row,x.col,v),b(null))}}),d("div",{className:"flex items-center gap-2 mt-1.5",children:[n("button",{onClick:()=>{$.current&&clearTimeout($.current),L(O.dataKey,x.row,x.col,v),b(null)},className:"px-3 py-1 text-[10px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded cursor-pointer border-none hover:bg-[#D7FF63]/80 transition-colors",children:"Save"}),n("button",{onClick:()=>I(),className:"px-3 py-1 text-[10px] text-gray-400 hover:text-white bg-transparent border-none cursor-pointer",children:"Cancel"}),d("span",{className:"text-[9px] text-gray-600 ml-auto",children:["⌘","+Enter to save, Esc to cancel"]})]})]}),j&&!x&&d("div",{className:"border-t border-[#3d3d3d] bg-amber-500/5 px-3 py-2 flex items-center gap-2",children:[n("span",{className:"text-[10px] text-amber-400/80",children:"Data modified — recapture to update the screenshot"}),n("div",{className:"flex-1"}),n("button",{onClick:()=>{M(!0),Promise.resolve().then(()=>(s&&s(),new Promise(P=>setTimeout(P,2e3)))).then(()=>fetch("/api/editor-capture-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e})})).then(()=>_(!1)).catch(()=>{}).finally(()=>M(!1))},disabled:F,className:"px-3 py-1 text-[10px] font-medium text-white bg-amber-600 rounded cursor-pointer border-none hover:bg-amber-500 disabled:opacity-50 transition-colors",children:F?"Recapturing...":"Recapture Screenshot"})]}),r&&d("div",{className:"border-t border-[#3d3d3d]",children:[n("div",{className:"flex justify-center py-2",children:n("button",{onClick:()=>g(!y),className:"px-3 py-1 text-[10px] font-medium text-[#D7FF63] border border-[#D7FF63]/40 rounded cursor-pointer transition-colors hover:bg-[#D7FF63]/10 bg-transparent",children:y?"Hide Claude":"Edit with Claude"})}),y&&n("div",{className:"border-t border-[#3d3d3d]",children:n(un,{prompt:r,height:400,onClose:()=>{g(!1),k(P=>P+1)}})})]})]});function I(){if($.current&&clearTimeout($.current),!!x){if(v!==w){if(a&&m){const P=a[m];if(P&&P[x.row]){let R=w;w===""?R="":w==="null"?R=null:w==="true"?R=!0:w==="false"?R=!1:isNaN(Number(w))||(R=Number(w));const E=[...P];E[x.row]={...E[x.row],[x.col]:R},o({...a,[m]:E})}}fetch("/api/editor-save-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e,table:O.dataKey,rowIndex:x.row,column:x.col,value:w})}).then(()=>{s&&s()}).catch(()=>{})}b(null),_(!1)}}async function L(P,R,E,J){if(a&&m){const K=a[m];if(K&&K[R]){let Q=J;J==="null"?Q=null:J==="true"?Q=!0:J==="false"?Q=!1:J!==""&&!isNaN(Number(J))&&(Q=Number(J));const q=[...K];q[R]={...q[R],[E]:Q},o({...a,[m]:q})}}_(!0);try{await fetch("/api/editor-save-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e,table:P,rowIndex:R,column:E,value:J})}),s&&s()}catch{}}}function k5(){const[e,t]=A([]),[r,s]=A([]),[a,o]=A(!0),[i,l]=A(null),[c,p]=A(!1),[u,h]=A(null);if(ne(()=>{fetch("/api/editor-schema").then(g=>g.json()).then(g=>{var x,b;h(g.source||null),g.source==="explicit"?(s(g.dataStructures||[]),((x=g.dataStructures)==null?void 0:x.length)>0&&l(g.dataStructures[0].name)):(t(g.models||[]),((b=g.models)==null?void 0:b.length)>0&&l(g.models[0].name))}).catch(()=>{}).finally(()=>o(!1))},[]),a)return n("div",{className:"text-xs text-gray-400 py-4",children:"Loading schema..."});if(!(u==="explicit"?r.length>0:e.length>0))return n("div",{className:"text-xs text-gray-500 py-4",children:"No data structure found. Use the chat below to have Claude analyze your codebase and generate one."});const f=u==="explicit"?j5(r):E5(e,u);return u==="explicit"?d("div",{className:"space-y-2",children:[r.map(g=>{const x=i===g.name,b=g.category==="datastore"?"text-[#D7FF63]/80 bg-[#D7FF63]/10 border border-[#D7FF63]/30":g.category==="mock-api"?"text-blue-400/80 bg-blue-400/10 border border-blue-400/30":"text-gray-400 bg-gray-700/30 border border-gray-600/30";return d("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:[d("button",{onClick:()=>l(x?null:g.name),className:"w-full flex items-center gap-2 px-3 py-2 bg-[#252525] text-left cursor-pointer border-none transition-colors hover:bg-[#2a2a2a]",children:[n("svg",{className:`text-gray-500 transition-transform shrink-0 ${x?"rotate-90":""}`,width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M9 18l6-6-6-6"})}),n("span",{className:"text-xs font-semibold text-gray-200",children:g.name}),g.order===1&&n("span",{className:"text-[9px] text-amber-400/70",children:"Primary"}),n("span",{className:`text-[9px] rounded px-1.5 py-0 ${b}`,children:g.category==="mock-api"?"API Mock":g.category}),d("span",{className:"text-[10px] text-gray-500",children:[g.fields.length," fields"]})]}),x&&d("div",{className:"border-t border-[#3d3d3d]",children:[g.description&&n("div",{className:"px-3 py-1.5 text-[10px] text-gray-400 border-b border-[#2d2d2d]",children:g.description}),n("table",{className:"w-full text-[10px]",children:n("tbody",{children:g.fields.map(v=>d("tr",{className:"border-b border-[#2d2d2d] last:border-b-0",children:[d("td",{className:"px-3 py-1.5 text-gray-300 font-medium w-1/3",children:[v.isId&&n("span",{className:"text-amber-400 mr-1",title:"Primary key",children:"•"}),v.name]}),n("td",{className:"px-3 py-1.5 text-gray-500",children:v.type}),n("td",{className:"px-3 py-1.5 text-gray-600 w-16 text-right",children:v.required===!1?"optional":""})]},v.name))})})]})]},g.name)}),n("div",{className:"flex justify-center pt-2",children:n("button",{onClick:()=>p(!c),className:"px-4 py-1.5 text-[11px] font-medium text-[#D7FF63] border border-[#D7FF63]/40 rounded-lg cursor-pointer transition-colors hover:bg-[#D7FF63]/10 bg-transparent",children:c?"Hide Chat":"Chat with Claude about the Data Structure"})}),c&&n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(un,{prompt:f,height:500,onClose:()=>p(!1)})})]}):d("div",{className:"space-y-2",children:[n(_5,{prompt:`Analyze this codebase and generate a .codeyam/data-structure.json file that describes the app's data structures.
608
-
609
- The file should be a JSON array where each entry has:
610
- - "name": display name for the data structure
611
- - "description": what this data represents and how it's used
612
- - "category": either "datastore" (persisted data like DB tables, localStorage) or "mock-api" (mocked external API responses)
613
- - "order": integer for display order (1 = primary/most important)
614
- - "fields": array of { "name", "type", "isId" (boolean), "required" (boolean) }
615
-
616
- Look at:
617
- - Database schemas (prisma/schema.prisma, SQLite, etc.)
618
- - TypeScript interfaces/types used for stored data
619
- - localStorage usage patterns
620
- - API response types that need mocking
621
- - Do NOT include types that are only used as component props
622
-
623
- Write the file to .codeyam/data-structure.json.`}),e.map(g=>{const x=i===g.name,b=g.fields.filter(N=>N.isRelation),v=g.fields.filter(N=>!N.isRelation);return d("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:[d("button",{onClick:()=>l(x?null:g.name),className:"w-full flex items-center gap-2 px-3 py-2 bg-[#252525] text-left cursor-pointer border-none transition-colors hover:bg-[#2a2a2a]",children:[n("svg",{className:`text-gray-500 transition-transform ${x?"rotate-90":""}`,width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M9 18l6-6-6-6"})}),n("span",{className:"text-xs font-semibold text-gray-200",children:g.name}),d("span",{className:"text-[10px] text-gray-500",children:[v.length," fields"]}),b.length>0&&d("span",{className:"text-[10px] text-[#D7FF63]/70",children:[b.length," relation",b.length>1?"s":""]})]}),x&&n("div",{className:"border-t border-[#3d3d3d]",children:n("table",{className:"w-full text-[10px]",children:d("tbody",{children:[v.map(N=>d("tr",{className:"border-b border-[#2d2d2d] last:border-b-0",children:[d("td",{className:"px-3 py-1.5 text-gray-300 font-medium w-1/3",children:[N.isId&&n("span",{className:"text-amber-400 mr-1",title:"Primary key",children:"•"}),N.name]}),d("td",{className:"px-3 py-1.5 text-gray-500",children:[N.type,N.isOptional&&"?",N.isList&&"[]"]})]},N.name)),b.length>0&&n("tr",{children:d("td",{colSpan:2,className:"px-3 py-1.5 border-t border-[#3d3d3d]",children:[n("span",{className:"text-[9px] text-gray-500 uppercase tracking-wider",children:"Relations"}),n("div",{className:"mt-1 flex flex-wrap gap-1.5",children:b.map(N=>n("button",{onClick:()=>l(N.relatedModel??null),className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/80 bg-[#D7FF63]/10 border border-[#D7FF63]/30 rounded px-1.5 py-0.5 cursor-pointer transition-colors",children:N.isList?`${N.relatedModel}[]`:N.relatedModel},N.name))})]})})]})})})]},g.name)}),n("div",{className:"flex justify-center pt-2",children:n("button",{onClick:()=>p(!c),className:"px-4 py-1.5 text-[11px] font-medium text-[#D7FF63] border border-[#D7FF63]/40 rounded-lg cursor-pointer transition-colors hover:bg-[#D7FF63]/10 bg-transparent",children:c?"Hide Chat":"Chat with Claude about the Data Structure"})}),c&&n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(un,{prompt:f,height:500,onClose:()=>p(!1)})})]})}function _5({prompt:e}){const[t,r]=A(!1),[s,a]=A(()=>typeof window>"u"?!1:localStorage.getItem("codeyam-ds-migration-dismissed")==="1");return s?null:d("div",{className:"relative border border-amber-500/30 bg-amber-500/5 rounded-lg p-3 pr-8",children:[n("button",{onClick:()=>{a(!0),localStorage.setItem("codeyam-ds-migration-dismissed","1")},className:"absolute top-2 right-2 text-gray-500 hover:text-white bg-transparent border-none cursor-pointer p-0.5",title:"Dismiss",children:n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M2 2l8 8M10 2l-8 8"})})}),n("p",{className:"text-[11px] text-amber-400/90 m-0 font-['IBM_Plex_Sans'] leading-relaxed",children:"This data structure was auto-detected. For better results, ask Claude to generate an explicit data structure config."}),n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"mt-2 px-3 py-1 text-[10px] font-medium text-amber-400 border border-amber-500/40 rounded cursor-pointer transition-colors hover:bg-amber-500/10 bg-transparent",children:t?"Copied!":"Copy prompt for Claude"})]})}function E5(e,t){const r=e.map(a=>{const o=a.fields.map(i=>{let l=` ${i.name}: ${i.type}`;return i.isList&&(l+="[]"),i.isOptional&&(l+=" (optional)"),i.isId&&(l+=" [PK]"),i.isRelation&&(l+=` → ${i.relatedModel}`),l}).join(`
624
- `);return`${a.name}:
625
- ${o}`}).join(`
626
-
627
- `);return`You are helping the user understand and modify the data structure of their application.
628
-
629
- ${t==="prisma"?"The data structure is defined in `prisma/schema.prisma`.":t==="typescript"?"The data structure is defined via TypeScript interfaces in the `src/` directory.":"The data structure was inferred from the project."}
630
-
631
- Here is the current data structure:
632
-
633
- ${r}
634
-
635
- Wait for the user to tell you what they want to do. They might want to:
636
- - Add new models/tables
637
- - Add or modify fields on existing models
638
- - Understand relationships between models
639
- - Get advice on data modeling
640
- - Generate or modify seed data for scenarios
641
-
642
- When making changes:
643
- ${t==="prisma"?"- Edit `prisma/schema.prisma` directly":"- Edit the TypeScript interface files in `src/`"}
644
- - After schema changes, update any affected scenario seed data
645
- - Explain the impact of changes on existing data
646
-
647
- Do NOT start making changes until the user tells you what they want.`}function j5(e){return`You are helping the user understand and modify the data structure of their application.
648
-
649
- The data structure is explicitly defined in \`.codeyam/data-structure.json\`.
650
-
651
- Here is the current data structure:
652
-
653
- ${e.map(r=>{const s=r.category==="datastore"?"[datastore]":r.category==="mock-api"?"[mock-api]":`[${r.category}]`,a=r.fields.map(i=>{let l=` ${i.name}: ${i.type}`;return i.isId&&(l+=" [PK]"),i.required===!1&&(l+=" (optional)"),l}).join(`
654
- `),o=r.description?` ${r.description}`:"";return`${r.name} ${s}${o?`
655
- ${o}`:""}
656
- ${a}`}).join(`
657
-
658
- `)}
659
-
660
- Each data structure has:
661
- - **name**: display name
662
- - **description**: what this data represents
663
- - **category**: "datastore" (persisted data) or "mock-api" (mocked external API)
664
- - **order**: display order (1 = primary)
665
- - **fields**: array of { name, type, isId, required }
666
-
667
- Wait for the user to tell you what they want to do. They might want to:
668
- - Add new data structures (tables, API mocks)
669
- - Add or modify fields
670
- - Change categories or descriptions
671
- - Understand how data flows through the app
672
-
673
- When making changes:
674
- - Edit \`.codeyam/data-structure.json\` directly
675
- - Keep the file as a JSON array sorted by order
676
- - Update descriptions to reflect changes
677
- - After data structure changes, update affected scenario seed data
678
-
679
- Do NOT start making changes until the user tells you what they want.`}function Jc({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 A5({testFile:e,entityName:t,cachedResult:r}){const{results:s,isRunning:a,runTests:o,stale:i}=Ji(e,r);if(a&&!s)return d("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#00a0c4] animate-pulse"}),n("span",{className:"text-[10px] text-gray-500",children:"Running tests..."})]});if(!s)return null;if(s.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-400",children:s.errorMessage})});const l=t?s.testCases.filter(u=>u.fullName.startsWith(t)):s.testCases,c=l.length>0?l:s.testCases;if(c.length===0)return null;const p=t?`${t} > `:"";return d("div",{className:"pt-1 space-y-0.5",children:[c.map(u=>{var m;const h=p&&u.fullName.startsWith(p)?u.fullName.slice(p.length):u.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[u.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):u.status==="failed"?n("span",{className:"text-red-400 text-[10px]",children:"✗"}):n("span",{className:"text-gray-500 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${u.status==="passed"?"text-green-400":u.status==="failed"?"text-red-400":"text-gray-500"}`,children:h})]}),u.status==="failed"&&((m=u.failureMessages)==null?void 0:m.map((f,y)=>n("div",{className:"pl-4 text-[9px] text-red-400/70 truncate max-w-full",title:f,children:f.split(`
680
- `)[0]},y)))]},u.fullName)}),d("div",{className:"flex items-center gap-2 mt-1",children:[n("button",{onClick:o,disabled:a,className:"text-[10px] text-[#00a0c4] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:a?"Running...":i?"Re-run (stale)":"Re-run"}),i&&!a&&n("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0",title:"Source or test file changed since last run"})]})]})}const P5={added:"text-green-400",untracked:"text-green-400",modified:"text-blue-400",renamed:"text-purple-400"};function T5({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 ${P5[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 M5={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 $5(e){try{return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function I5(e){try{return new Date(e+"T00:00:00").toLocaleDateString([],{weekday:"long",month:"long",day:"numeric"})}catch{return e}}const F5=[{value:"1d",label:"1 Day"},{value:"3d",label:"3 Days"},{value:"7d",label:"1 Week"},{value:"30d",label:"1 Month"}];function D5({entries:e,onScreenshotClick:t}){const[r,s]=A(!1),[a,o]=A("7d"),i=le(()=>Wv(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:F5.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(Hc,{scenario:l,onScreenshotClick:t},l.name))]}),i.componentGroups.size>0&&d("div",{className:"space-y-2",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),[...i.componentGroups.entries()].sort(([l],[c])=>l.localeCompare(c)).map(([l,c])=>d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:l}),c.map(p=>n(Hc,{scenario:p,onScreenshotClick:t},p.name))]},l))]})]})]})]})}function Hc({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 R5({isActive:e,onScreenshotClick:t,glossaryFunctions:r=[],cachedTestResults:s={}}){const[a,o]=A([]),[i,l]=A(!0),[c,p]=A(new Set),u=oe(f=>{p(y=>{const g=new Set(y);return g.has(f)?g.delete(f):g.add(f),g})},[]),h=oe(async()=>{try{const f=await fetch("/api/editor-journal");if(f.ok){const y=await f.json();o(y.entries||[])}}catch{}finally{l(!1)}},[]);if(ne(()=>{h()},[h]),ne(()=>{e&&h()},[e,h]),ne(()=>{if(!e)return;const f=setInterval(()=>void h(),5e3);return()=>clearInterval(f)},[e,h]),i)return n("div",{className:"flex-1 flex items-center justify-center",children:n("span",{className:"text-gray-500 text-sm",children:"Loading journal..."})});if(a.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:d("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No journal entries yet"}),n("p",{className:"text-xs",children:"Journal entries will appear as you build. Claude records features, screenshots, and commits as the project evolves."})]})});const m=Uv(a);return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-4",children:[n(D5,{entries:a,onScreenshotClick:t}),[...m.entries()].map(([f,y])=>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:I5(f)})}),n("div",{className:"space-y-2",children:y.map((g,x)=>{const b=M5[g.type]||{label:g.type,color:"bg-gray-600"},v=`${g.time}-${x}`,N=c.has(v);return d("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[d("div",{className:`p-3 space-y-2 ${N?"":"max-h-[300px] overflow-y-auto"}`,children:[n("div",{className:"flex items-start gap-2 cursor-pointer",onClick:()=>u(v),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:g.title}),n("span",{className:`${b.color} text-white text-[9px] font-bold px-1.5 py-0.5 rounded uppercase tracking-wider shrink-0`,children:b.label})]}),n("span",{className:"text-[10px] text-gray-500",children:$5(g.time)}),g.featureName&&n("span",{className:"text-[10px] text-gray-500 italic truncate",title:g.featureName,children:g.featureName})]})}),g.userPrompt&&n(Np,{text:g.userPrompt,theme:"dark"}),n("p",{className:"text-xs text-gray-400 leading-relaxed",children:g.description}),g.screenshot&&n("button",{type:"button",className:"rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] flex items-center justify-center p-1 cursor-pointer transition-colors w-full",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${g.screenshot.replace("screenshots/","")}`,commitSha:g.commitSha,commitMessage:g.commitMessage,scenarioName:g.title}),children:n("img",{src:`/api/editor-journal-image/${g.screenshot.replace("screenshots/","")}`,alt:g.title,className:"max-w-full max-h-full object-contain",loading:"lazy"})}),g.scenarioScreenshots&&g.scenarioScreenshots.length>0&&(()=>{const w=Jv(g.scenarioScreenshots),C=g.entityChangeStatus,S=w.filter(([M])=>M==="App").flatMap(([,M])=>M),k=w.filter(([M])=>M!=="App"),j=new Map;for(const M of S){const $=M,O=$.pageFilePath?Lt(jt($.pageFilePath)):yt($.url??null),D=j.get(O)||[];D.push(M),j.set(O,D)}const _=[...j.entries()],F=M=>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/${M.path.replace("screenshots/","")}`,commitSha:g.commitSha,commitMessage:g.commitMessage,scenarioName:M.name}),children:n("img",{src:`/api/editor-journal-image/${M.path.replace("screenshots/","")}`,alt:M.name,title:M.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})},M.path);return d("div",{className:"space-y-2",children:[_.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"}),_.map(([M,$])=>d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:M}),(C==null?void 0:C[M])&&n(Jc,{status:C[M]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:$.map(F)})]},M))]}),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:"Components"}),k.map(([M,$])=>d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:M}),(C==null?void 0:C[M])&&n(Jc,{status:C[M]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:$.map(F)})]},M))]})]})})(),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(w=>d("div",{children:[n("span",{className:"text-[11px] font-medium text-gray-200",children:w.name}),n("span",{className:"text-[9px] text-gray-500 truncate block",children:w.filePath}),w.testFile?n(A5,{testFile:w.testFile,entityName:w.name,cachedResult:s[w.testFile]}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},w.name))})]}),g.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:g.commitSha.slice(0,7)}),n("span",{className:"text-gray-500 truncate",children:g.commitMessage})]}),N&&g.modifiedFiles&&g.modifiedFiles.length>0&&n(T5,{files:g.modifiedFiles})]}),d("button",{onClick:()=>u(v),className:"w-full py-1.5 text-[10px] text-gray-500 hover:text-gray-300 border-t border-[#3d3d3d] transition-colors cursor-pointer",children:["——— ",N?"Collapse":"Expand"," ———"]})]},v)})})]},f))]})})}const O5=()=>n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#D7FF63",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})});function fo({title:e,completedCount:t,totalCount:r,subtitle:s,onClick:a,secondaryAction:o,previewTasks:i}){const l=r>0&&t>=r;return d("button",{type:"button",onClick:a,className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-lg p-3 flex flex-col gap-1.5 cursor-pointer hover:border-[#555] transition-colors text-left",children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-white",children:e}),l?n(O5,{}):r>0?d("span",{className:"text-xs text-gray-500",children:["(",t,"/",r,")"]}):null]}),s&&n("p",{className:"text-xs text-gray-400 m-0 leading-snug",children:s}),i&&i.length>0&&n("div",{className:"flex flex-col gap-1 mt-0.5",children:i.map(c=>d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[11px] truncate flex-1 ${c.completed?"text-gray-300":"text-gray-500"}`,children:c.label}),c.completed&&n("span",{className:"shrink-0 w-3.5 h-3.5 rounded-full bg-green-600 flex items-center justify-center",children:n("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})})]},c.label))}),o&&n("span",{role:"link",onClick:c=>{c.stopPropagation(),o.onClick()},className:"text-xs text-[#D7FF63]/70 hover:text-[#D7FF63] text-left truncate mt-0.5",children:o.label})]})}function L5({onNavigateToRoadmap:e,onSwitchToBuild:t}){const[r,s]=A(null),a=oe(()=>{fetch("/api/editor-roadmap").then(m=>m.json()).then(m=>s(m)).catch(()=>{})},[]);if(ne(()=>{a()},[a]),!r)return null;const o=r.plan.filter(m=>m.completed).length,i=r.plan.length,l=r.deploy.filter(m=>m.completed).length,c=r.deploy.length,p=r.buildSessionCount===1?"1 working session":`${r.buildSessionCount} working sessions`,u=r.featureName&&r.editorStepLabel?`${r.featureName} — ${r.editorStepLabel}`:r.featureName?r.featureName:null,h=m=>{const f=[...m].reverse().find(g=>g.completed),y=m.filter(g=>!g.completed);if(f){const g=[{label:f.label,completed:!0}];return y.length>0&&g.push({label:y[0].label,completed:!1}),g}return y.slice(0,2).map(g=>({label:g.label,completed:!1}))};return d("div",{children:[n("span",{className:"text-xs font-bold text-gray-400 uppercase tracking-wider font-['IBM_Plex_Mono']",children:"Roadmap"}),d("div",{className:"grid grid-cols-3 gap-3 mt-2",children:[n(fo,{title:"Plan",completedCount:o,totalCount:i,onClick:e,previewTasks:h(r.plan)}),n(fo,{title:"Build",completedCount:r.buildSessionCount,totalCount:0,subtitle:p,onClick:e,secondaryAction:u?{label:u,onClick:t}:void 0}),n(fo,{title:"Deploy",completedCount:l,totalCount:c,onClick:e,previewTasks:h(r.deploy)})]})]})}function Lo(e){return{name:z5(e),description:B5(e),colors:Y5(e),fonts:W5(e),typographyScale:U5(e),radiusTokens:J5(e)}}function z5(e){const t=e.match(/^# (.+)$/m);return t?t[1].trim():"Design System"}function B5(e){const t=e.match(/^> (.+)$/m);return t?t[1].trim():""}function Y5(e){const t=[],r=Vi(e,"Colors");if(!r)return t;const s=K5(r);for(const{heading:a,content:o}of s){const i=_p(o);for(const l of i){const c=/--([a-zA-Z0-9_-]+):\s*([^;]+);(?:\s*\/\*\s*(.+?)\s*\*\/)?/g;let p;for(;(p=c.exec(l))!==null;){const u=p[2].trim();G5(u)&&t.push({name:p[1],value:u,group:a,...p[3]?{comment:p[3]}:{}})}}}return t}function W5(e){const t=e.match(/\*\*Font stack:\*\*\s*`([^`]+)`(?:\s*\([^)]*\))?(?:,\s*`([^`]+)`)?/);if(!t)return[];const r=[];if(t[1]){const a=go(t[1]);a&&r.push(a)}if(t[2]){const a=go(t[2]);a&&!r.includes(a)&&r.push(a)}const s=e.match(/\*\*Font stack:\*\*\s*`[^`]+`[^`]*`[^`]+`[^`]*`([^`]+)`/);if(s){const a=go(s[1]);a&&!r.includes(a)&&r.push(a)}return r}function go(e){return e.split(",")[0].trim().replace(/'/g,"")||null}function U5(e){const t=[],r=Vi(e,"Typography");if(!r)return t;const s=r.split(`
681
- `).filter(a=>a.startsWith("|"));if(s.length<3)return t;for(let a=2;a<s.length;a++){const o=s[a].split("|").map(i=>i.trim()).filter(Boolean);o.length>=3&&t.push({style:o[0],size:o[1],weight:o[2],notes:o.slice(3).join(" | ")})}return t}function J5(e){const t=[],r=Vi(e,"Spacing");if(!r)return t;const s=_p(r);for(const a of s){const o=/--radius-([a-zA-Z0-9_-]+):\s*([^;]+);(?:\s*\/\*\s*(.+?)\s*\*\/)?/g;let i;for(;(i=o.exec(a))!==null;)t.push({name:`radius-${i[1]}`,value:i[2].trim(),...i[3]?{comment:i[3]}:{}})}return t}function H5(e,t,r){const s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`(--${s}:\\s*)([^;]+)(;.*)`,"g");return e.replace(a,`$1${r}$3`)}function V5(e,t){return e.replace(/(\*\*Font stack:\*\*\s*`)([^`]+)(`)/,`$1${t}$3`)}function Vi(e,t){const s=new RegExp(`^## .*${t}.*$`,"im").exec(e);if(!s)return null;const a=s.index+s[0].length,o=e.indexOf(`
682
- ## `,a);return o===-1?e.slice(a):e.slice(a,o)}function K5(e){const t=[],r=e.split(/^### /m);for(let s=0;s<r.length;s++){if(s===0){const o=r[s].trim();o&&t.push({heading:"General",content:o});continue}const a=r[s].indexOf(`
683
- `);a===-1?t.push({heading:r[s].trim(),content:""}):t.push({heading:r[s].slice(0,a).trim(),content:r[s].slice(a+1)})}return t}function _p(e){const t=[],r=/```css\n([\s\S]*?)```/g;let s;for(;(s=r.exec(e))!==null;)t.push(s[1]);return t}function G5(e){return!!(e.startsWith("#")||e.startsWith("rgb")||e.startsWith("hsl")||e.startsWith("var(--"))}const Vc=[{key:"languages",label:"Languages"},{key:"frameworks",label:"Frameworks"},{key:"databases",label:"Databases"},{key:"services",label:"External Services"},{key:"libraries",label:"Key Libraries"},{key:"infrastructure",label:"Infrastructure"}];function Kc({todo:e,expanded:t,onToggle:r,onRemove:s,children:a}){return d("div",{children:[d("div",{className:"flex items-center gap-2 py-1.5 group cursor-pointer",onClick:r,children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-gray-500 transition-transform ${t?"rotate-90":""}`,children:n("path",{d:"M3 1l4 4-4 4"})}),d("span",{className:`text-sm flex-1 ${e.completed?"text-white":"text-gray-500"}`,children:[e.label,e.autoDetect&&!e.userCreated&&n("span",{className:"text-[10px] text-gray-600 ml-1.5",children:"(auto)"})]}),e.completed&&n("span",{className:"shrink-0 w-5 h-5 rounded-full bg-green-600 flex items-center justify-center",children:n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}),e.userCreated&&s&&n("button",{type:"button",onClick:o=>{o.stopPropagation(),s()},className:"opacity-0 group-hover:opacity-100 text-gray-600 hover:text-red-400 bg-transparent border-none cursor-pointer p-0 transition-opacity",title:"Remove",children:n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:n("path",{d:"M2 2l8 8M10 2l-8 8"})})})]}),t&&a]})}function Gc({title:e,completedCount:t,totalCount:r}){const s=r>0&&t>=r;return d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-sm font-medium text-white m-0",children:e}),s?n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#D7FF63",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})}):r>0?d("span",{className:"text-xs text-gray-500",children:[t,"/",r]}):null]})}const q5={feature:"bg-[#005c75]",fix:"bg-amber-700",refactor:"bg-purple-700",scaffold:"bg-green-700",data:"bg-blue-700",milestone:"bg-yellow-600"};function Q5(e){try{return new Date(e).toLocaleDateString([],{month:"short",day:"numeric"})}catch{return""}}function Z5({designSystem:e,onEdit:t}){const r=e.colors.filter(s=>s.value.startsWith("#")).slice(0,10);return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-xs font-medium text-gray-200 mb-2",children:e.name}),r.length>0&&n("div",{className:"flex gap-1.5 mb-2 flex-wrap",children:r.map(s=>n("div",{className:"w-5 h-5 rounded border border-[#444]",style:{backgroundColor:s.value},title:`--${s.name}: ${s.value}`},`${s.group}-${s.name}`))}),e.fonts.length>0&&d("div",{className:"text-[10px] text-gray-500 mb-2",children:["Font: ",e.fonts.join(", ")]}),t&&n("button",{type:"button",onClick:t,className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors font-medium",children:"View & Edit >"})]})}function qc({projectTitle:e,projectDescription:t,onSave:r,onEditNavigate:s,defaultEditing:a=!1}){const[o,i]=A(a),[l,c]=A(e||""),[p,u]=A(t||""),[h,m]=A(!1);ne(()=>{c(e||""),u(t||"")},[e,t]);const f=()=>{m(!0),r(l,p),m(!1),i(!1)},y=()=>{c(e||""),u(t||""),i(!1)};return o?n("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:d("div",{className:"space-y-2.5",children:[d("div",{children:[n("label",{className:"block text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1",children:"Project Name"}),n("input",{type:"text",value:l,onChange:g=>c(g.target.value),placeholder:"My App",className:"w-full px-2.5 py-1.5 text-sm bg-[#2a2a2a] border border-[#3d3d3d] rounded-md text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"})]}),d("div",{children:[n("label",{className:"block text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1",children:"Description"}),n("textarea",{value:p,onChange:g=>u(g.target.value),placeholder:"A brief description of your project...",rows:2,className:"w-full px-2.5 py-1.5 text-sm bg-[#2a2a2a] border border-[#3d3d3d] rounded-md text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors resize-none"})]}),d("div",{className:"flex gap-2 pt-0.5",children:[n("button",{type:"button",onClick:f,disabled:h,className:"px-3 py-1 text-[11px] text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium disabled:opacity-50",children:h?"Saving...":"Save"}),n("button",{type:"button",onClick:y,className:"px-3 py-1 text-[11px] text-gray-400 bg-transparent border border-[#3d3d3d] rounded-md hover:text-white hover:border-[#555] transition-colors cursor-pointer",children:"Cancel"})]})]})}):d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[e?n("div",{className:"text-xs font-medium text-gray-200 mb-0.5",children:e}):n("div",{className:"text-xs text-gray-500 italic mb-0.5",children:"No name set"}),t&&n("div",{className:"text-[11px] text-gray-400 leading-relaxed",children:t}),n("button",{type:"button",onClick:s??(()=>i(!0)),className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-1.5 cursor-pointer transition-colors font-medium",children:"Edit >"})]})}function X5({techStack:e,onNavigate:t}){if(!(e&&Vc.some(({key:i})=>e[i]&&e[i].length>0)))return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-xs text-gray-400 mb-2",children:"No tech stack configured yet"}),t&&n("button",{type:"button",onClick:t,className:"px-3 py-1.5 text-[11px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer",children:"Set up with Claude >"})]});const s=[];for(const{key:i}of Vc){const l=e[i];if(l)for(const c of l)s.push(c)}const a=s.slice(0,5),o=s.length-5;return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[d("div",{className:"flex flex-wrap gap-1.5",children:[a.map((i,l)=>d("span",{className:"inline-flex items-center gap-1 text-xs text-gray-300 bg-[#2a2a2a] px-2 py-0.5 rounded",children:[i.name,i.version&&d("span",{className:"text-[10px] text-gray-500",children:["v",i.version]})]},l)),o>0&&d("span",{className:"text-[10px] text-gray-500 self-center",children:["+",o," more"]})]}),t&&n("button",{type:"button",onClick:t,className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-2 cursor-pointer transition-colors font-medium",children:"View all >"})]})}function yo({iconType:e,size:t=14,className:r=""}){const s={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",className:r};switch(e){case"desktop":return d("svg",{...s,children:[n("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n("path",{d:"M8 21h8M12 17v4"})]});case"laptop":return d("svg",{...s,children:[n("path",{d:"M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8H4V6z"}),n("path",{d:"M2 18h20"})]});case"tablet":return d("svg",{...s,children:[n("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]});case"mobile":return d("svg",{...s,children:[n("rect",{x:"7",y:"2",width:"10",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]})}}function Qc({open:e,size:t=12}){return e?d("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),n("circle",{cx:"12",cy:"12",r:"3"})]}):d("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"}),n("path",{d:"M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"}),n("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),n("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}const ek=new Set(yp.flatMap(e=>e.presets.map(t=>t.name)));function Zc({screenSizes:e,projectScreenSizes:t,defaultScreenSize:r,appFormats:s,onSave:a,onEditNavigate:o,defaultEditing:i=!1}){const l=le(()=>xp(e,s),[e,s]),c=le(()=>{if(e){for(const[B,Y]of Object.entries(e))if(Y.default)return B}return(r==null?void 0:r.name)||""},[e,r]),[p,u]=A(i),[h,m]=A({}),[f,y]=A(new Set),[g,x]=A(""),[b,v]=A(""),[N,w]=A(""),[C,S]=A(""),k=()=>{const B={};for(const L of l)B[L.name]={width:L.width,height:L.height};m(B);const Y=new Set,I=t||e;if(I)for(const L of Object.keys(I)){const P=I[L];(t||!P||!("default"in P))&&Y.add(L)}y(Y),x(c),v(""),w(""),S(""),u(!0)};ne(()=>{i&&k()},[]);const j=(B,Y,I)=>{m(L=>{const P={...L};if(P[B]){if(delete P[B],y(R=>{const E=new Set(R);return E.delete(B),E}),B===g){const R=Object.keys(P);x(R[0]||"")}}else P[B]={width:Y,height:I},Object.keys(L).length===0&&x(B);return P})},_=B=>{y(Y=>{const I=new Set(Y);return I.has(B)?I.delete(B):I.add(B),I})},F=B=>{h[B]&&x(B)},M=()=>{const B=b.trim(),Y=parseInt(N,10),I=parseInt(C,10);!B||isNaN(Y)||isNaN(I)||Y<=0||I<=0||(m(L=>(Object.keys(L).length===0&&x(B),{...L,[B]:{width:Y,height:I}})),v(""),w(""),S(""))},$=B=>{m(Y=>{const I={...Y};return delete I[B],B===g&&x(Object.keys(I)[0]||""),I}),y(Y=>{const I=new Set(Y);return I.delete(B),I})},O=()=>{const B={};for(const[I,L]of Object.entries(h))B[I]={width:L.width,height:L.height,...I===g?{default:!0}:{}};const Y={};for(const I of f)h[I]&&(Y[I]={...h[I]});a(B,Y),u(!1)};if(p){const B=Object.entries(h).filter(([Y])=>!ek.has(Y));return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[d("div",{className:"flex items-center gap-2 mb-2 px-0.5",children:[n("div",{className:"w-3.5"}),n("div",{className:"w-3.5"}),n("span",{className:"text-[9px] font-semibold text-gray-600 uppercase tracking-wider flex-1",children:"Size"}),n("span",{className:"text-[9px] font-semibold text-gray-600 uppercase tracking-wider w-[72px] text-right",children:"Dimensions"}),n("span",{className:"text-[9px] font-semibold text-gray-600 uppercase tracking-wider w-[50px] text-center",title:"Include in project screenshot sizes",children:"Project"}),n("span",{className:"text-[9px] font-semibold text-gray-600 uppercase tracking-wider w-[54px] text-center",children:"Default"})]}),d("div",{className:"space-y-3",children:[yp.map(Y=>d("div",{children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1.5",children:Y.category}),n("div",{className:"space-y-0.5",children:Y.presets.map(I=>{const L=!!h[I.name],P=g===I.name,R=f.has(I.name),E=Is(I);return d("div",{className:"flex items-center gap-2 py-0.5",children:[n("button",{type:"button",onClick:()=>j(I.name,I.width,I.height),className:`w-3.5 h-3.5 rounded-sm border flex items-center justify-center shrink-0 cursor-pointer transition-colors ${L?"bg-[#D7FF63] border-[#D7FF63]":"bg-transparent border-[#555] hover:border-[#888]"}`,children:L&&n("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"#1e1e1e",strokeWidth:"3.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}),n(yo,{iconType:E,size:14,className:L?"text-gray-300":"text-gray-600"}),n("span",{className:`text-xs flex-1 ${L?"text-gray-300":"text-gray-500"}`,children:I.name}),d("span",{className:"text-[10px] text-gray-500 tabular-nums w-[72px] text-right",children:[I.width," × ",I.height]}),n("div",{className:"w-[50px] flex justify-center",children:L?n("button",{type:"button",onClick:()=>_(I.name),className:`p-1 rounded cursor-pointer transition-colors ${R?"text-[#D7FF63] hover:text-[#D7FF63]/70":"text-gray-600 hover:text-gray-400"}`,title:R?"In project screenshots":"Not in project screenshots",children:n(Qc,{open:R})}):n("span",{className:"w-3"})}),n("div",{className:"w-[54px] flex justify-center",children:L?n("button",{type:"button",onClick:()=>F(I.name),className:`text-[10px] px-1.5 py-0.5 rounded border cursor-pointer transition-colors ${P?"text-[#1e1e1e] bg-[#D7FF63] border-[#D7FF63]":"text-gray-500 bg-transparent border-[#444] hover:border-[#666] hover:text-gray-300"}`,title:P?"Default size":"Set as default",children:P?"★":"☆"}):n("span",{className:"w-3"})})]},I.name)})})]},Y.category)),B.length>0&&d("div",{children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1.5",children:"Custom"}),n("div",{className:"space-y-0.5",children:B.map(([Y,I])=>{const L=g===Y,P=f.has(Y),R=Is({name:Y,width:I.width,height:I.height});return d("div",{className:"flex items-center gap-2 py-0.5",children:[n("div",{className:"w-3.5"}),n(yo,{iconType:R,size:14,className:"text-gray-300"}),n("span",{className:"text-xs text-gray-300 flex-1",children:Y}),d("span",{className:"text-[10px] text-gray-500 tabular-nums w-[72px] text-right",children:[I.width," × ",I.height]}),n("div",{className:"w-[50px] flex justify-center",children:n("button",{type:"button",onClick:()=>_(Y),className:`p-1 rounded cursor-pointer transition-colors ${P?"text-[#D7FF63] hover:text-[#D7FF63]/70":"text-gray-600 hover:text-gray-400"}`,title:P?"In project screenshots":"Not in project screenshots",children:n(Qc,{open:P})})}),n("div",{className:"w-[54px] flex justify-center",children:n("button",{type:"button",onClick:()=>F(Y),className:`text-[10px] px-1.5 py-0.5 rounded border cursor-pointer transition-colors ${L?"text-[#1e1e1e] bg-[#D7FF63] border-[#D7FF63]":"text-gray-500 bg-transparent border-[#444] hover:border-[#666] hover:text-gray-300"}`,title:L?"Default size":"Set as default",children:L?"★":"☆"})}),n("button",{type:"button",onClick:()=>$(Y),className:"text-gray-600 hover:text-red-400 bg-transparent border-none p-0.5 cursor-pointer transition-colors text-xs leading-none",children:"×"})]},Y)})})]}),d("div",{children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1.5",children:"Add Custom Size"}),d("div",{className:"flex items-center gap-1.5",children:[n("input",{type:"text",value:b,onChange:Y=>v(Y.target.value),placeholder:"Name",className:"flex-1 min-w-0 px-2 py-1 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("input",{type:"number",value:N,onChange:Y=>w(Y.target.value),placeholder:"W",className:"w-14 px-2 py-1 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("span",{className:"text-[10px] text-gray-500",children:"×"}),n("input",{type:"number",value:C,onChange:Y=>S(Y.target.value),placeholder:"H",className:"w-14 px-2 py-1 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("button",{type:"button",onClick:M,className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors font-medium",children:"+ Add"})]})]})]}),d("div",{className:"flex gap-2 pt-2.5",children:[n("button",{type:"button",onClick:O,className:"px-3 py-1 text-[11px] text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium",children:"Save"}),n("button",{type:"button",onClick:()=>u(!1),className:"px-3 py-1 text-[11px] text-gray-400 bg-transparent border border-[#3d3d3d] rounded-md hover:text-white hover:border-[#555] transition-colors cursor-pointer",children:"Cancel"})]})]})}if(l.length===0)return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-xs text-gray-500 italic",children:"No screen sizes configured"}),n("button",{type:"button",onClick:o??k,className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-1.5 cursor-pointer transition-colors font-medium",children:"Edit >"})]});const D=B=>c===B,T=B=>{var Y;return!!((Y=t||e)!=null&&Y[B])};return d("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"flex flex-wrap gap-1.5",children:l.map(B=>{const Y=Is(B);return d("span",{className:"inline-flex items-center gap-1.5 text-xs bg-[#2a2a2a] px-2 py-1 rounded text-gray-300",children:[n(yo,{iconType:Y,size:12,className:"text-gray-400"}),B.name,d("span",{className:"text-[10px] text-gray-500",children:[B.width,"×",B.height]}),D(B.name)&&n("span",{className:"text-[10px] text-[#D7FF63]",children:"★"}),T(B.name)&&n("span",{className:"text-[10px] text-[#D7FF63]",title:"Project screenshot size",children:"P"})]},B.name)})}),n("button",{type:"button",onClick:o??k,className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-2 cursor-pointer transition-colors font-medium",children:"Edit >"})]})}function tk({onBack:e,onSwitchToBuild:t,onSwitchToHistory:r,onNavigateToDesignSystem:s,onNavigateToTechStack:a,expandedTasks:o,onExpandedTasksChange:i}){const{revalidate:l}=Rt(),[c,p]=A(null),[u,h]=A(!1),[m,f]=A(null),y=oe(()=>{fetch("/api/editor-roadmap").then(T=>T.json()).then(T=>p(T)).catch(()=>{})},[]);ne(()=>{y()},[y]);const g=(c==null?void 0:c.plan.some(T=>T.id==="plan-design-system"&&T.completed))??!1;ne(()=>{if(!g){f(null);return}fetch("/api/editor-design-system").then(T=>T.json()).then(T=>{T.exists&&T.content?f(Lo(T.content)):f(null)}).catch(()=>f(null))},[g]);const x=oe(T=>{h(!0),fetch("/api/editor-roadmap",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(T)}).then(B=>B.json()).then(()=>y()).catch(()=>{}).finally(()=>h(!1))},[y]),b=oe((T,B)=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectTitle:T,projectDescription:B})}).then(()=>y()).catch(()=>{})},[y]),v=oe((T,B)=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenSizes:T,projectScreenSizes:B})}).then(()=>{y(),l()}).catch(()=>{})},[y,l]),N=oe((T,B)=>{if(!c)return;const Y=c[T].filter(I=>I.id!==B);p({...c,[T]:Y}),x({[T]:Y})},[c,x]),[w,C]=A(null),S=ye(null),k=ye(0),j=oe(T=>{const B=new Set(o);B.has(T)?B.delete(T):B.add(T),i(B)},[o,i]),_=oe(T=>{S.current&&(k.current=S.current.scrollTop),C(T)},[]),F=oe(()=>{C(null),requestAnimationFrame(()=>{S.current&&(S.current.scrollTop=k.current)})},[]);if(!c)return n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:n("span",{className:"text-sm text-gray-500",children:"Loading roadmap..."})});const M=c.plan.filter(T=>T.completed).length,$=c.deploy.filter(T=>T.completed).length,O=c.buildSessionCount===1?"1 working session completed":`${c.buildSessionCount} working sessions completed`,D=w&&([...c.plan,...c.deploy].find(T=>T.id===w)??null);if(D){const T=D.id==="plan-project-name"&&D.completed?n(qc,{projectTitle:c.projectTitle,projectDescription:c.projectDescription,onSave:b,defaultEditing:!0}):D.id==="plan-screen-sizes"&&D.completed?n(Zc,{screenSizes:c.screenSizes,projectScreenSizes:c.projectScreenSizes,defaultScreenSize:c.defaultScreenSize,appFormats:c.appFormats,onSave:v,defaultEditing:!0}):null;return n("div",{className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:d("div",{className:"p-4 space-y-4",children:[d("button",{type:"button",onClick:F,className:"flex items-center gap-1.5 text-xs text-gray-500 hover:text-white bg-transparent border-none p-0 cursor-pointer transition-colors",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M15 18l-6-6 6-6"})}),"Back to Roadmap"]}),d("div",{className:"flex items-center gap-2.5",children:[n("h2",{className:"text-lg font-medium text-white mt-0 mb-0",children:D.label}),D.completed&&n("span",{className:"shrink-0 w-5 h-5 rounded-full bg-green-600 flex items-center justify-center",children:n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})})]}),T?n("div",{children:T}):n("p",{className:"text-sm text-gray-500",children:D.completed?"This task has been completed.":"This task has not been started yet."}),u&&n("span",{className:"text-[10px] text-gray-600",children:"Saving..."})]})})}return n("div",{ref:S,className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:d("div",{className:"p-4 space-y-6",children:[d("button",{type:"button",onClick:e,className:"flex items-center gap-1.5 text-xs text-gray-500 hover:text-white bg-transparent border-none p-0 cursor-pointer transition-colors",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M15 18l-6-6 6-6"})}),"Back to App"]}),n("h2",{className:"text-lg font-medium text-white mt-0 mb-6",children:"Roadmap"}),d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-lg p-4",children:[n(Gc,{title:"Plan",completedCount:M,totalCount:c.plan.length}),n("div",{className:"mt-2",children:c.plan.map(T=>d(Kc,{todo:T,expanded:o.has(T.id),onToggle:()=>j(T.id),onRemove:T.userCreated?()=>N("plan",T.id):void 0,children:[T.id==="plan-project-name"&&T.completed&&n(qc,{projectTitle:c.projectTitle,projectDescription:c.projectDescription,onSave:b,onEditNavigate:()=>_(T.id)}),T.id==="plan-tech-stack"&&n(X5,{techStack:c.techStack,onNavigate:a}),T.id==="plan-design-system"&&T.completed&&m&&n(Z5,{designSystem:m,onEdit:s}),T.id==="plan-screen-sizes"&&T.completed&&n(Zc,{screenSizes:c.screenSizes,projectScreenSizes:c.projectScreenSizes,defaultScreenSize:c.defaultScreenSize,appFormats:c.appFormats,onSave:v,onEditNavigate:()=>_(T.id)})]},T.id))})]}),d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-lg p-4",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-sm font-medium text-white m-0",children:"Build"}),n("span",{className:"text-xs text-gray-500",children:O})]}),c.featureName&&d("div",{className:"mt-3 flex items-center gap-2",children:[n("span",{className:"text-xs text-gray-400",children:"Active:"}),d("button",{type:"button",onClick:t,className:"text-xs text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors",children:[c.featureName,c.editorStepLabel&&d("span",{className:"text-gray-500 ml-1",children:["— ",c.editorStepLabel]})]})]}),!c.featureName&&c.buildSessionCount===0&&n("p",{className:"text-xs text-gray-500 m-0 mt-2",children:"No working sessions yet. Start building to track progress here."}),!c.featureName&&c.buildSessionCount>0&&c.recentEntries.length===0&&n("p",{className:"text-xs text-gray-500 m-0 mt-2",children:"No active feature. Start a new working session in the Build tab."}),c.recentEntries.length>0&&d("div",{className:"mt-3 space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Recent"}),c.recentEntries.map(T=>d("button",{type:"button",onClick:r,className:"w-full flex items-center gap-2 py-1 px-0 bg-transparent border-none cursor-pointer text-left group",children:[n("span",{className:`${q5[T.type]||"bg-gray-600"} text-white text-[8px] font-bold px-1.5 py-0.5 rounded uppercase tracking-wider shrink-0`,children:T.type}),n("span",{className:"text-xs text-gray-300 group-hover:text-white transition-colors truncate flex-1",children:T.title}),n("span",{className:"text-[10px] text-gray-600 shrink-0",children:Q5(T.time)})]},T.time)),c.buildSessionCount>3&&n("button",{type:"button",onClick:r,className:"text-xs text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 pt-1 cursor-pointer transition-colors",children:"View all working session results >"})]})]}),d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-lg p-4",children:[n(Gc,{title:"Deploy",completedCount:$,totalCount:c.deploy.length}),n("div",{className:"mt-2",children:c.deploy.map(T=>n(Kc,{todo:T,expanded:o.has(T.id),onToggle:()=>j(T.id),onRemove:T.userCreated?()=>N("deploy",T.id):void 0,children:n("p",{className:"text-xs text-gray-500 m-0 mt-1 mb-2",children:T.completed?"Completed":"Not started yet"})},T.id))})]}),u&&n("span",{className:"text-[10px] text-gray-600",children:"Saving..."})]})})}function nk({color:e,onColorChange:t}){const r=ye(null),s=rk(e.value),a=e.value.startsWith("#");return d("div",{className:"flex flex-col gap-1",children:[n("button",{type:"button",className:"w-full h-10 rounded-md border border-[#444] cursor-pointer relative group",style:{backgroundColor:e.value},onClick:()=>{var o;return a&&((o=r.current)==null?void 0:o.click())},title:`--${e.name}: ${e.value}${e.comment?` (${e.comment})`:""}`,children:a&&n("div",{className:"absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/30 rounded-md",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})}),a&&n("input",{ref:r,type:"color",value:s,onChange:o=>t(e.name,o.target.value),className:"sr-only"}),d("div",{className:"text-[9px] font-mono text-gray-500 truncate",title:`--${e.name}`,children:["--",e.name]}),n("div",{className:"text-[9px] font-mono text-gray-600 truncate",children:e.value})]})}function rk(e){if(!e.startsWith("#"))return"#000000";const t=e.slice(1);return t.length===3?`#${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`:t.length===6||t.length===8?`#${t.slice(0,6)}`:"#000000"}function sk({group:e,colors:t,onColorChange:r}){const[s,a]=A(!1);return d("div",{className:"mb-4",children:[d("button",{type:"button",onClick:()=>a(!s),className:"flex items-center gap-1.5 text-[10px] font-semibold text-gray-400 uppercase tracking-wider mb-2 bg-transparent border-none p-0 cursor-pointer hover:text-gray-300 transition-colors",children:[n("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:`transition-transform ${s?"":"rotate-90"}`,children:n("path",{d:"M9 18l6-6-6-6"})}),e,d("span",{className:"text-gray-600 font-normal",children:["(",t.length,")"]})]}),!s&&n("div",{className:"grid grid-cols-5 gap-2",children:t.map(o=>n(nk,{color:o,onColorChange:r},`${o.group}-${o.name}`))})]})}function ak({designSystem:e,rawMarkdown:t,onSave:r}){const s=e.colors.reduce((c,p)=>(c[p.group]||(c[p.group]=[]),c[p.group].push(p),c),{}),a=oe((c,p)=>{const u=H5(t,c,p);r(u)},[t,r]),[o,i]=A(e.fonts.length>0?e.fonts.join(", "):""),l=oe(()=>{if(!o.trim())return;const c=V5(t,`'${o.trim()}', sans-serif`);r(c)},[t,o,r]);return d("div",{className:"space-y-6",children:[Object.keys(s).length>0&&d("div",{children:[n("h4",{className:"text-xs font-medium text-white mb-3",children:"Colors"}),Object.entries(s).map(([c,p])=>n(sk,{group:c,colors:p,onColorChange:a},c))]}),e.fonts.length>0&&d("div",{children:[n("h4",{className:"text-xs font-medium text-white mb-3",children:"Typography"}),d("div",{className:"flex items-center gap-2 mb-3",children:[n("label",{className:"text-[10px] text-gray-500 uppercase tracking-wider shrink-0",children:"Font"}),n("input",{type:"text",value:o,onChange:c=>i(c.target.value),onBlur:l,onKeyDown:c=>c.key==="Enter"&&l(),className:"flex-1 px-2 py-1 text-xs bg-[#222] border border-[#3d3d3d] rounded text-gray-300 outline-none focus:border-[#D7FF63]/50"})]}),e.typographyScale.length>0&&n("div",{className:"bg-[#222] rounded border border-[#333] overflow-hidden",children:d("table",{className:"w-full",children:[n("thead",{children:d("tr",{className:"border-b border-[#333]",children:[n("th",{className:"text-left px-3 py-1.5 text-[9px] font-semibold text-gray-500 uppercase tracking-wider",children:"Style"}),n("th",{className:"text-left px-3 py-1.5 text-[9px] font-semibold text-gray-500 uppercase tracking-wider",children:"Size"}),n("th",{className:"text-left px-3 py-1.5 text-[9px] font-semibold text-gray-500 uppercase tracking-wider",children:"Weight"})]})}),n("tbody",{children:e.typographyScale.map(c=>d("tr",{className:"border-b border-[#333] last:border-b-0",children:[n("td",{className:"px-3 py-1.5 text-xs text-gray-300",children:c.style}),n("td",{className:"px-3 py-1.5 text-xs font-mono text-gray-400",children:c.size}),n("td",{className:"px-3 py-1.5 text-xs font-mono text-gray-400",children:c.weight})]},c.style))})]})})]}),e.radiusTokens.length>0&&d("div",{children:[n("h4",{className:"text-xs font-medium text-white mb-3",children:"Border Radius"}),n("div",{className:"flex gap-3 flex-wrap",children:e.radiusTokens.map(c=>d("div",{className:"flex flex-col items-center gap-1",children:[n("div",{className:"w-10 h-10 bg-[#D7FF63]/20 border border-[#D7FF63]/40",style:{borderRadius:c.value}}),d("div",{className:"text-[9px] font-mono text-gray-500",children:["--",c.name]}),n("div",{className:"text-[9px] font-mono text-gray-600",children:c.value})]},c.name))})]})]})}function ok({content:e,onSave:t}){const[r,s]=A(e),[a,o]=A(!1);ne(()=>{s(e),o(!1)},[e]);const i=oe(()=>{t(r),o(!1)},[r,t]);return d("div",{className:"flex flex-col gap-2 h-full",children:[n("textarea",{value:r,onChange:l=>{s(l.target.value),o(!0)},className:"flex-1 min-h-[400px] p-3 text-xs font-mono bg-[#1a1a1a] border border-[#3d3d3d] rounded-lg text-gray-300 outline-none focus:border-[#D7FF63]/50 resize-none leading-relaxed",spellCheck:!1}),d("div",{className:"flex items-center gap-2",children:[n("button",{type:"button",onClick:i,disabled:!a,className:`px-4 py-1.5 text-xs rounded-md font-medium transition-colors cursor-pointer ${a?"text-[#1e1e1e] bg-[#D7FF63] hover:bg-[#D7FF63]/80":"text-gray-500 bg-[#333] cursor-not-allowed"}`,children:"Save"}),a&&n("span",{className:"text-[10px] text-gray-500",children:"Unsaved changes"})]})]})}function ik({onClose:e}){return n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(un,{prompt:`# Edit Design System
684
-
685
- You are helping the user edit their design system file at \`.codeyam/design-system.md\`.
686
-
687
- Read the current design system file first, then ask the user what they'd like to change. Common changes include:
688
- - Changing colors (background, text, accent colors)
689
- - Switching fonts or typography scale
690
- - Adjusting spacing, radius, or shadow values
691
- - Adding or removing theme modes (light/dark)
692
- - Changing the overall aesthetic (minimal, bold, editorial, etc.)
693
-
694
- After making changes, briefly summarize what was updated.`,height:500,onClose:e})})}function lk({onBack:e,onPreviewShowcase:t}){const[r,s]=A("visual"),[a,o]=A(null),[i,l]=A(null),[c,p]=A(!1),[u,h]=A(!1),m=oe(()=>{fetch("/api/editor-design-system").then(g=>g.json()).then(g=>{g.exists&&g.content&&(o(g.content),l(Lo(g.content)))}).catch(()=>{})},[]);ne(()=>{m()},[m]),ne(()=>{if(r!=="claude"||!u)return;const g=setInterval(m,3e3);return()=>clearInterval(g)},[r,u,m]);const f=oe(g=>{p(!0),o(g),l(Lo(g)),fetch("/api/editor-design-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:g})}).then(()=>{t()}).catch(()=>{}).finally(()=>p(!1))},[t]);if(!a||!i)return n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:n("span",{className:"text-sm text-gray-500",children:"Loading design system..."})});const y=[{id:"visual",label:"Visual"},{id:"markdown",label:"Markdown"},{id:"claude",label:"Claude"}];return n("div",{className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:d("div",{className:"p-4 space-y-4",children:[d("button",{type:"button",onClick:e,className:"flex items-center gap-1.5 text-xs text-gray-500 hover:text-white bg-transparent border-none p-0 cursor-pointer transition-colors",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M15 18l-6-6 6-6"})}),"Back to Roadmap"]}),d("div",{className:"flex items-center justify-between",children:[d("div",{children:[n("h2",{className:"text-lg font-medium text-white m-0",children:i.name}),i.description&&n("p",{className:"text-xs text-gray-500 m-0 mt-1 max-w-md",children:i.description})]}),d("button",{type:"button",onClick:t,className:"flex items-center gap-1.5 px-3 py-1.5 text-xs text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium",children:[d("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),n("circle",{cx:"12",cy:"12",r:"3"})]}),"Preview Components"]})]}),n("div",{className:"flex gap-1 bg-[#222] rounded-lg p-0.5 w-fit border border-[#333]",children:y.map(g=>n("button",{type:"button",onClick:()=>{s(g.id),g.id==="claude"&&h(!0)},className:`px-3 py-1 text-xs rounded-md transition-colors cursor-pointer border-none ${r===g.id?"bg-[#3a3a3a] text-white font-medium":"bg-transparent text-gray-500 hover:text-gray-300"}`,children:g.label},g.id))}),d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-lg p-4",children:[r==="visual"&&n(ak,{designSystem:i,rawMarkdown:a,onSave:f}),r==="markdown"&&n(ok,{content:a,onSave:f}),r==="claude"&&u&&n(ik,{onClose:()=>{h(!1),m()}}),r==="claude"&&!u&&d("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[n("p",{className:"text-xs text-gray-500",children:"Use Claude to make design system changes with natural language."}),n("button",{type:"button",onClick:()=>h(!0),className:"px-4 py-2 text-xs text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium",children:"Start Claude Chat"})]})]}),c&&n("span",{className:"text-[10px] text-gray-600",children:"Saving..."})]})})}const js=[{key:"languages",label:"Languages"},{key:"frameworks",label:"Frameworks"},{key:"databases",label:"Databases"},{key:"services",label:"External Services"},{key:"libraries",label:"Key Libraries"},{key:"infrastructure",label:"Infrastructure"}];function ck({onBack:e}){const[t,r]=A(null),[s,a]=A(!1),[o,i]=A(!1),[l,c]=A({}),[p,u]=A(!1),h=typeof window<"u"?window.location.origin:"",m=oe(()=>{fetch("/api/editor-project-info").then(S=>S.json()).then(S=>{r(S.techStack||null),a(!0)}).catch(()=>a(!0))},[]);ne(()=>{m()},[m]);const f=oe(S=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({techStack:S})}).then(()=>m()).catch(()=>{})},[m]),y=()=>{c(t?JSON.parse(JSON.stringify(t)):{}),i(!0)},g=()=>{const S={};for(const{key:k}of js){const j=l[k];j&&j.length>0&&(S[k]=j.filter(_=>_.name.trim()!==""))}f(S),i(!1)},x=S=>{c(k=>({...k,[S]:[...k[S]||[],{name:"",url:"",description:""}]}))},b=(S,k)=>{c(j=>({...j,[S]:(j[S]||[]).filter((_,F)=>F!==k)}))},v=(S,k,j,_)=>{c(F=>({...F,[S]:(F[S]||[]).map((M,$)=>$===k?{...M,[j]:_}:M)}))},N=(S,k,j)=>{const _=j.split(",").map(F=>F.trim()).filter(Boolean);c(F=>({...F,[S]:(F[S]||[]).map((M,$)=>$===k?{...M,envKeys:_}:M)}))},w=le(()=>`# Detect and Set Up Tech Stack
695
-
696
- You are helping the user configure their project's tech stack in CodeYam.
697
-
698
- ## Instructions
699
-
700
- 1. Read \`package.json\` to find all dependencies and devDependencies
701
- 2. Check for framework config files: \`next.config.js\`, \`next.config.ts\`, \`tailwind.config.js\`, \`prisma/schema.prisma\`, \`tsconfig.json\`, \`vite.config.ts\`, etc.
702
- 3. Check \`.env\`, \`.env.example\`, \`.env.local\` for service references (e.g., STRIPE_SECRET_KEY, DATABASE_URL, OPENAI_API_KEY)
703
- 4. Categorize everything into: languages, frameworks, databases, services, libraries, infrastructure
704
-
705
- ## Tech Stack Categories
706
-
707
- - **languages**: Programming languages (TypeScript, JavaScript, Python, etc.)
708
- - **frameworks**: Application frameworks (Next.js, React, Express, etc.)
709
- - **databases**: Database systems (PostgreSQL, SQLite, MongoDB, etc.)
710
- - **services**: External services/APIs (Stripe, Auth0, SendGrid, AWS S3, etc.) — include \`url\` and \`envKeys\` for each
711
- - **libraries**: Key libraries beyond the framework (Prisma, Tailwind CSS, Zod, etc.)
712
- - **infrastructure**: Deployment/infrastructure tools (Vercel, Docker, etc.)
713
-
714
- ## Output Format
715
-
716
- After scanning, POST the tech stack:
717
-
718
- \`\`\`bash
719
- curl -s -X POST ${h}/api/editor-project-info \\
720
- -H "Content-Type: application/json" \\
721
- -d '{"techStack":{"languages":[{"name":"TypeScript","url":"https://typescriptlang.org","description":"Statically typed JavaScript superset","version":"5"}],"frameworks":[{"name":"Next.js","url":"https://nextjs.org","description":"Full-stack React framework with SSR and API routes","version":"15"}],"databases":[{"name":"SQLite","url":"https://sqlite.org","description":"Embedded relational database"}],"services":[{"name":"Stripe","url":"https://stripe.com","description":"Payment processing and billing","envKeys":["STRIPE_SECRET_KEY","STRIPE_PUBLISHABLE_KEY"]}],"libraries":[{"name":"Prisma","url":"https://prisma.io","description":"Type-safe database ORM and query builder","version":"7"}],"infrastructure":[]}}'
722
- \`\`\`
723
-
724
- Replace the example values with what you actually detect. For each item:
725
- - \`name\` (required): Technology name
726
- - \`url\` (required): Link to homepage or docs
727
- - \`description\` (required): Brief description of what it does or how it's used in this project
728
- - \`version\` (optional): Version number
729
- - \`envKeys\` (optional): Array of environment variable names associated with this tech
730
-
731
- Omit empty categories. After posting, briefly summarize what was detected.`,[h]),C=t&&js.some(({key:S})=>t[S]&&t[S].length>0);return n("div",{className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:d("div",{className:"p-4 space-y-4",children:[d("button",{type:"button",onClick:e,className:"flex items-center gap-1.5 text-xs text-gray-500 hover:text-white bg-transparent border-none p-0 cursor-pointer transition-colors",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M15 18l-6-6 6-6"})}),"Back to Roadmap"]}),d("div",{className:"flex items-center justify-between",children:[n("h2",{className:"text-lg font-medium text-white m-0",children:"Tech Stack"}),n("div",{className:"flex items-center gap-2",children:s&&!o&&!p&&(C?n("button",{type:"button",onClick:y,className:"px-3 py-1.5 text-[11px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer",children:"Edit"}):n("button",{type:"button",onClick:()=>u(!0),className:"px-3 py-1.5 text-[11px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer",children:"Set up with Claude"}))})]}),p&&n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(un,{prompt:w,height:400,onClose:()=>{u(!1),m()}})}),o&&d("div",{className:"space-y-4",children:[n("button",{type:"button",onClick:()=>{i(!1),u(!0)},className:"px-3 py-1.5 text-[11px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer",children:"Re-detect with Claude"}),js.map(({key:S,label:k})=>{const j=l[S]||[];return d("div",{children:[d("div",{className:"flex items-center justify-between mb-2",children:[n("label",{className:"text-[11px] font-semibold text-gray-500 uppercase tracking-wider",children:k}),n("button",{type:"button",onClick:()=>x(S),className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors",children:"+ Add"})]}),j.map((_,F)=>d("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-lg p-2.5 mb-2 space-y-1.5",children:[d("div",{className:"flex items-center gap-1.5",children:[n("input",{type:"text",value:_.name,onChange:M=>v(S,F,"name",M.target.value),placeholder:"Name *",className:"flex-1 min-w-0 px-2 py-1 text-xs bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors font-medium"}),n("input",{type:"text",value:_.version||"",onChange:M=>v(S,F,"version",M.target.value),placeholder:"Version",className:"w-20 px-2 py-1 text-xs bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("button",{type:"button",onClick:()=>b(S,F),className:"text-gray-600 hover:text-red-400 bg-transparent border-none p-0.5 cursor-pointer transition-colors text-xs leading-none",children:"×"})]}),n("input",{type:"text",value:_.url||"",onChange:M=>v(S,F,"url",M.target.value),placeholder:"URL * (e.g. https://stripe.com)",className:"w-full px-2 py-1 text-[11px] bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-300 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("input",{type:"text",value:_.description||"",onChange:M=>v(S,F,"description",M.target.value),placeholder:"Description * (e.g. Payment processing and billing)",className:"w-full px-2 py-1 text-[11px] bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-300 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("input",{type:"text",value:(_.envKeys||[]).join(", "),onChange:M=>N(S,F,M.target.value),placeholder:"ENV_KEYS (comma-separated, e.g. STRIPE_SECRET_KEY, STRIPE_PUBLISHABLE_KEY)",className:"w-full px-2 py-1 text-[10px] bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-400 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors font-mono"})]},F)),j.length===0&&n("div",{className:"text-[11px] text-gray-600 italic py-1",children:"No items"})]},S)}),d("div",{className:"flex gap-2 pt-1",children:[n("button",{type:"button",onClick:g,className:"px-4 py-1.5 text-[11px] text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium",children:"Save"}),n("button",{type:"button",onClick:()=>i(!1),className:"px-4 py-1.5 text-[11px] text-gray-400 bg-transparent border border-[#3d3d3d] rounded-md hover:text-white hover:border-[#555] transition-colors cursor-pointer",children:"Cancel"})]})]}),!o&&!p&&n(ve,{children:C?n("div",{className:"space-y-4",children:js.map(({key:S,label:k})=>{const j=t[S];return!j||j.length===0?null:d("div",{children:[n("div",{className:"text-[11px] font-semibold text-gray-500 uppercase tracking-wider mb-2",children:k}),n("div",{className:"space-y-2",children:j.map((_,F)=>d("div",{className:"bg-[#2a2a2a] rounded-lg px-3 py-2.5",children:[d("div",{className:"flex items-center gap-2",children:[_.url?n("a",{href:_.url,target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-gray-200 hover:text-[#D7FF63] transition-colors",children:_.name}):n("span",{className:"text-sm font-medium text-gray-200",children:_.name}),_.version&&d("span",{className:"text-[11px] text-gray-500",children:["v",_.version]}),_.url&&n("a",{href:_.url,target:"_blank",rel:"noopener noreferrer",className:"text-[11px] text-gray-600 hover:text-gray-400 transition-colors truncate",children:_.url.replace(/^https?:\/\//,"")})]}),_.description&&n("div",{className:"text-xs text-gray-400 mt-1",children:_.description}),_.envKeys&&_.envKeys.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-1.5",children:_.envKeys.map((M,$)=>n("span",{className:"text-[10px] text-[#D7FF63]/60 bg-[#D7FF63]/10 px-1.5 py-0.5 rounded font-mono",children:M},$))})]},F))})]},S)})}):n("div",{className:"text-xs text-gray-500 italic py-4",children:"No tech stack configured yet. Use the buttons above to set up your project's tech stack."})})]})})}function dk({hasProject:e,scenarios:t,analyzedEntities:r,allEntities:s=[],glossaryFunctions:a=[],cachedTestResults:o={},glossaryEntries:i=[],projectRoot:l,activeScenarioId:c,onScenarioSelect:p,onAnalyzedScenarioSelect:u,onSwitchToBuild:h,onSwitchToHistory:m,zoomComponent:f,focusedEntity:y,onZoomChange:g,entityImports:x,pageFilePaths:b={},projectTitle:v,projectDescription:N,migrationMode:w="none",migrationState:C,onStartMigration:S,breadcrumbItems:k=[],onReseedPreview:j,isAdmin:_=!1,roadmapView:F=!1,onRoadmapViewChange:M,designSystemView:$=!1,onDesignSystemViewChange:O,onPreviewDesignSystem:D,techStackView:T=!1,onTechStackViewChange:B}){const{pageGroups:Y,componentGroups:I}=le(()=>Hi(t),[t]),L=le(()=>wp(Y,I),[Y,I]),P=le(()=>new Set(r.map(Ne=>Ne.sha)),[r]),R=le(()=>x5(x||{}),[x]),E=oe(Ne=>b5(Ne,P,s,R),[P,s,R]),J=le(()=>{const Ne=new Map;for(const _e of s)Ne.set(_e.sha,_e.name);return Ne},[s]),K=le(()=>v5(Y,I,L,E),[Y,I,L,E]),Q=le(()=>r.filter(Ne=>Ne.entityType==="visual").sort((Ne,_e)=>Ne.name.localeCompare(_e.name)),[r]),[q,U]=A(()=>{try{return localStorage.getItem("codeyam-app-banner-dismissed")==="true"}catch{return!1}}),z=oe(()=>{U(!0);try{localStorage.setItem("codeyam-app-banner-dismissed","true")}catch{}},[]),[W,V]=A(""),[ae,pe]=A(()=>new Set),xe=ye(null),ie=ye(0),me=oe(()=>{xe.current&&(ie.current=xe.current.scrollTop)},[]);ne(()=>{xe.current&&ie.current>0&&(xe.current.scrollTop=ie.current)});const we=(y==null?void 0:y.sha)??"overview";if(!e)return n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:d("div",{className:"flex flex-col items-center gap-4",children:[n("h2",{className:"text-lg font-medium text-white m-0",children:"Ready to build something?"}),n("button",{onClick:h,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Start Building"})]})});if(w==="candidate")return n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:d("div",{className:"flex flex-col items-center gap-5 px-8 text-center max-w-[420px]",children:[n("h2",{className:"text-lg font-medium text-white m-0",children:"Migrate Your Project"}),n("p",{className:"text-sm text-gray-400 m-0 leading-relaxed",children:"It looks like you have an existing project. Claude can survey your codebase and systematically migrate it — deconstructing pages into clean components, extracting functions with tests, and creating scenarios. One page per session."}),n("button",{onClick:S,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Get Started"}),n("button",{onClick:h,className:"text-xs text-gray-500 hover:text-gray-300 bg-transparent border-none p-0 cursor-pointer underline",children:"Skip — build a new feature instead"})]})});if(w==="active"&&C){const Ne=C.pages||[],_e=Ne.filter(te=>te.status==="complete").length,Z=Ne.length,he=Z>0?Math.round(_e/Z*100):0;return d("div",{className:"flex-1 flex flex-col overflow-auto p-4 font-['IBM_Plex_Sans']",children:[n("h2",{className:"text-lg font-medium text-white m-0 mb-3",children:"Project Migration"}),d("div",{className:"mb-4",children:[n("div",{className:"flex items-center gap-2 mb-1",children:d("span",{className:"text-xs text-gray-400",children:[_e,"/",Z," pages (",he,"%)"]})}),n("div",{className:"w-full h-1.5 bg-[#2d2d2d] rounded-full overflow-hidden",children:n("div",{className:"h-full bg-[#005c75] rounded-full transition-all",style:{width:`${he}%`}})})]}),n("div",{className:"space-y-1.5",children:Ne.map((te,se)=>{const ce=te.status==="complete"?"✓":te.status==="in-progress"?"→":"○",je=te.status==="complete"?"text-green-400":te.status==="in-progress"?"text-cyan-400":"text-gray-600";return d("div",{className:"flex items-center gap-2",children:[n("span",{className:`text-xs ${je} w-3 text-center`,children:ce}),n("span",{className:`text-xs ${te.status==="in-progress"?"text-white font-medium":te.status==="complete"?"text-gray-400":"text-gray-600"}`,children:te.name}),n("span",{className:"text-[10px] text-gray-600",children:te.route}),te.status==="complete"&&d("span",{className:"text-[10px] text-gray-600",children:[(te.extractedComponents||[]).length,"c"," ",(te.extractedFunctions||[]).length,"f"," ",te.scenarioCount||0,"s"]})]},se)})}),(C.sharedComponents||[]).length>0&&d("div",{className:"mt-4",children:[n("h3",{className:"text-xs font-medium text-gray-400 mb-1.5",children:"Shared Components"}),(C.sharedComponents||[]).map((te,se)=>d("div",{className:"text-[10px] text-gray-500 mb-0.5",children:[te.name," ",d("span",{className:"text-gray-600",children:["— used in: ",(te.usedInPages||[]).join(", ")]})]},se))]}),n("div",{className:"mt-4",children:n("button",{onClick:h,className:"px-4 py-2 bg-[#005c75] text-white text-xs font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Continue in Chat"})})]})}return t.length>0||Q.length>0?y?n(kp,{focusedEntity:y,breadcrumbItems:k,onZoomChange:g,projectRoot:l,scenarios:t,analyzedEntities:r,activeScenarioId:c,onScenarioSelect:p,onAnalyzedScenarioSelect:u,onSwitchToBuild:h,entityImports:x,glossaryFunctions:a,cachedTestResults:o,glossaryEntries:i,entityShaMap:L,componentGroups:I,visualEntities:Q,isEntityComplete:E,onReseedPreview:j}):T?n(ck,{onBack:()=>{B==null||B(!1),M==null||M(!0)}}):$?n(lk,{onBack:()=>{O==null||O(!1),M==null||M(!0)},onPreviewShowcase:()=>D==null?void 0:D()}):_&&F?n(tk,{onBack:()=>M==null?void 0:M(!1),onSwitchToBuild:h,onSwitchToHistory:m,onNavigateToDesignSystem:()=>{M==null||M(!1),O==null||O(!0)},onNavigateToTechStack:()=>{M==null||M(!1),B==null||B(!0)},expandedTasks:ae,onExpandedTasksChange:pe}):n("div",{ref:xe,onScroll:me,className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:d("div",{className:"p-4 space-y-4 flex flex-col gap-12",children:[K.length>1&&n(S5,{brokenEntities:K}),!q&&d("div",{className:"relative border border-[#2e7d32]/40 bg-cybg rounded-lg p-4 pr-10",children:[n("button",{onClick:z,className:"absolute top-3 right-3 text-[#D7FF63] hover:text-white bg-transparent border-none cursor-pointer p-0.5",title:"Dismiss",children:n("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M2 2l8 8M10 2l-8 8"})})}),n("p",{className:"text-sm text-white font-medium m-0 leading-snug",children:"These are all the pages in your project."}),d("p",{className:"text-sm text-gray-400 m-0 leading-snug mt-0.5",children:["(1) Select a scenario below and switch to"," ",n("button",{type:"button",onClick:h,className:"underline text-[#D7FF63] bg-transparent border-none cursor-pointer p-0 text-sm inline hover:text-[#D7FF63]/70 transition-colors",children:"build"})," ","to change or enhance an existing page."]}),n("p",{className:"text-sm text-gray-400 m-0 leading-snug mt-0.5",children:"(2) Select a page to see all of its sub-components and edit scenarios."})]}),_&&n("div",{className:"mb-4",children:n(L5,{onNavigateToRoadmap:()=>M==null?void 0:M(!0),onSwitchToBuild:h})}),Y.size>0&&d("div",{children:[d("div",{className:"flex items-center gap-3 font-['IBM_Plex_Mono']",children:[n("span",{className:"text-xs font-bold text-gray-400 uppercase tracking-wider shrink-0",children:"Pages"}),n("div",{className:"flex-1"}),d("div",{className:"relative",style:{width:170},children:[d("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"11",cy:"11",r:"8"}),n("path",{d:"M21 21l-4.35-4.35"})]}),n("input",{type:"text",placeholder:"SEARCH...",value:W,onChange:Ne=>V(Ne.target.value),className:"w-full pl-9 pr-3 py-2 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded-md text-gray-300 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors tracking-wider"})]}),d("button",{onClick:h,className:"flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer shrink-0 uppercase tracking-wider",children:[n("span",{children:"+"})," New Page"]})]}),n("div",{className:"border-b border-[#2d2d2d] mt-3"}),[...Y.entries()].sort(([Ne],[_e])=>Ne==="Home"?-1:_e==="Home"?1:Ne.localeCompare(_e)).filter(([Ne])=>{if(!W.trim())return!0;const _e=L.get(Ne);return((_e?J.get(_e):void 0)||Ne).toLowerCase().includes(W.trim().toLowerCase())}).map(([Ne,_e])=>{const Z=_e.some(he=>he.id===c);return n("div",{className:"mt-2",children:L.has(Ne)&&E(L.get(Ne))?d(ve,{children:[n("div",{className:"flex items-center gap-1.5 py-1",children:d("button",{onClick:()=>g(Ne,L.get(Ne)),className:`flex items-center gap-1.5 text-sm font-normal cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0 ${Z?"text-[#D7FF63]":"text-gray-300"}`,children:[(()=>{const he=L.get(Ne);return(he?J.get(he):void 0)||Ne})(),d("span",{className:`font-normal text-sm ${Z?"text-[#D7FF63]/60":"text-gray-500"}`,children:["(",_e.length,")"]}),n("svg",{className:Z?"text-[#D7FF63]/60":"text-gray-500",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M9 18l6-6-6-6"})})]})}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:cn(_e).map(({scenario:he,dimensionLabel:te,screenshotPath:se,key:ce})=>n(Fs,{scenarioId:he.id,screenshotPath:se,updatedAt:he.updatedAt,hasScreenshot:!!se,name:he.name,dimensionLabel:te,isActive:he.id===c,onSelect:()=>p(he,te??void 0)},ce))})]}):d("div",{className:"py-2",children:[n("span",{className:"text-sm font-normal text-gray-500",children:(()=>{const he=L.get(Ne);return he&&J.get(he)||Ne})()}),d("div",{className:"flex items-center gap-2 mt-1.5",children:[d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#E0D400",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),n("p",{className:"text-xs text-[#E0D400]/80 m-0 leading-relaxed",children:"Data missing for this page."}),n(Cp,{name:Ne,scenarios:_e,reason:L.has(Ne)?"incomplete":"missing"})]})]})},Ne)})]})]})},we):n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:d("div",{className:"flex flex-col items-center gap-4 px-8 text-center",children:[v?d(ve,{children:[n("h2",{className:"text-lg font-medium text-white m-0",children:v}),N&&n("p",{className:"text-sm text-gray-400 m-0 leading-relaxed",children:N})]}):n("h2",{className:"text-lg font-medium text-white m-0",children:"Your project is ready"}),n("p",{className:"text-sm text-gray-400 m-0 leading-relaxed",children:"Describe what you want to build in the Chat and your pages and components will appear here."}),n("button",{onClick:h,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Start Building"})]})})}const Xc=[{key:"app",label:"App"},{key:"build",label:"Build"},{key:"data",label:"Structure"},{key:"history",label:"History"}],uk=()=>n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"text-[#8E8E8E] shrink-0",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})});function pk({activeTab:e,onTabChange:t,buildIdle:r,projectTitle:s,breadcrumbItems:a,onBreadcrumbNavigate:o}){const[i,l]=A(!1),c=ye(null);ne(()=>{if(!i)return;const u=h=>{c.current&&!c.current.contains(h.target)&&l(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[i]);const p=a&&a.length>0;return d("div",{className:"shrink-0 z-20 @container",children:[d("div",{className:"bg-black h-10 flex items-center px-4 gap-4",children:[d("div",{className:"flex items-center gap-3 min-w-0",children:[d("div",{className:"flex items-center gap-2 shrink-0",children:[n("img",{src:na,alt:"CodeYam",className:"h-5 shrink-0"}),n("span",{className:"text-sm font-medium text-white whitespace-nowrap hidden @min-[500px]:inline",children:"CodeYam Editor"})]}),n("span",{className:"text-[#8E8E8E] text-sm shrink-0",children:"/"}),n("div",{className:"hidden @min-[350px]:flex items-center gap-1",children:Xc.map(u=>d("button",{onClick:()=>t(u.key),className:`px-2.5 py-2.5 text-sm transition-colors cursor-pointer border-b ${e===u.key?"text-[#D7FF63] border-[#D7FF63] font-medium":"text-[#8E8E8E] border-transparent hover:text-white font-light"}`,children:[u.label,u.key==="build"&&r&&e!=="build"&&n("span",{className:"ml-1 inline-block w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"})]},u.key))})]}),n("div",{className:"flex-1"}),n("button",{onClick:()=>t("settings"),className:`hidden @min-[350px]:block p-1.5 rounded-md transition-colors cursor-pointer ${e==="settings"?"text-[#D7FF63]":"text-[#8E8E8E] hover:text-white"}`,title:"Settings",children:d("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"3"}),n("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}),d("div",{className:"@min-[350px]:hidden relative",ref:c,children:[n("button",{onClick:()=>l(!i),className:"p-1.5 rounded-md transition-colors cursor-pointer text-[#8E8E8E] hover:text-white",title:"Menu",children:d("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[n("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),n("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),n("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),i&&d("div",{className:"absolute right-0 top-full mt-1 bg-[#2d2d2d] border border-[#3d3d3d] rounded-lg shadow-lg py-1 min-w-[140px] z-50",children:[Xc.map(u=>d("button",{onClick:()=>{t(u.key),l(!1)},className:`w-full text-left px-4 py-2 text-sm transition-colors cursor-pointer bg-transparent border-none ${e===u.key?"text-[#D7FF63]":"text-[#8E8E8E] hover:text-white hover:bg-[#3d3d3d]"}`,children:[u.label,u.key==="build"&&r&&e!=="build"&&n("span",{className:"ml-1 inline-block w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"})]},u.key)),n("div",{className:"border-t border-[#3d3d3d] my-1"}),n("button",{onClick:()=>{t("settings"),l(!1)},className:`w-full text-left px-4 py-2 text-sm transition-colors cursor-pointer bg-transparent border-none ${e==="settings"?"text-[#D7FF63]":"text-[#8E8E8E] hover:text-white hover:bg-[#3d3d3d]"}`,children:"Settings"})]})]})]}),n("div",{className:`bg-[#161616] h-8 flex items-center px-4 border-b border-[#2d2d2d]${e==="build"?" hidden":""}`,children:n("nav",{className:"flex items-center gap-2 text-sm min-w-0",children:p?d(ve,{children:[n("button",{type:"button",onClick:()=>o==null?void 0:o(),className:"text-[#8E8E8E] hover:text-white transition-colors bg-transparent border-none p-0 cursor-pointer shrink-0",children:s||"Untitled Project"}),a.slice(1).map((u,h)=>{const m=h===a.length-2;return d("span",{className:"flex items-center gap-2 min-w-0",children:[n(uk,{}),m?n("span",{className:"text-white truncate",children:u.name}):n("button",{type:"button",onClick:()=>o==null?void 0:o(u.componentName,u.entitySha),className:"text-[#8E8E8E] hover:text-white transition-colors bg-transparent border-none p-0 cursor-pointer truncate",children:u.name})]},u.componentName||u.name)})]}):n("span",{className:"text-[#8E8E8E]",children:s||"Untitled Project"})})})]})}function hk({onMouseDown:e,onDoubleClick:t,isDragging:r}){return d("div",{className:"shrink-0 relative flex items-center justify-center cursor-col-resize group",style:{width:12},onMouseDown:e,onDoubleClick:t,children:[n("div",{className:"absolute inset-y-0 left-1/2 -translate-x-1/2",style:{width:r?3:1,backgroundColor:r?"#3b82f6":"#3d3d3d",transition:"width 100ms, background-color 100ms"}}),!r&&n("div",{className:"absolute inset-0 bg-blue-500/0 group-hover:bg-blue-500/20 transition-colors pointer-events-none"}),d("div",{className:"relative z-10 flex flex-col gap-[3px] opacity-0 group-hover:opacity-100 transition-opacity",style:r?{opacity:1}:void 0,children:[n("div",{className:"w-2 h-px bg-gray-400"}),n("div",{className:"w-2 h-px bg-gray-400"}),n("div",{className:"w-2 h-px bg-gray-400"})]})]})}const ed=300,As=150;function mk(e){const[t,r]=A(null),[s,a]=A(!1),o=ye(0),i=ye(null);ne(()=>{e.current&&r(Math.round(e.current.offsetWidth*.5))},[e]);const l=oe(()=>{var x;return((x=e.current)==null?void 0:x.offsetWidth)??(typeof window<"u"?window.innerWidth:1024)},[e]),c=oe(x=>{x.preventDefault(),a(!0)},[]),p=oe(()=>{r(Math.round(l()*.5))},[l]),u=oe(()=>{r(x=>(x&&x>0&&(i.current=x),0))},[]),h=oe(()=>{const x=i.current;i.current=null,r(x&&x>=ed?x:Math.round(l()*.5))},[l]),m=oe(()=>{r(Math.round(l()*.5))},[l]);ne(()=>{if(!s)return;document.body.style.cursor="col-resize",document.body.style.userSelect="none";const x=v=>{cancelAnimationFrame(o.current),o.current=requestAnimationFrame(()=>{var _;const N=(_=e.current)==null?void 0:_.getBoundingClientRect(),w=(N==null?void 0:N.left)??0,S=((N==null?void 0:N.width)??window.innerWidth)-As,k=v.clientX-w,j=Math.min(Math.max(k,ed),S);r(j)})},b=v=>{var k;cancelAnimationFrame(o.current),a(!1);const N=(k=e.current)==null?void 0:k.getBoundingClientRect(),w=(N==null?void 0:N.left)??0,C=(N==null?void 0:N.width)??window.innerWidth,S=v.clientX-w;S<As?r(0):C-S<As&&r(C)};return document.addEventListener("mousemove",x),document.addEventListener("mouseup",b),()=>{cancelAnimationFrame(o.current),document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",b),document.body.style.cursor="",document.body.style.userSelect=""}},[s,e]),ne(()=>{const x=()=>{r(b=>{if(b===null||b===0)return b;const v=l();return b>=v?v:Math.min(b,v-As)})};if(!(typeof window>"u"))return window.addEventListener("resize",x),()=>window.removeEventListener("resize",x)},[l]);const f=l(),y=t===0,g=t!==null&&t>=f;return{editorWidth:t,isDragging:s,isEditorCollapsed:y,isPreviewCollapsed:g,handleMouseDown:c,handleDoubleClick:p,collapseEditor:u,expandEditor:h,expandPreview:m}}function fk({preview:e,viewportWidth:t,viewportHeight:r,scale:s,onDismiss:a,onLoadCommit:o}){const i=t*s,l=r*s;return d("div",{className:"flex flex-col items-center gap-4 w-full",style:{maxWidth:`${i}px`},children:[d("div",{className:"text-center shrink-0",children:[n("h2",{className:"text-lg font-semibold text-[#333] m-0 font-['IBM_Plex_Sans']",children:"Journal Screenshot"}),n("p",{className:"text-sm text-[#888] mt-1 m-0 font-['IBM_Plex_Sans']",children:"This is a snapshot from a previous version — not a live preview"})]}),n("div",{className:"rounded-lg border-2 border-[#ccc] shadow-md overflow-y-auto overflow-x-hidden shrink",style:{width:`${i}px`,maxHeight:`${l}px`},children:n("img",{src:e.screenshotUrl,alt:e.scenarioName,className:"block",style:{width:`${i}px`}})}),d("div",{className:"flex items-center gap-2 text-sm text-[#666] shrink-0",children:[e.commitSha&&n("span",{className:"font-mono text-xs text-[#00a0c4] bg-[#00a0c4]/15 px-2 py-0.5 rounded",children:e.commitSha.slice(0,7)}),d("span",{className:"truncate",children:[e.scenarioName,e.commitMessage&&` — ${e.commitMessage}`]})]}),n("div",{className:"flex items-center gap-3 shrink-0",children:e.commitSha&&o&&n(gk,{commitSha:e.commitSha,onLoadCommit:o})})]})}function gk({commitSha:e,onLoadCommit:t}){const[r,s]=A(!1),[a,o]=A(null);return d(ve,{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 yk({preview:e,viewportWidth:t,viewportHeight:r,scale:s,onDismiss:a}){const o=t*s,i=r*s;return d("div",{className:"flex flex-col items-center gap-4 w-full",style:{maxWidth:`${o}px`},children:[d("div",{className:"text-center shrink-0",children:[n("h2",{className:"text-lg font-semibold text-gray-200 m-0 font-['IBM_Plex_Sans']",children:e.scenarioName}),d("div",{className:"flex items-center justify-center gap-2 mt-2",children:[n("span",{className:"inline-block w-2 h-2 rounded-full bg-amber-400 animate-pulse"}),n("p",{className:"text-sm text-amber-400/90 m-0 font-['IBM_Plex_Sans']",children:"The app is being edited - you can control the live preview when building is paused or complete."})]})]}),e.hasScreenshot?n("div",{className:"rounded-lg border-2 border-[#4d4d4d] shadow-md overflow-y-auto overflow-x-hidden shrink",style:{width:`${o}px`,maxHeight:`${i}px`},children:n(or,{scenarioId:e.scenarioId,screenshotPath:e.screenshotPath,updatedAt:e.updatedAt,alt:e.scenarioName,imgClassName:"block w-full",className:""})}):n("div",{className:"rounded-lg border-2 border-[#4d4d4d] bg-[#1a1a1a] flex items-center justify-center w-[400px] h-[300px]",children:n("span",{className:"text-sm text-gray-500",children:"No screenshot available"})}),n("button",{onClick:a,className:"text-xs text-gray-500 hover:text-gray-300 bg-transparent border-none cursor-pointer transition-colors shrink-0",children:"Dismiss"})]})}function xk({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,onStateChange:o}){const{interactiveServerUrl:i,isStarting:l,isLoading:c}=In({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:!0});return ne(()=>{o(i,l||c)},[i,l,c,o]),null}function bk({onSaveToCurrent:e,onSaveAsNew:t,onDismiss:r,isSaving:s,scenarioName:a}){return d("div",{className:"flex items-center justify-between px-4 py-1.5 bg-emerald-900/60 border-b border-emerald-700/50 text-emerald-200 text-xs",children:[n("span",{className:"font-medium",children:a?d(ve,{children:["Data modified in “",a,"”."]}):"Data modified."}),d("div",{className:"flex items-center gap-2",children:[n("button",{onClick:e,disabled:s,className:"px-2.5 py-0.5 bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white text-xs font-medium rounded transition-colors cursor-pointer disabled:cursor-not-allowed",children:s?"Saving...":"Save to Scenario"}),n("button",{onClick:t,disabled:s,className:"px-2.5 py-0.5 bg-emerald-800 hover:bg-emerald-700 disabled:opacity-50 text-emerald-200 text-xs font-medium rounded transition-colors cursor-pointer disabled:cursor-not-allowed",children:"Save as New"}),n("button",{onClick:r,disabled:s,className:"text-emerald-400 hover:text-emerald-200 disabled:opacity-50 transition-colors cursor-pointer disabled:cursor-not-allowed",title:"Dismiss",children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})}function vk({latestVersion:e}){const[t,r]=A(!1);if(t)return null;const s=`npm install -g @codeyam/codeyam-cli@${e}`;return d("div",{className:"shrink-0 w-full bg-[#D7FF63] px-4 py-1.5 flex items-center text-xs text-black font-['IBM_Plex_Sans']",children:[d("div",{className:"flex-1 flex items-center justify-center gap-2",children:[n("span",{children:"An update to the codeyam editor is available."}),n("code",{className:"bg-[#2d2d2d] text-white font-mono text-xs px-3 py-0.5 rounded-full",children:s}),n(pt,{content:s,icon:!0,iconSize:12,className:"text-black hover:text-gray-700 transition-colors"})]}),n("button",{type:"button",onClick:()=>r(!0),className:"shrink-0 p-0.5 rounded text-black/60 hover:text-black hover:bg-black/10 transition-colors cursor-pointer bg-transparent border-none","aria-label":"Dismiss upgrade banner",children:n("svg",{className:"w-3.5 h-3.5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})}function wk(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 Nk(e){const[t,r]=A({url:null,proxyUrl:null,isStarting:!1,error:null,canStartServer:!0,autoStartAttempted:!1}),s=ye(t);s.current=t,ne(()=>{let i=!1,l=null;const c=async()=>{try{const p=await fetch("/api/editor-dev-server");if(i)return;const u=await p.json(),h=wk(s.current,u),{shouldAutoStart:m,...f}=h;if(r(f),m&&!(e!=null&&e.skipAutoStart))try{const y=await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})});if(i)return;y.ok?r(g=>({...g,isStarting:!0})):r(g=>({...g,canStartServer:!1}))}catch{}}catch{}};return c(),l=setInterval(()=>void c(),2e3),()=>{i=!0,l&&clearInterval(l)}},[t.url]);const a=oe(()=>{r(i=>({...i,error:null,isStarting:!0})),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})}).catch(()=>{})},[]),o=oe(()=>{r(i=>({...i,error:null,isStarting:!0})),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}).catch(()=>{})},[]);return{devServerUrl:t.url,proxyUrl:t.proxyUrl,isStarting:t.isStarting,error:t.error,canStartServer:t.canStartServer,retryServer:a,startServer:o}}function Sk(e){const t=ye(null),r=ye(null);ne(()=>{if(typeof document>"u")return;r.current||(r.current=document.createElement("canvas"),r.current.width=64,r.current.height=64);const s=document.querySelector('link[rel="icon"]');if(!s)return;if(t.current||(t.current=s.href),!e){s.href=t.current;return}const a=new Image;a.crossOrigin="anonymous",a.onload=()=>{const o=r.current,i=o.getContext("2d");i.clearRect(0,0,64,64);const l=56,c=(64-l)/2;i.drawImage(a,c,c,l,l);const p=12,u=64-p-1,h=p+1;i.beginPath(),i.arc(u,h,p,0,2*Math.PI),i.fillStyle="#ef4444",i.fill(),s.href=o.toDataURL("image/png")},a.src=t.current},[e]),ne(()=>()=>{if(typeof document>"u")return;const s=document.querySelector('link[rel="icon"]');s&&t.current&&(s.href=t.current)},[])}function Ck(e){if(!e||typeof e!="object")return[];for(const t of Object.values(e))if(Array.isArray(t))return t;return[]}function kk(e){return H.join(e,".codeyam","migration-state.json")}function Ep(e){const t=kk(e);try{const r=G.readFileSync(t,"utf8"),s=JSON.parse(r);return _k(s)}catch{return null}}function _k(e){const t=Array.isArray(e.pages)?e.pages:[],r=Array.isArray(e.sharedComponents)?e.sharedComponents:[];return{status:e.status||"surveyed",startedAt:e.startedAt||new Date().toISOString(),completedAt:e.completedAt??null,currentPageIndex:typeof e.currentPageIndex=="number"?e.currentPageIndex:0,pages:t.map(s=>({name:s.name||"Unknown",route:s.route||"/",filePath:s.filePath||"",status:s.status||"pending",startedAt:s.startedAt??null,completedAt:s.completedAt??null,extractedComponents:Array.isArray(s.extractedComponents)?s.extractedComponents:[],extractedFunctions:Array.isArray(s.extractedFunctions)?s.extractedFunctions:[],scenarioCount:typeof s.scenarioCount=="number"?s.scenarioCount:0})),sharedComponents:r.map(s=>({name:s.name||"",filePath:s.filePath||"",extractedFromPage:s.extractedFromPage||"",usedInPages:Array.isArray(s.usedInPages)?s.usedInPages:[]}))}}function Ek(e,t){if(!G.existsSync(H.join(e,"package.json"))||t!=null&&t.hasEditorScenarios)return!1;const r=H.join(e,".codeyam","glossary.json");if(G.existsSync(r))try{const o=JSON.parse(G.readFileSync(r,"utf8"));if((Array.isArray(o)?o:Ck(o)).length>0)return!1}catch{}const s=H.join(e,".codeyam","editor-step.json");if(G.existsSync(s))try{const o=JSON.parse(G.readFileSync(s,"utf8"));if(o.feature||o.scaffolded)return!1}catch{}const a=Ep(e);return(a==null?void 0:a.status)!=="complete"}function jk(e){const t=H.join(e,".codeyam","editor-step.json");try{const r=G.readFileSync(t,"utf8");return!!JSON.parse(r).migration}catch{return!1}}function Ak({currentUrl:e,nextUrl:t,formMethod:r,defaultShouldRevalidate:s}){return r||e.pathname===t.pathname?s:e.pathname.startsWith("/editor")&&t.pathname.startsWith("/editor")?!1:s}const Pk=()=>[{title:"Editor - CodeYam"},{name:"description",content:"CodeYam Code + Data Editor"}];function Tk(e){const t=new URL(e).pathname.match(/\/editor\/entity\/([^/]+)/);return t?t[1]:null}async function Mk({request:e}){var P;const t=await Ye();let r=!1,s=[],a=[];const o=Ce()||process.cwd();let i={map:{},allFiles:[]};try{i=Si(o)}catch{}let l=[];try{l=fr()}catch{}if(t){const{project:R}=await Re(t);r=((P=R.metadata)==null?void 0:P.editorMode)??!1;try{const E=$e();try{const q=await E.selectFrom("editor_scenarios").select(["id","url"]).where("project_id","=",R.id).where("component_name","is",null).where("page_file_path","is",null).execute();if(q.length>0){const{allFiles:U}=i;for(const z of q){const W=z;if(!W.url)continue;const V=Kd(W.url,U);V&&await E.updateTable("editor_scenarios").set({page_file_path:V}).where("id","=",W.id).execute()}}}catch(q){console.warn("[editor] page_file_path backfill failed (non-fatal):",q instanceof Error?q.message:q)}const J=await E.selectFrom("editor_scenarios").selectAll().where("project_id","=",R.id).orderBy("created_at","asc").execute(),K=q=>{const U=q;let z=null,W=null;try{U.dimensions&&(z=typeof U.dimensions=="string"?JSON.parse(U.dimensions):U.dimensions)}catch{}try{U.screenshot_paths&&(W=typeof U.screenshot_paths=="string"?JSON.parse(U.screenshot_paths):U.screenshot_paths)}catch{}return{id:q.id,name:q.name,description:q.description||"",componentName:q.component_name||null,componentPath:q.component_path||null,screenshotPath:q.screenshot_path||null,url:U.url||null,type:U.type||null,viewportWidth:U.viewport_width||null,viewportHeight:U.viewport_height||null,dimensions:z,screenshotPaths:W,pageFilePath:U.page_file_path||null,entitySha:U.entity_sha||null,displayName:U.display_name||null,updatedAt:U.updated_at||null}};a=_t(J,q=>`${q.name}::${q.url||"/"}`).map(K);const Q=Eu(o);if(Q){const q=Qr(Q),U=J.filter(z=>ci(z,q));s=_t(U,z=>`${z.name}::${z.url||"/"}`).map(K)}else s=a}catch{}}const c=[...new Set(a.map(R=>R.componentName).filter(R=>R!==null))];let p=[];try{const R=H.join(o,".codeyam","glossary.json");if(G.existsSync(R)){const E=G.readFileSync(R,"utf8");p=JSON.parse(E)}}catch{}const u=ey(p),h={};try{const R=Pi(o),E=u.filter(J=>J.testFile).map(J=>({filePath:J.filePath,testFile:J.testFile}));if(E.length>0){const J=Ti(o,E);for(const[K,Q]of Object.entries(R.results)){const q=J[K];h[K]={...Q,stale:q?Lu(Q,q.sourceHash,q.testHash):!0}}}}catch{}let m=[],f=[];try{const R=await $n()||[];m=R.map(E=>({sha:E.sha,name:E.name,entityType:E.entityType||"visual",filePath:E.filePath||""})),f=ty(R,p)}catch{}let y=[];try{if(m.length>0){const R=m.map(E=>E.sha);await Je(),y=await Xe({shas:R})||[]}}catch{}let g={};try{if(y.length>0){const R=new Set([...f.map(E=>E.name),...m.map(E=>E.name),...c,...p.map(E=>E.name)]);g=ny(y,R)}}catch{}const x=i.map,b=i.allFiles;if(Object.keys(x).length>0&&y.length>0&&(g=ry(g,x,y)),b.length>0&&y.length>0){const R=new Map;for(const E of y)E.filePath&&R.set(E.filePath,E.name);for(const E of b){const J=Lt(jt(E));if(g[J])continue;const K=R.get(E);K&&g[K]&&(g[J]=g[K])}}let v={};try{v=(await gr({projectRoot:o,scenarioInputs:a,glossaryInputs:u,precomputedPageFilePaths:i,precomputedGitFiles:l,precomputedEntities:y})).entityChangeStatus}catch{}const N=l.filter(R=>R.status!=="deleted").map(R=>({path:R.path,status:R.status})),w=Ca(o),C=_i(o),S=Ci(o),k=ju(o);let j=null,_=null,F=null,M=null,$=null;try{const R=H.join(o,".codeyam","config.json");if(G.existsSync(R)){const E=JSON.parse(G.readFileSync(R,"utf8"));j=E.projectTitle||null,_=E.projectDescription||null,F=E.defaultScreenSize||null,M=E.screenSizes||null,$=E.appFormats||null}}catch{}$||($=ki(o));const O=Tk(e.url);let D=null,T=null;if(O&&t)try{await Je();const R=await Xe({}),E=R==null?void 0:R.find(J=>J.sha===O);if(E){const J=E.name,K=E.filePath||"",Q=E.entityType||"visual";T={name:J,filePath:K,entityType:Q,displayName:J};const q=R==null?void 0:R.find(U=>U.name===E.name&&U.filePath===E.filePath&&U.sha!==O&&U.createdAt&&E.createdAt&&U.createdAt>E.createdAt);q&&(D=q.sha)}}catch{}const B=Au(o),Y=B&&a.some(R=>R.id===B)?B:null;let I="none",L=null;try{if(L=Ep(projRoot),(L==null?void 0:L.status)==="complete")I="complete";else if((L==null?void 0:L.status)==="in-progress"||(L==null?void 0:L.status)==="surveyed")I="active";else if(jk(projRoot))I="active";else if(t){const R=a.length>0;Ek(projRoot,{hasEditorScenarios:R})&&(I="candidate")}}catch{}return re({projectSlug:t,projectRoot:Ce(),hasProject:!!t,editorMode:r,scenarios:s,allScenarios:a,components:c,analyzedEntities:f,allEntities:m,glossaryFunctions:u,glossaryEntries:p,entityImports:g,pageFilePaths:x,entityChangeStatus:v,modifiedFiles:N,featureName:w,userPrompt:C,projectTitle:j,projectDescription:_,defaultScreenSize:F,screenSizes:M,appFormats:$,editorStep:(S==null?void 0:S.step)??null,editorStepLabel:(S==null?void 0:S.label)??null,claudeSessionId:k,focusedEntitySha:O,newerEntitySha:D,focusedEntity:T,savedActiveScenarioId:Y,migrationMode:I,migrationState:L,cachedTestResults:h})}class $k extends mh{constructor(){super(...arguments);ht(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 Ik=et(function(){var ul,pl;const{projectSlug:t,projectRoot:r,hasProject:s,scenarios:a,allScenarios:o,analyzedEntities:i,allEntities:l,glossaryFunctions:c,glossaryEntries:p,entityImports:u,pageFilePaths:h,entityChangeStatus:m,modifiedFiles:f,featureName:y,userPrompt:g,projectTitle:x,projectDescription:b,defaultScreenSize:v,screenSizes:N,appFormats:w,editorStep:C,editorStepLabel:S,claudeSessionId:k,focusedEntitySha:j,newerEntitySha:_,focusedEntity:F,migrationMode:M,migrationState:$,cachedTestResults:O}=ot(),D=nd("root"),T=(D==null?void 0:D.npmUpdate)??null,B=(D==null?void 0:D.isAdmin)??!1,[Y,I]=ir(),L=Dt(),P=ye(null),R=ye(null),E=ye(null),J=ye(null),[K,Q]=A(j),[q,U]=A(!1),[z,W]=A(!1),[V,ae]=A(!1),[pe,xe]=A(0);ne(()=>{Q(j)},[j]),ne(()=>{const X=de=>{const Se=de.target;(Se.tagName==="BUTTON"||Se.closest("button"))&&(Se.closest("button")??Se).blur()};return document.addEventListener("mouseup",X),()=>document.removeEventListener("mouseup",X)},[]);const ie=le(()=>Fc(K,l),[K,l,o]),me=(ie==null?void 0:ie.displayName)??void 0,we=Y.get("scenario")||((ul=ys(o))==null?void 0:ul.id)||void 0,[Te,Ne]=A(()=>me?[me]:[]),_e=ye(null),Z=ye([]),he=ye(null);ne(()=>{var Ue;const X=we||((Ue=ys(o))==null?void 0:Ue.id);if(!my(X,_e.current))return;const de=o.find(qe=>qe.id===X);if(!de)return;_e.current=X;const Se=to(de,Z.current,he.current);Se&&qt(Se);const Ie=Mt(de.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Ie,scenarioId:de.id,scenarioName:de.name,scenarioType:de.type})}).catch(()=>{})},[we,o]),ne(()=>{const X=new BroadcastChannel("codeyam-editor");return X.onmessage=de=>{var Se;if(((Se=de.data)==null?void 0:Se.type)==="switch-scenario"&&de.data.scenarioId){const Ie=de.data.scenarioId,Ue=o.find(Qn=>Qn.id===Ie);if(!Ue)return;_e.current=Ie;const qe=new URLSearchParams(Y);qe.set("scenario",Ie),qe.delete("zoom"),I(qe),Xr(null),At(null),vt(null),tn(!0);const nn=Mt(Ue.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:nn,scenarioId:Ie,scenarioType:Ue.type})}).then(()=>{Le(!1),Hn(Qn=>Qn+1)}).catch(()=>{tn(!1)})}},()=>X.close()},[Y,I,o]),ne(()=>{if(Y.get("ref")!=="link"||!we)return;const X=new BroadcastChannel("codeyam-editor");X.postMessage({type:"switch-scenario",scenarioId:we}),X.close(),window.close()},[]);const{devServerUrl:te,proxyUrl:se,isStarting:ce,error:je,canStartServer:ge,retryServer:ze,startServer:Ve}=Nk({skipAutoStart:M==="candidate"||M==="active"}),[it,Le]=A(!1),[lt,Xr]=A(null),[fn,At]=A(null),[Fn,Dn]=A(!1),[Rn,vt]=A(null),[On,zt]=A(null),wt=oe(async X=>{const Se=await(await fetch("/api/editor-load-commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commitSha:X})})).json();return Se.success&&(vt(null),Le(!1)),Se},[]),Bt=oe((X,de)=>{At(Se=>(X&&X!==Se&&Le(!1),X)),!de&&X&&Le(!0),Dn(de)},[]),rt=oe(X=>{vt(null),Xr(Se=>(Se&&Se.analysisId===X.analysisId||(At(null),Hn(Ue=>Ue+1)),X)),Dn(!0),Le(!1);const de=new URLSearchParams(Y);de.delete("scenario"),de.delete("zoom"),I(de)},[Y,I]),[Fe,qt]=A(v?{name:v.name,width:v.width,height:v.height}:{name:"Desktop",width:1440,height:900}),[Ln,yr]=A(!1),[ct,xr]=A(!1),Aa=(w==null?void 0:w.includes("mobile-app"))??!1,br=v?{name:v.name,width:v.width,height:v.height}:null;he.current=br;const vr=Jr(),Qe=le(()=>{const X=vr.pathname.split("/").filter(Boolean),de=X[X.length-1];return de==="build"||de==="history"||de==="settings"?de:de==="structure"?"data":"app"},[vr.pathname]),ut=oe(X=>{Q(null),Ne([]),U(!1);const de=X==="app"?"":`/${X==="data"?"structure":X}`,Se=Y.get("scenario"),Ie=Se?`?scenario=${Se}`:"";L(`/editor${de}${Ie}`)},[L,Y]),wr=oe(()=>{ut("build"),Qt(!0)},[ut]),Pa=oe(()=>{ut("history")},[ut]),Ta=oe(()=>{ut("build"),Qt(!0),setTimeout(()=>{var X;(X=P.current)==null||X.sendInput("codeyam editor migrate")},300)},[ut]),[Ma,Qt]=A(Qe==="build"),Zt=!!(y&&C),zn=C!=null&&C<=1,[gn,Nr]=A(Zt&&!zn?"pending":Zt&&zn?"fresh":"no-session"),Sr=ye(!1);ne(()=>{gn==="pending"&&!Sr.current&&(Sr.current=!0,ut("build"),Qt(!0))},[gn,ut]);const Cr=ye(!1);ne(()=>{Zt&&zn&&!Cr.current&&(Cr.current=!0,fetch("/api/editor-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}).catch(()=>{}))},[Zt,zn]);const es=oe(()=>{Nr("continue")},[]),ts=oe(()=>{fetch("/api/editor-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}).catch(()=>{}),Nr("fresh")},[]),[ns,Bn]=A("none"),rs=oe(()=>{Bn("choosing")},[]),ss=oe(()=>{var X;fetch("/api/editor-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}).catch(()=>{}),Bn("none"),(X=P.current)==null||X.sendInput("/clear"),setTimeout(()=>{var de;(de=P.current)==null||de.sendInput("/codeyam-editor")},500)},[]),as=oe(()=>{Bn("none")},[]),[Yn,Wn]=A(!1),[os,kr]=A(!1),fe=ye(!1),Me=ye(0),tt=ye(!1),We=oe(X=>{Wn(X),X||(tt.current=!0),X&&!fe.current&&(kr(!1),Me.current=Date.now()),X||(Me.current=0),fe.current=X},[]),[Ke,Pt]=A(!1),He=ye(!1),st=oe(X=>{X!==He.current&&(console.log("[Editor] claudeBuilding: %s → %s",He.current,X),He.current=X,Pt(X))},[]);Sk(Yn);const at=ye(Ke);ne(()=>{var de;const X=at.current&&!Ke;if(at.current=Ke,!Ke)if(X){const Se=Y.get("scenario")||((de=ys(o))==null?void 0:de.id),Ie=o.find(Ue=>Ue.id===Se);if(Ie){console.log("[Editor] Building stopped, loading live preview for: %s",Ie.name),zt(null);const Ue=Mt(Ie.name);_e.current=Ie.id,tn(!0),Vn(!1),Le(!1),fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Ue,scenarioId:Ie.id,scenarioType:Ie.type,skipBroadcast:!0})}).then(()=>{Hn(qe=>qe+1)}).catch(()=>{tn(!1),Le(!0)})}else zt(null)}else zt(null)},[Ke,Y,o]);const{editorWidth:Xt,isDragging:Un,isEditorCollapsed:yn,isPreviewCollapsed:$a,handleMouseDown:jp,handleDoubleClick:Ap,collapseEditor:Pp,expandEditor:Ki,expandPreview:Tp}=mk(J),[Ia,Gi]=A(!1),Mp=oe(()=>{Gi(!0),ut("build"),Qt(!0)},[ut]),qi=oe(()=>{Gi(!1)},[]),$p=oe(X=>{qt(X),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:X,skipBroadcast:!0})})},[]),[Qi,Zi]=A(tr);ne(()=>{const X=z0();Zi(X),X.systemNotification&&typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()},[]);const Ip=oe(X=>{Zi(X),B0(X)},[]);ne(()=>{if(Qe==="build"){Wn(!1);const X=setTimeout(()=>{var de,Se;(de=P.current)==null||de.scrollToBottom(),(Se=P.current)==null||Se.focus()},50);return()=>clearTimeout(X)}},[Qe]),ne(()=>{function X(){!document.hidden&&Qe==="build"&&Wn(!1)}return document.addEventListener("visibilitychange",X),()=>document.removeEventListener("visibilitychange",X)},[Qe]);const[xn,Fp]=A(null);ne(()=>{const X=E.current;if(!X)return;const de=new ResizeObserver(Se=>{const Ie=Se[0];Ie&&Fp({width:Ie.contentRect.width,height:Ie.contentRect.height})});return de.observe(X),()=>de.disconnect()},[]);const _r=Aa&&!ct&&(Fe.height??900)>Fe.width,en=le(()=>xn?_r?Ll(xn,{width:Fe.width+_s.width,height:(Fe.height??900)+_s.height}):Ll(xn,Fe):1,[xn,Fe,_r]),[Jn,Hn]=A(0),[Xi,Fa]=A(null),[is,tn]=A(!1),ls=ye(!1),[Dp,Vn]=A(!1),[Rp,el]=A(!1),Da=ye(0);ne(()=>{Jn>0&&(Da.current=Date.now()+3e3)},[Jn]);const Op=oe(()=>{if(Date.now()<Da.current)return;const X=Me.current;X===0||Date.now()-X<5e3||Vn(!0)},[]);ne(()=>{const X=de=>{var Se;if(((Se=de.data)==null?void 0:Se.type)==="codeyam-localstorage-changed"){if(Date.now()<Da.current)return;const Ie=Me.current;if(Ie===0||Date.now()-Ie<5e3)return;Vn(!0)}};return window.addEventListener("message",X),()=>window.removeEventListener("message",X)},[]);const tl=oe(async X=>{el(!0);try{let de;const Se=R.current;Se!=null&&Se.contentWindow&&(de=await new Promise(qe=>{const nn=setTimeout(()=>qe(void 0),2e3),Qn=hl=>{var ml;((ml=hl.data)==null?void 0:ml.type)==="codeyam-localstorage-state"&&(clearTimeout(nn),window.removeEventListener("message",Qn),qe(hl.data.data))};window.addEventListener("message",Qn),Se.contentWindow.postMessage({type:"codeyam-get-localstorage"},"*")}));const Ue=await(await fetch("/api/editor-save-seed-state",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:X,localStorage:de})})).json();Ue.success?Vn(!1):console.error("[editor] Save seed state failed:",Ue.error)}catch(de){console.error("[editor] Save seed state error:",de)}finally{el(!1)}},[]),Lp=oe((X,de)=>{if(Fa(X||null),de){const Se=new URLSearchParams(Y);Se.set("scenario",de),_e.current=de,I(Se);const Ie=o.find(Ue=>Ue.id===de);if(Ie){const Ue=to(Ie,Z.current,he.current);Ue&&qt(Ue)}}vt(null),Le(!1),Hn(Se=>Se+1)},[Y,I,o]),{customSizes:Ra,addCustomSize:zp,removeCustomSize:Bp}=ha(t),Er=le(()=>xp(N,w),[N,w]),cs=le(()=>[...Er,...Ra],[Er,Ra]);Z.current=cs;const ds=le(()=>{const X=new Map;for(const de of l){X.set(de.name,de.sha);const Se=Lt(jt(de.filePath));Se!==de.name&&X.set(Se,de.sha)}return X},[l]),nl=le(()=>{const X=new Map;for(const de of l)X.set(de.sha,de.name);return X},[l]),rl=le(()=>{const X=[{name:"App"}];q&&X.push({name:"Roadmap"}),z&&X.push({name:"Design System"}),V&&X.push({name:"Tech Stack"});for(const de of Te){const Se=ds.get(de),Ie=Se?nl.get(Se):void 0;X.push({name:Ie||de,componentName:de,entitySha:Se})}return X},[Te,ds,nl,q,z,V]),{pageGroups:sl,componentGroups:Oa}=le(()=>Hi(o),[o]),us=le(()=>wp(sl,Oa),[sl,Oa]),[Yp,Wp]=A("application"),[Kn,La]=A([]),[za,al]=A(null),ol=le(()=>za?Fc(za,l):null,[za,l,o]),il=le(()=>{const X=[{name:"App"}];for(const de of Kn)X.push({name:de,componentName:de,entitySha:ds.get(de)});return X},[Kn,ds]),Ba=oe((X,de)=>{if(!X){La([]),al(null);return}const Se=de||us.get(X);if(!Se)return;const Ie=Kn.indexOf(X);Ie>=0?La(Kn.slice(0,Ie+1)):La([...Kn,X]),al(Se)},[Kn,us]),ll=oe((X,de)=>{if(!X){Ne([]),Q(null);const qe=Y.get("scenario"),nn=qe?`?scenario=${qe}`:"";L(`/editor${nn}`);return}if(!de){console.error(`[editor] No entity SHA for "${X}" — entity missing from database`);return}const Se=Te.indexOf(X);Se>=0?Ne(Te.slice(0,Se+1)):Ne([...Te,X]);const Ie=o.find(qe=>qe.entitySha===de);Q(de);const Ue=Ie?`?scenario=${Ie.id}`:"";L(`/editor/entity/${de}${Ue}`)},[L,o,Te,Y]),cl=oe(X=>{tn(!0),ls.current=!0,Vn(!1),Le(!1);const de=Mt(X.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:de,scenarioId:X.id,scenarioType:X.type,skipBroadcast:!0})}).then(()=>{ls.current=!1,Hn(Se=>Se+1)}).catch(()=>{ls.current=!1,tn(!1),Le(!0)})},[]),Gn=oe((X,de)=>{console.log("[Editor] Scenario selected: %s dimension=%s (claudeBuilding=%s)",X.name,de??"default",Ke),Xr(null),At(null),vt(null),Fa(null);let Se=null;if(de&&(N!=null&&N[de])){const Ue=N[de],qe=cs.find(nn=>nn.width===Ue.width&&nn.height===Ue.height);Se={name:(qe==null?void 0:qe.name)||de,...Ue}}Se||(Se=to(X,cs,br)),Se&&qt(Se),_e.current=X.id;const Ie=new URLSearchParams(Y);Ie.set("scenario",X.id),I(Ie),Ke?zt({scenarioId:X.id,scenarioName:X.name,updatedAt:X.updatedAt,hasScreenshot:!!X.screenshotPath,screenshotPath:X.screenshotPath}):(zt(null),cl(X))},[Y,I,cs,N,Ke,cl]),Up=oe(()=>{const X=we;if(!X)return;const de=o.find(Ie=>Ie.id===X);if(!de)return;const Se=Mt(de.name);Le(!1),fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Se,scenarioId:de.id,scenarioType:de.type})}).then(()=>{Hn(Ie=>Ie+1)})},[we,o]),Jp=oe(X=>{if(!X.commitSha){const de=o.find(Se=>Se.name===X.scenarioName);if(de){Gn(de);return}}vt(X)},[o,Gn]),Hp=X=>{const de={name:X.name,width:X.width,height:X.height};qt(de),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:de,skipBroadcast:!0})})},Vp=(X,de,Se)=>{zp(X,de,Se)},Kp=X=>{qt(X),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:X,skipBroadcast:!0})})};ne(()=>{const X=de=>{var Se;if(((Se=de.data)==null?void 0:Se.type)==="codeyam-preview-ready"&&!lt){if(ls.current)return;Le(!0),tn(!1)}};return window.addEventListener("message",X),()=>window.removeEventListener("message",X)},[lt]);const dl=()=>{lt||setTimeout(()=>{Le(X=>(X||tn(!1),!0))},5e3)},qn=le(()=>hy({activeAnalyzedScenario:!!lt,analyzedPreviewUrl:fn,activeScenarioId:we||null,scenarios:o,proxyUrl:se,devServerUrl:te,zoomComponent:me||null}),[se,te,me,we,o,lt,fn]),Ya=le(()=>{if(z)return`/api/design-system-showcase?__cb=${pe}`;const X=eu(qn,Xi);if(!X)return null;const de=X.includes("?")?"&":"?";return`${X}${de}__cb=${Jn}`},[qn,Xi,Jn,z,pe]),Gp=le(()=>({projectSlug:t,hasProject:s,scenarioCount:a==null?void 0:a.length,allScenarioCount:o==null?void 0:o.length,analyzedEntityCount:i==null?void 0:i.length,glossaryFunctionCount:c==null?void 0:c.length,entityChangeStatusKeys:m?Object.keys(m):[],featureName:y}),[t,s,a,o,i,c,m,y]);return d(ve,{children:[n($k,{loaderSnapshot:Gp,children:d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[lt&&n(xk,{analysisId:lt.analysisId,scenarioId:lt.scenarioId,scenarioName:lt.scenarioName,entityName:lt.entityName,projectSlug:t,onStateChange:Bt},lt.analysisId),T&&n(vk,{latestVersion:T.latestVersion}),d("div",{ref:J,className:"flex-1 flex min-h-0",children:[yn&&n("div",{className:"shrink-0 flex items-center justify-center cursor-pointer hover:bg-[#3d3d3d] transition-colors",style:{width:8,backgroundColor:"#2d2d2d"},onClick:Ki,title:"Expand editor",children:n("svg",{width:"6",height:"10",viewBox:"0 0 6 10",fill:"none",stroke:"#888",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M1 1l4 4-4 4"})})}),d("aside",{className:"bg-[#1e1e1e] shrink-0 flex flex-col overflow-hidden",style:{...yn?{display:"none"}:Xt!==null?{width:`${Xt}px`}:{width:"50%"}},children:[_&&ie&&d("div",{className:"px-3 py-2 text-xs flex items-center justify-between",style:{background:"#2a1f00",borderBottom:"1px solid #3d2e00",color:"#f0c040"},children:[d("span",{children:["Viewing an older version of"," ",n("strong",{children:ie.name}),". A newer version exists."]}),n("a",{href:`/editor/entity/${_}`,className:"px-2 py-0.5 rounded text-xs",style:{background:"#3d2e00",color:"#f0c040",textDecoration:"none"},children:"View latest"})]}),n(pk,{activeTab:Qe,onTabChange:X=>{ut(X),X==="build"&&Qt(!0),fetch("/api/telemetry-page-view",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({route:`/editor/${X}`})}).catch(()=>{})},buildIdle:Yn,projectTitle:x,breadcrumbItems:Qe==="data"?il:rl,onBreadcrumbNavigate:Qe==="data"?Ba:ll}),d("div",{className:"flex-1 min-h-0 overflow-hidden relative",children:[Yn&&Qe!=="build"&&!os&&d("div",{className:"absolute top-3 left-1/2 -translate-x-1/2 z-50 animate-[slideDown_0.3s_ease-out]",children:[n("style",{children:`
732
- @keyframes slideDown {
733
- from { transform: translate(-50%, -100%); opacity: 0; }
734
- to { transform: translate(-50%, 0); opacity: 1; }
735
- }
736
- `}),d("div",{className:"flex items-center gap-1 bg-amber-50 border-2 border-amber-300 rounded-lg shadow-lg",children:[d("button",{onClick:()=>{ut("build"),Qt(!0)},className:"flex items-center gap-2 px-4 py-2 cursor-pointer hover:bg-amber-100 transition-colors rounded-l-md",children:[n("span",{className:"inline-block w-2 h-2 rounded-full bg-amber-400 animate-pulse"}),n("span",{className:"text-sm font-medium text-amber-900",children:"Claude is waiting for you"}),n("span",{className:"text-xs text-amber-600 ml-1",children:"Go to Build"})]}),n("button",{onClick:X=>{X.stopPropagation(),kr(!0)},className:"px-2 py-2 cursor-pointer hover:bg-amber-100 transition-colors rounded-r-md text-amber-400 hover:text-amber-600","aria-label":"Dismiss",children:n("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M3 3l8 8M11 3l-8 8"})})})]})]}),Ma&&d("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Qe==="build"?"visible":"hidden"},children:[n(d5,{projectTitle:x,featureName:y,editorStep:C,editorStepLabel:S,migrationMode:M}),n("div",{className:"flex-1 min-h-0",style:Ia?{flex:"1 1 50%"}:void 0,children:gn==="pending"?n(n5,{featureName:y,editorStep:C,editorStepLabel:S,onContinue:es,onStartFresh:ts}):d("div",{className:"relative h-full",children:[n(Vd,{ref:P,entityName:"Editor",projectSlug:t,entityFilePath:null,scenarioName:null,onRefreshPreview:Lp,onShowResults:Mp,onHideResults:qi,onSetViewport:$p,onDataMutationForwarded:Op,onFeatureComplete:rs,editorMode:!0,onIdleChange:We,onBuildingChange:st,notificationSettings:Qi,buildTabActive:Qe==="build",claudeStartMode:gn==="continue"?"resume":"fresh",claudeSessionId:k,editorStepLabel:S,resultsOpen:Ia}),ns==="choosing"&&n(r5,{onStartNextFeature:ss,onContinueInSession:as})]})}),Ia&&n("div",{style:{flex:"1 1 50%"},className:"min-h-0 border-t-2 border-gray-300",children:n(N5,{scenarios:a,allScenarios:o,glossaryFunctions:c,cachedTestResults:O,projectRoot:r,activeScenarioId:we,onScenarioSelect:Gn,onClose:qi,entityChangeStatus:m,modifiedFiles:f,featureName:y,userPrompt:g})})]}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Qe==="app"?"visible":"hidden"},children:n(dk,{hasProject:s,scenarios:o,analyzedEntities:i,allEntities:l,glossaryFunctions:c,cachedTestResults:O,glossaryEntries:p,projectRoot:r,activeScenarioId:we,onScenarioSelect:Gn,onAnalyzedScenarioSelect:rt,onSwitchToBuild:wr,onSwitchToHistory:Pa,zoomComponent:me,focusedEntity:ie,onZoomChange:ll,entityImports:u,pageFilePaths:h,projectTitle:x,projectDescription:b,breadcrumbItems:rl,migrationMode:M,migrationState:$,onStartMigration:Ta,onReseedPreview:Up,isAdmin:B,roadmapView:q,onRoadmapViewChange:U,designSystemView:z,onDesignSystemViewChange:W,onPreviewDesignSystem:()=>{xe(X=>X+1)},techStackView:V,onTechStackViewChange:ae})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Qe==="data"?"visible":"hidden"},children:ol?n(kp,{focusedEntity:ol,breadcrumbItems:il,onZoomChange:Ba,projectRoot:r,scenarios:o,analyzedEntities:[],activeScenarioId:we,onScenarioSelect:Gn,onAnalyzedScenarioSelect:rt,onSwitchToBuild:wr,entityImports:u,glossaryFunctions:c,cachedTestResults:O,glossaryEntries:p,entityShaMap:us,componentGroups:Oa,visualEntities:[],isEntityComplete:()=>!0}):n(u5,{scenarios:o,projectRoot:r,activeScenarioId:we,onScenarioSelect:Gn,zoomComponent:void 0,focusedEntity:null,onZoomChange:Ba,analyzedEntities:[],glossaryFunctions:c,cachedTestResults:O,activeAnalyzedScenarioId:lt==null?void 0:lt.scenarioId,onAnalyzedScenarioSelect:rt,entityImports:u,pageFilePaths:h,onSwitchToBuild:wr,entityShaMap:us,structureTab:Yp,onStructureTabChange:Wp})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Qe==="history"?"visible":"hidden"},children:n(R5,{isActive:Qe==="history",onScreenshotClick:Jp,glossaryFunctions:c,cachedTestResults:O})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:Qe==="settings"?"visible":"hidden"},children:d("div",{className:"flex-1 overflow-auto p-4",children:[n("h2",{className:"text-sm font-semibold text-white mb-4",children:"Settings"}),n("p",{className:"text-xs text-gray-400",children:"Settings panel coming soon."})]})})]}),n(Hd,{serverUrl:te,isStarting:ce,projectSlug:t,devServerError:je,onStartServer:ge?Ve:void 0,notificationSettings:Qi,onChangeNotificationSettings:Ip})]}),!yn&&!$a&&n(hk,{onMouseDown:jp,onDoubleClick:Ap,isDragging:Un}),$a&&n("div",{className:"shrink-0 flex items-center justify-center cursor-pointer hover:bg-[#3d3d3d] transition-colors",style:{width:8,backgroundColor:"#2d2d2d"},onClick:Tp,title:"Expand preview",children:n("svg",{width:"6",height:"10",viewBox:"0 0 6 10",fill:"none",stroke:"#888",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M5 1l-4 4 4 4"})})}),d("div",{className:"flex-1 flex flex-col min-w-0",style:{...$a?{display:"none"}:void 0,...Un?{pointerEvents:"none"}:void 0},children:[d("div",{className:"bg-[#2d2d2d] border-b border-[#3d3d3d] shrink-0 z-10 h-10 flex items-center pr-4 relative",children:[n("div",{className:"flex items-center gap-1 shrink-0 z-10",children:n("button",{onClick:()=>{yn?(Ki(),setTimeout(()=>{var X;return(X=P.current)==null?void 0:X.focus()},50)):Pp()},className:`p-1.5 rounded transition-colors cursor-pointer ${yn?"text-white bg-[#666] hover:bg-[#777]":"text-gray-500 hover:text-gray-300"}`,title:yn?"Show chat":"Hide chat",children:n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:yn?d(ve,{children:[n("path",{d:"M13 17l5-5-5-5"}),n("path",{d:"M6 17l5-5-5-5"})]}):d(ve,{children:[n("path",{d:"M11 17l-5-5 5-5"}),n("path",{d:"M18 17l-5-5 5-5"})]})})})}),n("div",{className:"absolute inset-0 flex items-center justify-center gap-1 pointer-events-none",children:d("div",{className:"flex items-center gap-1 pointer-events-auto",children:[Er.map(X=>{const de=Is(X),Se=de==="desktop"?"Desktop":de==="laptop"?"Laptop":de==="tablet"?"Tablet":"Mobile";return d("button",{onClick:()=>{ct&&xr(!1),Hp(X)},className:`p-1.5 rounded transition-colors cursor-pointer ${!ct&&Fe.name===X.name?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:`${X.name} (${X.width}×${X.height})`,children:[Se==="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"})]}),Se==="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"})]}),Se==="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"})]}),Se==="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"})]})]},X.name)}),d("div",{className:"relative",children:[d("button",{onClick:()=>{ct||yr(X=>!X)},className:`flex items-center gap-1.5 px-2 py-1 rounded transition-colors ${ct?"":"cursor-pointer"} ${ct||Ln||!Er.some(X=>X.name===Fe.name)?"text-white bg-[#555]":"text-gray-400 hover:text-gray-200 hover:bg-[#444]"}`,title:"Custom dimensions",children:[n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),n("span",{className:"text-xs font-mono",children:ct&&xn?`${Math.round(xn.width)} × ${Math.round(xn.height)}`:`${Fe.width} × ${Fe.height??900}`})]}),Ln&&n(I0,{currentWidth:Fe.width,currentHeight:Fe.height??900,devicePresets:Er,customSizes:Ra,onApply:Kp,onSave:Vp,onRemove:Bp,onClose:()=>yr(!1)})]}),n("button",{onClick:()=>{xr(X=>!X)},className:`p-1.5 rounded transition-colors cursor-pointer ${ct?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:ct?"Exit fullscreen":"Fill page with preview",children:n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:ct?d(ve,{children:[n("polyline",{points:"4 14 10 14 10 20"}),n("polyline",{points:"20 10 14 10 14 4"}),n("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),n("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):d(ve,{children:[n("polyline",{points:"15 3 21 3 21 9"}),n("polyline",{points:"9 21 3 21 3 15"}),n("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),n("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})}),n("button",{onClick:()=>{const X=Ya||qn;X&&window.open(X,"_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"})]})})]})})]}),Dp&&n(bk,{onSaveToCurrent:()=>void tl("overwrite"),onSaveAsNew:()=>void tl("new"),onDismiss:()=>Vn(!1),isSaving:Rp,scenarioName:(pl=o.find(X=>{var de;return X.id===(we||((de=ys(o))==null?void 0:de.id))}))==null?void 0:pl.name}),n("div",{ref:E,className:`flex-1 flex ${Rn||On?"overflow-y-auto overflow-x-hidden":"overflow-hidden"} ${ct?"":"items-center justify-center p-8"}`,style:ct?{backgroundColor:"#fff"}:Rn?{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)"}:On?{backgroundColor:"#1e1e1e"}:{backgroundImage:`
737
- linear-gradient(45deg, #333 25%, transparent 25%),
738
- linear-gradient(-45deg, #333 25%, transparent 25%),
739
- linear-gradient(45deg, transparent 75%, #333 75%),
740
- linear-gradient(-45deg, transparent 75%, #333 75%)
741
- `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#2d2d2d"},children:Rn?n(fk,{preview:Rn,viewportWidth:Fe.width,viewportHeight:Fe.height??900,scale:en,onDismiss:()=>vt(null),onLoadCommit:wt}):On?n(yk,{preview:On,viewportWidth:Fe.width,viewportHeight:Fe.height??900,scale:en,onDismiss:()=>zt(null)}):qn?ct?d("div",{className:"relative w-full h-full bg-white",children:[!it&&!is&&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(Ut,{})}),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"})]})]})}),is&&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:R,src:Ya||qn,className:"w-full h-full border-none",title:"Editor preview",onLoad:dl,style:{opacity:it?1:0}},Jn)]}):n("div",{style:{width:`${(_r?Fe.width+_s.width:Fe.width)*en}px`,height:`${(_r?(Fe.height??900)+_s.height:Fe.height??900)*en}px`},children:n("div",{className:"origin-top-left",style:{transform:en<1?`scale(${en})`:void 0},children:n(t5,{width:Fe.width,height:Fe.height??900,enabled:_r,children:d("div",{className:"relative bg-white",style:{width:`${Fe.width}px`,height:`${Fe.height??900}px`},children:[!it&&!is&&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(Ut,{})}),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"})]})]})}),is&&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:R,src:Ya||qn,className:"w-full h-full border-none",title:"Editor preview",onLoad:dl,style:{opacity:it?1:0}},Jn)]})})})}):n("div",{className:"bg-[#2a2a2a] rounded-lg flex flex-col items-center justify-center",style:{width:`${Fe.width*en}px`,height:`${(Fe.height??900)*en}px`},children:je?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:je}),n("button",{onClick:ze,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"})]}):ce||Fn?d(ve,{children:[n("div",{className:"mb-4",children:n(Ut,{})}),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:Fn?"Starting Interactive Mode":"Starting Dev Server"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:Fn?"Loading component preview...":"Your dev server is starting up..."})]})]}):d("div",{className:"flex flex-col gap-3 text-center px-8",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Live Preview"}),n("p",{className:"text-sm text-gray-500 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Describe what you want to build in the Build tab"})]})})})]})]})]})}),n(td,{})]})}),Fk=Object.freeze(Object.defineProperty({__proto__:null,default:Ik,loader:Mk,meta:Pk,shouldRevalidate:Ak},Symbol.toStringTag,{value:"Module"})),Dk=et(function(){return null}),er=Object.freeze(Object.defineProperty({__proto__:null,default:Dk},Symbol.toStringTag,{value:"Module"})),W_={entry:{module:"/assets/entry.client-j1Vi0bco.js",imports:["/assets/jsx-runtime-D_zvdyIk.js","/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/index-vyrZD2g4.js"],css:[]},routes:{root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!0,module:"/assets/root-Didv9PLi.js",imports:["/assets/jsx-runtime-D_zvdyIk.js","/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/index-vyrZD2g4.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/ReportIssueModal-DQsceHVv.js","/assets/useReportContext-jkCytuYz.js","/assets/loader-circle-D-q28GLF.js","/assets/createLucideIcon-BwyFiRot.js","/assets/book-open-BFSIqZgO.js","/assets/useToast-BgqkixU9.js","/assets/useLastLogLine-C8QvIe05.js","/assets/LogViewer-C-9zQdXg.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/chevron-down-B9fDzFVh.js","/assets/circle-check-DLPObLUx.js","/assets/CopyButton-DTBZZfSk.js","/assets/triangle-alert-D87ekDl8.js","/assets/copy-DXEmO0TD.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-DziaVQX1.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/Spinner-CIil5-gb.js","/assets/useLastLogLine-C8QvIe05.js","/assets/ViewportInspectBar-BqkA9zyZ.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/InlineSpinner-ByaELMbv.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-C8AyYgYT.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/Spinner-CIil5-gb.js","/assets/useLastLogLine-C8QvIe05.js","/assets/ViewportInspectBar-BqkA9zyZ.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/InlineSpinner-ByaELMbv.js","/assets/editorPreview-C6fEYHrh.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/preload-helper-ckwbz45p.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-switch-scenario":{id:"routes/api.interactive-switch-scenario",parentId:"root",path:"api/interactive-switch-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-switch-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-screenshot":{id:"routes/api.editor-journal-screenshot",parentId:"root",path:"api/editor-journal-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-save-scenario-data":{id:"routes/api.editor-save-scenario-data",parentId:"root",path:"api/editor-save-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-save-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-D_O_ajfZ.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/InteractivePreview-6WjVfhxX.js","/assets/Spinner-CIil5-gb.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C8QvIe05.js","/assets/InlineSpinner-ByaELMbv.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-BTcpgIpC.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/InteractivePreview-6WjVfhxX.js","/assets/Spinner-CIil5-gb.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C8QvIe05.js","/assets/InlineSpinner-ByaELMbv.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-capture-scenario":{id:"routes/api.editor-capture-scenario",parentId:"root",path:"api/editor-capture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-capture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-recapture-stale":{id:"routes/api.editor-recapture-stale",parentId:"root",path:"api/editor-recapture-stale",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-recapture-stale-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-rename-scenario":{id:"routes/api.editor-rename-scenario",parentId:"root",path:"api/editor-rename-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-rename-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-save-seed-state":{id:"routes/api.editor-save-seed-state",parentId:"root",path:"api/editor-save-seed-state",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-save-seed-state-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-prompt":{id:"routes/api.editor-scenario-prompt",parentId:"root",path:"api/editor-scenario-prompt",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-prompt-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-switch-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-update-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-client-errors-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-entity-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-entry-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-verify-routes":{id:"routes/api.editor-verify-routes",parentId:"root",path:"api/editor-verify-routes",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-verify-routes-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-project-info":{id:"routes/api.editor-project-info",parentId:"root",path:"api/editor-project-info",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-project-info-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-test-results-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-load-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.agent-transcripts-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-dev-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.logs._projectSlug-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-file-diff":{id:"routes/api.editor-file-diff",parentId:"root",path:"api/editor-file-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.execute-function-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-mode-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.delete-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.dev-mode-events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.generate-report-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-refresh-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-roadmap":{id:"routes/api.editor-roadmap",parentId:"root",path:"api/editor-roadmap",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-roadmap-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-session":{id:"routes/api.editor-session",parentId:"root",path:"api/editor-session",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-session-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.memory-profile-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.restart-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/agent-transcripts-B8NCeOrm.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/createLucideIcon-BwyFiRot.js","/assets/terminal-DHemCJIs.js","/assets/search-BooqacKS.js","/assets/chevron-down-B9fDzFVh.js","/assets/book-open-BFSIqZgO.js","/assets/triangle-alert-D87ekDl8.js","/assets/copy-DXEmO0TD.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-schema":{id:"routes/api.editor-schema",parentId:"root",path:"api/editor-schema",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-schema-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-audit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.save-fixture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-DqM9hbNE.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/LogViewer-C-9zQdXg.js","/assets/useLastLogLine-C8QvIe05.js","/assets/useReportContext-jkCytuYz.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/EntityTypeBadge-CQgyEGV-.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LoadingDots-By5zI316.js","/assets/loader-circle-D-q28GLF.js","/assets/pause-BP6fitdh.js","/assets/createLucideIcon-BwyFiRot.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._-Ce1s4OQ1.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useLastLogLine-C8QvIe05.js","/assets/Spinner-CIil5-gb.js","/assets/InteractivePreview-6WjVfhxX.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LibraryFunctionPreview-ChX-Hp7W.js","/assets/LoadingDots-By5zI316.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-Cl4oOA3A.js","/assets/createLucideIcon-BwyFiRot.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/CopyButton-DTBZZfSk.js","/assets/LogViewer-C-9zQdXg.js","/assets/MiniClaudeChat-BusrvT2F.js","/assets/useReportContext-jkCytuYz.js","/assets/preload-helper-ckwbz45p.js","/assets/InlineSpinner-ByaELMbv.js","/assets/ViewportInspectBar-BqkA9zyZ.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/ReportIssueModal-DQsceHVv.js","/assets/circle-check-DLPObLUx.js","/assets/triangle-alert-D87ekDl8.js","/assets/copy-DXEmO0TD.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-ovy6FjRY.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LoadingDots-By5zI316.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/chevron-down-B9fDzFVh.js","/assets/search-BooqacKS.js","/assets/loader-circle-D-q28GLF.js","/assets/createLucideIcon-BwyFiRot.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-iRhRIFlp.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/ScenarioViewer-Cl4oOA3A.js","/assets/InteractivePreview-6WjVfhxX.js","/assets/ViewportInspectBar-BqkA9zyZ.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/LogViewer-C-9zQdXg.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/useLastLogLine-C8QvIe05.js","/assets/Spinner-CIil5-gb.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-DQsceHVv.js","/assets/createLucideIcon-BwyFiRot.js","/assets/circle-check-DLPObLUx.js","/assets/triangle-alert-D87ekDl8.js","/assets/copy-DXEmO0TD.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/InlineSpinner-ByaELMbv.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-BM0nbryO.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/CopyButton-DTBZZfSk.js","/assets/copy-DXEmO0TD.js","/assets/createLucideIcon-BwyFiRot.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-DnOgyseQ.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useLastLogLine-C8QvIe05.js","/assets/useToast-BgqkixU9.js","/assets/useReportContext-jkCytuYz.js","/assets/LogViewer-C-9zQdXg.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-BwyFiRot.js","/assets/circle-check-DLPObLUx.js","/assets/loader-circle-D-q28GLF.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-CEWIUC4t.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/createLucideIcon-BwyFiRot.js","/assets/terminal-DHemCJIs.js","/assets/copy-DXEmO0TD.js","/assets/CopyButton-DTBZZfSk.js","/assets/chevron-down-B9fDzFVh.js","/assets/search-BooqacKS.js","/assets/pause-BP6fitdh.js","/assets/book-open-BFSIqZgO.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-kuny2Q_s.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/EntityItem-BxclONWq.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/chevron-down-B9fDzFVh.js","/assets/search-BooqacKS.js","/assets/createLucideIcon-BwyFiRot.js","/assets/useToast-BgqkixU9.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LibraryFunctionPreview-ChX-Hp7W.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-D87ekDl8.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/EntityTypeBadge-CQgyEGV-.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/labs-c3yLxSEp.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.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-DgCZPMie.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/EntityItem-BxclONWq.js","/assets/LogViewer-C-9zQdXg.js","/assets/index-SqjQKTdH.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/createLucideIcon-BwyFiRot.js","/assets/useToast-BgqkixU9.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LibraryFunctionPreview-ChX-Hp7W.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-D87ekDl8.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/EntityTypeBadge-CQgyEGV-.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/editor.entity.($sha)":{id:"routes/editor.entity.($sha)",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor.entity.(_sha)-CsYVRiNH.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/editorPreview-C6fEYHrh.js","/assets/CopyButton-DTBZZfSk.js","/assets/MiniClaudeChat-BusrvT2F.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/Spinner-CIil5-gb.js","/assets/copy-DXEmO0TD.js","/assets/createLucideIcon-BwyFiRot.js","/assets/useLastLogLine-C8QvIe05.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-index":{id:"editor-tab-index",parentId:"routes/editor.entity.($sha)",path:void 0,index:!0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-build":{id:"editor-tab-build",parentId:"routes/editor.entity.($sha)",path:"build",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-structure":{id:"editor-tab-structure",parentId:"routes/editor.entity.($sha)",path:"structure",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-history":{id:"editor-tab-history",parentId:"routes/editor.entity.($sha)",path:"history",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-settings":{id:"editor-tab-settings",parentId:"routes/editor.entity.($sha)",path:"settings",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-entity":{id:"editor-tab-entity",parentId:"routes/editor.entity.($sha)",path:"entity/:sha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-ef0f624d.js",version:"ef0f624d",sri:void 0},U_="build/client",J_="/",H_={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,unstable_previewServerPrerendering:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},V_=!0,K_=!1,G_=[],q_={mode:"lazy",manifestPath:"/__manifest"},Q_="/",Z_={module:bm},X_={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:M0},"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:O0},"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:yy},"routes/api.interactive-switch-scenario":{id:"routes/api.interactive-switch-scenario",parentId:"root",path:"api/interactive-switch-scenario",index:void 0,caseSensitive:void 0,module:Zy},"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:ex},"routes/api.editor-save-scenario-data":{id:"routes/api.editor-save-scenario-data",parentId:"root",path:"api/editor-save-scenario-data",index:void 0,caseSensitive:void 0,module:nx},"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:Cx},"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:Vx},"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:Qx},"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:sb},"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:ib},"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:cb},"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:ub},"routes/api.editor-recapture-stale":{id:"routes/api.editor-recapture-stale",parentId:"root",path:"api/editor-recapture-stale",index:void 0,caseSensitive:void 0,module:kb},"routes/api.editor-rename-scenario":{id:"routes/api.editor-rename-scenario",parentId:"root",path:"api/editor-rename-scenario",index:void 0,caseSensitive:void 0,module:Eb},"routes/api.editor-save-seed-state":{id:"routes/api.editor-save-seed-state",parentId:"root",path:"api/editor-save-seed-state",index:void 0,caseSensitive:void 0,module:Ab},"routes/api.editor-scenario-prompt":{id:"routes/api.editor-scenario-prompt",parentId:"root",path:"api/editor-scenario-prompt",index:void 0,caseSensitive:void 0,module:Tb},"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:$b},"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:Yv},"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:tw},"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:rw},"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:aw},"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:iw},"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:cw},"routes/api.editor-verify-routes":{id:"routes/api.editor-verify-routes",parentId:"root",path:"api/editor-verify-routes",index:void 0,caseSensitive:void 0,module:uw},"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:mw},"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:yw},"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:Ew},"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:Iw},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:Dw},"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:Vw},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:Qw},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:uN},"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:fN},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:xN},"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:vN},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,module:NN},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:kN},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:jN},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:PN},"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:$N},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:UN},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,module:HN},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,module:e1},"routes/api.editor-roadmap":{id:"routes/api.editor-roadmap",parentId:"root",path:"api/editor-roadmap",index:void 0,caseSensitive:void 0,module:u1},"routes/api.editor-session":{id:"routes/api.editor-session",parentId:"root",path:"api/editor-session",index:void 0,caseSensitive:void 0,module:h1},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:x1},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:N1},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:_1},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:j1},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:U1},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,module:H1},"routes/api.editor-schema":{id:"routes/api.editor-schema",parentId:"root",path:"api/editor-schema",index:void 0,caseSensitive:void 0,module:q1},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,module:Z1},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:eS},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:oS},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:lS},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:xS},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:wS},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,module:SS},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,module:ES},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:AS},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,module:IS},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:rC},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:oC},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:hC},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:fC},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:yC},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:TC},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:IC},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:RC},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:UC},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:HC},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:t2},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:_2},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:M2},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:B2},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:Z2},"routes/editor.entity.($sha)":{id:"routes/editor.entity.($sha)",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,module:Fk},"editor-tab-index":{id:"editor-tab-index",parentId:"routes/editor.entity.($sha)",path:void 0,index:!0,caseSensitive:void 0,module:er},"editor-tab-build":{id:"editor-tab-build",parentId:"routes/editor.entity.($sha)",path:"build",index:void 0,caseSensitive:void 0,module:er},"editor-tab-structure":{id:"editor-tab-structure",parentId:"routes/editor.entity.($sha)",path:"structure",index:void 0,caseSensitive:void 0,module:er},"editor-tab-history":{id:"editor-tab-history",parentId:"routes/editor.entity.($sha)",path:"history",index:void 0,caseSensitive:void 0,module:er},"editor-tab-settings":{id:"editor-tab-settings",parentId:"routes/editor.entity.($sha)",path:"settings",index:void 0,caseSensitive:void 0,module:er},"editor-tab-entity":{id:"editor-tab-entity",parentId:"routes/editor.entity.($sha)",path:"entity/:sha",index:void 0,caseSensitive:void 0,module:er}},eE=!1;export{pf as $,ig as A,sg as B,dg as C,tg as D,$e as E,kf as F,_f as G,Mn as H,T_ as I,Wm as J,Jm as K,Hm as L,Vm as M,yd as N,Gm as O,qm as P,xd as Q,Zm as R,Xm as S,ff as T,bd as U,rf as V,af as W,of as X,lf as Y,df as Z,uf as _,Dm as a,hf as a0,Bm as a1,Ym as a2,mf as a3,Bs as a4,yf as a5,xf as a6,bf as a7,vf as a8,Nf as a9,K_ as aA,G_ as aB,q_ as aC,Q_ as aD,Z_ as aE,X_ as aF,eE as aG,W_ as aH,wf as aa,D_ as ab,ri as ac,R_ as ad,L_ as ae,O_ as af,F_ as ag,Y_ as ah,Re as ai,Ng as aj,vg as ak,$g as al,Gr as am,M_ as an,kd as ao,fg as ap,gg as aq,qN as ar,B_ as as,mn as at,$_ as au,I_ as av,U_ as aw,J_ as ax,H_ as ay,V_ as az,jn as b,En as c,Ht as d,Kr as e,Zo as f,ra as g,gd as h,Im as i,Lf as j,zf as k,dn as l,Vt as m,ei as n,Kf as o,Ws as p,Xe as q,Nd as r,Sd as s,ti as t,an as u,Cd as v,ur as w,sr as x,Rf as y,El as z};