@codeyam/codeyam-cli 0.1.0-staging.e090cb3 → 0.1.0

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 (100) hide show
  1. package/analyzer-template/.build-info.json +7 -7
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/package.json +1 -1
  4. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +29 -18
  5. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +50 -25
  6. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +153 -76
  7. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts.map +1 -1
  8. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js +93 -2
  9. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  10. package/analyzer-template/packages/utils/src/lib/fs/rsyncCopy.ts +108 -2
  11. package/analyzer-template/project/constructMockCode.ts +2 -2
  12. package/background/src/lib/virtualized/project/constructMockCode.js +2 -2
  13. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  14. package/codeyam-cli/src/commands/analyze.js +2 -2
  15. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  16. package/codeyam-cli/src/commands/default.js +1 -1
  17. package/codeyam-cli/src/commands/default.js.map +1 -1
  18. package/codeyam-cli/src/commands/verify.js +2 -2
  19. package/codeyam-cli/src/commands/verify.js.map +1 -1
  20. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js +179 -0
  21. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js.map +1 -0
  22. package/codeyam-cli/src/utils/backgroundServer.js +90 -23
  23. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  24. package/codeyam-cli/src/utils/npmVersionCheck.js +76 -0
  25. package/codeyam-cli/src/utils/npmVersionCheck.js.map +1 -0
  26. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js +66 -0
  27. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js.map +1 -0
  28. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  29. package/codeyam-cli/src/webserver/backgroundServer.js +26 -0
  30. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  31. package/codeyam-cli/src/webserver/bootstrap.js +11 -0
  32. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -1
  33. package/codeyam-cli/src/webserver/build/client/assets/{CopyButton-CA3JxPb7.js → CopyButton-jNYXRRNI.js} +1 -1
  34. package/codeyam-cli/src/webserver/build/client/assets/{EntityItem-B86KKU7e.js → EntityItem-bwuHPyTa.js} +1 -1
  35. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-B5ctlSYt.js → EntityTypeBadge-CvzqMxcu.js} +1 -1
  36. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeIcon-BqY8gDAW.js → EntityTypeIcon-BH0XDim7.js} +1 -1
  37. package/codeyam-cli/src/webserver/build/client/assets/{InlineSpinner-ClaLpuOo.js → InlineSpinner-EhOseatT.js} +1 -1
  38. package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-BDhPilK7.js → InteractivePreview-yjIHlOGa.js} +2 -2
  39. package/codeyam-cli/src/webserver/build/client/assets/{LibraryFunctionPreview-VeqEBv9v.js → LibraryFunctionPreview-Cq5o8jL4.js} +1 -1
  40. package/codeyam-cli/src/webserver/build/client/assets/{LoadingDots-Bs7Nn1Jr.js → LoadingDots-BvMu2i-g.js} +1 -1
  41. package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-Bm3PmcCz.js → LogViewer-kgBTLoJD.js} +1 -1
  42. package/codeyam-cli/src/webserver/build/client/assets/{ReportIssueModal-CgMEzchJ.js → ReportIssueModal-BzPgx-xO.js} +1 -1
  43. package/codeyam-cli/src/webserver/build/client/assets/{SafeScreenshot-Gq3Ocjo6.js → SafeScreenshot-CwZrv-Ok.js} +1 -1
  44. package/codeyam-cli/src/webserver/build/client/assets/{ScenarioViewer-CBui0id_.js → ScenarioViewer-BX2Ny2Qj.js} +1 -1
  45. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-CiwXDxLh.js → TruncatedFilePath-CDpEprKa.js} +1 -1
  46. package/codeyam-cli/src/webserver/build/client/assets/{_index-B3TDXxnk.js → _index-BRx8ZGZo.js} +1 -1
  47. package/codeyam-cli/src/webserver/build/client/assets/{activity.(_tab)-BtBFH820.js → activity.(_tab)-4S4yPfFw.js} +1 -1
  48. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-DHKuQSmR.js +17 -0
  49. package/codeyam-cli/src/webserver/build/client/assets/{book-open-PttOB2SF.js → book-open-D4IPYH_y.js} +1 -1
  50. package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-TJp6ofnp.js → chevron-down-CG65viiV.js} +1 -1
  51. package/codeyam-cli/src/webserver/build/client/assets/{chunk-JZWAC4HX-JE9ZIoBl.js → chunk-JZWAC4HX-DB3aFuEO.js} +9 -9
  52. package/codeyam-cli/src/webserver/build/client/assets/{circle-check-CXhHQYrI.js → circle-check-igfMr5DY.js} +1 -1
  53. package/codeyam-cli/src/webserver/build/client/assets/{copy-6y9ALfGT.js → copy-Coc4o_8c.js} +1 -1
  54. package/codeyam-cli/src/webserver/build/client/assets/{createLucideIcon-Ca9fAY46.js → createLucideIcon-D1zB-pYc.js} +1 -1
  55. package/codeyam-cli/src/webserver/build/client/assets/{dev.empty-C0epRiVn.js → dev.empty-JTAjQ54M.js} +1 -1
  56. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-BVnB8a9L.js → entity._sha._-B0h9AqE6.js} +2 -2
  57. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha.scenarios._scenarioId.fullscreen-CBoafmVs.js → entity._sha.scenarios._scenarioId.fullscreen-DjLxr2JB.js} +1 -1
  58. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.create-scenario-DGgZjdFg.js → entity._sha_.create-scenario-CtYowLOt.js} +1 -1
  59. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.edit._scenarioId-38yPijoD.js → entity._sha_.edit._scenarioId-PePWg17F.js} +1 -1
  60. package/codeyam-cli/src/webserver/build/client/assets/{entry.client-BSHEfydn.js → entry.client-I-Wo99C_.js} +1 -1
  61. package/codeyam-cli/src/webserver/build/client/assets/{fileTableUtils-DCPhhSMo.js → fileTableUtils-9sMMAiWJ.js} +1 -1
  62. package/codeyam-cli/src/webserver/build/client/assets/{files-0N0YJQv7.js → files-Co65J0s3.js} +1 -1
  63. package/codeyam-cli/src/webserver/build/client/assets/{git-DXnyr8uP.js → git-BdHOxVfg.js} +1 -1
  64. package/codeyam-cli/src/webserver/build/client/assets/globals-CCgBKWy4.css +1 -0
  65. package/codeyam-cli/src/webserver/build/client/assets/{index-ChN9-fAY.js → index-CUM5iXwc.js} +1 -1
  66. package/codeyam-cli/src/webserver/build/client/assets/{index-CcsFv748.js → index-_417gcQW.js} +1 -1
  67. package/codeyam-cli/src/webserver/build/client/assets/{labs-BLJ7HxOC.js → labs-BK0C1H1T.js} +1 -1
  68. package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-CTqLEAGU.js → loader-circle-TzRHMVog.js} +1 -1
  69. package/codeyam-cli/src/webserver/build/client/assets/{manifest-b171b9d3.js → manifest-390cb8fa.js} +1 -1
  70. package/codeyam-cli/src/webserver/build/client/assets/{memory-CCQd4aZA.js → memory-CzZySbBE.js} +17 -17
  71. package/codeyam-cli/src/webserver/build/client/assets/{pause-D6vreykR.js → pause-hjzB7t2z.js} +1 -1
  72. package/codeyam-cli/src/webserver/build/client/assets/root-DnbDhvTU.js +62 -0
  73. package/codeyam-cli/src/webserver/build/client/assets/{search-B8VUL8nl.js → search-DcAwD_Ln.js} +1 -1
  74. package/codeyam-cli/src/webserver/build/client/assets/{settings-BejnUJ6R.js → settings-CclxrcPK.js} +1 -1
  75. package/codeyam-cli/src/webserver/build/client/assets/{simulations-CPoAg7Zo.js → simulations-DVNJVQgD.js} +1 -1
  76. package/codeyam-cli/src/webserver/build/client/assets/{terminal-BrCP7uQo.js → terminal-DbEAHMbA.js} +1 -1
  77. package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-BZz2NjYa.js → triangle-alert-CAD5b1o_.js} +1 -1
  78. package/codeyam-cli/src/webserver/build/client/assets/{useCustomSizes-DNwUduNu.js → useCustomSizes-BqgrAzs3.js} +1 -1
  79. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-COky1GVF.js → useLastLogLine-DAFqfEDH.js} +1 -1
  80. package/codeyam-cli/src/webserver/build/client/assets/{useReportContext-CpZgwliL.js → useReportContext-DZlYx2c4.js} +1 -1
  81. package/codeyam-cli/src/webserver/build/client/assets/{useToast-Bv9JFvUO.js → useToast-ihdMtlf6.js} +1 -1
  82. package/codeyam-cli/src/webserver/build/server/assets/{index-8Fv-lH1-.js → index-CxaRxKVt.js} +1 -1
  83. package/codeyam-cli/src/webserver/build/server/assets/server-build-D4DT0nM_.js +259 -0
  84. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  85. package/codeyam-cli/src/webserver/build-info.json +5 -5
  86. package/codeyam-cli/templates/codeyam-memory.md +5 -1
  87. package/codeyam-cli/templates/rules-instructions.md +1 -1
  88. package/package.json +8 -8
  89. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +24 -16
  90. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  91. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +42 -13
  92. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  93. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +123 -67
  94. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  95. package/packages/utils/src/lib/fs/rsyncCopy.js +93 -2
  96. package/packages/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  97. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-CN61MOMa.js +0 -11
  98. package/codeyam-cli/src/webserver/build/client/assets/globals-CKT08Djd.css +0 -1
  99. package/codeyam-cli/src/webserver/build/client/assets/root-CHhiHoo_.js +0 -62
  100. package/codeyam-cli/src/webserver/build/server/assets/server-build-Akn3iYFP.js +0 -257
@@ -1,257 +0,0 @@
1
- var fi=Object.defineProperty;var Ya=e=>{throw TypeError(e)};var gi=(e,t,r)=>t in e?fi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var fn=(e,t,r)=>gi(e,typeof t!="symbol"?t+"":t,r),yi=(e,t,r)=>t.has(e)||Ya("Cannot "+r);var za=(e,t,r)=>(yi(e,t,"read from private field"),r?r.call(e):t.get(e)),Ba=(e,t,r)=>t.has(e)?Ya("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);import{jsx as n,jsxs as l,Fragment as he}from"react/jsx-runtime";import{PassThrough as xi}from"node:stream";import{createReadableStreamFromReadable as bi}from"@react-router/node";import{ServerRouter as vi,useFetcher as Ae,useLocation as Hn,useNavigate as Mt,Link as se,UNSAFE_withComponentProps as De,Meta as wi,Links as Ci,ScrollRestoration as Ni,Scripts as Si,useLoaderData as Be,useRevalidator as at,Outlet as Ei,data as B,useSearchParams as sn,useParams as Is,useActionData as Ai,redirect as ki}from"react-router";import{isbot as Pi}from"isbot";import{renderToPipeableStream as _i}from"react-dom/server";import{useState as P,useEffect as ee,useCallback as oe,createContext as Ur,useContext as Jn,useRef as Ne,useMemo as re}from"react";import{Settings as Ua,CheckCircle2 as Wr,Bug as $s,AlertTriangle as _n,Check as At,Copy as $t,Loader2 as Ze,HomeIcon as Mi,GitCommitIcon as Wa,File as Ti,RefreshCw as ji,BookOpen as Hr,FlaskConical as Ii,SettingsIcon as $i,PanelsTopLeftIcon as Ri,ComponentIcon as Di,FileText as Ha,Code as Ja,Box as Li,List as Fi,BarChart3 as Oi,Tag as Yi,Image as en,Code2 as Rs,Activity as yr,ChevronDown as mt,CircleEqual as zi,ArrowLeft as Bi,Terminal as Mn,Search as on,ChevronRight as Lt,Save as Ui,Pause as Ds,ListTodo as Wi,PauseCircle as Hi,FileCode as Tn,GripVertical as Ji,Ban as Vi,CheckCircle as Gi,FolderOpen as qi,CodeXml as Ki,Zap as Qi,Pencil as Zi,Trash2 as Xi,X as Jr,Folder as Ls,Info as $r,Plus as Vr,Eye as el,FolderTree as tl,ChevronsUpDown as Fs,ChevronsDownUp as Os}from"lucide-react";import"fetch-retry";import nl from"better-sqlite3";import{Pool as rl}from"pg";import*as K from"fs";import kt,{existsSync as It}from"fs";import*as Z from"path";import ie from"path";import{OperationNodeTransformer as al,Kysely as Ys,ParseJSONResultsPlugin as sl,SqliteDialect as ol,PostgresDialect as il,sql as Ke}from"kysely";import*as ll from"kysely/helpers/sqlite";import*as cl from"kysely/helpers/postgres";import Te from"typescript";import*as Re from"fs/promises";import pe,{readdir as Va,stat as Ga,readFile as tn,writeFile as Gt,mkdir as dl}from"fs/promises";import*as ul from"os";import Rr from"os";import hl from"prompts";import jn from"chalk";import*as ml from"crypto";import Vn,{randomUUID as zs,createHmac as pl}from"crypto";import{execSync as je,spawn as Gn,exec as Gr}from"child_process";import{fileURLToPath as qn}from"url";import{promisify as qr}from"util";import fl from"dotenv";import gl,{EventEmitter as yl}from"events";import{v4 as xl}from"uuid";import bl from"openai";import vl from"p-queue";import qa from"p-retry";import{DynamoDBClient as Kn,PutItemCommand as wl}from"@aws-sdk/client-dynamodb";import{LRUCache as Kr}from"lru-cache";import"pluralize";import"piscina";import Cl from"json5";import{marshall as Nl}from"@aws-sdk/util-dynamodb";import Sl from"v8";import{Prism as El}from"react-syntax-highlighter";import{vscDarkPlus as Al}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as kl}from"node:crypto";import{minimatch as Bs}from"minimatch";import Pl from"react-markdown";import _l from"remark-gfm";import Ml from"react-diff-viewer-continued";const Us=5e3;function Tl(e,t,r,a,s){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let c=!1,d=e.headers.get("user-agent"),h=d&&Pi(d)||a.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>p(),Us+1e3);const{pipe:m,abort:p}=_i(n(vi,{context:a,url:e.url}),{[h](){c=!0;const f=new xi({final(g){clearTimeout(u),u=void 0,g()}}),y=bi(f);r.set("Content-Type","text/html"),m(f),o(new Response(y,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,c&&console.error(f)}})})}const jl=Object.freeze(Object.defineProperty({__proto__:null,default:Tl,streamTimeout:Us},Symbol.toStringTag,{value:"Module"}));function Il({id:e,selected:t,onClick:r,icon:a,name:s}){const[o,i]=P(!1);ee(()=>{i(!0)},[]);const c=oe(()=>{r==null||r(e)},[r,e]);return l("button",{className:`
2
- w-full px-1.5 py-2 cursor-pointer focus:outline-none
3
- flex flex-col items-center justify-center gap-1 transition-colors
4
- ${t?"text-[#CBF3FA]":"text-[#568B94] hover:text-[#CBF3FA]"}
5
- `,onClick:c,children:[n("div",{className:`${t?"bg-[#CBF3FA] text-[#022A35]":""} w-9 h-9 rounded-lg flex items-center justify-center transition-colors`,children:o&&a}),n("span",{className:`text-[10px] font-normal text-center leading-tight ${t?"text-[#CBF3FA]":""}`,style:t?{color:"#CBF3FA !important"}:void 0,children:s})]})}const Ws="/assets/cy-logo-cli-CCKUIm0S.svg";function $l(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 Rl({content:e,className:t=""}){const[r,a]=P(!1),s=oe(()=>{navigator.clipboard.writeText(e).then(()=>{a(!0),setTimeout(()=>a(!1),2e3)}).catch(o=>{console.error("Failed to copy:",o)})},[e]);return n("button",{onClick:s,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?l(he,{children:[n(At,{size:14}),"Copied"]}):l(he,{children:[n($t,{size:14}),"Copy"]})})}function Hs({isOpen:e,onClose:t,context:r,defaultEmail:a="",screenshotDataUrl:s}){const[o,i]=P(""),[c,d]=P(a),[h,u]=P(!1),[m,p]=P(!1),[f,y]=P(null),[g,x]=P(null),b=Ae(),v=b.state!=="idle",C=!!(r.scenarioId||r.analysisId),w=r.analysisId||r.scenarioId||"",N=()=>{const j=`/codeyam-diagnose ${w}`;return o.trim()?`${j} ${o.trim()}`:j};if(b.data&&!m&&!g){const j=b.data;j.success&&j.reportId?(p(!0),y(j.reportId)):j.error&&x(j.error)}const S=async()=>{x(null);const j=new FormData;if(j.append("issueType","other"),j.append("description",o),j.append("email",c),j.append("source",r.source),j.append("entitySha",r.entitySha||""),j.append("scenarioId",r.scenarioId||""),j.append("analysisId",r.analysisId||""),j.append("currentUrl",r.currentUrl),j.append("entityName",r.entityName||""),j.append("entityType",r.entityType||""),j.append("scenarioName",r.scenarioName||""),j.append("errorMessage",r.errorMessage||""),s)try{const F=await(await fetch(s)).blob();j.append("screenshot",F,"screenshot.jpg")}catch(L){console.error("Failed to convert screenshot:",L)}b.submit(j,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},k=()=>{i(""),u(!1),p(!1),y(null),x(null),t()},M=j=>{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:M,children:l("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl max-h-[90vh] overflow-y-auto",children:[l("div",{className:"flex items-center justify-between mb-6",children:[l("div",{className:"flex items-center gap-3",children:[v?n("div",{className:"animate-spin",children:n(Ua,{size:24,style:{strokeWidth:1.5}})}):m?n(Wr,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n($s,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:m?"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"})})})]}),m?l("div",{children:[l("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[n("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),l("p",{className:"text-xs text-green-700",children:["Report ID:"," ",n("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),n("p",{className:"text-sm text-gray-600 mb-6",children:"The CodeYam team will investigate and may reach out if you provided an email address."}),n("div",{className:"flex justify-end",children:n("button",{onClick:k,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):l("div",{children:[l("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[l("div",{className:"flex items-center justify-between",children:[n("div",{className:"text-sm font-medium text-gray-900",title:`${r.source}${r.entitySha?` • Entity: ${r.entitySha}`:""}${r.scenarioId?` • Scenario: ${r.scenarioId}`:""}${r.analysisId?` • Analysis: ${r.analysisId}`:""}`,children:$l(r)}),n("button",{type:"button",onClick:()=>u(!h),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:h?"Hide":"Details"})]}),h&&l("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[l("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),l("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&l("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&l("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&l("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),s&&l("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:s,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:o,onChange:j=>i(j.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"})]}),C&&l(he,{children:[l("div",{className:"mb-4 p-4 bg-purple-50 rounded-lg border border-purple-200",children:[l("div",{className:"flex items-center gap-2 mb-2",children:[n("span",{className:"text-lg",children:"🔧"}),n("h3",{className:"text-sm font-semibold text-purple-900",children:"Diagnose & Fix (Recommended)"})]}),n("p",{className:"text-xs text-purple-700 mb-3",children:"Run this command in Claude Code to investigate the issue locally and potentially fix it. A detailed report will also be uploaded."}),l("div",{className:"relative",children:[n("div",{className:"bg-gray-800 text-gray-50 px-3 py-2.5 pr-20 rounded-md text-xs font-mono overflow-x-auto whitespace-nowrap",children:N()}),n(Rl,{content:N(),className:"absolute top-1.5 right-2 px-2 py-1 bg-purple-600 text-white border-none rounded text-[11px] font-medium hover:bg-purple-700 transition-colors"})]})]}),l("div",{className:"relative my-5",children:[n("div",{className:"absolute inset-0 flex items-center",children:n("div",{className:"w-full border-t border-gray-300"})}),n("div",{className:"relative flex justify-center",children:n("span",{className:"bg-white px-3 text-xs text-gray-500 uppercase",children:"or"})})]})]}),l("div",{className:C?"opacity-75":"",children:[C&&l("div",{className:"flex items-center gap-2 mb-3",children:[n("span",{className:"text-lg",children:"📤"}),n("h3",{className:"text-sm font-semibold text-gray-700",children:"Quick Report"}),n("span",{className:"text-xs text-gray-500",children:"(won't investigate locally)"})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),n("input",{id:"email",type:"email",value:c,onChange:j=>d(j.target.value),placeholder:"you@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"})]}),l("div",{className:"mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(_n,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),l("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),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&&l("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(_n,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),l("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:g})]})]}),l("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:k,disabled: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?l(he,{children:[n("div",{className:"animate-spin",children:n(Ua,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):g?"Try Again":"Submit Report"})]})]})]})]})}):null}const Ka={source:"navbar"},Qr=Ur(void 0);function Dl({children:e}){const[t,r]=P(Ka),a=oe(o=>{r(o)},[]),s=oe(()=>{r(Ka)},[]);return n(Qr.Provider,{value:{contextData:t,setContextData:a,resetContextData:s},children:e})}function Xe(e){const t=Jn(Qr),r=Ne(t);ee(()=>{if(r.current)return r.current.setContextData(e),()=>{var a;(a=r.current)==null||a.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId,e.entityName,e.entityType,e.scenarioName,e.errorMessage])}function Ll(){const e=Jn(Qr),t=Hn();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 Fl({labs:e}){var w;const t=Hn(),r=Mt(),[a,s]=P(),[o,i]=P(!1),[c,d]=P(!1),[h,u]=P(null),m=Ae();ee(()=>{m.state==="idle"&&!m.data&&m.load("/api/generate-report")},[m]);const p=((w=m.data)==null?void 0:w.defaultEmail)||"",f={width:"20px",height:"20px",strokeWidth:1.5},y=(e==null?void 0:e.simulations)??!1,g=[{id:"dashboard",icon:n(Mi,{style:f}),link:"/",name:"Dashboard",hidden:!y},{id:"simulations",icon:l("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:f,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:!y},{id:"git",icon:n(Wa,{style:f}),link:"/git",name:"Git",hidden:!y},{id:"files",icon:n(Ti,{style:f}),link:"/files",name:"Files",hidden:!y},{id:"activity",icon:n(ji,{style:f}),link:"/activity",name:"Activity",hidden:!y},{id:"memory",icon:n(Hr,{style:f}),link:"/memory",name:"Memory"},{id:"labs",icon:n(Ii,{style:f}),link:"/labs",name:"Labs"},{id:"settings",icon:n($i,{style:f}),link:"/settings",name:"Settings"},{id:"commits",icon:n(Wa,{style:f}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(Ri,{style:f}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(Di,{style:f}),link:"/components",name:"Components",hidden:!0}],x=oe(N=>{const S=g.find(k=>k.id===N);S!=null&&S.link&&r(S.link),s(k=>k===N?void 0:N)},[g,r]);ee(()=>{const N={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[S,k]of Object.entries(N))if(k.some(M=>M==="/"?t.pathname==="/":t.pathname.includes(M))){s(S);return}s(void 0)},[t]);const b=async()=>{d(!0);try{const{default:N}=await import("html2canvas-pro"),k=(await N(document.body)).toDataURL("image/jpeg",.8);u(k),i(!0)}catch(N){console.error("Screenshot capture failed:",N),i(!0)}finally{d(!1)}},v=()=>{i(!1),u(null)},C=Ll();return l(he,{children:[l("div",{id:"sidebar",className:"relative w-full h-screen bg-[#051C22] flex flex-col justify-between py-3",children:[l("div",{className:"w-full flex flex-col items-center",children:[n("div",{className:"py-3 mt-2 mb-4",children:n(se,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:Ws,alt:"CodeYam",className:"h-6"})})}),g.filter(N=>!N.hidden).map(N=>n(Il,{id:N.id,selected:N.id===a,onClick:x,icon:N.icon,name:N.name},`sidebar-button-${N.id}`))]}),n("div",{className:"w-full flex flex-col items-center pb-2",children:l("button",{onClick:()=>void b(),disabled:c,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:c?n(Ze,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n($s,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:c?"Capturing...":`Report
6
- Bug`})]})})]}),o&&n(Hs,{isOpen:!0,onClose:v,context:C,defaultEmail:p,screenshotDataUrl:h??void 0})]})}const Js=Ur(void 0);function Ol({children:e}){const[t,r]=P([]),a=oe((o,i="info",c=5e3)=>{const h={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:c};r(u=>[...u,h])},[]),s=oe(o=>{r(i=>i.filter(c=>c.id!==o))},[]);return n(Js.Provider,{value:{toasts:t,showToast:a,closeToast:s},children:e})}function Zr(){const e=Jn(Js);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Yl({toast:e,onClose:t}){ee(()=>{const s=e.duration||5e3;if(s>0){const o=setTimeout(()=>{t(e.id)},s);return()=>clearTimeout(o)}},[e.id,e.duration,t]);const r={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return l("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg min-w-[320px] max-w-[500px] animate-[slideIn_0.3s_ease-out] ${{success:"bg-emerald-50 border-emerald-200 text-emerald-900",error:"bg-red-50 border-red-200 text-red-900",info:"bg-blue-50 border-blue-200 text-blue-900",warning:"bg-amber-50 border-amber-200 text-amber-900"}[e.type]}`,children:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function zl({toasts:e,onClose:t}){return e.length===0?null:l("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
7
- @keyframes slideIn {
8
- from {
9
- transform: translateX(400px);
10
- opacity: 0;
11
- }
12
- to {
13
- transform: translateX(0);
14
- opacity: 1;
15
- }
16
- }
17
- `}),e.map(r=>n(Yl,{toast:r,onClose:t},r.id))]})}function ft(e,t){const[r,a]=P(""),[s,o]=P(!1),[i,c]=P(null),[d,h]=P(!1);ee(()=>{t&&(h(!1),o(!1),c(null))},[t]),ee(()=>{if(!e||!t){t||a("");return}const m=async()=>{try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const g=(await f.text()).trim().split(`
18
- `).filter(v=>v.length>0);if(g.length<3){o(!1),h(!1),c(null),a("");return}const x=g.filter(v=>v.includes("CodeYam Log Level 1"));if(x.length>0){const v=x[x.length-1];a(v.replace(/.*CodeYam Log Level 1: /,""))}const b=g.find(v=>v.includes("$$INTERACTIVE_SERVER_URL$$:"));if(b){const v=b.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();c(v),h(!0)}g.some(v=>v.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};m().catch(()=>{});const p=setInterval(()=>{m().catch(()=>{})},2e3);return()=>clearInterval(p)},[e,t]);const u=oe(()=>{a(""),o(!1),c(null),h(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:s,resetLogs:u}}function ht({projectSlug:e,onClose:t}){const[r,a]=P("Loading logs..."),[s,o]=P(!0),[i,c]=P(!0),[d,h]=P("all"),u=Ne(null);return ee(()=>{const m=async()=>{try{const p=await fetch(`/api/logs/${e}`);if(p.ok){const f=await p.text();if(d==="all")a(f);else{const y=f.trim().split(`
19
- `).filter(g=>{if(g.length===0)return!1;const x=g.match(/^.*CodeYam Log Level (\d+):/);return!!x&&Number(x[1])<=d});a(y.map(g=>g.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
20
- `))}i&&u.current&&setTimeout(()=>{var y;(y=u.current)==null||y.scrollTo({top:u.current.scrollHeight,behavior:"smooth"})},100)}else a(`Error: ${p.status} - ${await p.text()}`)}catch(p){a(`Error fetching logs: ${p.message}`)}};if(m().catch(()=>{}),s){const p=setInterval(()=>{m().catch(()=>{})},2e3);return()=>clearInterval(p)}},[e,s,i,d]),ee(()=>{const m=p=>{p.key==="Escape"&&t()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:l("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:m=>m.stopPropagation(),children:[l("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[l("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),l("div",{className:"flex items-center gap-4",children:[l("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),l("select",{value:d,onChange:m=>h(m.target.value==="all"?"all":Number(m.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:s,onChange:m=>o(m.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:m=>c(m.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 Je({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"}},a=r[e]||r.other,s=t==="large"?18:14,o=t==="large"?32:18,i=()=>{switch(e){case"library":return n(Rs,{size:s,color:a.iconColor});case"visual":return n(en,{size:s,color:a.iconColor});case"type":return n(Yi,{size:s,color:a.iconColor});case"data":return n(Oi,{size:s,color:a.iconColor});case"index":return n(Fi,{size:s,color:a.iconColor});case"functionCall":return n(Ja,{size:s,color:a.iconColor});case"class":return n(Li,{size:s,color:a.iconColor});case"method":return n(Ja,{size:s,color:a.iconColor});case"other":return n(Ha,{size:s,color:a.iconColor});default:return n(Ha,{size:s,color:a.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${a.bgColor}`,style:{width:`${o}px`,height:`${o}px`},children:i()})}function Vs({filePath:e,maxLength:t=60,className:r,style:a}){const o=((c,d)=>{if(c.length<=d)return c;const h="...",u=d-h.length,m=Math.ceil(u*.4),p=Math.floor(u*.6),f=c.slice(0,m),y=c.slice(-p),g=f.lastIndexOf("/"),x=y.indexOf("/"),b=g>m*.5?f.slice(0,g+1):f,v=x!==-1&&x<p*.5?y.slice(x):y;return`${b}${h}${v}`})(e,t),i=o!==e;return n("span",{className:r||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...a,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:o})}function xr({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:a=50,showScenarioCount:s=!1,scenarioCount:o=0,additionalContent:i}){return l("div",{className:"flex flex-col gap-1",children:[l("div",{className:"flex items-center gap-1",children:[n(Je,{type:e.entityType||"other"}),l(se,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:t,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,s&&o>0&&` (${o})`]}),n(Vs,{filePath:e.filePath,maxLength:a,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const br={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function Bl({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:a=!1,queuedJobCount:s=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:c=[]}){var V,U,z;const[d,h]=P(!1),[u,m]=P(!1),[p,f]=P(null),[y,g]=P(new Set),[x,b]=P(new Set),[v,C]=P(!1),w=!!i||o.length>0,N=!!i,S=(i==null?void 0:i.entities)||r,k=!!(e!=null&&e.analysisCompletedAt),M=(e==null?void 0:e.readyToBeCaptured)??0,j=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||k&&(M===0||j>=M);const L=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,F=w,{lastLine:_}=ft(t,F),E=N||o.length>0,T=new Set(((V=i==null?void 0:i.entities)==null?void 0:V.map(Y=>Y.sha))||[]),O=c.filter(Y=>!(Y.currentEntityShas||[]).some(A=>T.has(A))),G=(()=>{const R=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&L){const A=e.analysisCompletedAt||e.createdAt;if(new Date(A).getTime()>R)return!0}if(O.length>0){const A=O[0],H=A.analysisCompletedAt||A.archivedAt||A.createdAt;if(H&&new Date(H).getTime()>R)return!0}return!1})();return ee(()=>{const Y=(i==null?void 0:i.id)||null;w&&!u&&Y!==p&&m(!0),!w&&p!==null&&f(null)},[w,i==null?void 0:i.id,u,p]),l(he,{children:[l("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${u?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!u&&l("div",{onClick:()=>{m(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[E?n(Ze,{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(yr,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:E?"Analyzing...":"Activity: No Activity Yet"}),E&&n("button",{onClick:Y=>{Y.stopPropagation(),h(!0)},className:"ml-auto px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),u&&l("div",{children:[l("div",{className:"flex items-center justify-between px-3 py-2",children:[l("div",{className:"flex items-center gap-2",children:[E?n(Ze,{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(yr,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:E?"Analyzing...":"Activity"})]}),l("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>h(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{m(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:n(mt,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),l("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[E&&i&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(yr,{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?l("div",{className:"space-y-1.5",children:[(v?S:S.slice(0,3)).map(Y=>n(xr,{entity:Y,nameSize:"11px",pathSize:"10px",pathMaxLength:150},Y.sha)),S.length>3&&n("button",{onClick:()=>C(Y=>!Y),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:br,"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:_})]}):l("div",{children:[i.entityNames&&i.entityNames.length>0?l("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((Y,R)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:Y},R)),i.entityNames.length>5&&l("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):l("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((U=i.entityShas)==null?void 0:U.length)||0," ",((z=i.entityShas)==null?void 0:z.length)===1?"entity":"entities","..."]}),_&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:_})]})})]}),o.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(zi,{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(Y=>{var H,W;const R=y.has(Y.id),A=R?Y.entities:Y.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:Y.entities.length>0?l("div",{className:"space-y-1.5",children:[A.map(J=>n(xr,{entity:J,nameSize:"10px",pathSize:"9px",pathMaxLength:120},J.sha)),Y.entities.length>3&&n("button",{onClick:()=>{g(J=>{const ae=new Set(J);return ae.has(Y.id)?ae.delete(Y.id):ae.add(Y.id),ae})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:br,"aria-label":R?"Show fewer entities":`Show ${Y.entities.length-3} more entities`,children:R?"Show less":`+${Y.entities.length-3} more`})]}):l("div",{style:{fontSize:"10px",color:"#343434"},children:[Y.type==="analysis"&&n(he,{children:Y.entityNames&&Y.entityNames.length>0?l("div",{className:"space-y-0.5",children:[Y.entityNames.slice(0,5).map((J,ae)=>n("div",{children:J},ae)),Y.entityNames.length>5&&l("div",{className:"italic",children:["+",Y.entityNames.length-5," more"]})]}):`Analyzing ${((H=Y.entityShas)==null?void 0:H.length)||0} ${((W=Y.entityShas)==null?void 0:W.length)===1?"entity":"entities"}`}),Y.type==="recapture"&&"Recapturing scenario",Y.type==="debug-setup"&&"Setting up debug environment"]})},Y.id)})})]}),G&&O.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Wr,{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:O.slice(0,3).map((Y,R)=>{const A=Y.entities||[],H=Y.analysisCompletedAt||Y.archivedAt||Y.createdAt||"",W=(()=>{if(!H)return"";const I=Date.now()-new Date(H).getTime(),D=Math.floor(I/6e4),q=Math.floor(I/36e5);return q>0?`${q}h ago`:D>0?`${D}m ago`:"just now"})(),J=x.has(R),$=(J?A:A.slice(0,3)).map(I=>{var D,q,te;return{...I,scenarioCount:((te=(q=(D=I.analyses)==null?void 0:D[0])==null?void 0:q.scenarios)==null?void 0:te.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:A.length>0&&l("div",{className:"space-y-1.5",children:[$.map((I,D)=>l("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(xr,{entity:I,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:I.scenarioCount})}),D===0&&W&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:W})]},I.sha)),A.length>3&&n("button",{onClick:()=>{b(I=>{const D=new Set(I);return D.has(R)?D.delete(R):D.add(R),D})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:br,"aria-label":J?"Show fewer entities":`Show ${A.length-3} more entities`,children:J?"Show less":`+${A.length-3} more`})]})},R)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(se,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&t&&n(ht,{projectSlug:t,onClose:()=>h(!1)})]})}function Ve(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function ln(e){const{file_id:t,project_id:r,commit_id:a,file_path:s,entity_type:o,entity_branches:i,analyses:c,commit:d,created_at:h,updated_at:u,...m}=e,p=(i??[]).map(g=>g.branch_id),f=c?c.map(st):void 0,y=d?Pt(d):void 0;return Ve({...m,fileId:t,projectId:r,commitId:a,filePath:s,entityType:o,commit:y,analyses:f,branchIds:p,createdAt:h,updatedAt:u})}function Xr(e){return Ve({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 ea(e){const{branches:t,files:r,analyzed_at:a,content_changed_at:s,created_at:o,updated_at:i,github_token:c,configuration:d,team_id:h,...u}=e;return Ve({...u,branches:t?t.map(Rt):void 0,files:r?r.map(Xr):void 0,analyzedAt:a,contentChangedAt:s,createdAt:o,updatedAt:i})}function Ul(e){const{id:t,project_id:r,user_id:a,scenario_id:s,thumbs_up:o,user:i}=e,c=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return Ve({id:t,projectId:r,userId:a,scenarioId:s,thumbsUp:!!o,user:c})}function Wl(e){const{id:t,project_id:r,user_id:a,scenario_id:s,text:o,created_at:i,updated_at:c,user:d}=e,h=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return Ve({id:t,projectId:r,userId:a,scenarioId:s,text:o,createdAt:i,updatedAt:c,user:h})}function Gs(e){const{project_id:t,analysis_id:r,previous_version_id:a,analysis:s,user_scenarios:o,scenario_comments:i,approved:c,...d}=e,h=s?st(s):void 0,u=o?o.map(Ul):void 0,m=i?i.map(Wl):void 0;return Ve({...d,projectId:t,analysisId:r,previousVersionId:a,analysis:h,userScenarios:u,comments:m})}function Hl(e){return Ve({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?st(e.analysis):void 0,entity:e.entity?ln(e.entity):void 0,branch:e.branch?Rt(e.branch):void 0,createdAt:e.created_at})}function st(e){const{project_id:t,commit_id:r,file_id:a,file_path:s,entity_sha:o,entity_type:i,entity_name:c,previous_analysis_id:d,file:h,entity:u,commit:m,project:p,scenarios:f,analysis_branches:y,dependency_analyzed_tree_sha:g,analyzed_tree_sha:x,branch_commit_sha:b,committed_at:v,completed_at:C,created_at:w,updated_at:N,indirect:S,...k}=e,M=u?ln(u):void 0,j=h?Xr(h):void 0,L=p?ea(p):void 0,F=m?Pt(m):void 0,_=f?f.map(Gs):void 0,E=y?y.map(Hl):void 0,T=E?E.map(O=>O.branch):void 0;return Ve({...k,projectId:t,commitId:r,fileId:a,filePath:s,entitySha:o,entityType:i,entityName:c,previousAnalysisId:d,entity:M,file:j,commit:F,project:L,scenarios:_,analysisBranches:E,branches:T,dependencyAnalyzedTreeSha:g,analyzedTreeSha:x,branchCommitSha:b,committedAt:v,completedAt:C,createdAt:w,updatedAt:N,indirect:!!S})}function ta(e){return Ve({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?Pt(e.commit):void 0,branch:e.branch?Rt(e.branch):void 0})}function Jl(e){const{project_id:t,commit_id:r,created_at:a,updated_at:s,success:o,...i}=e;return Ve({...i,projectId:t,commitId:r,createdAt:a,updatedAt:s,success:!!o})}function Pt(e){const{project_id:t,branch_id:r,branch:a,background_jobs:s,merged_branch_id:o,mergedBranch:i,ai_message:c,html_url:d,author:h,analyses:u,entities:m,commit_branches:p,committed_at:f,analyzed_at:y,...g}=e,x=a?Rt(a):void 0,b=i?Rt(i):void 0,v=(s==null?void 0:s.length)>0?Jl(s[s.length-1]):void 0,C=(u??[]).map(st),w=(m??[]).map(ln),N=(p==null?void 0:p.length)>0?p.map(ta):void 0;return h&&(h.username=h.preferredUsername??h.username),Ve({...g,projectId:t,branchId:r,branch:x,backgroundJob:v,mergedBranchId:o,mergedBranch:b,aiMessage:c,htmlUrl:d,author:h,analyses:C,entities:w,commitBranches:N,committedAt:f,analyzedAt:y})}function Rt(e){const{project_id:t,content_changed_at:r,commits:a,analysis_branches:s,active_at:o,created_at:i,updated_at:c,primary:d,...h}=e,u=a?a.map(Pt):void 0,m=s?s.flatMap(p=>st(p.analysis)):void 0;return Ve({...h,projectId:t,contentChangedAt:r,commits:u,analyses:m,activeAt:o,createdAt:i,updatedAt:c,primary:!!d})}var Wn;class Vl{constructor(){Ba(this,Wn,new Gl)}transformQuery(t){return za(this,Wn).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}Wn=new WeakMap;class Gl extends al{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 X=()=>null,ql={analyzed_at:X(),configuration:X(),content_changed_at:X(),created_at:X(),description:X(),github_token:X(),id:X(),metadata:X(),name:X(),path:X(),slug:X(),team_id:X(),updated_at:X()},Kl=Object.keys(ql),Ql={active:X(),analysis_id:X(),branch_id:X(),created_at:X(),entity_sha:X(),id:X()},Zl=Object.keys(Ql),Xl={active_at:X(),content_changed_at:X(),created_at:X(),id:X(),metadata:X(),name:X(),primary:X(),project_id:X(),ref:X(),sha:X(),updated_at:X()},qs=Object.keys(Xl),ec={ai_message:X(),analyzed_at:X(),author_github_username:X(),branch_id:X(),committed_at:X(),created_at:X(),files:X(),html_url:X(),id:X(),merged_branch_id:X(),message:X(),metadata:X(),project_id:X(),sha:X(),title:X(),url:X()},Ks=Object.keys(ec);Ks.filter(e=>e!=="files");const tc={commit_id:X(),created_at:X(),description:X(),documentation:X(),entity_type:X(),file_id:X(),file_path:X(),metadata:X(),name:X(),project_id:X(),quality:X(),sha:X(),updated_at:X()},Qs=Object.keys(tc),nc={active:X(),branch_id:X(),entity_sha:X()},rc=Object.keys(nc),ac={created_at:X(),deleted:X(),id:X(),metadata:X(),name:X(),path:X(),project_id:X(),updated_at:X()},sc=Object.keys(ac),oc={analysis_id:X(),approved:X(),created_at:X(),description:X(),id:X(),metadata:X(),name:X(),previous_version_id:X(),project_id:X()},In=Object.keys(oc),ic=!!_t("ENABLE_QUERY_LOGGING"),lc=!!_t("ENABLE_QUERY_ERROR_LOGGING");_t("USE_LOCAL_POSTGRESQL_FOR_TESTING");let gn;function ke(){if(!gn){const e=Xs();if(e==="sqlite")gn=cc();else if(e==="postgresql")gn=dc();else throw new Error(`Unknown database type: ${e}`)}return gn}function cc(e){if(e||(e=_t("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=K.existsSync(e),r=Z.dirname(e);if(!K.existsSync(r))K.mkdirSync(r,{recursive:!0,mode:493});else try{K.chmodSync(r,493)}catch(s){console.warn(`Warning: Could not set permissions on database directory: ${s.message}`)}const a=new nl(e,{readonly:!1,fileMustExist:!1});if(a.pragma("journal_mode = WAL"),a.pragma("synchronous = FULL"),!process.env.CLAUDE_CODE_MODE)try{const s=a.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();t&&s.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(s){console.error("CodeYam DB ERROR: Failed to verify database schema:",s)}return new Ys({dialect:new ol({database:a}),plugins:[new sl,new Vl],log:Zs})}function dc(){const e=hc();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new rl({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,a)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new Ys({dialect:new il({pool:t}),log:Zs})}let vr=null;function Tt(){return vr||(vr=uc(Xs())),vr}function Zs(e){e.level==="error"?lc&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):ic&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function uc(e){if(e==="sqlite")return ll;if(e==="postgresql")return cl;throw new Error(`Unknown database type: ${e}`)}function Xs(){if(_t("SQLITE_PATH"))return"sqlite";if(_t("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function hc(){const e=_t("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function _t(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}var cn=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(cn||{});const Qn="Default Scenario";let mc="<main>";function pc(){return mc}function Qa(e,...t){we(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function we(...e){const t=pc(),r=e.map(s=>{if(s)return typeof s=="string"?s:s instanceof Error?`${s.name}: ${s.message}
21
- ${s.stack}`:typeof s=="object"?fc(s):String(s)}).filter(Boolean).join(`
22
- `),a=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(a+`
23
- `);return}console.log(a.replace(/\n/g,"\r"))}function fc(e,t=2){function r(a,s=new WeakMap){return a===null||typeof a!="object"?a:s.has(a)?`"[Circular: ${a.constructor.name}]"`:(s.set(a,!0),Array.isArray(a)?`[${a.map(c=>{const d=r(c,s);return typeof c=="string"?`"${d}"`:d}).join(",")}]`:`{${Object.entries(a).map(([i,c])=>{let d;return typeof c>"u"?null:(typeof c=="function"?d=`"(function: ${c.name||"anonymous"})"`:c instanceof Date?d=`"${c.toISOString()}"`:typeof c=="object"&&c!==null?d=r(c,s):typeof c=="string"?d=`"${c.replace(/"/g,'\\"')}"`:d=JSON.stringify(c),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(a){const s=r(e);if(!t)return s;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:a,serialized:s}),s}}}function $n(e,t){try{let r=function(o){var i,c;if(Te.isFunctionDeclaration(o)&&Jt(o)){const d=((i=o.name)==null?void 0:i.text)||"default",h=o.getText(a),u=wr(o);s.push({name:d,code:h,sha:vt(t,d,h),entityType:"function",isDefault:u})}else if(Te.isClassDeclaration(o)&&Jt(o)){const d=((c=o.name)==null?void 0:c.text)||"default",h=o.getText(a),u=wr(o),m=h.includes("React.")||h.includes("jsx")||h.includes("tsx");s.push({name:d,code:h,sha:vt(t,d,h),entityType:m?"component":"class",isDefault:u})}else if(Te.isInterfaceDeclaration(o)&&Jt(o)){const d=o.name.text,h=o.getText(a);s.push({name:d,code:h,sha:vt(t,d,h),entityType:"interface",isDefault:!1})}else if(Te.isTypeAliasDeclaration(o)&&Jt(o)){const d=o.name.text,h=o.getText(a);s.push({name:d,code:h,sha:vt(t,d,h),entityType:"type",isDefault:!1})}else if(Te.isVariableStatement(o)&&Jt(o)){const d=wr(o);o.declarationList.declarations.forEach(h=>{var u;if(Te.isIdentifier(h.name)){const m=h.name.text,p=o.getText(a),f=((u=h.initializer)==null?void 0:u.getText(a))||"",y=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));s.push({name:m,code:p,sha:vt(t,m,p),entityType:y?"component":"variable",isDefault:d})}})}else if(Te.isExportAssignment(o)){const d=o.getText(a);s.push({name:"default",code:d,sha:vt(t,"default",d),entityType:"unknown",isDefault:!0})}else if(Te.isExportDeclaration(o)&&o.exportClause&&Te.isNamedExports(o.exportClause)){const d=o.getText(a);for(const h of o.exportClause.elements){const u=h.name.text;s.push({name:u,code:d,sha:vt(t,u,d),entityType:"unknown",isDefault:!1})}}Te.forEachChild(o,r)};const a=Te.createSourceFile(t,e,Te.ScriptTarget.Latest,!0),s=[];return r(a),s}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function Jt(e){if(!Te.canHaveModifiers(e))return!1;const t=Te.getModifiers(e);return t?t.some(r=>r.kind===Te.SyntaxKind.ExportKeyword):!1}function wr(e){if(!Te.canHaveModifiers(e))return!1;const t=Te.getModifiers(e);return t?t.some(r=>r.kind===Te.SyntaxKind.DefaultKeyword):!1}function vt(e,t,r){const a=Vn.createHash("sha256");return a.update(`${e}:${t}:${r}`),a.digest("hex").substring(0,40)}function gc(e){var h;const{webapp:t,port:r,environmentVariables:a,packageManager:s}=e,o=t==null?void 0:t.startCommand;if(!o)return`${s} ${s==="npm"?"run ":""}dev`;const i=((h=o.args)==null?void 0:h.map(u=>u.replace(/\$PORT/g,String(r))))??[],c=[];for(const u of a)if(u.key&&u.value!==void 0){const m=String(u.value).replace(/'/g,"'\\''");c.push(`${u.key}='${m}'`)}if(o.env)for(const[u,m]of Object.entries(o.env)){const f=String(m).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");c.push(`${u}='${f}'`)}const d=c.length>0?c.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${o.command} ${i.join(" ")}`}function yc(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=Z.normalize(e),a=[...t].sort((s,o)=>{var i,c;return(((i=o.path)==null?void 0:i.length)??0)-(((c=s.path)==null?void 0:c.length)??0)});for(const s of a){const o=Z.normalize(s.path??".");if(o==="."||r.startsWith(o+Z.sep)||r===o)return s}return t[0]}function xc(e){const{filePath:t,webapps:r,environmentVariables:a,port:s,packageManager:o}=e;if(!r||r.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=yc(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const c=gc({webapp:i,port:s,environmentVariables:a,packageManager:o});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??o,startCommand:c,url:`http://localhost:${s}/static/codeyam-sample`}}function Zn(e,t,r=[]){const a=Array.isArray(t)?t:[t];return s=>s.columns(a).doUpdateSet(o=>{const i=Object.keys(e).filter(c=>c!==t&&!r.includes(c));return Object.fromEntries(i.map(c=>[c,o.ref(`excluded.${c}`)]))})}function bc(e){const{jsonObjectFrom:t}=Tt();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 vc({ids:e,analysisId:t}){const r=ke();try{let a=r.deleteFrom("scenarios");if(e){if(e.length===0)return;a=a.where("id","in",e)}else if(t)a=a.where("analysis_id","=",t);else throw we("CodeYam Error: No deletion criteria provided",null,{ids:e,analysisId:t}),new Error("No deletion criteria provided for scenarios");await a.execute()}catch(a){throw we("CodeYam Error: Database error deleting scenarios",a,{ids:e,analysisId:t}),a}}function wc(...e){try{const t=Vn.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 Cr(e,t){return t.map(r=>Cc(e,r))}function Cc(e,t){return Ke` ${Ke.ref(e)}.${Ke.ref(t)}`.as(t)}function Nc(e,t,r){return t.map(a=>Sc(e,a,r))}function Sc(e,t,r){return Ke` ${Ke.ref(e)}.${Ke.ref(t)}`.as(`_cy_${r}:${t}`)}function Ec(e,...t){const r={};for(const[a,s]of Object.entries(e)){const o=a.match(/^_cy_(.+?):(.+)$/);if(o){const[,i,c]=o;if(t.includes(i)){r[i]||(r[i]={}),r[i][c]=s;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${a}'`);continue}r[a]=s}return r}const Ac=50;function kc(e,t){return e.length<=t?[e]:Array.from({length:Math.ceil(e.length/t)},(r,a)=>e.slice(a*t,a*t+t))}function Za({projectId:e,ids:t,fileIds:r,entityName:a,entityShas:s,commitIds:o,branchCommitSha:i,limit:c,excludeMetadata:d}){const h=ke(),{jsonObjectFrom:u,jsonArrayFrom:m}=Tt();let p=d?h.selectFrom("analyses").select(["analyses.id","analyses.project_id","analyses.file_id","analyses.commit_id","analyses.entity_sha","analyses.entity_name","analyses.entity_type","analyses.file_path","analyses.status","analyses.created_at","analyses.updated_at","analyses.tree_sha","analyses.analyzed_tree_sha","analyses.dependency_analyzed_tree_sha","analyses.previous_analysis_id","analyses.branch_commit_sha","analyses.indirect","analyses.committed_at","analyses.completed_at"]):h.selectFrom("analyses").selectAll("analyses");if(e&&(p=p.where("project_id","=",e)),t){if(t.length===0)return null;p=p.where("id","in",t)}if(r){if(r.length===0)return null;p=p.where("file_id","in",r)}if(o){if(o.length===0)return null;p=p.where("commit_id","in",o)}return a&&(p=p.where("entity_name","=",a)),s&&(p=p.where("entity_sha","in",s)),i&&(p=p.where("branch_commit_sha","=",i)),c&&(p=p.limit(c)),d?h.with("filtered_analyses",()=>p).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[m(f.selectFrom("scenarios").select(Cr("scenarios",In)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),m(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):h.with("filtered_analyses",()=>p).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select(Cr("entities",Qs)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),m(f.selectFrom("scenarios").select(Cr("scenarios",In)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),m(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function pt(e){const{ids:t,fileIds:r,entityShas:a,commitIds:s}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:a,key:"entityShas"},commit_id:{arr:s,key:"commitIds"}}).find(([d,{arr:h}])=>(h==null?void 0:h.length)>0);let c=[];if(i){const[d,{arr:h,key:u}]=i,m=kc(h,Ac),p=[];for(let f=0;f<m.length;f++){const y=m[f],x=await Za({...e,[u]:y}).execute();x&&p.push(...x)}c=p}else{const h=await Za(e).execute();if(!h||h.length===0)return we("CodeYam: No analyses found",null,e),null;c=h}return c.length===0?null:c.map(st)}catch(o){return we("CodeYam Error: Database error in loadAnalyses",o,e),null}}function Pc(e,t){const{jsonArrayFrom:r,jsonObjectFrom:a}=Tt();let s=e.selectFrom("analysis_branches").select(Zl).select(o=>a(o.selectFrom("branches").select(qs).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(s=t(s)),r(s)}async function ot({id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}){const f=ke(),y=Date.now();try{let g=f.selectFrom("analyses").selectAll("analyses");e&&(g=g.where("id","=",e)),r&&(g=g.where("project_id","=",r)),i?g=g.where("dependency_analyzed_tree_sha","=",i):c?g=g.where("analyzed_tree_sha","=",c):a&&(g=g.where("file_id","=",a)),o&&(g=g.where("entity_name","=",o)),s?g=g.where("commit_id","=",s):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}=Tt();g=g.select(w=>{const N=[];return N.push(x(w.selectFrom("entities").select(Qs).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&N.push(x(w.selectFrom("files").select(sc).whereRef("files.id","=","analyses.file_id")).as("file")),h&&N.push(x(w.selectFrom("projects").select(Kl).whereRef("projects.id","=","analyses.project_id")).as("project")),m&&N.push(b(w.selectFrom("scenarios").select(In).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),p&&N.push(Pc(w,S=>S.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&N.push(x(w.selectFrom("commits").select(Ks).select(S=>bc(S).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),N});const v=await g.executeTakeFirst(),C=Date.now()-y;if(!v)return we("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}),null;if(C>100&&u){const w=v.commit,N=w!=null&&w.files?JSON.stringify(w.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${C}ms (files: ${Math.round(N/1024)}KB)`,{id:v.id,entityName:v.entity_name})}return st(v)}catch(g){return we("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}),null}}async function eo({projectId:e,ids:t,names:r,includeInactive:a}){const s=ke();try{let o=s.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 a||(o=o.where("active_at","is not",null)),(await o.execute()).map(Rt)}catch(o){return we("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:a}),[]}}async function _c({projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}){const o=ke();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(s,h=>h.select(Nc("branches",qs,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),a!==void 0&&(i=i.where("commit_branches.active","=",a));const c=await i.execute();return!c||c.length===0?null:c.map(h=>Ec(h,"branch")).map(ta)}catch(i){return we("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}),null}}async function Mc(e){if(e.length===0)return new Map;const t=ke();try{const r=await t.selectFrom("commits").select(["id","branch_id","merged_branch_id"]).where("id","in",e).execute(),a=new Set;if(r.forEach(o=>{o.branch_id&&a.add(o.branch_id),o.merged_branch_id&&a.add(o.merged_branch_id)}),a.size===0)return new Map;const s=await t.selectFrom("branches").selectAll().where("id","in",Array.from(a)).execute();return new Map(s.map(o=>[o.id,o]))}catch(r){return we("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function Tc(e){if(e.length===0)return new Map;const t=ke(),{jsonObjectFrom:r,jsonArrayFrom:a}=Tt();try{const s=await t.selectFrom("analyses").selectAll("analyses").select(i=>[r(i.selectFrom("files").select(["id","name","path"]).whereRef("files.id","=","analyses.file_id")).as("file"),a(i.selectFrom("scenarios").select(In).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),o=new Map;return s.forEach(i=>{const c=o.get(i.commit_id)||[];c.push(i),o.set(i.commit_id,c)}),o}catch(s){return we("CodeYam Error: Loading analyses for commits",s,{commitIds:e}),new Map}}async function jc(e){if(e.length===0)return new Map;const t=ke();try{const r=await t.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),a=new Map;return r.forEach(s=>{const o=a.get(s.commit_id)||[];o.push(s),a.set(s.commit_id,o)}),a}catch(r){return we("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function Rn({projectId:e,branchId:t,ids:r,shas:a,fileNames:s,limit:o=10,skipRelations:i=!1}){if(!e&&!r)throw new Error("Must provide projectId or ids");const c=ke(),{jsonObjectFrom:d}=Tt(),h=Date.now();try{let u=c.selectFrom("commits").selectAll("commits").select(v=>[d(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(a){if(a.length===0)return[];u=u.where("sha","in",a)}if(s&&s.length>0){const v=Ke.join(s.map(C=>Ke`${C}`),Ke`, `);u=u.where(Ke`
24
- EXISTS (
25
- SELECT 1
26
- FROM json_each(${Ke.ref("commits.files")}) AS f
27
- WHERE json_extract(f.value, '$.fileName') IN (${v})
28
- )
29
- `)}t&&(u=u.where("branch_id","=",t));const m=await u.orderBy("committed_at","desc").limit(o).execute(),p=Date.now()-h;if(!m||m.length===0)return[];if(p>100){const v=m.reduce((C,w)=>C+(w.files?JSON.stringify(w.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${p}ms (${m.length} commits, totalFiles: ${Math.round(v/1024)}KB)`)}if(i)return m.map(C=>({...C,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(Pt);const f=m.map(v=>v.id),[y,g,x]=await Promise.all([Mc(f),Tc(f),jc(f)]);return m.map(v=>{const C=v.branch_id?y.get(v.branch_id):void 0,w=v.merged_branch_id?y.get(v.merged_branch_id):void 0,N=g.get(v.id)||[],S=x.get(v.id)||[];return{...v,branch:C,mergedBranch:w,analyses:N,entities:S}}).map(Pt)}catch(u){return we("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:t,ids:r,shas:a,limit:o}),[]}}async function rt({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:o,excludeMetadata:i}){if(r&&r.length==0||a&&a.length==0||s&&s.length==0||o&&o.length==0)return[];if(o&&o.length>50){const d=[];for(let h=0;h<o.length;h+=50){const u=o.slice(h,h+50),m=await rt({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:u,excludeMetadata:i});m&&d.push(...m)}return d}const c=ke();try{const u=await(i?c.selectFrom("entities").select(["entities.project_id","entities.file_id","entities.commit_id","entities.name","entities.sha","entities.entity_type","entities.file_path","entities.description","entities.documentation","entities.quality","entities.created_at","entities.updated_at"]):c.selectFrom("entities").selectAll("entities")).$if(!!t,m=>m.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,m=>m.where("entities.project_id","=",e)).$if(!!o,m=>m.where("entities.sha","in",o)).$if(!!a,m=>m.where("entities.file_path","in",a)).$if(!!s,m=>m.where("entities.name","in",s)).$if(!!r,m=>m.where("entities.file_id","in",r)).execute();return!u||u.length===0?(console.log("Load Entities: No entities found",{projectId:e,fileIds:r,filePaths:a,shas:o}),null):u.map(ln)}catch(d){return console.log("Load Entities: Error occurred",d,{projectId:e,fileIds:r,filePaths:a,shas:o}),null}}function Ic(e,t){const{jsonArrayFrom:r}=Tt();let a=e.selectFrom("entity_branches").select(rc);return t&&(a=t(a)),r(a)}async function to({projectId:e,sha:t}){const r=ke();try{const a=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(s=>Ic(s,o=>o.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return a?ln(a):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&we("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:t}),null)}catch(a){return we("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:t}),null}}const Nr=1e3;async function no({projectId:e,filePaths:t,fileIds:r,fileNames:a}){if(t&&t.length>50){const c=[];for(let d=0;d<t.length;d+=50){const h=t.slice(d,d+50),u=await no({projectId:e,filePaths:h,fileIds:r,fileNames:a});u&&c.push(...u)}return c}const s=ke(),o=[];let i=0;try{for(;;){let c=s.selectFrom("files").selectAll().where("project_id","=",e).limit(Nr).offset(i);if(t){if(t.length===0)return[];c=c.where("path","in",t)}if(r){if(r.length===0)return[];c=c.where("id","in",r)}if(a){if(a.length===0)return[];c=c.where("name","in",a)}const d=await c.execute();if(!d||d.length===0||(o.push(...d),d.length<Nr))break;i+=Nr}return o==null?void 0:o.map(Xr)}catch(c){return console.log("CodeYam Error: Error loading project files in loadFiles",c),null}}async function $c({id:e,slug:t,withBranches:r,withFiles:a,silent:s}){try{let i=ke().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(t)i=i.where("slug","=",t);else throw new Error("Either id or slug must be provided");const c=await i.executeTakeFirst();if(!c)return s||console.log("CodeYam Error: Error loading project",{id:e,slug:t,withBranches:r,withFiles:a}),null;const d=ea(c);return a&&(d.files=await no({projectId:d.id})),r&&(d.branches=await eo({projectId:d.id,includeInactive:!1})),d}catch(o){return s||console.log("CodeYam Error: Error loading project",o),null}}function Dn(e,t){const r={...e};for(const a in t){const s=t[a],o=e[a];s!=null&&typeof s=="object"&&!Array.isArray(s)&&o!==void 0&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[a]=Dn(o,s):s!==void 0&&(r[a]=s)}return r}async function ut({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:a,archiveCurrentRun:s,updateCallback:o}){try{return await ke().transaction().execute(async i=>{var u,m;const c=await i.selectFrom("commits").select(["id","metadata"]).$if(!!e,p=>p.where("id","=",e)).$if(!!t,p=>p.where("sha","=",t)).executeTakeFirst();if(!c)return we(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const d=c.metadata||{};if(a)a.lastUpdatedAt??(a.lastUpdatedAt=new Date().toISOString()),a.currentEntityShas!==void 0&&(console.log("[updateCommitMetadata] Updating currentRun.currentEntityShas"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Previous entity SHAs:",(u=d.currentRun)==null?void 0:u.currentEntityShas),console.log("[updateCommitMetadata] New entity SHAs:",a.currentEntityShas),console.log("[updateCommitMetadata] Archive flag:",s)),r=Dn(r??{},{currentRun:a});else if(!r&&!o)return d;const h=r?Dn(d,r):d;if(s&&h.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Current run entity SHAs:",h.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${h.currentRun.analyzerPid}, capture=${h.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${h.currentRun.analysesCompleted}, captures=${h.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${((m=h.historicalRuns)==null?void 0:m.length)||0}`);const p={...h.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(p,null,2)),h.historicalRuns=[...h.historicalRuns||[],p],console.log(`[updateCommitMetadata] Historical runs after archiving: ${h.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(h.historicalRuns.map(f=>({entityShas:f.currentEntityShas,archivedAt:f.archivedAt,completed:{analyses:f.analysesCompleted,captures:f.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}o&&await o(h);try{return await i.updateTable("commits").set({metadata:JSON.stringify(h)}).where("id","=",c.id).returning(["id"]).executeTakeFirst()?h:(we(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),d)}catch(p){return we(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,p),d}})}catch(i){return we(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}`,i),null}}async function ro(e,t,r="analysis"){try{return await ke().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return we(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=st(s);return t(o.metadata,o),await a.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(we(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return we(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function Ft(e,t,r="capture"){try{return await ke().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return we(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=st(s);return t(o.status,o),await a.updateTable("analyses").set({status:JSON.stringify(o.status)}).where("id","=",e).returningAll().executeTakeFirst()?o.status:(we(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return we(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function Ln({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:a}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await ke().transaction().execute(async s=>{const o=await s.selectFrom("projects").selectAll().$if(!!e,d=>d.where("id","=",e)).$if(!!t,d=>d.where("slug","=",t)).executeTakeFirst();if(!o)return we(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!a)return i;const c=r?Dn(i,r):i;a&&await a(c,ea(o));try{return await s.updateTable("projects").set({metadata:JSON.stringify(c)}).where("id","=",o.id).returningAll().executeTakeFirst()?c:(we(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return we(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(s){return we(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,s),null}}const Rc=()=>crypto.randomUUID();function Dc(e){const{id:t,projectId:r,analysisId:a,previousVersionId:s,analysis:o,metadata:i,data:c,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:t??Rc(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:a,previous_version_id:s}}async function Lc(e){if(e.length===0)return[];const t=ke(),r=e.map(Dc);try{return(await t.insertInto("scenarios").values(r).onConflict(Zn(r[0],"id",["created_at"])).returningAll().execute()).map(Gs)}catch(a){return we("CodeYam Error: Database error upserting scenarios",a,{scenarioCount:e.length}),null}}const Fc=()=>crypto.randomUUID();function Oc(e){const{id:t,commitId:r,branchId:a,...s}=e;return delete s.commit,delete s.branch,{...s,id:t??Fc(),commit_id:r,branch_id:a}}async function Xa(e){if(e.length===0)return[];const t=ke(),r=e.map(Oc);try{return(await t.insertInto("commit_branches").values(r).onConflict(Zn(r[0],"id",["created_at"])).returningAll().execute()).map(ta)}catch(a){return we("CodeYam Error: Database error upserting commit branches",a,{commitBranchCount:e.length,commitBranchIds:e.map(s=>s.id)}),[]}}async function Yc(e,t){const r=ke(),a={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(a).onConflict(Zn(a,"username",[])).returningAll().executeTakeFirst()||null}catch(s){return we("CodeYam Error: Error upserting github user",s,{username:e,avatarUrl:t}),null}}const zc=()=>crypto.randomUUID();function Bc(e,t){const{id:r,projectId:a,branchId:s,mergedBranchId:o,aiMessage:i,htmlUrl:c,analyzedAt:d,committedAt:h,author:u,metadata:m,files:p,...f}=e;return delete f.branch,delete f.mergedBranch,delete f.backgroundJob,delete f.analyses,delete f.parents,delete f.entities,delete f.commitBranches,{...f,id:r??zc(),project_id:a??String(t),metadata:m?JSON.stringify(m):void 0,files:p?JSON.stringify(p):void 0,branch_id:s,merged_branch_id:o,author_github_username:u==null?void 0:u.username,html_url:c,ai_message:i,analyzed_at:d,committed_at:h}}async function Uc({projectId:e,commits:t}){const r=ke();try{const a=t.reduce((i,c)=>{const{author:d}=c;return d!=null&&d.username&&(d!=null&&d.avatarUrl)&&(i[d.username]=d.avatarUrl),i},{});for(const i in a)await Yc(i,a[i]);const s=t.map(i=>Bc(i,e));return(await r.insertInto("commits").values(s).onConflict(Zn(s[0],"id",["created_at"])).returningAll().execute()).map(Pt)}catch(a){return we("CodeYam Error: Error saving commits",a,{projectId:e,commitCount:t.length,commitIds:t.map(s=>s.id).filter(Boolean)}),[]}}const Fn=Z.join(ul.homedir(),".codeyam","secrets.json"),On=Z.join(process.cwd(),".codeyam","secrets.json");async function gt(){let e={};try{if(K.existsSync(On)){const o=await Re.readFile(On,"utf8");e=JSON.parse(o)}}catch{console.warn(jn.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(K.existsSync(Fn)){const o=await Re.readFile(Fn,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(jn.yellow("⚠ Could not read home secrets file, falling back to environment variables"))}const t={},r=e.OPENAI_API_KEY||process.env.OPENAI_API_KEY;r&&(t.OPENAI_API_KEY=r);const a=e.ANTHROPIC_API_KEY||process.env.ANTHROPIC_API_KEY;a&&(t.ANTHROPIC_API_KEY=a);const s=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return s&&(t.GROQ_API_KEY=s),t}async function Wc(e,t=!0){const r=t?Fn:On,a=Z.dirname(r);await Re.mkdir(a,{recursive:!0}),await Re.writeFile(r,JSON.stringify(e,null,2)),await Re.chmod(r,384)}function Hc(e=!0){return e?Fn:On}async function es(){const e=await gt(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function Jc(e){console.log(),console.log(jn.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const a=await hl({type:"password",name:"key",message:"OpenAI API Key",validate:s=>s&&!s.startsWith("sk-")?"OpenAI API key should start with sk-":!0});a.key&&(t.OPENAI_API_KEY=a.key);break}return t}async function Vc(e=!0){const t=await es();if(t.isValid)return t.secrets;const r=await Jc(t.missing),s={...await gt(),...r};await Wc(s,e);const o=Hc(e);return console.log(jn.green(`✓ Configuration saved to ${o}`)),(await es()).secrets}function ao(e=process.cwd()){let t=Z.resolve(e);const r=Z.parse(t).root;for(;t!==r;){const s=Z.join(t,".codeyam","config.json");if(K.existsSync(s))return t;t=Z.dirname(t)}const a=Z.join(r,".codeyam","config.json");return K.existsSync(a)?r:null}let so=ao();function fe(){return so}function Gc(e){so=e}function oo(e){const t={...e};for(const r in e)if(r.includes(".")){const a=r.replace(/\./g,"");t[a]=e[r]}return t}const qc={"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>`};oo(qc);const Kc={"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>`};oo(Kc);function qt(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 s=Array.isArray(e)?e:[],o=[];for(let i=0;i<t.length;i++){const c=t[i];c&&typeof c=="object"&&!Array.isArray(c)||Array.isArray(c)?o[i]=qt(s[i],c,r):o[i]=c}return o}const a={...e};for(const s in t)if(t[s]===null)a[s]=null;else if(Array.isArray(t[s])){const o=Array.isArray(e[s])?e[s]:[];a[s]=[];for(let i=0;i<t[s].length;i++){const c=t[s][i];typeof c=="object"&&c!==null?a[s][i]=qt(o[i],c,r):a[s][i]=c}}else typeof t[s]=="object"&&t[s]!==null?a[s]=qt(a[s]??{},t[s],r):a[s]=t[s];return a}catch(a){throw console.log("CodeYam: Error merging data",e,t),a}}async function Qc({projectId:e,commit:t,branch:r}){var c,d,h,u,m,p,f;let a;const s={commitId:t.id,branchId:r.id,active:!0},o=await _c({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){a=(c=o.sort((g,x)=>{var b,v,C,w;return(((v=(b=g.branch.metadata)==null?void 0:b.permanent)==null?void 0:v.order)??999)-(((w=(C=x.branch.metadata)==null?void 0:C.permanent)==null?void 0:w.order)??999)})[0])==null?void 0:c.branch,a&&((h=(d=r.metadata)==null?void 0:d.permanent)==null?void 0:h.order)!==void 0&&(((m=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:m.order)<=((f=(p=a.metadata)==null?void 0:p.permanent)==null?void 0:f.order)?a=r:s.active=!1);const y=o.filter(g=>g.active&&g.branch.id!==a.id||!g.active&&g.branch.id===a.id);y.length>0&&await Xa(y.map(g=>({...g,active:g.branchId===a.id})))}(o==null?void 0:o.find(y=>y.branchId===s.branchId))||await Xa([s])}function yt(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=fe();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return ie.join(e,".codeyam","db.sqlite3")}async function Le(){const e=await Vc();process.env.SQLITE_PATH=yt(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Ie(e){await Le();const t=await $c({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await eo({projectId:t.id,names:["_local"]}),a=r==null?void 0:r[0];if(!a)throw new Error(`Local development branch not found for project "${e}". Please run "codeyam init" to set up local analysis.`);return{project:t,branch:a}}async function Zc(e,t,r){await Le();const a=fe(),s=wc(`${e.slug}-local-${Date.now()}-${Math.random()}`),o=r.map(d=>{let h="";if(a)try{if(h=je(`git diff HEAD -- "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!h)try{const u=je(`cat "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const m=u.split(`
30
- `);h=`@@ -0,0 +1,${m.length} @@
31
- ${m.map(p=>`+${p}`).join(`
32
- `)}`}}catch{}}catch{}return{fileName:d,status:"modified",patch:h}}),i={sha:s,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${s}`,htmlUrl:`local://codeyam/${e.slug}/${s}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:o,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},c=await Uc({projectId:e.id,commits:[i]});if(!c||c.length===0)throw new Error("Failed to create fake commit");return await Qc({projectId:e.id,commit:c[0],branch:t}),c[0]}async function dn(){await Le();const e=await rt({excludeMetadata:!0});if(!e||e.length===0)return[];const t=e.filter(d=>{var h;return!((h=d.metadata)!=null&&h.isSuperseded)}),r=t.map(d=>d.sha),a=t.map(d=>{var h;return(h=d.metadata)==null?void 0:h.previousVersionWithAnalyses}).filter(d=>!!d),s=[...new Set([...r,...a])],o=await pt({entityShas:s,excludeMetadata:!0}),i=new Map;if(o)for(const d of o)i.has(d.entitySha)||i.set(d.entitySha,[]),i.get(d.entitySha).push(d);return t.map(d=>{var m;const h=i.get(d.sha)||[];if(h.length>0)return{...d,analyses:h};const u=(m=d.metadata)==null?void 0:m.previousVersionWithAnalyses;if(u){const p=i.get(u)||[];return{...d,analyses:p}}return{...d,analyses:[]}})}async function Xn(e,t){await Le();const r=await pt({entityShas:[e],limit:1});if(r&&r.length>0&&t){const a=await to({projectId:r[0].projectId,sha:e});if(a)for(const s of r)s.entity=a}return r||[]}async function na(e){if(await Le(),e.name&&e.projectId){const r=await pt({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const a=r.filter(o=>{const i=o.scenarios&&o.scenarios.length>0,c=!e.filePath||o.filePath===e.filePath;return i&&c});if(a.length>0)return a.sort((o,i)=>{const c=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),a[0];const s=r.filter(o=>o.scenarios&&o.scenarios.length>0);if(s.length>0)return s.sort((o,i)=>{const c=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),s[0]}}const t=await pt({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function io(e){await Le();const t=await pt({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function Dt(e){await Le();const t=await $e();if(!t)return null;const{project:r}=await Ie(t);return await to({projectId:r.id,sha:e})}async function lo(e){var a,s,o,i,c,d,h,u;await Le();const t=[],r=[];if((a=e.metadata)!=null&&a.importedExports&&e.metadata.importedExports.length>0){const m=e.metadata.importedExports;for(const p of m){if(!p.filePath||!p.name)continue;const f=p.resolvedFilePath??p.filePath,y=p.resolvedName??p.name;let g=await rt({projectId:e.projectId,filePaths:[f],names:[y]});if((!g||g.length===0)&&p.resolvedIsDefault&&(g=await rt({projectId:e.projectId,filePaths:[f],names:["default"]})),g&&g.length>0){const x=g[0],b=await pt({entityShas:[x.sha],limit:1});let v,C,w;if(b&&b.length>0&&b[0].scenarios){const N=b[0],S=N.scenarios||[],k=S.length,M=S.find(L=>{var F,_;return(_=(F=L.metadata)==null?void 0:F.screenshotPaths)==null?void 0:_[0]});M&&(v=(o=(s=M.metadata)==null?void 0:s.screenshotPaths)==null?void 0:o[0],C=M.name),w={status:((i=x.metadata)==null?void 0:i.previousVersionWithAnalyses)||N.entitySha!==x.sha?"out_of_date":"up_to_date",scenarioCount:k,timestamp:N.createdAt?new Date(N.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:C,analysisStatus:w})}}}if((c=e.metadata)!=null&&c.importedBy){const m=[];for(const p in e.metadata.importedBy)for(const f in e.metadata.importedBy[p]){const y=e.metadata.importedBy[p][f];y.shas&&m.push(...y.shas)}if(m.length>0){const p=await rt({projectId:e.projectId,shas:m});if(p)for(const f of p){const y=await pt({entityShas:[f.sha],limit:1});let g,x,b;if(y&&y.length>0&&y[0].scenarios){const v=y[0],C=v.scenarios||[],w=C.length,N=C.find(k=>{var M,j;return(j=(M=k.metadata)==null?void 0:M.screenshotPaths)==null?void 0:j[0]});N&&(g=(h=(d=N.metadata)==null?void 0:d.screenshotPaths)==null?void 0:h[0],x=N.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 $e(){try{const e=fe();if(!e)return null;const t=ie.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 Ot(){await Le();try{const e=await $e();if(!e)return null;const{project:t,branch:r}=await Ie(e),a=await Rn({projectId:t.id,branchId:r.id,limit:1,skipRelations:!0});return a&&a.length>0?a[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function er(){try{const e=fe();if(!e)return null;const t=ie.join(e,".codeyam","config.json");return JSON.parse(await pe.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function co(e){try{const t=fe();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=ie.join(t,e.filePath);return await pe.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function uo(e){try{const t=fe();if(!t||!e.filePath)return!1;const r=ie.join(t,e.filePath),s=(await pe.stat(r)).mtime.getTime(),o=e.updatedAt||e.createdAt;if(!o)return!1;const i=new Date(o).getTime();return s>i+1e3}catch{return!1}}async function ho(e){if(await Le(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await rt({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),a=await pt({entityShas:r}),s=new Map;if(a)for(const i of a)s.has(i.entitySha)||s.set(i.entitySha,[]),s.get(i.entitySha).push(i);for(const[i,c]of s.entries())c.sort((d,h)=>{const u=new Date(d.createdAt||0).getTime();return new Date(h.createdAt||0).getTime()-u});const o=t.map(i=>({...i,analyses:s.get(i.sha)||[]}));return o.sort((i,c)=>{var u,m;const d=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",h=((m=c.analyses[0])==null?void 0:m.createdAt)||c.createdAt||"";return new Date(h).getTime()-new Date(d).getTime()}),o}async function mo(e){try{const t=fe();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=ie.join(t,".codeyam","config.json"),a=await pe.readFile(r,"utf8"),s=JSON.parse(a),o={...s,...e},i=JSON.stringify(o,null,2);if(await pe.writeFile(r,i,"utf8"),s.projectSlug){const c={};e.universalMocks!==void 0&&(c.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(c.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(c.webapps=e.webapps),await Ln({projectSlug:s.projectSlug,metadataUpdate:c})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const Xc=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:dn,getAnalysesForEntity:Xn,getAnalysisForExactEntitySha:io,getCurrentCommit:Ot,getEntityBySha:Dt,getEntityCodeFromFilesystem:co,getEntityHistory:ho,getLatestAnalysisForEntity:na,getProjectConfig:er,getProjectSlug:$e,getRelatedEntities:lo,hasFileBeenModifiedSinceEntity:uo,requireBranchAndProject:Ie,updateProjectConfig:mo},Symbol.toStringTag,{value:"Module"})),po="secrets.json";function fo(e){return ie.join(e,".codeyam",po)}function go(){return ie.join(Rr.homedir(),".codeyam",po)}async function tr(e){let t={};try{const r=go(),a=await pe.readFile(r,"utf-8");t=JSON.parse(a)}catch{}try{const r=fo(e),a=await pe.readFile(r,"utf-8"),s=JSON.parse(a);t={...t,...s}}catch{}return t}async function ed(e,t,r=!0){const a=r?go():fo(e),s=ie.dirname(a);await pe.mkdir(s,{recursive:!0}),await pe.writeFile(a,JSON.stringify(t,null,2)+`
33
- `,"utf-8")}async function td(e){const t=await tr(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 nd=3;let Vt=0;async function yn(e){if(!e||e.length===0)return[];if(Vt>=nd)return console.warn(`[Loader] Circuit breaker open (${Vt} 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 a=!1;const s=setTimeout(()=>{a||(a=!0,Vt++,console.warn(`[Loader] Entity fetch timeout after ${t}ms for ${e.length} entities`),r([]))},t);rt({shas:e,excludeMetadata:!0}).then(o=>{a||(a=!0,clearTimeout(s),Vt=0,r(o||[]))}).catch(()=>{a||(a=!0,clearTimeout(s),Vt++,r([]))})})}async function rd({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:a=!1,silent:s=!1,extraArgs:o=[]}){return new Promise((i,c)=>{const d=e.endsWith("/")?e:`${e}/`,h=t.endsWith("/")?t:`${t}/`,u=["-a"];a||u.push("--delete","--force"),u.push(...o);for(const f of r)u.push(`--exclude=${f}`);u.push(d,h);const m=Date.now(),p=Gn("rsync",u);p.on("exit",f=>{if(f===0){if(!s){const y=((Date.now()-m)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${y}s]`)}i()}else c(new Error(`rsync failed with exit code ${f}`))}),p.on("error",f=>{s||console.log("Error occurred:",f),c(f)})})}const ad=qr(Gr);async function sd(e){return new Promise(t=>setTimeout(t,e))}function od(e){try{return process.kill(e,0),!0}catch{return!1}}async function yo(e){try{const{stdout:t}=await ad(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
34
- `).filter(s=>s.trim()).map(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s)),a=[...r];for(const s of r){const o=await yo(s);a.push(...o)}return a}catch{return[]}}function ts(e,t,r){try{process.kill(e,t)}catch(a){r==null||r(`Error sending ${t} to process ${e}: ${a}`)}}async function id(e,t,r){const a=await yo(e);for(const s of a.reverse())await ts(s,t,r);await ts(e,t,r)}async function nn(e,t=console.log,r=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let a=0;async function s(o,i){await id(e,o,t);for(let c=0;c<i;c++)if(await sd(1e3),a+=1e3,!await od(e))return t(`Process tree ${e} successfully killed with ${o} after ${a/1e3} seconds.`),!0;return t(`Process tree still running after ${o}...`),!1}if(await s("SIGINT",5)||await s("SIGTERM",5))return!0;for(let o=0;o<r;o++)if(await s("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${a/1e3} seconds.`),!1}function ld(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:kl(),createdAt:t}}fl.config({quiet:!0});var xo=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(xo||{});class cd extends gl{constructor(){super(...arguments),this.processes=new Map}register(t){const r=xl(),{process:a,type:s,name:o,metadata:i,parentId:c}=t,d={id:r,type:s,name:o,pid:a.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:c,children:[]};if(this.processes.set(r,{info:d,process:a}),c){const m=this.processes.get(c);m&&(m.info.children=m.info.children||[],m.info.children.push(r))}const h=(m,p)=>{this.handleProcessExit(r,m,p)},u=m=>{this.handleProcessError(r,m)};return a.on("exit",h),a.on("error",u),a.__cleanup=()=>{a.removeListener("exit",h),a.removeListener("error",u)},this.emit("processStarted",d),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const a=this.processes.get(t);if(!a)throw new Error(`Process not found: ${t}`);const{info:s,process:o}=a;if(s.state==="completed"||s.state==="failed"||s.state==="killed")return;if(r.shutdownChildren&&s.children&&s.children.length>0&&await Promise.all(s.children.map(c=>this.shutdown(c,r))),o.pid)try{await nn(o.pid,c=>console.log(`[Process ${t}] ${c}`))}catch(c){console.warn(`Error killing process ${t}:`,c)}await new Promise(c=>setTimeout(c,100)),s.state==="running"&&(s.state="killed",s.endedAt=Date.now());const i=o.__cleanup;i&&i()}async shutdownByType(t,r={}){const a=this.listByType(t);await Promise.all(a.map(s=>this.shutdown(s.id,r)))}async shutdownAll(t={}){const r=this.listAll();await Promise.all(r.map(a=>this.shutdown(a.id,t)))}cleanupCompleted(t={}){const{retentionMs:r=6e4}=t,a=Date.now();for(const[s,o]of this.processes.entries()){const{info:i}=o;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&a-i.endedAt>r){const c=o.process.__cleanup;c&&c(),this.processes.delete(s)}}}handleProcessExit(t,r,a){const s=this.processes.get(t);if(!s)return;const{info:o}=s;o.endedAt=Date.now(),o.exitCode=r,o.signal=a,r===0?o.state="completed":a?o.state="killed":o.state="failed",this.emit("processExited",o)}handleProcessError(t,r){const a=this.processes.get(t);if(!a)return;const{info:s}=a;s.endedAt=Date.now(),s.state="failed",s.metadata={...s.metadata,error:r.message},this.emit("processExited",s)}}let Sr=null;function dd(){return Sr||(Sr=new cd),Sr}const ud={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function hd({command:e,args:t,workingDir:r,outputOptions:a=ud,processName:s,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${s}`},c=Gn(e,t,{cwd:r,env:i});return dd().register({process:c,type:xo.Other,name:s,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const m=f=>{const y=ie.join(r,"log.txt");K.appendFile(y,f,g=>{g&&console.log("Error writing to log file:",g)})},p=(f,y="")=>{const g=new Date().toLocaleString();return f.split(`
35
- `).map(b=>b.trim()?`[${g}]${y} ${b}`:b).join(`
36
- `)};c.stdout.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=p(y);a.stdoutToConsole&&console.log(g),a.stdoutToFile&&m(g+`
37
- `),a.stdoutCallback&&a.stdoutCallback(y)}),c.stderr.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=p(y,"<STDERR>");a.stderrToConsole&&console.error(g),a.stderrToFile&&m(g+`
38
- `),a.stderrCallback&&a.stderrCallback(y)}),c.on("exit",function(f){u(f)})}),process:c}}function md(e){const t=[];return Object.keys(e).forEach(r=>{const a=e[r];a!==void 0&&(typeof a=="boolean"?a&&t.push(`--${r}`):a!==null&&t.push(`--${r}`,String(a)))}),t}function pd({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:a}){const s=Object.entries(t).map(([i,c])=>`${i}=${c}`).join(`
39
- `);K.writeFileSync(`${e}/.env`,s);const o=md(r);return hd({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:a,processName:"analyzer",env:t})}const fd="/tmp/codeyam/local-dev";function bo(e){return Z.join(fd,e)}function vo(e){return Z.join(bo(e),"codeyam")}function it(e){return Z.join(bo(e),"project")}function nr(e){return Z.join(vo(e),"log.txt")}const gd=[".sync-metadata.json","__codeyamMocks__"];async function yd(e,t={}){const{port:r,silent:a=!0}=t,s=it(e);if(r)try{je(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:a?"ignore":"inherit"})}catch{}try{je(`lsof +D "${s}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:a?"ignore":"inherit"})}catch{}await new Promise(o=>setTimeout(o,500))}async function xd(e,t={}){const{killProcesses:r=!0,port:a,silent:s=!0}=t,o=it(e),i=[],c=[];if(!K.existsSync(o))return{removed:i,errors:c};r&&await yd(e,{port:a,silent:s});for(const d of gd){const h=Z.join(o,d);if(K.existsSync(h))try{(await Re.stat(h)).isDirectory()?await Re.rm(h,{recursive:!0,force:!0}):await Re.unlink(h),i.push(d)}catch(u){c.push(`${d}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:c}}const bd=Z.dirname(qn(import.meta.url));function vd(e){let t=e;for(;t!==Z.dirname(t);){const r=Z.join(t,"package.json");if(K.existsSync(r))try{if(JSON.parse(K.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=Z.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function rr(){const e=vd(bd);return Z.join(e,"analyzer-template")}function Yt(e){return vo(e)}function wd(){const e=rr();return K.existsSync(Z.join(e,".finalized"))}async function ns(e){const t=rr(),r=Yt(e);if(!K.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await Re.mkdir(Z.dirname(r),{recursive:!0}),await rd({sourcePath:t,destinationPath:r,silent:!0})}function zt(e,t,r,a){const s=Yt(e);if(!K.existsSync(s))throw new Error(`Analyzer not found at ${s}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const o=void 0;return pd({absoluteCodeyamRootPath:s,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function Cd(e){const t=rr(),r=Yt(e),a=Z.join(t,".build-info.json"),s=Z.join(r,".build-info.json");if(!K.existsSync(a))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!K.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!K.existsSync(s))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(K.readFileSync(a,"utf8")),i=JSON.parse(K.readFileSync(s,"utf8"));return o.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${o.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(o){return{isFresh:!1,reason:`Error reading build markers: ${o.message}`}}}async function un(e,t){const r=Yt(e);if(!K.existsSync(r)){t.update("Creating analyzer..."),await ns(e);return}const a=Cd(e);a.isFresh||(t.update(`Updating analyzer (${a.reason})...`),await ns(e))}async function ra(e){await xd(e,{killProcesses:!1})}const Nd=Z.dirname(qn(import.meta.url));function wo(){let e=Nd;for(;e!==Z.dirname(e);){const t=Z.join(e,"package.json");if(K.existsSync(t))try{if(JSON.parse(K.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=Z.dirname(e)}return null}function Zt(e){if(!K.existsSync(e))return null;try{return JSON.parse(K.readFileSync(e,"utf8"))}catch{return null}}function Sd(){const e=wo();if(e){const t=[Z.join(e,"src/webserver/build-info.json"),Z.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const a=Zt(r);if(a!=null&&a.semanticVersion)return a.semanticVersion}}return"unknown"}const aa=Sd();function Co(e){const t=wo();let r=null;if(t){const d=[Z.join(t,"src/webserver/build-info.json"),Z.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const h of d)if(r=Zt(h),r)break}const a=rr(),s=Z.join(a,".build-info.json"),o=Zt(s);let i=null;if(e){const d=Yt(e),h=Z.join(d,".build-info.json");i=Zt(h)}let c=!1;return o&&i?c=o.buildTime>i.buildTime:o&&!i&&e&&(c=!0),{cliVersion:aa,webserverVersion:r,templateVersion:o,cachedAnalyzerVersion:i,isCacheStale:c}}function ar(e){const t=Yt(e),r=Z.join(t,".build-info.json"),a=Zt(r);return(a==null?void 0:a.version)??null}function No(){const e=fe();return e?Z.join(e,".codeyam","server.json"):null}function So(){const e=No();if(!e||!K.existsSync(e))return null;try{const t=K.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function Ed(){const e=No();if(e)try{K.unlinkSync(e)}catch{}}const Ad="/assets/globals-CKT08Djd.css";function rs({text:e,subtext:t,linkText:r,linkTo:a}){const[s,o]=P(!1);return s?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:l("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),l("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(se,{to:a,className:"shrink-0 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 transition-colors",children:r})]}),n("button",{type:"button",onClick:()=>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 kd(){return n("div",{className:"px-6 sm:px-12 pb-8 mt-auto pt-8",children:l("div",{className:"border-t border-cygray-30 pt-6 flex flex-wrap justify-between items-center gap-4",children:[n("span",{className:"font-mono text-sm font-semibold tracking-widest text-cyblack-100",children:"CODEYAM"}),l("div",{className:"flex items-center gap-4 font-mono text-xs uppercase tracking-widest",children:[n("a",{href:"https://codeyam.com/blog",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/codeyam",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Join Discord"})]})]})})}function Pd({serverVersion:e}){const[t,r]=P("stale"),[a,s]=P(null),o=async()=>{r("restarting"),s(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let c=0;const d=30,h=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}c++,c<d?setTimeout(()=>void u(),h):(s("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void u(),500)}catch(i){s(i instanceof Error?i.message:"Failed to restart server"),r("stale")}};return n("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:n("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-amber-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),l("div",{className:"flex-1",children:[t==="stale"&&l(he,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Dashboard server is out of date"}),l("p",{className:"text-xs text-amber-700 mt-0.5",children:["Server version: ",e,". A newer version of CodeYam CLI is installed. Restart the server to get the latest features."]}),a&&n("p",{className:"text-xs text-red-600 mt-1",children:a})]}),t==="restarting"&&l(he,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Restarting server..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Please wait while the server restarts."})]}),t==="reconnecting"&&l(he,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Reconnecting..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Waiting for the server to come back online."})]})]}),t==="stale"&&n("button",{type:"button",onClick:()=>void o(),className:"shrink-0 px-4 py-2 bg-amber-600 text-white text-sm font-medium rounded hover:bg-amber-700 transition-colors cursor-pointer",children:"Restart Server"}),(t==="restarting"||t==="reconnecting")&&l("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 text-amber-700 text-sm",children:[l("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t==="restarting"?"Stopping...":"Reconnecting..."]})]})})})}function Yn(e){return Z.join(e,".codeyam","queue.json")}function Kt(e){const t=Yn(e);if(!K.existsSync(t))return{paused:!1,jobs:[]};try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function _d(e,t){const r=Yn(e),a=Z.dirname(r);K.existsSync(a)||K.mkdirSync(a,{recursive:!0});try{K.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(s){throw console.error("Failed to save queue state:",s),s}}async function Md(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await Td(e,t,r);else if(e.type==="baseline")await jd(e,t,r);else if(e.type==="recapture")await Id(e,t,r);else if(e.type==="capture-only")await $d(e,t,r);else if(e.type==="debug-setup")await Rd(e,t,r);else if(e.type==="interactive-start")await Dd(e,t,r);else if(e.type==="interactive-stop")await Ld(e,t,r);else throw new Error(`Unknown job type: ${e.type}`);console.log(`[Queue] Job ${e.id} completed successfully`)}catch(a){throw console.error(`[Queue] Job ${e.id} failed:`,a),a}}async function Td(e,t,r){var g,x,b,v;const{projectSlug:a,commitSha:s,entityShas:o}=e;if(!s)throw new Error("Analysis job missing commitSha");const i=o||[],{project:c}=await Ie(a);await ra(a),await un(a,{update:C=>console.log(`[Queue] ${C}`)});const d=ar(a),h={...await gt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:s,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:yt(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...d?{ANALYZER_VERSION:d}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},u=(x=(g=c.metadata)==null?void 0:g.webapps)==null?void 0:x[0];if(!u)throw new Error("No webapps found in project metadata");const m=e.onlyDataStructure,p={packageManager:((b=c.metadata)==null?void 0:b.packageManager)||"npm",absoluteProjectRootPath:it(a),port:0,noServer:!0,framework:u.framework,...m?{}:{orchestrateCapture:"local-sequential"}},f=zt(a,h,p),y=C=>{try{return process.kill(C,0),!0}catch{return!1}};await ut({commitSha:s,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((v=e.filePaths)==null?void 0:v.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:f.process.pid}}),r==null||r.notifyChange("commit");try{try{const C=new Promise((w,N)=>setTimeout(()=>N(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,C]),await ut({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await ut({commitSha:s,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(w=>setTimeout(w,2e3))}finally{if(f.process.pid)try{y(f.process.pid)&&await nn(f.process.pid,()=>{})}catch{}}}catch(C){if(console.error(`[Queue] Analysis job ${e.id} failed:`,C),f.process.pid&&y(f.process.pid))try{await nn(f.process.pid,()=>{})}catch{}try{await ut({commitSha:s,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(w){console.error("[Queue] Failed to update commit metadata after job failure:",w)}throw C}}async function jd(e,t,r){var p,f,y;const{projectSlug:a,commitSha:s}=e;if(!s)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${a}`);const{project:o}=await Ie(a);await ra(a),await un(a,{update:g=>console.log(`[Queue] ${g}`)});const i=ar(a),c={...await gt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:s,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:yt(),...i?{ANALYZER_VERSION:i}:{}},d=(f=(p=o.metadata)==null?void 0:p.webapps)==null?void 0:f[0];if(!d)throw new Error("No webapps found in project metadata");const h={packageManager:((y=o.metadata)==null?void 0:y.packageManager)||"npm",absoluteProjectRootPath:it(a),port:0,noServer:!0,framework:d.framework,orchestrateCapture:"local-sequential"},u=zt(a,c,h),m=g=>{try{return process.kill(g,0),!0}catch{return!1}};await ut({commitSha:s,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 ut({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${a}`),await new Promise(x=>setTimeout(x,2e3))}finally{if(u.process.pid)try{m(u.process.pid)&&await nn(u.process.pid,()=>{})}catch{}}}async function Id(e,t,r){var f,y,g,x;const{projectSlug:a,analysisId:s,scenarioId:o,defaultWidth:i}=e;if(!s)throw new Error("Recapture job missing analysisId");const c=await ot({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${s} not found`);if(i){const{getDatabase:b}=await import("./index-8Fv-lH1-.js"),v=b(),C=await v.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let w={};C!=null&&C.metadata&&(typeof C.metadata=="string"?w=JSON.parse(C.metadata):w=C.metadata),w.defaultWidth=i,await v.updateTable("entities").set({metadata:JSON.stringify(w)}).where("sha","=",c.entitySha).execute()}await Ft(s,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:d}=await Ie(a);await un(a,{update:b=>console.log(`[Queue] ${b}`)});const h=ar(a),u={...await gt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:yt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,...o?{SCENARIO_IDS:o}:{},...h?{ANALYZER_VERSION:h}:{}},m={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:it(a),port:void 0,noServer:!0,framework:((x=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??cn.Next,orchestrateCapture:"local-sequential"},p=zt(a,u,m);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function $d(e,t,r){var f,y,g,x;const{projectSlug:a,analysisId:s,scenarioId:o,defaultWidth:i}=e;if(!s)throw new Error("Capture-only job missing analysisId");const c=await ot({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${s} not found`);if(i){const{getDatabase:b}=await import("./index-8Fv-lH1-.js"),v=b(),C=await v.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let w={};C!=null&&C.metadata&&(typeof C.metadata=="string"?w=JSON.parse(C.metadata):w=C.metadata),w.defaultWidth=i,await v.updateTable("entities").set({metadata:JSON.stringify(w)}).where("sha","=",c.entitySha).execute()}await Ft(s,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:d}=await Ie(a);await un(a,{update:b=>console.log(`[Queue] ${b}`)});const h=ar(a);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await gt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:yt(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:s,...o?{SCENARIO_IDS:o}:{},...h?{ANALYZER_VERSION:h}:{}},m={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:it(a),port:void 0,noServer:!0,fast:!0,framework:((x=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??cn.Next,orchestrateCapture:"local-sequential"},p=zt(a,u,m);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function Rd(e,t,r){var p,f,y,g;const{projectSlug:a,analysisId:s,scenarioId:o}=e;if(!s)throw new Error("Debug setup job missing analysisId");const i=await ot({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${s} not found`);const{project:c}=await Ie(a);await ra(a),await un(a,{update:x=>console.log(`[Queue] ${x}`)});const d={...await gt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:yt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,PREP_ONLY:"true"};o&&(d.SCENARIO_IDS=o);const h={packageManager:((p=c.metadata)==null?void 0:p.packageManager)||"npm",absoluteProjectRootPath:it(a),port:void 0,noServer:!1,framework:((g=(y=(f=c.metadata)==null?void 0:f.webapps)==null?void 0:y[0])==null?void 0:g.framework)||cn.Next},m=await zt(a,d,h).promise;if(m!==0)throw new Error(`Prep process exited with code ${m}`)}async function Dd(e,t,r){var m,p,f,y;const{projectSlug:a,analysisId:s,scenarioId:o}=e;if(!s)throw new Error("Interactive start job missing analysisId");const i=await ot({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${s} not found`);const{project:c}=await Ie(a),d={...await gt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:yt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,INTERACTIVE_MODE:"true"};o&&(d.SCENARIO_IDS=o);const h={packageManager:((m=c.metadata)==null?void 0:m.packageManager)||"npm",absoluteProjectRootPath:it(a),port:void 0,noServer:!1,framework:((y=(f=(p=c.metadata)==null?void 0:p.webapps)==null?void 0:f[0])==null?void 0:y.framework)||cn.Next};await Ft(s,g=>{g.readyToBeCaptured=!0});const u=zt(a,d,h);await ro(s,g=>{g.interactiveMode={pid:u.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${s}, PID: ${u.process.pid}`)}async function Ld(e,t,r){var d;const{projectSlug:a,analysisId:s}=e;if(!s)throw new Error("Interactive stop job missing analysisId");const o=await ot({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!o)throw new Error(`Analysis ${s} not found`);const i=(d=o.metadata)==null?void 0:d.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${s}`);return}const c=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${s}, killing PID: ${c}`);try{try{process.kill(c,0)}catch{console.log(`[Queue] Process ${c} already exited`);return}await nn(c,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${c}`)}catch(h){throw console.error(`[Queue] Failed to kill process ${c}:`,h),h}finally{await ro(s,h=>{h.interactiveMode=null})}}class Fd{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=Kt(this.projectRoot),this.state.jobs.length>0?(this.state.currentlyExecuting&&(console.log(`[Queue] Clearing stale currentlyExecuting job from previous session: ${this.state.currentlyExecuting.id}`),this.state.currentlyExecuting=void 0),this.state.paused=!0,this.save(),console.log(`[Queue] Found ${this.state.jobs.length} queued jobs from previous session (paused)`)):this.state.paused=!1}enqueue(t){const r=t.commitSha||zs(),a={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(a),this.save(),console.log(`[Queue] Enqueued job ${r} (${a.type})`);const s=new Promise((o,i)=>{this.completionCallbacks.set(r,c=>{c?i(c):o()})});return this.state.paused||this.processNext().catch(o=>{console.error("[Queue] ERROR in processNext():",o)}),{jobId:r,completion:s}}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(s=>s.id!==t);const a=this.state.jobs.length<r;if(a){console.log(`[Queue] Removed job ${t}`),this.save();const s=this.completionCallbacks.get(t);s&&(setImmediate(()=>s(new Error("Job cancelled by user"))),this.completionCallbacks.delete(t))}else console.log(`[Queue] Job ${t} not found in queue`);return a}clearQueue(){const t=this.state.jobs.length;return t===0?0:(this.state.jobs.forEach(r=>{const a=this.completionCallbacks.get(r.id);a&&(setImmediate(()=>a(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 a=this.state.jobs.findIndex(i=>i.id===t);if(a===-1)return console.log(`[Queue] Job ${t} not found in queue`),!1;const s=r==="up"?a-1:a+1;if(s<0||s>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const o=this.state.jobs[a];return this.state.jobs[a]=this.state.jobs[s],this.state.jobs[s]=o,console.log(`[Queue] Moved job ${t} ${r} (position ${a} -> ${s})`),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 Md(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 a=this.completionCallbacks.get(t.id);a&&(a(r),this.completionCallbacks.delete(t.id))}finally{this.processing=!1,!this.state.paused&&this.state.jobs.length>0&&setImmediate(()=>void this.processNext())}}save(){_d(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class Od{constructor(t,r,a=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=a}start(){const t=Yn(this.projectRoot);if(!K.existsSync(t)){console.log("[QueueFileWatcher] Queue file does not exist yet, will start watching when created"),this.watchDirectory();return}this.watchFile(t)}watchDirectory(){const t=Yn(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=K.watch(r,(a,s)=>{s==="queue.json"&&(this.stop(),this.watchFile(t),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(a){console.error("[QueueFileWatcher] Failed to watch directory:",a)}}watchFile(t){try{this.watcher=K.watch(t,r=>{r==="change"&&this.notifyChange()}),console.log("[QueueFileWatcher] Watching queue.json for changes")}catch(r){console.error("[QueueFileWatcher] Failed to watch queue file:",r)}}notifyChange(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.onChange(),this.debounceTimer=null},this.debounceMs)}stop(){this.watcher&&(this.watcher.close(),this.watcher=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}class Yd{constructor(t,r,a){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=a,this.cachedState=Kt(r)}start(){this.cachedState=Kt(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 Od(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,a;const s=new Promise((i,c)=>{r=i,a=c}),o=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),a(i)}),{jobId:o,completion:s}}async enqueueRemote(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...t})});if(!r.ok){const a=await r.text();throw new Error(`Failed to enqueue: ${r.status} ${a}`)}return r.json()}resume(){console.log("[ProxyQueue] Sending resume command to background server"),this.sendAction("resume").catch(t=>{console.error("[ProxyQueue] Failed to resume:",t)})}pause(){console.log("[ProxyQueue] Sending pause command to background server"),this.sendAction("pause").catch(t=>{console.error("[ProxyQueue] Failed to pause:",t)})}async sendAction(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t})});if(!r.ok){const a=await r.text();throw new Error(`Failed to ${t}: ${r.status} ${a}`)}this.refreshState()}getState(){return this.cachedState=Kt(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=Kt(this.projectRoot),this.onStateChange&&this.onStateChange()}async isServerAlive(){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),a=await fetch(`${this.serverInfo.url}/api/health`,{signal:t.signal});return clearTimeout(r),a.ok}catch{return!1}}getServerInfo(){return{...this.serverInfo}}stop(){this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null)}}function zd(e){const t=Z.join(e,".codeyam","server.json");if(!K.existsSync(t))return null;try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function Bd(e){try{return process.kill(e,0),!0}catch{return!1}}async function Ud(e){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),a=await fetch(`${e}/api/health`,{signal:t.signal});return clearTimeout(r),a.ok}catch{return!1}}async function Wd(e){const t=zd(e);return!t||!Bd(t.pid)||!await Ud(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class Hd extends yl{constructor(){super();fn(this,"watcher",null);fn(this,"dbPath",null);fn(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=yt();const{default:r}=await import("chokidar"),a=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=r.watch(a,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",s=>{const o=Date.now(),i=new Date(o).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${s}`),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",s=>{console.error("Database watcher error:",s),this.emit("error",s)}),this.isWatching=!0}catch(r){console.error("Failed to start database watcher:",r),this.emit("error",r)}}notifyChange(r="unknown"){const a=Date.now(),s=new Date(a).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${r}`),console.log(`[dbNotifier] Timestamp: ${s} (${a})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:r,timestamp:a})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const Dr=new Hd;let St=null,Qt=null;async function Jd(){if(!St){if(Qt){await Qt;return}Qt=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||ao()||process.cwd();Gc(e),console.log(`[GlobalQueue] Project root: ${e}`);const t=await Wd(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new Yd(t,e,()=>{Dr.notifyChange("unknown")});await r.start(),St=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new Fd(e,Dr);await r.start(),St=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Qt}}async function lt(){return St||await Jd(),St}function Vd(){return St||(Qt&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const Gd=()=>[{rel:"stylesheet",href:Ad},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}],qd={currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[],isServerOutOfDate:!1,serverVersion:"unknown",labs:null,simulationsEnabled:!1,isSimulationsReady:!1};async function Kd({request:e,context:t}){var r,a,s,o,i,c,d,h,u,m;try{const p=e.signal,f=()=>{if(p.aborted)throw new Response(null,{status:499})};f();const y=fe()||process.cwd(),[g,x]=await Promise.all([$e(),tr(y)]);if(!g)throw new Error("Project slug not found");const{project:b,branch:v}=await Ie(g);f();const C=await Rn({projectId:b.id,branchId:v.id,limit:20,skipRelations:!0});f();const w=C.length>0?C[0]:null,N=t.analysisQueue||Vd(),S=N==null?void 0:N.getState();f();const k=await Promise.all(((S==null?void 0:S.jobs)||[]).map(async $=>{var D;const I=await yn($.entityShas||[]);return I.length===0&&((D=$.entityShas)!=null&&D.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",$.id),{...$,entities:I}}));let M=null;if(S!=null&&S.currentlyExecuting){const $=S.currentlyExecuting,I=await yn($.entityShas||[]);I.length===0&&((r=$.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",$.id),M={...$,entities:I}}const j=M?k.filter($=>$.id!==M.id):k;let L=((s=(a=w==null?void 0:w.metadata)==null?void 0:a.currentRun)==null?void 0:s.currentEntityShas)||[];if(L.length===0){const $=((o=w==null?void 0:w.metadata)==null?void 0:o.historicalRuns)||[];if($.length>0){const D=[...$].sort((q,te)=>{const ce=q.archivedAt||q.createdAt||"";return(te.archivedAt||te.createdAt||"").localeCompare(ce)})[0];if(D){const q=D.analysisCompletedAt||D.createdAt;if(q){const te=new Date(q).getTime(),me=Date.now()-1440*60*1e3;te>me&&(L=D.currentEntityShas||[])}}}}const F=await yn(L),_=[];x.ANTHROPIC_API_KEY&&_.push("ANTHROPIC_API_KEY"),x.GROQ_API_KEY&&_.push("GROQ_API_KEY"),x.OPENAI_API_KEY&&_.push("OPENAI_API_KEY"),x.OPENROUTER_API_KEY&&_.push("OPENROUTER_API_KEY"),f();const E=[];for(const $ of C){const I=((i=$.metadata)==null?void 0:i.historicalRuns)||[];for(const D of I)E.push(D)}E.sort(($,I)=>{const D=$.archivedAt||$.analysisCompletedAt||$.createdAt||"";return(I.archivedAt||I.analysisCompletedAt||I.createdAt||"").localeCompare(D)});const T=new Set(((c=M==null?void 0:M.entities)==null?void 0:c.map($=>$.sha))||[]),G=E.filter($=>!($.currentEntityShas||[]).some(D=>T.has(D))).slice(0,3),V=new Set;for(const $ of G)for(const I of $.currentEntityShas||[])V.add(I);const U=await yn(Array.from(V)),z=new Map;for(const $ of U)z.set($.sha,$);const Y=G.map($=>({...$,entities:($.currentEntityShas||[]).map(I=>z.get(I)).filter(I=>I!=null)})),R=So(),A=(R==null?void 0:R.cliVersion)??"unknown",H=A!=="unknown"&&A!==aa,W=((h=(d=b.metadata)==null?void 0:d.labs)==null?void 0:h.simulations)??!1,J=W?wd():!1,ae={currentRun:(u=w==null?void 0:w.metadata)==null?void 0:u.currentRun,projectSlug:g,currentEntities:F,availableAPIKeys:_,queuedJobCount:j.length,queueJobs:j,currentlyExecuting:M,historicalRuns:Y,isServerOutOfDate:H,serverVersion:A,labs:((m=b.metadata)==null?void 0:m.labs)??null,simulationsEnabled:W,isSimulationsReady:J};return B(ae)}catch(p){return p instanceof Response&&p.status===499||console.error("Failed to load root data:",p),B(qd)}}function Qd(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:a,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:c,isServerOutOfDate:d,serverVersion:h,labs:u,simulationsEnabled:m,isSimulationsReady:p}=Be(),{toasts:f,closeToast:y}=Zr(),g=at(),x=Ne(g),b=Hn();ee(()=>{x.current=g},[g]);const v=b.pathname.startsWith("/entity/")&&b.pathname.includes("/edit/")||b.pathname.startsWith("/dev/"),C=b.pathname.includes("/fullscreen");return ee(()=>{const w=new EventSource("/api/events");let N=null,S=0;const k=2e3;return w.addEventListener("message",M=>{const j=JSON.parse(M.data);if(j.type==="queue")x.current.revalidate(),S=Date.now();else if(j.type==="db-change"||j.type==="unknown"){const L=Date.now(),F=L-S;F<k?(N&&clearTimeout(N),N=setTimeout(()=>{x.current.revalidate(),S=Date.now(),N=null},k-F)):(x.current.revalidate(),S=L)}}),w.addEventListener("error",M=>{console.error("SSE connection error:",M)}),()=>{N&&clearTimeout(N),w.close()}},[]),l(he,{children:[l("div",{className:`min-h-screen ${v?"":"grid"} bg-cygray-10`,style:v?void 0:{gridTemplateColumns:"65px minmax(0, 1fr)"},children:[!v&&n(Fl,{labs:u}),l("div",{className:"max-h-screen overflow-auto bg-cygray-10 flex flex-col min-h-screen",children:[d&&n(Pd,{serverVersion:h}),m&&a.length===0&&n(rs,{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&&!p&&n(rs,{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(Ei,{})}),n(kd,{})]})]}),n(zl,{toasts:f,onClose:y}),!C&&m&&n(Bl,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:c})]})}const Zd=De(function(){return l("html",{lang:"en",children:[l("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(wi,{}),n(Ci,{})]}),l("body",{children:[n(Ol,{children:n(Dl,{children:n(Qd,{})})}),n(Ni,{}),n(Si,{})]})]})}),Xd=Object.freeze(Object.defineProperty({__proto__:null,default:Zd,links:Gd,loader:Kd},Symbol.toStringTag,{value:"Module"}));function as(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function hn({analysisId:e,scenarioId:t,scenarioName:r,projectSlug:a,enabled:s=!0,refreshTrigger:o=0}){const i=Ae(),[c,d]=P(null),[h,u]=P(!1),[m,p]=P(!1),[f,y]=P(!1),g=Ne(!1),x=Ne(null),b=Ne(null),[v,C]=P(0),[w,N]=P(0),S=Ne(null),k=Ne(!1),{interactiveUrl:M,resetLogs:j}=ft(a,s),L=Ne(t),F=Ne(o);ee(()=>{F.current!==o&&(F.current=o,c&&(console.log("[useInteractiveMode] Manual refresh triggered"),p(!0),y(!1),C(0),N(E=>E+1),k.current=!1,S.current&&(clearTimeout(S.current),S.current=null)))},[o,c]),ee(()=>{if(L.current!==t&&(L.current=t,x.current&&b.current&&r)){const E=as(b.current),T=as(r),O=x.current.replace(E,T);d(O),p(!0),y(!1),C(0),N(G=>G+1),k.current=!1,S.current&&(clearTimeout(S.current),S.current=null);return}},[t,r]),ee(()=>{if(M){const E=M+"?width=600px";x.current=E,r&&(b.current=r),d(E),u(!1),p(!0)}},[M]),ee(()=>{const E=T=>{T.data.type==="codeyam-resize"&&(k.current||(k.current=!0,S.current&&(clearTimeout(S.current),S.current=null),C(0),y(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{p(!1)})})))};return window.addEventListener("message",E),()=>window.removeEventListener("message",E)},[]);const _=()=>{k.current=!1,S.current&&clearTimeout(S.current);const E=500*Math.pow(2,v);S.current=setTimeout(()=>{k.current||(v<2?(C(T=>T+1),N(T=>T+1),p(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),y(!0),p(!1)))},E)};return ee(()=>{s&&!g.current&&t&&e&&(g.current=!0,u(!0),y(!1),d(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(T){console.error("[useInteractiveMode] Failed to clear log file:",T)}j(),i.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[s,t,e,j,a]),ee(()=>{const E=e,T=()=>{if(g.current&&E){const G=new URLSearchParams({action:"stop",analysisId:E});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const V=navigator.sendBeacon("/api/interactive-mode",G);console.log("[useInteractiveMode] sendBeacon result:",V),V||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:G,keepalive:!0}).catch(U=>console.error("Failed to stop interactive mode:",U)))}},O=()=>{T()};return window.addEventListener("beforeunload",O),()=>{window.removeEventListener("beforeunload",O),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:g.current,analysisId:E}),T()}},[e]),{interactiveServerUrl:c,isStarting:h,isLoading:m,showIframe:f,iframeKey:w,onIframeLoad:_}}const xn=10,eu=1024;function Eo({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:a,onHoverChange:s,hideLabel:o=!1,lightMode:i=!1}){const[c,d]=P(null),h=Ne(null),u=re(()=>[...a].sort((v,C)=>v.width-C.width),[a]),{fittingPresets:m,overflowPresets:p}=re(()=>{const v=[],C=[];for(const w of u)w.width<=eu?v.push(w):C.push(w);return C.sort((w,N)=>N.width-w.width),{fittingPresets:v,overflowPresets:C}},[u]),f=oe(v=>{if(!h.current)return null;const C=h.current.getBoundingClientRect(),w=v-C.left,N=C.width,S=N/2,M=(m.length>0?m[m.length-1].width:0)/2,j=S-M,L=S+M,F=p.length>0?(p.length-1)*xn:0;if(p.length>0){if(w<j){if(w<=F){const E=Math.min(Math.floor(w/xn),p.length-1);return p[E]}return p[p.length-1]}if(w>L){const E=N-w;if(E<=F){const T=Math.min(Math.floor(E/xn),p.length-1);return p[T]}return p[p.length-1]}}const _=Math.abs(w-S);for(let E=m.length-1;E>=0;E--){const T=m[E],O=m[E-1],G=T.width/2,V=O?O.width/2:0;if(_<=G&&_>=V)return T}return m[0]||p[p.length-1]||null},[m,p]),y=oe(v=>{const C=f(v.clientX);d(C),s==null||s(C)},[f,s]),g=oe(()=>{d(null),s==null||s(null)},[s]),x=oe(v=>{const C=f(v.clientX);C&&r(C)},[f,r]),b=c||{name:t,width:e};return l("div",{ref:h,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:y,onMouseLeave:g,onClick:x,children:[c&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${c.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:m.map(v=>{const C=v.width===e,w=(c==null?void 0:c.name)===v.name,N=v.width/2;return l("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${N}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${C||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% + ${N}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${C||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:p.map((v,C)=>{const w=C*xn,N=v.width===e,S=(c==null?void 0:c.name)===v.name;return l("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${w}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${N||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 ${N||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:l("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${c?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[b.name," - ",b.width,"px"]})})]})}function Ao({width:e,height:t,onSave:r,onCancel:a}){const[s,o]=P(""),[i,c]=P(""),d=()=>{const u=s.trim();if(!u){c("Please enter a name for this custom size");return}r(u)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:l("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[l("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:a,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),l("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),l("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),l("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:s,onChange:u=>{o(u.target.value),c("")},onKeyDown:u=>{u.key==="Enter"&&s.trim()&&d(),u.key==="Escape"&&a()},placeholder:"e.g., iPhone 15 Pro",className:`w-full px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] ${i?"border-red-300":"border-gray-300"}`,autoFocus:!0}),i&&n("p",{className:"mt-1 text-sm text-red-600",children:i})]}),l("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:a,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors cursor-pointer",children:"Cancel"}),n("button",{onClick:d,disabled:!s.trim(),className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors cursor-pointer disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function ko(e){const[t,r]=P([]),a=e?`codeyam-custom-sizes-${e}`:null;ee(()=>{if(!a||typeof window>"u"){r([]);return}try{const c=localStorage.getItem(a);if(c){const d=JSON.parse(c);Array.isArray(d)&&r(d)}}catch(c){console.error("[useCustomSizes] Failed to load custom sizes:",c),r([])}},[a]);const s=oe(c=>{if(!(!a||typeof window>"u"))try{localStorage.setItem(a,JSON.stringify(c))}catch(d){console.error("[useCustomSizes] Failed to save custom sizes:",d)}},[a]),o=oe((c,d,h)=>{r(u=>{const m=u.findIndex(y=>y.name===c),p={name:c,width:d,height:h};let f;return m>=0?(f=[...u],f[m]=p):f=[...u,p],s(f),f})},[s]),i=oe(c=>{r(d=>{const h=d.filter(u=>u.name!==c);return s(h),h})},[s]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}function zn(){return l("div",{className:"spinner-container",children:[n("span",{className:"loader"}),n("style",{children:`
40
- .loader {
41
- width: 48px;
42
- height: 48px;
43
- border: 3px solid rgba(0, 92, 117, 0.2);
44
- border-radius: 50%;
45
- display: inline-block;
46
- position: relative;
47
- box-sizing: border-box;
48
- animation: rotation 1s linear infinite;
49
- }
50
- .loader::after {
51
- content: '';
52
- box-sizing: border-box;
53
- position: absolute;
54
- left: 50%;
55
- top: 50%;
56
- transform: translate(-50%, -50%);
57
- width: 56px;
58
- height: 56px;
59
- border-radius: 50%;
60
- border: 3px solid;
61
- border-color: #005c75 transparent;
62
- }
63
-
64
- @keyframes rotation {
65
- 0% {
66
- transform: rotate(0deg);
67
- }
68
- 100% {
69
- transform: rotate(360deg);
70
- }
71
- }
72
- `})]})}const ss=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],tu=80;function Bn(){const[e,t]=P(0);return ee(()=>{const r=setInterval(()=>{t(a=>(a+1)%ss.length)},tu);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:ss[e]})}async function nu({params:e}){var c;const{sha:t,scenarioId:r}=e;if(!t||!r)throw B("Invalid parameters",{status:400});const a=await Dt(t);if(!a)throw B("Entity not found",{status:404});const s=await na(a),o=((c=s==null?void 0:s.scenarios)==null?void 0:c.find(d=>d.id===r))||null;if(!o)throw B("Scenario not found",{status:404});const i=await $e();return B({entity:a,scenario:o,analysis:s,projectSlug:i})}const Er=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],ru=De(function(){const{entity:t,scenario:r,analysis:a,projectSlug:s}=Be(),o=Mt(),[i]=sn(),[c,d]=P(null),[h,u]=P(1440),[m,p]=P({name:"Desktop",width:1440,height:900}),[f,y]=P(!1),[g,x]=P(null),{customSizes:b,addCustomSize:v}=ko(s),C=re(()=>[...Er,...b],[b]),{interactiveServerUrl:w,isStarting:N,isLoading:S,showIframe:k,iframeKey:M,onIframeLoad:j}=hn({analysisId:a==null?void 0:a.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:s,enabled:!0}),{lastLine:L}=ft(s,N||S),F=()=>{o(`/entity/${t.sha}`)},_=(W,J)=>{u(W);const ae=C.find(I=>I.width===W&&I.height===J);d(ae||null),p({name:(ae==null?void 0:ae.name)||"Custom",width:W,height:J})},E=W=>{d(W),u(W.width),p({name:W.name,width:W.width,height:W.height})},T=W=>{v(W,m.width,m.height??900),y(!1),p(J=>({...J,name:W}))},O=((a==null?void 0:a.scenarios)||[]).filter(W=>{var J;return!((J=W.metadata)!=null&&J.sameAsDefault)}),G=O.findIndex(W=>W.id===(r==null?void 0:r.id)),V=G+1,U=O.length,z=G>0,Y=G<O.length-1,R=()=>{if(z){const W=O[G-1],J=encodeURIComponent(`/entity/${t.sha}/scenarios/${W.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${W.id}/fullscreen?from=${J}`)}},A=()=>{if(Y){const W=O[G+1],J=encodeURIComponent(`/entity/${t.sha}/scenarios/${W.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${W.id}/fullscreen?from=${J}`)}},H=N||S||!k;return l("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[l("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:Ws,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),l("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:R,disabled:!z,className:`${z?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),l("span",{className:"text-gray-400 text-sm",children:[V,"/",U]}),n("button",{onClick:A,disabled:!Y,className:`${Y?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),l("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&l("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]})]}),n("button",{onClick:F,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),l("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Er[Er.length-1].width}px`,width:"100%"},children:n(Eo,{currentViewportWidth:h,currentPresetName:m.name,onDevicePresetClick:E,devicePresets:C,hideLabel:!0,onHoverChange:x,lightMode:!0})})}),l("div",{className:"relative z-10 flex items-center gap-2",children:[l("div",{className:"relative w-28 h-5",children:[l("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(g==null?void 0:g.name)||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"})})]}),l("select",{value:m.name,onChange:W=>{const J=C.find(ae=>ae.name===W.target.value);J&&E(J)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[C.map(W=>n("option",{value:W.name,children:W.name},W.name)),m.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:m.width,onChange:W=>{const J=parseInt(W.target.value,10);!isNaN(J)&&J>0&&_(J,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:"×"}),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:()=>y(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
73
- linear-gradient(45deg, #ebebeb 25%, transparent 25%),
74
- linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
75
- linear-gradient(45deg, transparent 75%, #ebebeb 75%),
76
- linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
77
- `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:w?l("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${m.width}px`,maxHeight:`${m.height}px`},children:[H&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(zn,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),L&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Bn,{}),L]})]})]})}),n("iframe",{src:w,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:j,style:{opacity:k?1:0}},M)]}):l("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(zn,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),L&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Bn,{}),L]})]})]})}),f&&n(Ao,{width:m.width,height:m.height??900,onSave:T,onCancel:()=>y(!1)})]})}),au=Object.freeze(Object.defineProperty({__proto__:null,default:ru,loader:nu},Symbol.toStringTag,{value:"Module"})),Po=Ur({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),sa=()=>{const e=Jn(Po);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},sr=({children:e})=>{const[t,r]=P({height:720,width:1200}),[a,s]=P(1),[o,i]=P(1200),c=Ne(null),d=oe(({height:m,width:p})=>{r(f=>({height:m??f.height,width:p??f.width}))},[]),h=oe(m=>{s(m)},[]),u=oe(m=>{i(m)},[]);return n(Po.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:c,scale:a,updateScale:h,maxWidth:o,updateMaxWidth:u},children:e})},su=typeof window<"u";function ou(){const[e,t]=P(null);return ee(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const iu=1200,lu=720,os=30,cu=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:a=1440,defaultHeight:s=900,onDataOverride:o,onIframeLoad:i,onScaleChange:c,onDimensionChange:d})=>{const h=ou(),[u,m]=P(!1),[p,f]=P(!1),[y,g]=P(iu),[x,b]=P(lu),[v,C]=P(null),[w,N]=P(null),{dimensions:S,updateDimensions:k,iframeRef:M,updateScale:j,updateMaxWidth:L}=sa(),F=re(()=>Math.min(1,y/S.width),[y,S.width]),_=w!==null?w:F;ee(()=>{u||(j(_),c==null||c(_))},[_,j,c,u]),ee(()=>{L(y)},[y,L]);const E=oe(()=>{m(!0),N(F)},[F]),T=oe(()=>{m(!1),N(null)},[]),O=oe((Y,R)=>{const A=w!==null?w:1,H=Math.round(R.size.width/A);k({width:H}),d==null||d(H,S.height)},[k,w,d,S.height]),G=oe(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);ee(()=>{const Y=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",Y),()=>{window.removeEventListener("message",Y)}},[M,t,a,S,k]),ee(()=>{p&&o&&o(M.current)},[p,o,M]),ee(()=>{if(!t)return;const Y=setInterval(()=>{var R,A;(A=(R=M==null?void 0:M.current)==null?void 0:R.contentWindow)==null||A.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(Y)},[t,M]),ee(()=>{const Y=()=>{const R=document.getElementById("scenario-container");if(!R)return;const A=R.getBoundingClientRect(),H=R.clientWidth-os*2,W=window.innerHeight-A.top-os*2,J=Math.max(W,400),ae=window.innerHeight-A.top;g(H),b(J),C(ae)};return Y(),window.addEventListener("resize",Y),()=>window.removeEventListener("resize",Y)},[]),ee(()=>{k({width:a,height:s})},[a,s,k]);const V=re(()=>S.width*_,[S.width,_]),U=re(()=>{const Y=S.height,R=Y*_;return Y&&Y!==720&&Y!==900&&R<x?R:x},[S.height,x,_]),z=oe(()=>{window.history.back()},[]);return!su||!h?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):l("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:v?{height:`${v}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
78
- .react-resizable-handle-e {
79
- display: flex !important;
80
- align-items: center !important;
81
- justify-content: center !important;
82
- width: 6px !important;
83
- height: 48px !important;
84
- right: -8px !important;
85
- top: 50% !important;
86
- transform: translateY(-50%) !important;
87
- cursor: ew-resize !important;
88
- background: #d1d5db !important;
89
- border-radius: 3px !important;
90
- opacity: 0 !important;
91
- transition: all 0.2s ease !important;
92
- }
93
- .react-resizable-handle-e:hover {
94
- opacity: 0.8 !important;
95
- background: #9ca3af !important;
96
- }
97
- .react-resizable:hover .react-resizable-handle-e {
98
- opacity: 0.4 !important;
99
- }
100
- `}),n(h,{width:V,height:U,minConstraints:[300,200],maxConstraints:[y,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:E,onResizeStop:T,onResize:O,children:n("div",{className:"overflow-auto",style:{width:`${V}px`,height:`${U}px`},children:n("div",{style:{width:`${S.width}px`,height:`${S.height}px`,transform:`scale(${_})`,transformOrigin:"top left"},children:r?n("iframe",{ref:M,className:"w-full h-full rounded-lg",src:r,onLoad:G,sandbox:"allow-scripts allow-same-origin"}):l("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[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:z,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function du({presets:e,customSizes:t,currentWidth:r,currentHeight:a,scale:s,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:c,className:d=""}){const[h,u]=P(!1),[m,p]=P(String(r)),[f,y]=P(String(a)),[g,x]=P(!1),[b,v]=P(!1),C=Ne(null);ee(()=>{g||p(String(r))},[r,g]),ee(()=>{b||y(String(a))},[a,b]),ee(()=>{const _=E=>{C.current&&!C.current.contains(E.target)&&u(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]);const w=re(()=>{const _=e.find(T=>T.width===r&&T.height===a);if(_)return _.name;const E=t.find(T=>T.width===r&&T.height===a);return E?E.name:"Custom"},[e,t,r,a]),N=w==="Custom",S=_=>{o(_.width,_.height),u(!1)},k=_=>{const E=_.target.value;p(E);const T=parseInt(E,10);!isNaN(T)&&T>0&&o(T,a)},M=_=>{const E=_.target.value;y(E);const T=parseInt(E,10);!isNaN(T)&&T>0&&o(r,T)},j=()=>{x(!1);const _=parseInt(m,10);(isNaN(_)||_<=0)&&p(String(r))},L=()=>{v(!1);const _=parseInt(f,10);(isNaN(_)||_<=0)&&y(String(a))},F=_=>{(_.key==="Enter"||_.key==="Escape")&&_.target.blur()};return l("div",{className:`flex items-center gap-3 ${d}`,children:[l("div",{className:"relative",ref:C,children:[l("button",{onClick:()=>u(!h),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:w}),n("svg",{className:`w-4 h-4 transition-transform ${h?"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"})})]}),h&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:l("div",{className:"py-1",children:[e.length>0&&l(he,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(_=>l("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}),l("span",{className:"text-xs text-gray-500",children:[_.width," x ",_.height]})]},_.name))]}),t.length>0&&l(he,{children:[n("div",{className:"border-t border-gray-100 my-1"}),n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Custom"}),[...t].sort((_,E)=>_.width-E.width).map(_=>l("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${w===_.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[l("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}),l("span",{className:"text-xs text-gray-500",children:[_.width," x ",_.height]})]}),c&&n("button",{onClick:E=>{E.stopPropagation(),w===_.name&&e.length>0&&o(e[0].width,e[0].height),c(_.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))]})]})})]}),l("div",{className:"flex items-center gap-1 text-sm",children:[l("div",{className:"flex items-center",children:[n("input",{type:"text",value:m,onChange:k,onFocus:()=>x(!0),onBlur:j,onKeyDown:F,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),l("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:M,onFocus:()=>v(!0),onBlur:L,onKeyDown:F,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"})]}),s!==void 0&&s<1&&l("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(s*100),"%)"]})]}),N&&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 Ar(e,t,r){if(Array.isArray(e)){if(!isNaN(parseInt(t)))return e[parseInt(t)];for(const a of e)if(a.name===t||a.title===t||a.id===t)return a}return e[t]}function Lr(e){return e&&(typeof e=="object"||Array.isArray(e))}function uu(e){return Array.isArray(e)?e.length:void 0}function hu(e){const{data:t,structure:r}=e;if(!(!t&&!r)){if(Array.isArray(r))return Array.isArray(t)?t.map((a,s)=>s.toString()):[];if(typeof r=="object")return[...new Set([...Object.keys(t),...Object.keys(r)])].sort((s,o)=>{const i=Lr(t[s]),c=Lr(t[o]);return i&&!c?1:!i&&c?-1:s.localeCompare(o)});if(typeof t=="object")return Object.keys(t).sort((s,o)=>s.localeCompare(o))}}function mu({scenarioFormData:e,handleInputChange:t}){return l("div",{className:"p-3 flex flex-col gap-3",children:[l("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),n("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),l("div",{className:"grid w-full gap-1.5 pt-2",children:[n("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),n("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[100px]"})]}),n("button",{type:"submit",className:"mt-3 w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium",children:"Save Name & Description"})]})}function pu({path:e,namedPath:t,isArray:r,count:a,onClick:s}){const o=oe(()=>{s&&s(e)},[s,e]);return l("div",{className:"bg-blue-50 p-3 rounded-lg flex items-center justify-between cursor-pointer group hover:bg-blue-100 transition-colors border border-blue-200",onClick:o,children:[l("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),l("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],a!==void 0&&` (${a})`]})]}),l("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var _o=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(_o||{});const fu=({name:e,value:t,options:r,onChange:a})=>{const s=oe(o=>{a({target:{name:e,value:o.target.value}})},[e,a]);return n("select",{name:e,value:t,onChange:s,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))})},gu=({name:e,value:t,onChange:r})=>{const a=oe(s=>{const o=s.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:a,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
101
- bg-gray-300 checked:bg-blue-600
102
- after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
103
- after:bg-white after:rounded-full after:transition-transform
104
- checked:after:translate-x-4`})})};function yu({dataType:e,path:t,value:r,onChange:a}){const s=re(()=>t[t.length-1],[t]),o=re(()=>t.join("-"),[t]),i=oe(d=>{a(t,d.target.value)},[a,t]),c=oe(d=>{a(t,d.target.value)},[a,t]);return l("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:o,className:"capitalize text-sm font-medium text-gray-700",children:s==="~~codeyam-code~~"?"Dynamic Field":s}),e.includes("|")?n(fu,{name:o,value:r,options:e.split("|"),onChange:i}):e===_o.BOOLEAN?n(gu,{name:o,value:r??!1,onChange:c}):n("input",{id:o,name:o,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${o}`)]})}function xu({analysis:e,scenarioName:t,dataItem:r,onResult:a,onGenerateData:s}){const[o,i]=P(!1),[c,d]=P(""),h=oe(async()=>{if(!s){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const m=e.scenarios.find(x=>x.name===t);if(!m)throw new Error("Scenario not found");const p=e.scenarios.find(x=>x.name===Qn),f=await s(c,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(C=>{g(b[C])?C in x?v[C]=y(x[C],b[C]):Object.assign(v,{[C]:b[C]}):Object.assign(v,{[C]:b[C]})}),v},g=x=>x&&typeof x=="object"&&!Array.isArray(x);m.metadata.data=y(y((p==null?void 0:p.metadata.data)||{},m.metadata.data),f.data||{}),a(m),i(!1),d("")}catch(m){console.error("Error generating AI data:",m),i(!1)}},[e,c,r,t,a,s]),u=oe(m=>{d(m.target.value)},[]);return l("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:c}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${c.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void h(),children:o?l(he,{children:[l("svg",{className:"animate-spin h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Please wait"]}):"Generate Data"})]})}function bu({namedPath:e,path:t,last:r,onClick:a}){const s=oe(()=>a(r?t.slice(0,-1):t),[r,t,a]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:s,children:e[e.length-1]})}function vu({dataItem:e,onClick:t}){const r=oe(()=>t([]),[t]),a=re(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return l("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&l("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(a).map((s,o)=>l("div",{className:"flex items-center gap-1",children:[n(bu,{namedPath:e.namedPath.slice(0,o+a+1),path:e.path.slice(0,o+a+1),last:o+a===e.namedPath.length-1,onClick:t}),o+a<e.namedPath.length-1&&n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},`path-${s}-${o+a}`))]})}function is({analysis:e,scenarioName:t,dataItem:r,onClick:a,onChange:s,onAIResult:o,onGenerateData:i,saveFeedback:c}){const d=re(()=>r.data,[r]),h=re(()=>hu(r),[r]);return l("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(vu,{dataItem:r,onClick:a}),l("div",{className:"flex flex-col gap-3",children:[n(xu,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),h==null?void 0:h.map((u,m)=>{var f;if(Lr(d[u])){let y=u;isNaN(Number(u))||(y=d[u].name??d[u].title??d[u].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const g=[...r.path,u],x=[...r.namedPath,y];return n(pu,{path:g,namedPath:x,isArray:Array.isArray(d),count:uu(d[u]),onClick:a},`data-${u}-${m}`)}if(u==="id")return null;const p=[...r.path,u];return n(yu,{dataType:((f=r.structure)==null?void 0:f[u])??"string",path:p,value:d[u],onChange:s},`InputField-${p.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),l("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:c==null?void 0:c.isSaving,className:"flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:c!=null&&c.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled:c==null?void 0:c.isSaving,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save & Recapture"})]}),(c==null?void 0:c.message)&&!(c!=null&&c.isSaving)&&n("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${c.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:c.message})]})}function ls({title:e,children:t,defaultOpen:r=!1,borderT:a=!1,borderB:s=!1}){const[o,i]=P(r),c=[];return a&&c.push("border-t"),s&&c.push("border-b"),l("div",{className:`${c.join(" ")} border-gray-300`,children:[l("button",{type:"button",onClick:()=>i(!o),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${o?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),o&&n("div",{className:"px-4 py-3",children:t})]})}const wu=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:a,shouldCreateNewScenario:s,onSave:o,onNavigate:i,iframeRef:c,onGenerateData:d,saveFeedback:h})=>{const u=oe((k,M)=>{const j=Object.assign({},k),L=F=>F&&typeof F=="object"&&!Array.isArray(F);return L(k)&&L(M)&&Object.keys(M).forEach(F=>{L(M[F])?F in k?j[F]=u(k[F],M[F]):Object.assign(j,{[F]:M[F]}):Object.assign(j,{[F]:M[F]})}),j},[]),[m,p]=P({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,y]=P(null),g=re(()=>({...m.data}),[m]),x=re(()=>({...g.mockData?{"Retrieved Data":g.mockData}:{},...g.argumentsData?{"Function Arguments":g.argumentsData}:{}}),[g]),b=re(()=>{const k={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(k).reduce((M,j)=>{if(j.includes(".")){const[L,F]=j.split(".");M[L]||(M[L]={}),M[L][F]=k[j]}else M[j]=k[j];return M},{})},[r]),v=oe(async k=>{k.preventDefault();const M=k.target.querySelector('input[name="recapture"]'),j=(M==null?void 0:M.value)==="true",L={mockData:m.data.mockData??{},argumentsData:m.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:m.name,shouldRecapture:j,dataToSave:L,rawFormData:m.data,iframePayload:{arguments:g.argumentsData??[],...g.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(L,null,2).substring(0,1e3));const F=a==null?void 0:a.scenarios.map(_=>!s&&_.name===e.name?{..._,name:m.name,description:m.description,metadata:{..._.metadata,data:L}}:_);s&&F.push({name:m.name,description:m.description,metadata:{data:L,interactiveExamplePath:a==null?void 0:a.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",F),o&&await o(F,{recapture:j}),i&&i(m.name)},[a,e.name,m,g,s,o,i]),C=oe(k=>{p(M=>({...M,[k.target.name]:k.target.value}))},[]),w=oe(k=>{y(M=>{if(!M)return null;for(const j of[{arguments:k.metadata.data.argumentsData},k.metadata.data.mockData]){let L=j;for(const F of M.path)if(L=Ar(L,F),!L)break;L&&(M.data=L)}return{...M}}),p({name:k.name,description:k.description,data:k.metadata.data})},[]),N=oe((k,M)=>{p(j=>{for(const L of[{"Function Arguments":j.data.argumentsData},{"Retrieved Data":j.data.mockData}]){let F=L;for(const _ of k.slice(0,-1))if(F=Ar(F,_),!F)break;if(F){const _=F[k[k.length-1]];y(E=>E?(E.namedPath[E.namedPath.length-1]===_&&(E.namedPath[E.namedPath.length-1]=M.toString()),E.data[k[k.length-1]]=M,{...E}):null),F[k[k.length-1]]=M}}return{...j}})},[]),S=oe(k=>{var F,_,E;if(k.length===0){y(null);return}let M=x;const j=[];let L=b;for(const T of k){if(j.push(isNaN(parseInt(T))?T:((F=M[T])==null?void 0:F.name)??((_=M[T])==null?void 0:_.title)??((E=M[T])==null?void 0:E.id)??T),M=Ar(M,T),!M){console.log("Data not found",M,T),y(null);return}Array.isArray(L)?L=L[0]:L=L[T]}y({path:k,namedPath:j,data:M,structure:L})},[x,b]);return ee(()=>{const k=M=>{var j;M.data.type==="codeyam-log"&&((j=M.data.data)!=null&&j.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",M.data.data)};return window.addEventListener("message",k),()=>window.removeEventListener("message",k)},[]),ee(()=>{var k;if((k=c==null?void 0:c.current)!=null&&k.contentWindow){const M={arguments:g.argumentsData??[],...g.mockData??{}},j={type:"codeyam-override-data",name:e.name,data:JSON.stringify(M)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:j.type,name:j.name,dataPreview:JSON.stringify(M).substring(0,200)+"...",fullData:M}),c.current.contentWindow.postMessage(j,"*")}},[g,e,c]),n("form",{method:"post",onSubmit:k=>void v(k),children:f?n(is,{analysis:a,scenarioName:m.name,dataItem:f,onClick:S,onChange:N,onAIResult:w,onGenerateData:d,saveFeedback:h}):l(he,{children:[n(ls,{title:"Edit Name and Description",borderT:!0,children:n(mu,{scenarioFormData:m,handleInputChange:C})}),e.metadata.data&&n(ls,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(is,{analysis:a,scenarioName:m.name,dataItem:{path:[],namedPath:[],data:x,structure:b},onClick:S,onChange:N,onAIResult:w,onGenerateData:d,saveFeedback:h})})]})})};function or({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:a,isLoading:s,showIframe:o,iframeKey:i,onIframeLoad:c,onScaleChange:d,onDimensionChange:h,projectSlug:u,defaultWidth:m=1440,defaultHeight:p=900,retryCount:f=0}){const{lastLine:y}=ft(u??null,a||s);return r?l("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:o?1:0,background:"transparent"},children:n(cu,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:m,defaultHeight:p,onIframeLoad:c,onScaleChange:d,onDimensionChange:h},i)}),!o&&(a||s)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(zn,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Bn,{}),y]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center",children:l("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(zn,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Bn,{}),y]})]})]})})}const Cu=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Nu({params:e}){var d,h;const{sha:t,scenarioId:r}=e;if(!t)throw new Response("Entity SHA is required",{status:400});if(!r)throw new Response("Scenario ID is required",{status:400});const a=await Xn(t,!0),s=a&&a.length>0?a[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const o=(d=s.scenarios)==null?void 0:d.find(u=>u.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=(h=s.scenarios)==null?void 0:h.find(u=>u.name===Qn),c=await $e();return B({analysis:s,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:c})}function Su(){var T,O,G;const e=Be(),t=e.analysis,r=e.scenario,a=e.defaultScenario,s=e.entitySha,o=e.projectSlug,i=Mt(),{iframeRef:c}=sa(),[d,h]=P(!1),[u,m]=P(null),[p,f]=P(null),[y,g]=P(!1),[x,b]=P(!1),[v,C]=P(null),{interactiveServerUrl:w,isStarting:N,isLoading:S,showIframe:k,iframeKey:M,onIframeLoad:j}=hn({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}),L=oe(async(V,U)=>{h(!0),m(null),f(null),console.log("[EditScenario] Starting save with options:",U),console.log("[EditScenario] Scenarios to save:",V);try{const z={analysis:t,scenarios:V};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:V.length,scenarioNames:V.map(A=>A.name)});const Y=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(z)}),R=await Y.json();if(console.log("[EditScenario] API response:",R),!Y.ok||!R.success)throw new Error(R.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),U!=null&&U.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}),m("Changes saved. Capturing screenshot...");const A={serverUrl:w,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",A);const H=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});console.log("[EditScenario] Capture response status:",H.status);const W=await H.json();if(console.log("[EditScenario] Capture response body:",W),!H.ok||!W.success)throw console.error("[EditScenario] Capture failed:",W),new Error(W.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",W),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),m("Recapture successful")}else if(U!=null&&U.recapture&&!w){console.log("[EditScenario] No running server, using queued recapture");const A=new FormData;A.append("analysisId",t.id||""),A.append("scenarioId",r.id||"");const H=await fetch("/api/recapture-scenario",{method:"POST",body:A}),W=await H.json();if(!H.ok||!W.success)throw new Error(W.error||"Failed to trigger recapture");console.log("Recapture queued:",W),f(W.jobId),m("Changes saved. Screenshot recapture queued.")}else m("Changes saved successfully.")}catch(z){console.error("Error saving scenarios:",z),m(`Error: ${z instanceof Error?z.message:String(z)}`)}finally{h(!1)}},[t,r.id,w]),F=oe(V=>{},[]),_=oe(async(V,U)=>{var R;const z=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:V,existingScenarios:t.scenarios,scenariosDataStructure:(R=t.metadata)==null?void 0:R.scenariosDataStructure,editingMockName:r.name,editingMockData:U==null?void 0:U.data})}),Y=await z.json();if(!z.ok||!Y.success)throw new Error(Y.error||"Failed to generate scenario data");return Y.data},[t,r.name]),E=oe(async()=>{var V;if(!r.id){C("Cannot delete scenario without ID");return}g(!0),C(null);try{const U=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((V=r.metadata)==null?void 0:V.screenshotPaths)||[]})}),z=await U.json();if(!U.ok||!z.success)throw new Error(z.error||"Failed to delete scenario");i(`/entity/${s}`)}catch(U){console.error("[EditScenario] Error deleting scenario:",U),C(U instanceof Error?U.message:"Failed to delete scenario"),b(!1)}finally{g(!1)}},[r.id,(T=r.metadata)==null?void 0:T.screenshotPaths,s,i]);return l("div",{className:"h-screen bg-gray-50 flex flex-col",children:[l("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:l(se,{to:`/entity/${s}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(O=t.entity)==null?void 0:O.name]})}),l("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",r.name]}),r.description&&n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:r.description})]}),l("div",{className:"flex flex-1 gap-0 min-h-0",children:[l("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n(wu,{currentScenario:r,defaultScenario:a,dataStructure:((G=t.metadata)==null?void 0:G.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:L,onNavigate:F,iframeRef:c,onGenerateData:_,saveFeedback:{isSaving:d,message:u,isError:(u==null?void 0:u.startsWith("Error"))??!1}}),u==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(se,{to:`/entity/${s}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),l("div",{className:"border-t border-gray-200 p-4 mt-4",children:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),x?l("div",{className:"space-y-3",children:[l("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),l("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void E(),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(or,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:w,isStarting:N,isLoading:S,showIframe:k,iframeKey:M,onIframeLoad:j,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const Eu=De(function(){return n(sr,{children:n(Su,{})})}),Au=Object.freeze(Object.defineProperty({__proto__:null,default:Eu,loader:Nu,meta:Cu},Symbol.toStringTag,{value:"Module"}));function ku({executionFlows:e,selections:t,onChange:r,disabled:a=!1}){const s=oe(i=>t.some(c=>c.flowId===i),[t]),o=oe(i=>{s(i.id)?r(t.filter(c=>c.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,s]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const c=s(i.id),d=i.usedInScenarios.length>0;return l("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[l("label",{className:"flex items-start gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:c,onChange:()=>o(i),disabled:a,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!d&&n("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&n("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&n("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),c&&i.requiredValues.length>0&&l("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[n("span",{className:"text-gray-700 font-medium",children:"Required values:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((h,u)=>l("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:h.attributePath})," ",n("span",{className:"text-gray-400",children:h.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:h.value})]},u))})]})]},i.id)})})}function oa(e,t){const r=(e||[]).map(d=>({...d,usedInScenarios:[]})),a=new Map;r.forEach(d=>{a.set(d.id,d)});const s=[];t.forEach(d=>{var u;const h=((u=d.metadata)==null?void 0:u.coveredFlows)||[];h.forEach(m=>{const p=a.get(m);p&&p.usedInScenarios.push({id:d.id||"",name:d.name})}),s.push({scenario:d,coveredFlowIds:h})});const o=r.length,i=r.filter(d=>d.usedInScenarios.length>0).length,c=o>0?i/o*100:0;return{executionFlows:r,totalFlows:o,coveredFlows:i,coveragePercentage:c,scenariosWithFlows:s}}function Pu(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const _u=({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 Mu({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await Xn(t,!0),a=r&&r.length>0?r[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const s=(i=a.scenarios)==null?void 0:i.find(c=>c.name===Qn);if(!s)throw new Response("Default scenario not found",{status:404});const o=await $e();return B({analysis:a,defaultScenario:s,entity:a.entity,entitySha:t,projectSlug:o})}function Tu(){var z;const{analysis:e,defaultScenario:t,entity:r,entitySha:a,projectSlug:s}=Be(),o=Mt(),{iframeRef:i}=sa(),[c,d]=P(""),[h,u]=P(400),[m,p]=P(!1),[f,y]=P(!1),[g,x]=P(!1),[b,v]=P(null),[C,w]=P(null),[N,S]=P([]),k=re(()=>{var R;return!((R=e==null?void 0:e.metadata)!=null&&R.executionFlows)||!(e!=null&&e.scenarios)?[]:oa(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:M,isStarting:j,isLoading:L,showIframe:F,iframeKey:_,onIframeLoad:E}=hn({analysisId:e==null?void 0:e.id,scenarioId:t==null?void 0:t.id,scenarioName:t==null?void 0:t.name,projectSlug:s,enabled:!0}),T=oe(async()=>{var Y,R,A,H;if(!c.trim()&&N.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 W=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:c,existingScenarios:e.scenarios,scenariosDataStructure:(Y=e.metadata)==null?void 0:Y.scenariosDataStructure,flowSelections:N.length>0?N:void 0})}),J=await W.json();if(!W.ok||!J.success)throw new Error(J.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",J.data);const ae=J.data;if(!ae.name||!ae.data)throw new Error("AI response missing required fields (name or data)");w("Saving new scenario..."),x(!0);const $={name:ae.name,description:ae.description||c,metadata:{data:ae.data,interactiveExamplePath:(R=t.metadata)==null?void 0:R.interactiveExamplePath}},I=[...e.scenarios||[],$],D=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:I})}),q=await D.json();if(!D.ok||!q.success)throw new Error(q.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",q);const te=(H=(A=q.analysis)==null?void 0:A.scenarios)==null?void 0:H.find(ce=>ce.name===ae.name);if(!(te!=null&&te.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),w("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${a}`),1e3);return}if(M){w("Capturing screenshot...");const ce=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:M,scenarioId:te.id,projectId:e.projectId,viewportWidth:1440})}),me=await ce.json();!ce.ok||!me.success?(console.error("[CreateScenario] Capture failed:",me),w("Scenario created! (Screenshot capture failed)")):w("Scenario created and captured!")}else w("Scenario created!");setTimeout(()=>{o(`/entity/${a}/scenarios/${te.id}`)},1e3)}catch(W){console.error("[CreateScenario] Error:",W),v(W instanceof Error?W.message:String(W)),w(null)}finally{y(!1),x(!1)}},[c,N,e,t,a,M,o]),O=f||g,G=oe(()=>{p(!0)},[]),V=oe(Y=>{if(!m)return;const R=Y.clientX;R>=250&&R<=600&&u(R)},[m]),U=oe(()=>{p(!1)},[]);return ee(()=>(m?(document.addEventListener("mousemove",V),document.addEventListener("mouseup",U)):(document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",U)),()=>{document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",U)}),[m,V,U]),l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-end h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:()=>void o(`/entity/${a}`),className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:r==null?void 0:r.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:r==null?void 0:r.filePath,children:r==null?void 0:r.filePath})]}),l("div",{className:"flex items-end gap-8 shrink-0",children:[n(se,{to:`/entity/${a}/scenarios`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-medium border-b-2",style:{color:"#005C75",borderColor:"#005C75"},children:l("span",{className:"flex items-center gap-2",children:["Scenarios",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:((z=e==null?void 0:e.scenarios)==null?void 0:z.length)||0})]})}),n(se,{to:`/entity/${a}/related`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Related Entities"}),n(se,{to:`/entity/${a}/code`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Code"}),n(se,{to:`/entity/${a}/data`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Data Structure"}),n(se,{to:`/entity/${a}/history`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"History"})]})]})}),l("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[l("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${h}px`},children:[l("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select execution flows and/or describe how you'd like to change it."})]}),k.length>0&&l("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[l("summary",{className:"px-3 py-2 text-sm font-medium text-gray-700 cursor-pointer hover:bg-gray-50 rounded-lg",children:["Select Execution Flows"," ",N.length>0&&l("span",{className:"text-blue-600",children:["(",N.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(ku,{executionFlows:k,selections:N,onChange:S,disabled:O})})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"Describe your scenario"}),n("textarea",{id:"prompt",value:c,onChange:Y=>d(Y.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:O})]}),l("div",{className:"space-y-2",children:[n("button",{onClick:()=>void T(),disabled:O||!c.trim()&&N.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:O?"Creating...":"Create Scenario"}),C&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:C}),b&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:b})]})]}),l("div",{onMouseDown:G,style:{width:"20px",position:"absolute",top:0,left:`${h-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[n("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:m?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),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:`
105
- linear-gradient(45deg, #ebebeb 25%, transparent 25%),
106
- linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
107
- linear-gradient(45deg, transparent 75%, #ebebeb 75%),
108
- linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
109
- `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:n(or,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:M,isStarting:j,isLoading:L,showIframe:F,iframeKey:_,onIframeLoad:E,projectSlug:s,defaultWidth:1440,defaultHeight:900})})]})]})}const ju=De(function(){return n(sr,{children:n(Tu,{})})}),Iu=Object.freeze(Object.defineProperty({__proto__:null,default:ju,loader:Mu,meta:_u},Symbol.toStringTag,{value:"Module"}));var le;(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={}))})(le||(le={}));function Mo(e,t){return e?Object.values(le.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const To=Mo(process.env.DEFAULT_SMALLER_MODEL,le.Model.OPENAI_GPT4_1_MINI),$u=Mo(process.env.DEFAULT_LARGER_MODEL,le.Model.OPENAI_GPT4_1),Qe={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},kr={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},Ru={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},Pr={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},ct={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},Du={[le.Model.OPENAI_GPT5_1]:{id:le.Model.OPENAI_GPT5_1,provider:Qe,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[le.Model.OPENAI_GPT5]:{id:le.Model.OPENAI_GPT5,provider:Qe,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[le.Model.OPENAI_GPT5_MINI]:{id:le.Model.OPENAI_GPT5_MINI,provider:Qe,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[le.Model.OPENAI_GPT5_NANO]:{id:le.Model.OPENAI_GPT5_NANO,provider:Qe,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[le.Model.OPENAI_GPT4_1]:{id:le.Model.OPENAI_GPT4_1,provider:Qe,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[le.Model.OPENAI_GPT4_1_MINI]:{id:le.Model.OPENAI_GPT4_1_MINI,provider:Qe,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[le.Model.OPENAI_GPT4_O]:{id:le.Model.OPENAI_GPT4_O,provider:Qe,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[le.Model.OPENAI_GPT4_O_MINI]:{id:le.Model.OPENAI_GPT4_O_MINI,provider:Qe,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[le.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:le.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:kr,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[le.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:le.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:kr,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[le.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:le.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:kr,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[le.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:le.Model.OPENAI_GPT_OSS_120B_GROQ,provider:Ru,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[le.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:le.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:ct,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[le.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:le.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:ct,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[le.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:le.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:ct,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[le.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:le.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:ct,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[le.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:le.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:ct,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[le.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:le.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:Pr,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[le.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:le.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:Pr,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[le.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:le.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:Pr,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[le.Model.PHIND_CODELLAMA]:{id:le.Model.PHIND_CODELLAMA,provider:Qe,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[le.Model.GOOGLE_GEMINI_PRO]:{id:le.Model.GOOGLE_GEMINI_PRO,provider:ct,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[le.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:le.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:ct,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[le.Model.META_CODELLAMA_34B_INSTRUCT]:{id:le.Model.META_CODELLAMA_34B_INSTRUCT,provider:ct,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[le.Model.OPENAI_GPT4_PREVIEW]:{id:le.Model.OPENAI_GPT4_PREVIEW,provider:Qe,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function ir(e){const t=Du[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function Lu(e){return ir(e).maxCompletionTokens}function Fu(e){return ir(e).pricing}const cs=1e6;function Ou({model:e,usage:t}){const r=Fu(e);return r?t.prompt_tokens*(r.input/cs)+t.completion_tokens*(r.output/cs):null}function Yu({chatRequest:e,chatCompletion:t,model:r}){if("error"in t&&t.error)return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),error:JSON.stringify(t.error)};const a=t.usage||{prompt_tokens:0,completion_tokens:0},s=Ou({model:r,usage:a});return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,cost:s?Math.round(s*1e5)/1e5:void 0}}function zu({messages:{system:e,prompt:t},model:r,responseType:a,jsonSchema:s}){const o=r??To,i=ir(o);Lu(o);const c=[];return e&&c.push({role:"system",content:e}),c.push({role:"user",content:[{type:"text",text:t}]}),{messages:c,model:i.apiModelName,response_format:a==="json_schema"&&s?{type:"json_schema",json_schema:{name:s.name,schema:s.schema,strict:s.strict!==!1}}:{type:a&&a=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}const Fr="/tmp/codeyam-e2e-tracking";let _r,Mr;function Bu(){return _r===void 0&&(_r=process.env.CODEYAM_E2E_TRACK_DATA==="true"),_r}function Uu(){return Mr===void 0&&(Mr=!process.env.CODEYAM_LLM_FIXTURES_DIR),Mr}function Wu(){K.existsSync(Fr)||K.mkdirSync(Fr,{recursive:!0})}function Hu(e){const t=JSON.stringify(e,null,0);return ml.createHash("md5").update(t).digest("hex")}function Ju(e,t,r){return[e].join("_")+".json"}function jo(e,t,r,a){if(!Bu())return;Wu();const s=Ju(e),o=Z.join(Fr,s),i=Hu(t);if(Uu()){const c={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:a,dataHash:i,data:t};K.writeFileSync(o,JSON.stringify(c,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(K.existsSync(o)){const c=JSON.parse(K.readFileSync(o,"utf-8")),d={matches:i===c.dataHash,firstRunHash:c.dataHash};if(d.matches)console.log(`[E2E Tracking] Match at ${e} hash=${i.substring(0,8)}`);else{d.differences=Or(c.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${c.dataHash}`),console.log(` Second run hash: ${i}`);const h=o.replace(".json","_DIFF.json");K.writeFileSync(h,JSON.stringify({checkpoint:e,entityName:r,scenarioName:a,firstRun:c.data,secondRun:t,differences:d.differences},null,2)),console.log(` Diff saved to: ${h}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function Or(e,t,r=""){const a=[];if(typeof e!=typeof t)return a.push(`${r||"root"}: type mismatch (${typeof e} vs ${typeof t})`),a;if(e===null||t===null)return e!==t&&a.push(`${r||"root"}: ${JSON.stringify(e)} vs ${JSON.stringify(t)}`),a;if(Array.isArray(e)&&Array.isArray(t)){e.length!==t.length&&a.push(`${r||"root"}: array length ${e.length} vs ${t.length}`);const s=Math.max(e.length,t.length);for(let o=0;o<s;o++)a.push(...Or(e[o],t[o],`${r}[${o}]`));return a}if(typeof e=="object"&&typeof t=="object"){const s=Object.keys(e),o=Object.keys(t),i=Array.from(new Set([...s,...o]));for(const c of i){const d=e[c],h=t[c];c in e?c in t?a.push(...Or(d,h,`${r?r+".":""}${c}`)):a.push(`${r?r+".":""}${c}: missing in second run`):a.push(`${r?r+".":""}${c}: missing in first run`)}return a}if(e!==t){const s=JSON.stringify(e),o=JSON.stringify(t);s.length<100&&o.length<100?a.push(`${r||"root"}: ${s} vs ${o}`):a.push(`${r||"root"}: values differ (${s.length} chars vs ${o.length} chars)`)}return a}qr(Gr);const bn=new vl({concurrency:100,timeout:1200*1e3,throwOnTimeout:!0,autoStart:!0}),ds={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},dt={};async function Yr({type:e,systemMessage:t,prompt:r,jsonResponse:a=!0,jsonSchema:s,model:o=To,attempts:i=0}){var S,k,M,j,L,F,_;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await Vu(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${bn.size}, running=${bn.pending}]`);const c=Date.now();let d,h=0;const u=ir(o),m=process.env[u.provider.apiKeyEnvVar];if(!m)throw new Error(`API key not found for provider ${u.provider.name}. Please set ${u.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${u.provider.name} for AI request`);const p=new bl({apiKey:m,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:s?"json_schema":a?"json_object":"text",jsonSchema:s},y=zu(f),g=await bn.add(()=>(d=Date.now(),qa(async()=>{const E=Date.now(),T=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],O=setInterval(()=>{const G=Math.floor((Date.now()-E)/1e3),V=Math.floor(G/10)%T.length;Qa(1,`${T[V]} [type=${e}, model=${o}, elapsed=${G}s]`)},1e4);try{return await p.chat.completions.create(y,{timeout:300*1e3})}finally{clearInterval(O)}},{...ds,onFailedAttempt:E=>{h++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:E,prompt:r,systemMessage:t,attempts:i,retryCount:h})}})),{throwOnTimeout:!0}),x=Date.now(),b=Yu({chatRequest:f,chatCompletion:g,model:o});if(!b)throw new Error("Failed to get LLM call stats");b.retries=h,b.wait_ms=d-c,b.duration_ms=x-c;const v=(S=g.choices)==null?void 0:S[0];let C=null;if(v){if(!v.finish_reason)throw console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({chatCompletion:g,chatRequest:f},null,2)),new Error("completionCall(): missing finish_reason in LLM response");C=(k=v.message)==null?void 0:k.content}let w=C;C&&(w=C.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const N=a?w&&(((M=w.match(/\{[\s\S]*\}/))==null?void 0:M[0])??w):w;if(!N){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:N,rawCompletion:C,chatCompletion:g,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await Yr({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(N.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:C,prompt:r,systemMessage:t}),new Error("Empty completion");if(a)try{JSON.parse(N)}catch(E){if(console.log("CodeYam Error: Invalid JSON in completion",{error:E.message,model:o,completion:N.substring(0,500),rawCompletion:C==null?void 0:C.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:E.message});const T=`Your previous response contained invalid JSON with the following error:
110
-
111
- ${E.message}
112
-
113
- Here was your previous response:
114
- \`\`\`
115
- ${N}
116
- \`\`\`
117
-
118
- Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,O=await bn.add(()=>qa(async()=>{const z=Date.now(),Y=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],R=setInterval(()=>{const A=Math.floor((Date.now()-z)/1e3),H=Math.floor(A/10)%Y.length;Qa(1,`${Y[H]} [type=${e}, model=${o}, elapsed=${A}s]`)},1e4);try{return await p.chat.completions.create({...y,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:N},{role:"user",content:T}]},{timeout:300*1e3})}finally{clearInterval(R)}},{...ds,onFailedAttempt:z=>{console.log("CodeYam Error: Correction call failed",{error:z,attempts:i})}}),{throwOnTimeout:!0}),G=(F=(L=(j=O.choices)==null?void 0:j[0])==null?void 0:L.message)==null?void 0:F.content;let V=G;G&&(V=G.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const U=V&&(((_=V.match(/\{[\s\S]*\}/))==null?void 0:_[0])??V);if(!U)throw new Error("Correction attempt returned empty completion");try{JSON.parse(U),console.log("CodeYam: JSON correction successful");const z=Date.now();return b.duration_ms=z-c,{finishReason:O.choices[0].finish_reason,completion:U,stats:b}}catch(z){return console.log("CodeYam Error: Corrected JSON still invalid",{error:z.message,correctedCompletion:U.substring(0,500)}),await Yr({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${E.message}`)}return jo(`completionCall_${e}`,{completion:N,finishReason:g.choices[0].finish_reason}),{finishReason:g.choices[0].finish_reason,completion:N,stats:b}}async function Vu(e,t,r){var o,i,c,d,h;const a=await import("fs"),s=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!a.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=a.readdirSync(t).filter(v=>v.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${t}`);const m={};for(const v of u)try{const C=a.readFileSync(s.join(t,v),"utf-8"),w=JSON.parse(C);m[w.prompt_type]||(m[w.prompt_type]=[]),m[w.prompt_type].push(w)}catch(C){console.warn(`Failed to parse LLM fixture file ${v}:`,C)}for(const v of Object.keys(m))m[v].sort((C,w)=>{const N=C.created_at??0,S=w.created_at??0;return N-S});const p=m[e];if(!p||p.length===0){const v=Object.keys(m).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: "([^"]+)"/),C=v==null?void 0:v[1];if(C){const w={};for(const S of p)try{const M=((o=JSON.parse(S.props||"{}").scenario)==null?void 0:o.name)||"__NO_SCENARIO__";w[M]||(w[M]=[]),w[M].push(S)}catch{}const N=w[C];if(N&&N.length>0){const S=`${t}::${e}::${C}`;dt[S]===void 0&&(dt[S]=0);const k=dt[S];dt[S]=(k+1)%N.length,f=N[k],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${C}' [${k+1}/${N.length}]`)}else{const S=Object.keys(w).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${C}'. Available: [${S}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const v=`${t}::${e}`;dt[v]===void 0&&(dt[v]=0);const C=dt[v];dt[v]=(C+1)%p.length,f=p[C],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${C+1}/${p.length}]`)}let g;try{g=((d=(c=(i=JSON.parse(f.response).choices)==null?void 0:i[0])==null?void 0:c.message)==null?void 0:d.content)||f.response}catch{g=f.response}let x=g;g&&(x=g.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const b=x&&(((h=x.match(/\{[\s\S]*\}/))==null?void 0:h[0])??x);return jo(`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 us(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function Gu(e){const{propsJson:t,...r}=e,a=JSON.stringify(t,null,2),s=zs(),o=Date.now(),i={...r,id:s,created_at:o,props:a};let c;const d=`${i.object_id}_${s}.json`;if(process.env.DYNAMODB_PATH?c=Z.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(c=Z.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),c)try{const u=Z.dirname(c);return await Re.mkdir(u,{recursive:!0}),await Re.writeFile(c,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${c}`),{id:s}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const h=us();if(!h)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,m]of Object.entries(i))typeof m>"u"&&console.log(`CodeYam Warning: LLM call ${s} property ${u} with explicit value 'undefined'`);try{return await new Kn().send(new wl({TableName:us(),Item:Nl(i,{removeUndefinedValues:!0})})),{id:s}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${h}`,u),{id:"-1"}}}new Kn({});new Kn({});new Kn({});const qu=3,Ku=2,ia=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+qu*String(t).length*(1+Ku)});new Kr(ia());new Kr(ia());new Kr(ia());class Qu{constructor(){this.byMethodName=new Map,this.byClassAndMethod=new Map}register(t,r,a){this.byMethodName.has(t)||this.byMethodName.set(t,[]),this.byMethodName.get(t).push(r),a&&(this.byClassAndMethod.has(a)||this.byClassAndMethod.set(a,new Map),this.byClassAndMethod.get(a).set(t,r))}getByMethodName(t){return this.byMethodName.get(t)}getByClassAndMethod(t,r){var a;return(a=this.byClassAndMethod.get(t))==null?void 0:a.get(r)}}class Zu{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Xu{getReturnType(){return"boolean"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"boolean");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class eh{getReturnType(){return"boolean"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"boolean");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class th{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class nh{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];if(a.addType(o,"function"),a.addEquivalence(o.withParameter(1),r.withElement("*")),s.args.length>1){const i=s.args[1];a.addEquivalence(o.withParameter(0),i)}}}isComplete(){return!0}}class rh{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"unknown");const s=t.getLastFunctionCallSegment();s&&s.args.forEach(o=>{a.addEquivalence(t,o)}),a.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class ah{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"unknown");const s=t.withReturnValues();a.addType(s,"unknown")}isComplete(){return!0}}class sh{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>2)for(let o=2;o<s.args.length;o++){const i=s.args[o];a.addEquivalence(r.withElement("*"),i)}}isComplete(){return!0}}class oh{getReturnType(){return"number"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0)for(let o=0;o<s.args.length;o++)a.addEquivalence(r.withElement("*"),t.withParameter(o))}isComplete(){return!0}}class ih{getReturnType(){return"string"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}class lh{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class ch{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class dh{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"unknown"),a.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class uh{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class hh{getReturnType(){return"object"}addEquivalences(t,r,a){const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"array")}}isComplete(){return!0}}class mh{getReturnType(){return"string[]"}addEquivalences(t,r,a){a.addType(r,"string"),a.addType(t,"string[]"),a.addEquivalence(t.withReturnValues().withElement("*"),r)}isComplete(){return!0}}class ph{getReturnType(){return"unknown"}addEquivalences(t,r,a){const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r),a.addEquivalence(t.withProperty("functionCallReturnValue"),o.withProperty("returnValue"))}}isComplete(){return!0}}class fh{getReturnType(){return"unknown"}addEquivalences(t,r,a){t.getLastFunctionCallSegment()}isComplete(){return!0}}class gh{getReturnType(){return"array"}addEquivalences(t,r,a){const s=t.getLastFunctionCallSegment();if(a.addType(t.withParameter(1),"function"),s&&s.args.length>0){const o=s.args[0];a.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}function yh(){const e=new Qu;return e.register("filter",new Zu,"Array"),e.register("map",new lh,"Array"),e.register("flatMap",new ch,"Array"),e.register("join",new ih,"Array"),e.register("find",new th,"Array"),e.register("findLast",new uh,"Array"),e.register("at",new dh,"Array"),e.register("reduce",new nh,"Array"),e.register("concat",new rh,"Array"),e.register("slice",new ah,"Array"),e.register("splice",new sh,"Array"),e.register("push",new oh,"Array"),e.register("some",new Xu,"Array"),e.register("every",new eh,"Array"),e.register("fromEntries",new hh,"Object"),e.register("split",new mh,"String"),e.register("then",new ph,"Promise"),e.register("useState",new gh,"React"),e.register("useMemo",new fh,"React"),e}yh();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 xh=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),bh=new Set(["find","findLast","at","pop","shift"]),vh=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),wh=new Set([...xh,...bh,...vh]),Ch=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Nh=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Sh=new Set([...Ch,...Nh]);[...wh,...Sh];class Eh{constructor(t){this.depth=0,this.traceCount=0,this.defaultOutput=(r,a)=>{const s=" ".repeat(this.depth),o=this.timestamps?`[${Date.now()}] `:"";a?console.info(`${o}${s}${r}`,JSON.stringify(a)):console.info(`${o}${s}${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 Eh({enabled:!1});function wt(e,t){const r={added:{},removed:{},changed:{}},a=new Set(Object.keys(e??{})),s=new Set(Object.keys(t??{}));for(const o of s)a.has(o)||(r.added[o]=t[o]);for(const o of a)s.has(o)||(r.removed[o]=e[o]);for(const o of a)s.has(o)&&e[o]!==t[o]&&(r.changed[o]={from:e[o],to:t[o]});return r}function Ah(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function vn(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let kh=0;class la{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++kh,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,a){var d,h,u,m;if(!this.isEnabled())return;const s=this.traces.get(t);if(!s)return this.log(`snapshot: no trace for ${t}, creating one`),this.startEntity({name:t,entityType:"unknown",filePath:"unknown"}),this.snapshot(t,r,a);this.log(`snapshot: ${t} → ${r}`),this.currentStage=r;const o=JSON.parse(JSON.stringify(a)),i={stage:r,timestamp:Date.now(),data:o},c=s.stages[s.stages.length-1];if(c&&(i.diffFromPrevious={signatureSchema:wt(c.data.signatureSchema,o.signatureSchema),returnValueSchema:wt(c.data.returnValueSchema,o.returnValueSchema)},o.dependencySchemas||c.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const p=new Set([...Object.keys(o.dependencySchemas??{}),...Object.keys(c.data.dependencySchemas??{})]);for(const f of p){const y=(d=c.data.dependencySchemas)==null?void 0:d[f],g=(h=o.dependencySchemas)==null?void 0:h[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,C=(m=g==null?void 0:g[x])==null?void 0:m.returnValueSchema,w=wt(v,C);Ah(w)&&(i.diffFromPrevious.dependencySchemas[b]=w)}}}s.stages.push(i)}operation(t,r){if(!this.isEnabled())return;const a=this.traces.get(t);a&&a.operations.push({...r,stage:r.stage??this.currentStage??void 0,timestamp:Date.now()})}flush(){var d;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(h=>`${h}(${this.traces.get(h).stages.length})`).join(", ");this.log(`flush: writing ${t.length} entities: ${r}`);const a={},s=new Map;for(const[h,u]of this.traces){let m=0;for(const p of u.stages){if(!p.diffFromPrevious)continue;const y=`${((d=u.stages[u.stages.indexOf(p)-1])==null?void 0:d.stage)??"start"}→${p.stage}`;if(a[y]||(a[y]={added:0,removed:0,changed:0}),p.diffFromPrevious.signatureSchema){const g=p.diffFromPrevious.signatureSchema;a[y].added+=Object.keys(g.added).length,a[y].removed+=Object.keys(g.removed).length,a[y].changed+=Object.keys(g.changed).length,m+=vn(g)}if(p.diffFromPrevious.returnValueSchema){const g=p.diffFromPrevious.returnValueSchema;a[y].added+=Object.keys(g.added).length,a[y].removed+=Object.keys(g.removed).length,a[y].changed+=Object.keys(g.changed).length,m+=vn(g)}}s.set(h,m)}const o=[...s.entries()].sort((h,u)=>u[1]-h[1]).slice(0,10).map(([h])=>h),i={meta:{timestamp:new Date().toISOString(),projectSlug:this.projectSlug,entityCount:this.traces.size},summary:{stageChangeCounts:a,entitiesWithMostChanges:o},entities:Object.fromEntries(this.traces)},c=Z.dirname(this.outputPath);K.existsSync(c)||K.mkdirSync(c,{recursive:!0}),K.writeFileSync(this.outputPath,JSON.stringify(i,null,2)),this.log(`flush: wrote trace to ${this.outputPath}`)}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=K.readFileSync(t,"utf-8"),a=JSON.parse(r),s=new la({enabled:!1});s.projectSlug=a.meta.projectSlug;for(const[o,i]of Object.entries(a.entities))s.traces.set(o,i);return s}getSummary(){var s,o,i;const t={},r=new Map;for(const[c,d]of this.traces){let h=0;for(let u=1;u<d.stages.length;u++){const m=d.stages[u],f=`${((s=d.stages[u-1])==null?void 0:s.stage)??"start"}→${m.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(o=m.diffFromPrevious)!=null&&o.signatureSchema){const y=m.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,h+=vn(y)}if((i=m.diffFromPrevious)!=null&&i.returnValueSchema){const y=m.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,h+=vn(y)}}r.set(c,h)}const a=[...r.entries()].sort((c,d)=>d[1]-c[1]).slice(0,10).map(([c,d])=>({name:c,totalChanges:d}));return{entityCount:this.traces.size,stageChangeCounts:t,entitiesWithMostChanges:a}}getEntitySummary(t){const r=this.traces.get(t);return r?{entityName:t,stages:r.stages.map(a=>({stage:a.stage,diffFromPrevious:a.diffFromPrevious?{signatureSchema:a.diffFromPrevious.signatureSchema,returnValueSchema:a.diffFromPrevious.returnValueSchema}:void 0}))}:null}getOperations(t,r){const a=this.traces.get(t);return a?r?a.operations.filter(s=>s.path&&r.test(s.path)):a.operations:[]}tracePath(t,r){var o,i;const a=this.traces.get(t),s=[];if(!a)return{entityName:t,path:r,history:s};for(const c of a.stages){const d=(o=c.data.signatureSchema)==null?void 0:o[r],h=(i=c.data.returnValueSchema)==null?void 0:i[r],u=d??h;u!==void 0&&s.push({stage:c.stage,value:u})}for(const c of a.operations)c.path===r&&s.push({operation:c.operation,stage:c.stage,value:c.after??c.before,context:c.context});return{entityName:t,path:r,history:s}}getEntityTrace(t){return this.traces.get(t)}getEntityNames(){return[...this.traces.keys()]}findProperty(t,r){const a=this.traces.get(t);if(!a)return[];const s=[],o=new RegExp(`(^|\\.)${r}(\\.|\\[|$)`);for(const i of a.stages){for(const[c,d]of Object.entries(i.data.signatureSchema??{}))o.test(c)&&s.push({stage:i.stage,path:c,type:d,schemaType:"signature"});for(const[c,d]of Object.entries(i.data.returnValueSchema??{}))o.test(c)&&s.push({stage:i.stage,path:c,type:d,schemaType:"returnValue"});for(const[c,d]of Object.entries(i.data.dependencySchemas??{}))for(const[h,u]of Object.entries(d))for(const[m,p]of Object.entries(u.returnValueSchema??{}))o.test(m)&&s.push({stage:i.stage,path:`${c}/${h}::${m}`,type:p,schemaType:"dependency"})}return s}findTypeInconsistencies(t){const r=this.traces.get(t);if(!r)return[];let a=r.stages[r.stages.length-1];for(let d=r.stages.length-1;d>=0;d--)if(Object.keys(r.stages[d].data.dependencySchemas??{}).length>0){a=r.stages[d];break}if(!a)return[];const s=new Set(["length","toString","valueOf","constructor"]),o=new Map,i=(d,h)=>{const u=d.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!u)return;const m=u[1],p=u[2]==="[]";if(s.has(m))return;const f=m+(p?"[]":"");o.has(f)||o.set(f,[]),o.get(f).push({path:d,type:h})};for(const[,d]of Object.entries(a.data.dependencySchemas??{}))for(const[,h]of Object.entries(d))for(const[u,m]of Object.entries(h.returnValueSchema??{}))i(u,m);const c=[];for(const[d,h]of o)new Set(h.map(m=>m.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&c.push({propertyName:d,paths:h.map(m=>({...m,stage:a.stage}))});return c.sort((d,h)=>{const u=new Set(d.paths.map(p=>p.type)).size;return new Set(h.paths.map(p=>p.type)).size-u}),c}getStageDiffSummary(t,r,a){const s=this.traces.get(t);if(!s)return null;const o=s.stages.find(p=>p.stage===r),i=s.stages.find(p=>p.stage===a);if(!o||!i)return null;const c={added:[],removed:[],typeChanged:[]},d=o.data.returnValueSchema??{},h=i.data.returnValueSchema??{},u=new Set(Object.keys(d)),m=new Set(Object.keys(h));for(const p of m)u.has(p)?d[p]!==h[p]&&c.typeChanged.push({path:p,from:d[p],to:h[p]}):c.added.push(`${p}: ${h[p]}`);for(const p of u)m.has(p)||c.removed.push(`${p}: ${d[p]}`);return c}traceSchemaTransform(t,r,a,s,o){if(!this.enabled)return s(a),a;const i={...a};s(a);const c=wt(i,a);for(const[d,h]of Object.entries(c.added))this.operation(t,{operation:r,path:d,before:void 0,after:h,context:{...o,changeType:"added"}});for(const[d,h]of Object.entries(c.removed))this.operation(t,{operation:r,path:d,before:h,after:void 0,context:{...o,changeType:"removed"}});for(const[d,{from:h,to:u}]of Object.entries(c.changed))this.operation(t,{operation:r,path:d,before:h,after:u,context:{...o,changeType:"changed"}});return a}traceSchemaTransformResult(t,r,a,s,o){if(!this.enabled)return;const i=wt(a,s);for(const[c,d]of Object.entries(i.added))this.operation(t,{operation:r,path:c,before:void 0,after:d,context:{...o,changeType:"added"}});for(const[c,d]of Object.entries(i.removed))this.operation(t,{operation:r,path:c,before:d,after:void 0,context:{...o,changeType:"removed"}});for(const[c,{from:d,to:h}]of Object.entries(i.changed))this.operation(t,{operation:r,path:c,before:d,after:h,context:{...o,changeType:"changed"}})}traceDependencySchemaTransform(t,r,a,s,o="both"){if(!this.enabled){for(const i in a)for(const c in a[i]){const d=a[i][c];(o==="signature"||o==="both")&&d.signatureSchema&&s(d.signatureSchema),(o==="returnValue"||o==="both")&&d.returnValueSchema&&s(d.returnValueSchema)}return}for(const i in a)for(const c in a[i]){const d=a[i][c],h={filePath:i,dependencyName:c};(o==="signature"||o==="both")&&d.signatureSchema&&this.traceSchemaTransform(t,r,d.signatureSchema,s,{...h,schemaType:"signature"}),(o==="returnValue"||o==="both")&&d.returnValueSchema&&this.traceSchemaTransform(t,r,d.returnValueSchema,s,{...h,schemaType:"returnValue"})}}traceDependencySchemaChanges(t,r,a,s){var i;if(!this.enabled){s();return}const o={};for(const c in a){o[c]={};for(const d in a[c]){const h=a[c][d];o[c][d]={sig:{...h.signatureSchema||{}},rv:{...h.returnValueSchema||{}}}}}s();for(const c in a)for(const d in a[c]){const h=a[c][d],u=(i=o[c])==null?void 0:i[d],m={filePath:c,dependencyName:d};if(h.signatureSchema){const p=(u==null?void 0:u.sig)||{},f=wt(p,h.signatureSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...m,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:{...m,schemaType:"signature",changeType:"changed"}})}if(h.returnValueSchema){const p=(u==null?void 0:u.rv)||{},f=wt(p,h.returnValueSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...m,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:{...m,schemaType:"returnValue",changeType:"changed"}})}}}}function Ph(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const hs=new la({enabled:Ph(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{hs.isEnabled()&&hs.flush()});function Io(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 Cl.parse(e)}catch(r){const s=r.message.match(/invalid character .* at (\d+):(\d+)/);if(s){const o=parseInt(s[2],10);if(e.substring(o-2,o-1)==='"')return e=e.substring(0,o-2)+"\\"+e.substring(o-2),Io(e)}return null}}function _h({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:a}){let s="";return a&&a.length>0&&(s=`
119
- User-selected Execution Flow Values:
120
- The user has specifically requested these values be used in the scenario:
121
- ${a.map(o=>` - ${o.path}: ${o.value}${o.isCustom?" (custom value)":""}`).join(`
122
- `)}
123
-
124
- IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
125
- `),`Mock Scenario Data Structure:
126
- \`\`\`
127
- ${JSON.stringify(r,null,2)}
128
- \`\`\`
129
- Existing Mock Scenario Data:
130
- \`\`\`
131
- ${JSON.stringify(t,null,2)}
132
- \`\`\`
133
- ${s}
134
- New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
135
- `}function Mh({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}){const o=a.find(i=>i.name===Qn);return`Mock Scenario Data Structure:
136
- \`\`\`
137
- ${JSON.stringify({props:s.arguments,dataVariables:s.dataForMocks},null,2)}
138
- \`\`\`
139
-
140
- Existing Mock Scenario Data:
141
- \`\`\`
142
- ${JSON.stringify(a.map(i=>({name:i.name,data:qt(o.metadata.data,i.metadata.data)})),null,2)}
143
- \`\`\`
144
-
145
- Mock Scenario that should be edited: "${t}"
146
- ${r?`The portion of the data that should be edited:
147
- \`\`\`
148
- ${JSON.stringify(r,null,2)}
149
- \`\`\``:""}
150
-
151
- How this data should be changed: "${e}"
152
- `}async function Th({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,flowSelections:o,model:i}){const c=t?Mh({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}):_h({description:e,existingScenarios:a,scenariosDataStructure:s,flowSelections:o}),d=await Yr({type:"guessScenarioDataFromDescription",systemMessage:t?Ih(r):jh,prompt:c,model:i??$u});await Gu({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,model:i},...d.stats});const{completion:h}=d;return h?Io(h):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const jh=`
153
- You will be provided with a list of data secnarios for a component and the overall structure for the data. Additionally you'll receive a description for a new scenario written by the user.
154
-
155
- Your goal is to add one scenario to the list of existing scenarios by generating an english name, proper description, and a JSON data structure that describes the data that would be used in a scenario for the code.
156
-
157
- The data for the scenario will be merged with the "Default Scenario" data, so you don't need to replicate any data in the default scenario but must overwrite any data that should be different.
158
-
159
- You must respond with valid JSON following this format of this TS type definition:
160
- \`\`\`
161
- export type ScenarioData = {
162
- name: string;
163
- description: string;
164
- data: {
165
- mockData: { [key: string]: unknown };
166
- argumentsData: { [key: string]: unknown };
167
- };
168
- };
169
-
170
- \`\`\`
171
- `,Ih=e=>`
172
- You will be provided with a list of data secnarios for a component and the overall structure for the data. Additionally you'll receive a description for a new scenario written by the user.
173
-
174
- Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
175
- ${e?`
176
- We only want to edit a specific portion of the data, which is provided in the "The portion of the data that should be edited" section. You should only change the data that is provided in this section.`:""}
177
-
178
- Always return the complete data structure for the scenario, with both mockData and argumentsData, even if you only changed a small portion of the data.
179
-
180
- You must respond with valid JSON following this type definition:
181
- \`\`\`
182
- {
183
- data: {
184
- mockData: { [key: string]: unknown };
185
- argumentsData: { [key: string]: unknown };
186
- }
187
- }
188
- \`\`\`
189
- `;async function $h({request:e}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:a,scenariosDataStructure:s,editingMockName:o,editingMockData:i,flowSelections:c}=t;if(!r&&(!c||c.length===0))return B({error:"Missing required field: description or flowSelections"},{status:400});const d=await Th({description:r||"",existingScenarios:a??[],scenariosDataStructure:s,editingMockName:o,editingMockData:i,flowSelections:c}),h=(d==null?void 0:d.data)||d;return B({success:!0,data:h})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),B({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const Rh=Object.freeze(Object.defineProperty({__proto__:null,action:$h},Symbol.toStringTag,{value:"Module"}));async function Dh(e,t){const r=fe();if(!r)return{entityCalls:[],analysisCalls:[]};const a=Z.join(r,".codeyam","llm-calls");try{await Re.access(a)}catch{return{entityCalls:[],analysisCalls:[]}}const s=[],o=[];try{const c=(await Re.readdir(a)).filter(b=>b.endsWith(".json")),d=`${e}_`,h=t?`${t}_`:null,u=[],m=[];for(const b of c)b.startsWith(d)||h&&b.startsWith(h)?u.push(b):m.push(b);const p=u.map(async b=>{try{const v=Z.join(a,b),C=await Re.readFile(v,"utf-8");return JSON.parse(C)}catch{return null}}),f=m.map(async b=>{try{const v=Z.join(a,b),C=await Re.readFile(v,"utf-8"),w=JSON.parse(C);return w.object_id===e||t&&w.object_id===t?w:null}catch{return null}}),[y,g]=await Promise.all([Promise.all(p),Promise.all(f)]),x=[...y,...g].filter(b=>b!==null);for(const b of x)b.object_id===e?s.push(b):t&&b.object_id===t&&o.push(b);s.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:s,analysisCalls:o}}async function Lh({params:e,request:t}){const{entitySha:r}=e;if(!r)return B({error:"Entity SHA is required"},{status:400});const s=new URL(t.url).searchParams.get("analysisId")||void 0,o=await Dh(r,s);return B(o)}const Fh=Object.freeze(Object.defineProperty({__proto__:null,loader:Lh},Symbol.toStringTag,{value:"Module"}));function Oh(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=je("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return Yh(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function Yh(e){const t=e.trim().split(`
190
- `).filter(a=>a.length>0),r=[];for(const a of t){const s=a[0],o=a[1];let i=a.slice(2).replace(/^[ \t]+/,""),c,d=!1,h;if(s==="A"||o==="A")c="added",d=s==="A";else if(s==="M"||o==="M")c="modified",d=s==="M";else if(s==="D"||o==="D")c="deleted",d=s==="D";else if(s==="R"||o==="R"){c="renamed",d=s==="R";const u=i.indexOf(" -> ");u!==-1&&(h=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(c="untracked",d=!1):(c="modified",d=s!==" "&&s!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),m=ie.join(u,i);try{const p=(y,g)=>{const x=kt.readdirSync(y,{withFileTypes:!0}),b=[];for(const v of x){const C=ie.join(y,v.name),w=ie.relative(u,C);v.isDirectory()?b.push(...p(C,g)):v.isFile()&&b.push(w)}return b},f=p(m,u);for(const y of f)r.push({path:y,status:c,staged:d,...h&&{oldPath:h}})}catch(p){console.error(`Failed to expand directory ${i}:`,p)}}else r.push({path:i,status:c,staged:d,...h&&{oldPath:h}})}return r}function zh(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return je("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 Bh(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const a=je('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().match(/refs\/remotes\/origin\/(.+)/);if(a)return a[1];try{return je("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return je("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 Uh(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return je('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
191
- `).filter(a=>a.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function $o(){const e=fe();return e?Oh(e):[]}function Wh(){const e=fe();return e?zh(e):null}function Hh(){const e=fe();return e?Bh(e):"main"}function Jh(){const e=fe();return e?Uh(e):[]}function Ro(e,t){const r=fe();return r?Vh(e,t,r):[]}function Vh(e,t,r){const a=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return je(`git diff --name-status ${e}...${t}`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
192
- `).filter(i=>i.length>0).map(i=>{const c=i.split(" "),d=c[0];let h=c[1],u,m;return d==="A"?m="added":d==="M"?m="modified":d==="D"?m="deleted":d.startsWith("R")?(m="renamed",u=c[1],h=c[2]):m="modified",{path:h,status:m,...u&&{oldPath:u}}})}catch(s){return console.error("Failed to get branch diff:",s),[]}}function Gh(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let a="";try{a=je(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{a=""}let s="";try{s=kt.readFileSync(ie.join(r,e),"utf8")}catch(o){console.error(`Failed to read current file ${e}:`,o),s=""}return{oldContent:a,newContent:s,fileName:e}}catch(a){return console.error(`Failed to get diff for ${e}:`,a),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function qh(e){const t=fe();return t?Gh(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Kh(e,t,r,a){const s=a||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=je(`git show ${t}:"${e}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=je(`git show ${r}:"${e}"`,{cwd:s,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 An(e,t,r){const a=fe();return a?Kh(e,t,r,a):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function ms(e,t){var r,a;try{return((a=(r=je(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:r.toString())==null?void 0:a.trim())??null}catch(s){return console.error(`Failed to get commit SHA for ${e}:`,s),""}}function Qh(e,t,r,a){const s=Vn.createHash("sha256");return s.update(`${e}:${t}:${r}:${a}`),s.digest("hex").substring(0,16)}function Do(){const e=fe();if(!e)throw new Error("No project root found");const t=ie.join(e,".codeyam","cache","branch-entity-diff");return kt.existsSync(t)||kt.mkdirSync(t,{recursive:!0}),t}function Zh(e){try{const t=Do(),r=ie.join(t,`${e}.json`);if(!kt.existsSync(r))return null;const a=kt.readFileSync(r,"utf8");return JSON.parse(a)}catch(t){return console.error("Failed to read cache:",t),null}}function Xh(e,t){try{const r=Do(),a=ie.join(r,`${e}.json`);kt.writeFileSync(a,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function em(e,t,r){const a=$n(t,e),s=$n(r,e),o=new Map(a.map(u=>[u.name,u])),i=new Map(s.map(u=>[u.name,u])),c=[],d=[],h=[];for(const[u,m]of i){const p=o.get(u);p?p.sha!==m.sha&&d.push({name:u,baseSha:p.sha,compareSha:m.sha,entityType:m.entityType}):c.push(m)}for(const[u,m]of o)i.has(u)||h.push(m);return{filePath:e,newEntities:c,modifiedEntities:d,deletedEntities:h}}function tm(e,t){const r=fe();if(!r)throw new Error("No project root found");const a=ms(e,r),s=ms(t,r);if(!a||!s)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=Qh(e,t,a,s),i=Zh(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const c=Ro(e,t),d=[];for(const u of c)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const m=An(u.path,e,t),p=$n(m.oldContent,u.path);d.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:p})}else if(u.status==="added"){const m=An(u.path,e,t),p=$n(m.newContent,u.path);d.push({filePath:u.path,newEntities:p,modifiedEntities:[],deletedEntities:[]})}else{const m=An(u.path,e,t),p=em(u.path,m.oldContent,m.newContent);(p.newEntities.length>0||p.modifiedEntities.length>0||p.deletedEntities.length>0)&&d.push(p)}const h={baseBranch:e,compareBranch:t,baseCommitSha:a,compareCommitSha:s,fileComparisons:d,cacheKey:o,computedAt:new Date().toISOString()};return Xh(o,h),h}function nm({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),a=t.searchParams.get("compare");if(!r||!a)return B({error:"Missing required parameters: base and compare"},{status:400});const s=tm(r,a);return B(s)}catch(t){return console.error("Failed to compute branch entity diff:",t),B({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const rm=Object.freeze(Object.defineProperty({__proto__:null,loader:nm},Symbol.toStringTag,{value:"Module"}));async function am({request:e}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:a,projectId:s,viewportWidth:o=1440}=t;if(!r||!a||!s)return B({error:"Missing required fields: serverUrl, scenarioId, and projectId"},{status:400});console.log(`[Capture] URL to capture: ${r}`),console.log(`[Capture] Scenario ID from request: ${a}`);const i=fe();if(!i)return B({error:"Project root not found"},{status:500});const c=Z.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:r,scenarioId:a,projectId:s,projectRoot:i,viewportWidth:o}),h=await new Promise(p=>{const f=Z.join(i,".codeyam","db.sqlite3"),y=Gn("npx",["tsx",c,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let g="",x="";y.stdout.on("data",b=>{const v=b.toString();g+=v;const C=v.trim().split(`
193
- `);for(const w of C)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=>{p(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),p({success:!1,output:"",error:b.message})})});if(!h.success)return B({error:"Failed to capture screenshot",details:h.error},{status:500});const u=h.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return B({error:"Failed to parse capture result"},{status:500});const m=JSON.parse(u[1]);return B(m)}catch(t){return console.error("[Capture] Error:",t),B({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const sm=Object.freeze(Object.defineProperty({__proto__:null,action:am},Symbol.toStringTag,{value:"Module"}));async function om(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await Le();const a=await ot({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const s=ke(),o=a.entitySha,i=await s.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let c={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?c=JSON.parse(i.metadata):c=i.metadata),c.defaultWidth=t,await s.updateTable("entities").set({metadata:JSON.stringify(c)}).where("sha","=",o).execute(),console.log(`[recapture] Updated defaultWidth for entity ${o} to ${t}`),!a.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=a.scenarios)==null?void 0:f.length)||0} scenarios`),await Ft(e,y=>{if(y){if(y.readyToBeCaptured=!0,y.scenarios)for(const g of y.scenarios)delete g.finishedAt,delete g.startedAt,delete g.screenshotStartedAt,delete g.screenshotFinishedAt,delete g.interactiveStartedAt,delete g.interactiveFinishedAt,delete g.error,delete g.errorStack;delete y.finishedAt}}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const d=fe();if(!d)throw new Error("Project root not found");const h=Z.join(d,".codeyam","config.json"),u=JSON.parse(K.readFileSync(h,"utf8")),{projectSlug:m}=u;if(!m)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:m,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${p}`),{jobId:p}}async function im(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await Le();const a=await ot({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);if(!a.commit)throw new Error(`Commit not found for analysis ${e}`);const s=(u=a.scenarios)==null?void 0:u.find(m=>m.id===t);if(!s)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: ${s.name}`),await Ft(e,m=>{if(m&&(m.readyToBeCaptured=!0,delete m.finishedAt,m.scenarios)){const p=m.scenarios.find(f=>f.name===s.name);p&&(delete p.finishedAt,delete p.startedAt,delete p.error,delete p.errorStack,delete p.screenshotStartedAt,delete p.screenshotFinishedAt,delete p.interactiveStartedAt,delete p.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${s.name} for recapture`);const o=fe();if(!o)throw new Error("Project root not found");const i=Z.join(o,".codeyam","config.json"),c=JSON.parse(K.readFileSync(i,"utf8")),{projectSlug:d}=c;if(!d)throw new Error("Project slug not found in config");const{jobId:h}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:d,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${h}`),{jobId:h}}async function lm({request:e,context:t}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await lt()),!r)return B({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s||!o)return B({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${s}, scenario ${o}`);const i=await im(s,o,r);return console.log("[API] Scenario recapture queued",i),B({success:!0,message:"Scenario recapture queued",...i})}catch(a){return console.log("[API] Error during scenario recapture:",a),B({error:"Failed to recapture scenario",details:a instanceof Error?a.message:String(a)},{status:500})}}const cm=Object.freeze(Object.defineProperty({__proto__:null,action:lm},Symbol.toStringTag,{value:"Module"})),dm=/<system-reminder>[\s\S]*?<\/system-reminder>/g,ps=2e3;function um(){return`/private/tmp/claude-501/-${(fe()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const hm="/tmp/claude-rule-markers";function mm(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||""),a=String(t.path||"");return a?`"${r}" in ${a}`:`"${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 pm=["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 fm(e){const t=[],r=new Set;for(const a of e)if(!(a.type!=="tool_call"||!a.name||!a.input)){if(a.name==="Write"||a.name==="Edit"){const s=String(a.input.file_path||"");if(s.includes(".claude/rules/")){const o=s.replace(/^.*?(\.claude\/rules\/)/,"$1"),i=`${a.name}:${o}`;r.has(i)||(r.add(i),a.name==="Write"?t.push({action:"created",filePath:o,content:String(a.input.content||"")}):t.push({action:"modified",filePath:o,oldString:String(a.input.old_string||""),newString:String(a.input.new_string||"")}))}}else if(a.name==="Bash"){const s=String(a.input.command||"");if(s.includes("codeyam memory touch")){const o=`touch:${s}`;r.has(o)||(r.add(o),t.push({action:"touched",filePath:s}))}}}return t}function gm(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const a of pm)if(r.includes(a))return!0}return!1}function ym(e){const t=[],r={};for(const a of e){const s=a.trim();if(!s)continue;let o;try{o=JSON.parse(s)}catch{continue}const i=o.type;if(i==="progress"||i==="system"||i==="result")continue;const d=(o.message||{}).content,h=o.timestamp||"";if(i==="user"){if(typeof d=="string")t.push({type:"user_prompt",text:d,timestamp:h,agent_id:String(o.agentId||o.session_id||"unknown"),slug:String(o.slug||"")});else if(Array.isArray(d)){for(const u of d)if(typeof u=="object"&&u!==null&&u.type==="tool_result"){const m=u,p=String(m.tool_use_id||"");let f=m.content;const y=!!m.is_error;typeof f=="string"&&(f=f.replace(dm,"").trim()),t.push({type:"tool_result",tool_use_id:p,tool_name:r[p]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:y,timestamp:h})}}}else if(i==="assistant"&&Array.isArray(d))for(const u of d){if(typeof u!="object"||u===null)continue;const m=u;if(m.type==="text"){const p=String(m.text||"").trim();p&&t.push({type:"assistant_text",text:p,timestamp:h})}else if(m.type==="tool_use"){const p=String(m.id||""),f=String(m.name||"unknown"),y=m.input||{};r[p]=f,t.push({type:"tool_call",tool_use_id:p,name:f,input:y,timestamp:h})}}}return t}function xm(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}async function bm({request:e}){var t;try{const a=((t=new URL(e.url).searchParams.get("search"))==null?void 0:t.toLowerCase())||"",s=um(),o=hm,i=[];if(It(s)){const d=await Va(s);for(const h of d)if(h.endsWith(".output")){const u=ie.join(s,h),m=await Ga(u);i.push({filePath:u,stem:h.replace(".output",""),mtime:m.mtimeMs})}}if(It(o)){const d=await Va(o);for(const h of d)if(h.endsWith(".log")){const u=ie.join(o,h),m=await Ga(u);i.push({filePath:u,stem:h.replace(".log",""),mtime:m.mtimeMs})}}i.sort((d,h)=>h.mtime-d.mtime);const c=[];for(const d of i){const u=(await tn(d.filePath,"utf-8")).split(`
194
- `),m=ym(u);if(m.length===0)continue;const p=m.find(N=>N.type==="user_prompt"),f=d.stem;let y=(p==null?void 0:p.slug)||"",g=(p==null?void 0:p.timestamp)||"";g||(g=new Date(d.mtime).toISOString());let x;if(d.filePath.endsWith(".log")){d.stem.endsWith("-stale")?y=y||"rule-reflection/stale":d.stem.endsWith("-conversation")?y=y||"rule-reflection/conversation":d.stem.endsWith("-interruption")?y=y||"rule-reflection/interruption":y=y||"rule-reflection";const N=d.filePath.replace(/\.log$/,".context");if(It(N))try{x=await tn(N,"utf-8")}catch{}}const b=m.filter(N=>N.type==="tool_call").length,v=m.filter(N=>N.type==="assistant_text").length;for(const N of m)N.type==="tool_call"&&N.name&&N.input&&(N.summary=mm(N.name,N.input));if(a&&!(f.toLowerCase().includes(a)||y.toLowerCase().includes(a)||m.some(S=>xm(S,a))))continue;for(const N of m)N.type==="tool_result"&&N.content&&N.content.length>ps&&(N.truncated=!0,N.fullLength=N.content.length,N.content=N.content.slice(0,ps));const C=fm(m),w=gm(m);c.push({id:f,slug:y,timestamp:g,stats:{toolCalls:b,textBlocks:v},entries:m,context:x,ruleChanges:C,hasConfusion:w})}return Response.json({agents:c})}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 vm=Object.freeze(Object.defineProperty({__proto__:null,loader:bm},Symbol.toStringTag,{value:"Module"}));async function wm({params:e,request:t}){const{projectSlug:r}=e;if(!r)return new Response("Project slug is required",{status:400});if(t.method!=="DELETE")return new Response("Method not allowed",{status:405});const a=nr(r);try{return await Gt(a,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(s){console.error("[api.logs] Error clearing log file:",s);const o=s instanceof Error?s.message:String(s);return new Response(`Error clearing log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function Cm({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=nr(t);try{if(!It(r))return new Response("No logs available yet. Analysis may not have started.",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});const a=await tn(r,"utf-8");return!a||a.trim().length===0?new Response("Log file is empty. Waiting for analysis to start...",{headers:{"Content-Type":"text/plain; charset=utf-8"}}):new Response(a,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(a){console.error("[api.logs] Error reading log file:",a);const s=a instanceof Error?a.message:String(a);return new Response(`Error reading log file: ${s}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const Nm=Object.freeze(Object.defineProperty({__proto__:null,action:wm,loader:Cm},Symbol.toStringTag,{value:"Module"}));async function Sm(e,t){var o,i,c,d,h,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await Le();const r=await ot({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const a=(o=r.scenarios)==null?void 0:o.find(m=>m.id===t);if(!a)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${a.name}`);const s={returnValue:{status:"success",data:((d=(c=(i=a.metadata)==null?void 0:i.data)==null?void 0:c.argumentsData)==null?void 0:d[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(h=a.metadata)==null?void 0:h.data)==null?void 0:u.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),s}async function Em({request:e}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),a=t.get("scenarioId");if(!r||!a)return B({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${a}`);const s=await Sm(r,a);return console.log("[API] Function execution completed successfully"),B({success:!0,result:s})}catch(t){return console.log("[API] Error during function execution:",t),B({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const Am=Object.freeze(Object.defineProperty({__proto__:null,action:Em},Symbol.toStringTag,{value:"Module"}));function km({request:e}){return B({status:"ok"})}async function Pm({request:e,context:t}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await lt()),!r)return console.error("[Interactive Mode API] Queue not initialized"),B({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("action"),o=a.get("analysisId"),i=a.get("scenarioId");if(!s||!o)return B({error:"Missing required fields: action and analysisId"},{status:400});if(s!=="start"&&s!=="stop")return B({error:'Invalid action. Must be "start" or "stop"'},{status:400});const c=await $e();if(console.log("[Interactive Mode API] projectSlug:",c),!c)return B({error:"Project not initialized"},{status:500});if(s==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:c});return B({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:c});return B({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:d})}}catch(a){console.error("[Interactive Mode API] Error:",a);const s=a instanceof Error?a.message:String(a),o=a instanceof Error?a.stack:void 0;return console.error("[Interactive Mode API] Error stack:",o),B({error:"Failed to control interactive mode",details:s},{status:500})}}const _m=Object.freeze(Object.defineProperty({__proto__:null,action:Pm,loader:km},Symbol.toStringTag,{value:"Module"}));async function Mm({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,screenshotPaths:a}=t;if(!r)return Response.json({error:"Missing required field: scenarioId"},{status:400});if(console.log(`[API] Deleting scenario ${r}`),a&&a.length>0){const s=fe();if(s)for(const o of a){const i=ie.join(s,".codeyam","captures","screenshots",o);try{await pe.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(c){console.log(`[API] Could not delete screenshot ${i}:`,c instanceof Error?c.message:c)}}}return await vc({ids:[r]}),console.log(`[API] Scenario ${r} deleted successfully`),Response.json({success:!0,message:"Scenario deleted successfully"})}catch(t){return console.error("[API] Error deleting scenario:",t),Response.json({error:"Failed to delete scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const Tm=Object.freeze(Object.defineProperty({__proto__:null,action:Mm},Symbol.toStringTag,{value:"Module"})),rn="/tmp/codeyam",zr=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",Lo=500,jm=Lo*1024*1024;function Nt(e,t){try{return je(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function kn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Fo(e){return Nt("config user.email",e)}function Im(e){const t=Z.join(e,".codeyam","debug-report.md");if(!K.existsSync(t))return null;try{return K.readFileSync(t,"utf8")}catch{return null}}function $m(e,t=20){const r=Z.join(rn,"local-dev",e,"codeyam","log.txt");if(!K.existsSync(r))return[];try{return K.readFileSync(r,"utf8").split(`
195
- `).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function Rm(e){try{const t=await fetch(`${zr}/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 Dm(e,t){try{je(`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 Lm(e){const{projectRoot:t,projectSlug:r,outputPath:a,metadata:s,screenshot:o,onProgress:i}=e,c=i||(()=>{}),d=Date.now(),h=Z.join(rn,`delta-staging-${d}`),u=Z.join(h,"delta");K.mkdirSync(u,{recursive:!0});try{const m=Nt("diff --binary HEAD",t)||"";K.writeFileSync(Z.join(u,"tracked.patch"),m?m+`
196
- `:"");const p=Nt("ls-files --others --exclude-standard",t);if(p){const x=Z.join(u,"untracked");K.mkdirSync(x,{recursive:!0});for(const b of p.split(`
197
- `).filter(Boolean)){const v=Z.join(t,b),C=Z.join(x,b);if(K.existsSync(v)){const w=Z.dirname(C);K.mkdirSync(w,{recursive:!0}),K.statSync(v).isFile()&&K.copyFileSync(v,C)}}}const f=Z.join(t,".codeyam");if(K.existsSync(f)){const x=Z.join(u,"codeyam");K.cpSync(f,x,{recursive:!0})}K.writeFileSync(Z.join(u,"meta.json"),JSON.stringify(s,null,2));const y=Z.join(rn,"local-dev",r,"codeyam","log.txt");K.existsSync(y)?K.copyFileSync(y,Z.join(u,"codeyam-log.txt")):K.writeFileSync(Z.join(u,"codeyam-log.txt"),`# Log file not found
198
- `);const g=Z.join(t,".codeyam","debug-report.md");K.existsSync(g)&&(K.copyFileSync(g,Z.join(u,"debug-report.md")),c("Debug report included")),o&&o.length>0&&(K.writeFileSync(Z.join(u,"screenshot.jpg"),o),c(`Screenshot included (${kn(o.length)})`));try{je(`tar -czf "${a}" -C "${h}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{K.rmSync(h,{recursive:!0,force:!0})}}async function Fm(e){const{projectRoot:t,projectSlug:r,feedback:a,screenshot:s,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const c=Nt("rev-parse HEAD",t);if(!c)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const d=Nt("rev-parse --abbrev-ref HEAD",t)||"unknown",h=Nt("status --porcelain",t),u=Nt("remote get-url origin",t),m=h!==null&&h.length>0,p=Co(r),f=Im(t);let y=a;f&&(y={...a||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /codeyam-diagnose workflow"));const g={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:c,branch:d,isDirty:m,remoteUrl:u},versions:{cli:p.cliVersion,webserver:p.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:y},x=Date.now(),b=Z.join(rn,`base-${c}-${x}.tar.gz`),v=Z.join(rn,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const C=await Rm(c);let w=null;C?i("Server already has base, skipping..."):(i("Generating base archive..."),Dm(t,b),w=K.statSync(b).size,i(`Base archive: ${kn(w)}`)),i("Generating delta archive..."),Lm({projectRoot:t,projectSlug:r,outputPath:v,metadata:g,screenshot:s,onProgress:o});const S=K.statSync(v).size;i(`Delta archive: ${kn(S)}`);const k=(w||0)+S;if(k>jm)throw K.existsSync(b)&&K.unlinkSync(b),K.unlinkSync(v),new Error(`Bundle too large: ${kn(k)} (max: ${Lo} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:C?null:b,deltaPath:v,metadata:g,baseSha:c,baseSize:w,deltaSize:S}}async function Om(e){const{basePath:t,deltaPath:r,projectSlug:a,metadata:s,baseSha:o,deltaSize:i,onProgress:c}=e,d=c||(()=>{}),h=K.statSync(r),u=t?K.statSync(t):null,m=h.size+((u==null?void 0:u.size)||0);d("Requesting upload URLs...");const p=await fetch(`${zr}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:a,fileSizeBytes:m,baseSha:o,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:s.timestamp,git:s.git,versions:s.versions,system:s.system,feedback:s.feedback}})});if(!p.ok){const C=await p.json();throw new Error(C.error||`Server returned ${p.status}`)}const{reportId:f,deltaUploadUrl:y,baseUploadUrl:g}=await p.json(),x=[];if(t&&g){d("Uploading base...");const C=K.readFileSync(t);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:C}).then(w=>{if(!w.ok)throw new Error(`Base upload failed: ${w.status}`)}))}d("Uploading delta...");const b=K.readFileSync(r);x.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:b}).then(C=>{if(!C.ok)throw new Error(`Delta upload failed: ${C.status}`)})),await Promise.all(x),d("Confirming upload...");const v=await fetch(`${zr}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!v.ok){const C=await v.json();throw new Error(C.error||`Confirm failed: ${v.status}`)}return t&&K.existsSync(t)&&K.unlinkSync(t),K.unlinkSync(r),{bundleId:f}}async function Ym({request:e}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),a=t.get("description"),s=t.get("email"),o=t.get("source"),i=t.get("entitySha"),c=t.get("scenarioId"),d=t.get("analysisId"),h=t.get("currentUrl"),u=t.get("entityName"),m=t.get("entityType"),p=t.get("scenarioName"),f=t.get("errorMessage"),y=t.get("screenshot");let g=a||void 0;!g&&u&&(p?g=`Issue on ${u} scenario "${p}"`:g=`Issue on ${u}`);let x;if(y&&y.size>0){const k=await y.arrayBuffer();x=Buffer.from(k),console.log(`[Bundle] Screenshot received: ${y.size} bytes`)}const b=fe();if(!b)return B({error:"Project root not found"},{status:500});const v=await $e();if(!v)return B({error:"Project slug not found"},{status:500});const C={issueType:r||"other",description:g,email:s||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:c||void 0,analysisId:d||void 0,currentUrl:h||void 0,recentActivity:$m(v,20),entityName:u||void 0,entityType:m||void 0,scenarioName:p||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${v}...`),console.log(`[Bundle] Context: ${C.source}, issue: ${C.issueType}`);const w=await Fm({projectRoot:b,projectSlug:v,feedback:C,screenshot:x,onProgress:k=>{console.log(`[Bundle] ${k}`)}}),N=(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 Om({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}`),B({success:!0,reportId:S.bundleId,size:N})}catch(t){return console.error("[Bundle] Error:",t),B({error:t.message||"Failed to generate bundle"},{status:500})}}function zm(){const e=fe(),t=e?Fo(e):null;return B({defaultEmail:t})}const Bm=Object.freeze(Object.defineProperty({__proto__:null,action:Ym,loader:zm},Symbol.toStringTag,{value:"Module"}));function Et(){const e=process.memoryUsage(),t=Sl.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(Rr.totalmem()/1024/1024),freeMemory:Math.round(Rr.freemem()/1024/1024)}}}function Um(){const e=Et();console.log(`
199
- [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 Wm(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=Et();global.gc();const t=Et(),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 Hm(){const e=Et(),t=e.heap.usedHeapSize/e.heap.heapSizeLimit*100,r={highHeapUsage:t>80,highExternalMemory:e.process.external>200,highArrayBuffers:e.process.arrayBuffers>100,nearHeapLimit:e.heap.totalAvailableSize<100},a=[];return r.highHeapUsage&&a.push(`High heap usage: ${t.toFixed(1)}% of limit`),r.highExternalMemory&&a.push(`High external memory: ${e.process.external} MB`),r.highArrayBuffers&&a.push(`High ArrayBuffer usage: ${e.process.arrayBuffers} MB`),r.nearHeapLimit&&a.push(`Near heap limit: only ${e.heap.totalAvailableSize} MB available`),{indicators:r,warnings:a,hasIssues:a.length>0}}function Jm({request:e}){const r=new URL(e.url).searchParams.get("action");try{switch(r){case"snapshot":return Response.json({success:!1,error:"Heap snapshots are disabled because they block the server for several minutes. Use action=leaks instead."},{status:400});case"gc":{const a=Wm(),s=Et();return Response.json({success:a,message:a?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:s})}case"detailed":{const a=Um();return Response.json({success:!0,stats:a})}case"leaks":{const a=Hm(),s=Et();return Response.json({success:!0,leakCheck:a,stats:s})}default:{const a=Et();return Response.json({success:!0,stats:a,actions:{gc:"/api/memory-profile?action=gc - Force garbage collection (requires --expose-gc)",detailed:"/api/memory-profile?action=detailed - Log detailed stats to console",leaks:"/api/memory-profile?action=leaks - Check for memory leak indicators"}})}}}catch(a){return console.error("[Memory API] Error:",a),Response.json({success:!1,error:a.message},{status:500})}}const Vm=Object.freeze(Object.defineProperty({__proto__:null,loader:Jm},Symbol.toStringTag,{value:"Module"})),wn=qr(Gr);async function Gm({request:e}){const r=new URL(e.url).searchParams.get("pids");if(!r)return Response.json({error:"Missing pids parameter"},{status:400});const a=r.split(",").map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o));if(a.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const s=await Promise.all(a.map(async o=>{const i=qm(o),c=i?await Km(o):null;return{pid:o,isRunning:i,processName:c}}));return Response.json({processes:s})}function qm(e){try{return process.kill(e,0),!0}catch{return!1}}async function Km(e){if(process.platform==="win32")try{const{stdout:r}=await wn(`tasklist /FI "PID eq ${e}" /FO CSV /NH`),a=r.match(/"([^"]+)"/);if(!a)return null;const s=a[1];if(s.toLowerCase()==="node.exe")try{const{stdout:o}=await wn(`wmic process where "ProcessId=${e}" get CommandLine /FORMAT:LIST`),i=o.match(/codeyam-(\w+)/);if(i)return`codeyam-${i[1]}`}catch{}return s}catch{return null}try{const{stdout:r}=await wn(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:a}=await wn(`ps -p ${e} -o args=`),s=a.trim(),o=s.match(/codeyam-(\w+)/);return o?`codeyam-${o[1]}`:s.split(" ")[0]||null}catch{return null}}}const Qm=Object.freeze(Object.defineProperty({__proto__:null,loader:Gm},Symbol.toStringTag,{value:"Module"})),Zm=qn(import.meta.url),Xm=Z.dirname(Zm);function ep({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=So(),r=fe()||(t==null?void 0:t.projectRoot);if(!r)throw new Error("Could not determine project root");const a=(t==null?void 0:t.port)||3111,s=Z.join(Xm,"..","..","..","..","webserver","bootstrap.js"),o=Z.join(r,".codeyam","logs");K.existsSync(o)||K.mkdirSync(o,{recursive:!0});const i=K.openSync(Z.join(o,"background-server.log"),"a"),c=K.openSync(Z.join(o,"background-server-error.log"),"a"),d=new Date().toISOString();K.appendFileSync(Z.join(o,"background-server.log"),`
200
- [${d}] Server restart requested via dashboard
201
- `),Ed();const h=Gn("node",[s],{detached:!0,stdio:["ignore",i,c],env:{...process.env,CODEYAM_PORT:a.toString(),CODEYAM_ROOT_PATH:r,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});h.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${h.pid})`);const u=new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}});return setTimeout(()=>{console.log("[api.restart-server] Exiting old server process"),process.exit(0)},100),u}catch(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 tp=Object.freeze(Object.defineProperty({__proto__:null,action:ep},Symbol.toStringTag,{value:"Module"}));async function np({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:a}=t;if(!r||!a)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${r.id}`),console.log(`[API] Received ${a.length} scenarios to save`),a.forEach((c,d)=>{var m,p,f,y,g;const h=(p=(m=c.metadata)==null?void 0:m.data)==null?void 0:p.argumentsData,u=Array.isArray(h)&&h.length>0?JSON.stringify(h[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${d}: ${c.name}`,{id:c.id,projectId:c.projectId,analysisId:c.analysisId,hasMetadata:!!c.metadata,hasData:!!((f=c.metadata)!=null&&f.data),mockDataKeys:(g=(y=c.metadata)==null?void 0:y.data)!=null&&g.mockData?Object.keys(c.metadata.data.mockData):[],argumentsDataLength:Array.isArray(h)?h.length:"not-array",argumentsDataPreview:u})});const s=a.map(c=>({...c,projectId:c.projectId||r.projectId,analysisId:c.analysisId||r.id})),o=await Lc(s);if(!o||o.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${o.length} scenarios to database`),o.forEach((c,d)=>{var u,m;const h=(m=(u=c.metadata)==null?void 0:u.data)==null?void 0:m.argumentsData;console.log(`[API] Saved scenario ${d}: ${c.name}`,{id:c.id,argumentsDataLength:Array.isArray(h)?h.length:"not-array"})});const i={...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 rp=Object.freeze(Object.defineProperty({__proto__:null,action:np},Symbol.toStringTag,{value:"Module"})),ap=()=>[{title:"Agent Transcripts - CodeYam"},{name:"description",content:"View background agent transcripts and tool call history"}];async function sp({request:e}){try{const r=new URL(e.url).searchParams.get("search")||"",a=new URL(`/api/agent-transcripts${r?`?search=${encodeURIComponent(r)}`:""}`,e.url),o=await(await fetch(a.toString())).json();return o.error?B({agents:[],error:o.error,search:r}):B({agents:o.agents||[],error:null,search:r})}catch(t){return console.error("Failed to load agent transcripts:",t),B({agents:[],error:"Failed to load agent transcripts",search:""})}}function op(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 ip(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 Pn({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"},a={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:a[e]||e})}function lp({input:e}){return n("div",{className:"text-xs font-mono space-y-1",children:Object.entries(e).map(([t,r])=>{let a=typeof r=="string"?r:JSON.stringify(r);return a.length>500&&(a=a.slice(0,500)+"..."),l("div",{children:[l("span",{className:"text-[#f4a261] font-bold",children:[t,":"]})," ",n("span",{className:"text-gray-700",children:a})]},t)})})}function cp({content:e,truncated:t,fullLength:r}){const[a,s]=P(!1);return l("div",{children:[l("pre",{className:"whitespace-pre-wrap break-words text-xs max-h-96 overflow-y-auto text-gray-700",children:[e,t&&!a&&"..."]}),t&&n("button",{onClick:()=>s(!a),className:"text-[11px] text-gray-500 hover:text-gray-700 mt-1 font-mono cursor-pointer",children:a?"Show less":`Show more (${(r||0)-e.length} more chars)`})]})}function dp({entry:e,pairedResult:t}){const[r,a]=P(!1),s=op(e.timestamp||"");return e.type==="user_prompt"?l("div",{className:"my-2",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(Pn,{type:"user_prompt"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:s})]}),n("pre",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#00b4d8] max-h-72 overflow-y-auto text-gray-800",children:e.text})]}):e.type==="assistant_text"?l("div",{className:"my-2",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(Pn,{type:"assistant_text"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:s})]}),n("div",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-sm border-l-[3px] border-l-[#a8dadc] text-gray-800",children:e.text})]}):e.type==="tool_call"?l("div",{className:"my-2",children:[l("button",{onClick:()=>a(!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(mt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n(Lt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n(Pn,{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:s})]}),r&&l("div",{className:"bg-white border border-t-0 border-gray-200 rounded-b-md px-3 py-2 border-l-[3px] border-l-[#f4a261]",children:[n(lp,{input:e.input||{}}),t&&l("div",{className:"mt-3 pt-3 border-t border-gray-200",children:[l("div",{className:"text-[11px] font-bold uppercase tracking-wide text-[#2a9d8f] mb-1",children:["Result",t.is_error?" (Error)":"",":"]}),n(cp,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function up({change:e}){const[t,r]=P(!1),a=e.action==="created"?!!e.content:e.action==="modified"?!!(e.oldString||e.newString):!1;return l("li",{children:[n("button",{onClick:()=>a&&r(!t),className:`text-left w-full ${a?"hover:text-green-900 cursor-pointer":""}`,children:l("span",{className:"inline-flex items-center gap-1",children:[a&&(t?n(mt,{className:"w-3 h-3 inline flex-shrink-0"}):n(Lt,{className:"w-3 h-3 inline flex-shrink-0"})),e.action==="created"?"Created":"Modified"," ",e.filePath]})}),t&&e.action==="created"&&e.content&&n("pre",{className:"mt-1 mb-2 ml-4 p-2 bg-white border border-green-200 rounded text-[11px] text-gray-700 whitespace-pre-wrap break-words max-h-64 overflow-y-auto",children:e.content}),t&&e.action==="modified"&&l("div",{className:"mt-1 mb-2 ml-4 space-y-1",children:[e.oldString&&l("pre",{className:"p-2 bg-red-50 border border-red-200 rounded text-[11px] text-red-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["- ",e.oldString]}),e.newString&&l("pre",{className:"p-2 bg-green-50 border border-green-300 rounded text-[11px] text-green-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["+ ",e.newString]})]})]})}function hp({changes:e}){const t=e.filter(a=>a.action==="touched"),r=e.filter(a=>a.action!=="touched");return l("div",{className:"my-2 bg-green-50 border border-green-200 rounded-md p-3",children:[n("div",{className:"text-xs font-bold text-green-800 mb-1",children:"Rule Changes:"}),l("ul",{className:"text-xs text-green-700 space-y-0.5 font-mono",children:[r.map((a,s)=>n(up,{change:a},s)),t.length>0&&l("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function mp({agent:e,defaultOpen:t}){const[r,a]=P(t),[s,o]=P(!1),[i,c]=P(null),d=re(()=>{const x={};for(const b of e.entries)b.type==="tool_result"&&b.tool_use_id&&(x[b.tool_use_id]=b);return x},[e.entries]),h=re(()=>{const x=new Set;for(const b of e.entries)b.type==="tool_call"&&b.tool_use_id&&d[b.tool_use_id]&&x.add(b.tool_use_id);return x},[e.entries,d]),u=x=>{x.stopPropagation(),o(!0),c(null),fetch("/api/save-fixture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e.id})}).then(b=>b.json()).then(b=>{b.success?c(`Saved to ${b.fixturePath}`):c(`Error: ${b.error}`)}).catch(b=>{c(`Error: ${b instanceof Error?b.message:String(b)}`)}).finally(()=>{o(!1)})},m=(e.ruleChanges||[]).filter(x=>x.action!=="touched"),p=(e.ruleChanges||[]).filter(x=>x.action==="touched"),f=m.length>0,y=p.length>0,g=f||y;return l("div",{className:`bg-white border rounded-lg overflow-hidden mb-4 ${f?"border-green-300":"border-gray-200"}`,children:[l("button",{onClick:()=>a(!r),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:[r?n(mt,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n(Lt,{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}),f&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-green-100 text-green-800",children:[n(Hr,{className:"w-3 h-3"}),m.length===1?"1 rule changed":`${m.length} rules changed`]}),!f&&y&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-gray-100 text-gray-500",children:[p.length," timestamp",p.length!==1?"s":""," ","touched"]}),e.hasConfusion&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-100 text-amber-800",children:[n(_n,{className:"w-3 h-3"}),"Confusion Detected"]}),l("span",{className:"text-[11px] text-gray-400 font-mono",children:[e.stats.toolCalls," tool calls, ",e.stats.textBlocks," text blocks"]}),l("span",{className:"text-[11px] text-gray-400 font-mono ml-auto flex items-center gap-2",children:[ip(e.timestamp),f&&l("button",{onClick:u,disabled:s,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(Ui,{className:"w-3 h-3"}),s?"Saving...":"Save Fixture"]})]})]}),i&&n("div",{className:`px-4 py-2 text-xs font-mono ${i.startsWith("Error")?"bg-red-50 text-red-700":"bg-green-50 text-green-700"}`,children:i}),r&&l("div",{className:"px-4 pb-4 border-t border-gray-100",children:[g&&n(hp,{changes:e.ruleChanges}),e.context&&l("div",{className:"my-2",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(Pn,{type:"context"}),n("span",{className:"text-xs text-gray-500",children:"Input context given to the agent"})]}),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.context})]}),e.entries.map((x,b)=>{if(x.type==="tool_result"&&x.tool_use_id&&h.has(x.tool_use_id))return null;const v=x.type==="tool_call"&&x.tool_use_id?d[x.tool_use_id]:void 0;return n(dp,{entry:x,pairedResult:v},`${e.id}-${b}`)})]})]})}const pp=De(function(){const{agents:t,error:r,search:a}=Be(),s=Mt(),[o,i]=P(a),[c,d]=P(!1),[h,u]=P(0);Xe({source:"agent-transcripts-page"});const m=f=>{f.preventDefault(),window.location.href=`/agent-transcripts${o?`?search=${encodeURIComponent(o)}`:""}`},p=()=>{d(!c),u(f=>f+1)};return r?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:r})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[l("div",{className:"flex items-center gap-3 mb-1",children:[n("button",{onClick:()=>{s("/memory")},className:"text-gray-600 hover:text-[#005C75] transition-colors cursor-pointer",title:"Back to Memory","aria-label":"Back to Memory",children:n(Bi,{className:"w-5 h-5"})}),n(Mn,{className:"w-6 h-6 text-[#232323]"}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Agent Transcripts"})]}),n("p",{className:"text-[15px] text-gray-500 ml-14",children:"View background agent transcripts and tool call history"})]}),l("div",{className:"flex items-center gap-4 mb-6",children:[l("form",{onSubmit:m,className:"relative flex-1 max-w-md",children:[n(on,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:o,onChange:f=>i(f.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:p,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:c?"Collapse All":"Expand All"})]}),l("div",{className:"text-sm text-gray-500 mb-4",children:[t.length," agent",t.length!==1?"s":""," found",a&&l("span",{children:[" ","matching “",a,"”",n(se,{to:"/agent-transcripts",className:"text-[#005C75] hover:underline ml-2",children:"Clear"})]})]}),t.length===0?l("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(Mn,{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(f=>n(mp,{agent:f,defaultOpen:c},f.id))},h)]})})}),fp=Object.freeze(Object.defineProperty({__proto__:null,default:pp,loader:sp,meta:ap},Symbol.toStringTag,{value:"Module"}));async function gp({request:e}){try{const t=await e.json(),{pid:r,signal:a="SIGTERM",commitSha:s}=t;if(!r||typeof r!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!fs(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,a)}catch(u){return Response.json({error:"Failed to kill process",pid:r,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,c=500,d=Date.now();let h=!0;for(;h&&Date.now()-d<i;)await new Promise(u=>setTimeout(u,c)),h=fs(r);if(h){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(s)try{await ut({commitSha:s,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:a,message:`Process ${r} killed successfully`,waitedMs:Date.now()-d})}catch(t){return console.error("Error in kill-process API:",t),Response.json({error:"Internal server error",details:t instanceof Error?t.message:String(t)},{status:500})}}function fs(e){try{return process.kill(e,0),!0}catch{return!1}}const yp=Object.freeze(Object.defineProperty({__proto__:null,action:gp},Symbol.toStringTag,{value:"Module"})),xp=qn(import.meta.url),bp=ie.dirname(xp),gs="/tmp/claude-rule-markers",vp=ie.resolve(bp,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function wp(e){const t=[],r=new Set;for(const a of e.split(`
202
- `)){const s=a.trim();if(!s)continue;let o;try{o=JSON.parse(s)}catch{continue}if(o.type!=="assistant")continue;const i=o.message;if(!(!i||!Array.isArray(i.content)))for(const c of i.content){if(typeof c!="object"||c===null)continue;const d=c;if(d.type!=="tool_use")continue;const h=String(d.name||""),u=d.input||{};if(h==="Write"||h==="Edit"){const m=String(u.file_path||"");if(m.includes(".claude/rules/")){const p=m.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${h}:${p}`;r.has(f)||(r.add(f),t.push({action:h==="Write"?"created":"modified",filePath:p}))}}else if(h==="Bash"){const m=String(u.command||"");if(m.includes("codeyam memory touch")){const p=`touch:${m}`;r.has(p)||(r.add(p),t.push({action:"touched",filePath:m}))}}}}return t}async function Cp({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 a=ie.join(gs,`${r}.log`);if(!It(a))return Response.json({error:`Log file not found: ${a}`},{status:404});const s=await tn(a,"utf-8"),o=ie.join(gs,`${r}.context`);let i=null;if(It(o))try{i=await tn(o,"utf-8")}catch{}const c=wp(s),h=i?["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(y=>i.toLowerCase().includes(y)):!1,u=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":r.endsWith("-interruption")?"-int":"",m=r.slice(0,8)+u,p=ie.join(vp,m);await dl(p,{recursive:!0}),await Gt(ie.join(p,"agent-log.jsonl"),s),i&&await Gt(ie.join(p,"context.md"),i),await Gt(ie.join(p,"rule-changes.json"),JSON.stringify(c,null,2)),await Gt(ie.join(p,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:h,ruleChangeCount:c.length},null,2));const f=ie.relative(process.cwd(),p);return console.log(`[api.save-fixture] Saved fixture to ${f}`),Response.json({success:!0,fixturePath:f})}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 Np=Object.freeze(Object.defineProperty({__proto__:null,action:Cp},Symbol.toStringTag,{value:"Module"}));async function Sp({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=fe();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const a=ie.join(r,".codeyam","captures","screenshots",t);try{await pe.access(a);const s=await pe.readFile(a),o=ie.extname(a).toLowerCase(),i=o===".png"?"image/png":o===".jpg"||o===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(s,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const Ep=Object.freeze(Object.defineProperty({__proto__:null,loader:Sp},Symbol.toStringTag,{value:"Module"})),ys={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 ca({type:e,className:t=""}){const r=ys[e]||ys.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 Ap={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 Cn({variant:e,pid:t,label:r,className:a=""}){const s=Ap[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] ${a}`,style:{backgroundColor:s.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:s.borderColor,height:"20px"},children:n("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:s.textColor},children:o})})}function ze({screenshotPath:e,cacheBuster:t,alt:r,className:a="",title:s}){const[o,i]=P("loading"),[c,d]=P(!1),h=Ne(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,m=()=>{i("success"),d(!0)},p=()=>{i("error"),d(!1)};return ee(()=>{i("loading"),d(!1);const f=h.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[u]),e?l("div",{className:"relative w-full h-full flex items-center justify-center",title:s,children:[n("img",{ref:h,src:u,alt:r,onLoad:m,onError:p,className:a||"max-w-full max-h-full object-contain",style:{visibility:c?"visible":"hidden",position:c?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&l("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:s,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}let xs=!1;function kp(){if(xs)return;const e=document.createElement("style");e.textContent=`
203
- @keyframes strongPulse {
204
- 0%, 100% { opacity: 0.2; }
205
- 50% { opacity: 1; }
206
- }
207
- `,document.head.appendChild(e),xs=!0}function da({size:e="medium",className:t=""}){typeof document<"u"&&kp();const r={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:a,centerDotSize:s,gap:o}=r[e];return l("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${o}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}const Pp=()=>[{title:"Activity - CodeYam"},{name:"description",content:"View analysis activity and queue status"}];async function _p({request:e,context:t,params:r}){var z,Y,R,A,H,W,J,ae;let a=t.analysisQueue;a||(a=await lt());const s=new URL(e.url),o=parseInt(s.searchParams.get("page")||"1",10),i=20,c=r.tab||"current";if(!a)return B({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:c,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const d=a.getState(),h=await $e();let u=null;if(h&&((z=d==null?void 0:d.currentlyExecuting)!=null&&z.commitSha)){const{project:$,branch:I}=await Ie(h),D=await Rn({projectId:$.id,branchId:I.id,shas:[d.currentlyExecuting.commitSha]});u=D&&D.length>0?D[0]:null}else u=await Ot();const m=async $=>{const I=await Dt($);if(!I)return null;const{getAnalysesForEntity:D}=await Promise.resolve().then(()=>Xc),q=await D($,!1);return{...I,analyses:q||[]}},p=await Promise.all(((d==null?void 0:d.jobs)||[]).map(async $=>{const I=[];if($.entityShas&&$.entityShas.length>0){const D=$.entityShas.map(te=>m(te)),q=await Promise.all(D);I.push(...q.filter(te=>te!==null))}return{...$,entities:I}}));let f=null;if(d!=null&&d.currentlyExecuting){const $=d.currentlyExecuting,I=[];if($.entityShas&&$.entityShas.length>0){const D=$.entityShas.map(te=>m(te)),q=await Promise.all(D);I.push(...q.filter(te=>te!==null))}f={...$,entities:I}}const y=f?p.filter($=>$.id!==f.id):p,g=((R=(Y=u==null?void 0:u.metadata)==null?void 0:Y.currentRun)==null?void 0:R.currentEntityShas)||[],b=(await Promise.all(g.map($=>m($)))).filter($=>$!==null),v=[];if(h)try{const{project:$,branch:I}=await Ie(h),D=await Rn({projectId:$.id,branchId:I.id,limit:100});for(const q of D){const te=((A=q.metadata)==null?void 0:A.historicalRuns)||[];v.push(...te)}}catch($){console.error("[activity.tsx] Failed to load historical runs from commits:",$)}const C=[...v].sort(($,I)=>{const D=$.lastCaptureAt||$.analysisCompletedAt||$.archivedAt||$.createdAt||"";return(I.lastCaptureAt||I.analysisCompletedAt||I.archivedAt||I.createdAt||"").localeCompare(D)}),w=(o-1)*i,N=w+i,S=C.slice(w,N),k=Math.ceil(C.length/i),M=await Promise.all(S.map(async $=>{const I=$.currentEntityShas||[];if(I.length===0)return{...$,entities:[]};const D=await Promise.all(I.map(q=>m(q)));return{...$,entities:D.filter(q=>q!==null)}})),j=!!f,L=y.length,F=C.filter($=>{const I=!!$.failedAt,D=$.readyToBeCaptured,q=$.capturesCompleted??0,te=D===void 0?!0:D===0||q>=D;return!I&&!!$.analysisCompletedAt&&te}),_=new Set(((H=f==null?void 0:f.entities)==null?void 0:H.map($=>$.sha))||[]),E=F.filter($=>!($.currentEntityShas||[]).some(D=>_.has(D))),O=(await Promise.all(E.slice(0,3).map(async $=>{const I=$.currentEntityShas||[];if(I.length===0)return{run:$,entities:[]};const D=await Promise.all(I.map(q=>m(q)));return{run:$,entities:D.filter(q=>q!==null)}}))).flatMap(({run:$,entities:I})=>I.map(D=>({...D,runId:$.id,completedAt:$.lastCaptureAt||$.analysisCompletedAt||$.archivedAt||$.createdAt})));let G=[],V=null,U=null;if((J=(W=u==null?void 0:u.metadata)==null?void 0:W.currentRun)!=null&&J.analysisCompletedAt&&b.length>0){const $=b[0].sha;V=b[0];const I=await Xn($);I&&I.length>0&&I[0].scenarios&&(G=I[0].scenarios,U=I[0].status)}return B({state:{...d,jobs:y,currentlyExecuting:f},currentRun:(ae=u==null?void 0:u.metadata)==null?void 0:ae.currentRun,historicalRuns:M,totalHistoricalRuns:C.length,currentPage:o,totalPages:k,projectSlug:h,commitSha:u==null?void 0:u.sha,queueJobs:y,currentlyExecuting:f,currentEntities:b,tab:c,hasCurrentActivity:j,queuedCount:L,recentCompletedEntities:O,hasMoreCompletedRuns:E.length>3,currentEntityScenarios:G,currentEntityForScenarios:V,currentAnalysisStatus:U})}function Mp({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:a}){const s=[{id:"current",label:"Current Activity",hasContent:t,count:t?1:null},{id:"queued",label:"Queued Activity",hasContent:r>0,count:r},{id:"historic",label:"Historic Activity",hasContent:a>0,count:a}];return n("div",{className:"border-b border-gray-200 mb-6",children:n("nav",{className:"flex gap-8",children:s.map(o=>{const i=e===o.id;return n(se,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
208
- relative pb-4 px-2 text-sm transition-colors cursor-pointer
209
- ${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
210
- `,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[o.label,o.count!==null&&o.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
211
- inline-block w-2 h-2 rounded-full
212
- ${i?"":"bg-gray-400"}
213
- `,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function Tp({currentlyExecuting:e,currentRun:t,state:r,projectSlug:a,commitSha:s,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:c,currentEntityScenarios:d,currentEntityForScenarios:h,currentAnalysisStatus:u}){var T,O,G,V;const[m,p]=P({}),[f,y]=P({isKilling:!1,current:0,total:0}),g=at(),x=!!e,b=(e==null?void 0:e.entities)||[],v=!!(t!=null&&t.analysisCompletedAt),C=v&&!!(t!=null&&t.capturePid),w=!v,N=x,S=d||[],{lastLine:k}=ft(a,N);ee(()=>{if(!t)return;const U=[t.analyzerPid,t.capturePid].filter(A=>!!A);if(U.length===0)return;let z=!0;const Y=async()=>{try{const H=await(await fetch(`/api/process-status?pids=${U.join(",")}`)).json();if(H.processes&&z){const W={};H.processes.forEach(J=>{W[J.pid]={isRunning:J.isRunning,processName:J.processName}}),p(W)}}catch(A){z&&console.error("Failed to fetch process statuses:",A)}};Y();const R=setInterval(()=>void Y(),5e3);return()=>{z=!1,clearInterval(R)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[M,j]=P(!1),[L,F]=P(!1);ee(()=>{b.length<=3&&M&&j(!1)},[b.length,M]),ee(()=>{i.length<=3&&L&&F(!1)},[i.length,L]);const _=M?b:b.slice(0,3),E=b.length>3;return l("div",{className:"flex flex-col gap-[45px]",children:[N?l("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"1px solid #e0e9ec"},children:[l("div",{className:"flex items-center gap-2 mb-[15px]",children:[n(Ze,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:C?"Capturing...":"Analyzing..."})]}),_.map(U=>l("div",{className:"bg-white border border-[#e1e1e1] rounded-[4px] mb-[15px]",style:{height:"60px",padding:"0 15px",display:"flex",alignItems:"center",justifyContent:"space-between",boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1)"},children:[l("div",{className:"flex items-center gap-3",children:[n("div",{children:n(Je,{type:U.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col gap-[1px]",children:[l("div",{className:"flex items-center gap-[14px]",children:[n(se,{to:`/entity/${U.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:U.name}),U.entityType&&n(ca,{type:U.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:U.filePath,children:U.filePath})]})]}),n("button",{onClick:o,className:"px-[10px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},children:"View Logs"})]},U.sha)),E&&!M&&l("button",{onClick:()=>j(!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"]}),M&&E&&n("button",{onClick:()=>j(!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"}),C&&S&&S.length>0&&h&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:S.map(U=>{var J,ae,$,I;if(!U.id)return null;const z=(ae=(J=U.metadata)==null?void 0:J.screenshotPaths)==null?void 0:ae[0],Y=($=U.metadata)==null?void 0:$.noScreenshotSaved,R=z&&!Y,A=(I=u==null?void 0:u.scenarios)==null?void 0:I.find(D=>D.name===U.name),W=A&&A.screenshotStartedAt&&!A.screenshotFinishedAt||!R&&!Y;return n(se,{to:`/entity/${h.sha}/scenarios/${U.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:W?"#f9f9f9":void 0,borderColor:W?"#efefef":"#ccc"},children:R?n(ze,{screenshotPath:z,alt:U.name,className:"w-full h-full object-contain bg-gray-100"}):W?n("div",{className:"w-full h-full flex items-center justify-center",children:n(da,{size:"medium"})}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},U.id)})}),k&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:k}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.capturePid))&&l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-2",children:[l("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(t==null?void 0:t.analyzerPid)&&n(Cn,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(w||((T=m[t.analyzerPid])==null?void 0:T.isRunning))&&n(Cn,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(Cn,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(C||((O=m[t.capturePid])==null?void 0:O.isRunning))&&n(Cn,{variant:"running"})]}),(((G=m[t==null?void 0:t.analyzerPid])==null?void 0:G.isRunning)||((V=m[t==null?void 0:t.capturePid])==null?void 0:V.isRunning))&&n("button",{onClick:()=>{const U=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(R=>{var A;return!!R&&((A=m[R])==null?void 0:A.isRunning)});if(U.length===0)return;const z=U.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${z})?`))return;y({isKilling:!0,current:1,total:U.length}),(async()=>{for(let R=0;R<U.length;R++){const A=U[R];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:A,commitSha:s||""})})}catch(H){console.error(`Failed to kill process ${A}:`,H)}R<U.length-1&&y({isKilling:!0,current:R+2,total:U.length})}y({isKilling:!1,current:0,total:0}),g.revalidate()})()},disabled:f.isKilling,className:"px-[8px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:"#991b1b",color:"white",fontSize:"12px",lineHeight:"15px",fontWeight:500,height:"27px",width:"114px"},children:f.isKilling?"Killing...":"Kill All Processes"})]})]}):l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Ds,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Current Activity"}),l("p",{className:"text-sm",style:{color:"#8e8e8e"},children:["There are no analyses running. Trigger one from"," ",n(se,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(se,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),l(se,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]}),i&&i.length>0&&l("div",{children:[n("h3",{className:"font-mono uppercase",style:{fontSize:"12px",lineHeight:"18px",color:"#8e8e8e",marginBottom:"16px",fontWeight:500,letterSpacing:"0.05em"},children:"Recently Completed Analyses"}),l("div",{className:"flex flex-col gap-4",children:[(L?i:i.slice(0,3)).map(U=>{var R;const z=(R=U.analyses)==null?void 0:R[0],Y=(z==null?void 0:z.scenarios)||[];return z==null||z.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:l("div",{className:"flex flex-col gap-[15px]",children:[l("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",children:n(Je,{type:U.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[l("div",{className:"flex items-center gap-[5px]",children:[n(se,{to:`/entity/${U.sha}`,className:"hover:underline cursor-pointer",title:U.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:U.name}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:"#e8ffe6",color:"#00925d",fontSize:"12px",lineHeight:"16px",fontWeight:400},children:U.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:U.filePath,children:U.filePath})]}),n("div",{className:"flex-1"}),n("div",{className:"flex-shrink-0",children:n("button",{onClick:o,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:A=>{A.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:A=>{A.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),Y.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:Y.map(A=>{var ae,$,I;if(!A.id)return null;const H=($=(ae=A.metadata)==null?void 0:ae.screenshotPaths)==null?void 0:$[0],W=(I=A.metadata)==null?void 0:I.noScreenshotSaved,J=H&&!W;return l("div",{className:"shrink-0 flex flex-col gap-2",children:[n(se,{to:`/entity/${U.sha}/scenarios/${A.id}`,className:"block cursor-pointer",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{backgroundColor:J?"#f3f4f6":"#FAFAFA",borderColor:J?"#d1d5db":"#BCCDD3",borderStyle:J?"solid":"dashed"},onMouseEnter:D=>{J&&(D.currentTarget.style.borderColor="#005C75",D.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:D=>{D.currentTarget.style.borderColor=J?"#d1d5db":"#BCCDD3",D.currentTarget.style.boxShadow="none"},children:J?n(ze,{screenshotPath:H,alt:A.name,className:"max-w-full max-h-full object-contain"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})})}),n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:A.name})]},A.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},U.sha)}),i.length>3&&!L&&l("button",{onClick:()=>F(!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"]}),L&&i.length>3&&n("button",{onClick:()=>F(!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 jp({queueJobs:e,state:t,currentRun:r}){if(!e||e.length===0)return l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Wi,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Queued Jobs"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Analysis jobs will appear here when they are queued but not yet started."})]})]}),l(se,{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[a,s]=P(null),[o,i]=P(null),[c,d]=P(null),[h,u]=P(!1),[m,p]=P(!1),[f,y]=P(new Set),g=at();ee(()=>{e.length<=3&&m&&p(!1)},[e.length,m]);const x=S=>{s(S)},b=(S,k)=>{S.preventDefault(),i(k)},v=async(S,k)=>{if(S.preventDefault(),!a){i(null);return}const M=e.findIndex(F=>F.id===a);if(M===-1){s(null),i(null);return}if(M===k){s(null),i(null);return}const j=M<k?"down":"up",L=Math.abs(k-M);u(!0);try{for(let F=0;F<L;F++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:a,direction:j})});g.revalidate()}catch(F){console.error("Failed to reorder job:",F)}finally{u(!1),s(null),i(null)}},C=()=>{h||(s(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)}},N=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 l("div",{children:[l("div",{className:"flex items-center justify-between mb-4",children:[l("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:[e.length," Queued Job",e.length!==1?"s":""]}),e.length>0&&n("button",{onClick:()=>void N(),className:"px-[10px] py-0 rounded transition-colors cursor-pointer hover:bg-red-300",style:{backgroundColor:"#ffdcd9",color:"#ef4444",fontSize:"12px",fontWeight:500,height:"29px"},children:"Cancel All"})]}),l("div",{className:"flex flex-col gap-3",children:[(m?e:e.slice(0,3)).map(S=>{var E,T,O,G;const k=e.findIndex(V=>V.id===S.id),M=c===k,j=a===S.id,L=o===k,F=f.has(S.id),_=((E=S.entities)==null?void 0:E.length)>0?F?S.entities:S.entities.slice(0,3):[];return l("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:j||h?.5:1,transform:L&&a!==null&&!j?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:h?"not-allowed":j?"grabbing":"grab"},onMouseEnter:()=>d(k),onMouseLeave:()=>d(null),draggable:!h,onDragStart:V=>{x(S.id),V.dataTransfer.effectAllowed="move"},onDragOver:V=>b(V,k),onDrop:V=>void v(V,k),onDragEnd:C,children:[l("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(Hi,{size:16,style:{color:"#005C75"}}),l("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",k+1]})]}),l("div",{className:"flex flex-col gap-2 mt-8",children:[_.length>0?l(he,{children:[_.map(V=>n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(Je,{type:V.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(se,{to:`/entity/${V.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:V.name}),V.entityType&&n(ca,{type:V.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:V.filePath})]})]})})},V.sha)),((T=S.entities)==null?void 0:T.length)>3&&n("button",{onClick:()=>{y(V=>{const U=new Set(V);return U.has(S.id)?U.delete(S.id):U.add(S.id),U})},className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"40px",fontSize:"12px",color:"#646464",fontWeight:500},children:F?"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:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(Tn,{size:18,style:{color:"#8e8e8e"}})}),l("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((O=S.entityNames)==null?void 0:O[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:((G=S.filePaths)==null?void 0:G[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")})]})]})})}),l("div",{className:"flex items-center justify-end gap-2 mt-1",children:[M&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(Ji,{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&&!m&&l("button",{onClick:()=>p(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",e.length-3," more"," ",e.length-3===1?"job":"jobs"]}),m&&e.length>3&&n("button",{onClick:()=>p(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})}function Ip({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:a,tab:s,onShowLogs:o}){if(t===0)return l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Vi,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Historic Activity"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Completed analyses will appear here for historical reference."})]})]}),l(se,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[i,c]=P(!1),d=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(m=>{d.push({...m,runCreatedAt:u.createdAt})})});const h=i?d:d.slice(0,3);return l("div",{className:"flex flex-col gap-4",children:[h.map(u=>{var y;const m=(y=u.analyses)==null?void 0:y[0],p=(m==null?void 0:m.scenarios)||[],f=!u.isUncommitted;return l("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[l("div",{className:"flex items-start justify-between mb-3",children:[l("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{children:n(Je,{type:u.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(se,{to:`/entity/${u.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:u.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:f?"#e8ffe6":"#fef3cd",color:f?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:f?"Up to date":"Out of date"})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},title:u.filePath,children:u.filePath})]})]}),n("button",{onClick:o,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),p.length>0&&l("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[p.slice(0,8).map(g=>{var C,w,N;if(!g.id)return null;const x=(w=(C=g.metadata)==null?void 0:C.screenshotPaths)==null?void 0:w[0],b=(N=g.metadata)==null?void 0:N.noScreenshotSaved,v=x&&!b;return n(se,{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(ze,{screenshotPath:x,alt:g.name,className:"w-full h-full object-cover bg-gray-100"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},g.id)}),p.length>8&&l("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",p.length-8," more"]})]})]},`${u.sha}-${u.runCreatedAt}`)}),d.length>3&&!i&&l("button",{onClick:()=>c(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",d.length-3," more"," ",d.length-3===1?"entity":"entities"]}),i&&d.length>3&&n("button",{onClick:()=>c(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})}const $p=De(function(){const t=Be(),r=Is(),[a,s]=P(!1);Xe({source:"activity-page"});const o=r.tab||"current";return t?l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-[15px] text-gray-500",children:"View queued, current, and historical analysis activity."})]}),n(Mp,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(Tp,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>s(!0),recentCompletedEntities:t.recentCompletedEntities||[],hasMoreCompletedRuns:t.hasMoreCompletedRuns||!1,currentEntityScenarios:t.currentEntityScenarios||[],currentEntityForScenarios:t.currentEntityForScenarios,currentAnalysisStatus:t.currentAnalysisStatus}),o==="queued"&&n(jp,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(Ip,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>s(!0)}),a&&t.projectSlug&&n(ht,{projectSlug:t.projectSlug,onClose:()=>s(!1)})]}):n("div",{className:"px-20 py-12",children:n("div",{className:"text-center",children:n("p",{className:"text-gray-600",children:"Loading..."})})})}),Rp=Object.freeze(Object.defineProperty({__proto__:null,default:$p,loader:_p,meta:Pp},Symbol.toStringTag,{value:"Module"}));async function Oo(e,t,r){var w,N;await Le();const a=await ot({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw new Error(`Analysis ${e} not found`);if(!a.commit)throw new Error(`Commit not found for analysis ${e}`);const s=fe();if(!s)throw new Error("Project root not found");const o=Z.join(s,".codeyam","config.json"),i=JSON.parse(K.readFileSync(o,"utf8")),{projectSlug:c}=i;if(!c)throw new Error("Project slug not found in config");const d=nr(c);try{K.writeFileSync(d,"","utf8")}catch{}const{project:h}=await Ie(c),u=((w=h.metadata)==null?void 0:w.packageManager)||"npm",m=3112,p=it(c),f=((N=h.metadata)==null?void 0:N.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${c}`);const y=i.environmentVariables||[],g=xc({filePath:a.filePath,webapps:f,environmentVariables:y,port:m,packageManager:u});await Ft(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:a.commit.sha,projectSlug:c,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:p}]},{heading:"What's Happening",items:[{content:"1. Preparing analyzer and dependencies"},{content:"2. Syncing project files"},{content:"3. Setting up mock environment"}]},{heading:"Next Steps (Once Complete)",items:[{label:"1. Open the project directory",content:`code ${p}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:b,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${m}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:p,projectSlug:c,port:m,packageManager:u,framework:g.framework,instructions:v}}async function Dp({request:e,context:t}){const r=new URL(e.url),a=r.searchParams.get("analysisId"),s=r.searchParams.get("scenarioId")||void 0;if(!a)return B({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 lt()),!o)return B({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:a,scenarioId:s});try{const i=await Oo(a,s,o);return B({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),B({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function Lp({request:e,context:t}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await lt()),!r)return B({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s)return B({error:"Missing required field: analysisId"},{status:400});const i=await Oo(s,o,r);return B({...i,success:!0,message:"Debug setup queued"})}catch(a){console.error("[Debug Setup API] Error during debug setup:",a);const s=a instanceof Error?a.message:String(a),o=a instanceof Error?a.stack:void 0;return console.error("[Debug Setup API] Error stack:",o),B({error:"Failed to setup debug environment",details:s},{status:500})}}const Fp=Object.freeze(Object.defineProperty({__proto__:null,action:Lp,loader:Dp},Symbol.toStringTag,{value:"Module"})),Op=process.env.LABS_UNLOCK_SALT||"codeyam-labs-default-salt";function Yo(e){const t=pl("sha256",Op);return t.update(e),`CY-${t.digest("hex").slice(0,16)}`}function Yp(e,t){return t===Yo(e)}async function zp({request:e}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});try{const r=(await e.formData()).get("unlockCode");if(!r)return B({success:!1,error:"Unlock code is required"},{status:400});const a=await $e();return a?Yp(a,r)?(await Ln({projectSlug:a,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),B({success:!0})):B({success:!1,error:"Invalid unlock code"},{status:400}):B({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("[Labs Unlock] Error:",t),B({success:!1,error:"Failed to validate unlock code. Please try again."},{status:500})}}const Bp=Object.freeze(Object.defineProperty({__proto__:null,action:zp},Symbol.toStringTag,{value:"Module"}));async function Up({request:e,context:t}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await lt()),!r)return B({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("defaultWidth");if(!s||!o)return B({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return B({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${s} with width ${i}`);const c=await om(s,i,r);return console.log("[API] Recapture queued",c),B({success:!0,message:"Recapture queued",...c})}catch(a){return console.log("[API] Error during recapture:",a),B({error:"Failed to recapture screenshots",details:a instanceof Error?a.message:String(a)},{status:500})}}const Wp=Object.freeze(Object.defineProperty({__proto__:null,action:Up},Symbol.toStringTag,{value:"Module"}));function Hp(e,t){var i,c,d,h,u;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,a=e.analyses&&e.analyses.length>0&&e.analyses.some(m=>m.scenarios&&m.scenarios.length>0);if(!r){const m=!!((c=e.metadata)!=null&&c.previousVersionWithAnalyses),p=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return m||p?a?{state:"committed_no_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Committed - Simulations Outdated",color:"text-orange-700",bgColor:"bg-orange-50",borderColor:"border-orange-300",icon:"⚠"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Yet Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}:a?{state:"committed_with_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up to date",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"✓"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}const s=!!((d=e.metadata)!=null&&d.previousCommittedSha);if(!!((h=e.metadata)!=null&&h.previousVersionWithAnalyses)||s){const m=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return a&&!m?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:a?{state:"uncommitted_outdated_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Edited - Simulations Outdated",color:"text-amber-700",bgColor:"bg-amber-50",borderColor:"border-amber-300",icon:"⚠"}}:{state:"uncommitted_outdated_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}else return a?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:{state:"uncommitted_no_previous_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"New",color:"text-purple-700",bgColor:"bg-purple-50",borderColor:"border-purple-200",icon:"+"}}}function Jp(e){return Hp(e).hasOutdatedSimulations}function lr(e,t,r,a,s){var V,U,z,Y,R,A,H,W;const o=(V=t==null?void 0:t.scenarios)==null?void 0:V.find(J=>J.name===e.name),i=!!(o!=null&&o.startedAt),c=!!(o!=null&&o.screenshotStartedAt),d=!!(o!=null&&o.screenshotFinishedAt),h=!!(o!=null&&o.finishedAt),u=1800*1e3,m=c&&!d&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,p=!!((z=(U=e.metadata)==null?void 0:U.screenshotPaths)!=null&&z[0])||!!((Y=e.metadata)!=null&&Y.executionResult),f=c&&!d,y=o==null?void 0:o.error,g=(A=(R=e.metadata)==null?void 0:R.executionResult)==null?void 0:A.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const J of t.errors)x.push({source:`${J.phase} phase`,message:J.message});if(t!=null&&t.steps)for(const J of t.steps)J.error&&x.push({source:J.name,message:J.error});const b=!p&&!y&&!g&&x.length>0,v=!!(y||g||m||b),C=m?"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=m?"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=(a&&s?s.jobs.some(J=>{var ae;return((ae=J.entityShas)==null?void 0:ae.includes(a))||J.type==="analysis"&&J.entityShas&&J.entityShas.length===0})||((W=(H=s.currentlyExecuting)==null?void 0:H.entityShas)==null?void 0:W.includes(a)):!1)&&!i&&!v||!!(o!=null&&o.analyzing)&&!i&&!v,k=i&&!c&&!h&&!v,M=(S||k||f)&&!v,j=(S||k)&&r===!1&&!p;let L;j?L="crashed":v?L="error":p||h?L="completed":f?L="capturing":k?L="starting":S?L="queued":L="pending";let F="📷",_="pending",E=!1,T=`Not captured: ${e.name}`;const O="border-gray-300",G=v||j?"bg-red-50":"bg-white";return v||j?(F="⚠️",_="error",T=`Error: ${j?"Analysis process crashed":C||"Unknown error"}`):S?(F="⋯",_="queued",T=`Queued: ${e.name}`):k?(F="⋯",_="starting",E=!0,T=`Starting server for ${e.name}...`):f&&!v?(F="⋯",_="capturing",E=!0,T=`Capturing ${e.name}...`):p&&(F="✓",_="completed",T=e.name),{hasError:v||j,errorMessage:j?"Analysis process crashed":C,errorStack:j?"Process terminated unexpectedly before completing analysis":w,isCapturing:f,isCaptured:p,hasCrashed:j,isAnalyzing:M,isQueued:S,isServerStarting:k,status:L,icon:F,iconType:_,shouldSpin:E,title:T,borderColor:O,bgColor:G}}function zo({scenario:e,entitySha:t,size:r="medium",showBorder:a=!0,isOutdated:s=!1}){var w,N,S,k,M,j;const o=lr(e,void 0,void 0,t,void 0),i=(w=e.metadata)==null?void 0:w.executionResult,c=!!i,h=(((S=(N=e.metadata)==null?void 0:N.data)==null?void 0:S.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,m=((M=(k=i==null?void 0:i.sideEffects)==null?void 0:k.consoleOutput)==null?void 0:M.length)||0,p=((j=i==null?void 0:i.timing)==null?void 0:j.duration)||0;let f=0;h>0&&f++,h>2&&f++,u&&f++,m>0&&f++,f=Math.min(3,f);const y=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},x=o.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:c?s?{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=a?`border-2 ${x.border}`:"",v=Array.from({length:3},(L,F)=>n("div",{className:`w-1 h-1 rounded-full ${F<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},F)),C=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:c?`${e.name}
214
- ${h} args → ${u?"value":"void"}${m>0?` (${m} logs)`:""}
215
- ${p}ms`:`Not executed: ${e.name}`;return l(se,{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:C,onClick:L=>L.stopPropagation(),children:[n("div",{className:`${x.icon} ${y.iconSize} font-mono font-bold`,children:o.hasError?"⚠":c?"ƒ":"○"}),c&&!o.hasError&&l("div",{className:`flex items-center gap-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:[n("span",{children:h}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),c&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:v}),c&&!o.hasError&&p>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:p>1e3?`${Math.round(p/1e3)}s`:`${p}ms`}),c&&!o.hasError&&m>0&&r==="medium"&&l("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",m]})]})}function Br({size:e=24,className:t=""}){return l("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:[n("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),n("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),n("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function bs({scenario:e,entity:t,analysisStatus:r,queueState:a,processIsRunning:s,size:o="medium",cacheBuster:i,className:c="",viewMode:d}){var g,x;if(t.entityType==="library")return n(zo,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=lr(e,r,s,t.sha,a),m=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},p=`relative ${m.containerClass} ${c}`,f=()=>{const b=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${b}/${d}`:b};if(u.isCaptured){const b=(x=(g=e.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return n(se,{to:f(),className:`${p} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(ze,{screenshotPath:b,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const y=()=>{const b={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},v=n(da,{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 l("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(Br,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(Gi,{...b});default:return v}};return n(se,{to:f(),className:`${p} ${u.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:u.title,children:n("div",{className:m.iconSize,children:y()})})}const jt=70;function Vp({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:a,entitySha:s,cacheBuster:o,activeTab:i,entityType:c,entity:d,queueState:h,processIsRunning:u,isEntityAnalyzing:m,areScenariosStale:p,viewMode:f,setViewMode:y,isBreakdownView:g}){var E,T,O,G,V,U;const x=Ne(null),[b,v]=P(new Set),[C,w]=P(!1);ee(()=>{x.current&&i==="scenarios"&&x.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[a==null?void 0:a.id,i]);const N=z=>`/entity/${s}/scenarios/${z}`,S=z=>{v(Y=>{const R=new Set(Y);return R.has(z)?R.delete(z):R.add(z),R})},k=(z,Y=2)=>{const A=z.split(`
216
- `).slice(0,Y).join(" ").trim();return A.length>jt?A.substring(0,jt-3):(z.split(`
217
- `).length>Y||z.length>A.length,A)},M=re(()=>{var Y;if(!((Y=r==null?void 0:r.metadata)!=null&&Y.executionFlows)||!(r!=null&&r.scenarios))return null;const z=r.scenarios.filter(R=>{var A;return!((A=R.metadata)!=null&&A.sameAsDefault)});return oa(r.metadata.executionFlows,z)},[r]),j=(M==null?void 0:M.totalFlows)||0,L=(M==null?void 0:M.coveredFlows)||0,F=(M==null?void 0:M.coveragePercentage)||0;(E=d==null?void 0:d.metadata)!=null&&E.defaultWidth||(T=r==null?void 0:r.metadata)!=null&&T.defaultWidth;const _=(O=r==null?void 0:r.status)!=null&&O.finishedAt?new Date(r.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return l("aside",{className:"w-[250px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-4",children:[r&&e.length>0&&l("div",{className:"flex flex-col gap-2",children:[n("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),l("div",{className:"grid grid-cols-2 gap-2",children:[l(se,{to:g?`/entity/${s}/scenarios/${(a==null?void 0:a.id)||((G=e[0])==null?void 0:G.id)}`:`/entity/${s}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[l("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(F),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),l(se,{to:g?`/entity/${s}/scenarios/${(a==null?void 0:a.id)||((V=e[0])==null?void 0:V.id)}`:`/entity/${s}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[l("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[L,"/",j]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),l(se,{to:g?`/entity/${s}/scenarios/${(a==null?void 0:a.id)||((U=e[0])==null?void 0:U.id)}`:`/entity/${s}/scenarios/breakdown`,className:`border rounded px-3 py-2 no-underline hover:shadow-sm transition-shadow flex items-center justify-between ${g?"bg-[#CBF3FA] border-[#CBF3FA]":"bg-[#F6F9FC] border-[#E0E9EC]"}`,children:[n("div",{className:"text-[11px] text-[#005c75] font-normal uppercase font-mono underline",children:"EXECUTION FLOWS"}),g?n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M3 3L9 9M9 3L3 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),d&&d.filePath&&n("div",{children:n(se,{to:`/entity/${s}/create-scenario`,className:"w-full px-3 py-2 bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[11px] font-medium font-mono cursor-pointer transition-colors hover:bg-[#004a5e] no-underline flex items-center justify-center gap-1",children:"+ Create New Scenario"})}),e.length>0&&l("div",{className:"py-3 flex items-center justify-between",children:[l("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),_&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:_})]}),m&&(p||e.length===0)?l("div",{className:"",children:[l("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[l("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[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((z,Y)=>{const R=!g&&(a==null?void 0:a.id)===z.id,A=b.has(z.id||"");return z.id?l(se,{to:N(z.id),ref:R?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${R?"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(bs,{scenario:z,entity:{sha:s,entityType:c},analysisStatus:r==null?void 0:r.status,queueState:h,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),l("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${A?"":"line-clamp-1"}`,children:z.name}),z.description&&n("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[A?z.description:k(z.description),!A&&z.description.length>jt&&l(he,{children:["...",n("button",{onClick:H=>{H.preventDefault(),H.stopPropagation(),S(z.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),A&&z.description.length>jt&&n("button",{onClick:H=>{H.preventDefault(),H.stopPropagation(),S(z.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},Y):null})})}),t.length>0&&!(m&&p)&&l("div",{className:"border-t border-[#e1e1e1] pt-3",children:[l("button",{onClick:()=>w(!C),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 ${C?"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,")"]}),C&&l("div",{className:"mt-2",children:[n("p",{className:"text-[10px] text-[#8e8e8e] leading-[14px] mb-3",children:"These scenarios were hidden because the screenshots did not differ from the Default Scenario."}),n("div",{className:"flex flex-col gap-[11.6px]",children:t.map((z,Y)=>{const R=!g&&(a==null?void 0:a.id)===z.id,A=b.has(z.id||"");return z.id?l(se,{to:`/entity/${s}/scenarios/${z.id}`,ref:R?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${R?"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(bs,{scenario:z,entity:{sha:s,entityType:c},analysisStatus:r==null?void 0:r.status,queueState:h,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),l("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${A?"":"line-clamp-1"}`,children:z.name}),z.description&&n("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[A?z.description:k(z.description),!A&&z.description.length>jt&&l(he,{children:["...",n("button",{onClick:H=>{H.preventDefault(),H.stopPropagation(),S(z.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),A&&z.description.length>jt&&n("button",{onClick:H=>{H.preventDefault(),H.stopPropagation(),S(z.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},Y):null})})]})]})]})}function Gp({scenario:e,entitySha:t,onApply:r,onSave:a,onEditMockData:s,onDelete:o,isApplying:i=!1,isSaving:c=!1,saveMessage:d=null,showDeleteConfirm:h=!1,onShowDeleteConfirm:u,isDeleting:m=!1,deleteError:p=null}){const[f,y]=P(""),g=async()=>{await r(f)},x=async b=>{await a(f,b),b||y("")};return l("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[l("div",{className:"border-b border-[#e1e1e1] pb-3",children:[l("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(se,{to:`/entity/${t}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),n("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),l("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[l("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange: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}),l("button",{onClick:()=>void g(),disabled:i||!f.trim(),className:"w-full mt-1 h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center gap-1",children:[i&&l("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),i?"Applying...":"Apply"]})]}),n("div",{className:"border-t border-[#e1e1e1] my-1"}),l("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick:s,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),d&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${d.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:d}),d==="Recapture successful"&&n("div",{children:n(se,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),l("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[n("button",{onClick:()=>void x(!1),disabled:c||!f.trim(),className:"w-full h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center",children:c?"Saving...":"Save Scenario Data"}),n("button",{onClick:()=>void x(!0),disabled:c||!f.trim(),className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:"Save As New"}),o&&l(he,{children:[h?l("div",{className:"flex flex-col gap-1",children:[l("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),l("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void o(),disabled:m,className:"flex-1 h-[22px] bg-red-600 text-white rounded text-[10px] font-normal hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors flex items-center justify-center cursor-pointer",children:m?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>u==null?void 0:u(!1),disabled:m,className:"flex-1 h-[22px] bg-gray-100 text-gray-700 border border-gray-300 rounded text-[10px] font-normal hover:bg-gray-200 disabled:opacity-50 transition-colors flex items-center justify-center cursor-pointer",children:"Cancel"})]})]}):n("button",{onClick:()=>u==null?void 0:u(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),p&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:p})]})]})]})}function qp({scenario:e,analysis:t,entity:r}){var i,c,d;const a=((i=e.metadata)==null?void 0:i.executionResult)||null,s=((d=(c=e.metadata)==null?void 0:c.data)==null?void 0:d.argumentsData)||[],o=h=>{var y,g,x;if(!h)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const u=[],m=((y=h.sideEffects)==null?void 0:y.consoleOutput)||[];m.length>0&&(u.push(`Console Output: ${m.length} log ${m.length===1?"entry":"entries"} captured`),m.forEach(b=>{u.push(` [${b.level.toUpperCase()}] ${b.args.join(" ")}`)}));const p=((g=h.sideEffects)==null?void 0:g.fileWrites)||[];p.length>0&&(u.push(`
218
- File System Operations: ${p.length} ${p.length===1?"operation":"operations"} detected`),p.forEach(b=>{u.push(` ${b.operation}: ${b.path}${b.size?` (${b.size} bytes)`:""}`)}));const f=((x=h.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(u.push(`
219
- 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)`:""}`)})),h.error&&u.push(`
220
- Error: ${h.error.name||"Error"}: ${h.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
221
- `)};return l("div",{className:"flex w-full h-full gap-0",children:[l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(s,null,2)})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:a?n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:a.returnValue!==void 0?JSON.stringify(a.returnValue,null,2):"undefined"}):n("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:o(a)})})]})]})}const Ct={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function Nn({scenarioId:e,analysisId:t}){const[r,a]=P(!1),[s,o]=P(!1),[i,c]=P(null),[d,h]=P(!1),u=e||t;if(!u)return null;const m=`/codeyam-diagnose ${u}`,p=async()=>{o(!0);try{const{default:y}=await import("html2canvas-pro"),x=(await y(document.body,{scale:.5})).toDataURL("image/jpeg",.8);c(x),a(!0)}catch(y){console.error("Screenshot capture failed:",y),a(!0)}finally{o(!1)}},f=()=>{a(!1),c(null)};return l(he,{children:[l("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[n("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:Ct.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:Ct.subtext},children:"Simply run this command in Claude Code:"}),l("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:Ct.commandBoxBg,borderColor:Ct.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:Ct.commandBoxText},children:m}),n("button",{onClick:y=>{y.stopPropagation(),navigator.clipboard.writeText(m),h(!0),setTimeout(()=>h(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:d?"#22c55e":Ct.commandBoxText},title:d?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:d?n(At,{size:14}):n($t,{size:14})})]}),l("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",n("button",{onClick:()=>void p(),disabled:s,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:Ct.link},children:s?"capturing...":"please do so here"}),"."]})]}),n(Hs,{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 vs=1440,Sn=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],nt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function Bo({selectedScenario:e,analysis:t,entity:r,viewMode:a,cacheBuster:s,hasScenarios:o,isAnalyzing:i=!1,projectSlug:c,hasAnApiKey:d=!0,processIsRunning:h,queueState:u}){var q,te,ce,me,ge,be,Ce,Ee,Se,Pe,Me;const m=Ae(),[p,f]=P(!1),[y,g]=P(!1),[x,b]=P({name:"Desktop",width:vs,height:900}),[v,C]=P(vs),[w,N]=P(1),{customSizes:S,addCustomSize:k,removeCustomSize:M}=ko(c),j=re(()=>[...Sn,...S],[S]),L=(ve,Q)=>{C(ve);const ue=j.find(ye=>ye.width===ve&&ye.height===Q);b({name:(ue==null?void 0:ue.name)||"Custom",width:ve,height:Q})},F=ve=>{C(ve.width),b({name:ve.name,width:ve.width,height:ve.height})},_=ve=>{k(ve,x.width,x.height??900),g(!1),b(Q=>({...Q,name:ve}))},E=(ve,Q)=>{C(ve);const ue=j.find(ye=>ye.width===ve&&ye.height===Q);b(ye=>({name:(ue==null?void 0:ue.name)||"Custom",width:ve,height:ye.height}))},T=(te=(q=e==null?void 0:e.metadata)==null?void 0:q.screenshotPaths)==null?void 0:te[0],O=re(()=>e?lr(e,t==null?void 0:t.status,h,r==null?void 0:r.sha,u):null,[e,t==null?void 0:t.status,h,r==null?void 0:r.sha,u]),G=re(()=>{var Q,ue;const ve=[];if((Q=t==null?void 0:t.status)!=null&&Q.errors&&t.status.errors.length>0)for(const ye of t.status.errors)ve.push({source:`${ye.phase} phase`,message:ye.message,stack:ye.stack});if((ue=t==null?void 0:t.status)!=null&&ue.steps)for(const ye of t.status.steps)ye.error&&ve.push({source:ye.name,message:ye.error,stack:ye.errorStack});return ve},[(ce=t==null?void 0:t.status)==null?void 0:ce.errors,(me=t==null?void 0:t.status)==null?void 0:me.steps]),V=(O==null?void 0:O.errorMessage)||null,U=(O==null?void 0:O.errorStack)||null,{interactiveServerUrl:z,isStarting:Y,isLoading:R,showIframe:A,iframeKey:H,onIframeLoad:W}=hn({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:c,enabled:a==="interactive"}),J=re(()=>z||null,[z]),ae=!i&&o&&e&&!((be=(ge=e.metadata)==null?void 0:ge.screenshotPaths)!=null&&be[0])&&((Ee=(Ce=t==null?void 0:t.status)==null?void 0:Ce.scenarios)==null?void 0:Ee.some(ve=>ve.name===e.name&&ve.screenshotStartedAt&&!ve.screenshotFinishedAt)),{lastLine:$}=ft(c,i||a==="interactive"||ae||!1);if(!e){if(i&&r)return l(he,{children:[n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:l("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:ae?"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."}),$&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:$}),c&&n("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})}),p&&c&&n(ht,{projectSlug:c,onClose:()=>f(!1)})]});if(!o&&r&&!i){if(G.length>0){const ve=G.length===1?((Se=G[0])==null?void 0:Se.message)||"An error occurred during analysis.":`${G.length} errors occurred during analysis.`;return l(he,{children:[n("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:l("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded",style:{backgroundColor:nt.background,border:`2px solid ${nt.border}`},role:"alert",children:l("div",{className:"flex items-center gap-3",children:[n(Br,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:l("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:nt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",ve," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:nt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Nn,{analysisId:t==null?void 0:t.id})})]})}),p&&c&&n(ht,{projectSlug:c,onClose:()=>f(!1)})]})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:l("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{m.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:m.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return l(he,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
222
- linear-gradient(45deg, #ebebeb 25%, transparent 25%),
223
- linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
224
- linear-gradient(45deg, transparent 75%, #ebebeb 75%),
225
- linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
226
- `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||ae&&!T)&&!V&&a==="screenshot"?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-linear-to-br from-blue-50 to-indigo-50",children:l("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[l("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:ae?`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:ae?`Taking screenshots for ${((Pe=t==null?void 0:t.scenarios)==null?void 0:Pe.length)||0} scenario${((Me=t==null?void 0:t.scenarios)==null?void 0:Me.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&l("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),$&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:l("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),l("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:$,children:$})]})]})}),c&&n("button",{onClick:()=>f(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),n("p",{className:"text-xs text-gray-500 mt-8 m-0",children:"Screenshots will appear here as they are captured. This may take a few minutes."})]})}):a==="screenshot"&&(T||V)||a==="interactive"&&(J||Y)||a==="data"?l(he,{children:[V&&!T&&n("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:l("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:nt.background,border:`2px solid ${nt.border}`,maxHeight:"50vh"},role:"alert",children:l("div",{className:"flex flex-col gap-3",children:[l("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:nt.text},children:[n(Br,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),l("div",{className:"text-center",children:[n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:nt.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:nt.text},children:V})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Nn,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),a==="interactive"?l("div",{className:"flex-1 flex flex-col min-h-0",children:[J&&l("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center items-center gap-4",children:[n(du,{presets:[...Sn],customSizes:S,currentWidth:x.width,currentHeight:x.height??900,scale:w,onSizeChange:L,onSaveCustomSize:()=>g(!0),onRemoveCustomSize:M}),e&&r&&l(se,{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"]})]}),J&&n("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${Sn[Sn.length-1].width}px`,width:"100%"},children:n(Eo,{currentViewportWidth:v,currentPresetName:x.name,onDevicePresetClick:F,devicePresets:j})})}),n(or,{scenarioId:e.id,scenarioName:e.name,iframeUrl:J,isStarting:Y,isLoading:R,showIframe:A,iframeKey:H,onIframeLoad:W,onScaleChange:N,onDimensionChange:E,projectSlug:c,defaultWidth:x.width,defaultHeight:x.height})]}):a==="data"?n("div",{className:"flex-1 min-h-0",children:n(qp,{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:(T||!V)&&n(ze,{screenshotPath:T,cacheBuster:s,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!T?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),l("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),l("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),$&&l("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:$})]}),c&&n("button",{onClick:()=>f(!0),className:"mt-4 px-4 py-2 bg-[#005c75] text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-[#004a5e]",children:"📋 View Full Logs"})]})]})})}):V?l("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!d&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:l("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[l("div",{className:"flex items-start gap-4",children:[n("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),l("div",{className:"bg-white border border-blue-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-blue-900 m-0 mb-2 uppercase tracking-wide",children:"CodeYam requires an AI API key for reliable analysis."}),l("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[n("li",{children:"You can use API keys for a variety of models"}),n("li",{children:"Faster analysis processing"}),n("li",{children:"Better handling of complex code structures"}),n("li",{children:"Improved scenario generation quality"})]})]}),n(se,{to:"/settings",className:"inline-block px-4 py-2 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700",children:"🔐 Configure API Keys"})]})}),n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),l("div",{className:"bg-white border border-red-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),n("div",{className:"max-h-[300px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:V})})]}),U&&l("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:U})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Nn,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):G.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:G,title:"Analysis Error",description:G.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${G.length} errors occurred during analysis. Screenshot capture was not completed.`}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Nn,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):l("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),p&&c&&n(ht,{projectSlug:c,onClose:()=>f(!1)}),y&&n(Ao,{width:x.width,height:x.height??900,onSave:_,onCancel:()=>g(!1)})]})}function Kp({analysis:e,entitySha:t}){at();const[r,a]=P(e);ee(()=>{a(e)},[e]);const[s,o]=P(null),i=re(()=>{var m;if(!((m=r==null?void 0:r.metadata)!=null&&m.executionFlows)||!(r!=null&&r.scenarios))return null;const u=r.scenarios.filter(p=>{var f;return!((f=p.metadata)!=null&&f.sameAsDefault)});return oa(r.metadata.executionFlows,u)},[r]),c=re(()=>i?Pu(i):[],[i]),d=re(()=>r!=null&&r.scenarios?r.scenarios.filter(u=>{var m;return!((m=u.metadata)!=null&&m.sameAsDefault)}):[],[r]),h=u=>{var p;const m=((p=u.metadata)==null?void 0:p.coveredFlows)||[];return i?i.executionFlows.filter(f=>m.includes(f.id)):[]};return r?!i||i.executionFlows.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:l("div",{className:"p-6 space-y-6",children:[l("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),l("div",{className:"grid grid-cols-4 gap-4 text-center",children:[l("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:d.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:i.executionFlows.length}),n("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[l("div",{className:"text-2xl font-bold text-gray-900",children:[i.coveredFlows,"/",i.totalFlows]}),n("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[l("div",{className:`text-2xl font-bold ${i.coveragePercentage===100?"text-green-600":i.coveragePercentage>=50?"text-amber-600":"text-red-600"}`,children:[i.coveragePercentage.toFixed(0),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),l("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:l("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",d.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:d.length===0?l("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",n(se,{to:`/entity/${t}/create-scenario`,className:"text-blue-600 hover:underline",children:"Create one"})]}):d.map(u=>{var f,y,g;const m=(y=(f=u.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0],p=h(u);return l("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(ze,{screenshotPath:m,alt:u.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),l("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:l("div",{children:[n(se,{to:`/entity/${t}/scenarios/${u.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:u.name}),((g=u.metadata)==null?void 0:g.error)&&n("span",{className:"ml-2 text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"Error"})]})}),n("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:u.description}),p.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:p.map(x=>n("span",{className:`text-xs px-1.5 py-0.5 rounded ${x.isError?"bg-red-50 text-red-700":x.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:x.name},x.id))})]})]},u.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:l(se,{to:`/entity/${t}/create-scenario`,className:"w-full px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 flex items-center justify-center gap-2 no-underline",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),c.length>0&&l("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[l("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[c.length," uncovered execution flow",c.length>1?"s":""," — consider adding scenarios to cover these"]}),l("div",{className:"flex flex-wrap gap-1",children:[c.slice(0,10).map(u=>l("span",{className:`text-xs px-2 py-0.5 rounded ${u.impact==="high"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[u.name,u.impact==="high"&&" (high impact)"]},u.id)),c.length>10&&l("span",{className:"text-xs text-amber-600",children:["+",c.length-10," more"]})]})]}),l("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:l("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",i.executionFlows.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:i.executionFlows.map(u=>{const m=s===u.id,p=u.usedInScenarios.length>0;return l("div",{children:[n("button",{onClick:()=>o(m?null:u.id),className:"w-full px-4 py-3 flex items-start justify-between text-left bg-transparent border-none cursor-pointer hover:bg-gray-50",children:l("div",{className:"flex items-start gap-3 flex-1",children:[n("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:m?"▼":"▶"}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-medium text-sm text-gray-900",children:u.name}),p?n("span",{className:"text-xs px-2 py-0.5 rounded bg-green-100 text-green-700",children:"Covered"}):n("span",{className:"text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700",children:"Uncovered"}),u.blocksOtherFlows&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),u.impact==="high"&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),u.isError&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),u.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:u.description})]})]})}),m&&l("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[u.requiredValues.length>0&&l("div",{className:"mb-4",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),n("div",{className:"space-y-1",children:u.requiredValues.map((f,y)=>l("div",{className:"flex items-center gap-2 text-xs",children:[n("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children:f.attributePath}),n("span",{className:"text-gray-400",children:f.comparison}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:f.value})]},y))})]}),p&&l("div",{children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),n("div",{className:"flex flex-wrap gap-1",children:u.usedInScenarios.map(f=>n("span",{className:"text-xs px-1.5 py-0.5 bg-green-50 text-green-700 rounded",children:f.name},f.id))})]}),u.codeSnippet&&l("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:u.codeSnippet})})]})]})]},u.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function ws({hasIndirectBadge:e,onAnalyze:t}){return l(he,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-end gap-2",children:[e&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:"0 scenarios"})]})}),l("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[n("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),n("button",{className:"px-[15px] py-0 h-[23px] bg-[#005c75] text-white rounded text-xs font-medium leading-5 border-none cursor-pointer hover:bg-[#004a5e] transition-colors flex items-center justify-center",onClick:t,children:"Analyze"})]})]})}function Qp({entity:e,history:t}){const[r,a]=P("entity"),[s,o]=P(new Set),i=t.filter(u=>u.analyses.length>0).length,c=re(()=>{const u=new Map;return t.forEach(m=>{m.analyses.forEach(p=>{(p.scenarios??[]).filter(y=>{var g;return!((g=y.metadata)!=null&&g.sameAsDefault)}).forEach(y=>{u.has(y.name)||u.set(y.name,[]),u.get(y.name).push({version:m,analysis:p,scenario:y})})})}),Array.from(u.entries()).map(([m,p])=>{var f;return{name:m,description:((f=p[0])==null?void 0:f.scenario.description)||"",versions:p.sort((y,g)=>{const x=new Date(y.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-x})}})},[t]),d=c.length,h=u=>{o(m=>{const p=new Set(m);return p.has(u)?p.delete(u):p.add(u),p})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:l("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:l("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[l("button",{onClick:()=>a("entity"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="entity"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-semibold leading-6",children:"Entity History"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="entity"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:i})]}),l("button",{onClick:()=>a("scenarios"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="scenarios"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-normal leading-6",children:"Scenario Changes"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="scenarios"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:d})]})]})}),t.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):r==="entity"?l("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((u,m)=>l("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3",children:[u.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),l(se,{to:`/entity/${u.sha}/scenarios`,className:"text-xs font-mono text-[#646464] leading-5 hover:text-[#005c75] transition-colors",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:u.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:u.createdAt&&new Date(u.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),u.analyses.length>0?n("div",{children:u.analyses.map((p,f)=>{var g;const y=(p.scenarios??[]).filter(x=>{var b;return!((b=x.metadata)!=null&&b.sameAsDefault)});return n("div",{children:y.length===0?n(ws,{hasIndirectBadge:p.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):l(he,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-end gap-2",children:[p.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),l("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[y.length," scenario",y.length!==1?"s":""]})]})}),((g=p.metadata)==null?void 0:g.scenarioChangesOverview)&&n("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:l("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[l("span",{className:"font-medium",children:["What Changed:"," "]}),p.metadata.scenarioChangesOverview]})}),y.length>0&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:y.map((x,b)=>{var w,N;const v=(N=(w=x.metadata)==null?void 0:w.screenshotPaths)==null?void 0:N[0],C=`${x.name}-${b}`;return l(se,{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(ze,{screenshotPath:v,alt:x.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:x.name})})]},C)})})})]})},p.id||f)})}):n(ws,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:c.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):c.map((u,m)=>{const p=s.has(u.name),f=p?u.versions:u.versions.slice(0,1),y=u.versions.length-1,g=u.versions[0];return g==null||g.version.sha,e==null||e.sha,l("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),l("div",{className:"p-5 bg-white",children:[f.map((x,b)=>{var k,M;const{version:v,analysis:C,scenario:w}=x,N=(M=(k=w.metadata)==null?void 0:k.screenshotPaths)==null?void 0:M[0],S=b===0;return l("div",{className:`flex gap-5 items-start ${S?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(se,{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:N?n(ze,{screenshotPath:N,alt:w.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),l("div",{className:"flex-1 flex flex-col gap-2",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[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&&l("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[u.versions.length," versions"]})]}),l(se,{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)})]}),C.createdAt&&l("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(C.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),C.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${v.sha}-${b}`)}),y>0&&l("button",{onClick:()=>h(u.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${p?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),p?"Hide":`${y} previous version${y!==1?"s":""}`]})]})]})]},u.name)})})]})})}function Cs({entity:e,analysisInfo:t,from:r}){const a=Ae(),s=a.state!=="idle",o=e.entityType==="visual"||e.entityType==="library",i=c=>{c.preventDefault(),c.stopPropagation(),o&&a.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(se,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:l("div",{className:"flex gap-0 border border-gray-200 rounded-lg overflow-hidden transition-all hover:border-[#005c75] hover:shadow-md bg-white h-[100px]",children:[e.screenshotPath?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(ze,{screenshotPath:e.screenshotPath,alt:e.name,className:"max-w-full max-h-full object-contain"})}):n("div",{className:"w-[125px] h-full bg-[#efefef] flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n("span",{className:"text-[40px]",children:n(Je,{type:e.entityType})})}),l("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(Je,{type:e.entityType}),n("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),n("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),t.hasScenarios&&l("div",{className:"flex items-center gap-2 mt-2",children:[l("span",{className:"px-[5px] py-0 bg-[#efefef] text-[#3e3e3e] rounded text-[10px] font-medium",children:[t.scenarioCount," scenarios"]}),n("span",{className:"text-xs text-[#8e8e8e]",children:t.timestamp})]})]}),n("div",{className:"shrink-0 ml-4",children:t.status==="not_analyzed"?l(he,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:s,children:s?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):l(he,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:s,children:s?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const Ns=e=>{var s,o,i;const t=((s=e.analysisStatus)==null?void 0:s.status)||"not_analyzed",r=((o=e.analysisStatus)==null?void 0:o.scenarioCount)||0,a=(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:a}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:r>0,scenarioCount:r,timestamp:a}};function Zp({importedEntities:e,importingEntities:t}){const[r]=sn(),a=r.get("from"),s=Ae(),o=s.state!=="idle",i=e.length>0,c=t.length>0,d=p=>p.filter(f=>f.entityType==="visual"||f.entityType==="library"),h=p=>{const f=d(p);f.length!==0&&s.submit({entityShas:f.map(y=>y.sha).join(",")},{method:"post",action:"/api/analyze"})},u=d(e).length>0,m=d(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:l("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-6 py-4 flex items-start justify-between",children:[l("div",{children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&n("button",{onClick:()=>h(e),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(p=>n(Cs,{entity:p,analysisInfo:Ns(p),from:a},p.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-6 py-4 flex items-start justify-between",children:[l("div",{children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),m&&n("button",{onClick:()=>h(t),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),c?n("div",{className:"p-6 space-y-4",children:t.map(p=>n(Cs,{entity:p,analysisInfo:Ns(p),from:a},p.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px] text-center",children:"Not imported by any entity."})})]})]})})}function Xp({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(Zp,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function ef({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(an,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function an({data:e,depth:t,defaultExpanded:r,maxDepth:a,objectKey:s,showInlineToggle:o=!1}){const[i,c]=P(r||t<2);if(ee(()=>{c(r||t<2)},[r,t]),e===null)return n("span",{className:"text-gray-500",children:"null"});if(e===void 0)return n("span",{className:"text-gray-500",children:"undefined"});const d=typeof e;if(d==="string")return l("span",{className:"text-green-600",children:['"',e,'"']});if(d==="number")return n("span",{className:"text-blue-600",children:e});if(d==="boolean")return n("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?n("span",{className:"text-gray-600",children:"[]"}):l("span",{children:[l("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>c(!i),children:[l("span",{children:[i?"▼":"▶"," ","["]}),!i&&l("span",{children:[e.length,"]"]})]}),i?l(he,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((h,u)=>n("div",{className:"py-0.5",children:n(an,{data:h,depth:t+1,defaultExpanded:r,maxDepth:a})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const h=Object.keys(e);if(h.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=p=>p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,m=p=>Array.isArray(p)&&p.length>0;return l("span",{children:[l("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>c(!i),children:[l("span",{children:[i?"▼":"▶"," ","{"]}),!i&&l("span",{children:[h.length,"}"]})]}),i?l(he,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:h.map(p=>{const f=e[p],y=u(f),g=m(f);return n("div",{className:"py-0.5",children:y?n(ua,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):g?n(ha,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):l(he,{children:[l("span",{className:"text-orange-600",children:[p,": "]}),n(an,{data:f,depth:t+1,defaultExpanded:r,maxDepth:a})]})},p)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function ua({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=P(a||r<2),c=Object.keys(t);return ee(()=>{i(a||r<2)},[a,r]),l(he,{children:[l("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&l("span",{className:"text-gray-600",children:[c.length,"}"]})]}),o&&l(he,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:c.map(d=>{const h=t[d],u=h!==null&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,m=Array.isArray(h)&&h.length>0;return n("div",{className:"py-0.5",children:u?n(ua,{propertyKey:d,value:h,depth:r+1,defaultExpanded:a,maxDepth:s}):m?n(ha,{propertyKey:d,value:h,depth:r+1,defaultExpanded:a,maxDepth:s}):l(he,{children:[l("span",{className:"text-orange-600",children:[d,": "]}),n(an,{data:h,depth:r+2,defaultExpanded:a,maxDepth:s})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function ha({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=P(a||r<2);return ee(()=>{i(a||r<2)},[a,r]),l(he,{children:[l("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&l("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&l(he,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((c,d)=>{const h=c!==null&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,u=Array.isArray(c)&&c.length>0;return n("div",{className:"py-0.5",children:h?n(ua,{propertyKey:d.toString(),value:c,depth:r+1,defaultExpanded:a,maxDepth:s}):u?n(ha,{propertyKey:d.toString(),value:c,depth:r+1,defaultExpanded:a,maxDepth:s}):n(an,{data:c,depth:r+2,defaultExpanded:a,maxDepth:s})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function Tr({label:e,count:t,isActive:r,onClick:a,badgeColorActive:s,badgeTextActive:o}){return l("button",{onClick:a,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${s} ${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 Ss({label:e,isActive:t,onClick:r,disabled:a=!1}){return n("button",{onClick:r,className:`w-full text-left px-3 py-2.5 rounded-md transition-all text-sm cursor-pointer ${t?"bg-[#f6f9fc] text-[#005c75] font-medium border-l-2 border-[#005c75] pl-[10px]":"text-[#3e3e3e] hover:bg-gray-50"}`,disabled:a,children:e})}function Es({call:e,scenarioName:t}){const[r,a]=P(!1),[s,o]=P("system"),i=p=>new Date(p).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),c=p=>p?`$${p.toFixed(4)}`:null,d=(p,f)=>{if(!p&&!f)return null;const y=[];return p&&y.push(`${p.toLocaleString()} in`),f&&y.push(`${f.toLocaleString()} out`),y.join(" / ")},h=re(()=>{var p,f,y,g,x;try{const b=JSON.parse(e.response);return(y=(f=(p=b.choices)==null?void 0:p[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=re(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),m=re(()=>{var p;if(t)return t;try{const f=JSON.parse(e.props);return((p=f==null?void 0:f.scenario)==null?void 0:p.name)||null}catch{return null}},[e.props,t]);return l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>a(!r),children:l("div",{className:"flex items-start justify-between gap-4",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),m&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:m}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),l("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&n("span",{children:d(e.input_tokens,e.output_tokens)}),c(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:c(e.cost)})]}),l("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.object_id,"_",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&l("div",{className:"border-t border-[#e1e1e1]",children:[l("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="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 ${s==="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 ${s==="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 ${s==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),s&&l("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[s==="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"})}),s==="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})}),s==="response"&&l("div",{children:[e.error&&l("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:h})]}),s==="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&&!s&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:l("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const As=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function tf({entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s}){var C,w,N,S,k,M,j,L,F;const[o,i]=P("entity"),[c,d]=P("analysis"),[h,u]=P(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[m,p]=P("entity"),{entityLlmCalls:f,scenarioLlmCalls:y,totalLlmCalls:g}=re(()=>{if(!s)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const _=[...s.entityCalls,...s.analysisCalls],E=_.filter(O=>O.object_type==="entity"||As.includes(O.prompt_type)),T=_.filter(O=>O.object_type!=="entity"&&!As.includes(O.prompt_type));return E.sort((O,G)=>G.created_at-O.created_at),T.sort((O,G)=>G.created_at-O.created_at),{entityLlmCalls:E,scenarioLlmCalls:T,totalLlmCalls:_.length}},[s]),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:(C=e==null?void 0:e.metadata)==null?void 0:C.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=(N=e==null?void 0:e.metadata)==null?void 0:N.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":(M=e==null?void 0:e.metadata)==null?void 0:M.importedExports,"External Dependencies":(j=e==null?void 0:e.metadata)==null?void 0:j.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(L=t==null?void 0:t.metadata)==null?void 0:L.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(E=>E.id===c);_&&_.data!==void 0&&_.data!==null&&(v={title:_.title,description:_.description,data:_.data})}else if(o==="scenarios"&&h){const _=r.find(E=>(E.id||E.name)===h.scenarioId);_&&(v={title:_.name,description:_.description||"Scenario data and configuration",data:_.metadata})}return l("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:l("div",{className:"flex border-b border-gray-200 relative",children:[n(Tr,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(Tr,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(Tr,{label:"LLM Calls",count:g,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((F=t==null?void 0:t.metadata)==null?void 0:F.analyzerVersion)&&l("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?l("div",{className:"flex-1 min-h-0",children:[l("div",{className:"flex gap-4 mb-4",children:[l("button",{onClick:()=>p("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),l("button",{onClick:()=>p("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",y.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:m==="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(Es,{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(Es,{call:_},_.id))})]}):l("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:o==="entity"?l(he,{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 E=_.data!==void 0&&_.data!==null;return n(Ss,{label:_.title,isActive:c===_.id,onClick:()=>d(_.id),disabled:!E},_.id)})})]}):l(he,{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 E=_.id||_.name,T=(h==null?void 0:h.scenarioId)===E;return n(Ss,{label:_.name,isActive:T,onClick:()=>u({scenarioId:E})},E)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:v?n(nf,{title:v.title,description:v.description,data:v.data}):o==="scenarios"&&r.length===0?n(ks,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:a}):o==="entity"?n(ks,{title:"No Entity Data Yet",description:"Entity data structures will appear here after analysis is complete.",onAnalyze:a}):n("div",{className:"p-6 text-center py-12 text-gray-500",children:"Select a section to view data"})})]})]})}function ks({title:e,description:t,onAnalyze:r}){return l("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[n("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),n("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:t}),r&&n("button",{onClick:r,className:"h-[54px] w-[183px] bg-[#005c75] text-white text-base font-medium rounded-lg border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]})}function nf({title:e,description:t,data:r}){const[a,s]=P(!0),[o,i]=P("Copy JSON");return l(he,{children:[l("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[n("h3",{className:"text-base font-semibold text-black m-0",children:e}),n("p",{className:"text-sm text-[#646464] mt-1 m-0",children:t})]}),l("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[l("div",{className:"flex gap-2",children:[n("button",{onClick:()=>s(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${a?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),n("button",{onClick:()=>s(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${a?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),n("button",{onClick:()=>{const d=JSON.stringify(r,null,2);navigator.clipboard.writeText(d),i("Copied!"),setTimeout(()=>i("Copy JSON"),2e3)},className:"px-4 h-8 bg-[#343434] hover:bg-[#232323] text-white text-sm font-medium rounded border-none cursor-pointer transition-colors whitespace-nowrap",children:o})]}),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(ef,{data:r,defaultExpanded:a,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function rf({entity:e,analysis:t,scenarios:r,onAnalyze:a}){const s=Ae();return ee(()=>{if(e!=null&&e.sha&&s.state==="idle"&&!s.data){const o=t!=null&&t.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;s.load(o)}},[e==null?void 0:e.sha,t==null?void 0:t.id,s.state,s.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(tf,{entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s.data})})}function Uo({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:a="",duration:s=2e3,ariaLabel:o,icon:i=!1,iconSize:c=14}){const[d,h]=P(!1),u=oe(()=>{navigator.clipboard.writeText(e).then(()=>{h(!0),setTimeout(()=>h(!1),s)}).catch(m=>{console.error("Failed to copy:",m)})},[e,s]);return n("button",{onClick:u,className:`cursor-pointer ${a}`,disabled:d,"aria-label":o||(d?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?d?n(At,{size:c,className:"text-green-500"}):n($t,{size:c}):d?r:t})}const af={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},sf={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},of=2e3,lf=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 cf({entity:e,entityCode:t}){const r=Hn(),a=Ne(null);return ee(()=>{const s=r.hash;if(!s||!a.current)return;const o=s.match(/^#L(\d+)$/);if(!o)return;const i=parseInt(o[1],10);setTimeout(()=>{if(!a.current)return;const c=a.current.querySelector(`[data-line-number="${i}"]`);if(c&&c instanceof HTMLElement){c.scrollIntoView({behavior:"smooth",block:"center"});const d=c.style.backgroundColor;c.style.backgroundColor="rgba(255, 255, 0, 0.2)",setTimeout(()=>{c.style.backgroundColor=d},2e3)}},300)},[r.hash,t]),n("div",{ref:a,className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:l("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[l("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[l("div",{children:[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(Uo,{content:t,label:"Copy Code",duration:of,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(El,{language:lf(e==null?void 0:e.filePath),style:Al,showLineNumbers:!0,customStyle:af,lineNumberStyle:sf,wrapLines:!0,lineProps:s=>({"data-line-number":s,style:{display:"block"}}),children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const df=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function uf({currentParams:e,nextParams:t,currentUrl:r,nextUrl:a,formMethod:s,defaultShouldRevalidate:o}){return r.pathname===a.pathname&&r.search===a.search?o:!!(e.sha!==t.sha||s)}async function hf({params:e,request:t,context:r}){const{sha:a}=e;if(!a)throw new Response("Entity SHA is required",{status:400});const o=new URL(t.url).searchParams.get("from"),c=(e["*"]||"").split("/").filter(Boolean),d=c[0]||"scenarios",h=c[1]||null,u=c[2]||null,m=r.analysisQueue,p=m?m.getState():{paused:!1,jobs:[]},[f,y,g,x]=await Promise.all([Dt(a),$e(),Ot(),td(fe()||process.cwd())]),b=f?await na(f):null,v=f?await io(f.sha):null;let C={importedEntities:[],importingEntities:[]},w=null,N=[];f&&(C=await lo(f),w=await co(f),N=await ho(f));const S=!!(f&&N.length>0&&N[0].sha!==f.sha),k=N.length>0?N[0].sha:null,M=!!(N.length>0&&N[0].analyses&&N[0].analyses.length>0),j=f?await uo(f):!1;return B({entity:f??void 0,analysis:b??void 0,currentEntityAnalysis:v??void 0,projectSlug:y,from:o,relatedEntities:C,entityCode:w??void 0,hasNewerVersion:S,newestEntitySha:k,newestVersionHasAnalysis:M,fileModifiedSinceEntity:j,history:N,tab:d,scenarioId:h,viewModeFromUrl:u,currentCommit:g,hasAnApiKey:x,queueState:p})}const mf=De(function(){var Ea,Aa,ka,Pa,_a,Ma,Ta,ja,Ia,$a,Ra,Da,La,Fa,Oa;const t=Be(),s=(Is()["*"]||"").split("/").filter(Boolean),o=s[0]||"scenarios",i=s[1]||null,c=s[2]||null,d=t.entity,h=t.analysis,u=t.currentEntityAnalysis,m=u||h,p=t.projectSlug;t.from;const f=t.relatedEntities,y=t.entityCode,g=t.hasNewerVersion,x=t.newestEntitySha,b=t.newestVersionHasAnalysis,v=t.fileModifiedSinceEntity,C=t.history,w=t.currentCommit,N=t.hasAnApiKey,S=t.queueState;(Ea=m==null?void 0:m.status)==null||Ea.errors;const k=(m==null?void 0:m.scenarios)||[],M=k.filter(ne=>{var xe;return!((xe=ne.metadata)!=null&&xe.sameAsDefault)}),j=k.filter(ne=>{var xe;return(xe=ne.metadata)==null?void 0:xe.sameAsDefault}),L=Mt(),F=Ne(null);ee(()=>{F.current===null&&(F.current=window.history.length)},[]);const _=()=>{if(typeof window>"u")return;const ne=window.history.state;if(ne===null||(ne==null?void 0:ne.idx)===void 0||(ne==null?void 0:ne.idx)===0)L("/");else{const xe=window.history.length,He=F.current;if(He!==null&&xe>He){const _e=xe-He+1;L(-_e)}else L(-1)}},E=!!S.currentlyExecuting,T=o,O=(Aa=w==null?void 0:w.metadata)==null?void 0:Aa.currentRun,G=!!(O!=null&&O.createdAt)&&!(O!=null&&O.analysisCompletedAt),V=!!(d!=null&&d.sha&&((ka=O==null?void 0:O.currentEntityShas)!=null&&ka.includes(d.sha))),U=!!(d!=null&&d.sha&&((_a=(Pa=S.currentlyExecuting)==null?void 0:Pa.entityShas)!=null&&_a.includes(d.sha))),z=!!(d!=null&&d.sha&&((Ma=S.jobs)!=null&&Ma.some(ne=>{var xe;return(xe=ne.entityShas)==null?void 0:xe.includes(d.sha)}))),Y=V||U||z,R=Y&&((Ta=m==null?void 0:m.status)==null?void 0:Ta.finishedAt)!=null&&M.length>0&&m.entitySha!==(d==null?void 0:d.sha),A=re(()=>{if(T!=="scenarios")return null;if(i){const ne=M.find(xe=>xe.id===i);if(ne)return ne}return M.length>0&&!Y?M[0]:null},[T,i,M,Y]),H=(($a=(Ia=(ja=A==null?void 0:A.metadata)==null?void 0:ja.executionResult)==null?void 0:Ia.error)==null?void 0:$a.message)||((La=(Da=(Ra=m==null?void 0:m.status)==null?void 0:Ra.errors)==null?void 0:Da[0])==null?void 0:La.message);Xe({source:A?"scenario-page":"entity-page",entitySha:d==null?void 0:d.sha,scenarioId:A==null?void 0:A.id,analysisId:m==null?void 0:m.id,entityName:d==null?void 0:d.name,entityType:d==null?void 0:d.entityType,scenarioName:A==null?void 0:A.name,errorMessage:H});const[W,J]=P(()=>c&&c!=="edit"?c:(d==null?void 0:d.entityType)==="library"?"data":"screenshot");ee(()=>{c&&c!==W&&c!=="edit"&&J(c)},[c]);const ae=c==="edit",[$,I]=P(!1),[D,q]=P(!1),[te,ce]=P(null),[me,ge]=P(!1),[be,Ce]=P(!1),[Ee,Se]=P(null),[Pe,Me]=P(null),[ve,Q]=P(0),{interactiveServerUrl:ue,isStarting:ye,isLoading:xt,showIframe:de,iframeKey:Fe,onIframeLoad:Oe}=hn({analysisId:m==null?void 0:m.id,scenarioId:A==null?void 0:A.id,scenarioName:A==null?void 0:A.name,projectSlug:p,enabled:ae&&!!A,refreshTrigger:ve}),[Bt,e0]=P(!1),[t0,n0]=P(""),[mn,Ut]=P(!1),[wa,hr]=P(Date.now()),[ai,mr]=P(!1),et=Ae(),bt=Ae(),We=Ae(),Ye=at(),si=S.jobs.some(ne=>{var xe;return(d==null?void 0:d.sha)&&((xe=ne.entityShas)==null?void 0:xe.includes(d.sha))||ne.type==="analysis"&&ne.commitSha===(w==null?void 0:w.sha)&&ne.entityShas&&ne.entityShas.length===0}),pr=Y,Ca=((Fa=d==null?void 0:d.metadata)==null?void 0:Fa.defaultWidth)||((Oa=m==null?void 0:m.metadata)==null?void 0:Oa.defaultWidth)||1440,oi=Math.round(Ca*(900/1440));et.state==="submitting"||et.state,re(()=>{var ne;return!!((ne=A==null?void 0:A.metadata)!=null&&ne.interactiveExamplePath)},[A]);const{isCompleted:Na}=ft(p,mn);ee(()=>{et.state==="idle"&&et.data&&(et.data.success?setTimeout(()=>{hr(Date.now()),Ye.revalidate(),Ut(!1)},1500):et.data.error&&(Ut(!1),alert(`Recapture failed: ${et.data.error}`)))},[et.state,et.data,Ye]),ee(()=>{mn&&Na&&setTimeout(()=>{hr(Date.now()),Ye.revalidate(),Ut(!1)},1500)},[mn,Na,Ye]),ee(()=>{bt.state==="idle"&&bt.data&&(bt.data.success?setTimeout(()=>{hr(Date.now()),Ye.revalidate(),Ut(!1)},1500):bt.data.error&&(Ut(!1),alert(`Recapture failed: ${bt.data.error}`)))},[bt.state,bt.data,Ye]);const Sa=()=>{d&&(g&&x&&x!==d.sha?(L(`/entity/${x}/scenarios`),setTimeout(()=>{We.submit({entitySha:x,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})},100)):We.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"}))};ee(()=>{We.state==="idle"&&We.data&&(We.data.success?Ye.revalidate():We.data.error&&alert(`Analysis failed: ${We.data.error}`))},[We.state,We.data,d==null?void 0:d.sha,Ye]),ee(()=>{const ne=setTimeout(()=>{Ye.revalidate()},500);return()=>clearTimeout(ne)},[]),ee(()=>{if(G||pr){const ne=setInterval(()=>{Ye.revalidate()},3e3);return()=>clearInterval(ne)}else{const ne=setInterval(()=>{Ye.revalidate()},5e3),xe=setTimeout(()=>{clearInterval(ne)},3e4);return()=>{clearInterval(ne),clearTimeout(xe)}}},[G,pr,Ye]);const ii=(ne,xe)=>ne==="scenarios"?`/entity/${d==null?void 0:d.sha}/scenarios`:`/entity/${d==null?void 0:d.sha}/${ne}`,li=(ne,xe)=>`/entity/${d==null?void 0:d.sha}/scenarios/${ne}/${xe}`,ci=ne=>{J(ne),A!=null&&A.id&&(ne==="interactive"?L(`/entity/${d==null?void 0:d.sha}/scenarios/${A.id}/fullscreen`,{replace:!0}):L(li(A.id,ne),{replace:!0}))},di=async ne=>{var xe,He;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:ne,hasSelectedScenario:!!A,hasAnalysis:!!m}),!A||!m){const _e="Error: No scenario or analysis available";console.error("[EntityDetail]",_e),ce(_e);return}I(!0),ce(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:ne,scenarioId:A.id,scenarioName:A.name,currentData:A.data});try{const _e=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:ne,existingScenarios:m.scenarios,scenariosDataStructure:(xe=m.metadata)==null?void 0:xe.scenariosDataStructure,editingMockName:A.name,editingMockData:Pe||((He=A.metadata)==null?void 0:He.data)})}),tt=await _e.json();if(!_e.ok||!tt.success)throw new Error(tt.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",tt.data),Me(tt.data);const pn=(m.scenarios||[]).map(Ue=>Ue.id===A.id?{...Ue,metadata:{...Ue.metadata,data:tt.data}}:Ue),Wt=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:pn})}),Ge=await Wt.json();if(!Wt.ok||!Ge.success)throw console.error("[EntityDetail] Temp save failed:",Ge),new Error(Ge.error||"Failed to apply preview");if(ce("Generating preview. Capturing screenshot..."),ue){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:ue});const Ue=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:ue,scenarioId:A.id,projectId:m.projectId,viewportWidth:1440})}),Ht=await Ue.json();!Ue.ok||!Ht.success?(console.error("[EntityDetail] Direct capture failed:",Ht),ce("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),ce('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Ue=new FormData;Ue.append("analysisId",m.id||""),Ue.append("scenarioId",A.id||"");const Ht=await fetch("/api/recapture-scenario",{method:"POST",body:Ue}),gr=await Ht.json();!Ht.ok||!gr.success?(console.warn("[EntityDetail] Recapture failed:",gr.error),ce("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",gr.jobId),ce('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}Q(Ue=>Ue+1),Ye.revalidate()}catch(_e){console.error("Error applying changes:",_e),ce(`Error: ${_e instanceof Error?_e.message:String(_e)}`)}finally{I(!1)}},ui=async(ne,xe)=>{var He;if(!A||!m){ce("Error: No scenario or analysis available");return}q(!0),ce(null),console.log("[EntityDetail] Saving scenario to database",{description:ne,saveAsNew:xe});try{const _e=Pe||((He=A.metadata)==null?void 0:He.data);let tt;if(xe){const Ge={...A,id:`${A.name}-${Date.now()}`,name:`${A.name} (Copy)`,metadata:{...A.metadata,data:_e},description:ne||A.description};tt=[...m.scenarios||[],Ge]}else tt=(m.scenarios||[]).map(Ge=>Ge.id===A.id?{...Ge,metadata:{...Ge.metadata,data:_e},description:ne||Ge.description}:Ge);const pn=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:tt})}),Wt=await pn.json();if(!pn.ok||!Wt.success)throw new Error(Wt.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),ce(xe?"New scenario created successfully":"Scenario saved successfully"),Me(null),Ye.revalidate()}catch(_e){console.error("Error saving scenario:",_e),ce(`Error: ${_e instanceof Error?_e.message:String(_e)}`)}finally{q(!1)}},hi=()=>{console.log("[EntityDetail] Edit mock data clicked"),ce("Mock data editor coming soon")},mi=async()=>{var ne;if(!(A!=null&&A.id)){Se("Cannot delete scenario without ID");return}ge(!0),Se(null);try{const xe=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:A.id,screenshotPaths:((ne=A.metadata)==null?void 0:ne.screenshotPaths)||[]})}),He=await xe.json();if(!xe.ok||!He.success)throw new Error(He.error||"Failed to delete scenario");L(`/entity/${d==null?void 0:d.sha}/scenarios`)}catch(xe){console.error("[EntityDetail] Error deleting scenario:",xe),Se(xe instanceof Error?xe.message:"Failed to delete scenario"),Ce(!1)}finally{ge(!1)}},fr=m&&d&&m.entitySha!==d.sha,pi=d?Jp(d):!1;return n(sr,{children:l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-end h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:_,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:d==null?void 0:d.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d==null?void 0:d.filePath,children:d==null?void 0:d.filePath})]}),n("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:M.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(ne=>n(se,{to:ii(ne.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${T===ne.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:T===ne.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[ne.label,ne.count!==void 0&&ne.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${T===ne.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:ne.count})]})},ne.id))})]})}),(g||fr&&!u||v&&pi)&&!Y&&!si&&n("div",{className:"border-b border-[#FEE585] px-6 py-3 flex items-center justify-center shrink-0",style:{backgroundColor:"#FEE585"},children:l("div",{className:"flex items-center gap-3",children:[n("svg",{className:"w-4 h-4",style:{color:"#714A25"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),n("span",{className:"text-sm font-semibold",style:{color:"#714A25"},children:fr&&!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.":fr?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),g&&x&&b?n(se,{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:ne=>{ne.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:ne=>{ne.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:Sa,disabled:We.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:ne=>{We.state==="idle"&&(ne.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:ne=>{We.state==="idle"&&(ne.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),l("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[T==="scenarios"&&l(he,{children:[ae&&A?n(Gp,{scenario:A,entitySha:(d==null?void 0:d.sha)||"",onApply:di,onSave:ui,onEditMockData:hi,onDelete:mi,isApplying:$,isSaving:D,saveMessage:te,showDeleteConfirm:be,onShowDeleteConfirm:Ce,isDeleting:me,deleteError:Ee}):n(Vp,{scenarios:M,hiddenScenarios:j,analysis:m,selectedScenario:A,entitySha:(d==null?void 0:d.sha)||"",cacheBuster:wa,activeTab:T,entityType:d==null?void 0:d.entityType,entity:d,queueState:S,processIsRunning:E,isEntityAnalyzing:Y,areScenariosStale:R,viewMode:W,setViewMode:ci,isBreakdownView:i==="breakdown"}),i==="breakdown"?n(Kp,{analysis:m??null,entitySha:(d==null?void 0:d.sha)||""}):ae&&A?n(or,{scenarioId:A.id||A.name,scenarioName:A.name,iframeUrl:ue,isStarting:ye,isLoading:xt,showIframe:de,iframeKey:Fe,onIframeLoad:Oe,projectSlug:p,defaultWidth:1440,defaultHeight:900}):l("div",{className:"flex flex-col flex-1 min-h-0",children:[A&&l("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[l("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:A.name}),l("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[Ca," × ",oi]})]}),l("div",{className:"flex items-center gap-2",children:[n(se,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${A.id}/edit`,className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors no-underline flex items-center",title:"Edit Scenario Data",children:"Edit Scenario"}),l("button",{className:"px-3 py-1.5 bg-[#022A35] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#011a21] transition-colors flex items-center gap-1.5",onClick:()=>{alert("Download functionality coming soon")},title:"Download",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"})}),"Download"]}),l(se,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${A.id}/fullscreen`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Interactive Mode",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:n("path",{d:"M8 5v14l11-7z"})}),"Interactive Mode"]})]})]}),n(Bo,{selectedScenario:A,analysis:m,entity:d,viewMode:W,cacheBuster:wa,hasScenarios:M.length>0,isAnalyzing:pr,projectSlug:p,hasAnApiKey:N,processIsRunning:E,queueState:S})]})]}),T==="related"&&n(Xp,{relatedEntities:f}),T==="data"&&n(rf,{entity:d,analysis:m,scenarios:M,onAnalyze:Sa}),T==="code"&&n(cf,{entity:d,entityCode:y}),T==="history"&&n(Qp,{entity:d,history:C})]}),ai&&p&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>mr(!1),children:l("div",{className:"bg-white rounded-xl max-w-[1200px] w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:ne=>ne.stopPropagation(),children:[l("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>mr(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(ht,{projectSlug:p,onClose:()=>mr(!1)})})]})})]})})}),pf=Object.freeze(Object.defineProperty({__proto__:null,default:mf,loader:hf,meta:df,shouldRevalidate:uf},Symbol.toStringTag,{value:"Module"}));async function ff(e){const{entityShas:t,filePaths:r,context:a,scenarioCount:s,queue:o}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await Le();const i=fe();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const c=ie.join(i,".codeyam","config.json"),d=JSON.parse(await pe.readFile(c,"utf8")),{projectSlug:h,branchId:u}=d;if(!h||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${h}, Branch: ${u}`);const m=nr(h);try{await pe.writeFile(m,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:p,branch:f}=await Ie(h);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const y=await rt({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 Zc(p,f,g);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await ut({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 C=v.currentRun;if(C&&C.id&&C.archivedAt)return;C&&(C.analysesCompleted&&C.analysesCompleted>0||C.capturesCompleted&&C.capturesCompleted>0)&&ld(v)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:b}=o.enqueue({type:"analysis",commitSha:x.sha,projectSlug:h,filePaths:g,entityShas:t,entityNames:y.map(v=>v.name),...a?{context:a}:{},...s?{scenarioCount:s}:{}});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 gf({request:e,context:t}){if(e.method!=="POST")return B({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await lt()),!r)return B({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("entitySha"),o=a.get("entityShas"),i=a.get("filePath"),c=a.get("context"),d=a.get("scenarioCount");let h;if(o)h=o.split(",").filter(Boolean);else if(s)h=[s];else return B({error:"Missing required field: entitySha or entityShas"},{status:400});if(h.length===0)return B({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${h.length} entity(ies)`);const u=await rt({shas:h}),p=[...new Set(u.map(y=>y.filePath).filter(y=>!!y))].length,{jobId:f}=await ff({entityShas:h,filePaths:i?[i]:void 0,context:c||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),B({success:!0,message:`Analysis queued for ${h.length} entity(ies)`,entityCount:h.length,fileCount:p,jobId:f})}catch(a){return console.error("[API] Error starting analysis:",a),B({error:"Failed to start analysis",details:a.message},{status:500})}}const yf=Object.freeze(Object.defineProperty({__proto__:null,action:gf},Symbol.toStringTag,{value:"Module"}));function xf(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function Wo(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 s=t.getHours(),o=t.getMinutes(),i=s>=12?"pm":"am",c=s%12||12,d=o.toString().padStart(2,"0");return`Today, ${c}:${d} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function qe(e,t=[],r=!1){var u,m;if(t.some(p=>{var f,y;return!!((f=p.entityShas)!=null&&f.includes(e.sha)||(y=p.entities)!=null&&y.some(g=>g.sha===e.sha))}))return r?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const s=e.analyses[0];if(!(((u=s.status)==null?void 0:u.scenarios)&&s.status.scenarios.length>0&&s.status.scenarios.some(p=>p.screenshotFinishedAt||p.finishedAt))||s.entitySha!==e.sha)return"not-analyzed";const i=s.createdAt?new Date(s.createdAt).getTime():0,c=(m=e.metadata)!=null&&m.editedAt?new Date(e.metadata.editedAt).getTime():0,d=s.scenarios||[],h=d.some(p=>{var f,y,g;return((y=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||((g=p.metadata)==null?void 0:g.executionResult)});return i>=c?d.length>0&&h?d.every(f=>{var y,g,x;return((g=(y=f.metadata)==null?void 0:y.screenshotPaths)==null?void 0:g[0])||((x=f.metadata)==null?void 0:x.executionResult)})?"up-to-date":"incomplete":d.length>0?"incomplete":"not-analyzed":"out-of-date"}const bf=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function vf({request:e,context:t}){try{const r=t.analysisQueue,a=r?r.getState():{paused:!1,jobs:[]},s=await dn();return B({entities:s||[],queueState:a})}catch(r){return console.error("Failed to load simulations:",r),B({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const wf=De(function(){const t=Be(),r=t.entities,a=t.queueState;Xe({source:"simulations-page"});const[s,o]=P(""),[i,c]=P("visual"),d=re(()=>{const g=[];return r.forEach(x=>{var v;const b=(v=x.analyses)==null?void 0:v[0];if(b!=null&&b.scenarios){const C=b.scenarios.filter(w=>{var N;return!((N=w.metadata)!=null&&N.sameAsDefault)}).map(w=>{var F,_,E,T,O;const N=(_=(F=w.metadata)==null?void 0:F.screenshotPaths)==null?void 0:_[0],S=(E=w.metadata)==null?void 0:E.noScreenshotSaved,k=N&&!S,M=(O=(T=b.status)==null?void 0:T.scenarios)==null?void 0:O.find(G=>G.name===w.name),j=M&&M.screenshotStartedAt&&!M.screenshotFinishedAt;let L;return k?L="completed":j?L="capturing":L="error",{scenarioName:w.name,scenarioDescription:w.description||"",screenshotPath:N||"",scenarioId:w.id,state:L}}).filter(w=>w.state==="completed"||w.state==="capturing");C.length>0&&g.push({entity:x,screenshots:C,createdAt:b.createdAt||""})}}),g.sort((x,b)=>new Date(b.createdAt).getTime()-new Date(x.createdAt).getTime()),g},[r]),h=re(()=>r.filter(g=>{var v,C;const x=(v=g.analyses)==null?void 0:v[0];return!((C=x==null?void 0:x.scenarios)==null?void 0:C.some(w=>{var N,S;return(S=(N=w.metadata)==null?void 0:N.screenshotPaths)==null?void 0:S[0]}))}),[r]),u=re(()=>d.filter(({entity:g})=>{const x=!s||g.name.toLowerCase().includes(s.toLowerCase()),b=i==="all"||g.entityType===i;return x&&b}),[d,s,i]),m=re(()=>h.filter(g=>{const x=!s||g.name.toLowerCase().includes(s.toLowerCase()),b=i==="all"||g.entityType===i;return x&&b}),[h,s,i]),p=oe(g=>{o(g.target.value)},[]),f=oe(g=>{c(g.target.value)},[]),y=d.length>0;return n("div",{className:"bg-[#F8F7F6] min-h-screen overflow-y-auto",children:l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!y&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:l("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",n("strong",{children:"Start by analyzing your first component below."})]})}),l("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),l("div",{className:"flex gap-3",children:[l("div",{className:"relative",children:[l("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 pr-8 text-[13px] h-[39px] cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:i,onChange:f,children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(mt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"flex-1 relative",children:[n(on,{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:s,onChange:p})]})]})]}),y&&u.length>0&&n("div",{className:"mb-2",children:l("div",{className:"flex items-center py-3",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:u.length})," ",u.length===1?"entity":"entities"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:u.reduce((g,{screenshots:x})=>g+x.length,0)})," ","scenarios"]})]})}),l("div",{className:"flex flex-col gap-3",children:[y&&(u.length===0?n("div",{className:"bg-white border border-gray-200 rounded-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):n(he,{children:u.map(({entity:g,screenshots:x})=>n(Cf,{entity:g,screenshots:x,queueJobs:(a==null?void 0:a.jobs)||[]},g.sha))})),!y&&(m.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."}):m.map(g=>n(Nf,{entity:g},g.sha)))]})]})})});function Cf({entity:e,screenshots:t,queueJobs:r}){var f,y,g;const a=Mt(),s=Ae(),[o,i]=P(!1),c=t.length||(((g=(y=(f=e.analyses)==null?void 0:f[0])==null?void 0:y.scenarios)==null?void 0:g.length)??0),d=x=>{a(`/entity/${e.sha}/scenarios/${x}?from=simulations`)},h=()=>{i(!0),s.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};ee(()=>{s.state==="idle"&&o&&i(!1)},[s.state,o]);const u=qe(e,r),m=xf(u),p=u==="out-of-date";return n("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:l("div",{className:"flex flex-col",children:[l("div",{className:"flex items-center px-[15px] py-[15px]",children:[n("div",{className:"flex-shrink-0",children:n(Je,{type:e.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[l("div",{className:"flex items-center gap-[5px]",children:[l(se,{to:`/entity/${e.sha}`,className:"hover:underline cursor-pointer",title:e.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:[e.name," (",c,")"]}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:m.bgColor,color:m.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:m.text})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),l("div",{className:"flex-shrink-0 flex items-center gap-2",children:[p&&n(he,{children:o||s.state!=="idle"?l("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[n(Ze,{size:14,className:"animate-spin",style:{color:"#be185d"}}),n("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):n("button",{onClick:h,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 a(`/entity/${e.sha}/logs`),className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})]})]}),n("div",{className:"border-t border-gray-200"}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:t.length>0?t.map(x=>l("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>d(x.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:x.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:x.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:b=>{x.state==="completed"&&(b.currentTarget.style.borderColor="#005C75",b.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:b=>{b.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",b.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(ze,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(da,{size:"medium"}):null})}),l("div",{className:"relative group",children:[n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.scenarioName}),n("div",{className:"fixed hidden group-hover:block pointer-events-none",style:{zIndex:1e4,transform:"translateY(8px)"},children:l("div",{className:"bg-gray-100 text-gray-800 text-xs rounded-lg px-3 py-2 shadow-lg max-w-xs border border-gray-200",children:[x.scenarioName,x.scenarioDescription&&l(he,{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 Nf({entity:e}){const t=Ae(),[r,a]=P(!1),s=()=>{a(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return ee(()=>{t.state==="idle"&&r&&a(!1)},[t.state,r]),n("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:s,children:l("div",{className:"px-5 py-4 flex items-center",children:[l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(Je,{type:e.entityType}),l("div",{className:"min-w-0",children:[l("div",{className:"flex items-center gap-3 mb-0.5",children:[n(se,{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:Wo(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?l("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(Ze,{size:14,className:"animate-spin"}),"Analyzing..."]}):n("button",{onClick:s,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 Sf=Object.freeze(Object.defineProperty({__proto__:null,default:wf,loader:vf,meta:bf},Symbol.toStringTag,{value:"Module"}));function Ef({request:e,context:t}){const r=t.dbNotifier||Dr;if(!r)return console.error("[SSE] ERROR: dbNotifier not found in context or global!"),new Response("Server configuration error",{status:500});r.start().catch(()=>{});const a=new ReadableStream({start(s){const o=new TextEncoder;s.enqueue(o.encode(`data: ${JSON.stringify({type:"connected"})}
227
-
228
- `)),Math.random().toString(36).substring(7);let i=!1;const c=()=>{if(!i){i=!0,r.off("change",d),clearInterval(h);try{s.close()}catch{}}},d=u=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
229
-
230
- `))}catch{c()}};r.on("change",d);const h=setInterval(()=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
231
-
232
- `))}catch{c()}},3e4);e.signal.addEventListener("abort",c)}});return new Response(a,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const Af=Object.freeze(Object.defineProperty({__proto__:null,loader:Ef},Symbol.toStringTag,{value:"Module"}));function kf(){return new Response(JSON.stringify({status:"ok",version:aa,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const Pf=Object.freeze(Object.defineProperty({__proto__:null,loader:kf},Symbol.toStringTag,{value:"Module"}));function ma(e){const t=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,r=e.match(t);if(!r)return{frontmatter:{},body:e};const a=r[1],s=r[2],o={},i=a.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/);i&&(o.paths=i[1].split(`
233
- `).filter(d=>d.trim().startsWith("-")).map(d=>d.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean));const c=a.match(/^category:\s*(.+)$/m);return c&&(o.category=c[1].replace(/['"]/g,"").trim()),{frontmatter:o,body:s}}async function cr(e,t=""){const r=[];try{const a=await pe.readdir(e,{withFileTypes:!0});for(const s of a){const o=t?`${t}/${s.name}`:s.name;if(s.isDirectory()){const i=await cr(ie.join(e,s.name),o);r.push(...i)}else s.isFile()&&s.name.endsWith(".md")&&r.push(o)}}catch{}return r}async function dr(e){const t=await cr(e),r=[];for(const a of t){const s=ie.join(e,a);try{const o=await pe.readFile(s,"utf-8"),{frontmatter:i,body:c}=ma(o);r.push({filePath:a,absolutePath:s,frontmatter:i,body:c})}catch{}}return r}function _f(e,t){return!t.frontmatter.paths||t.frontmatter.paths.length===0?!1:t.frontmatter.paths.some(r=>Bs(e,r,{matchBase:!0}))}const Mf="codeyam-rule-state.json",jr=1;function Ho(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return Vn.createHash("sha256").update(t).digest("hex")}function Jo(e){return ie.join(e,".claude",Mf)}async function Vo(e){const t=Jo(e);try{const r=await pe.readFile(t,"utf-8"),a=JSON.parse(r);return a.version!==jr?(console.warn(`[ruleState] Unknown version ${a.version}, using empty state`),{version:jr,rules:{}}):a}catch{return{version:jr,rules:{}}}}async function Go(e,t){const r=Jo(e),a=ie.dirname(r);await pe.mkdir(a,{recursive:!0}),await pe.writeFile(r,JSON.stringify(t,null,2)+`
234
- `,"utf-8")}async function pa(e,t){const r=await Vo(e),a=new Set(t.map(s=>s.filePath));for(const s of Object.keys(r.rules))a.has(s)||delete r.rules[s];for(const s of t){const o=await pe.readFile(s.absolutePath,"utf-8"),i=Ho(o),c=r.rules[s.filePath];c?c.contentHash!==i&&(r.rules[s.filePath]={...c,contentHash:i,reviewed:!1}):r.rules[s.filePath]={contentHash:i,reviewed:!1}}return await Go(e,r),r}async function Ps(e,t,r,a){const s=await Vo(e);if(r){const o=ie.join(e,".claude","rules"),i=ie.join(o,t),c=await pe.readFile(i,"utf-8"),d=Ho(c);s.rules[t]?(s.rules[t].reviewed=!0,s.rules[t].contentHash=d):s.rules[t]={contentHash:d,reviewed:!0}}else s.rules[t]&&(s.rules[t].reviewed=!1);await Go(e,s)}function fa(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function qo(e,t=""){const r=[],a=await pe.readdir(e,{withFileTypes:!0});for(const s of a){const o=t?`${t}/${s.name}`:s.name;s.isDirectory()?r.push(...await qo(ie.join(e,s.name),o)):s.name.endsWith(".md")&&r.push(o)}return r}function Ko(e){if(!e||e==="(diff not available)")return!1;const t=e.split(`
235
- `).filter(a=>!(!a.startsWith("+")&&!a.startsWith("-")||a.startsWith("+++")||a.startsWith("---"))).map(a=>a.substring(1).trim());if(t.length===0)return!1;const r=/^(category:\s*\w+)$/;return t.every(a=>r.test(a))}async function Tf({request:e}){const t=fe();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=new URL(e.url),a=r.searchParams.get("action"),s=ie.join(t,".claude","rules");if(a==="recent-changes")return If(t,s);if(a==="reviewed-status")return $f(t,s);if(a==="audit")return Rf(t,s);if(a==="source-files")return Df(t);if(a==="rules-for-path"){const o=r.searchParams.get("path");return o?Lf(s,o):Response.json({error:"Missing required parameter: path"},{status:400})}try{const o=await cr(s),i=[];for(const m of o){const p=ie.join(s,m);try{const f=await pe.readFile(p,"utf-8"),y=await pe.stat(p),{frontmatter:g,body:x}=ma(f);i.push({filePath:m,content:f,frontmatter:g,body:x,lastModified:y.mtime.toISOString()})}catch{}}i.sort((m,p)=>new Date(p.lastModified).getTime()-new Date(m.lastModified).getTime());let c=i.length>0;if(!c)try{await pe.access(ie.join(t,".claude","codeyam-rule-state.json")),c=!0}catch{}const d=await dr(s),h=await pa(t,d),u={};for(const m of d)u[m.filePath]=fa(h,m.filePath);return Response.json({memories:i,memoryInitialized:c,reviewedStatus:u})}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 jf(e,t){const r=[];try{const a=t("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const s of a.split(`
236
- `).filter(Boolean)){const o=s.substring(0,2);let i=s.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const c=o[0],d=o[1];let h=[i];if(i.endsWith("/")&&c==="?"){const u=ie.join(e,i);try{h=(await qo(u)).map(p=>i+p)}catch{continue}}for(const u of h){if(u.endsWith("/"))continue;const m=u.replace(".claude/rules/","");let p="modified";c==="A"||c==="?"?p="added":c==="D"||d==="D"?p="deleted":(c==="M"||d==="M")&&(p="modified");let f="";try{if(p==="deleted")f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(p==="added"&&c==="?"){const y=`${e}/${u}`;try{const g=await pe.readFile(y,"utf-8");f=`diff --git a/${u} b/${u}
237
- new file mode 100644
238
- --- /dev/null
239
- +++ b/${u}
240
- @@ -0,0 +1,${g.split(`
241
- `).length} @@
242
- ${g.split(`
243
- `).map(x=>"+"+x).join(`
244
- `)}`}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)+`
245
- ... (truncated)`)}catch{f="(diff not available)"}p==="modified"&&Ko(f)||r.push({filePath:m,changeType:p,diff:f})}}}catch{}return r}async function If(e,t){try{const{execSync:r}=await import("child_process"),a=[],s=await dr(t),o=await pa(e,s),i={};for(const m of s)i[m.filePath]=fa(o,m.filePath);const d=(await jf(e,r)).filter(m=>!i[m.filePath]);d.length>0&&a.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:d});const u=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(`
246
- `).filter(Boolean).slice(0,20);for(const m of u){const[p,f,...y]=m.split("|"),g=y.join("|");if(!p||!f)continue;const x=r(`git diff-tree --no-commit-id --name-status -r ${p} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),b=[];for(const v of x.split(`
247
- `).filter(Boolean)){const[C,w]=v.split(" ");if(!w||!w.startsWith(".claude/rules/"))continue;const N=w.replace(".claude/rules/","");let S="modified";if(C==="A"?S="added":C==="D"&&(S="deleted"),i[N])continue;let k="";try{k=r(`git show ${p} --format="" -- "${w}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),k.length>5e3&&(k=k.substring(0,5e3)+`
248
- ... (truncated)`)}catch{k="(diff not available)"}S==="modified"&&Ko(k)||b.push({filePath:N,changeType:S,diff:k})}b.length>0&&a.push({commitHash:p.substring(0,8),date:f,message:g,files:b})}return Response.json({changes:a,reviewedStatus:i})}catch(r){return console.error("[API] Error getting recent changes:",r),Response.json({changes:[],reviewedStatus:{}})}}async function $f(e,t){try{const r=await dr(t),a=await pa(e,r),s={};for(const o of r)s[o.filePath]=fa(a,o.filePath);return Response.json({reviewedStatus:s})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function Qo(e){const t=[],r=[".ts",".tsx",".js",".jsx",".vue",".svelte"];async function a(s,o){try{const i=await pe.readdir(s,{withFileTypes:!0});for(const c of i){const d=ie.join(s,c.name),h=o?`${o}/${c.name}`:c.name;if(!(c.isDirectory()&&(c.name==="node_modules"||c.name===".git"||c.name==="dist"||c.name===".codeyam"||c.name===".claude"||c.name==="build"||c.name==="coverage"))){if(c.isDirectory())await a(d,h);else if(c.isFile()){const u=ie.extname(c.name);r.includes(u)&&t.push(h)}}}}catch{}}return await a(e,""),t}async function Rf(e,t){try{const r=await dr(t),a=await Qo(e),s=[];for(const o of a){const i=r.filter(c=>_f(o,c));if(i.length>0){const c=i.reduce((d,h)=>d+h.body.length,0);s.push({filePath:o,matchingRules:i.map(d=>({filePath:d.filePath,patterns:d.frontmatter.paths||[],bodyLength:d.body.length})),totalTextLength:c})}}return s.sort((o,i)=>i.totalTextLength-o.totalTextLength),Response.json({topPaths:s,totalFilesWithCoverage:s.length,allSourceFiles:a})}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 Df(e){try{const t=await Qo(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 Lf(e,t){try{const r=await cr(e),a=[];for(const o of r){const i=ie.join(e,o);try{const c=await pe.readFile(i,"utf-8"),d=await pe.stat(i),{frontmatter:h,body:u}=ma(c);h.paths&&h.paths.some(m=>Bs(t,m,{matchBase:!0}))&&a.push({filePath:o,content:c,frontmatter:h,body:u,lastModified:d.mtime.toISOString()})}catch{}}const s=a.reduce((o,i)=>o+i.body.length,0);return Response.json({rules:a,totalTextLength:s})}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 Ff({request:e}){const t=fe();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=ie.join(t,".claude","rules");try{const a=await e.json(),{action:s,filePath:o,content:i,lastModified:c}=a;if(!o)return Response.json({error:"Missing required field: filePath"},{status:400});if(s==="mark-reviewed")return await Ps(t,o,!0),console.log(`[API] Rule marked as reviewed: ${o}`),Response.json({success:!0,message:"Rule marked as reviewed",filePath:o});if(s==="mark-unreviewed")return await Ps(t,o,!1),console.log(`[API] Rule marked as unreviewed: ${o}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:o});const d=ie.normalize(o);if(d.includes("..")||ie.isAbsolute(d))return Response.json({error:"Invalid file path"},{status:400});const h=ie.join(r,d);switch(s){case"create":case"update":return i?(await pe.mkdir(ie.dirname(h),{recursive:!0}),await pe.writeFile(h,i,"utf-8"),console.log(`[API] Memory ${s}d: ${o}`),Response.json({success:!0,message:`Memory ${s}d successfully`,filePath:o})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await pe.unlink(h),console.log(`[API] Memory deleted: ${o}`);const u=ie.dirname(h);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(a){return console.error("[API] Error managing memory:",a),Response.json({error:"Failed to manage memory",details:a instanceof Error?a.message:String(a)},{status:500})}}const Of=Object.freeze(Object.defineProperty({__proto__:null,action:Ff,loader:Tf},Symbol.toStringTag,{value:"Module"}));async function Yf({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await lt()),!r)return B({error:"Queue not initialized"},{status:500});const a=new URL(e.url),s=a.searchParams.get("queryType");if(!s)return B({error:"Missing queryType parameter for GET request"},{status:400});if(s==="job"){const i=a.searchParams.get("jobId");if(!i)return B({error:"Missing jobId parameter for job query"},{status:400});const c=r.getState();if(((o=c.currentlyExecuting)==null?void 0:o.id)===i)return B({jobId:i,status:"running",job:c.currentlyExecuting});const d=c.jobs.find(u=>u.id===i);if(d){const u=c.jobs.indexOf(d);return B({jobId:i,status:"queued",position:u,job:d})}const h=r.getJobResult(i);return h?B({jobId:i,status:h.status==="error"?"failed":"completed",error:h.error}):B({jobId:i,status:"completed"})}if(s==="full"){const i=r.getState(),c=await Promise.all(i.jobs.map(async h=>{const u=[];if(h.entityShas&&h.entityShas.length>0){const m=h.entityShas.map(f=>Dt(f)),p=await Promise.all(m);u.push(...p.filter(f=>f!==null))}return{id:h.id,type:h.type,commitSha:h.commitSha,projectSlug:h.projectSlug,queuedAt:h.queuedAt,entities:u,filePaths:h.filePaths}}));let d;if(i.currentlyExecuting){const h=i.currentlyExecuting,u=[];if(h.entityShas&&h.entityShas.length>0){const m=h.entityShas.map(f=>Dt(f)),p=await Promise.all(m);u.push(...p.filter(f=>f!==null))}d={id:h.id,type:h.type,commitSha:h.commitSha,projectSlug:h.projectSlug,queuedAt:h.queuedAt,entities:u,filePaths:h.filePaths}}return B({state:{...i,jobsWithEntities:c,currentlyExecutingWithEntities:d}})}return B({error:"Unknown queryType"},{status:400})}async function zf({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 lt(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),B({error:"Queue not initialized"},{status:500});const a=await e.json(),{action:s,...o}=a;if(console.log("[Queue API] Action:",s,"Params:",Object.keys(o)),s==="enqueue"){const{jobId:i,completion:c}=r.enqueue(o);return c.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),B({jobId:i,status:"queued"})}if(s==="resume")return r.resume(),B({status:"resumed"});if(s==="pause")return r.pause(),B({status:"paused"});if(s==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?B({status:"removed",jobId:i}):B({error:"Job not found in queue"},{status:404}):B({error:"Missing jobId parameter"},{status:400})}if(s==="clear"){const i=r.clearQueue();return B({status:"cleared",count:i})}if(s==="reorder"){const{jobId:i,direction:c}=o;return!i||!c?B({error:"Missing jobId or direction parameter"},{status:400}):c!=="up"&&c!=="down"?B({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,c)?B({status:"reordered",jobId:i,direction:c}):B({error:"Could not reorder job (not found or at boundary)"},{status:400})}return B({error:"Unknown action"},{status:400})}const Bf=Object.freeze(Object.defineProperty({__proto__:null,action:zf,loader:Yf},Symbol.toStringTag,{value:"Module"})),Uf=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],Wf=De(function(){return Ae(),n(sr,{children:l("div",{className:"h-screen bg-[#F8F7F6] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-center h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0",children:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[l("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),l("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:l("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[l("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded bg-[#343434] text-[#efefef] font-semibold h-8",children:["Scenarios",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),l("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),l("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(Bo,{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})]})]})})}),Hf=Object.freeze(Object.defineProperty({__proto__:null,default:Wf,meta:Uf},Symbol.toStringTag,{value:"Module"})),Jf=()=>[{title:"Settings - CodeYam"},{name:"description",content:"Configure project settings"}];async function Vf({request:e}){var t,r;try{const a=await er();if(!a)return B({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Project configuration not found"});let s=!1;try{const d=await $e();if(d){const{project:h}=await Ie(d);s=((r=(t=h.metadata)==null?void 0:t.labs)==null?void 0:r.simulations)===!0}}catch{}const o=fe()||process.cwd(),i=await tr(o),c=Co(a.projectSlug);return B({config:a,secrets:{GROQ_API_KEY:i.GROQ_API_KEY||"",ANTHROPIC_API_KEY:i.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:i.OPENAI_API_KEY||""},versionInfo:c,simulationsEnabled:s,error:null})}catch(a){return console.error("Failed to load config:",a),B({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Failed to load configuration"})}}function Gf(e){if(!e||!e.trim())return;const t=e.trim().split(/\s+/);if(t.length===0)return;const r=t[0],a=t.length>1?t.slice(1):void 0;return{command:r,args:a}}async function qf({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),a=t.get("startCommands"),s=t.get("groqApiKey"),o=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),c=t.get("pathsToIgnore"),d=t.get("memorySettings");let h;if(r)try{h=JSON.parse(r)}catch{return B({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let u;if(a)try{u=JSON.parse(a)}catch{return B({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let m;c&&(m=c.split(",").map(x=>x.trim()).map(x=>x.startsWith('"')&&x.endsWith('"')||x.startsWith("'")&&x.endsWith("'")?x.slice(1,-1):x).filter(x=>x.length>0));let p;if(d)try{p=JSON.parse(d)}catch{return B({success:!1,error:"Invalid memorySettings JSON format",requiresRestart:!1},{status:400})}let f;if(u){const x=await er();x!=null&&x.webapps&&(f=x.webapps.map((b,v)=>{if(u[v]!==void 0){const C=Gf(u[v]);return{...b,startCommand:C}}return b}))}if(!await mo({universalMocks:h,pathsToIgnore:m,webapps:f,memory:p}))return B({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let g=!1;if(s!==void 0||o!==void 0||i!==void 0){const x=fe()||process.cwd(),b=await tr(x);g=s!==void 0&&s!==(b.GROQ_API_KEY||"")||o!==void 0&&o!==(b.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(b.OPENAI_API_KEY||""),await ed(x,{...b,GROQ_API_KEY:s||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return B({success:!0,error:null,requiresRestart:g})}catch(t){return console.log("[Settings Action] Failed to save config:",t),B({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function _s(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Ms({mock:e,onSave:t,onCancel:r}){const[a,s]=P(e.entityName),[o,i]=P(e.filePath),[c,d]=P(e.content);return l("div",{className:"space-y-3",children:[l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:a,onChange:u=>s(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., determineDatabaseType"})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:o,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:c,onChange:u=>d(u.target.value),rows:6,className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., function determineDatabaseType() { return 'postgresql' }"})]}),l("div",{className:"flex gap-2 justify-end",children:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!a.trim()||!o.trim()||!c.trim()){alert("All fields are required");return}t({entityName:a,filePath:o,content:c})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function Kf(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const Qf=De(function(){var Ee,Se,Pe,Me,ve;const{config:t,secrets:r,versionInfo:a,simulationsEnabled:s,error:o}=Be(),i=Ai(),c=Ae(),d=at(),[h,u]=P(s?"project-metadata":"memory");Xe({source:"settings-page"});const[m,p]=P((t==null?void 0:t.universalMocks)||[]),[f,y]=P(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,x]=P(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[b,v]=P((r==null?void 0:r.GROQ_API_KEY)||""),[C,w]=P((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[N,S]=P((r==null?void 0:r.OPENAI_API_KEY)||""),[k,M]=P(!1),[j,L]=P(!1),[F,_]=P(!1),[E,T]=P(!1),[O,G]=P(!1),[V,U]=P(!1),[z,Y]=P(null),[R,A]=P(!1),[H,W]=P({}),[J,ae]=P(((Ee=t==null?void 0:t.memory)==null?void 0:Ee.conversationReflection)??!0),[$,I]=P(((Se=t==null?void 0:t.memory)==null?void 0:Se.ruleMaintenance)??!0),[D,q]=P(((Pe=t==null?void 0:t.memory)==null?void 0:Pe.promptModel)??"haiku");ee(()=>{var Q,ue,ye,xt;if(t){p(t.universalMocks||[]);const de=(t.pathsToIgnore||[]).join(", ");y(de),x(de);const Fe={};(Q=t.webapps)==null||Q.forEach((Oe,Bt)=>{Oe.startCommand&&(Fe[Bt]=_s(Oe.startCommand))}),W(Fe),ae(((ue=t.memory)==null?void 0:ue.conversationReflection)??!0),I(((ye=t.memory)==null?void 0:ye.ruleMaintenance)??!0),q(((xt=t.memory)==null?void 0:xt.promptModel)??"haiku")}r&&(v(r.GROQ_API_KEY||""),w(r.ANTHROPIC_API_KEY||""),S(r.OPENAI_API_KEY||""))},[t,r]),ee(()=>{if(i!=null&&i.success){T(!0);const Q=setTimeout(()=>T(!1),3e3);return()=>clearTimeout(Q)}},[i]),ee(()=>{if(c.state==="idle"&&c.data&&!V){console.log("[Settings] Fetcher data:",c.data);const Q=c.data;if(Q.success){console.log("[Settings] Save successful, revalidating..."),T(!0),U(!0),(f!==g||Q.requiresRestart)&&G(!0),d.revalidate();const ue=setTimeout(()=>{T(!1),U(!1)},3e3);return()=>clearTimeout(ue)}}},[c.state,c.data,V,d,f,g]);const te=Q=>{Q.preventDefault();const ue=new FormData(Q.currentTarget);ue.set("universalMocks",JSON.stringify(m)),ue.set("startCommands",JSON.stringify(H)),ue.set("memorySettings",JSON.stringify({conversationReflection:J,ruleMaintenance:$,promptModel:D})),console.log("[Settings] Submitting form data:",{universalMocks:ue.get("universalMocks"),startCommands:ue.get("startCommands"),openAiApiKey:ue.get("openAiApiKey")?"***":"(empty)"}),c.submit(ue,{method:"post"})},ce=Q=>{p([...m,Q]),A(!1)},me=(Q,ue)=>{const ye=[...m];ye[Q]=ue,p(ye),Y(null)},ge=Q=>{p(m.filter((ue,ye)=>ye!==Q))};if(o)return l("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:o})})]});const be=[{id:"project-metadata",label:"Project Metadata"},{id:"ai-provider",label:"AI Provider Configuration"},{id:"commands",label:"Commands"},{id:"paths-to-ignore",label:"Paths To Ignore"},{id:"universal-mocks",label:"Universal Mocks"},{id:"memory",label:"Memory"},{id:"current-configuration",label:"Current Configuration"}],Ce=s?be:be.filter(Q=>Q.id==="memory");return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 pt-8 pb-12 font-sans",children:[l("div",{className:"mb-8 flex justify-between items-start",children:[l("div",{children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Settings"}),n("p",{className:"text-[15px] text-gray-500",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:c.state==="submitting",className:"px-6 py-2 bg-[#005C75] text-white border-none rounded text-sm font-medium cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 hover:bg-[#004a5d] whitespace-nowrap",children:c.state==="submitting"?"Saving...":"Save Settings"})]}),l("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8 items-start",children:[n("nav",{className:"w-full lg:w-64 flex-shrink-0",children:n("ul",{className:"flex lg:flex-col overflow-x-auto gap-1",children:Ce.map(Q=>n("li",{children:n("button",{type:"button",onClick:()=>u(Q.id),className:`w-full text-left px-3 lg:px-0 py-2.5 text-sm transition-colors cursor-pointer whitespace-nowrap ${h===Q.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:Q.label})},Q.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:l("form",{id:"settings-form",onSubmit:te,className:"space-y-6",children:[h==="project-metadata"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),l("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((Q,ue)=>{var ye;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:Q.path==="."?"Root":Q.path})]}),Q.appDirectory&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:Q.appDirectory})]}),l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:Q.framework})]}),Q.startCommand&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",l("span",{className:"text-gray-900 font-mono text-xs",children:[Q.startCommand.command," ",(ye=Q.startCommand.args)==null?void 0:ye.join(" ")]})]})]})},ue)})}):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`."})]})]}),h==="ai-provider"&&l("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),l("div",{className:"space-y-6",children:[l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:k?"text":"password",id:"groqApiKey",name:"groqApiKey",value:b,onChange:Q=>v(Q.target.value),placeholder:"gsk_...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>M(!k),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:k?"Hide":"Show"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:j?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:C,onChange:Q=>w(Q.target.value),placeholder:"sk-ant-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>L(!j),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:j?"Hide":"Show"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:F?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:N,onChange:Q=>S(Q.target.value),placeholder:"sk-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),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:F?"Hide":"Show"})]})]})]})]})]}),h==="commands"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((Q,ue)=>l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[l("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:Q.path==="."?"Root":Q.path}),n("div",{className:"text-sm text-gray-600",children:Q.framework})]}),l("div",{children:[n("label",{htmlFor:`startCommand-${ue}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${ue}`,name:`startCommand-${ue}`,value:H[ue]||"",onChange:ye=>W({...H,[ue]:ye.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"})]})]},ue))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),h==="paths-to-ignore"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:f,onChange:Q=>y(Q.target.value),placeholder:"e.g., __tests__, \\.test\\.ts$, ^background (no quotes needed)",className:"w-full px-3 py-3 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-2 focus:ring-[#005C75]/10"}),l("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",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"})]})]}),h==="universal-mocks"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),m.length===0?l("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>A(!0),className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}):n("div",{className:"space-y-3",children:m.map((Q,ue)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:z===ue?n(Ms,{mock:Q,onSave:ye=>me(ue,ye),onCancel:()=>Y(null)}):n(he,{children:l("div",{className:"flex justify-between items-start mb-2",children:[l("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:Q.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:Q.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:Q.content})]}),l("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>Y(ue),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:()=>ge(ue),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},ue))}),m.length>0&&n("button",{type:"button",onClick:()=>A(!0),className:"mt-4 px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}),h==="memory"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Memory"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure how CodeYam reflects on conversations and maintains rules between sessions."}),l("div",{className:"space-y-6",children:[n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Conversation Reflection"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent reviews the session for architectural decisions, tribal knowledge, confusion, or corrections that future sessions would benefit from knowing. It creates or updates Claude Rules based on what it learns."})]}),n("button",{type:"button",role:"switch","aria-checked":J,onClick:()=>ae(!J),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 ${J?"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 ${J?"translate-x-5":"translate-x-0"}`})})]})}),n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Rule Maintenance"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent checks if any existing Claude Rules have become stale based on recent code changes. It reviews the rule content against file diffs and updates rules that are out of date."})]}),n("button",{type:"button",role:"switch","aria-checked":$,onClick:()=>I(!$),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 ${$?"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 ${$?"translate-x-5":"translate-x-0"}`})})]})}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Memory Prompt Model"}),n("p",{className:"text-sm text-gray-600 mb-4",children:"Choose the Claude model used for conversation reflection and rule maintenance tasks."}),n("div",{className:"space-y-3",children:[{value:"haiku",label:"Haiku",badge:"Default, Recommended",description:"Fastest and cheapest. Good for routine reflection tasks."},{value:"sonnet",label:"Sonnet",badge:null,description:"Balanced speed and quality. Better at nuanced rule writing."},{value:"opus",label:"Opus",badge:null,description:"Highest quality. Best for complex architectural decisions. Costs significantly more."}].map(Q=>l("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${D===Q.value?"border-[#005C75] bg-[#005C75]/5":"border-gray-200 hover:border-gray-300"}`,children:[n("input",{type:"radio",name:"promptModel",value:Q.value,checked:D===Q.value,onChange:()=>q(Q.value),className:"mt-1 accent-[#005C75]"}),l("div",{children:[l("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-gray-900",children:Q.label}),Q.badge&&n("span",{className:"px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:Q.badge})]}),n("p",{className:"text-sm text-gray-600 mt-0.5",children:Q.description})]})]},Q.value))})]})]})]}),h==="current-configuration"&&l("div",{className:"space-y-6",children:[t&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:l("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&l("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((Q,ue)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:Q.path==="."?"Root":Q.path})]}),Q.appDirectory&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:Q.appDirectory})]}),l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:Q.framework})]}),Q.startCommand&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:_s(Q.startCommand)})]})]})},ue))})]})]}),a&&l("div",{className:"mt-6",children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[a.webserverVersion&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",n("span",{className:"text-gray-900 font-mono",children:a.webserverVersion.version||"unknown"})]}),a.templateVersion&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",n("span",{className:"font-mono text-gray-900",children:a.templateVersion.version||((Me=a.templateVersion.gitCommit)==null?void 0:Me.slice(0,7))||"unknown"}),a.templateVersion.buildTimestamp&&l("span",{className:"text-gray-500 ml-2",children:["(built"," ",Kf(a.templateVersion.buildTimestamp),")"]})]}),a.cachedAnalyzerVersion&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"font-mono text-gray-900",children:a.cachedAnalyzerVersion.version||((ve=a.cachedAnalyzerVersion.gitCommit)==null?void 0:ve.slice(0,7))||"unknown"}),a.isCacheStale?n("span",{className:"ml-2 px-2 py-0.5 bg-amber-100 text-amber-800 rounded text-xs",children:"Stale - will update on next analysis"}):n("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]}),!a.cachedAnalyzerVersion&&(t==null?void 0:t.projectSlug)&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),(E||O||(i==null?void 0:i.error)||c.data&&typeof c.data=="object"&&"error"in c.data)&&l("div",{className:"mt-6 max-w-5xl mx-auto space-y-3",children:[E&&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!"}),O&&l("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[n("div",{children:"⚠️ Settings changed. Please restart CodeYam for changes to take effect:"}),n("code",{className:"ml-2 bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"})]}),(i==null?void 0:i.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:i.error}),(()=>{if(c.data&&typeof c.data=="object"&&"error"in c.data){const Q=c.data;return typeof Q.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:Q.error}):null}return null})()]}),R&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:l("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[n("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),n(Ms,{mock:{entityName:"",filePath:"",content:""},onSave:ce,onCancel:()=>A(!1)})]})})]})})}),Zf=Object.freeze(Object.defineProperty({__proto__:null,action:qf,default:Qf,loader:Vf,meta:Jf},Symbol.toStringTag,{value:"Module"}));async function Xf({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=fe();if(!r)return new Response("Project root not found",{status:500});const s=ie.extname(t)!==""?t:`${t}.html`,o=ie.join(r,".codeyam","captures","static",s);try{await pe.access(o);let i=await pe.readFile(o);const c=ie.extname(o).toLowerCase();let d="application/octet-stream";if(c===".html"){d="text/html";let h=i.toString("utf-8");const u=h.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const p=u[1].match(/=\s*(\{[\s\S]*\})/);if(p){const f=JSON.parse(p[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const y=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;h=h.replace(u[0],y)}}catch(m){console.error("[Static] Failed to parse Remix context:",m)}i=Buffer.from(h,"utf-8")}else c===".js"||c===".mjs"?d="application/javascript":c===".css"?d="text/css":c===".json"?d="application/json":c===".png"?d="image/png":c===".jpg"||c===".jpeg"?d="image/jpeg":c===".svg"?d="image/svg+xml":c===".woff"?d="font/woff":c===".woff2"?d="font/woff2":c===".ttf"&&(d="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const eg=Object.freeze(Object.defineProperty({__proto__:null,loader:Xf},Symbol.toStringTag,{value:"Module"}));function tg(e,t,r=10){var d;const a=new Map,s=h=>h.entityType==="visual"||h.entityType==="library";for(const h of e)s(h)&&a.set(h.sha,{entity:h,depth:0});const o=new Map;for(const h of t){const u=(d=h.metadata)==null?void 0:d.importedBy;if(u)for(const m of Object.keys(u))for(const p of Object.keys(u[m])){const{shas:f}=u[m][p];for(const y of f)o.has(h.sha)||o.set(h.sha,new Set),o.get(h.sha).add(y)}}const i=[],c=new Set;for(const h of e)i.push({sha:h.sha,depth:0}),c.add(h.sha);for(;i.length>0;){const{sha:h,depth:u}=i.shift();if(u>=r)continue;const m=o.get(h);if(m)for(const p of m){if(c.has(p))continue;c.add(p);const f=t.find(y=>y.sha===p);if(f){if(s(f)){const y=u+1,g=a.get(p);(!g||y<g.depth)&&a.set(p,{entity:f,depth:y})}i.push({sha:p,depth:u+1})}}}return Array.from(a.values()).sort((h,u)=>h.depth!==u.depth?h.depth-u.depth:h.entity.name.localeCompare(u.entity.name))}function Un(e){const t=new Map;for(const a of e)t.has(a.name)||t.set(a.name,[]),t.get(a.name).push(a);const r=[];for(const a of t.values())if(a.length===1)r.push(a[0]);else{const s=a.sort((o,i)=>{var h,u;const c=((h=o.metadata)==null?void 0:h.editedAt)||o.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(c)});r.push(s[0])}return r}function Zo(e,t){const r=new Map,a=new Set(e.map(s=>s.path));for(const s of e)s.status==="renamed"&&s.oldPath&&a.add(s.oldPath);for(const s of e){const o=t.filter(d=>d.filePath===s.path||s.status==="renamed"&&s.oldPath&&d.filePath===s.oldPath),i=o.filter(d=>{var h,u;return a.has(d.filePath)&&((h=d.metadata)==null?void 0:h.isUncommitted)&&!((u=d.metadata)!=null&&u.isSuperseded)}),c=Un(i);r.set(s.path,{status:s,entities:o,editedEntities:c})}return r}function ng(e,t,r){const a=new Map;if(!r){for(const o of e)if(o.status==="deleted")a.set(o.path,{status:o,entities:[]});else{const i=t.filter(d=>d.filePath===o.path||o.status==="renamed"&&o.oldPath&&d.filePath===o.oldPath),c=Un(i);a.set(o.path,{status:o,entities:c})}return a}const s=new Map;for(const o of r.fileComparisons){const i=new Set;for(const c of o.newEntities)i.add(c.name);for(const c of o.modifiedEntities)i.add(c.name);for(const c of o.deletedEntities)i.add(c.name);i.size>0&&s.set(o.filePath,i)}for(const o of e){const i=s.get(o.path);if(o.status==="deleted")a.set(o.path,{status:o,entities:[]});else{const c=i?t.filter(h=>(h.filePath===o.path||o.status==="renamed"&&o.oldPath&&h.filePath===o.oldPath)&&i.has(h.name)):[],d=Un(c);a.set(o.path,{status:o,entities:d})}}return a}function rg(e,t){const r=new Map,a=Xo(e,t);for(const s of a){const i=tg([s],t).filter(({depth:c})=>c>0);r.set(s.sha,i)}return r}function Xo(e,t){const r=new Set(e.map(s=>s.path));for(const s of e)s.status==="renamed"&&s.oldPath&&r.add(s.oldPath);const a=t.filter(s=>{var o,i;return r.has(s.filePath)&&((o=s.metadata)==null?void 0:o.isUncommitted)&&!((i=s.metadata)!=null&&i.isSuperseded)});return Un(a)}function ag({recentSimulations:e}){const t=re(()=>{const r=new Map;return e.forEach(a=>{const s=a.entitySha,o=r.get(s);o?o.push(a):r.set(s,[a])}),Array.from(r.entries()).map(([a,s])=>({entitySha:a,entityName:s[0].entityName,scenarios:s}))},[e]);return l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:e.length>0?`Latest ${e.length} captured screenshot${e.length!==1?"s":""}`:"No simulations captured yet"})]})}),e.length>0?l(he,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>l("div",{children:[l("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(en,{size:16,style:{color:"#8B5CF6"}})}),n(se,{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((a,s)=>n(se,{to:a.scenarioId?`/entity/${a.entitySha}/scenarios/${a.scenarioId}`:`/entity/${a.entitySha}`,className:"aspect-4/3 border border-gray-200 rounded-lg overflow-hidden bg-gray-50 transition-all flex items-center justify-center hover:scale-105",onMouseEnter: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:a.scenarioName,children:n(ze,{screenshotPath:a.screenshotPath,alt:a.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},a.scenarioId||`${a.entitySha}-${s}`))})]},r.entitySha))}),n(se,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:r=>r.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:r=>r.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):l("div",{className:"py-12 px-6 text-center rounded-lg w-full flex flex-col items-center justify-center min-h-50 border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:n(en,{size:24,style:{color:"#7A9BA5"},strokeWidth:1.5})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No simulations captured yet."}),l("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",n(se,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(se,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const sg="/assets/codeyam-name-logo-CvKwUgHo.svg",og=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function ig({request:e,context:t}){var r,a,s,o;try{const i=await $e();if(i){const{project:_}=await Ie(i);if(!(((a=(r=_.metadata)==null?void 0:r.labs)==null?void 0:a.simulations)??!1))return ki("/memory")}const c=t.analysisQueue,d=c?c.getState():{paused:!1,jobs:[]},[h,u]=await Promise.all([dn(),Ot()]),m=$o(),p=h?Zo(m,h):new Map,f=Array.from(p.entries()).sort((_,E)=>_[0].localeCompare(E[0])),y=(h==null?void 0:h.length)||0,g=(h==null?void 0:h.filter(_=>_.entityType==="visual").length)||0,x=(h==null?void 0:h.filter(_=>_.entityType==="library").length)||0,b=h?Xo(m,h):[],v=b.length,C=(h==null?void 0:h.filter(_=>(_.analyses??[]).filter(E=>E.scenarios&&E.scenarios.length>0).length>0).length)||0,w=(h==null?void 0:h.reduce((_,E)=>{var O,G,V;const T=((V=(G=(O=E.analyses)==null?void 0:O[0])==null?void 0:G.scenarios)==null?void 0:V.length)||0;return _+T},0))||0,N=(h==null?void 0:h.reduce((_,E)=>{var G,V;const O=(((V=(G=E.analyses)==null?void 0:G[0])==null?void 0:V.scenarios)||[]).filter(U=>{var z,Y;return(Y=(z=U.metadata)==null?void 0:z.screenshotPaths)==null?void 0:Y[0]}).length;return _+O},0))||0,S=[];h==null||h.forEach(_=>{var T;const E=(T=_.analyses)==null?void 0:T[0];E!=null&&E.scenarios&&E.scenarios.filter(G=>{var V;return!((V=G.metadata)!=null&&V.sameAsDefault)}).forEach(G=>{var U,z;const V=(z=(U=G.metadata)==null?void 0:U.screenshotPaths)==null?void 0:z[0];V&&S.push({entitySha:_.sha,entityName:_.name,scenarioId:G.id,scenarioName:G.name,screenshotPath:V,createdAt:E.createdAt||""})})}),S.sort((_,E)=>new Date(E.createdAt).getTime()-new Date(_.createdAt).getTime());const k=S.slice(0,16),M=(h==null?void 0:h.filter(_=>_.entityType==="visual").filter(_=>{var O,G;const E=(O=_.analyses)==null?void 0:O[0];return!((G=E==null?void 0:E.scenarios)==null?void 0:G.some(V=>{var U,z;return(z=(U=V.metadata)==null?void 0:U.screenshotPaths)==null?void 0:z[0]}))}).slice(0,8))||[],j=(s=u==null?void 0:u.metadata)==null?void 0:s.currentRun,L=((o=j==null?void 0:j.currentEntityShas)==null?void 0:o.length)||0,F=d.jobs.length||0;return B({stats:{totalEntities:y,visualEntities:g,libraryEntities:x,uncommittedEntities:v,entitiesWithAnalyses:C,totalScenarios:w,capturedScreenshots:N,currentlyAnalyzing:L,filesOnQueue:F},uncommittedFiles:f,uncommittedEntitiesList:b,recentSimulations:k,visualEntitiesForSimulation:M,projectSlug:i,queueState:d,currentCommit:u})}catch(i){return console.error("Failed to load dashboard data:",i),B({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 lg=De(function(){var z,Y;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:a,recentSimulations:s,visualEntitiesForSimulation:o,projectSlug:i,queueState:c,currentCommit:d}=Be(),h=Ae(),u=at(),{showToast:m}=Zr();Xe({source:"dashboard"});const[p,f]=P(new Set),[y,g]=P(null),[x,b]=P(!1),[v,C]=P(!1),{lastLine:w,isCompleted:N}=ft(i,!!y),{simulatingEntity:S,scenarios:k,scenarioStatuses:M,allScenariosCaptured:j}=re(()=>{var I,D;const R={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!y)return R;const A=o==null?void 0:o.find(q=>q.sha===y);if(!A)return R;const H=(I=A.analyses)==null?void 0:I[0],W=(H==null?void 0:H.scenarios)||[],J=((D=H==null?void 0:H.status)==null?void 0:D.scenarios)||[],ae=J.filter(q=>q.screenshotFinishedAt).length,$=W.length>0&&ae===W.length;return{simulatingEntity:A,scenarios:W,scenarioStatuses:J,allScenariosCaptured:$}},[y,o]);ee(()=>{(N||j)&&g(null)},[N,j]);const L=(z=d==null?void 0:d.metadata)==null?void 0:z.currentRun,F=new Set((L==null?void 0:L.currentEntityShas)||[]),_=new Set(c.jobs.flatMap(R=>R.entityShas||[])),E=new Set(((Y=c.currentlyExecuting)==null?void 0:Y.entityShas)||[]),T=a.filter(R=>R.entityType==="visual"||R.entityType==="library"),O=T.filter(R=>!F.has(R.sha)&&!_.has(R.sha)&&!E.has(R.sha)),G=()=>{if(O.length===0){m("All entities are already queued or analyzing","info",3e3);return}const R=O.map(A=>A.sha);C(!0),m(`Starting analysis for ${O.length} entities...`,"info",3e3),h.submit({entityShas:R.join(",")},{method:"post",action:"/api/analyze"})};ee(()=>{if(h.state==="idle"&&h.data){const R=h.data;R.success?(console.log("[Analyze All] Success:",R.message),m(`Analysis started for ${R.entityCount} entities in ${R.fileCount} files. Watch the logs for progress.`,"success",6e3),C(!1)):R.error&&(console.error("[Analyze All] Error:",R.error),m(`Error: ${R.error}`,"error",8e3),C(!1))}},[h.state,h.data,m]);const V=R=>{f(A=>{const H=new Set(A);return H.has(R)?H.delete(R):H.add(R),H})},U=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#005C75",tooltip:"In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested."},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981",tooltip:"Entities that have been analyzed by CodeYam and have generated scenarios."},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6",tooltip:"React components and visual elements that can be rendered and captured as screenshots."},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9",tooltip:"Reusable functions and utilities that can be independently tested."}];return n("div",{className:"bg-cygray-10 min-h-screen",children:l("div",{className:"px-20 pt-8 pb-12",children:[l("header",{className:"mb-8 flex justify-between items-center",children:[l("div",{className:"flex items-center gap-4",children:[n("img",{src:sg,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:U.map((R,A)=>n(se,{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:l("div",{className:"px-6 py-6 flex flex-col gap-3 flex-1",children:[l("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[l("div",{className:"flex items-center gap-1.5 group relative",children:[n("span",{className:"text-xs text-gray-700 font-medium font-mono uppercase",children:R.label}),l("svg",{className:"w-3 h-3 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[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 →"})]}),l("div",{className:"flex flex-col gap-2",children:[l("div",{className:"flex items-center gap-3",children:[l("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${R.color}15`},children:[R.iconType==="folder"&&n(qi,{size:20,style:{color:R.color}}),R.iconType==="check"&&n(Wr,{size:20,style:{color:R.color}}),R.iconType==="image"&&n(en,{size:20,style:{color:R.color}}),R.iconType==="code-xml"&&n(Ki,{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 →"})]})]})},A))}),l("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[l("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[l("div",{className:"flex justify-between items-start mb-5",children:[l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),n("p",{className:"text-sm text-gray-500 m-0",children:r.length>0?`${r.length} file${r.length!==1?"s":""} with ${a.length} uncommitted entit${a.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),T.length>0&&n("button",{onClick:G,disabled:h.state!=="idle"||v||O.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:h.state!=="idle"||v?"Starting analysis...":O.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([R,A])=>{const H=p.has(R),W=A.editedEntities||[];return l("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#005C75"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>V(R),role:"button",tabIndex:0,children:l("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:H?"▼":"▶"}),l("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[l("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),l("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:R}),l("span",{className:"text-xs text-gray-500",children:[W.length," entit",W.length!==1?"ies":"y"]})]})]})}),H&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:W.length>0?W.map(J=>{const ae=F.has(J.sha),$=_.has(J.sha)||E.has(J.sha);return l(se,{to:`/entity/${J.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:I=>I.currentTarget.style.borderColor="#005C75",onMouseLeave:I=>I.currentTarget.style.borderColor="inherit",children:[l("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:J.entityType==="visual"?"#8B5CF615":J.entityType==="library"?"#6366F1":"#EC4899"},children:[J.entityType==="visual"&&n(en,{size:16,style:{color:"#8B5CF6"}}),J.entityType==="library"&&n(Rs,{size:16,className:"text-white"}),J.entityType==="other"&&n(Qi,{size:16,className:"text-white"})]}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:J.name}),J.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),J.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),J.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),J.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:J.description})]}),l("div",{className:"flex items-center gap-2 shrink-0",children:[ae&&l("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(Ze,{size:14,className:"animate-spin"}),"Analyzing..."]}),!ae&&$&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!ae&&!$&&n("button",{onClick:I=>{I.preventDefault(),I.stopPropagation(),m(`Starting analysis for ${J.name}...`,"info",3e3),h.submit({entityShas:J.sha},{method:"post",action:"/api/analyze"})},disabled:h.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:I=>I.currentTarget.style.backgroundColor="#004560",onMouseLeave:I=>I.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},J.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},R)})}):l("div",{className:"py-12 px-6 text-center flex flex-col items-center rounded-lg min-h-50 justify-center border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:l("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#7A9BA5",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n("polyline",{points:"14 2 14 8 20 8"}),n("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),n("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!y&&n(ag,{recentSimulations:s}),y&&l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:s.length>0?`Latest ${s.length} captured screenshot${s.length!==1?"s":""}`:"No simulations captured yet"})]})}),y&&l("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:l("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(Je,{type:"visual"})}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",S.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:S.filePath})]})]})}),j?l("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[n("span",{className:"text-lg",children:"✅"}),l("span",{children:["Complete (",k.length," scenario",k.length!==1?"s":"",")"]})]}):w?l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Ze,{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"})]}):h.state!=="idle"?l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Ze,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Ze,{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,A)=>{var D,q,te;const H=(D=S==null?void 0:S.analyses)==null?void 0:D[0],W=lr(R,H==null?void 0:H.status,void 0,y||void 0,void 0),J=(te=(q=R.metadata)==null?void 0:q.screenshotPaths)==null?void 0:te[0],ae=W.isCaptured,$=W.status==="capturing"||W.status==="starting",I=W.hasError;return ae?n(se,{to:`/entity/${y}`,className:"w-20 h-15 border-2 border-gray-200 rounded overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center no-underline hover:border-blue-600 hover:scale-105 hover:shadow-md",children:n(ze,{screenshotPath:J,alt:R.name,title:R.name,className:"max-w-full max-h-full object-contain object-center"})},A):I?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:W.errorMessage||"Capture error",children:n("span",{className:"text-red-500",children:"⚠️"})},A):n("div",{className:"w-20 h-15 border-2 border-dashed border-gray-300 rounded bg-gray-50 flex items-center justify-center text-2xl",title:`${$?"Capturing":"Pending"} ${R.name}...`,children:n("span",{className:$?"animate-pulse":"text-gray-400",children:$?"⋯":"⏹️"})},A)})})]})]})]}),x&&i&&n(ht,{projectSlug:i,onClose:()=>b(!1)})]})})}),cg=Object.freeze(Object.defineProperty({__proto__:null,default:lg,loader:ig,meta:og},Symbol.toStringTag,{value:"Module"}));function ei({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(Pl,{remarkPlugins:[_l],components:{h1:({children:a})=>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:a}),h2:({children:a})=>n("h2",{className:"text-base font-semibold text-gray-900 mb-2 mt-5 first:mt-0",children:a}),h3:({children:a})=>n("h3",{className:"text-sm font-semibold text-gray-800 mb-2 mt-4 first:mt-0",children:a}),p:({children:a})=>n("p",{className:"text-sm text-gray-700 mb-3 leading-relaxed",children:a}),ul:({children:a})=>n("ul",{className:"list-disc ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:a}),ol:({children:a})=>n("ol",{className:"list-decimal ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:a}),li:({children:a})=>n("li",{className:"leading-relaxed",children:a}),code:({children:a,className:s})=>(s==null?void 0:s.includes("language-"))?n("pre",{className:"bg-gray-100 rounded p-3 text-xs font-mono overflow-x-auto mb-3",children:n("code",{children:a})}):n("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono text-gray-800",children:a}),pre:({children:a})=>n(he,{children:a}),strong:({children:a})=>n("strong",{className:"font-semibold text-gray-900",children:a}),blockquote:({children:a})=>n("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic text-gray-600 mb-3",children:a}),table:({children:a})=>n("div",{className:"overflow-x-auto mb-3",children:n("table",{className:"min-w-full text-sm border-collapse border border-gray-200",children:a})}),thead:({children:a})=>n("thead",{className:"bg-gray-50",children:a}),th:({children:a})=>n("th",{className:"border border-gray-200 px-3 py-2 text-left font-semibold text-gray-900",children:a}),td:({children:a})=>n("td",{className:"border border-gray-200 px-3 py-2 text-gray-700",children:a}),a:({children:a,href:s})=>n("a",{href:s,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:a})},children:r})}function ti(e){const t={name:"root",path:"",memories:[],children:new Map};for(const r of e){const a=r.filePath.split("/");a.pop();let s=t,o="";for(const i of a)o=o?`${o}/${i}`:i,s.children.has(i)||s.children.set(i,{name:i,path:o,memories:[],children:new Map}),s=s.children.get(i);a.length===0?t.memories.push(r):s.memories.push(r)}return t}function ni(e){let t=e.memories.length;for(const r of e.children.values())t+=ni(r);return t}function ur(e,t){var a;const r=e.match(/^#+ (.+)$/m);return r?r[1]:((a=t.split("/").pop())==null?void 0:a.replace(".md",""))||t}function Xt(e){return Math.round(e/3.5)}function ga(e){const t=new Date(e),r=new Date;if(t.toDateString()===r.toDateString()){const d=r.getTime()-t.getTime(),h=Math.floor(d/(1e3*60*60));return h<1?"Just now":h===1?"1h ago":`${h}h ago`}const s=t.toLocaleDateString("en-US",{month:"short"}),o=t.getDate(),i=t.getFullYear(),c=r.getFullYear();return i===c?`${s} ${o}`:`${s} ${o}, ${i}`}function dg({rule:e,onEdit:t,onDelete:r,onView:a,isReviewed:s,onToggleReviewed:o,changeType:i,isUncommitted:c,changeDate:d,diff:h,isFadingOut:u,showLeftBorder:m}){const[p,f]=P(!1),[y,g]=P(!1),x=re(()=>ur(e.body,e.filePath),[e.body,e.filePath]),b=Xt(e.body.length),v=p?"#3e3e3e":c?"#d97706":"#c7c7c7",C=`rounded-lg border overflow-hidden transition-all ease-in-out ${c?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,w={...u&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return l("div",{className:C,style:w,children:[n("div",{className:`p-4 cursor-pointer ${c?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>a?a(e):f(!p),children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:p?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:v})})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:c?"#78350f":"#000"},children:x}),i&&n("span",{className:`px-2 py-0.5 rounded uppercase font-medium tracking-wider ${i==="deleted"?"bg-red-100 text-red-700":""}`,style:{fontSize:"10px",...i==="added"&&{backgroundColor:"#CBF3FA",color:"#005C75"},...i==="modified"&&{backgroundColor:"#FFE8C1",color:"#C67E06"}},children:i}),c&&n("span",{className:"px-2 py-0.5 bg-amber-200 text-amber-800 rounded font-medium uppercase tracking-wider",style:{fontSize:"10px"},children:"Uncommitted"}),l("span",{className:"text-xs text-gray-400",children:["~",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&&l(he,{children:[e.frontmatter.paths.slice(0,2).map((N,S)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:N},S)),e.frontmatter.paths.length>2&&l("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-2," more"]})]})})]})]}),l("div",{className:"flex items-center gap-3 flex-shrink-0",children:[d&&n("span",{className:"text-xs text-gray-400",children:ga(d)}),o&&n("button",{onClick:N=>{N.stopPropagation(),o(e.filePath,e.lastModified,s??!1)},className:`w-5 h-5 rounded-full border-2 flex items-center justify-center cursor-pointer transition-colors ${s?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,title:s?"Mark as unreviewed":"Mark as reviewed",children:s&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}),p&&l("div",{className:`border-t ${c?"border-amber-200":"border-gray-100"}`,children:[l("div",{className:`px-4 py-3 flex items-center justify-between ${c?"bg-amber-50":"bg-white"}`,children:[n("div",{className:"flex items-center gap-2",children:i==="modified"&&h&&l("button",{onClick:N=>{N.stopPropagation(),g(!y)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${y?c?"bg-amber-200 text-amber-900":"bg-gray-200 text-gray-900":c?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(Mn,{className:"w-3 h-3"}),y?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&l("div",{className:"flex items-center gap-2",children:[l("button",{onClick:N=>{N.stopPropagation(),t(e)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${c?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(Zi,{className:"w-3 h-3"}),"Edit"]}),l("button",{onClick:N=>{N.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(Xi,{className:"w-3 h-3"}),"Delete"]})]})]}),y&&h&&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:h.split(`
249
- `).map((N,S)=>{let k="";return N.startsWith("+")&&!N.startsWith("+++")?k="text-green-400":N.startsWith("-")&&!N.startsWith("---")?k="text-red-400":N.startsWith("@@")&&(k="text-cyan-400"),n("div",{className:k,children:N},S)})}),l("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Edit with Claude:"}),l("div",{className:"flex items-center gap-2",children:[l("span",{className:"px-2 py-1 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:["Claude, can you help me edit this rule: `",e.filePath,"`"]}),n(Uo,{content:`Claude, can you help me edit this rule: \`${e.filePath}\``,icon:!0,iconSize:14,className:"p-1 text-gray-400 hover:text-gray-600 rounded transition-colors"})]})]}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&l("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Applies to paths:"}),n("div",{className:"flex flex-wrap gap-1.5",children:e.frontmatter.paths.map((N,S)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:N},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(ei,{content:e.body})})]})]})}function ug(){return new Date().toISOString().split(".")[0]+"",`---
250
- paths:
251
- - '**/*.ts'
252
- ---
253
-
254
- ## Title
255
-
256
- Description here.
257
- `}function hg({rule:e,onSave:t,onCancel:r}){const[a,s]=P(e?`.claude/rules/${e.filePath}`:""),[o,i]=P((e==null?void 0:e.content)||ug()),[c,d]=P(!!e),h=!e;return l("div",{className:"p-6",children:[l("div",{className:"flex items-center justify-between mb-4",children:[n("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),n("button",{onClick:r,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Jr,{className:"w-5 h-5"})})]}),h&&l("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:l("div",{className:"flex items-start gap-3",children:[n(Mn,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),l("div",{children:[n("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),n("p",{className:"text-sm text-[#0369a1] mb-2",children:"Run this command in Claude Code to create a properly formatted rule with the right file location and paths:"}),n("code",{className:"block bg-white px-3 py-2 rounded border border-[#bae6fd] font-mono text-sm text-[#0c4a6e]",children:"/codeyam-new-rule"})]})]})}),l("button",{onClick:()=>d(!c),className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:c?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:c?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(c||!h)&&l("div",{className:"space-y-4",children:[l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),l("div",{className:"relative",children:[n("input",{type:"text",value:a,onChange:u=>s(u.target.value),placeholder:"e.g., src/webserver/architecture.md",className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm",disabled:!!e}),n("button",{onClick:()=>{navigator.clipboard.writeText(a)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy path",children:n($t,{className:"w-4 h-4"})})]})]}),e&&l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ask Claude for help editing:"}),l("div",{className:"relative",children:[n("input",{type:"text",value:`Claude, can you help me edit the rule: \`${a}\``,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: \`${a}\``)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy prompt",children:n($t,{className:"w-4 h-4"})})]})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:o,onChange:u=>i(u.target.value),rows:20,className:"w-full px-3 py-2 border border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm bg-gray-900 text-gray-100 [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-track]:bg-gray-800 [&::-webkit-scrollbar-thumb]:bg-gray-600 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:hover:bg-gray-500 [&::-webkit-resizer]:bg-gray-700"})]}),l("div",{className:"flex justify-end gap-2",children:[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(a.replace(/^\.claude\/rules\//,""),o),disabled:!a.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 mg({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:a,onToggleFolder:s}){const o=re(()=>ti(e),[e]),i=(h,u,m)=>{if(h.target.closest(".chevron-toggle")){m&&s(u||"root");return}const f=u||null;r(t===f?null:f),m&&!a.has(u||"root")&&s(u||"root")},c=h=>{r(t===h?null:h)},d=(h,u=0)=>{const m=a.has(h.path||"root"),p=ni(h),f=h.children.size>0,y=h.name==="root"?"(root)":h.name,g=h.memories.length>0||f,x=h.path||"",b=t===x||t===null&&x==="";return l("div",{children:[l("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${b?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${u*12+8}px`},onClick:v=>i(v,h.path,g),children:[g&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:v=>{v.stopPropagation(),s(h.path||"root")},children:n(Lt,{className:`w-3 h-3 text-gray-500 transition-transform ${m?"rotate-90":""}`})}),!g&&n("div",{className:"w-3"}),n(Ls,{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}),l("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[p," rules"]})]}),m&&l("div",{className:"relative",children:[(h.memories.length>0||f)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${u*12+8+6}px`}}),h.memories.length>0&&n("div",{style:{paddingLeft:`${(u+1)*12+8}px`},children:h.memories.map(v=>{var w;const C=t===v.filePath;return n("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${C?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>c(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(h.children.values()).sort((v,C)=>v.name.localeCompare(C.name)).map(v=>d(v,u+1))})]})]},h.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:d(o)})}function pg({memories:e,onEdit:t,onDelete:r,expandedFolders:a,onToggleFolder:s,reviewedStatus:o,onMarkReviewed:i,onMarkUnreviewed:c,onViewRule:d}){const[h,u]=P({});ee(()=>{u({})},[o]);const m=re(()=>({...o,...h}),[o,h]),p=re(()=>ti(e),[e]),f=(g,x,b)=>{u(v=>({...v,[g]:!b})),b?c(g):i(g,x)},y=(g,x=0)=>{const b=a.has(g.path||"root"),v=g.children.size>0,C=g.name==="root"?"root":g.name,w=g.memories.length>0||v;return l("div",{children:[l("div",{className:"flex items-center gap-2 py-2 cursor-pointer hover:bg-gray-50 rounded px-2 mb-2",style:{backgroundColor:"rgba(224, 233, 236, 0.5)"},onClick:()=>w&&s(g.path||"root"),children:[w&&n(Lt,{className:`w-4 h-4 text-gray-500 transition-transform ${b?"rotate-90":""}`}),!w&&n("div",{className:"w-4"}),n(Ls,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:C})]}),b&&l("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(N=>n(dg,{rule:N,onEdit:t,onDelete:r,onView:d,isReviewed:m[N.filePath]??!1,onToggleReviewed:f},N.filePath))}),v&&n("div",{className:"space-y-4",children:Array.from(g.children.values()).sort((N,S)=>N.name.localeCompare(S.name)).map(N=>y(N,x+1))})]})]},g.path||"root")};return n("div",{children:y(p)})}function fg({memories:e,reviewedStatus:t,onViewRule:r}){const[a,s]=P("unreviewed"),[o,i]=P(new Map),c=Ne(t),d=Ne([]);ee(()=>()=>{d.current.forEach(clearTimeout)},[]),ee(()=>{const p=c.current,f=[];for(const[y,g]of Object.entries(t))g&&!p[y]&&f.push(y);c.current=t,f.length!==0&&(i(y=>{const g=new Map(y);return f.forEach(x=>g.set(x,"approved")),g}),d.current.push(setTimeout(()=>{i(y=>{const g=new Map(y);return f.forEach(x=>g.set(x,"fading")),g})},1500)),d.current.push(setTimeout(()=>{i(y=>{const g=new Map(y);return f.forEach(x=>g.delete(x)),g})},2500)))},[t]);const h=re(()=>[...e].sort((p,f)=>new Date(f.lastModified).getTime()-new Date(p.lastModified).getTime()),[e]),u=re(()=>h.filter(p=>!t[p.filePath]).length,[h,t]),m=re(()=>a==="unreviewed"?h.filter(p=>!t[p.filePath]||o.has(p.filePath)):h,[h,a,t,o]);return l("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:[l("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Recently Changed Rules"})}),n("div",{className:"flex-1"}),l("button",{onClick:()=>s("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),l("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:["Unreviewed Rules (",u,")"]})]}),l("button",{onClick:()=>s("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),l("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:["All (",h.length,")"]})]})]}),l("div",{className:"grid grid-cols-[1fr_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"}),n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center",children:"Changed At"}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center flex items-center justify-center gap-1 whitespace-nowrap",children:["✓ Reviewed",l("span",{className:"relative group",children:[n($r,{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",children:m.slice(0,8).map(p=>{const f=t[p.filePath]??!1,y=o.get(p.filePath),g=ur(p.body,p.filePath);return n("div",{className:`border-b border-gray-50 transition-all ${y==="fading"?"duration-1000":"duration-300"}`,style:{opacity:y==="fading"?0:1},children:l("div",{className:`grid grid-cols-[1fr_80px_100px] px-5 py-2.5 items-center cursor-pointer transition-colors duration-300 ${y==="approved"?"bg-[#f0fdf4]":"hover:bg-gray-50"}`,onClick:()=>r(p),children:[n("div",{className:"flex items-center gap-2 min-w-0",children:n("span",{className:"text-sm text-gray-900 truncate",children:g})}),n("span",{className:"text-xs text-gray-500 text-center",children:ga(p.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 ${f?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:f&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})})]})},p.filePath)})}),m.length===0&&a==="unreviewed"&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:"All rules have been reviewed"}),m.length>0&&m.length<6&&n("div",{className:"flex-1 min-h-[60px]",style:{backgroundColor:"#F0F0F0"}})]})}function gg({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:a}){const[s,o]=P("unreviewed"),[i,c]=P(null),[d,h]=P(""),[u,m]=P(0),[p,f]=P(!1),[y,g]=P(null),x=Ne(null),b=Ne(null),[v,C]=P({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[w,N]=P(!0);ee(()=>{(async()=>{N(!0);try{const O=await(await fetch("/api/memory?action=audit")).json();C({topPaths:O.topPaths||[],totalFilesWithCoverage:O.totalFilesWithCoverage||0,allSourceFiles:O.allSourceFiles||[]})}catch(T){console.error("Failed to load audit data:",T)}finally{N(!1)}})()},[e]);const S=re(()=>s==="all"?v.topPaths:v.topPaths.filter(E=>E.matchingRules.some(T=>!t[T.filePath])),[v.topPaths,s,t]);re(()=>v.topPaths.filter(E=>E.matchingRules.some(T=>!t[T.filePath])).length,[v.topPaths,t]);const k=E=>E.split("/").pop()||E,M=re(()=>{const E=new Map;for(const T of v.topPaths)E.set(T.filePath,T);return E},[v.topPaths]),j=re(()=>{if(!d.trim())return[];const E=d.toLowerCase(),T=[],O=[];for(const G of v.allSourceFiles){const V=G.toLowerCase();if(!V.includes(E))continue;const U=M.get(G)||{filePath:G,matchingRules:[],totalTextLength:0};V.startsWith(E)?T.push(U):O.push(U)}return T.sort((G,V)=>G.filePath.localeCompare(V.filePath)),O.sort((G,V)=>G.filePath.localeCompare(V.filePath)),[...T,...O].slice(0,8)},[d,v.allSourceFiles,M]),L=oe(E=>{var T;g(E),c(E.filePath),h(E.filePath),f(!1),(T=x.current)==null||T.blur()},[]),F=oe(()=>{var E;h(""),g(null),c(null),(E=x.current)==null||E.focus()},[]),_=oe(E=>{var T;!p||j.length===0||(E.key==="ArrowDown"?(E.preventDefault(),m(O=>Math.min(O+1,j.length-1))):E.key==="ArrowUp"?(E.preventDefault(),m(O=>Math.max(O-1,0))):E.key==="Enter"?(E.preventDefault(),L(j[u])):E.key==="Escape"&&(f(!1),(T=x.current)==null||T.blur()))},[p,j,u,L]);return ee(()=>{m(0)},[j]),l("div",{className:"bg-white rounded-lg border border-gray-200 flex flex-col",children:[l("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Rule Audit"})}),l("div",{className:"relative flex-1 max-w-[300px]",children:[n(on,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),n("input",{ref:x,type:"text",value:d,onChange:E=>{h(E.target.value),f(!0)},onFocus:()=>{d.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:_,placeholder:"Search files...",className:`w-full pl-8 ${d?"pr-7":"pr-3"} py-1 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-[#005C75] focus:border-[#005C75] bg-gray-50`}),d&&n("button",{type:"button",onMouseDown:E=>{E.preventDefault(),F()},className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center text-gray-400 hover:text-gray-600 cursor-pointer",children:n("svg",{viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"w-3 h-3",children:n("path",{d:"M1 1l12 12M13 1L1 13"})})}),p&&j.length>0&&n("div",{ref:b,className:"absolute left-0 top-full mt-0.5 bg-white border border-gray-200 rounded-md shadow-lg z-10 max-h-75 overflow-y-auto min-w-75 max-w-120",children:j.map((E,T)=>l("div",{onMouseDown:O=>{O.preventDefault(),L(E)},onMouseEnter:()=>m(T),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${T===u?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(Tn,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:E.filePath,children:(()=>{const O=E.filePath.toLowerCase().indexOf(d.toLowerCase());if(O===-1)return E.filePath;const G=E.filePath.slice(0,O),V=E.filePath.slice(O,O+d.length),U=E.filePath.slice(O+d.length);return l(he,{children:[G,n("span",{className:"font-semibold text-[#005C75]",children:V}),U]})})()}),l("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[E.matchingRules.length," rule",E.matchingRules.length!==1?"s":""]})]},E.filePath))})]}),n("div",{className:"flex-1"}),l("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:s==="unreviewed"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:s==="unreviewed"?600:400,color:s==="unreviewed"?"#005C75":"#626262"},children:"Unreviewed Rules"})]}),l("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:s==="all"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:s==="all"?600:400,color:s==="all"?"#005C75":"#626262"},children:"All"})]})]}),l("div",{className:"grid grid-cols-[1fr_140px_150px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Source file"}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Rules",l("span",{className:"relative group",children:[n($r,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-48 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Number of rules not yet reviewed for this file / Total number of rules that apply to this file"})]})]}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Tokens",l("span",{className:"relative group",children:[n($r,{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"})]})]})]}),w&&n("div",{className:"px-5 py-6",children:l("div",{className:"animate-pulse space-y-3",children:[n("div",{className:"h-4 bg-gray-200 rounded w-3/4"}),n("div",{className:"h-3 bg-gray-100 rounded w-1/2"}),n("div",{className:"h-4 bg-gray-200 rounded w-2/3 mt-4"})]})}),!w&&(S.length>0||y)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(y?[y,...S.filter(T=>T.filePath!==y.filePath)].slice(0,8):S.slice(0,8)).map((E,T)=>{const O=E.matchingRules.length,G=E.matchingRules.filter(A=>!t[A.filePath]),V=G.length,U=G.reduce((A,H)=>A+H.bodyLength,0),z=V>0,Y=i===E.filePath,R=(y==null?void 0:y.filePath)===E.filePath;return l("div",{children:[l("div",{onClick:()=>c(Y?null:E.filePath),className:`grid grid-cols-[1fr_140px_150px] px-5 py-2.5 items-center border-b border-gray-50 cursor-pointer ${R?"bg-[#f0f9ff] hover:bg-[#e0f2fe]":"hover:bg-gray-50"}`,children:[l("div",{className:"flex items-center gap-2 min-w-0",children:[Y?n(mt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n(Lt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(Tn,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:E.filePath,children:R?E.filePath:k(E.filePath)})]}),l("span",{className:"text-sm text-center",children:[n("span",{className:z?"font-semibold text-[#1A5276]":"text-gray-400",children:V}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:O})]}),l("span",{className:"text-sm text-center",children:[n("span",{className:z?"font-semibold text-[#1A5276]":"text-gray-400",children:Xt(U).toLocaleString()}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:Xt(E.totalTextLength).toLocaleString()})]})]}),Y&&n("div",{className:"bg-gray-50 border-b border-gray-100",children:E.matchingRules.map(A=>{const H=r.find(J=>J.filePath===A.filePath),W=t[A.filePath]??!1;return l("div",{onClick:J=>{J.stopPropagation(),H&&a(H)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(Hr,{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:H?ur(H.body,H.filePath):A.filePath}),l("span",{className:"text-xs text-gray-400 flex-shrink-0",children:[Xt(A.bodyLength).toLocaleString()," ","tokens"]}),n("div",{className:`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${W?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:W&&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"})})})]},A.filePath)})})]},E.filePath)})}),!w&&S.length===0&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:s==="unreviewed"?"No files have unreviewed rules":"No files have rule coverage yet"})]})}function yg({rule:e,changeInfo:t,isReviewed:r,onApprove:a,onEdit:s,onDelete:o,onClose:i}){const c=ur(e.body,e.filePath),d=Xt(e.body.length),h=e.frontmatter.category,u=`.claude/rules/${e.filePath}`,[m,p]=P(!1);return ee(()=>{const f=y=>{y.key==="Escape"&&i()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[i]),n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:i,children:l("div",{className:"rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",style:{backgroundColor:"#F8F7F6"},onClick:f=>f.stopPropagation(),children:[n("div",{className:"px-6 pt-5 pb-4",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"min-w-0 flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[n("h2",{className:"text-[16px] font-bold text-gray-900",children:c}),t&&l(he,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:ga(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})]})]}),h&&l("div",{className:"flex items-center gap-2 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"TYPE:"}),n("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase font-semibold tracking-wider bg-[#E0F2F1] text-[#00796B]",children:h})]}),l("div",{className:"flex items-center gap-1.5 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"FILE:"}),n("code",{className:"text-[11px] text-gray-600 font-mono",children:u}),n("button",{onClick:()=>{navigator.clipboard.writeText(u),p(!0),setTimeout(()=>p(!1),2e3)},className:"p-0.5 rounded text-gray-400 hover:text-gray-600 cursor-pointer transition-colors",title:"Copy file path",children:m?n(At,{className:"w-3 h-3 text-green-500"}):n($t,{className:"w-3 h-3"})})]}),l("div",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:["TOKENS: ~",d.toLocaleString()]})]}),l("div",{className:"flex items-center gap-2 flex-shrink-0 ml-4",children:[l("button",{onClick:a,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(At,{className:"w-3.5 h-3.5"}),r?"Approved":"Approve"]}),n("button",{onClick:s,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(Jr,{className:"w-5 h-5"})})]})]})}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&l("div",{className:"px-6 pb-4",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Applies to paths:"}),n("div",{className:"bg-white rounded-lg p-4 space-y-2.5",style:{border:"1px solid #E6E6E6"},children:e.frontmatter.paths.map((f,y)=>{const g=f.split("/"),x=g.pop()||f,b=g.length>0?g.join("/")+"/":"";return l("div",{className:"flex items-center gap-2 text-[13px] font-mono",children:[n(Tn,{className:"w-4 h-4 text-[#005C75] flex-shrink-0"}),l("span",{children:[b&&n("span",{className:"text-gray-500",children:b}),n("span",{className:"font-bold text-gray-900",children:x})]})]},y)})})]}),l("div",{className:"px-6 pb-6",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Rule Text:"}),n("div",{className:"bg-white rounded-lg p-6",style:{border:"1px solid #E6E6E6"},children:n(ei,{content:e.body})})]})]})})}function xg(){return l("svg",{width:"24",height:"24",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#232323"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#232323"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#232323"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#232323"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#232323"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#232323"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#232323"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#232323"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#232323"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#232323"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#232323"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#232323"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#232323"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#232323"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#232323"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#232323"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#232323"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#232323"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#232323"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#232323"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#232323"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#232323"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#232323"})]})}function bg(){return l("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}function vg(){return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans max-w-3xl mx-auto",children:[l("div",{className:"text-center mb-10",children:[n("h1",{className:"text-[22px] font-semibold mb-4",style:{fontFamily:"Sora",color:"#232323"},children:"Get Started with CodeYam Memory"}),n("p",{className:"text-[15px] text-gray-500 leading-relaxed max-w-2xl mx-auto",children:"CodeYam Memory generates path-scoped Claude Rules that load automatically when Claude works on matching files. These rules capture any confusion, architectural decisions, and tribal knowledge from your as you work with Claude, ensuring sessions become more efficient and aligned with your codebase over time."})]}),l("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"Setup Steps"}),l("ol",{className:"space-y-5",children:[l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"1"}),n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Open Claude Code in your project terminal"})]}),l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"2"}),l("div",{children:[l("div",{className:"flex items-center gap-2 pt-0.5",children:[n("span",{className:"text-[14px] font-medium text-gray-900",children:"Run"}),n(Ts,{value:"/codeyam-memory"})]}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"This kicks off analysis of your git history to find confusion patterns."})]})]}),l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"3"}),n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Confirm or refine the confusion patterns Claude discovers in your git history"})]}),l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"4"}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Review generated rules here, in the dashboard"}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"Come back to this page to review, edit, and approve the rules Claude creates."})]})]})]})]}),l("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"What Gets Created"}),l("div",{className:"relative",children:[n("div",{className:"absolute left-[15px] top-8 bottom-4",style:{borderLeft:"2px dotted #B0BEC5"}}),l("div",{className:"space-y-6",children:[l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[l("p",{className:"text-[14px] font-medium text-gray-900",children:[n("code",{className:"bg-gray-200/60 px-1.5 py-0.5 rounded text-[13px]",children:".claude/rules/*.md"}),n("span",{className:"text-gray-400 mx-1.5",children:"—"}),"path-scoped guidance files"]}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"Markdown files with frontmatter specifying which file paths they apply to."})]})]}),l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Rules load automatically when Claude works on matching files"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"No manual steps needed — Claude picks up relevant rules based on the files it touches."})]})]}),l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Pre-commit hook to keep rules fresh and capture new patterns"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"A git hook runs automatically to update rules when related code changes and looks for any new patterns of confusion in work sessions."})]})]})]})]})]}),l("div",{className:"rounded-lg px-8 py-5 flex items-center justify-center gap-3",style:{backgroundColor:"#1A2332"},children:[n("span",{className:"text-white text-[15px] font-medium",children:"Run"}),n(Ts,{value:"/codeyam-memory"}),n("span",{className:"text-white text-[15px] font-medium",children:"in your terminal to get started"})]})]})})}function Ts({value:e}){const[t,r]=P(!1);return l("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[13px] font-mono cursor-pointer border-0",style:{backgroundColor:"#2C3E50",color:"#E0E0E0"},title:"Copy to clipboard",children:[e,t?n(At,{className:"w-3.5 h-3.5 text-green-400"}):l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-400",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})}function En({label:e,count:t,icon:r,bgColor:a,iconBgColor:s,textColor:o}){return n("div",{className:"rounded-lg p-4",style:{backgroundColor:a,border:"1px solid #EFEFEF"},children:l("div",{className:"flex items-start gap-3",children:[n("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:s},children:r}),l("div",{className:"flex-1",children:[n("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:o},children:t}),n("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:o},children:e})]})]})})}function wg({searchFilter:e,onSearchChange:t,onCreateNew:r,onLearnMore:a,reviewCounts:s}){return l("div",{className:"mb-8",children:[l("div",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[l("div",{children:[l("div",{className:"flex items-center gap-3 mb-2",children:[n(xg,{}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),l("p",{className:"text-[15px] text-gray-500",children:["Rules help Claude understand your codebase patterns and conventions."," ",n("button",{onClick:a,className:"text-[#005C75] underline cursor-pointer",children:"Learn more about rules."})]})]}),l("div",{className:"flex items-center gap-3",children:[l("div",{className:"relative",children:[n(on,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:e,onChange:o=>t(o.target.value),placeholder:"Search rules...",className:"w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),l("button",{onClick:r,className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(Vr,{className:"w-4 h-4"}),"New Rule"]})]})]}),l("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[n(En,{label:"Total Rules",count:s.total,icon:n(bg,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(En,{label:"Unreviewed",count:s.unreviewed,icon:n(el,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(En,{label:"Reviewed",count:s.reviewed,icon:n(At,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(En,{label:"Stale",count:s.stale,icon:n(Ds,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]})}function Cg({onClose:e,onCreateNew:t}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:l("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:r=>r.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Jr,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-4",children:"What are Claude Rules?"}),n("h3",{className:"mb-4 font-semibold",children:"And how does CodeYam Memory work with Claude Rules?"}),l("div",{className:"text-gray-600 text-[15px] space-y-3 mb-6",children:[l("p",{children:["Claude Rules are a component of"," ",n("a",{href:"https://code.claude.com/docs/en/memory#modular-rules-with-claude%2Frules%2F",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 underline",children:"Memory Management in Claude Code"}),'. The text of each rule is passed into the context window when working on the specific files described in the "paths" frontmatter field of the rule.']}),n("p",{children:"This allows you to provide context that is surgically specific to certain files in your codebase. They are a powerful tool but are harder to write and maintain than CLAUDE.md files."}),n("p",{children:"CodeYam Memory helps write and maintain Claude Rules. Hooks ensure that rules are reviewed and added during Claude Code working sessions. The CodeYam CLI Dashboard provides a page dedicated to Memory where you can view, edit, create, delete, and review Claude Rules."})]}),n("div",{className:"flex justify-center",children:l("button",{onClick:t,className:"flex items-center gap-2 px-5 py-2.5 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(Vr,{className:"w-4 h-4"}),"New Rule"]})})]})})}function Ng({rule:e,onConfirm:t,onCancel:r}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:l("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[n("h3",{className:"text-lg font-semibold mb-2",children:"Delete Memory?"}),l("p",{className:"text-gray-600 mb-4",children:["Are you sure you want to delete"," ",n("span",{className:"font-mono text-sm",children:e.filePath}),"? This cannot be undone."]}),l("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>t(e),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})}const Sg=()=>[{title:"Memory - CodeYam"},{name:"description",content:"Manage Claude Memory documentation"}];async function Eg({request:e}){try{const r=await(await fetch(new URL("/api/memory",e.url).toString())).json();return r.error?B({memories:[],reviewedStatus:{},memoryInitialized:r.memoryInitialized??!1,error:r.error}):r.memoryInitialized??!1?B({memories:r.memories||[],reviewedStatus:r.reviewedStatus||{},memoryInitialized:!0,error:null}):B({memories:[],reviewedStatus:{},memoryInitialized:!1,error:null})}catch(t){return console.error("Failed to load memories:",t),B({memories:[],reviewedStatus:{},memoryInitialized:!1,error:"Failed to load memories"})}}const Ag=De(function(){const{memories:t,reviewedStatus:r,memoryInitialized:a,error:s}=Be(),o=Ae(),i=at(),[c,d]=P(""),[h,u]=P(null),[m,p]=P(new Set(["root"])),[f,y]=P(null),[g,x]=P(!1),[b,v]=P(null),[C,w]=P(0),[N,S]=P(!1),[k,M]=P(null),[j,L]=P(null),[F,_]=P({}),E=$=>{p(I=>{const D=new Set(I);return D.has($)?D.delete($):D.add($),D})};Xe({source:"memory-page"});const T=re(()=>({...r,...F}),[r,F]),O=Ne(o.state);ee(()=>{const $=O.current==="loading"||O.current==="submitting",I=o.state==="idle";$&&I&&o.data&&(i.revalidate(),y(null),x(!1),w(D=>D+1)),O.current=o.state},[o.state,o.data,i]),ee(()=>{_($=>{const I={};for(const[D,q]of Object.entries($))r[D]!==q&&(I[D]=q);return Object.keys(I).length===Object.keys($).length?$:I})},[r]);const G=($,I)=>{_(D=>({...D,[$]:!0})),o.submit({action:"mark-reviewed",filePath:$,lastModified:I},{method:"POST",action:"/api/memory",encType:"application/json"})},V=$=>{_(I=>({...I,[$]:!1})),o.submit({action:"mark-unreviewed",filePath:$},{method:"POST",action:"/api/memory",encType:"application/json"})},U=($,I)=>{M($),L(I??null)},z=re(()=>{let $=t;if(c.trim()){const I=c.toLowerCase();$=$.filter(D=>{var te;return(((te=D.filePath.split("/").pop())==null?void 0:te.replace(".md",""))||"").toLowerCase().includes(I)||D.body.toLowerCase().includes(I)})}return $},[t,c]),Y=re(()=>h?z.some(I=>I.filePath===h)?z.filter(I=>I.filePath===h):z.filter(I=>I.filePath.startsWith(h+"/")||I.filePath===h):z,[z,h]),R=($,I)=>{const D=f?"update":"create";o.submit({action:D,filePath:$,content:I},{method:"POST",action:"/api/memory",encType:"application/json"})},A=$=>{o.submit({action:"delete",filePath:$.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),v(null)},H=re(()=>{const $=t.filter(I=>T[I.filePath]).length;return{total:t.length,reviewed:$,unreviewed:t.length-$,stale:0}},[t,T]),W=re(()=>{const $=new Set(["root"]);for(const I of z){const D=I.filePath.split("/");D.pop();let q="";for(const te of D)q=q?`${q}/${te}`:te,$.add(q)}return $},[z]),J=W.size===m.size&&[...W].every($=>m.has($)),ae=()=>{p(J?new Set(["root"]):new Set(W))};return s?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:s})]})}):a?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans",children:[n(wg,{searchFilter:c,onSearchChange:d,onCreateNew:()=>x(!0),onLearnMore:()=>S(!0),reviewCounts:H}),(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:$=>$.stopPropagation(),children:n(hg,{rule:f,onSave:R,onCancel:()=>{x(!1),y(null)}})})}),l("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(fg,{memories:z,reviewedStatus:T,onViewRule:U}),n(gg,{onEditRule:y,onDeleteRule:v,refreshKey:C,reviewedStatus:T,onMarkReviewed:G,onMarkUnreviewed:V,memories:t,onViewRule:U})]}),l("div",{className:"flex items-center justify-between mb-4",children:[n("h2",{className:"text-xl leading-6 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"All Rules"}),n("div",{className:"flex items-center gap-4",children:W.size>1&&n("button",{onClick:ae,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:J?"Collapse All":"Expand All"})})]}),l("div",{className:"flex gap-6",children:[n("div",{className:"hidden lg:block w-80 flex-shrink-0",children:n(mg,{memories:z,selectedPath:h,onSelectPath:u,expandedFolders:m,onToggleFolder:E})}),n("div",{className:"flex-1 min-w-0",children:t.length===0?l("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(tl,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Rules Yet"}),l("p",{className:"text-gray-500 mb-4",children:["Run"," ",n("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam-memory"})," ","to generate initial memories for your codebase."]}),l("button",{onClick:()=>x(!0),className:"inline-flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer",children:[n(Vr,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):l("div",{children:[h&&l("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:["Showing rules in"," ",n("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:h||"(root)"}),n("button",{onClick:()=>u(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(pg,{memories:Y,onEdit:y,onDelete:v,expandedFolders:m,onToggleFolder:E,reviewedStatus:T,onMarkReviewed:G,onMarkUnreviewed:V,onViewRule:U})]})})]}),n("div",{className:"mt-8 mb-8",children:n(se,{to:"/agent-transcripts",className:"block bg-white border border-gray-200 rounded-lg p-5 hover:border-[#005C75] hover:shadow-sm transition-all group",children:l("div",{className:"flex items-center gap-3",children:[n("div",{className:"w-10 h-10 rounded-lg bg-[#EDF1F3] flex items-center justify-center",children:l("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#005C75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("polyline",{points:"4 17 10 11 4 5"}),n("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),l("div",{children:[n("h3",{className:"text-sm font-semibold text-[#232323] group-hover:text-[#005C75]",style:{fontFamily:"Sora"},children:"Agent Transcripts"}),n("p",{className:"text-xs text-gray-500",children:"View background agent transcripts and tool call history"})]})]})})}),k&&!f&&(()=>{const $=t.find(I=>I.filePath===k.filePath)??k;return n(yg,{rule:$,changeInfo:j??void 0,isReviewed:T[$.filePath]??!1,onApprove:()=>{T[$.filePath]??!1?V($.filePath):G($.filePath,$.lastModified),M(null)},onEdit:()=>{y($)},onDelete:()=>{v($),M(null)},onClose:()=>M(null)})})(),N&&n(Cg,{onClose:()=>S(!1),onCreateNew:()=>{S(!1),x(!0)}}),b&&n(Ng,{rule:b,onConfirm:A,onCancel:()=>v(null)})]})}):n(vg,{})}),kg=Object.freeze(Object.defineProperty({__proto__:null,default:Ag,loader:Eg,meta:Sg},Symbol.toStringTag,{value:"Module"}));function Ir(e){return`${e.filePath||""}::${e.name}`}function ri(e,t){const r=Ae(),{showToast:a}=Zr(),[s,o]=P(new Map);ee(()=>{if(r.state==="idle"&&r.data){const p=r.data;p!=null&&p.error&&a(`Error: ${p.error}`,"error",6e3)}},[r.state,r.data,a]),ee(()=>{var f;if(s.size===0)return;const p=new Set;(f=t==null?void 0:t.jobs)==null||f.forEach(y=>{var g;(g=y.entityShas)==null||g.forEach(x=>{s.forEach((b,v)=>{b===x&&p.add(v)})})}),e==null||e.forEach(y=>{s.forEach((g,x)=>{g===y&&p.add(x)})}),p.size>0&&o(y=>{const g=new Map(y);return p.forEach(x=>g.delete(x)),g})},[t,e,s]);const i=oe(p=>{console.log("Generate analysis clicked for entity:",p.sha,p.name);const f=Ir(p);o(g=>new Map(g).set(f,p.sha));const y=new FormData;y.append("entitySha",p.sha),y.append("filePath",p.filePath||""),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),c=oe(p=>{const f=p.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(x=>{const b=new Map(x);return f.forEach(v=>b.set(Ir(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]),d=oe(p=>(e==null?void 0:e.includes(p))??!1,[e]),h=oe(p=>{const f=Ir(p);return s.has(f)},[s]),u=oe(p=>{var f;return((f=t==null?void 0:t.jobs)==null?void 0:f.some(y=>{var g;return(g=y.entityShas)==null?void 0:g.includes(p)}))??!1},[t]),m=re(()=>Array.from(s.keys()),[s]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:c,isEntityBeingAnalyzed:d,isEntityPending:h,isEntityInQueue:u,pendingEntityKeys:m}}function ya({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:a,analyzeAllDisabled:s=!1,analyzeAllText:o="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:l("div",{className:"flex justify-between items-center px-3 py-2",children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:n("span",{children:"STATE"})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:n("span",{children:"SIMULATIONS"})}),l("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),l("div",{className:"flex items-center justify-center gap-1 cursor-pointer hover:text-[#232323] transition-colors",style:{width:"116px"},onClick:r,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r==null||r())},children:[n("span",{children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:t==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&n("div",{className:"text-center",style:{width:"127px"},children:a&&n("button",{onClick:a,disabled:s,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:s?o:"Analyze all entities",children:o})})]})]})]})})}function Pg({status:e,variant:t="compact"}){const r={modified:{label:"M",bgColor:"bg-[#f59e0c]"},added:{label:"A",bgColor:"bg-emerald-500"},deleted:{label:"D",bgColor:"bg-red-500",showWarning:!0},renamed:{label:"R",bgColor:"bg-indigo-500"},untracked:{label:"U",bgColor:"bg-purple-500"}},a={modified:{label:"MODIFIED",textColor:"#BB6BD9"},added:{label:"ADDED",textColor:"#F2994A"},deleted:{label:"DELETED",textColor:"#EF4444"},renamed:{label:"RENAMED",textColor:"#3B82F6"},untracked:{label:"UNTRACKED",textColor:"#6B7280"}};if(t==="full"){const o=a[e]||{label:"UNKNOWN",textColor:"#6B7280"};return n("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:o.textColor},children:o.label})})}const s=r[e]||{label:"?",bgColor:"bg-gray-500"};return l("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${s.bgColor}`,title:e,children:s.label}),s.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 xa({filePath:e,isExpanded:t,onToggle:r,fileStatus:a,simulationPreviews:s,entityCount:o,state:i,lastModified:c,actionButton:d,uncommittedCount:h,children:u,isNotAnalyzable:m=!1,isUncommitted:p=!1}){return l("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[l("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${m?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(Vs,{filePath:e}),a&&n(Pg,{status:typeof a=="string"?a:a.status,variant:"full"}),p&&i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(p||i==="out-of-date")&&l("div",{className:"flex gap-1.5 items-center",children:[p&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&!p&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:s}),l("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:l("span",{className:"text-[13px] text-[#3e3e3e]",children:[o," ",o===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:Wo(c)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:d})]})]})]}),t&&u&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:u})]})}function ba({entities:e,maxPreviews:t=3}){var a,s,o,i,c;const r=[];for(const d of e){if(r.length>=t)break;const h=((s=(a=d.analyses)==null?void 0:a[0])==null?void 0:s.scenarios)||[];if(d.entityType==="library"){const u=h.find(m=>{var p,f;return((p=m.metadata)==null?void 0:p.executionResult)||((f=m.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:d.sha})}else if(d.entityType==="visual"){const u=h.find(m=>{var p,f;return(f=(p=m.metadata)==null?void 0:p.screenshotPaths)==null?void 0:f[0]});if(u){const m=(i=(o=u.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],p=!!((c=u.metadata)!=null&&c.error);m&&r.push({type:"screenshot",screenshot:m,hasError:p,scenario:u,entitySha:d.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(he,{children:r.map((d,h)=>{if(d.type==="screenshot"&&d.screenshot){const u=d.hasError?"border-red-400":"border-gray-200";return l(se,{to:d.scenario?`/entity/${d.entitySha}/scenarios/${d.scenario.id}`:`/entity/${d.entitySha}`,className:`relative w-[50px] h-[38px] border ${u} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:m=>m.stopPropagation(),children:[n(ze,{screenshotPath:d.screenshot,alt:`Preview ${h+1}`,className:"max-w-full max-h-full object-contain object-center"}),d.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(_n,{size:12,color:"white"})})]},`screenshot-${h}`)}return d.type==="library"&&d.scenario&&d.entitySha?n(zo,{scenario:d.scenario,entitySha:d.entitySha,size:"small",showBorder:!0},`library-${h}`):null})})}function va({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:a}){var u,m;const s=t||r?[{entityShas:[e.sha]}]:[],o=qe(e,s,t),i=e.entityType==="visual"||e.entityType==="library",c=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,h=(((m=(u=e.analyses)==null?void 0:u[0])==null?void 0:m.scenarios)||[]).filter(p=>{var f,y;return(y=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0]});return l("div",{className:"bg-white rounded-lg",children:[l(se,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 shrink-0"}),e.entityType==="type"?n("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:n("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:n(Je,{type:"type"})})}):n(Je,{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(ca,{type:e.entityType||"other"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),l("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?o==="queued"?l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):o==="analyzing"?l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):o==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):o==="out-of-date"?n("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),a(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):c&&n("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),a(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"})})]})]})]}),h.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:h.map((p,f)=>{var g,x;const y=(x=(g=p.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return y?n(se,{to:`/entity/${e.sha}?scenario=${p.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:b=>b.stopPropagation(),children:n(ze,{screenshotPath:y,alt:p.name,className:"max-w-full max-h-full object-contain object-center"})},p.id):null})})]})}function _g({entities:e,page:t,itemsPerPage:r=50,currentRun:a,filter:s,entityType:o,queueState:i,isEntityPending:c,pendingEntityKeys:d,onGenerateSimulation:h,onGenerateAllSimulations:u,totalFilesCount:m,totalEntitiesCount:p,uncommittedFilesCount:f,showOnlyUncommitted:y,onToggleUncommitted:g}){const[x,b]=sn(),[v,C]=P(new Set),[w,N]=P(""),[S,k]=P(!1),[M,j]=P("all"),[L,F]=P("desc"),_=o||"all",E=re(()=>{let A=e;return _!=="all"&&(A=A.filter(H=>H.entityType===_)),s==="analyzed"&&(A=A.filter(H=>H.analyses&&H.analyses.length>0)),A},[e,_,s]),T=re(()=>{const A=new Map,H=new Map,W=new Map;E.forEach(I=>{var te,ce;const D=`${I.filePath}::${I.name}`,q=H.get(D);if(!q)H.set(D,I),W.set(D,[]);else{const me=((te=q.metadata)==null?void 0:te.editedAt)||q.createdAt||"",ge=((ce=I.metadata)==null?void 0:ce.editedAt)||I.createdAt||"";let be=!1;if(ge>me)be=!0;else if(ge===me){const Ce=q.createdAt||"";be=(I.createdAt||"")>Ce}be?(W.get(D).push(q),H.set(D,I)):W.get(D).push(I)}}),H.forEach((I,D)=>{var te;if(!(I.analyses&&I.analyses.length>0)&&((te=I.metadata)!=null&&te.previousVersionWithAnalyses)){const me=(W.get(D)||[]).find(ge=>{var be;return ge.sha===((be=I.metadata)==null?void 0:be.previousVersionWithAnalyses)});me&&me.analyses&&me.analyses.length>0&&(I.analyses=me.analyses)}}),Array.from(H.values()).sort((I,D)=>{var ce,me,ge,be;const q=!((ce=I.metadata)!=null&&ce.notExported)&&!((me=I.metadata)!=null&&me.namedExport),te=!((ge=D.metadata)!=null&&ge.notExported)&&!((be=D.metadata)!=null&&be.namedExport);return q&&!te?-1:!q&&te?1:0}).forEach(I=>{var me,ge,be,Ce,Ee;const D=I.filePath??"No File Path";A.has(D)||A.set(D,{filePath:D,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const q=A.get(D);q.entities.push(I),q.totalCount++,(me=I.metadata)!=null&&me.isUncommitted&&q.uncommittedCount++;const te=((Ce=(be=(ge=I.analyses)==null?void 0:ge[0])==null?void 0:be.scenarios)==null?void 0:Ce.length)||0;q.simulationCount+=te;const ce=((Ee=I.metadata)==null?void 0:Ee.editedAt)||I.updatedAt;ce&&(!q.lastUpdated||new Date(ce)>new Date(q.lastUpdated))&&(q.lastUpdated=ce)});const J=(i==null?void 0:i.jobs)||[],ae=I=>{const D=`${I.filePath||""}::${I.name}`;return(d==null?void 0:d.includes(D))||!1};A.forEach(I=>{const D=I.entities.map(q=>ae(q)?"queued":qe(q,J));D.includes("analyzing")||D.includes("queued")?I.state="analyzing":D.includes("incomplete")?I.state="incomplete":D.includes("out-of-date")?I.state="out-of-date":D.includes("not-analyzed")?I.state="not-analyzed":I.state="up-to-date"}),A.forEach(I=>{var D,q,te,ce,me;for(const ge of I.entities){if(I.previewScreenshots.length+I.previewLibraryScenarios.length>=3)break;const Ce=((q=(D=ge.analyses)==null?void 0:D[0])==null?void 0:q.scenarios)||[];if(ge.entityType==="library"){const Ee=Ce.find(Se=>{var Pe,Me;return((Pe=Se.metadata)==null?void 0:Pe.executionResult)||((Me=Se.metadata)==null?void 0:Me.error)});Ee&&I.previewLibraryScenarios.push({scenario:Ee,entitySha:ge.sha})}else{const Ee=Ce.find(Se=>{var Pe,Me;return(Me=(Pe=Se.metadata)==null?void 0:Pe.screenshotPaths)==null?void 0:Me[0]});if(Ee){const Se=(ce=(te=Ee.metadata)==null?void 0:te.screenshotPaths)==null?void 0:ce[0],Pe=!!((me=Ee.metadata)!=null&&me.error);Se&&!I.previewScreenshots.includes(Se)&&(I.previewScreenshots.push(Se),I.previewScreenshotErrors.push(Pe))}}}});const $=Array.from(A.values());return $.sort((I,D)=>{if(s==="analyzed"){const ce=Math.max(...I.entities.filter(ge=>{var be,Ce;return(Ce=(be=ge.analyses)==null?void 0:be[0])==null?void 0:Ce.createdAt}).map(ge=>new Date(ge.analyses[0].createdAt).getTime()),0),me=Math.max(...D.entities.filter(ge=>{var be,Ce;return(Ce=(be=ge.analyses)==null?void 0:be[0])==null?void 0:Ce.createdAt}).map(ge=>new Date(ge.analyses[0].createdAt).getTime()),0);return L==="desc"?me-ce:ce-me}if(I.uncommittedCount>0&&D.uncommittedCount===0)return-1;if(I.uncommittedCount===0&&D.uncommittedCount>0)return 1;const q=I.lastUpdated?new Date(I.lastUpdated).getTime():0,te=D.lastUpdated?new Date(D.lastUpdated).getTime():0;return L==="desc"?te-q:q-te}),$},[E,s,L,i,d]),O=re(()=>{let A=T;if(M!=="all"&&(A=A.filter(H=>H.state===M)),w.trim()){const H=w.toLowerCase();A=A.filter(W=>W.filePath.toLowerCase().includes(H))}return A},[T,w,M]),G=(t-1)*r,V=G+r,U=O.slice(G,V),z=Math.ceil(O.length/r),Y=A=>{C(H=>{const W=new Set(H);return W.has(A)?W.delete(A):W.add(A),W})},R=()=>{F(A=>A==="desc"?"asc":"desc")};return l("div",{children:[l("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),l("div",{className:"flex gap-3",children:[l("div",{className:"relative w-[130px]",children:[l("select",{value:_,onChange:A=>{const H=A.target.value,W=new URLSearchParams(x);H==="all"?W.delete("entityType"):W.set("entityType",H),W.set("page","1"),b(W)},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(mt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"relative w-[130px]",children:[l("select",{value:M,onChange:A=>j(A.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All States"}),n("option",{value:"analyzing",children:"Analyzing..."}),n("option",{value:"up-to-date",children:"Up to date"}),n("option",{value:"incomplete",children:"Incomplete"}),n("option",{value:"out-of-date",children:"Out of date"}),n("option",{value:"not-analyzed",children:"Not analyzed"})]}),n(mt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"flex-1 relative",children:[n(on,{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:A=>N(A.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),m!==void 0&&p!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:O.length})," ",O.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:O.reduce((A,H)=>A+H.totalCount,0)})," ",O.reduce((A,H)=>A+H.totalCount,0)===1?"entity":"entities"]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),y?l("button",{onClick:g,className:"flex items-center gap-2 text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase cursor-pointer",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[O.filter(A=>A.uncommittedCount>0).length," ","uncommitted"," ",O.filter(A=>A.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):l("button",{onClick:g,className:"text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[f," uncommitted"," ",f===1?"file":"files"]})]}),U.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:()=>{C(new Set(U.map(A=>A.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(Fs,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:()=>{C(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(Os,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(ya,{showActions:!0,sortOrder:L,onSortChange:R}),n("div",{className:"flex flex-col gap-[3px]",children:U.map(A=>{const H=v.has(A.filePath),J=A.entities.filter(D=>(D.entityType==="visual"||D.entityType==="library")&&(qe(D,(i==null?void 0:i.jobs)||[])==="not-analyzed"||qe(D,(i==null?void 0:i.jobs)||[])==="out-of-date"||qe(D,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,ae=D=>{var q;return((q=a==null?void 0:a.currentEntityShas)==null?void 0:q.includes(D))||!1},$=D=>{var q;return c!=null&&c(D)?!0:((q=i==null?void 0:i.jobs)==null?void 0:q.some(te=>{var ce;return(ce=te.entityShas)==null?void 0:ce.includes(D.sha)}))||!1},I=D=>{h==null||h(D)};return n(xa,{filePath:A.filePath,isExpanded:H,onToggle:()=>Y(A.filePath),simulationPreviews:n(ba,{entities:A.entities,maxPreviews:1}),entityCount:A.totalCount,state:A.state,lastModified:A.lastUpdated,uncommittedCount:A.uncommittedCount,isUncommitted:A.uncommittedCount>0,actionButton:J?n("button",{onClick:D=>{D.stopPropagation();const q=A.entities.filter(te=>(te.entityType==="visual"||te.entityType==="library")&&(qe(te,(i==null?void 0:i.jobs)||[])==="not-analyzed"||qe(te,(i==null?void 0:i.jobs)||[])==="out-of-date"||qe(te,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(q)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:A.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:A.entities.sort((D,q)=>{var be,Ce,Ee,Se;const te=!((be=D.metadata)!=null&&be.notExported)&&!((Ce=D.metadata)!=null&&Ce.namedExport),ce=!((Ee=q.metadata)!=null&&Ee.notExported)&&!((Se=q.metadata)!=null&&Se.namedExport);if(te&&!ce)return-1;if(!te&&ce)return 1;const me=D.entityType==="visual"||D.entityType==="library",ge=q.entityType==="visual"||q.entityType==="library";return me&&!ge?-1:!me&&ge?1:D.name.localeCompare(q.name)}).map(D=>n(va,{entity:D,isActivelyAnalyzing:ae(D.sha),isQueued:$(D),onGenerateSimulation:I},D.sha))},A.filePath)})}),z>1&&l("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),l("span",{children:["Page ",t," of ",z]}),t<z&&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 Mg=()=>[{title:"Files & Entities - CodeYam"},{name:"description",content:"Browse your codebase files and entities"}];async function Tg({request:e,context:t}){try{const r=new URL(e.url),a=parseInt(r.searchParams.get("page")||"1"),s=r.searchParams.get("filter")||null,o=r.searchParams.get("entityType"),i=t.analysisQueue,c=i?i.getState():{paused:!1,jobs:[]},[d,h]=await Promise.all([dn(),Ot()]);return B({entities:d,currentCommit:h,page:a,filter:s,entityType:o,queueState:c})}catch(r){return console.error("Failed to load entities:",r),B({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const jg=De(function(){var w,N,S;const{entities:t,currentCommit:r,page:a,filter:s,entityType:o,queueState:i,error:c}=Be();at();const[d,h]=sn(),[u,m]=P(!1);Xe({source:"files-page"});const{handleGenerateSimulation:p,handleGenerateAllSimulations:f,isEntityPending:y,pendingEntityKeys:g}=ri((N=(w=r==null?void 0:r.metadata)==null?void 0:w.currentRun)==null?void 0:N.currentEntityShas,i),x=t||[],b=re(()=>{const k=new Set([]);for(const M of x)k.add(M.filePath??"No File Path");return Array.from(k)},[x]),v=re(()=>{let k=x;return u&&(k=k.filter(M=>{var j;return(j=M.metadata)==null?void 0:j.isUncommitted})),k.sort((M,j)=>{var L,F,_,E,T,O;return(L=M.metadata)!=null&&L.isUncommitted&&!((F=j.metadata)!=null&&F.isUncommitted)?-1:!((_=M.metadata)!=null&&_.isUncommitted)&&((E=j.metadata)!=null&&E.isUncommitted)?1:new Date(((T=j.metadata)==null?void 0:T.editedAt)||0).getTime()-new Date(((O=M.metadata)==null?void 0:O.editedAt)||0).getTime()})},[x,u]),C=re(()=>{var M;const k=new Set([]);for(const j of x)(M=j.metadata)!=null&&M.isUncommitted&&k.add(j.filePath??"No File Path");return Array.from(k)},[x]);return c?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:c})]})}):x.length===0?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:l("div",{className:"max-w-md mx-auto",children:[n("h2",{className:"text-xl font-semibold text-gray-900 mb-3",children:"No entities found"}),l("p",{className:"text-[15px] text-gray-600 mb-6",children:["Your project hasn't been analyzed yet. Run"," ",n("code",{className:"px-2 py-1 bg-gray-100 rounded text-sm font-mono",children:"codeyam analyze"})," ","to extract entities from your codebase."]}),n("p",{className:"text-sm text-gray-500",children:"Entities include React components, functions, and other analyzable code elements."})]})})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n(_g,{entities:v,page:a,itemsPerPage:50,currentRun:(S=r==null?void 0:r.metadata)==null?void 0:S.currentRun,filter:s,entityType:o,queueState:i,isEntityPending:y,pendingEntityKeys:g,onGenerateSimulation:p,onGenerateAllSimulations:f,totalFilesCount:b.length,totalEntitiesCount:x.length,uncommittedFilesCount:C.length,showOnlyUncommitted:u,onToggleUncommitted:()=>m(!u)})]})})}),Ig=Object.freeze(Object.defineProperty({__proto__:null,default:jg,loader:Tg,meta:Mg},Symbol.toStringTag,{value:"Module"})),$g=()=>[{title:"Labs - CodeYam"},{name:"description",content:"Experimental features"}];async function Rg({request:e}){var t;try{const r=await $e();if(!r)return B({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Project not found"});const{project:a}=await Ie(r),s=fe()||process.cwd(),o=Fo(s)||"";let i="";try{const d=await er();if(d!=null&&d.webapps&&Array.isArray(d.webapps)){const h=d.webapps.map(u=>u.framework).filter(Boolean);h.length>0&&(i=h.join(", "))}}catch{}const c=Yo(r);return B({labs:((t=a.metadata)==null?void 0:t.labs)??null,projectSlug:r,defaultEmail:o,detectedTechStack:i,unlockCode:c,error:null})}catch(r){return console.error("Failed to load labs config:",r),B({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Failed to load labs configuration"})}}async function Dg({request:e}){try{const t=await e.formData(),r=t.get("feature"),a=t.get("enabled")==="true";if(!r)return B({success:!1,error:"Missing feature name"},{status:400});const s=await $e();return s?(r==="clearAccess"?await Ln({projectSlug:s,metadataUpdate:{labs:{accessGranted:!1,simulations:!1}}}):await Ln({projectSlug:s,metadataUpdate:{labs:{[r]:a}}}),B({success:!0,error:null})):B({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),B({success:!1,error:"Failed to save labs configuration"},{status:500})}}const Lg=[{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}],js="https://docs.google.com/forms/d/e/1FAIpQLSfopqQOQsjY9S4Ns0l3xDLzGl7iYNpKa2Wn2Xzmtxj8CR1sMA/viewform",Fg=[{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 Og({onClose:e}){const t=Ne(null),r=Ne(0);return ee(()=>{const a=t.current;if(!a)return;const s=100,o=2e3,i=500;let c=null,d=!1;const h=()=>{r.current=Date.now(),!c&&!d&&(c=setInterval(()=>{const u=Date.now()-r.current,m=a.scrollTop>s,p=u>o;m&&p&&(a.scrollTo({top:0,behavior:"smooth"}),d=!0,c&&(clearInterval(c),c=null))},i))};return a.addEventListener("scroll",h,{passive:!0}),()=>{a.removeEventListener("scroll",h),c&&clearInterval(c)}},[]),l("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:a=>{a.target===a.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),l("div",{ref:t,className:"relative bg-white rounded-xl p-4 md:p-6 max-w-3xl w-full mx-4 max-h-[90vh] overflow-y-auto",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none z-10",children:"×"}),l("div",{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:`${js}?embedded=true`,width:"100%",height:"1400",style:{border:0,minHeight:"1400px"},title:"Labs Waitlist Form",loading:"eager",children:n("div",{className:"flex items-center justify-center p-8 text-gray-600",children:l("div",{className:"text-center",children:[n("div",{className:"mb-4",children:"Loading form..."}),l("div",{className:"text-sm",children:["If this takes too long,"," ",n("a",{href:js,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"open the form directly"})]})]})})})})]})]})}function Yg({onClose:e,unlockCodeInput:t,setUnlockCodeInput:r,unlockFetcher:a}){var i,c;const s=(i=a.data)==null?void 0:i.error,o=(c=a.data)==null?void 0:c.success;return l("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:d=>{d.target===d.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),l("div",{className:"relative bg-white rounded-xl p-8 max-w-md w-full mx-4",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none",children:"×"}),n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Have an unlock code?"}),n("p",{className:"text-sm text-cygray-50 mb-6",children:"If you've received an unlock code, paste it below to enable Simulations immediately."}),l(a.Form,{method:"post",action:"/api/labs-unlock",className:"space-y-4",children:[n("input",{type:"text",name:"unlockCode",value:t,onChange:d=>r(d.target.value),placeholder:"CY-...",className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-100 focus:border-transparent"}),n("button",{type:"submit",disabled:!t.trim()||a.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:a.state==="submitting"?"Validating...":"Unlock"}),s&&n("p",{className:"text-red-600 text-sm mt-2",children:s}),o&&n("p",{className:"text-emerald-600 text-sm mt-2",children:"Simulations enabled! Refresh the page to see all tabs."})]})]})]})}const zg=De(function(){const{labs:t,unlockCode:r,error:a}=Be(),s=Ae(),o=Ae(),i=Ae(),[c,d]=P(""),[h,u]=P(!1),[m,p]=P(!1);Xe({source:"labs-page"});const f=(t==null?void 0:t.accessGranted)===!0||(t==null?void 0:t.simulations)===!0;return a?n("div",{className:"bg-cygray-10 min-h-screen",children:l("div",{className:"px-20 pt-8 pb-12 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Labs"}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 mt-4",children:n("p",{className:"text-red-700",children:a})})]})}):f?l("div",{className:"bg-cygray-10 min-h-screen font-sans flex flex-col",children:[n("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"})}),l("div",{className:"px-6 sm:px-12 pt-8 pb-10",children:[n("h2",{className:"font-serif italic text-[32px] sm:text-[48px] text-primary-100 mb-3 font-normal leading-tight",children:"Congrats!"}),n("p",{className:"font-serif text-[18px] sm:text-[24px] text-cyblack-100 font-normal leading-snug max-w-2xl",children:"You were granted early access to software simulation and other experimental features."})]}),n("div",{className:"px-6 sm:px-12 space-y-6 flex-1",children:Lg.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:l("div",{className:"flex items-center justify-between gap-4",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-3 mb-3",children:[n("h3",{className:"text-lg font-semibold text-cyblack-100 m-0",children:y.name}),n("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${g?"bg-primary-100/15 text-primary-100":"bg-cygray-20 text-cygray-50"}`,children:g?"Enabled":"Disabled"})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed m-0",children:y.description})]}),l(o.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:y.id}),n("input",{type:"hidden",name:"enabled",value:String(!g)}),n("button",{type:"submit",disabled:x,className:`relative inline-flex h-8 w-14 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none disabled:opacity-60 disabled:cursor-not-allowed ${g?"bg-primary-100":"bg-gray-300"}`,children:n("span",{className:`pointer-events-none inline-block h-7 w-7 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${g?"translate-x-6":"translate-x-0"}`})})]})]})},y.id)})}),r&&n("div",{className:"px-6 sm:px-12 pt-12",children:l("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:[n("h3",{className:"text-base font-semibold text-cyblack-100 mb-1",children:"Unlock Code"}),n("p",{className:"text-sm text-cygray-50 mb-3",children:"This code was used to enable Labs access. Clear it to revoke access and return to the landing page."}),l("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[n("code",{className:"sm:flex-1 px-4 py-2.5 bg-cygray-10 border border-cygray-30 rounded-lg text-sm font-mono text-cyblack-100 overflow-x-auto",children:r}),l(i.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:"clearAccess"}),n("input",{type:"hidden",name:"enabled",value:"false"}),n("button",{type:"submit",disabled:i.state==="submitting",className:"px-4 py-2.5 bg-red-50 border border-red-200 rounded-lg text-sm font-medium text-red-700 cursor-pointer transition-colors hover:bg-red-100 disabled:opacity-60 disabled:cursor-not-allowed",children:i.state==="submitting"?"Clearing...":"Clear"})]})]})]})})]}):l("div",{className:"bg-cygray-10 min-h-screen font-sans",children:[h&&n(Og,{onClose:()=>u(!1)}),m&&n(Yg,{onClose:()=>p(!1),unlockCodeInput:c,setUnlockCodeInput:d,unlockFetcher:s}),l("div",{className:"flex flex-wrap justify-between items-center gap-3 px-6 sm:px-12 pt-8 pb-4",children:[n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"}),l("div",{className:"flex flex-wrap items-center gap-3",children:[n("button",{onClick:()=>p(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cygray-30 bg-transparent text-cygray-50 cursor-pointer transition-colors hover:border-cyblack-100 hover:text-cyblack-100",children:"Have a Code?"}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cyblack-100 bg-transparent text-cyblack-100 cursor-pointer transition-colors hover:bg-cyblack-100 hover:text-white",children:"Apply for Early Access"})]})]}),l("div",{className:"px-6 sm:px-12 pt-12 pb-8",children:[n("h2",{className:"font-serif text-[24px] sm:text-[32px] leading-snug text-cyblack-100 max-w-xl mb-4 font-normal",children:"Powerful tools for the AI coding era."}),l("p",{className:"text-base sm:text-lg text-cygray-50 leading-relaxed max-w-xl mb-8",children:["We're opening early access to"," ",n("strong",{className:"text-cyblack-100",children:"experimental features"})," to a small group of developers and teams."]}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded bg-primary-200 text-white border-none cursor-pointer transition-colors hover:bg-primary-100",children:"Apply for Early Access"})]}),n("div",{className:"px-6 sm:px-12 py-8",children:n("hr",{className:"border-t border-cygray-30 m-0"})}),l("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:[n("h3",{className:"font-serif text-[22px] sm:text-[28px] text-cyblack-100 mb-10 font-normal text-center",children:"In The Works"}),n("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5 max-w-4xl mx-auto",children:Fg.map(y=>l("div",{className:"border border-cygray-30 bg-white p-5 sm:p-8 rounded-lg",children:[l("h4",{className:"text-base font-semibold text-cyblack-100 mb-1",children:[y.title," ",l("span",{className:"font-normal text-primary-100 font-serif italic",children:["(",y.status,")"]})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed mt-3 mb-0",children:y.desc})]},y.title))})]}),n("div",{className:"px-6 sm:px-12 py-16",children:l("div",{className:"rounded-lg p-6 sm:p-12 bg-primary-200",children:[n("h3",{className:"font-serif text-[20px] sm:text-[24px] text-white mb-4 font-semibold",children:"Request Early Access"}),n("p",{className:"text-sm text-white/80 leading-relaxed max-w-lg mb-10 font-mono",children:"We're onboarding a limited number of developers and teams. Tell us about how you build and we'll let you know when you can try simulations and other Labs features."}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded border border-white bg-white text-cyblack-100 cursor-pointer transition-colors hover:bg-white/90 mb-4",children:"Apply for Early Access"}),n("p",{className:"text-xs text-white/60 m-0",children:"Takes about 2 minutes. Your answers help us determine eligibility and prioritize access."})]})})]})}),Bg=Object.freeze(Object.defineProperty({__proto__:null,action:Dg,default:zg,loader:Rg,meta:$g},Symbol.toStringTag,{value:"Module"}));function Ug(e,t,r){const[a,s]=P(()=>new Set),[o,i]=P(()=>new Set),c=Ne([]),d=Ne([]);return ee(()=>{(t.length!==c.current.length||t.some((g,x)=>g!==c.current[x]))&&(c.current=t,s(g=>{const x=new Set;return t.forEach(b=>{g.has(b)&&x.add(b)}),x}))},[t]),ee(()=>{(r.length!==d.current.length||r.some((g,x)=>g!==d.current[x]))&&(d.current=r,i(g=>{const x=new Set;return r.forEach(b=>{g.has(b)&&x.add(b)}),x}))},[r]),{expandedUncommitted:a,expandedBranch:o,setExpandedUncommitted:s,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:()=>{s(new Set(t))},collapseAllUncommitted:()=>{s(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function Wg(e,t,r){const[a,s]=P(null),[o,i]=P(null),c=Ae();ee(()=>{var m,p;((m=c.data)==null?void 0:m.oldContent)!==void 0&&((p=c.data)==null?void 0:p.newContent)!==void 0&&i({oldContent:c.data.oldContent,newContent:c.data.newContent,fileName:c.data.fileName})},[c.data]);const d=m=>{s({type:"file",path:m}),i(null);const p=new FormData;p.append("actionType","getDiff"),p.append("filePath",m),p.append("diffType","branch"),p.append("baseBranch",e),p.append("currentBranch",t||""),c.submit(p,{method:"post"})},h=(m,p)=>{s({type:"entity",path:m,entitySha:p}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",m),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",p),c.submit(f,{method:"post"})},u=()=>{s(null),i(null)};return{diffView:a,diffContent:o,isLoading:c.state==="loading"||c.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:h,handleCloseDiff:u}}function Hg({diffView:e,diffContent:t,isLoading:r,entities:a,onClose:s}){var h;const[o,i]=P(!1),[c,d]=P(!1);return ee(()=>{d(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:l("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[l("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[l("div",{children:[n("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),n("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&l("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((h=a.find(u=>u.sha===e.entitySha))==null?void 0:h.name)||e.entitySha]})]}),l("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick:s,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:c&&n(Ml,{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:s,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 Jg({files:e,currentBranch:t,defaultBranch:r,baseBranch:a,allBranches:s,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:c,sortOrder:d,onToggleFile:h,onBranchChange:u,onGenerateSimulation:m,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=e.flatMap(([C,{entities:w}])=>{const N=w.filter(S=>i(S.sha)||c(S)).map(S=>S.sha);return N.length>0?[{entityShas:N}]:[]}),b=C=>{const w=C.map(N=>qe(N,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=re(()=>[...e].sort((C,w)=>{const N=C[1].entities.reduce((j,L)=>{var _;const F=((_=L.metadata)==null?void 0:_.editedAt)||L.updatedAt;return F?j?new Date(F)>new Date(j)?F:j:F:j},null),S=w[1].entities.reduce((j,L)=>{var _;const F=((_=L.metadata)==null?void 0:_.editedAt)||L.updatedAt;return F?j?new Date(F)>new Date(j)?F:j:F:j},null);if(!N&&!S)return 0;if(!N)return 1;if(!S)return-1;const k=new Date(N).getTime(),M=new Date(S).getTime();return d==="desc"?M-k:k-M}),[e,d]);return n("div",{children:e.length>0?l("div",{children:[n(ya,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:v.map(([C,{status:w,entities:N,isUncommitted:S}])=>{const k=o.has(C),M=b(N),j=N.reduce((E,T)=>{var G;const O=((G=T.metadata)==null?void 0:G.editedAt)||T.updatedAt;return O?E?new Date(O)>new Date(E)?O:E:O:E},null),F=N.filter(E=>E.entityType==="visual"||E.entityType==="library").length===0;let _;return F?_=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):M==="analyzing"?_=l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):M==="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"}):M==="out-of-date"?_=n("button",{onClick:E=>{E.stopPropagation(),N.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!i(T.sha)&&!c(T)).forEach(T=>m(T))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):M==="not-analyzed"&&(_=n("button",{onClick:E=>{E.stopPropagation(),N.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!i(T.sha)&&!c(T)).forEach(T=>m(T))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(xa,{filePath:C,isExpanded:k,onToggle:()=>h(C),fileStatus:w,isUncommitted:S,simulationPreviews:n(ba,{entities:N,maxPreviews:1}),entityCount:N.length,state:M,lastModified:j,isNotAnalyzable:F,actionButton:_,children:N.sort((E,T)=>{const O=E.entityType==="visual"||E.entityType==="library",G=T.entityType==="visual"||T.entityType==="library";return O&&!G?-1:!O&&G?1:0}).map(E=>n(va,{entity:E,isActivelyAnalyzing:i(E.sha),isQueued:c(E),onGenerateSimulation:m},E.sha))},C)})})]}):l("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function Vg({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:a,isEntityQueued:s,projectSlug:o,baseBranch:i,currentBranch:c,sortOrder:d,onToggleFile:h,onShowFileDiff:u,onGenerateSimulation:m,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=re(()=>{const C=[];return e.forEach(([w,{editedEntities:N}])=>{const S=N.filter(k=>a(k.sha)||s(k)).map(k=>k.sha);S.length>0&&C.push({entityShas:S})}),C},[e,a,s]),b=re(()=>{const C=new Map;return e.forEach(([w,{editedEntities:N}])=>{const S=N.map(L=>qe(L,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 M=N.reduce((L,F)=>{var E;const _=((E=F.metadata)==null?void 0:E.editedAt)||F.updatedAt;return _&&(!L||new Date(_)>new Date(L))?_:L},null),j=N.filter(L=>L.entityType==="visual"||L.entityType==="library").length;C.set(w,{state:k,lastModified:M,analyzableCount:j})}),C},[e,x]),v=re(()=>[...e].sort((C,w)=>{const N=b.get(C[0]),S=b.get(w[0]),k=N==null?void 0:N.lastModified,M=S==null?void 0:S.lastModified;if(!k&&!M)return 0;if(!k)return 1;if(!M)return-1;const j=new Date(k).getTime(),L=new Date(M).getTime();return d==="desc"?L-j:j-L}),[e,b,d]);return e.length===0?l("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"If you edit a file in your project, it will show up here."})]}):l("div",{children:[n(ya,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:v.map(([C,{status:w,editedEntities:N}])=>{const S=r.has(C),k=b.get(C),{state:M,lastModified:j,analyzableCount:L}=k,F=L===0;let _;return F?_=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):M==="analyzing"?_=l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):M==="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"}):M==="out-of-date"?_=n("button",{onClick:E=>{E.stopPropagation(),N.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!a(T.sha)&&!s(T)).forEach(T=>m(T))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):M==="not-analyzed"&&(_=n("button",{onClick:E=>{E.stopPropagation(),N.filter(T=>(T.entityType==="visual"||T.entityType==="library")&&!a(T.sha)&&!s(T)).forEach(T=>m(T))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(xa,{filePath:C,isExpanded:S,onToggle:()=>h(C),fileStatus:w,simulationPreviews:n(ba,{entities:N,maxPreviews:1}),entityCount:N.length,state:M,lastModified:j,isNotAnalyzable:F,isUncommitted:!0,actionButton:_,children:N.sort((E,T)=>{const O=E.entityType==="visual"||E.entityType==="library",G=T.entityType==="visual"||T.entityType==="library";return O&&!G?-1:!O&&G?1:0}).map(E=>n(va,{entity:E,isActivelyAnalyzing:a(E.sha),isQueued:s(E),onGenerateSimulation:m},E.sha))},C)})})]})}function Gg({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:a}){return n("div",{className:"border-b border-gray-200",children:l("nav",{className:"flex gap-8 items-center",children:[l("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[l("span",{className:"flex items-center gap-2",children:["Branch Changes",a>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="branch"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:a})]}),e==="branch"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]}),l("button",{onClick:()=>t("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[l("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:r})]}),e==="uncommitted"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const qg=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function Kg({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const a=t.get("filePath"),s=t.get("diffType"),o=t.get("baseBranch"),i=t.get("currentBranch"),c=t.get("entitySha");let d;return s==="branch"?d=An(a,o,i):d=qh(a),B({...d,entitySha:c})}return B({error:"Unknown action"},{status:400})}async function Qg({request:e,context:t}){try{const r=new URL(e.url),a=r.searchParams.get("compare"),s=r.searchParams.get("viewBranch"),o=t.analysisQueue,i=o?o.getState():{paused:!1,jobs:[]},[c,d,h]=await Promise.all([dn(),Ot(),$e()]),u=$o(),m=Wh(),p=Hh(),f=Jh(),y=s||m,g=a||p;let x=[];return y&&y!==g&&(x=Ro(g,y)),B({entities:c||[],gitStatus:u,currentBranch:y,actualCurrentBranch:m,defaultBranch:p,allBranches:f,baseBranch:g,branchDiff:x,currentCommit:d,projectSlug:h,queueState:i})}catch(r){return console.error("Failed to load git data:",r),B({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 Zg=De(function(){var ye,xt;const{entities:t,gitStatus:r,currentBranch:a,actualCurrentBranch:s,defaultBranch:o,allBranches:i,baseBranch:c,branchDiff:d,currentCommit:h,projectSlug:u,queueState:m}=Be();Xe({source:"git-page"});const[p,f]=sn(),[y,g]=P(null),[x,b]=P("desc"),[v,C]=P("branch"),w=p.get("expanded")==="true",N=()=>{b(de=>de==="desc"?"asc":"desc")},S=Ae(),k=S.data;ee(()=>{a&&c&&a!==c&&S.state==="idle"&&!k&&S.load(`/api/branch-entity-diff?base=${encodeURIComponent(c)}&compare=${encodeURIComponent(a)}`)},[a,c,S,k]);const M=re(()=>{const de=Zo(r,t);return Array.from(de.entries()).sort((Fe,Oe)=>Fe[0].localeCompare(Oe[0]))},[r,t]),j=re(()=>{const de=ng(d,t,k);return Array.from(de.entries()).sort((Fe,Oe)=>Fe[0].localeCompare(Oe[0]))},[d,t,k]),L=re(()=>rg(r,t),[r,t]),F=re(()=>v==="uncommitted"?M:j,[v,M,j]),_=re(()=>F.map(([de])=>de),[F]),{expandedUncommitted:E,setExpandedUncommitted:T,toggleFile:O,expandAllUncommitted:G,collapseAllUncommitted:V}=Ug(w,_,[]),{diffView:U,diffContent:z,isLoading:Y,handleShowFileDiff:R,handleCloseDiff:A}=Wg(c,a),H=(ye=h==null?void 0:h.metadata)==null?void 0:ye.currentRun,W=new Set((H==null?void 0:H.currentEntityShas)||[]),J=new Set(m.jobs.flatMap(de=>de.entityShas||[])),ae=new Set(((xt=m.currentlyExecuting)==null?void 0:xt.entityShas)||[]),{isAnalyzing:$,handleGenerateSimulation:I,handleGenerateAllSimulations:D,isEntityBeingAnalyzed:q,isEntityPending:te}=ri(H==null?void 0:H.currentEntityShas,m),ce=de=>te(de)||J.has(de.sha)||ae.has(de.sha),me=de=>{de===(s||a)?p.delete("viewBranch"):p.set("viewBranch",de),f(p)},ge=de=>{de===o?p.delete("compare"):p.set("compare",de),f(p)},be=()=>{const Fe=F.flatMap(([Oe,Bt])=>Bt.editedEntities||Bt.entities||[]).filter(Oe=>!W.has(Oe.sha)&&!J.has(Oe.sha)&&!ae.has(Oe.sha)&&!te(Oe));D(Fe)},Ce=M.length,Ee=j.length,Se=F.flatMap(([de,Fe])=>Fe.editedEntities||Fe.entities||[]),Pe=Se.filter(de=>de.entityType==="visual"||de.entityType==="library"),Me=Pe.length>0&&Pe.every(de=>W.has(de.sha)),ve=Pe.length>0&&!Me&&Pe.every(de=>J.has(de.sha)||ae.has(de.sha)),Q=$||Me||ve,ue=Me?"Analyzing...":ve?"Queued...":$?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Git Changes"}),l("p",{className:"text-[15px] text-gray-500",children:["This is a list of all the files that are affected by your local changes. ",n("strong",{children:"Analyze a file to get simulations."})]})]}),n("div",{className:"mb-6",children:n(Gg,{activeTab:v,onTabChange:C,uncommittedCount:Ce,branchCount:Ee})}),a&&v==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:a===o?l("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:o}),"."]}):l("div",{className:"flex gap-6 items-center",children:[l("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?l("div",{className:"relative w-50",children:[n("select",{value:a,onChange:de=>me(de.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(de=>n("option",{value:de,children:de},de))}),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:a})]}),l("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),l("div",{className:"relative w-[200px]",children:[n("select",{value:c,onChange:de=>ge(de.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(de=>de!==a).map(de=>n("option",{value:de,children:de},de))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children:l("div",{className:"relative flex items-center",children:[n("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),n("div",{className:"mb-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:F.length})," ","modified ",F.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:Se.length})," ",Se.length===1?"entity":"entities"]})]}),F.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:G,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Fs,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:V,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(Os,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),l("div",{className:"overflow-hidden",children:[v==="branch"&&a&&n(Jg,{files:j,currentBranch:a,defaultBranch:o,baseBranch:c,allBranches:i,expandedFiles:E,isEntityBeingAnalyzed:q,isEntityQueued:ce,sortOrder:x,onToggleFile:de=>O(de,E,T),onBranchChange:ge,onGenerateSimulation:I,onSortChange:N,onAnalyzeAll:be,analyzeAllDisabled:Q,analyzeAllText:ue}),v==="uncommitted"&&n(Vg,{files:M,entityImpactMap:L,expandedFiles:E,isEntityBeingAnalyzed:q,isEntityQueued:ce,projectSlug:u,baseBranch:c,currentBranch:a,sortOrder:x,onToggleFile:de=>O(de,E,T),onShowFileDiff:R,onGenerateSimulation:I,onSortChange:N,onAnalyzeAll:be,analyzeAllDisabled:Q,analyzeAllText:ue})]}),U&&n(Hg,{diffView:U,diffContent:z,isLoading:Y,entities:t,onClose:A}),y&&u&&n(ht,{projectSlug:u,onClose:()=>g(null)})]})})}),Xg=Object.freeze(Object.defineProperty({__proto__:null,action:Kg,default:Zg,loader:Qg,meta:qg},Symbol.toStringTag,{value:"Module"})),V0={entry:{module:"/assets/entry.client-BSHEfydn.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/index-ChN9-fAY.js"],css:[]},routes:{root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/root-CHhiHoo_.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/index-ChN9-fAY.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/ReportIssueModal-CgMEzchJ.js","/assets/useReportContext-CpZgwliL.js","/assets/loader-circle-CTqLEAGU.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/book-open-PttOB2SF.js","/assets/useToast-Bv9JFvUO.js","/assets/useLastLogLine-COky1GVF.js","/assets/LogViewer-Bm3PmcCz.js","/assets/EntityTypeIcon-BqY8gDAW.js","/assets/TruncatedFilePath-CiwXDxLh.js","/assets/chevron-down-TJp6ofnp.js","/assets/circle-check-CXhHQYrI.js","/assets/triangle-alert-BZz2NjYa.js","/assets/copy-6y9ALfGT.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.fullscreen-CBoafmVs.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/InlineSpinner-ClaLpuOo.js","/assets/useLastLogLine-COky1GVF.js","/assets/useCustomSizes-DNwUduNu.js","/assets/cy-logo-cli-DcX-ZS3p.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-38yPijoD.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/InteractivePreview-BDhPilK7.js","/assets/InlineSpinner-ClaLpuOo.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-COky1GVF.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha_.create-scenario-DGgZjdFg.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/InteractivePreview-BDhPilK7.js","/assets/InlineSpinner-ClaLpuOo.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-COky1GVF.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.agent-transcripts-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.logs._projectSlug-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.execute-function-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-mode-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.delete-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-report-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-profile-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.restart-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/agent-transcripts-CN61MOMa.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useReportContext-CpZgwliL.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/terminal-BrCP7uQo.js","/assets/search-B8VUL8nl.js","/assets/chevron-down-TJp6ofnp.js","/assets/book-open-PttOB2SF.js","/assets/triangle-alert-BZz2NjYa.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-fixture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-BtBFH820.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/LogViewer-Bm3PmcCz.js","/assets/useLastLogLine-COky1GVF.js","/assets/useReportContext-CpZgwliL.js","/assets/EntityTypeIcon-BqY8gDAW.js","/assets/EntityTypeBadge-B5ctlSYt.js","/assets/SafeScreenshot-Gq3Ocjo6.js","/assets/LoadingDots-Bs7Nn1Jr.js","/assets/loader-circle-CTqLEAGU.js","/assets/pause-D6vreykR.js","/assets/createLucideIcon-Ca9fAY46.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.debug-setup-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.labs-unlock-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha._-BVnB8a9L.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useLastLogLine-COky1GVF.js","/assets/InlineSpinner-ClaLpuOo.js","/assets/InteractivePreview-BDhPilK7.js","/assets/SafeScreenshot-Gq3Ocjo6.js","/assets/LibraryFunctionPreview-VeqEBv9v.js","/assets/LoadingDots-Bs7Nn1Jr.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-CBui0id_.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-BqY8gDAW.js","/assets/CopyButton-CA3JxPb7.js","/assets/LogViewer-Bm3PmcCz.js","/assets/useReportContext-CpZgwliL.js","/assets/preload-helper-ckwbz45p.js","/assets/useCustomSizes-DNwUduNu.js","/assets/ReportIssueModal-CgMEzchJ.js","/assets/circle-check-CXhHQYrI.js","/assets/triangle-alert-BZz2NjYa.js","/assets/copy-6y9ALfGT.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.analyze-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/simulations-CPoAg7Zo.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useReportContext-CpZgwliL.js","/assets/SafeScreenshot-Gq3Ocjo6.js","/assets/LoadingDots-Bs7Nn1Jr.js","/assets/EntityTypeIcon-BqY8gDAW.js","/assets/fileTableUtils-DCPhhSMo.js","/assets/chevron-down-TJp6ofnp.js","/assets/search-B8VUL8nl.js","/assets/loader-circle-CTqLEAGU.js","/assets/createLucideIcon-Ca9fAY46.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.health-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.queue-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/dev.empty-C0epRiVn.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/ScenarioViewer-CBui0id_.js","/assets/InteractivePreview-BDhPilK7.js","/assets/useCustomSizes-DNwUduNu.js","/assets/LogViewer-Bm3PmcCz.js","/assets/SafeScreenshot-Gq3Ocjo6.js","/assets/useLastLogLine-COky1GVF.js","/assets/InlineSpinner-ClaLpuOo.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-CgMEzchJ.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/circle-check-CXhHQYrI.js","/assets/triangle-alert-BZz2NjYa.js","/assets/copy-6y9ALfGT.js","/assets/scenarioStatus-B_8jpV3e.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/settings-BejnUJ6R.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useReportContext-CpZgwliL.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/static._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/_index-B3TDXxnk.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useLastLogLine-COky1GVF.js","/assets/useToast-Bv9JFvUO.js","/assets/useReportContext-CpZgwliL.js","/assets/LogViewer-Bm3PmcCz.js","/assets/EntityTypeIcon-BqY8gDAW.js","/assets/SafeScreenshot-Gq3Ocjo6.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/circle-check-CXhHQYrI.js","/assets/loader-circle-CTqLEAGU.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/memory-CCQd4aZA.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useReportContext-CpZgwliL.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/terminal-BrCP7uQo.js","/assets/copy-6y9ALfGT.js","/assets/CopyButton-CA3JxPb7.js","/assets/search-B8VUL8nl.js","/assets/pause-D6vreykR.js","/assets/chevron-down-TJp6ofnp.js","/assets/book-open-PttOB2SF.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/files-0N0YJQv7.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useReportContext-CpZgwliL.js","/assets/EntityItem-B86KKU7e.js","/assets/fileTableUtils-DCPhhSMo.js","/assets/chevron-down-TJp6ofnp.js","/assets/search-B8VUL8nl.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/useToast-Bv9JFvUO.js","/assets/TruncatedFilePath-CiwXDxLh.js","/assets/SafeScreenshot-Gq3Ocjo6.js","/assets/LibraryFunctionPreview-VeqEBv9v.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-BZz2NjYa.js","/assets/EntityTypeIcon-BqY8gDAW.js","/assets/EntityTypeBadge-B5ctlSYt.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/labs-BLJ7HxOC.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useReportContext-CpZgwliL.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/git-DXnyr8uP.js",imports:["/assets/chunk-JZWAC4HX-JE9ZIoBl.js","/assets/useReportContext-CpZgwliL.js","/assets/EntityItem-B86KKU7e.js","/assets/LogViewer-Bm3PmcCz.js","/assets/fileTableUtils-DCPhhSMo.js","/assets/createLucideIcon-Ca9fAY46.js","/assets/useToast-Bv9JFvUO.js","/assets/TruncatedFilePath-CiwXDxLh.js","/assets/SafeScreenshot-Gq3Ocjo6.js","/assets/LibraryFunctionPreview-VeqEBv9v.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-BZz2NjYa.js","/assets/EntityTypeIcon-BqY8gDAW.js","/assets/EntityTypeBadge-B5ctlSYt.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-b171b9d3.js",version:"b171b9d3",sri:void 0},G0="build/client",q0="/",K0={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},Q0=!0,Z0=!1,X0=[],ey={mode:"lazy",manifestPath:"/__manifest"},ty="/",ny={module:jl},ry={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:Xd},"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:au},"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:Au},"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:Iu},"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:Rh},"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:Fh},"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:rm},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:sm},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:cm},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:vm},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:Nm},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:Am},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:_m},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:Tm},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:Bm},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:Vm},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:Qm},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:tp},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:rp},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:fp},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:yp},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:Np},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:Ep},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:Rp},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:Fp},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,module:Bp},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:Wp},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:pf},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:yf},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:Sf},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:Af},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:Pf},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:Of},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:Bf},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:Hf},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:Zf},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:eg},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:cg},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:kg},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:Ig},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:Bg},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:Xg}},ay=!1;export{Yc as A,Lc as B,ke as C,cc as D,dc as E,Tt as F,Zl as G,qs as H,Ks as I,Qs as J,rc as K,sc as L,G0 as M,q0 as N,K0 as O,Kl as P,Q0 as Q,Z0 as R,In as S,X0 as T,ey as U,ty as V,ny as W,ry as X,ay as Y,V0 as Z,Hl as a,Rt as b,Pt as c,st as d,ln as e,Xr as f,ea as g,Gs as h,Ul as i,vc as j,wc as k,pt as l,ot as m,eo as n,_c as o,Rn as p,rt as q,to as r,no as s,$c as t,ut as u,ro as v,Ft as w,Ln as x,Xa as y,Uc as z};