@pi-chamber/web 1.0.6-rc.5 → 1.0.6

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 (63) hide show
  1. package/dist/assets/{DiagramView--XO16VPB.js → DiagramView-DsCdfDOP.js} +1 -1
  2. package/dist/assets/{DiffView-Duy2_7Gp.js → DiffView-BWo7yT-P.js} +6 -6
  3. package/dist/assets/{FileSaveConflictDialog-B1DvL9zy.js → FileSaveConflictDialog-IFbuQCcP.js} +1 -1
  4. package/dist/assets/{FilesView-CjjPpE4c.js → FilesView-DLIQkVep.js} +4 -4
  5. package/dist/assets/{GitHubDetailScaffold-DqxAKqCT.js → GitHubDetailScaffold-CxGg6x7R.js} +1 -1
  6. package/dist/assets/{GitHubLinkPicker-ELF_chia.js → GitHubLinkPicker-BmqbTUpE.js} +1 -1
  7. package/dist/assets/{GitHubListPrimitives-C2nGTntk.js → GitHubListPrimitives-a1DxU6Zp.js} +1 -1
  8. package/dist/assets/{GitView-5fIq2nzM.js → GitView-DbqM8Qi1.js} +5 -5
  9. package/dist/assets/{IssuesSurface-Dq5A_bWq.js → IssuesSurface-B2EfICtZ.js} +3 -3
  10. package/dist/assets/{JsonTreeView-BjFFSUwi.js → JsonTreeView-DzVqgwz-.js} +1 -1
  11. package/dist/assets/{MarkdownRendererImpl-B9Cu4TCh.js → MarkdownRendererImpl-7yTzCIEI.js} +3 -3
  12. package/dist/assets/PatchDiff-Dvfm6eOV.js +1 -0
  13. package/dist/assets/{PierreDiffViewer-H2f4pJ1k.js → PierreDiffViewer-ByYaUifK.js} +2 -2
  14. package/dist/assets/{PullRequestsSurface-DPpb2RW_.js → PullRequestsSurface-1IP_dDn8.js} +2 -2
  15. package/dist/assets/{SessionSwitcherContent-B5DaBWZU.js → SessionSwitcherContent-DVxWhG4x.js} +1 -1
  16. package/dist/assets/{SessionSwitcherDropdown-D86FaZg_.js → SessionSwitcherDropdown-DiBGmmtD.js} +2 -2
  17. package/dist/assets/{SessionUnreadDot-CY9-1iV2.js → SessionUnreadDot-qw67HcBO.js} +1 -1
  18. package/dist/assets/SettingsView-CMTIIpWD.js +6 -0
  19. package/dist/assets/{SettingsWindow-Bw1dUoJ1.js → SettingsWindow-DZUSs5Is.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-aR4kcgKL.js → ToolOutputDialog-pgTNzNPN.js} +5 -5
  21. package/dist/assets/{ToolPartDiffPreview-B_wWmhtE.js → ToolPartDiffPreview-Cvnr4JkU.js} +1 -1
  22. package/dist/assets/{VirtualizedFileDiff-BYby097w.js → VirtualizedFileDiff-D8dSHI_H.js} +3 -3
  23. package/dist/assets/{collapsible-Dz0bPrJ_.js → collapsible-ZT74WYMA.js} +1 -1
  24. package/dist/assets/{computeVirtualFileMetrics-8MuwxSC6.js → computeVirtualFileMetrics-g1aOl5nF.js} +1 -1
  25. package/dist/assets/{contextFileOpenGuard-fZ2NIQMQ.js → contextFileOpenGuard-IWdho_6z.js} +1 -1
  26. package/dist/assets/{fileTreeStatus-BzhMMLA9.js → fileTreeStatus-trDHgX4B.js} +2 -2
  27. package/dist/assets/{gitStatusPredicates-Cyh9UhYX.js → gitStatusPredicates-CfBh9Rne.js} +1 -1
  28. package/dist/assets/{githubLink-D2PznPcI.js → githubLink-CuQ2WFBa.js} +1 -1
  29. package/dist/assets/index-BaLCg7tL.css +1 -0
  30. package/dist/assets/{index-BX5pAOQX.js → index-CK9t5Znh.js} +1 -1
  31. package/dist/assets/{index-Cs2nBW_t.js → index-fmzQmSSv.js} +3 -3
  32. package/dist/assets/{main-BI6qe8pz.js → main-DOlk_lfi.js} +2 -2
  33. package/dist/assets/{main-7vBNPBMb.js → main-UnRe9F68.js} +4 -4
  34. package/dist/assets/{markdownCore-D5jiabKe.js → markdownCore-DuZmdypZ.js} +2 -2
  35. package/dist/assets/{miniChat-B3up4Bnz.js → miniChat-Dy9h0B6G.js} +2 -2
  36. package/dist/assets/{mobile-B4vLFgBc.js → mobile-CWrtn0Si.js} +2 -2
  37. package/dist/assets/{nativeFileSave-DpBH1Sa3.js → nativeFileSave-B4Rg6n8u.js} +1 -1
  38. package/dist/assets/{pi-session-focus-preference-BrB72skF.js → pi-session-focus-preference-q-s-Bhf0.js} +1 -1
  39. package/dist/assets/{renderDiffWithHighlighter-B6T04JGG.js → renderDiffWithHighlighter-HRnE6vfE.js} +1 -1
  40. package/dist/assets/{renderElectronMiniChatApp-CX10w321.js → renderElectronMiniChatApp-OZ2fG5eY.js} +2 -2
  41. package/dist/assets/{renderFileWithHighlighter-DtAcGyJr.js → renderFileWithHighlighter-tJRUQWjE.js} +1 -1
  42. package/dist/assets/{renderMobileApp-C9n-BhPZ.js → renderMobileApp-D1nkBJLP.js} +3 -3
  43. package/dist/assets/runtimeEndpointReset-Bby2E_Je.js +62 -0
  44. package/dist/assets/{runtimeSurface-DiP2a57a.js → runtimeSurface-X62LLBLv.js} +1 -1
  45. package/dist/assets/{useAppFontEffects-Oyin3dgQ.js → useAppFontEffects-BFgKpDYT.js} +86 -86
  46. package/dist/assets/{useGitHubRemoteSearch-CZ9Hauw0.js → useGitHubRemoteSearch-MxC4J-VO.js} +1 -1
  47. package/dist/assets/{useSwitcherItems-BSqDA1IF.js → useSwitcherItems-D5TsQEbM.js} +1 -1
  48. package/dist/assets/{web-components-CkTNGkJ2.js → web-components-B_NMC-2c.js} +4 -4
  49. package/dist/index.html +4 -4
  50. package/dist/mini-chat.html +3 -3
  51. package/dist/mobile.html +3 -3
  52. package/package.json +1 -1
  53. package/server/lib/pi/routes.js +5 -1
  54. package/server/lib/pi/routes.test.js +3 -0
  55. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
  56. package/server/lib/pi/session-daemon/session-daemon-list-live.test.js +60 -1
  57. package/server/lib/pi/session-daemon/session-daemon.js +34 -10
  58. package/server/lib/pi/session-daemon/session-engine-router.js +5 -1
  59. package/server/lib/pi/session-daemon/session-engine-router.test.js +21 -0
  60. package/dist/assets/PatchDiff-CTqTTcg7.js +0 -1
  61. package/dist/assets/SettingsView-CiIuOi_E.js +0 -6
  62. package/dist/assets/index-tmO0fZa4.css +0 -1
  63. package/dist/assets/runtimeEndpointReset-aGyXPXPs.js +0 -62
@@ -1,7 +1,7 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Cs2nBW_t.js","assets/vendor-zustand-CXhN0IMY.js","assets/vendor-react-Bz1tRBxM.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js","assets/index-tmO0fZa4.css"])))=>i.map(i=>d[i]);
2
- import{j as t}from"./vendor-boot-3SaHYVb1.js";import{R as u}from"./vendor-react-Bz1tRBxM.js";import{i as ze,j as rt,p as ot,l as lt,m as it,r as ct,b as ut,c as dt,G as mt,h as Ne,u as ht,n as ft,o as bt}from"./useGitHubRemoteSearch-CZ9Hauw0.js";import{as as gt,B as w,I as R,av as xt,aw as pt,aB as yt,ax as vt,ay as Ct,aC as jt,z as $e,h as wt,t as P,e6 as kt,o as ye,b2 as Pe,a$ as Re,b0 as Le,b1 as Ee,d_ as St,d$ as Nt,bv as xe,bT as Rt,y as Lt}from"./useAppFontEffects-Oyin3dgQ.js";import{be as Et,bf as Ie,bg as pe,bh as Ae,bi as ce,bj as It,bk as ue,aT as At,L as Oe,b2 as Dt,a$ as Tt,bl as Gt}from"./runtimeEndpointReset-aGyXPXPs.js";import{_ as Ht}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as Bt,d as Ft}from"./vendor-zustand-CXhN0IMY.js";import{j as _e,p as Mt}from"./index-Cs2nBW_t.js";import{a as Ue,u as zt,p as $t,r as Pt,t as De,x as Ot,z as _t,A as Ut,w as ie,y as Kt,B as oe,C as Ke,D as Wt,T as qt,E as Te,G as Vt,H as Qt,I as Jt,J as Yt,K as Ge}from"./GitHubDetailScaffold-DqxAKqCT.js";import{I as Zt,a as Xt,b as es,i as We,c as ts,d as ss,s as as,g as le,e as ns,f as rs,h as He,j as Be,C as os,k as ls,v as is}from"./githubLink-D2PznPcI.js";import{a as cs,f as us}from"./GitHubListPrimitives-C2nGTntk.js";import"./vendor-clsx-B-dksMZM.js";import"./runtimeSurface-DiP2a57a.js";import"./nativeFileSave-DpBH1Sa3.js";import"./vendor-tailwind-merge-BKkUfl9q.js";import"./vendor-fuse.js-t_7AcMTv.js";import"./SessionUnreadDot-CY9-1iV2.js";/* empty css */import"./permissionStore-zIpxq9Pq.js";import"./vendor-dompurify-BGCr_sdL.js";const ve={state:"open",involvement:"all",labels:"",search:"",sort:"updated"},ds=3e4,ms=100,hs=50,qe=(e,s)=>ue([e,"issues-collection",s]),Ve=(e,s)=>ue([e,"issues-remote",s.state,s.involvement,s.labels.trim(),s.q.trim()]),Ce=(e,s)=>ue([e,"issue-detail",s]),je=(e,s)=>ue([e,"issue-comments",s]),fs=e=>({state:e,perPage:ms}),bs=(e,s)=>({state:e.state,filter:e.involvement,q:e.q.trim()?e.q.trim():void 0,labels:e.labels.trim()?e.labels.trim():void 0,perPage:hs,...s?{cursor:s}:{}}),gs={set:e=>{typeof e=="function"?j.setState(s=>{const n={filtersByScope:s.filtersByScope,selectionByDirectory:s.selectionByDirectory};return e(n)}):j.setState(e)},get:()=>{const e=j.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},g=It({openCollection:"open",closedCollection:"closed",defaultFilters:ve,freshWindowMs:ds,serverKind:"issues",errorFallback:"Issue request failed",collectionKeyFor:qe,remoteKeyFor:Ve,detailKeyFor:Ce,commentsKeyFor:je,buildCollectionQuery:e=>({...fs(e)}),buildRemoteQuery:(e,s)=>({...bs(e,s)}),fetchList:async(e,s,n,r)=>{const l=await e.issuesList(s,n,r);return{items:l.items,nextCursor:l.nextCursor,fetchedAt:l.fetchedAt}},fetchDetail:async(e,s,n,r)=>e.issueGet(s,n,r),fetchComments:async(e,s,n,r,l)=>{const a=await e.issueComments(s,n,r,l);return{comments:a.comments,nextCursor:a.nextCursor,fetchedAt:a.fetchedAt}}},gs),j=Bt()(Ft((e,s)=>({...g.initialState,actionErrorByDetail:{},actingActions:{},setFilters:g.setFilters,resetFilters:g.resetFilters,selectIssue:g.select,ensureCollection:g.ensureCollection,ensureCollectionsFresh:g.ensureCollectionsFresh,prefetchClosedCollection:g.prefetchClosedCollection,loadMoreCollection:g.loadMoreCollection,refreshCollections:g.refreshCollections,searchRemote:g.searchRemote,loadMoreRemote:g.loadMoreRemote,dropRemoteForRepo:g.dropRemoteForRepo,refreshAllForScope:g.refreshAllForScope,ensureDetail:g.ensureDetail,refreshDetail:g.refreshDetail,ensureComments:g.ensureComments,loadMoreComments:g.loadMoreComments,refreshComments:g.refreshComments,updateIssue:async(n,r,l,a,d)=>{const b=Ae(r,l),o=Ce(r,l);if(s().actingActions[b])return{ok:!1,error:{kind:"failed",message:"An update is already in progress"}};e(C=>({actingActions:{...C.actingActions,[b]:!0},actionErrorByDetail:{...C.actionErrorByDetail,[b]:null}}));const c=g.resources.details.getEntry(o)?.data?.detail??null,p=c?.issue??null,v=p?{...p,title:a.title??p.title,body:a.body??p.body,state:a.state??p.state,stateReason:a.state!==void 0?a.stateReason??null:p.stateReason,labels:a.labels!==void 0?a.labels.map(C=>({name:C})):p.labels,assignees:a.assignees!==void 0?a.assignees.map(C=>({login:C})):p.assignees}:null;v&&c&&await g.resources.details.refresh(o,async()=>({detail:{...c,issue:v}})).catch(()=>null);try{return await d.issueUpdate(n,r,l,a),await pe(d,{directory:n,repo:r,kind:"issues",number:l}),s().dropRemoteForRepo(r),await s().refreshCollections(n,r,"both",d).catch(()=>null),await s().refreshDetail(n,r,l,d).catch(()=>null),e(C=>({actingActions:{...C.actingActions,[b]:!1}})),{ok:!0}}catch(C){const k=g.toStoreError(C);return c&&await g.resources.details.refresh(o,async()=>({detail:c})).catch(()=>null),e(h=>({actingActions:{...h.actingActions,[b]:!1},actionErrorByDetail:{...h.actionErrorByDetail,[b]:k}})),{ok:!1,error:k}}},addComment:async(n,r,l,a,d)=>{const b=Ae(r,l),o=je(r,l),c=a.trim(),p={id:-Date.now(),url:"",body:c,author:null,createdAt:new Date().toISOString(),updatedAt:null},v=g.resources.comments.getEntry(o)?.data??null;if(v){const C={comments:[...v.comments,p],nextCursor:v.nextCursor,fetchedAt:v.fetchedAt};await g.resources.comments.refresh(o,async()=>C).catch(()=>null)}try{return await d.issueComment(n,r,l,c),await pe(d,{directory:n,repo:r,kind:"issues",number:l}),await s().refreshComments(n,r,l,d).catch(()=>null),await s().refreshDetail(n,r,l,d).catch(()=>null),{ok:!0}}catch(C){const k=g.toStoreError(C);return v?await g.resources.comments.refresh(o,async()=>v).catch(()=>null):g.resources.comments.remove(o),e(h=>({actionErrorByDetail:{...h.actionErrorByDetail,[b]:k}})),{ok:!1,error:k}}},createIssue:async(n,r)=>{try{const l=await r.issueCreate(n.directory,n.repo,{title:n.title,body:n.body,labels:n.labels,assignees:n.assignees});return await pe(r,{directory:n.directory,repo:n.repo,kind:"issues"}),s().dropRemoteForRepo(n.repo),await s().refreshCollections(n.directory,n.repo,"both",r).catch(()=>null),{ok:!0,number:l.issue.number}}catch(l){return{ok:!1,error:g.toStoreError(l)}}},notifyAgentTurnComplete:n=>{const r=_e((n||"").trim());if(!r)return;const l=s().selectionByDirectory[r];!l?.repo||typeof l.number!="number"||(g.markCollectionsStale(l.repo),Ht(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-Cs2nBW_t.js").then(d=>d.cJ);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([0,1,2,3,4,5,6,7])).then(({getRegisteredRuntimeAPIs:a})=>{const d=a()?.github??null;if(d)return s().refreshDetail(r,l.repo,l.number,d)}).catch(()=>{}))},resetForRuntimeSwitch:()=>{g.resetCore(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-issues-store"}));typeof window<"u"&&Mt(()=>{j.getState().resetForRuntimeSwitch()});const xs=e=>g.getLocalIndex(e),ps=(e,s)=>g.getLocalIndex(e).find(n=>n.number===s)??null,Fe=(e,s)=>ce(g.resources.collections,e?qe(e,s):null),ys=(e,s)=>ce(g.resources.remote,e?Ve(e,s):null),vs=(e,s)=>ce(g.resources.details,e!=null&&s!=null?Ce(e,s):null),Cs=(e,s)=>ce(g.resources.comments,e!=null&&s!=null?je(e,s):null),js=(e,s)=>j(n=>!e||!s?ve:n.filtersByScope[Et(e,s)]??ve),ws=e=>j(s=>e?s.selectionByDirectory[_e(e)]??Ie:Ie),ks=e=>typeof e!="number"||e===0?null:t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 typography-micro tabular-nums text-muted-foreground",title:`${e} comments`,"aria-label":`${e} comments`,children:[t.jsx(R,{name:"chat-1",className:"size-3.5"}),e]}),Ss=({items:e,hasMore:s,isLoadingMore:n,isLoading:r,isRefreshing:l,stale:a,error:d,filters:b,incompleteNotice:o=null,remote:c=null,numberJump:p=null,onFiltersChange:v,onClearFilters:C,onLoadMore:k,onRetry:h,onOpen:x,onNewIssue:S,headerActionsSlot:N=null,headerActionsPresentation:B="drawer"})=>{const G=b.state==="open"&&b.involvement==="all"&&!b.search.trim()&&!b.labels.trim(),{isMobile:$,isTablet:A}=gt(),I=$||A,H=N!=null,D=B??"drawer",T=H?D==="desktop"?t.jsxs(w,{type:"button",variant:"ghost",size:"sm",onClick:S,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-4"}),"New issue"]}):t.jsxs(w,{type:"button",variant:"ghost",size:"default",onClick:S,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-4"}),"New issue"]}):t.jsxs(w,{type:"button",variant:"ghost",size:I?"sm":"xs",onClick:S,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-3.5"}),"New issue"]}),O=u.useCallback(f=>t.jsx("li",{role:"listitem",children:t.jsx(ze,{glyph:t.jsx(Ue,{kind:"issue",state:f.state}),number:`#${f.number}`,title:f.title,signals:ks(f.comments),meta:t.jsxs(t.Fragment,{children:[t.jsx(rt,{login:f.author?.login,avatarUrl:f.author?.avatarUrl}),t.jsx(ot,{labels:f.labels??[]})]}),updatedAt:f.updatedAt,onOpen:()=>x(f.number),ariaLabel:`Open issue #${f.number} ${f.title}`})},f.number),[x]);return t.jsx(lt,{items:e,renderRow:O,hasMore:s,isLoadingMore:n,isLoading:r,isRefreshing:l,stale:a,error:d,searchValue:b.search,onSearchChange:f=>v({search:f}),searchPlaceholder:"Search issues, or label:bug",searchAriaLabel:"Search issues",toolbarControls:t.jsx(it,{stateValue:b.state,stateOptions:es.map(f=>({id:f.id,label:f.label})),onStateChange:f=>v({state:f}),involvementValue:b.involvement,involvementOptions:Xt.map(f=>({id:f.id,label:f.label})),onInvolvementChange:f=>v({involvement:f}),labelsValue:b.labels,onLabelsChange:f=>v({labels:f}),sortValue:b.sort,sortOptions:Zt.map(f=>({id:f.id,label:f.label})),onSortChange:f=>v({sort:f}),sortAriaLabel:"Sort issues"}),primaryAction:T,headerActionsSlot:N,headerActionsPresentation:D,isDefaultFilters:G,noItemsTitle:b.state==="open"?"No open issues":"No issues yet",noItemsBody:"Issues for this repository appear here.",noItemsIcon:"inbox-archive",noItemsAction:t.jsxs(w,{type:"button",variant:"outline",size:"sm",onClick:S,children:[t.jsx(R,{name:"add",className:"size-3.5"}),"New issue"]}),listAriaLabel:"Issues",skeletonLabel:"Loading issues",incompleteNotice:o,remote:c,numberJump:p,numberJumpKind:"issue",onClearFilters:C,onLoadMore:k,onRetry:h,onOpen:x})},Qe=(e,s,n)=>{const[r,l]=u.useState([]),[a,d]=u.useState([]),[b,o]=u.useState(!1);return u.useEffect(()=>{if(!n)return;let c=!1;return o(!0),n.repoMeta(e,s).then(p=>{c||(l(p.labels??[]),d(p.assignees??[]))}).catch(()=>{c||(l([]),d([]))}).finally(()=>{c||o(!1)}),()=>{c=!0}},[n,e,s]),{labels:r,assignees:a,loading:b}},Je=(e,s)=>e.includes(s)?e.filter(n=>n!==s):[...e,s],Ye=({candidates:e,loading:s,selected:n,onChange:r})=>s?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"Loading labels…"}):e.length===0?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No labels in this repository."}):t.jsx("div",{className:"flex flex-wrap gap-1",children:e.map(l=>{const a=n.includes(l.name);return t.jsx(w,{type:"button",variant:"chip",size:"xs","aria-pressed":a,onClick:()=>r(Je(n,l.name)),children:l.name},l.name)})}),Ze=({candidates:e,loading:s,selected:n,onChange:r})=>s?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"Loading assignees…"}):e.length===0?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No assignable users found."}):t.jsx("div",{className:"flex flex-wrap gap-1",children:e.map(l=>{const a=l.login,d=a?n.includes(a):!1;return t.jsx(w,{type:"button",variant:"chip",size:"xs","aria-pressed":d,onClick:()=>{a&&r(Je(n,a))},children:a},a)})}),Ns=({open:e,onOpenChange:s,issueNumber:n,issueTitle:r,busy:l,onChoose:a})=>{const[d,b]=u.useState("worktree"),o=We(n,r);return t.jsx(xt,{open:e,onOpenChange:s,children:t.jsxs(pt,{className:"max-w-md w-[calc(100vw-2rem)]",children:[t.jsxs(yt,{children:[t.jsxs(vt,{children:["Start session from issue #",n]}),t.jsx(Ct,{children:"Choose where the new session works. The composer is pre-filled — nothing is sent automatically."})]}),t.jsxs("div",{className:"flex flex-col gap-1",role:"radiogroup","aria-label":"Session location",children:[t.jsxs("button",{type:"button",role:"radio","aria-checked":d==="current",onClick:()=>b("current"),className:"flex items-start gap-2 rounded-md border border-border px-3 py-2 text-left hover:bg-interactive-hover",children:[t.jsx(R,{name:d==="current"?"record-circle":"checkbox-blank-circle-fill",className:"mt-0.5 size-4 shrink-0 text-muted-foreground"}),t.jsxs("span",{className:"min-w-0",children:[t.jsx("span",{className:"block typography-ui-label text-foreground",children:"Current checkout"}),t.jsx("span",{className:"block typography-micro text-muted-foreground",children:"Work directly where you are now."})]})]}),t.jsxs("button",{type:"button",role:"radio","aria-checked":d==="worktree",onClick:()=>b("worktree"),className:"flex items-start gap-2 rounded-md border border-border px-3 py-2 text-left hover:bg-interactive-hover",children:[t.jsx(R,{name:d==="worktree"?"record-circle":"checkbox-blank-circle-fill",className:"mt-0.5 size-4 shrink-0 text-muted-foreground"}),t.jsxs("span",{className:"min-w-0",children:[t.jsx("span",{className:"block typography-ui-label text-foreground",children:"New worktree"}),t.jsxs("span",{className:"block truncate font-mono typography-micro text-muted-foreground",title:o,children:["Branch ",o]})]})]})]}),t.jsxs(jt,{children:[t.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>s(!1),disabled:l,children:"Cancel"}),t.jsx(w,{type:"button",variant:"default",size:"sm",onClick:()=>a(d),disabled:l,"aria-label":d==="worktree"?"Create worktree and open session draft":"Open session draft in current checkout",children:l?"Working…":d==="worktree"?"Create worktree":"Open draft"})]})]})})},Me=e=>{const s=as(e.title);return e.kind==="pr"?`pr-${e.number}-${s}`:We(e.number,e.title)},Rs=async(e,s)=>{const{github:n,git:r,openDraft:l,refreshWorktrees:a}=s;if(!l)return{ok:!1,error:"Sessions are not available in this runtime"};let d;try{d=(await n.agentContext(e.directory,e.repo,e.kind==="pr"?"pr":"issue",e.number)).text}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Failed to load issue context"}}const o=`${e.kind==="pr"?"PR":"Issue"} #${e.number}: ${e.title.trim()||"(untitled)"}`,c=e.kind==="pr"?`Work on this GitHub pull request. Read the quoted context below, then propose a plan and wait for confirmation before changing code.
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-fmzQmSSv.js","assets/vendor-zustand-CXhN0IMY.js","assets/vendor-react-Bz1tRBxM.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js","assets/index-BaLCg7tL.css"])))=>i.map(i=>d[i]);
2
+ import{j as t}from"./vendor-boot-3SaHYVb1.js";import{R as u}from"./vendor-react-Bz1tRBxM.js";import{i as ze,j as rt,p as ot,l as lt,m as it,r as ct,b as ut,c as dt,G as mt,h as Ne,u as ht,n as ft,o as bt}from"./useGitHubRemoteSearch-MxC4J-VO.js";import{as as gt,B as w,I as R,av as xt,aw as pt,aB as yt,ax as vt,ay as Ct,aC as jt,z as Pe,h as wt,t as $,e9 as kt,o as ye,b2 as $e,a$ as Re,b0 as Le,b1 as Ee,e1 as St,e2 as Nt,bv as xe,bT as Rt,y as Lt}from"./useAppFontEffects-BFgKpDYT.js";import{bd as Et,be as Ie,bf as pe,bg as Ae,bh as ce,bi as It,bj as ue,aS as At,K as Oe,b1 as Dt,a_ as Tt,bk as Gt}from"./runtimeEndpointReset-Bby2E_Je.js";import{_ as Ht}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as Bt,d as Ft}from"./vendor-zustand-CXhN0IMY.js";import{j as _e,p as Mt}from"./index-fmzQmSSv.js";import{a as Ue,u as zt,p as Pt,r as $t,t as De,x as Ot,z as _t,A as Ut,w as ie,y as Kt,B as oe,C as Ke,D as Wt,T as qt,E as Te,G as Vt,H as Qt,I as Jt,J as Yt,K as Ge}from"./GitHubDetailScaffold-CxGg6x7R.js";import{I as Zt,a as Xt,b as es,i as We,c as ts,d as ss,s as as,g as le,e as ns,f as rs,h as He,j as Be,C as os,k as ls,v as is}from"./githubLink-CuQ2WFBa.js";import{a as cs,f as us}from"./GitHubListPrimitives-a1DxU6Zp.js";import"./vendor-clsx-B-dksMZM.js";import"./runtimeSurface-X62LLBLv.js";import"./nativeFileSave-B4Rg6n8u.js";import"./vendor-tailwind-merge-BKkUfl9q.js";import"./vendor-fuse.js-t_7AcMTv.js";import"./SessionUnreadDot-qw67HcBO.js";/* empty css */import"./permissionStore-zIpxq9Pq.js";import"./vendor-dompurify-BGCr_sdL.js";const ve={state:"open",involvement:"all",labels:"",search:"",sort:"updated"},ds=3e4,ms=100,hs=50,qe=(e,s)=>ue([e,"issues-collection",s]),Ve=(e,s)=>ue([e,"issues-remote",s.state,s.involvement,s.labels.trim(),s.q.trim()]),Ce=(e,s)=>ue([e,"issue-detail",s]),je=(e,s)=>ue([e,"issue-comments",s]),fs=e=>({state:e,perPage:ms}),bs=(e,s)=>({state:e.state,filter:e.involvement,q:e.q.trim()?e.q.trim():void 0,labels:e.labels.trim()?e.labels.trim():void 0,perPage:hs,...s?{cursor:s}:{}}),gs={set:e=>{typeof e=="function"?j.setState(s=>{const n={filtersByScope:s.filtersByScope,selectionByDirectory:s.selectionByDirectory};return e(n)}):j.setState(e)},get:()=>{const e=j.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},g=It({openCollection:"open",closedCollection:"closed",defaultFilters:ve,freshWindowMs:ds,serverKind:"issues",errorFallback:"Issue request failed",collectionKeyFor:qe,remoteKeyFor:Ve,detailKeyFor:Ce,commentsKeyFor:je,buildCollectionQuery:e=>({...fs(e)}),buildRemoteQuery:(e,s)=>({...bs(e,s)}),fetchList:async(e,s,n,r)=>{const l=await e.issuesList(s,n,r);return{items:l.items,nextCursor:l.nextCursor,fetchedAt:l.fetchedAt}},fetchDetail:async(e,s,n,r)=>e.issueGet(s,n,r),fetchComments:async(e,s,n,r,l)=>{const a=await e.issueComments(s,n,r,l);return{comments:a.comments,nextCursor:a.nextCursor,fetchedAt:a.fetchedAt}}},gs),j=Bt()(Ft((e,s)=>({...g.initialState,actionErrorByDetail:{},actingActions:{},setFilters:g.setFilters,resetFilters:g.resetFilters,selectIssue:g.select,ensureCollection:g.ensureCollection,ensureCollectionsFresh:g.ensureCollectionsFresh,prefetchClosedCollection:g.prefetchClosedCollection,loadMoreCollection:g.loadMoreCollection,refreshCollections:g.refreshCollections,searchRemote:g.searchRemote,loadMoreRemote:g.loadMoreRemote,dropRemoteForRepo:g.dropRemoteForRepo,refreshAllForScope:g.refreshAllForScope,ensureDetail:g.ensureDetail,refreshDetail:g.refreshDetail,ensureComments:g.ensureComments,loadMoreComments:g.loadMoreComments,refreshComments:g.refreshComments,updateIssue:async(n,r,l,a,d)=>{const b=Ae(r,l),o=Ce(r,l);if(s().actingActions[b])return{ok:!1,error:{kind:"failed",message:"An update is already in progress"}};e(C=>({actingActions:{...C.actingActions,[b]:!0},actionErrorByDetail:{...C.actionErrorByDetail,[b]:null}}));const c=g.resources.details.getEntry(o)?.data?.detail??null,p=c?.issue??null,v=p?{...p,title:a.title??p.title,body:a.body??p.body,state:a.state??p.state,stateReason:a.state!==void 0?a.stateReason??null:p.stateReason,labels:a.labels!==void 0?a.labels.map(C=>({name:C})):p.labels,assignees:a.assignees!==void 0?a.assignees.map(C=>({login:C})):p.assignees}:null;v&&c&&await g.resources.details.refresh(o,async()=>({detail:{...c,issue:v}})).catch(()=>null);try{return await d.issueUpdate(n,r,l,a),await pe(d,{directory:n,repo:r,kind:"issues",number:l}),s().dropRemoteForRepo(r),await s().refreshCollections(n,r,"both",d).catch(()=>null),await s().refreshDetail(n,r,l,d).catch(()=>null),e(C=>({actingActions:{...C.actingActions,[b]:!1}})),{ok:!0}}catch(C){const k=g.toStoreError(C);return c&&await g.resources.details.refresh(o,async()=>({detail:c})).catch(()=>null),e(h=>({actingActions:{...h.actingActions,[b]:!1},actionErrorByDetail:{...h.actionErrorByDetail,[b]:k}})),{ok:!1,error:k}}},addComment:async(n,r,l,a,d)=>{const b=Ae(r,l),o=je(r,l),c=a.trim(),p={id:-Date.now(),url:"",body:c,author:null,createdAt:new Date().toISOString(),updatedAt:null},v=g.resources.comments.getEntry(o)?.data??null;if(v){const C={comments:[...v.comments,p],nextCursor:v.nextCursor,fetchedAt:v.fetchedAt};await g.resources.comments.refresh(o,async()=>C).catch(()=>null)}try{return await d.issueComment(n,r,l,c),await pe(d,{directory:n,repo:r,kind:"issues",number:l}),await s().refreshComments(n,r,l,d).catch(()=>null),await s().refreshDetail(n,r,l,d).catch(()=>null),{ok:!0}}catch(C){const k=g.toStoreError(C);return v?await g.resources.comments.refresh(o,async()=>v).catch(()=>null):g.resources.comments.remove(o),e(h=>({actionErrorByDetail:{...h.actionErrorByDetail,[b]:k}})),{ok:!1,error:k}}},createIssue:async(n,r)=>{try{const l=await r.issueCreate(n.directory,n.repo,{title:n.title,body:n.body,labels:n.labels,assignees:n.assignees});return await pe(r,{directory:n.directory,repo:n.repo,kind:"issues"}),s().dropRemoteForRepo(n.repo),await s().refreshCollections(n.directory,n.repo,"both",r).catch(()=>null),{ok:!0,number:l.issue.number}}catch(l){return{ok:!1,error:g.toStoreError(l)}}},notifyAgentTurnComplete:n=>{const r=_e((n||"").trim());if(!r)return;const l=s().selectionByDirectory[r];!l?.repo||typeof l.number!="number"||(g.markCollectionsStale(l.repo),Ht(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-fmzQmSSv.js").then(d=>d.cJ);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([0,1,2,3,4,5,6,7])).then(({getRegisteredRuntimeAPIs:a})=>{const d=a()?.github??null;if(d)return s().refreshDetail(r,l.repo,l.number,d)}).catch(()=>{}))},resetForRuntimeSwitch:()=>{g.resetCore(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-issues-store"}));typeof window<"u"&&Mt(()=>{j.getState().resetForRuntimeSwitch()});const xs=e=>g.getLocalIndex(e),ps=(e,s)=>g.getLocalIndex(e).find(n=>n.number===s)??null,Fe=(e,s)=>ce(g.resources.collections,e?qe(e,s):null),ys=(e,s)=>ce(g.resources.remote,e?Ve(e,s):null),vs=(e,s)=>ce(g.resources.details,e!=null&&s!=null?Ce(e,s):null),Cs=(e,s)=>ce(g.resources.comments,e!=null&&s!=null?je(e,s):null),js=(e,s)=>j(n=>!e||!s?ve:n.filtersByScope[Et(e,s)]??ve),ws=e=>j(s=>e?s.selectionByDirectory[_e(e)]??Ie:Ie),ks=e=>typeof e!="number"||e===0?null:t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 typography-micro tabular-nums text-muted-foreground",title:`${e} comments`,"aria-label":`${e} comments`,children:[t.jsx(R,{name:"chat-1",className:"size-3.5"}),e]}),Ss=({items:e,hasMore:s,isLoadingMore:n,isLoading:r,isRefreshing:l,stale:a,error:d,filters:b,incompleteNotice:o=null,remote:c=null,numberJump:p=null,onFiltersChange:v,onClearFilters:C,onLoadMore:k,onRetry:h,onOpen:x,onNewIssue:S,headerActionsSlot:N=null,headerActionsPresentation:B="drawer"})=>{const G=b.state==="open"&&b.involvement==="all"&&!b.search.trim()&&!b.labels.trim(),{isMobile:P,isTablet:A}=gt(),I=P||A,H=N!=null,D=B??"drawer",T=H?D==="desktop"?t.jsxs(w,{type:"button",variant:"ghost",size:"sm",onClick:S,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-4"}),"New issue"]}):t.jsxs(w,{type:"button",variant:"ghost",size:"default",onClick:S,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-4"}),"New issue"]}):t.jsxs(w,{type:"button",variant:"ghost",size:I?"sm":"xs",onClick:S,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-3.5"}),"New issue"]}),O=u.useCallback(f=>t.jsx("li",{role:"listitem",children:t.jsx(ze,{glyph:t.jsx(Ue,{kind:"issue",state:f.state}),number:`#${f.number}`,title:f.title,signals:ks(f.comments),meta:t.jsxs(t.Fragment,{children:[t.jsx(rt,{login:f.author?.login,avatarUrl:f.author?.avatarUrl}),t.jsx(ot,{labels:f.labels??[]})]}),updatedAt:f.updatedAt,onOpen:()=>x(f.number),ariaLabel:`Open issue #${f.number} ${f.title}`})},f.number),[x]);return t.jsx(lt,{items:e,renderRow:O,hasMore:s,isLoadingMore:n,isLoading:r,isRefreshing:l,stale:a,error:d,searchValue:b.search,onSearchChange:f=>v({search:f}),searchPlaceholder:"Search issues, or label:bug",searchAriaLabel:"Search issues",toolbarControls:t.jsx(it,{stateValue:b.state,stateOptions:es.map(f=>({id:f.id,label:f.label})),onStateChange:f=>v({state:f}),involvementValue:b.involvement,involvementOptions:Xt.map(f=>({id:f.id,label:f.label})),onInvolvementChange:f=>v({involvement:f}),labelsValue:b.labels,onLabelsChange:f=>v({labels:f}),sortValue:b.sort,sortOptions:Zt.map(f=>({id:f.id,label:f.label})),onSortChange:f=>v({sort:f}),sortAriaLabel:"Sort issues"}),primaryAction:T,headerActionsSlot:N,headerActionsPresentation:D,isDefaultFilters:G,noItemsTitle:b.state==="open"?"No open issues":"No issues yet",noItemsBody:"Issues for this repository appear here.",noItemsIcon:"inbox-archive",noItemsAction:t.jsxs(w,{type:"button",variant:"outline",size:"sm",onClick:S,children:[t.jsx(R,{name:"add",className:"size-3.5"}),"New issue"]}),listAriaLabel:"Issues",skeletonLabel:"Loading issues",incompleteNotice:o,remote:c,numberJump:p,numberJumpKind:"issue",onClearFilters:C,onLoadMore:k,onRetry:h,onOpen:x})},Qe=(e,s,n)=>{const[r,l]=u.useState([]),[a,d]=u.useState([]),[b,o]=u.useState(!1);return u.useEffect(()=>{if(!n)return;let c=!1;return o(!0),n.repoMeta(e,s).then(p=>{c||(l(p.labels??[]),d(p.assignees??[]))}).catch(()=>{c||(l([]),d([]))}).finally(()=>{c||o(!1)}),()=>{c=!0}},[n,e,s]),{labels:r,assignees:a,loading:b}},Je=(e,s)=>e.includes(s)?e.filter(n=>n!==s):[...e,s],Ye=({candidates:e,loading:s,selected:n,onChange:r})=>s?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"Loading labels…"}):e.length===0?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No labels in this repository."}):t.jsx("div",{className:"flex flex-wrap gap-1",children:e.map(l=>{const a=n.includes(l.name);return t.jsx(w,{type:"button",variant:"chip",size:"xs","aria-pressed":a,onClick:()=>r(Je(n,l.name)),children:l.name},l.name)})}),Ze=({candidates:e,loading:s,selected:n,onChange:r})=>s?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"Loading assignees…"}):e.length===0?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No assignable users found."}):t.jsx("div",{className:"flex flex-wrap gap-1",children:e.map(l=>{const a=l.login,d=a?n.includes(a):!1;return t.jsx(w,{type:"button",variant:"chip",size:"xs","aria-pressed":d,onClick:()=>{a&&r(Je(n,a))},children:a},a)})}),Ns=({open:e,onOpenChange:s,issueNumber:n,issueTitle:r,busy:l,onChoose:a})=>{const[d,b]=u.useState("worktree"),o=We(n,r);return t.jsx(xt,{open:e,onOpenChange:s,children:t.jsxs(pt,{className:"max-w-md w-[calc(100vw-2rem)]",children:[t.jsxs(yt,{children:[t.jsxs(vt,{children:["Start session from issue #",n]}),t.jsx(Ct,{children:"Choose where the new session works. The composer is pre-filled — nothing is sent automatically."})]}),t.jsxs("div",{className:"flex flex-col gap-1",role:"radiogroup","aria-label":"Session location",children:[t.jsxs("button",{type:"button",role:"radio","aria-checked":d==="current",onClick:()=>b("current"),className:"flex items-start gap-2 rounded-md border border-border px-3 py-2 text-left hover:bg-interactive-hover",children:[t.jsx(R,{name:d==="current"?"record-circle":"checkbox-blank-circle-fill",className:"mt-0.5 size-4 shrink-0 text-muted-foreground"}),t.jsxs("span",{className:"min-w-0",children:[t.jsx("span",{className:"block typography-ui-label text-foreground",children:"Current checkout"}),t.jsx("span",{className:"block typography-micro text-muted-foreground",children:"Work directly where you are now."})]})]}),t.jsxs("button",{type:"button",role:"radio","aria-checked":d==="worktree",onClick:()=>b("worktree"),className:"flex items-start gap-2 rounded-md border border-border px-3 py-2 text-left hover:bg-interactive-hover",children:[t.jsx(R,{name:d==="worktree"?"record-circle":"checkbox-blank-circle-fill",className:"mt-0.5 size-4 shrink-0 text-muted-foreground"}),t.jsxs("span",{className:"min-w-0",children:[t.jsx("span",{className:"block typography-ui-label text-foreground",children:"New worktree"}),t.jsxs("span",{className:"block truncate font-mono typography-micro text-muted-foreground",title:o,children:["Branch ",o]})]})]})]}),t.jsxs(jt,{children:[t.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>s(!1),disabled:l,children:"Cancel"}),t.jsx(w,{type:"button",variant:"default",size:"sm",onClick:()=>a(d),disabled:l,"aria-label":d==="worktree"?"Create worktree and open session draft":"Open session draft in current checkout",children:l?"Working…":d==="worktree"?"Create worktree":"Open draft"})]})]})})},Me=e=>{const s=as(e.title);return e.kind==="pr"?`pr-${e.number}-${s}`:We(e.number,e.title)},Rs=async(e,s)=>{const{github:n,git:r,openDraft:l,refreshWorktrees:a}=s;if(!l)return{ok:!1,error:"Sessions are not available in this runtime"};let d;try{d=(await n.agentContext(e.directory,e.repo,e.kind==="pr"?"pr":"issue",e.number)).text}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Failed to load issue context"}}const o=`${e.kind==="pr"?"PR":"Issue"} #${e.number}: ${e.title.trim()||"(untitled)"}`,c=e.kind==="pr"?`Work on this GitHub pull request. Read the quoted context below, then propose a plan and wait for confirmation before changing code.
3
3
 
4
4
  PR #${e.number}: ${e.title}
5
5
  ${e.url}
6
6
 
7
- ${d}`:ts({repo:e.repo,number:e.number,title:e.title,url:e.url,contextText:d}),p=[{text:ss({kind:e.kind,number:e.number,title:e.title,url:e.url}),synthetic:!0},{text:d,synthetic:!0}];if(e.target==="current")return l({directoryOverride:e.directory,title:o,initialPrompt:c,syntheticParts:p}),{ok:!0,directory:e.directory};if(!r?.getGitBranches||!r?.createGitWorktree)return{ok:!1,error:"Worktree creation is not available in this runtime"};let v,C=!1;try{const x=await r.getGitBranches(e.directory);if(v=x.current?.trim()??"",!v)throw new Error("no current branch");C=Array.isArray(x.all)&&x.all.includes(Me(e))}catch{return{ok:!1,error:"Could not determine the current branch to start the worktree from"}}const k=Me(e);let h;try{if(C){let x=null;if(r.listGitWorktrees)try{const S=await r.listGitWorktrees(e.directory);x=Array.isArray(S)?S.find(N=>!N?.prunable&&N?.branch===k)?.path??null:null}catch{x=null}if(x)h=x;else if(h=(await r.createGitWorktree(e.directory,{mode:"existing",existingBranch:k})).path,!h)throw new Error("worktree path missing")}else if(h=(await r.createGitWorktree(e.directory,{mode:"new",startRef:v,branchName:k})).path,!h)throw new Error("worktree path missing")}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Worktree creation failed"}}return await a?.(e.directory),l({directoryOverride:h,title:o,initialPrompt:c,syntheticParts:p}),{ok:!0,directory:h}},Ls=()=>{const e=$e(),s=wt(a=>a.openNewSessionDraft),[n,r]=u.useState(null);return{start:u.useCallback(async a=>{const d=e.github;if(!d)return P.error("GitHub is not available in this runtime"),!1;const b=`${a.repo}#${a.number}:${a.target}`;r(b);try{const o=await Rs(a,{github:d,git:e.git??null,refreshWorktrees:c=>ct(c,e.git),openDraft:c=>s(c)});return o.ok?(P.success(a.target==="worktree"?"Worktree ready — session draft opened":"Session draft opened"),!0):(P.error(o.error),!1)}finally{r(null)}},[e.github,e.git,s]),startingKey:n}},Es=({issue:e})=>t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(Ke,{login:e.author?.login,avatarUrl:e.author?.avatarUrl,size:"xs"}),e.author?.login??"ghost"]}),e.createdAt?` · opened ${Ge(e.createdAt)}`:"",e.updatedAt&&e.updatedAt!==e.createdAt?` · updated ${Ge(e.updatedAt)}`:""]}),Is=({number:e,closed:s,closeReason:n,onCloseReasonChange:r,closeAllowed:l,closeReasonText:a,reopenAllowed:d,reopenReasonText:b,acting:o,onStateAction:c,askSending:p,onAskAgent:v,onEditTitle:C,editAllowed:k,editReasonText:h,onCopyLink:x,url:S})=>t.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-3 pt-1 pb-2","aria-label":"Issue actions",children:[s?t.jsx(Ne,{copy:Be("reopen",e),busy:o,variant:"outline",disabled:!d,disabledReason:b??"Reopen issue",label:"Reopen issue",icon:t.jsx(R,{name:"history",className:"size-3.5","aria-hidden":"true"}),onConfirm:()=>{c("reopen")}}):t.jsxs("span",{role:"group","aria-label":"Close issue",className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(Ne,{copy:Be(n==="not_planned"?"close-not-planned":"close-completed",e),busy:o,destructive:!0,variant:"outline",disabled:!l,disabledReason:a??"Close issue",label:"Close issue",icon:t.jsx(R,{name:"close",className:"size-3.5","aria-hidden":"true"}),onConfirm:()=>{c(n==="not_planned"?"close-not-planned":"close-completed")}}),t.jsxs(Re,{modal:!1,children:[t.jsx(Le,{asChild:!0,children:t.jsx(w,{type:"button",variant:"outline",size:"xs",className:"shrink-0 px-1.5",title:"Close options","aria-label":"Close options",disabled:!l||o,children:t.jsx(R,{name:"arrow-down-s",className:"size-3.5"})})}),t.jsx(Ee,{align:"start",className:"w-60",children:t.jsx(St,{value:n,onValueChange:N=>r(N),children:os.map(N=>t.jsx(Nt,{value:N.id,children:N.id==="completed"?"Close as completed":"Close as not planned"},N.id))})})]})]}),t.jsxs(w,{type:"button",variant:"outline",size:"xs",className:"shrink-0",onClick:v,disabled:p,title:"Send issue context to the agent composer","aria-label":"Ask agent about this issue",children:[t.jsx(R,{name:"send-plane-2",className:"size-3.5","aria-hidden":"true"}),p?"Asking…":"Ask agent"]}),t.jsxs(w,{type:"button",variant:"ghost",size:"xs",className:"shrink-0",onClick:()=>{ye(S)},title:"Open on GitHub","aria-label":"Open on GitHub",children:[t.jsx(R,{name:"external-link",className:"size-3.5","aria-hidden":"true"}),"Open on GitHub"]}),t.jsxs(Re,{modal:!1,children:[t.jsx(Le,{asChild:!0,children:t.jsx(w,{type:"button",variant:"ghost",size:"xs",className:"shrink-0 px-1.5","aria-label":"More issue actions",title:"More issue actions",children:t.jsx(R,{name:"more-2",className:"size-4"})})}),t.jsxs(Ee,{align:"end",className:"w-60",children:[t.jsxs(xe,{onClick:C,disabled:!k,title:h??"Edit title",children:[t.jsx(R,{name:"pencil",className:"size-3.5"}),"Edit title"]}),t.jsx(Rt,{}),t.jsxs(xe,{onClick:()=>{ye(S)},children:[t.jsx(R,{name:"external-link",className:"size-3.5"}),"Open on GitHub"]}),t.jsxs(xe,{onClick:x,children:[t.jsx(R,{name:"file-copy",className:"size-3.5"}),"Copy link"]})]})]})]}),As=e=>{const{directory:s,repo:n,number:r,github:l,issue:a}=e,d=j(i=>i.updateIssue),b=j(i=>i.addComment),o=j(i=>i.actionErrorByDetail[`${n}#${r}`]??null),c=j(i=>i.actingActions[`${n}#${r}`]??!1),{start:p,startingKey:v}=Ls(),C=zt(s,n),[k,h]=u.useState("completed"),[x,S]=u.useState(!1),[N,B]=u.useState(""),[G,$]=u.useState(!1),[A,I]=u.useState(""),[H,D]=u.useState(!1),[T,O]=u.useState([]),[f,M]=u.useState([]),{draft:y,onDraftChange:L,flushDraft:_}=ut(n,r),{busy:W,error:de,submit:X}=dt({postComment:i=>b(s,n,r,i,l),runFollowUp:i=>d(s,n,r,He(i==="reopen"?"reopen":k==="not_planned"?"close-not-planned":"close-completed"),l),verbs:{close:"close",reopen:"reopen"},doneLabels:{close:"Closed with comment",reopen:"Reopened with comment"},afterPost:()=>{L(""),ht.getState().clearCommentDraft(n,r)}}),[Q,me]=u.useState("newest"),[he,J]=u.useState(!1),[Y,ee]=u.useState(!1),U=u.useMemo(()=>({capabilities:e.capabilities??null,isAuthor:$t(a?.author?.login,e.viewerLogin),permissionFallback:e.viewerPermission?.fallback===!0}),[e.capabilities,e.viewerLogin,e.viewerPermission?.fallback,a?.author?.login]),F=le(a?.state==="closed"?"reopen":"close",a,U),z=le("edit",a,U),te=le("labels",a,U),se=le("comment",a,U),ae=kt(s),Z=u.useMemo(()=>{const i=new Set;for(const E of ae.scope?.repositories??[])E.host&&E.owner&&E.repo&&i.add(`${E.host}/${E.owner}/${E.repo}`.toLowerCase());return i.add(n.toLowerCase()),i},[ae.scope,n]),m=u.useCallback(i=>{Z.has(i.repoRef.toLowerCase())?At(s,i.repoRef,i.number):ye(i.url)},[s,Z]),{labels:q,assignees:Xe,loading:we}=Qe(s,n,l),ne=i=>{a&&(i==="title"?(B(a.title),S(!0)):i==="body"?(I(a.body??""),$(!0)):(O((a.labels??[]).map(E=>E.name)),M((a.assignees??[]).map(E=>E.login).filter(Boolean)),D(!0)))},fe=u.useCallback(async i=>{const E=await d(s,n,r,i,l);return E.ok?(S(!1),$(!1),D(!1),!0):(P.error(E.error?.kind==="failed"?E.error.message:"Update failed"),!1)},[d,s,n,r,l]),et=u.useCallback(async i=>{const E=He(i),ge=await d(s,n,r,E,l);return ge.ok?!0:(P.error(ge.error?.kind==="failed"?ge.error.message:"State change failed"),!1)},[d,s,n,r,l]),tt=Pt(a?.url),st=u.useCallback(async()=>{if(!(!a||Y)){ee(!0);try{const i=await l.agentContext(s,n,"issue",r);ns({kind:"issue",number:r,title:a.title,url:a.url,contextText:i.text},rs()),P.success("Added to composer")}catch(i){P.error(i instanceof Error?i.message:"Failed to fetch GitHub context")}finally{ee(!1)}}},[a,Y,l,s,n,r]),K=u.useMemo(()=>{const i=[...e.comments];return Q==="newest"&&i.reverse(),i},[e.comments,Q]),at=u.useMemo(()=>K.filter(i=>!De(i.author?.login)),[K]),nt=u.useMemo(()=>K.filter(i=>De(i.author?.login)),[K]),ke=a?.state==="closed",Se=v!==null,V=a??(e.seed&&e.seed.number===r?e.seed:null),be=t.jsxs(t.Fragment,{children:[t.jsx(Ot,{onBack:e.onBack,backLabel:"Back to issues",repoName:C,number:r,url:V?.url,numberTintClass:Ut("issue",V?.state??"open",!1,a?.stateReason),statePill:V?t.jsx(_t,{kind:"issue",state:V.state,stateReason:a?.stateReason}):void 0,openLabel:`Open issue #${r} on GitHub`,title:V?.title??null,onEditTitle:a?()=>ne("title"):void 0,editTitleLabel:"Edit issue title",editTitleDisabledReason:z.allowed?null:z.reason,meta:V?t.jsx(Es,{issue:V}):void 0,primary:a?t.jsxs(w,{type:"button",variant:"default",size:"xs",onClick:()=>J(!0),disabled:Se,"aria-label":"Start session from issue",children:[t.jsx(R,{name:"add-circle",className:"size-3.5"}),"Start session"]}):void 0}),a?t.jsx(Is,{number:r,closed:ke,closeReason:k,onCloseReasonChange:h,closeAllowed:a.state!=="closed"?F.allowed:!1,closeReasonText:a.state!=="closed"?F.reason:"Already closed",reopenAllowed:a.state==="closed"?F.allowed:!1,reopenReasonText:a.state==="closed"?F.reason:"Already open",acting:c,onStateAction:i=>et(i),askSending:Y,onAskAgent:()=>{st()},onEditTitle:()=>ne("title"),editAllowed:z.allowed,editReasonText:z.reason,onCopyLink:tt,url:a.url}):null]});if(!a&&e.detailError)return t.jsx(ie,{header:be,tabs:[],activeTab:"",onTabChange:()=>{},children:t.jsx(cs,{icon:"error-warning",title:"Could not load this issue",action:t.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:e.onRetryDetail,disabled:e.detailLoading,children:"Retry"})})});if(!a)return t.jsx(ie,{header:be,tabs:[],activeTab:"",onTabChange:()=>{},children:t.jsx(Kt,{label:"Loading issue"})});const re=ke?"reopen":"close";return t.jsxs(ie,{header:be,tabs:[],activeTab:"",onTabChange:()=>{},children:[t.jsxs("div",{className:"flex flex-col gap-1 px-3 py-2",children:[e.detailStale?t.jsxs("p",{className:"typography-micro text-muted-foreground",role:"note",children:["Showing saved issue — last refresh failed."," ",t.jsx("button",{type:"button",className:"underline",onClick:e.onRetryDetail,children:"Retry"})]}):null,o?t.jsxs("p",{className:"flex items-start gap-2 rounded-md border border-[var(--status-error-border)] bg-[var(--status-error-background)] px-3 py-2 typography-micro text-foreground",role:"alert",children:[t.jsx(R,{name:"error-warning",className:"size-4 shrink-0 text-[var(--status-error)]","aria-hidden":"true"}),t.jsx("span",{className:"min-w-0",children:o.kind==="failed"?o.message:"Action failed"})]}):null,U.permissionFallback?t.jsx("p",{className:"typography-micro text-muted-foreground",role:"note",children:"Permissions could not be loaded — actions stay enabled and any failure will be shown after you act."}):null,x?t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1 py-1",children:[t.jsx(Pe,{value:N,onChange:i=>B(i.target.value),"aria-label":"Issue title",className:"h-7"}),t.jsx(w,{type:"button",variant:"default",size:"xs",onClick:()=>{fe({title:N})},disabled:c||!N.trim(),children:"Save"}),t.jsx(w,{type:"button",variant:"ghost",size:"xs",onClick:()=>S(!1),disabled:c,children:"Cancel"})]}):null,t.jsxs("div",{className:"flex flex-col gap-1.5 py-1",children:[t.jsx(oe,{icon:"user",label:"Assignees",children:t.jsx("span",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:(a.assignees??[]).length===0?t.jsx("span",{className:"typography-micro text-muted-foreground",children:"Unassigned"}):(a.assignees??[]).map(i=>t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1 typography-micro text-muted-foreground",children:[t.jsx(Ke,{login:i.login,avatarUrl:i.avatarUrl,size:"xs"}),t.jsx("span",{className:"truncate",children:i.login})]},i.login))})}),t.jsx(oe,{icon:"list-unordered",label:"Labels",children:t.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-1",children:[(a.labels??[]).length===0?t.jsx("span",{className:"typography-micro text-muted-foreground",children:"None"}):(a.labels??[]).map(i=>t.jsx(Wt,{name:i.name,color:i.color},i.name)),t.jsx(w,{type:"button",variant:"ghost",size:"xs",onClick:()=>ne("meta"),"aria-label":"Edit labels and assignees",title:te.reason??"Edit labels and assignees",disabled:!te.allowed,children:"Edit"})]})}),a.milestone?t.jsx(oe,{icon:"time",label:"Milestone",children:t.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:a.milestone.title})}):null,t.jsx(oe,{icon:"git-pull-request",label:"Linked PRs",children:t.jsx("span",{className:"min-w-0 flex-1",children:e.linkedPullRequestsError?t.jsxs("span",{className:"flex items-center gap-2 typography-micro text-[var(--status-error)]",role:"alert",children:[t.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Linked pull requests failed to load"}),t.jsx(w,{type:"button",variant:"outline",size:"xs",onClick:e.onRetryDetail,children:"Retry"})]}):(e.linkedPullRequests??[]).length===0?t.jsx("span",{className:"typography-micro text-muted-foreground",children:"None"}):t.jsx("ul",{className:"flex min-w-0 flex-col",children:(e.linkedPullRequests??[]).map(i=>{const E=Z.has(i.repoRef.toLowerCase());return t.jsx("li",{children:t.jsx(ze,{glyph:t.jsx(Ue,{kind:"pr",state:i.state,draft:i.draft}),number:`#${i.number}`,title:i.title||"(no title)",meta:t.jsxs("span",{className:"truncate",children:[qt(i.repoRef),E?"":" · GitHub"]}),onOpen:()=>m(i),ariaLabel:`Open linked pull request #${i.number}: ${i.title}`})},`${i.repoRef}#${i.number}`)})})})}),H?t.jsxs("div",{className:"flex flex-col gap-2 py-1",children:[t.jsx("p",{className:"typography-micro font-medium text-muted-foreground",children:"Labels"}),t.jsx(Ye,{candidates:q,loading:we,selected:T,onChange:O}),t.jsx("p",{className:"typography-micro font-medium text-muted-foreground",children:"Assignees"}),t.jsx(Ze,{candidates:Xe,loading:we,selected:f,onChange:M}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(w,{type:"button",size:"sm",onClick:()=>{fe({labels:T,assignees:f})},disabled:c,children:"Save"}),t.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>D(!1),disabled:c,children:"Cancel"})]})]}):null]}),t.jsx(Te,{id:`issue-${r}-description`,title:"Description",action:G?void 0:t.jsx(w,{type:"button",variant:"ghost",size:"xs",onClick:()=>ne("body"),"aria-label":"Edit issue body",title:z.reason??"Edit issue body",disabled:!z.allowed,children:"Edit"}),children:G?t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Oe,{value:A,onChange:i=>I(i.target.value),"aria-label":"Issue body",rows:6}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(w,{type:"button",size:"sm",onClick:()=>{fe({body:A})},disabled:c,children:"Save"}),t.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>$(!1),disabled:c,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(Vt,{markdown:a.body??"",html:a.bodyHtml??null,fallbackUrl:a.url}),a.body?.trim()?null:t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No description."})]})}),t.jsx(Te,{id:`issue-${r}-comments`,title:`Comments${K.length?` (${K.length})`:""}`,action:t.jsx(Yt,{order:Q,onToggle:()=>me(i=>i==="newest"?"oldest":"newest")}),children:t.jsxs("div",{className:"flex flex-col gap-2",children:[K.length===0&&!e.commentsLoading?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No comments yet."}):at.map(i=>t.jsx(Qt,{comment:i},i.id)),t.jsx(Jt,{comments:nt}),e.commentsLoading&&K.length===0?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"Loading comments…"}):null,t.jsx(us,{hasMore:e.commentsHasMore,isLoading:e.commentsLoading,onLoadMore:e.onLoadMoreComments,label:"Load older comments"}),se.allowed?t.jsx(mt,{draft:y,onDraftChange:L,onDraftBlur:_,ariaLabel:`Leave a comment on issue #${r}`,busy:W,error:de,disabledReason:se.reason,followUp:{id:re,label:re==="close"?"Close with comment":"Reopen with comment",busyLabel:re==="close"?"Closing…":"Reopening…",onRun:()=>{X(re,y)},allowed:F.allowed,reason:F.reason},onSubmitComment:()=>{X("comment",y)}}):null]})})]}),a?t.jsx(Ns,{open:he,onOpenChange:J,issueNumber:r,issueTitle:a.title,busy:Se,onChoose:i=>{J(!1),p({directory:s,repo:n,number:r,kind:"issue",title:a.title,url:a.url,target:i})}}):null]})},Ds=({directory:e,repo:s,github:n,onCreated:r,onCancel:l})=>{const a=j(y=>y.createIssue),[d,b]=u.useState(""),[o,c]=u.useState(""),[p,v]=u.useState([]),[C,k]=u.useState([]),[h,x]=u.useState(""),[S,N]=u.useState([]),[B,G]=u.useState(null),{labels:$,assignees:A,loading:I}=Qe(e,s,n),[H,D]=u.useState(!1),[T,O]=u.useState({});u.useEffect(()=>{let y=!1;return n.issueTemplates(e,s).then(L=>{y||(N(L.templates),G(L.templates.length===0?"No markdown templates in this repository. YAML issue forms are not supported.":null))}).catch(()=>{y||G("Issue templates are unavailable.")}),()=>{y=!0}},[n,e,s]);const f=y=>{if(x(y),!y)return;const L=S.find(_=>_.filename===y);L&&c(_=>ls(_,L.body))},M=async()=>{const y=is({title:d,body:o});if(O(y.errors),!!y.ok){D(!0);try{const L=await a({directory:e,repo:s,title:d.trim(),body:o.trim()?o:void 0,labels:p.length>0?p:void 0,assignees:C.length>0?C:void 0},n);if(!L.ok||typeof L.number!="number"){P.error(L.error?.kind==="failed"?L.error.message:"Could not create the issue");return}P.success(`Issue #${L.number} created`),r(L.number)}finally{D(!1)}}};return t.jsx(ie,{header:t.jsxs("div",{className:"flex h-7 min-w-0 items-center gap-1 px-2 pt-1",children:[t.jsx(w,{type:"button",variant:"ghost",size:"icon",onClick:l,title:"Back to issues","aria-label":"Back to issues",className:"size-6 shrink-0",children:t.jsx(R,{name:"arrow-left",className:"size-4"})}),t.jsx("h1",{className:"min-w-0 flex-1 truncate text-base font-semibold text-foreground",children:"New issue"})]}),tabs:[],activeTab:"",onTabChange:()=>{},children:t.jsxs("div",{className:"flex flex-col gap-3 px-4 py-3",children:[t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{htmlFor:"new-issue-title",className:"typography-micro font-medium text-muted-foreground",children:"Title"}),t.jsx(Pe,{id:"new-issue-title",value:d,onChange:y=>b(y.target.value),placeholder:"Short summary","aria-label":"Issue title",className:"h-8",maxLength:300}),T.title?t.jsx("p",{className:"typography-micro text-[var(--status-error)]",role:"alert",children:T.title}):null]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{htmlFor:"new-issue-template",className:"typography-micro font-medium text-muted-foreground",children:"Template"}),t.jsxs("select",{id:"new-issue-template","aria-label":"Issue template",value:h,onChange:y=>f(y.target.value),className:"h-8 rounded-md border border-border bg-[var(--surface-elevated)] px-2 typography-micro text-foreground",children:[t.jsx("option",{value:"",children:"No template"}),S.map(y=>t.jsx("option",{value:y.filename,children:y.name},y.filename))]}),B?t.jsx("p",{className:"typography-micro text-muted-foreground",children:B}):null]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{htmlFor:"new-issue-body",className:"typography-micro font-medium text-muted-foreground",children:"Body"}),t.jsx(Oe,{id:"new-issue-body",value:o,onChange:y=>c(y.target.value),placeholder:"Describe the issue","aria-label":"Issue body",rows:8}),T.body?t.jsx("p",{className:"typography-micro text-[var(--status-error)]",role:"alert",children:T.body}):null]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("span",{className:"typography-micro font-medium text-muted-foreground",children:"Labels"}),t.jsx(Ye,{candidates:$,loading:I,selected:p,onChange:v})]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("span",{className:"typography-micro font-medium text-muted-foreground",children:"Assignees"}),t.jsx(Ze,{candidates:A,loading:I,selected:C,onChange:k})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(w,{type:"button",size:"sm",onClick:M,disabled:H||!d.trim(),"aria-label":"Create issue",children:H?"Creating…":"Create issue"}),t.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:H,children:"Cancel"})]})]})})},Ts=({directory:e,repo:s,isRefreshing:n,registerRefresh:r,onRefreshChange:l,headerActionsSlot:a=null,headerActionsPresentation:d="drawer"})=>{const o=$e().github??null,c=js(e,s),p=ws(e),v=Dt(),[C,k]=u.useState(!1),h=p.repo===s&&typeof p.number=="number"?p.number:null,x=c.state==="open"?"open":c.state==="all"?"both":"closed",S=u.useCallback(()=>{o&&(l(!0),j.getState().refreshAllForScope(e,s,o).catch(()=>null).finally(()=>l(!1)))},[o,e,s,l]);u.useEffect(()=>(r(S),()=>r(null)),[r,S]),u.useEffect(()=>{o&&(l(!0),j.getState().ensureCollectionsFresh(e,s,x,o).catch(()=>null).finally(()=>l(!1)))},[o,e,s,x]),u.useEffect(()=>{if(!o||h===null)return;const m=j.getState();m.ensureDetail(e,s,h,o),m.ensureComments(e,s,h,o)},[o,e,s,h]),u.useEffect(()=>{if(!o)return;const m=()=>{typeof document<"u"&&document.hidden||j.getState().ensureCollectionsFresh(e,s,x,o).catch(()=>{})};return window.addEventListener("focus",m),document.addEventListener("visibilitychange",m),()=>{window.removeEventListener("focus",m),document.removeEventListener("visibilitychange",m)}},[o,e,s,x]),u.useEffect(()=>Tt(m=>{j.getState().notifyAgentTurnComplete(m)}),[]);const N=Fe(s,"open"),B=Fe(s,"closed"),G=u.useMemo(()=>xs(s),[s,N?.data,B?.data]),$=u.useMemo(()=>new Set(G.map(m=>m.number)),[G]),A=u.useMemo(()=>Gt(G,{state:c.state,involvement:c.involvement,labels:c.labels,search:c.search,sort:c.sort,viewerLogin:v}),[G,c.state,c.involvement,c.labels,c.search,c.sort,v]),I=x==="both"?[N,B]:[x==="open"?N:B],H=I.some(m=>m?.data!=null),D=H&&I.every(m=>m?.data?.nextCursor==null),T=I.reduce((m,q)=>m+(q?.data?.items.length??0),0),O=I.find(m=>m?.error)?.error??null,f=I.some(m=>m?.stale),M=c.search.trim(),y=c.labels.trim(),L=c.involvement!=="all"&&!v||c.involvement==="mentioned",_=M.length>0||y.length>0||c.involvement!=="all",W=u.useMemo(()=>({state:c.state,involvement:c.involvement,labels:y,q:M}),[c.state,c.involvement,y,M]),de=`${W.state}|${W.involvement}|${W.labels}|${W.q}`,X=!D&&H&&(A.length===0||L)&&(M.length>0||y.length>0||L),Q=u.useCallback(m=>o?j.getState().searchRemote(e,s,m,o):Promise.resolve(null),[e,s,o]),me=u.useCallback(m=>o?j.getState().loadMoreRemote(e,s,m,o):Promise.resolve(null),[e,s,o]),{remoteView:he,numberJump:J,remotePending:Y,handleSearchAll:ee}=bt({repo:s,query:W,queryKey:de,autoRemote:X,indexNumbers:$,visibleItems:A,searchText:M,useRemoteEntry:ys,runSearch:Q,runLoadMore:me}),U=u.useMemo(()=>{if(D||!H||!_)return null;const m=A.length===1?"1 match":`${A.length} matches`,q=T===1?"1 most recent loaded issue":`${T} most recent loaded issues`;return`Showing ${m} from the ${q}`},[D,H,_,A.length,T]),F=vs(s,h),z=Cs(s,h),te=u.useCallback(()=>{!o||h===null||j.getState().loadMoreComments(e,s,h,o)},[o,e,s,h]),se=u.useCallback(()=>{j.getState().selectIssue(e,null,null)},[e]),ae=u.useCallback(()=>{!o||h===null||j.getState().refreshDetail(e,s,h,o)},[o,e,s,h]),Z=u.useCallback(()=>{!o||h===null||j.getState().refreshComments(e,s,h,o)},[o,e,s,h]);if(!o)return null;if(C)return t.jsx(Ds,{directory:e,repo:s,github:o,onCancel:()=>k(!1),onCreated:m=>{k(!1),j.getState().selectIssue(e,s,m)}});if(h!==null){const m=F?.data?.detail??null;return t.jsx(As,{directory:e,repo:s,number:h,github:o,seed:ps(s,h),issue:m?.issue??null,linkedPullRequests:m?.linkedPullRequests??[],linkedPullRequestsError:m?.sectionErrors?.linkedPullRequests??null,capabilities:m?.capabilities??null,viewerLogin:m?.viewerLogin??null,viewerPermission:m?.viewerPermission??null,detailError:F?.error??null,detailStale:F?.stale??!1,detailLoading:F?.isLoading??!1,comments:z?.data?.comments??[],commentsHasMore:!!z?.data?.nextCursor,commentsLoading:z?.isLoading??!1,onLoadMoreComments:te,onBack:se,onRetryDetail:ae,onRetryComments:Z})}return t.jsx(Ss,{items:A,headerActionsSlot:a,headerActionsPresentation:d,hasMore:I.some(m=>m?.data?.nextCursor!=null),isLoadingMore:I.some(m=>m?.isLoading),isLoading:I.some(m=>m?.isLoading),isRefreshing:n,stale:f,error:O,filters:c,incompleteNotice:U?{summary:U,searching:Y,onSearchAll:ee}:null,remote:he,numberJump:J,onFiltersChange:m=>j.getState().setFilters(e,s,m),onClearFilters:()=>j.getState().resetFilters(e,s),onLoadMore:()=>{const m=x==="both"?["open","closed"]:[x];Promise.all(m.map(q=>j.getState().loadMoreCollection(e,s,q,o)))},onRetry:()=>S(),onOpen:m=>j.getState().selectIssue(e,s,m),onNewIssue:()=>k(!0)})},ea=({headerActionsSlot:e=null,headerActionsPresentation:s="drawer"})=>{const n=Lt()??"",[r,l]=u.useState(!1),a=u.useRef(null),d=u.useCallback(o=>{a.current=o},[]),b=u.useCallback(o=>l(o),[]);return n?t.jsx(ft,{directory:n,isRefreshing:r,onRefresh:()=>a.current?.(),children:({repo:o,directory:c})=>t.jsx(Ts,{directory:c,repo:o,isRefreshing:r,registerRefresh:d,onRefreshChange:b,headerActionsSlot:e,headerActionsPresentation:s})}):t.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center",children:t.jsx("p",{className:"typography-ui text-muted-foreground",children:"Open a project to browse issues."})})};export{ea as IssuesSurface};
7
+ ${d}`:ts({repo:e.repo,number:e.number,title:e.title,url:e.url,contextText:d}),p=[{text:ss({kind:e.kind,number:e.number,title:e.title,url:e.url}),synthetic:!0},{text:d,synthetic:!0}];if(e.target==="current")return l({directoryOverride:e.directory,title:o,initialPrompt:c,syntheticParts:p}),{ok:!0,directory:e.directory};if(!r?.getGitBranches||!r?.createGitWorktree)return{ok:!1,error:"Worktree creation is not available in this runtime"};let v,C=!1;try{const x=await r.getGitBranches(e.directory);if(v=x.current?.trim()??"",!v)throw new Error("no current branch");C=Array.isArray(x.all)&&x.all.includes(Me(e))}catch{return{ok:!1,error:"Could not determine the current branch to start the worktree from"}}const k=Me(e);let h;try{if(C){let x=null;if(r.listGitWorktrees)try{const S=await r.listGitWorktrees(e.directory);x=Array.isArray(S)?S.find(N=>!N?.prunable&&N?.branch===k)?.path??null:null}catch{x=null}if(x)h=x;else if(h=(await r.createGitWorktree(e.directory,{mode:"existing",existingBranch:k})).path,!h)throw new Error("worktree path missing")}else if(h=(await r.createGitWorktree(e.directory,{mode:"new",startRef:v,branchName:k})).path,!h)throw new Error("worktree path missing")}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Worktree creation failed"}}return await a?.(e.directory),l({directoryOverride:h,title:o,initialPrompt:c,syntheticParts:p}),{ok:!0,directory:h}},Ls=()=>{const e=Pe(),s=wt(a=>a.openNewSessionDraft),[n,r]=u.useState(null);return{start:u.useCallback(async a=>{const d=e.github;if(!d)return $.error("GitHub is not available in this runtime"),!1;const b=`${a.repo}#${a.number}:${a.target}`;r(b);try{const o=await Rs(a,{github:d,git:e.git??null,refreshWorktrees:c=>ct(c,e.git),openDraft:c=>s(c)});return o.ok?($.success(a.target==="worktree"?"Worktree ready — session draft opened":"Session draft opened"),!0):($.error(o.error),!1)}finally{r(null)}},[e.github,e.git,s]),startingKey:n}},Es=({issue:e})=>t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(Ke,{login:e.author?.login,avatarUrl:e.author?.avatarUrl,size:"xs"}),e.author?.login??"ghost"]}),e.createdAt?` · opened ${Ge(e.createdAt)}`:"",e.updatedAt&&e.updatedAt!==e.createdAt?` · updated ${Ge(e.updatedAt)}`:""]}),Is=({number:e,closed:s,closeReason:n,onCloseReasonChange:r,closeAllowed:l,closeReasonText:a,reopenAllowed:d,reopenReasonText:b,acting:o,onStateAction:c,askSending:p,onAskAgent:v,onEditTitle:C,editAllowed:k,editReasonText:h,onCopyLink:x,url:S})=>t.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-3 pt-1 pb-2","aria-label":"Issue actions",children:[s?t.jsx(Ne,{copy:Be("reopen",e),busy:o,variant:"outline",disabled:!d,disabledReason:b??"Reopen issue",label:"Reopen issue",icon:t.jsx(R,{name:"history",className:"size-3.5","aria-hidden":"true"}),onConfirm:()=>{c("reopen")}}):t.jsxs("span",{role:"group","aria-label":"Close issue",className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(Ne,{copy:Be(n==="not_planned"?"close-not-planned":"close-completed",e),busy:o,destructive:!0,variant:"outline",disabled:!l,disabledReason:a??"Close issue",label:"Close issue",icon:t.jsx(R,{name:"close",className:"size-3.5","aria-hidden":"true"}),onConfirm:()=>{c(n==="not_planned"?"close-not-planned":"close-completed")}}),t.jsxs(Re,{modal:!1,children:[t.jsx(Le,{asChild:!0,children:t.jsx(w,{type:"button",variant:"outline",size:"xs",className:"shrink-0 px-1.5",title:"Close options","aria-label":"Close options",disabled:!l||o,children:t.jsx(R,{name:"arrow-down-s",className:"size-3.5"})})}),t.jsx(Ee,{align:"start",className:"w-60",children:t.jsx(St,{value:n,onValueChange:N=>r(N),children:os.map(N=>t.jsx(Nt,{value:N.id,children:N.id==="completed"?"Close as completed":"Close as not planned"},N.id))})})]})]}),t.jsxs(w,{type:"button",variant:"outline",size:"xs",className:"shrink-0",onClick:v,disabled:p,title:"Send issue context to the agent composer","aria-label":"Ask agent about this issue",children:[t.jsx(R,{name:"send-plane-2",className:"size-3.5","aria-hidden":"true"}),p?"Asking…":"Ask agent"]}),t.jsxs(w,{type:"button",variant:"ghost",size:"xs",className:"shrink-0",onClick:()=>{ye(S)},title:"Open on GitHub","aria-label":"Open on GitHub",children:[t.jsx(R,{name:"external-link",className:"size-3.5","aria-hidden":"true"}),"Open on GitHub"]}),t.jsxs(Re,{modal:!1,children:[t.jsx(Le,{asChild:!0,children:t.jsx(w,{type:"button",variant:"ghost",size:"xs",className:"shrink-0 px-1.5","aria-label":"More issue actions",title:"More issue actions",children:t.jsx(R,{name:"more-2",className:"size-4"})})}),t.jsxs(Ee,{align:"end",className:"w-60",children:[t.jsxs(xe,{onClick:C,disabled:!k,title:h??"Edit title",children:[t.jsx(R,{name:"pencil",className:"size-3.5"}),"Edit title"]}),t.jsx(Rt,{}),t.jsxs(xe,{onClick:()=>{ye(S)},children:[t.jsx(R,{name:"external-link",className:"size-3.5"}),"Open on GitHub"]}),t.jsxs(xe,{onClick:x,children:[t.jsx(R,{name:"file-copy",className:"size-3.5"}),"Copy link"]})]})]})]}),As=e=>{const{directory:s,repo:n,number:r,github:l,issue:a}=e,d=j(i=>i.updateIssue),b=j(i=>i.addComment),o=j(i=>i.actionErrorByDetail[`${n}#${r}`]??null),c=j(i=>i.actingActions[`${n}#${r}`]??!1),{start:p,startingKey:v}=Ls(),C=zt(s,n),[k,h]=u.useState("completed"),[x,S]=u.useState(!1),[N,B]=u.useState(""),[G,P]=u.useState(!1),[A,I]=u.useState(""),[H,D]=u.useState(!1),[T,O]=u.useState([]),[f,M]=u.useState([]),{draft:y,onDraftChange:L,flushDraft:_}=ut(n,r),{busy:W,error:de,submit:X}=dt({postComment:i=>b(s,n,r,i,l),runFollowUp:i=>d(s,n,r,He(i==="reopen"?"reopen":k==="not_planned"?"close-not-planned":"close-completed"),l),verbs:{close:"close",reopen:"reopen"},doneLabels:{close:"Closed with comment",reopen:"Reopened with comment"},afterPost:()=>{L(""),ht.getState().clearCommentDraft(n,r)}}),[Q,me]=u.useState("newest"),[he,J]=u.useState(!1),[Y,ee]=u.useState(!1),U=u.useMemo(()=>({capabilities:e.capabilities??null,isAuthor:Pt(a?.author?.login,e.viewerLogin),permissionFallback:e.viewerPermission?.fallback===!0}),[e.capabilities,e.viewerLogin,e.viewerPermission?.fallback,a?.author?.login]),F=le(a?.state==="closed"?"reopen":"close",a,U),z=le("edit",a,U),te=le("labels",a,U),se=le("comment",a,U),ae=kt(s),Z=u.useMemo(()=>{const i=new Set;for(const E of ae.scope?.repositories??[])E.host&&E.owner&&E.repo&&i.add(`${E.host}/${E.owner}/${E.repo}`.toLowerCase());return i.add(n.toLowerCase()),i},[ae.scope,n]),m=u.useCallback(i=>{Z.has(i.repoRef.toLowerCase())?At(s,i.repoRef,i.number):ye(i.url)},[s,Z]),{labels:q,assignees:Xe,loading:we}=Qe(s,n,l),ne=i=>{a&&(i==="title"?(B(a.title),S(!0)):i==="body"?(I(a.body??""),P(!0)):(O((a.labels??[]).map(E=>E.name)),M((a.assignees??[]).map(E=>E.login).filter(Boolean)),D(!0)))},fe=u.useCallback(async i=>{const E=await d(s,n,r,i,l);return E.ok?(S(!1),P(!1),D(!1),!0):($.error(E.error?.kind==="failed"?E.error.message:"Update failed"),!1)},[d,s,n,r,l]),et=u.useCallback(async i=>{const E=He(i),ge=await d(s,n,r,E,l);return ge.ok?!0:($.error(ge.error?.kind==="failed"?ge.error.message:"State change failed"),!1)},[d,s,n,r,l]),tt=$t(a?.url),st=u.useCallback(async()=>{if(!(!a||Y)){ee(!0);try{const i=await l.agentContext(s,n,"issue",r);ns({kind:"issue",number:r,title:a.title,url:a.url,contextText:i.text},rs()),$.success("Added to composer")}catch(i){$.error(i instanceof Error?i.message:"Failed to fetch GitHub context")}finally{ee(!1)}}},[a,Y,l,s,n,r]),K=u.useMemo(()=>{const i=[...e.comments];return Q==="newest"&&i.reverse(),i},[e.comments,Q]),at=u.useMemo(()=>K.filter(i=>!De(i.author?.login)),[K]),nt=u.useMemo(()=>K.filter(i=>De(i.author?.login)),[K]),ke=a?.state==="closed",Se=v!==null,V=a??(e.seed&&e.seed.number===r?e.seed:null),be=t.jsxs(t.Fragment,{children:[t.jsx(Ot,{onBack:e.onBack,backLabel:"Back to issues",repoName:C,number:r,url:V?.url,numberTintClass:Ut("issue",V?.state??"open",!1,a?.stateReason),statePill:V?t.jsx(_t,{kind:"issue",state:V.state,stateReason:a?.stateReason}):void 0,openLabel:`Open issue #${r} on GitHub`,title:V?.title??null,onEditTitle:a?()=>ne("title"):void 0,editTitleLabel:"Edit issue title",editTitleDisabledReason:z.allowed?null:z.reason,meta:V?t.jsx(Es,{issue:V}):void 0,primary:a?t.jsxs(w,{type:"button",variant:"default",size:"xs",onClick:()=>J(!0),disabled:Se,"aria-label":"Start session from issue",children:[t.jsx(R,{name:"add-circle",className:"size-3.5"}),"Start session"]}):void 0}),a?t.jsx(Is,{number:r,closed:ke,closeReason:k,onCloseReasonChange:h,closeAllowed:a.state!=="closed"?F.allowed:!1,closeReasonText:a.state!=="closed"?F.reason:"Already closed",reopenAllowed:a.state==="closed"?F.allowed:!1,reopenReasonText:a.state==="closed"?F.reason:"Already open",acting:c,onStateAction:i=>et(i),askSending:Y,onAskAgent:()=>{st()},onEditTitle:()=>ne("title"),editAllowed:z.allowed,editReasonText:z.reason,onCopyLink:tt,url:a.url}):null]});if(!a&&e.detailError)return t.jsx(ie,{header:be,tabs:[],activeTab:"",onTabChange:()=>{},children:t.jsx(cs,{icon:"error-warning",title:"Could not load this issue",action:t.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:e.onRetryDetail,disabled:e.detailLoading,children:"Retry"})})});if(!a)return t.jsx(ie,{header:be,tabs:[],activeTab:"",onTabChange:()=>{},children:t.jsx(Kt,{label:"Loading issue"})});const re=ke?"reopen":"close";return t.jsxs(ie,{header:be,tabs:[],activeTab:"",onTabChange:()=>{},children:[t.jsxs("div",{className:"flex flex-col gap-1 px-3 py-2",children:[e.detailStale?t.jsxs("p",{className:"typography-micro text-muted-foreground",role:"note",children:["Showing saved issue — last refresh failed."," ",t.jsx("button",{type:"button",className:"underline",onClick:e.onRetryDetail,children:"Retry"})]}):null,o?t.jsxs("p",{className:"flex items-start gap-2 rounded-md border border-[var(--status-error-border)] bg-[var(--status-error-background)] px-3 py-2 typography-micro text-foreground",role:"alert",children:[t.jsx(R,{name:"error-warning",className:"size-4 shrink-0 text-[var(--status-error)]","aria-hidden":"true"}),t.jsx("span",{className:"min-w-0",children:o.kind==="failed"?o.message:"Action failed"})]}):null,U.permissionFallback?t.jsx("p",{className:"typography-micro text-muted-foreground",role:"note",children:"Permissions could not be loaded — actions stay enabled and any failure will be shown after you act."}):null,x?t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1 py-1",children:[t.jsx($e,{value:N,onChange:i=>B(i.target.value),"aria-label":"Issue title",className:"h-7"}),t.jsx(w,{type:"button",variant:"default",size:"xs",onClick:()=>{fe({title:N})},disabled:c||!N.trim(),children:"Save"}),t.jsx(w,{type:"button",variant:"ghost",size:"xs",onClick:()=>S(!1),disabled:c,children:"Cancel"})]}):null,t.jsxs("div",{className:"flex flex-col gap-1.5 py-1",children:[t.jsx(oe,{icon:"user",label:"Assignees",children:t.jsx("span",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:(a.assignees??[]).length===0?t.jsx("span",{className:"typography-micro text-muted-foreground",children:"Unassigned"}):(a.assignees??[]).map(i=>t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1 typography-micro text-muted-foreground",children:[t.jsx(Ke,{login:i.login,avatarUrl:i.avatarUrl,size:"xs"}),t.jsx("span",{className:"truncate",children:i.login})]},i.login))})}),t.jsx(oe,{icon:"list-unordered",label:"Labels",children:t.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-1",children:[(a.labels??[]).length===0?t.jsx("span",{className:"typography-micro text-muted-foreground",children:"None"}):(a.labels??[]).map(i=>t.jsx(Wt,{name:i.name,color:i.color},i.name)),t.jsx(w,{type:"button",variant:"ghost",size:"xs",onClick:()=>ne("meta"),"aria-label":"Edit labels and assignees",title:te.reason??"Edit labels and assignees",disabled:!te.allowed,children:"Edit"})]})}),a.milestone?t.jsx(oe,{icon:"time",label:"Milestone",children:t.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:a.milestone.title})}):null,t.jsx(oe,{icon:"git-pull-request",label:"Linked PRs",children:t.jsx("span",{className:"min-w-0 flex-1",children:e.linkedPullRequestsError?t.jsxs("span",{className:"flex items-center gap-2 typography-micro text-[var(--status-error)]",role:"alert",children:[t.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Linked pull requests failed to load"}),t.jsx(w,{type:"button",variant:"outline",size:"xs",onClick:e.onRetryDetail,children:"Retry"})]}):(e.linkedPullRequests??[]).length===0?t.jsx("span",{className:"typography-micro text-muted-foreground",children:"None"}):t.jsx("ul",{className:"flex min-w-0 flex-col",children:(e.linkedPullRequests??[]).map(i=>{const E=Z.has(i.repoRef.toLowerCase());return t.jsx("li",{children:t.jsx(ze,{glyph:t.jsx(Ue,{kind:"pr",state:i.state,draft:i.draft}),number:`#${i.number}`,title:i.title||"(no title)",meta:t.jsxs("span",{className:"truncate",children:[qt(i.repoRef),E?"":" · GitHub"]}),onOpen:()=>m(i),ariaLabel:`Open linked pull request #${i.number}: ${i.title}`})},`${i.repoRef}#${i.number}`)})})})}),H?t.jsxs("div",{className:"flex flex-col gap-2 py-1",children:[t.jsx("p",{className:"typography-micro font-medium text-muted-foreground",children:"Labels"}),t.jsx(Ye,{candidates:q,loading:we,selected:T,onChange:O}),t.jsx("p",{className:"typography-micro font-medium text-muted-foreground",children:"Assignees"}),t.jsx(Ze,{candidates:Xe,loading:we,selected:f,onChange:M}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(w,{type:"button",size:"sm",onClick:()=>{fe({labels:T,assignees:f})},disabled:c,children:"Save"}),t.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>D(!1),disabled:c,children:"Cancel"})]})]}):null]}),t.jsx(Te,{id:`issue-${r}-description`,title:"Description",action:G?void 0:t.jsx(w,{type:"button",variant:"ghost",size:"xs",onClick:()=>ne("body"),"aria-label":"Edit issue body",title:z.reason??"Edit issue body",disabled:!z.allowed,children:"Edit"}),children:G?t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Oe,{value:A,onChange:i=>I(i.target.value),"aria-label":"Issue body",rows:6}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(w,{type:"button",size:"sm",onClick:()=>{fe({body:A})},disabled:c,children:"Save"}),t.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>P(!1),disabled:c,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(Vt,{markdown:a.body??"",html:a.bodyHtml??null,fallbackUrl:a.url}),a.body?.trim()?null:t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No description."})]})}),t.jsx(Te,{id:`issue-${r}-comments`,title:`Comments${K.length?` (${K.length})`:""}`,action:t.jsx(Yt,{order:Q,onToggle:()=>me(i=>i==="newest"?"oldest":"newest")}),children:t.jsxs("div",{className:"flex flex-col gap-2",children:[K.length===0&&!e.commentsLoading?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No comments yet."}):at.map(i=>t.jsx(Qt,{comment:i},i.id)),t.jsx(Jt,{comments:nt}),e.commentsLoading&&K.length===0?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"Loading comments…"}):null,t.jsx(us,{hasMore:e.commentsHasMore,isLoading:e.commentsLoading,onLoadMore:e.onLoadMoreComments,label:"Load older comments"}),se.allowed?t.jsx(mt,{draft:y,onDraftChange:L,onDraftBlur:_,ariaLabel:`Leave a comment on issue #${r}`,busy:W,error:de,disabledReason:se.reason,followUp:{id:re,label:re==="close"?"Close with comment":"Reopen with comment",busyLabel:re==="close"?"Closing…":"Reopening…",onRun:()=>{X(re,y)},allowed:F.allowed,reason:F.reason},onSubmitComment:()=>{X("comment",y)}}):null]})})]}),a?t.jsx(Ns,{open:he,onOpenChange:J,issueNumber:r,issueTitle:a.title,busy:Se,onChoose:i=>{J(!1),p({directory:s,repo:n,number:r,kind:"issue",title:a.title,url:a.url,target:i})}}):null]})},Ds=({directory:e,repo:s,github:n,onCreated:r,onCancel:l})=>{const a=j(y=>y.createIssue),[d,b]=u.useState(""),[o,c]=u.useState(""),[p,v]=u.useState([]),[C,k]=u.useState([]),[h,x]=u.useState(""),[S,N]=u.useState([]),[B,G]=u.useState(null),{labels:P,assignees:A,loading:I}=Qe(e,s,n),[H,D]=u.useState(!1),[T,O]=u.useState({});u.useEffect(()=>{let y=!1;return n.issueTemplates(e,s).then(L=>{y||(N(L.templates),G(L.templates.length===0?"No markdown templates in this repository. YAML issue forms are not supported.":null))}).catch(()=>{y||G("Issue templates are unavailable.")}),()=>{y=!0}},[n,e,s]);const f=y=>{if(x(y),!y)return;const L=S.find(_=>_.filename===y);L&&c(_=>ls(_,L.body))},M=async()=>{const y=is({title:d,body:o});if(O(y.errors),!!y.ok){D(!0);try{const L=await a({directory:e,repo:s,title:d.trim(),body:o.trim()?o:void 0,labels:p.length>0?p:void 0,assignees:C.length>0?C:void 0},n);if(!L.ok||typeof L.number!="number"){$.error(L.error?.kind==="failed"?L.error.message:"Could not create the issue");return}$.success(`Issue #${L.number} created`),r(L.number)}finally{D(!1)}}};return t.jsx(ie,{header:t.jsxs("div",{className:"flex h-7 min-w-0 items-center gap-1 px-2 pt-1",children:[t.jsx(w,{type:"button",variant:"ghost",size:"icon",onClick:l,title:"Back to issues","aria-label":"Back to issues",className:"size-6 shrink-0",children:t.jsx(R,{name:"arrow-left",className:"size-4"})}),t.jsx("h1",{className:"min-w-0 flex-1 truncate text-base font-semibold text-foreground",children:"New issue"})]}),tabs:[],activeTab:"",onTabChange:()=>{},children:t.jsxs("div",{className:"flex flex-col gap-3 px-4 py-3",children:[t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{htmlFor:"new-issue-title",className:"typography-micro font-medium text-muted-foreground",children:"Title"}),t.jsx($e,{id:"new-issue-title",value:d,onChange:y=>b(y.target.value),placeholder:"Short summary","aria-label":"Issue title",className:"h-8",maxLength:300}),T.title?t.jsx("p",{className:"typography-micro text-[var(--status-error)]",role:"alert",children:T.title}):null]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{htmlFor:"new-issue-template",className:"typography-micro font-medium text-muted-foreground",children:"Template"}),t.jsxs("select",{id:"new-issue-template","aria-label":"Issue template",value:h,onChange:y=>f(y.target.value),className:"h-8 rounded-md border border-border bg-[var(--surface-elevated)] px-2 typography-micro text-foreground",children:[t.jsx("option",{value:"",children:"No template"}),S.map(y=>t.jsx("option",{value:y.filename,children:y.name},y.filename))]}),B?t.jsx("p",{className:"typography-micro text-muted-foreground",children:B}):null]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{htmlFor:"new-issue-body",className:"typography-micro font-medium text-muted-foreground",children:"Body"}),t.jsx(Oe,{id:"new-issue-body",value:o,onChange:y=>c(y.target.value),placeholder:"Describe the issue","aria-label":"Issue body",rows:8}),T.body?t.jsx("p",{className:"typography-micro text-[var(--status-error)]",role:"alert",children:T.body}):null]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("span",{className:"typography-micro font-medium text-muted-foreground",children:"Labels"}),t.jsx(Ye,{candidates:P,loading:I,selected:p,onChange:v})]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("span",{className:"typography-micro font-medium text-muted-foreground",children:"Assignees"}),t.jsx(Ze,{candidates:A,loading:I,selected:C,onChange:k})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(w,{type:"button",size:"sm",onClick:M,disabled:H||!d.trim(),"aria-label":"Create issue",children:H?"Creating…":"Create issue"}),t.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:H,children:"Cancel"})]})]})})},Ts=({directory:e,repo:s,isRefreshing:n,registerRefresh:r,onRefreshChange:l,headerActionsSlot:a=null,headerActionsPresentation:d="drawer"})=>{const o=Pe().github??null,c=js(e,s),p=ws(e),v=Dt(),[C,k]=u.useState(!1),h=p.repo===s&&typeof p.number=="number"?p.number:null,x=c.state==="open"?"open":c.state==="all"?"both":"closed",S=u.useCallback(()=>{o&&(l(!0),j.getState().refreshAllForScope(e,s,o).catch(()=>null).finally(()=>l(!1)))},[o,e,s,l]);u.useEffect(()=>(r(S),()=>r(null)),[r,S]),u.useEffect(()=>{o&&(l(!0),j.getState().ensureCollectionsFresh(e,s,x,o).catch(()=>null).finally(()=>l(!1)))},[o,e,s,x]),u.useEffect(()=>{if(!o||h===null)return;const m=j.getState();m.ensureDetail(e,s,h,o),m.ensureComments(e,s,h,o)},[o,e,s,h]),u.useEffect(()=>{if(!o)return;const m=()=>{typeof document<"u"&&document.hidden||j.getState().ensureCollectionsFresh(e,s,x,o).catch(()=>{})};return window.addEventListener("focus",m),document.addEventListener("visibilitychange",m),()=>{window.removeEventListener("focus",m),document.removeEventListener("visibilitychange",m)}},[o,e,s,x]),u.useEffect(()=>Tt(m=>{j.getState().notifyAgentTurnComplete(m)}),[]);const N=Fe(s,"open"),B=Fe(s,"closed"),G=u.useMemo(()=>xs(s),[s,N?.data,B?.data]),P=u.useMemo(()=>new Set(G.map(m=>m.number)),[G]),A=u.useMemo(()=>Gt(G,{state:c.state,involvement:c.involvement,labels:c.labels,search:c.search,sort:c.sort,viewerLogin:v}),[G,c.state,c.involvement,c.labels,c.search,c.sort,v]),I=x==="both"?[N,B]:[x==="open"?N:B],H=I.some(m=>m?.data!=null),D=H&&I.every(m=>m?.data?.nextCursor==null),T=I.reduce((m,q)=>m+(q?.data?.items.length??0),0),O=I.find(m=>m?.error)?.error??null,f=I.some(m=>m?.stale),M=c.search.trim(),y=c.labels.trim(),L=c.involvement!=="all"&&!v||c.involvement==="mentioned",_=M.length>0||y.length>0||c.involvement!=="all",W=u.useMemo(()=>({state:c.state,involvement:c.involvement,labels:y,q:M}),[c.state,c.involvement,y,M]),de=`${W.state}|${W.involvement}|${W.labels}|${W.q}`,X=!D&&H&&(A.length===0||L)&&(M.length>0||y.length>0||L),Q=u.useCallback(m=>o?j.getState().searchRemote(e,s,m,o):Promise.resolve(null),[e,s,o]),me=u.useCallback(m=>o?j.getState().loadMoreRemote(e,s,m,o):Promise.resolve(null),[e,s,o]),{remoteView:he,numberJump:J,remotePending:Y,handleSearchAll:ee}=bt({repo:s,query:W,queryKey:de,autoRemote:X,indexNumbers:P,visibleItems:A,searchText:M,useRemoteEntry:ys,runSearch:Q,runLoadMore:me}),U=u.useMemo(()=>{if(D||!H||!_)return null;const m=A.length===1?"1 match":`${A.length} matches`,q=T===1?"1 most recent loaded issue":`${T} most recent loaded issues`;return`Showing ${m} from the ${q}`},[D,H,_,A.length,T]),F=vs(s,h),z=Cs(s,h),te=u.useCallback(()=>{!o||h===null||j.getState().loadMoreComments(e,s,h,o)},[o,e,s,h]),se=u.useCallback(()=>{j.getState().selectIssue(e,null,null)},[e]),ae=u.useCallback(()=>{!o||h===null||j.getState().refreshDetail(e,s,h,o)},[o,e,s,h]),Z=u.useCallback(()=>{!o||h===null||j.getState().refreshComments(e,s,h,o)},[o,e,s,h]);if(!o)return null;if(C)return t.jsx(Ds,{directory:e,repo:s,github:o,onCancel:()=>k(!1),onCreated:m=>{k(!1),j.getState().selectIssue(e,s,m)}});if(h!==null){const m=F?.data?.detail??null;return t.jsx(As,{directory:e,repo:s,number:h,github:o,seed:ps(s,h),issue:m?.issue??null,linkedPullRequests:m?.linkedPullRequests??[],linkedPullRequestsError:m?.sectionErrors?.linkedPullRequests??null,capabilities:m?.capabilities??null,viewerLogin:m?.viewerLogin??null,viewerPermission:m?.viewerPermission??null,detailError:F?.error??null,detailStale:F?.stale??!1,detailLoading:F?.isLoading??!1,comments:z?.data?.comments??[],commentsHasMore:!!z?.data?.nextCursor,commentsLoading:z?.isLoading??!1,onLoadMoreComments:te,onBack:se,onRetryDetail:ae,onRetryComments:Z})}return t.jsx(Ss,{items:A,headerActionsSlot:a,headerActionsPresentation:d,hasMore:I.some(m=>m?.data?.nextCursor!=null),isLoadingMore:I.some(m=>m?.isLoading),isLoading:I.some(m=>m?.isLoading),isRefreshing:n,stale:f,error:O,filters:c,incompleteNotice:U?{summary:U,searching:Y,onSearchAll:ee}:null,remote:he,numberJump:J,onFiltersChange:m=>j.getState().setFilters(e,s,m),onClearFilters:()=>j.getState().resetFilters(e,s),onLoadMore:()=>{const m=x==="both"?["open","closed"]:[x];Promise.all(m.map(q=>j.getState().loadMoreCollection(e,s,q,o)))},onRetry:()=>S(),onOpen:m=>j.getState().selectIssue(e,s,m),onNewIssue:()=>k(!0)})},ea=({headerActionsSlot:e=null,headerActionsPresentation:s="drawer"})=>{const n=Lt()??"",[r,l]=u.useState(!1),a=u.useRef(null),d=u.useCallback(o=>{a.current=o},[]),b=u.useCallback(o=>l(o),[]);return n?t.jsx(ft,{directory:n,isRefreshing:r,onRefresh:()=>a.current?.(),children:({repo:o,directory:c})=>t.jsx(Ts,{directory:c,repo:o,isRefreshing:r,registerRefresh:d,onRefreshChange:b,headerActionsSlot:e,headerActionsPresentation:s})}):t.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center",children:t.jsx("p",{className:"typography-ui text-muted-foreground",children:"Open a project to browse issues."})})};export{ea as IssuesSurface};
@@ -1 +1 @@
1
- import{dj as H,dM as Z,dN as Fe,dO as Ce,dP as ke,dQ as Ie,dR as ze,dk as Ne,dS as Oe,B as ee,I as te,dT as Pe}from"./useAppFontEffects-Oyin3dgQ.js";import{a as ie,s as Ve,b as Se,c as ne,d as ve,g as Be,e as re,f as I,h as De,i as Ue,j as _e,k as We,R as Ge,I as je,p as se,l as $e,m as qe,n as Ke,o as Je,w as Ye,q as ae,u as Xe,r as Qe,t as Ze,v as et,x as oe,S as tt,y as it,z as nt,A as rt,B as ye,C as he,F as st}from"./web-components-CkTNGkJ2.js";import{G as at,u as ot,W as ht,a as lt,b as dt,n as le,t as ct}from"./Virtualizer-okhy9Aq3.js";import{j as C}from"./vendor-boot-3SaHYVb1.js";import{o as ut,i as j,f as M,a as ft,q as de,s as pt,t as ce,d as gt,u as ue,b as mt,w as B,x as fe}from"./computeVirtualFileMetrics-8MuwxSC6.js";import{a as F,i as K,l as pe,h as Ct,r as St}from"./renderFileWithHighlighter-DtAcGyJr.js";import{t as A}from"./vendor-hast-util-to-html-O3stl53j.js";import{a as k,R as L}from"./vendor-react-Bz1tRBxM.js";let vt=-1;var yt=class{options;onRenderUpdate;workerManager;__id=`file-renderer:${++vt}`;highlighter;renderCache;computedLang="text";lineAnnotations={};lineCache;textDoucmentCache=new WeakMap;constructor(i={theme:H},e,t){this.options=i,this.onRenderUpdate=e,this.workerManager=t,t?.isWorkingPool()!==!0&&(this.highlighter=ie(i.theme??H)?ut():void 0)}setOptions(i){this.options=i}mergeOptions(i){this.options={...this.options,...i}}setLineAnnotations(i){this.lineAnnotations={};for(const e of i){const t=this.lineAnnotations[e.lineNumber]??[];this.lineAnnotations[e.lineNumber]=t,t.push(e)}}cleanUp(){this.recycle(),this.workerManager=void 0,this.onRenderUpdate=void 0}recycle(){this.clearRenderCache(),this.highlighter=void 0,this.workerManager?.cleanUpTasks(this),this.lineCache=void 0}clearRenderCache(){const i=this.renderCache;this.renderCache=void 0,i!=null&&i.isDirty===!0&&i.file.cacheKey!=null&&this.workerManager?.evictFileFromCache(i.file.cacheKey)}hydrate(i){const{options:e}=this.getRenderOptions(i),t=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());let n=this.workerManager?.getFileResultCache(i);n!=null&&!F(e,n.options)&&(n=void 0),this.renderCache??={file:i,options:e,highlighted:!t&&!K(i),result:t?void 0:n?.result,renderRange:void 0},this.workerManager?.isWorkingPool()===!0?this.renderCache.result==null&&!t&&this.workerManager.highlightFileAST(this,i):this.highlighter==null&&(this.computedLang=i.lang??j(i.name),this.initializeHighlighter())}getRenderOptions(i){const e=(()=>{if(this.workerManager?.isWorkingPool()===!0)return this.workerManager.getFileRenderOptions();const{theme:n=H,tokenizeMaxLineLength:r=1e3}=this.options;return{theme:n,useTokenTransformer:Ve(this.options),tokenizeMaxLineLength:r}})(),{renderCache:t}=this;return t?.result==null?{options:e,forceHighlight:!0}:!M(i,t.file)||!F(e,t.options)?{options:e,forceHighlight:!0}:{options:e,forceHighlight:!1}}getOrCreateLineCache(i){if(i.cacheKey==null)return this.lineCache=void 0,pe(i.contents);let{lineCache:e}=this;return(e==null||e.cacheKey!==i.cacheKey)&&(e={cacheKey:i.cacheKey,lines:pe(i.contents)}),this.lineCache=e,e.lines}getLineCount(i){return this.textDoucmentCache.get(i)?.lineCount??this.getOrCreateLineCache(i).length}updateRenderCache(i,e){if(this.renderCache==null)return;const{result:t}=this.renderCache;if(t!=null){for(const[n,r]of i)t.code[n]={type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:r.map(([s,a,o])=>s===0&&a===""?o===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:o}:{type:"element",tagName:"span",properties:{"data-char":s,style:`--diffs-token-${e}:${a};`},children:[{type:"text",value:o}]})};t.baseThemeType=e,this.renderCache.isDirty=!0}}applyDocumentChange(i){if(this.renderCache==null)return;const{file:e,result:t}=this.renderCache;if(t!=null&&t.code.length!==i.lineCount){t.code.length=Math.min(t.code.length,i.lineCount);for(let n=t.code.length;n<i.lineCount;n++)t.code.push({type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:[{type:"element",tagName:"span",properties:{"data-char":0},children:[{type:"text",value:i.getLineText(n)}]}]});this.renderCache.isDirty=!0}this.textDoucmentCache.set(e,i)}renderFile(i=this.renderCache?.file,e=Z){if(i==null)return;let{options:t,forceHighlight:n}=this.getRenderOptions(i);const r=this.getMatchingWorkerResultCache(i,t);r!=null&&!this.hasHighlightedRenderCache(i,t)&&(this.renderCache={file:i,highlighted:!0,renderRange:void 0,...r},n=!1),this.renderCache??={file:i,highlighted:!1,options:t,result:void 0,renderRange:void 0};const s=this.getOrCreateLineCache(i),a=i.contents.length>0,o=!a||K(i)||$(s.length,this.getTokenizeMaxLength()),h=!M(i,this.renderCache.file),d=!Se(this.renderCache.renderRange,e);if(this.workerManager?.isWorkingPool()===!0)(o||this.renderCache.result==null||!this.renderCache.highlighted&&(h||d))&&(this.renderCache.file=i,this.renderCache.options=t,this.renderCache.highlighted=!1,(this.renderCache.result==null||h||d||n)&&(this.renderCache.result=this.workerManager.getPlainFileAST(i,e.startingLine,e.totalLines,s)),this.renderCache.renderRange=e),!o&&a&&(!this.renderCache.highlighted||n)&&this.workerManager.highlightFileAST(this,i);else{this.computedLang=i.lang??j(i.name);const l=this.highlighter!=null&&ie(t.theme),c=this.highlighter!=null&&ne(this.computedLang),u=!o&&c;if(this.highlighter!=null&&l&&(n||o||!this.renderCache.highlighted&&u||this.renderCache.result==null)){const{result:p,options:f}=this.renderFileWithHighlighter(i,this.highlighter,o||!c);this.renderCache={file:i,options:f,highlighted:u,result:p,renderRange:void 0}}(!l||!o&&!c)&&this.asyncHighlight(i).then(({result:p,options:f})=>{this.renderCache!=null&&(this.renderCache.highlighted=!1),this.onHighlightSuccess(i,p,f,!o)})}return this.renderCache.result!=null?this.processFileResult(this.renderCache.file,e,this.renderCache.result):void 0}async asyncRender(i,e=Z){const{result:t}=await this.asyncHighlight(i);return this.processFileResult(i,e,t)}async asyncHighlight(i){const e=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());this.computedLang=e?"text":i.lang??j(i.name);const t=this.highlighter!=null&&Ct(ft(this.options.theme)),n=e||this.highlighter!=null&&ne(this.computedLang);return(this.highlighter==null||!t||!n)&&(this.highlighter=await this.initializeHighlighter()),this.renderFileWithHighlighter(i,this.highlighter,e)}renderFileWithHighlighter(i,e,t=!1){const{options:n}=this.getRenderOptions(i);return{result:St(i,e,n,{forcePlainText:t}),options:n}}processFileResult(i,e,{code:t,themeStyles:n,baseThemeType:r}){const s=this.getLineCount(i),{disableFileHeader:a=!1}=this.options,o=[],h=ue(),d=Math.min(e.startingLine+e.totalLines,s);let l=0;const c=ve(e)?Be(this.lineAnnotations):void 0;c!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:-1,lineIndex:-1,annotations:c.map(u=>I(u))})),l++);for(let u=e.startingLine;u<d;u++){const p=u+1,f=t[u];if(f==null){const g="FileRenderer.processFileResult: Line doesnt exist";throw console.error(g,{name:i.name,lineIndex:u,lineNumber:p}),new Error(g)}h.children.push(pt("context",p,`${u}`)),o.push(f),l++;const S=this.lineAnnotations[p];S!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:0,lineIndex:p,annotations:S.map(g=>I(g))})),l++)}return h.properties.style=`grid-row: span ${l}`,{gutterAST:h.children??[],contentAST:o,preAST:this.createPreElement(s),headerAST:a?void 0:this.renderHeader(i),totalLines:s,rowCount:l,themeStyles:n,baseThemeType:r,bufferBefore:e.bufferBefore,bufferAfter:e.bufferAfter,css:""}}renderHeader(i){const{headerRenderMode:e="default",stickyHeader:t=!1}=this.options;return De({fileOrDiff:i,mode:e,stickyHeader:t})}renderFullHTML(i){return A(this.renderFullAST(i))}renderFullAST(i,e=[]){return e.push(ce({tagName:"code",children:this.renderCodeAST(i),properties:{"data-code":""}})),{...i.preAST,children:e}}renderCodeAST(i){const e=ue();return e.children=i.gutterAST,e.properties.style=`grid-row: span ${i.rowCount}`,[e,Ue(i.contentAST,i.rowCount)]}renderPartialHTML(i,e=!1){return e?A(ce({tagName:"code",children:i,properties:{"data-code":""}})):A(i)}async initializeHighlighter(){return this.highlighter=await gt(_e(this.computedLang,this.options)),this.highlighter}onHighlightSuccess(i,e,t,n=!0){if(this.renderCache==null)return;const r=!M(i,this.renderCache.file)||!this.renderCache.highlighted||!F(t,this.renderCache.options);this.renderCache={file:i,options:t,highlighted:n,result:e,renderRange:void 0},r&&this.onRenderUpdate?.()}getMatchingWorkerResultCache(i,e){const t=this.workerManager?.getFileResultCache(i);if(!(t==null||!F(e,t.options)))return t}hasHighlightedRenderCache(i,e){const{renderCache:t}=this;return t?.result!=null&&t.highlighted&&M(i,t.file)&&F(e,t.options)}onHighlightError(i){console.error(i)}getTokenizeMaxLength(){return this.options.tokenizeMaxLength??1e5}createPreElement(i){const{disableLineNumbers:e=!1,overflow:t="scroll"}=this.options;return We({type:"file",diffIndicators:"none",disableBackground:!0,disableLineNumbers:e,overflow:t,split:!1,totalLines:i})}};function $(i,e){return i>e}function Tt(i,e){return i.lineNumber===e.lineNumber&&i.metadata===e.metadata}function ge(i){return{theme:i?.theme,disableLineNumbers:i?.disableLineNumbers,overflow:i?.overflow,themeType:i?.themeType,collapsed:i?.collapsed,disableFileHeader:i?.disableFileHeader,disableVirtualizationBuffers:i?.disableVirtualizationBuffers,stickyHeader:i?.stickyHeader,preferredHighlighter:i?.preferredHighlighter,useCSSClasses:i?.useCSSClasses,useTokenTransformer:i?.useTokenTransformer,tokenizeMaxLineLength:i?.tokenizeMaxLineLength,tokenizeMaxLength:i?.tokenizeMaxLength,unsafeCSS:i?.unsafeCSS,headerRenderMode:i?.renderCustomHeader!=null?"custom":"default"}}const bt=[""];let Rt=-1;var Te=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file:${++Rt}`;type="file";fileContainer;spriteSVG;pre;code;bufferBefore;bufferAfter;themeCSSStyle;appliedThemeCSS;hasAdoptedThemeCSS=!1;unsafeCSSStyle;appliedUnsafeCSS;gutterUtilityContent;errorWrapper;placeHolder;lastRenderedHeaderHTML;cachedHeaderHTML;appliedPreAttributes;lastRowCount;mounted=!1;headerElement;headerCustom;headerPrefix;headerFilenameSuffix;headerMetadata;fileRenderer;resizeManager;interactionManager;annotationCache=new Map;lineAnnotations=[];managersDirty=!1;file;renderRange;enabled=!0;editor;constructor(e={theme:H},t,n=!1){this.options=e,this.workerManager=t,this.isContainerManaged=n,this.fileRenderer=new yt(e,this.handleHighlightRender,this.workerManager),this.resizeManager=new Ge,this.interactionManager=new je("file",se(e)),this.workerManager?.subscribeToThemeChanges(this)}handleHighlightRender=()=>{this.rerender()};rerender(){!this.enabled||this.file==null||this.render({file:this.file,forceRender:!0,renderRange:this.renderRange})}onThemeChange(){this.fileRenderer.clearRenderCache(),this.rerender()}setOptions(e){e!=null&&(this.options=e,this.cachedHeaderHTML=void 0,this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(se(this.options))}mergeOptions(e){this.options={...this.options,...e}}setThemeType(e){(this.options.themeType??"system")!==e&&(this.mergeOptions({themeType:e}),this.applyCachedThemeState(e))}applyCachedThemeState(e){if(typeof this.options.theme=="string"||this.fileContainer==null||this.appliedThemeCSS==null)return!1;const t=this.appliedThemeCSS.baseThemeType??e;return this.appliedThemeCSS.themeType===t?!1:(this.applyThemeState(this.fileContainer,this.appliedThemeCSS.themeStyles,e,this.appliedThemeCSS.baseThemeType),!0)}hasThemeChanged(){return this.appliedThemeCSS!=null&&!mt(this.appliedThemeCSS.theme,this.options.theme??H)}getHoveredLine=()=>this.interactionManager.getHoveredLine();setLineAnnotations(e){this.lineAnnotations=e}setSelectedLines(e,t){this.interactionManager.setSelection(e,t)}flushManagers(){if(!this.managersDirty||this.pre==null){this.managersDirty=!1;return}const{overflow:e="scroll"}=this.options;this.interactionManager.setup(this.pre),this.resizeManager.setup(this.pre,e==="wrap"),this.managersDirty=!1}cleanUp(e=!1){this.emitPostRender(!0),this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.isContainerManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,e||(this.lineAnnotations=[]),this.annotationCache.clear(),this.pre=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.lastRenderedHeaderHTML=void 0,e||(this.cachedHeaderHTML=void 0),this.errorWrapper=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.placeHolder=void 0,this.unsafeCSSStyle=void 0,e?this.fileRenderer.recycle():(this.fileRenderer.cleanUp(),this.workerManager=void 0,this.file=void 0),this.enabled=!1,this.editor?.cleanUp(),this.editor=void 0}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate(e){const{fileContainer:t,prerenderedHTML:n,preventEmit:r=!1,file:s,lineAnnotations:a}=e;this.hydrateElements(t,n),Lt(this.pre,s,this.options.collapsed)||Mt(this.headerElement,s,this.options.disableFileHeader)?this.render({...e,preventEmit:!0}):this.hydrationSetup({file:s,lineAnnotations:a}),r||this.emitPostRender()}hydrateElements(e,t){this.fileContainer!==e&&this.emitPostRender(!0),$e(e,t);for(const n of Array.from(e.shadowRoot?.children??[])){if(n instanceof SVGElement){this.spriteSVG=n;continue}if(n instanceof HTMLElement){if(n instanceof HTMLPreElement){this.pre=n,this.appliedPreAttributes=void 0;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-theme-css")){this.themeCSSStyle=n;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-unsafe-css")){this.unsafeCSSStyle=n,this.appliedUnsafeCSS=n.textContent;continue}if("diffsHeader"in n.dataset){this.headerElement=n,this.lastRenderedHeaderHTML=void 0;continue}}}this.pre!=null&&(this.syncCodeNodeFromPre(this.pre),this.pre.removeAttribute("data-dehydrated")),this.fileContainer=e,this.hydrateMeasuredScrollbar()}hydrationSetup({file:e,lineAnnotations:t}){this.lineAnnotations=t??this.lineAnnotations,this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),this.pre!=null&&(this.fileRenderer.hydrate(e),this.renderAnnotations(),this.renderGutterUtility(),this.injectUnsafeCSS(),this.managersDirty=!0,this.flushManagers())}getOrCreateLineCache(e=this.file){return e!=null?this.fileRenderer.getOrCreateLineCache(e):bt}updateBuffers(e){this.pre!=null&&this.applyBuffers(this.pre,e)}syncRenderViewToEditor(){const e=this.editor,t=this.fileContainer,n=this.file;e!=null&&t!=null&&n!=null&&this.fileRenderer.initializeHighlighter().then(r=>{e.__syncRenderView(r,t,n,this.lineAnnotations,this.renderRange)})}attachEditor(e){return this.editor?.cleanUp(),this.editor=e,this.interactionManager.setEditorAttached(!0),this.syncRenderViewToEditor(),()=>{this.editor=void 0,this.interactionManager.setEditorAttached(!1)}}applyDocumentChange(e,t){this.fileRenderer.applyDocumentChange(e),t!=null&&t!==this.lineAnnotations&&this.file!=null&&(this.setLineAnnotations(t),this.fileRenderer.setLineAnnotations(this.lineAnnotations),this.renderAnnotations())}updateRenderCache(e,t){this.fileRenderer.updateRenderCache(e,t)}render({file:e,fileContainer:t,forceRender:n=!1,preventEmit:r=!1,containerWrapper:s,deferManagers:a=!1,lineAnnotations:o,renderRange:h}){if(!this.enabled)throw new Error("File.render: attempting to call render after cleaned up");this.editor?.__postponeBackgroundTokenizeToNextFrame();const{collapsed:d=!1,themeType:l="system"}=this.options,c=d?void 0:h,u=this.renderRange,p=this.hasThemeChanged(),f=o!=null&&(o.length>0||this.lineAnnotations.length>0)?o!==this.lineAnnotations:!1,S=!M(this.file,e);if(!d&&!n&&Se(c,this.renderRange)&&!S&&!f&&!p)return this.applyCachedThemeState(l);this.renderRange=c,S&&(this.cachedHeaderHTML=void 0),this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),o!=null&&this.setLineAnnotations(o),this.fileRenderer.setLineAnnotations(this.lineAnnotations);const{disableErrorHandling:g=!1,disableFileHeader:y=!1}=this.options;if(y&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),t=this.getOrCreateFileContainerNode(t,s),this.applyCachedThemeState(l),d){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const m=this.fileRenderer.renderFile(e,Fe);m!=null&&this.applyThemeState(t,m.themeStyles,l,m.baseThemeType),m?.headerAST!=null&&this.applyHeaderToDOM(m.headerAST,t),this.injectUnsafeCSS()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}try{const m=this.getOrCreatePreNode(t);if(!this.canPartiallyRender(n,f,S||p)||!this.applyPartialRender(u,c)){const v=this.fileRenderer.renderFile(e,c);if(v==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(t,v.themeStyles,l,v.baseThemeType),v.headerAST!=null&&this.applyHeaderToDOM(v.headerAST,t),this.applyFullRender(v,m)}this.applyBuffers(m,c),this.injectUnsafeCSS(),this.managersDirty=!0,a||this.flushManagers(),this.renderAnnotations(),this.renderGutterUtility(),this.editor!=null&&this.syncRenderViewToEditor()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}emitPostRender(e=!1){const{fileContainer:t,options:{onPostRender:n}}=this;if(e){if(!this.mounted||(this.mounted=!1,t==null))return;n?.(t,this,"unmount");return}if(t==null)return;const r=this.mounted?"update":"mount";this.mounted=!0,n?.(t,this,r)}removeRenderedCode(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.code?.remove(),this.code=void 0,this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0}clearAuxiliaryNodes(){for(const{element:e}of this.annotationCache.values())e.remove();this.annotationCache.clear(),this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0}canPartiallyRender(e,t,n){return!(e||t||n)}renderPlaceholder(e){if(this.fileContainer==null)return!1;if(this.emitPostRender(!0),this.cleanChildNodes(),this.placeHolder==null){const t=this.fileContainer.shadowRoot??this.fileContainer.attachShadow({mode:"open"});this.placeHolder=document.createElement("div"),this.placeHolder.dataset.placeholder="",t.appendChild(this.placeHolder)}return this.placeHolder.style.setProperty("height",`${e}px`),!0}primeHighlightCache(){const{file:e,workerManager:t}=this;e==null||e.cacheKey==null||t==null||K(e)||this.fileRenderer.getOrCreateLineCache(e).length>(this.options.tokenizeMaxLength??1e5)||t.primeFileHighlightCache(e)}cleanChildNodes(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.code?.remove(),this.errorWrapper?.remove(),this.headerElement?.remove(),this.gutterUtilityContent?.remove(),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.pre?.remove(),this.spriteSVG?.remove(),this.themeCSSStyle?.remove(),this.unsafeCSSStyle?.remove(),this.bufferAfter=void 0,this.bufferBefore=void 0,this.code=void 0,this.errorWrapper=void 0,this.headerElement=void 0,this.gutterUtilityContent=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.pre=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.lastRenderedHeaderHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderAnnotations(){if(this.isContainerManaged||this.fileContainer==null){for(const{element:n}of this.annotationCache.values())n.remove();this.annotationCache.clear();return}const e=new Map(this.annotationCache),{renderAnnotation:t}=this.options;if(t!=null&&this.lineAnnotations.length>0)for(const[n,r]of this.lineAnnotations.entries()){const s=`${n}-${I(r)}`;let a=this.annotationCache.get(s);if(a==null||!Tt(r,a.annotation)){a?.element.remove();const o=t(r);if(o==null)continue;a={element:qe(I(r)),annotation:r},a.element.appendChild(o),this.fileContainer.appendChild(a.element),this.annotationCache.set(s,a)}e.delete(s)}for(const[n,{element:r}]of e.entries())this.annotationCache.delete(n),r.remove()}renderGutterUtility(){const{renderGutterUtility:e}=this.options;if(this.fileContainer==null||e==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const t=e(this.interactionManager.getHoveredLine);if(t!=null&&this.gutterUtilityContent!=null)return;if(t==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const n=Ke();n.appendChild(t),this.fileContainer.appendChild(n),this.gutterUtilityContent=n}injectUnsafeCSS(){const{unsafeCSS:e}=this.options,t=this.fileContainer?.shadowRoot;if(t!=null){if(e==null||e===""){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}this.unsafeCSSStyle?.parentNode===t&&this.appliedUnsafeCSS===e||(this.unsafeCSSStyle??=Je(),this.unsafeCSSStyle.parentNode!==t&&t.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=Ye(e),this.appliedUnsafeCSS=e)}}applyThemeState(e,t,n,r){const s=e.shadowRoot??e.attachShadow({mode:"open"}),a=r??n,o=this.options.theme??H,h=typeof o=="string"?o:{...o},d=ae(s);if(this.themeCSSStyle?.parentNode===s&&this.appliedThemeCSS?.themeStyles===t&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===d){this.appliedThemeCSS.theme=h;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===s){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:d};return}this.themeCSSStyle=Xe({shadowRoot:s,currentNode:this.themeCSSStyle,themeCSS:Qe(t,a,d)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:d}:void 0}hydrateMeasuredScrollbar(){const e=this.fileContainer?.shadowRoot;e==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=Ze(this.themeCSSStyle.textContent??"",ae(e)))}applyFullRender(e,t){this.cleanupErrorWrapper(),this.applyPreNodeAttributes(t,e),this.code=et({code:this.code});const n=this.fileRenderer.renderCodeAST(e);if(this.code.childElementCount>=2)for(let r=0;r<2;r++){const s=this.code.children[r],a=n[r];s.innerHTML=A(a.children),s.style.cssText=a.properties.style}else this.code.innerHTML=A(n);t.contains(this.code)||t.replaceChildren(this.code),this.lastRowCount=e.rowCount}applyPartialRender(e,t){if(e==null||t==null)return!1;const{file:n,code:r}=this,s=r!=null?this.getColumns(r):void 0;if(n==null||r==null||s==null)return!1;const a=e.startingLine,o=t.startingLine,h=e.totalLines===1/0?Number.POSITIVE_INFINITY:a+e.totalLines,d=t.totalLines===1/0?Number.POSITIVE_INFINITY:o+t.totalLines,l=Math.max(a,o),c=Math.min(h,d);if(c<=l||!this.trimDOMToOverlap(s.gutter,l,c)||!this.trimDOMToOverlap(s.content,l,c))return!1;let{length:u}=s.content.children;const p=(y,m)=>{if(!(m<=0))return this.fileRenderer.renderFile(n,{startingLine:y,totalLines:m,bufferBefore:0,bufferAfter:0})},f=o<l?p(o,l-o):void 0;if(f===void 0&&o<l)return!1;const S=d===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,d-c),g=d>c?p(c,S):void 0;return g===void 0&&d>c?!1:(this.cleanupErrorWrapper(),f!=null&&(s.gutter.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.gutterAST)),s.content.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.contentAST)),u+=f.rowCount),g!=null&&(s.gutter.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.gutterAST)),s.content.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.contentAST)),u+=g.rowCount),this.lastRowCount!==u&&(s.gutter.style.setProperty("grid-row",`span ${u}`),s.content.style.setProperty("grid-row",`span ${u}`),this.lastRowCount=u),!0)}getColumns(e){const t=e.children[0],n=e.children[1];if(!(!(t instanceof HTMLElement)||!(n instanceof HTMLElement)||t.dataset.gutter==null||n.dataset.content==null))return{gutter:t,content:n}}trimDOMToOverlap(e,t,n){const r=this.getDOMBoundaryIndices(e,[t,n]),s=r.get(t)??e.children.length,a=r.get(n)??e.children.length;if(s>a)return!1;for(let o=e.children.length-1;o>=a;o-=1)e.children[o]?.remove();for(let o=s-1;o>=0;o-=1)e.children[o]?.remove();return!0}getDOMBoundaryIndices(e,t){const n=[...new Set(t)].sort((h,d)=>h-d),r=new Map;if(n.length===0)return r;let s=0,a=n[s];const{children:o}=e;a===0&&(r.set(0,0),s+=1,a=n[s]);for(let h=0;h<o.length;h+=1){const d=o[h];if(!(d instanceof HTMLElement))continue;const l=this.getLineIndexFromDOMNode(d);if(l!=null){for(;a!=null&&l>=a;)r.set(a,h),s+=1,a=n[s];if(s>=n.length)break}}for(const h of n)r.has(h)||r.set(h,o.length);return r}getLineIndexFromDOMNode(e){const t=e.dataset.lineIndex;if(t==null)return;const n=Number(t);return Number.isNaN(n)?void 0:n}applyBuffers(e,t){if(t==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}t.bufferBefore>0?(this.bufferBefore==null&&(this.bufferBefore=document.createElement("div"),this.bufferBefore.dataset.virtualizerBuffer="before",e.before(this.bufferBefore)),this.bufferBefore.style.setProperty("height",`${t.bufferBefore}px`),this.bufferBefore.style.setProperty("contain","strict")):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),t.bufferAfter>0?(this.bufferAfter==null&&(this.bufferAfter=document.createElement("div"),this.bufferAfter.dataset.virtualizerBuffer="after",e.after(this.bufferAfter)),this.bufferAfter.style.setProperty("height",`${t.bufferAfter}px`),this.bufferAfter.style.setProperty("contain","strict")):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyHeaderToDOM(e,t){const{file:n}=this;if(n==null)return;this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;const r=this.cachedHeaderHTML??A(e);if(this.cachedHeaderHTML=r,r!==this.lastRenderedHeaderHTML){const d=document.createElement("div");d.innerHTML=r;const l=d.firstElementChild;if(!(l instanceof HTMLElement))return;this.headerElement!=null?t.shadowRoot?.replaceChild(l,this.headerElement):t.shadowRoot?.prepend(l),this.headerElement=l,this.lastRenderedHeaderHTML=r}if(this.isContainerManaged)return;const{renderHeaderPrefix:s,renderHeaderFilenameSuffix:a,renderCustomHeader:o,renderHeaderMetadata:h}=this.options;if(o!=null){const d=o(n)??void 0;this.headerCustom=this.upsertHeaderSlotElement(t,this.headerCustom,Ce,d),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0}else{const d=s?.(n)??void 0,l=a?.(n)??void 0,c=h?.(n)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(t,this.headerPrefix,ke,d),this.headerFilenameSuffix=this.upsertHeaderSlotElement(t,this.headerFilenameSuffix,Ie,l),this.headerMetadata=this.upsertHeaderSlotElement(t,this.headerMetadata,ze,c),this.headerCustom?.remove(),this.headerCustom=void 0}}clearHeaderSlots(){this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0}upsertHeaderSlotElement(e,t,n,r){if(r==null){t?.remove();return}const s=t??this.createHeaderSlotElement(n);return t==null&&e.appendChild(s),this.replaceHeaderSlotContent(s,r),s}replaceHeaderSlotContent(e,t){e.replaceChildren(),t instanceof Element?e.appendChild(t):e.innerText=`${t}`}createHeaderSlotElement(e){const t=document.createElement("div");return t.slot=e,t}getOrCreateFileContainerNode(e,t){const{fileContainer:n}=this,r=e??n??document.createElement("diffs-container"),s=n!==r;return s&&this.emitPostRender(!0),this.fileContainer=r,n!=null&&s&&(this.lastRenderedHeaderHTML=void 0,this.headerElement=void 0),t!=null&&this.fileContainer.parentNode!==t&&t.appendChild(this.fileContainer),s&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(e){const{shadowRoot:t}=e;if(t!=null)for(const n of t.children)n instanceof SVGElement?this.spriteSVG??=n:oe(n)&&n.hasAttribute("data-theme-css")?(this.themeCSSStyle??=n,this.hasAdoptedThemeCSS=!0):oe(n)&&n.hasAttribute("data-unsafe-css")&&(this.unsafeCSSStyle??=n,this.appliedUnsafeCSS??=this.options.unsafeCSS??void 0)}ensureSpriteSVG(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});if(this.spriteSVG==null){const n=document.createElement("div");n.innerHTML=tt;const r=n.firstChild;r instanceof SVGElement&&(this.spriteSVG=r)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==t&&t.appendChild(this.spriteSVG)}getOrCreatePreNode(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});return this.pre==null?(this.pre=document.createElement("pre"),this.appliedPreAttributes=void 0,this.code=void 0,t.appendChild(this.pre)):this.pre.parentNode!==t&&(e.shadowRoot?.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodeFromPre(e){this.code=void 0;for(const t of Array.from(e.children))if(t instanceof HTMLElement&&t.hasAttribute("data-code")){this.code=t;return}}applyPreNodeAttributes(e,{totalLines:t}){const{overflow:n="scroll",disableLineNumbers:r=!1}=this.options,s={type:"file",split:!1,overflow:n,disableLineNumbers:r,diffIndicators:"none",disableBackground:!0,totalLines:t};it(s,this.appliedPreAttributes)||(nt(e,s),this.appliedPreAttributes=s)}applyErrorToDOM(e,t){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;const n=t.shadowRoot??t.attachShadow({mode:"open"});this.errorWrapper??=document.createElement("div"),this.errorWrapper.dataset.errorWrapper="",this.errorWrapper.textContent="",n.appendChild(this.errorWrapper);const r=document.createElement("div");r.dataset.errorMessage="",r.innerText=e.message,this.errorWrapper.appendChild(r);const s=document.createElement("pre");s.dataset.errorStack="",s.innerText=e.stack??"No Error Stack",this.errorWrapper.appendChild(s)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function Lt(i,e,t=!1){return!t&&i==null&&e!=null}function Mt(i,e,t=!1){return i==null&&e!=null&&!t}const Ht=5e3;let At=-1;function xt(i,e){return(i.overflow??"scroll")!==(e.overflow??"scroll")||(i.collapsed??!1)!==(e.collapsed??!1)||(i.disableLineNumbers??!1)!==(e.disableLineNumbers??!1)||(i.disableFileHeader??!1)!==(e.disableFileHeader??!1)||i.unsafeCSS!==e.unsafeCSS}var wt=class extends Te{virtualizer;metrics;__id=`virtualized-file:${++At}`;top;height=0;cache={heights:new Map,checkpoints:[],fileAnnotationHeight:0};isVisible=!1;isSetup=!1;layoutDirty=!0;forceRenderOverride;currentCollapsed;constructor(i,e,t=Ne,n,r=!1){super(i,n,r),this.virtualizer=e,this.metrics=t}setMetrics(i,e=!1){!e&&rt(this.metrics,i)||(this.metrics=i,this.resetLayoutCache())}setLineAnnotations(i){this.syncLineAnnotations(i)&&this.resetLayoutCache()}syncLineAnnotations(i){return i==null||i===this.lineAnnotations||i.length===0&&this.lineAnnotations.length===0?!1:(super.setLineAnnotations(i),!0)}hasLineAnnotations(){return this.lineAnnotations.some(i=>i.lineNumber>0)}getLineHeight(i,e=!1){const t=this.cache.heights.get(i);if(t!=null)return t;const n=e?2:1;return this.metrics.lineHeight*n}setOptions(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setOptions cannot be used inside CodeView. Update CodeView options instead.");if(i==null)return;const{options:e}=this,t=!ye(e,i),n=xt(e,i);super.setOptions(i),n&&this.resetLayoutCache(!0),t&&(this.forceRenderOverride=!0),t&&this.virtualizer.instanceChanged(this,n)}setThemeType(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setThemeType cannot be used inside CodeView. Update CodeView options instead.");super.setThemeType(i)}resetLayoutCache(i=!1){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heights.size>0&&this.cache.heights.clear(),this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.renderRange!=null&&(this.renderRange=void 0),i&&this.isSimpleMode()&&this.computeApproximateSize()}reconcileHeights(){let i=!1;if(this.fileContainer==null||this.file==null)return this.height!==0&&(i=!0),this.height=0,i;const{overflow:e="scroll"}=this.options;if(this.top=this.getVirtualizedTop(),e==="scroll"&&this.lineAnnotations.length===0&&!this.isResizeDebuggingEnabled()||this.code==null)return i;const t=this.code.children[1];if(!(t instanceof HTMLElement))return i;const n=he(this.lineAnnotations);if(this.renderRange!=null&&n&&ve(this.renderRange)){const r=Et(t)??0;r!==this.cache.fileAnnotationHeight&&(this.cache.fileAnnotationHeight=r,i=!0)}else!n&&this.cache.fileAnnotationHeight!==0&&(this.cache.fileAnnotationHeight=0,i=!0);for(const r of t.children){if(!(r instanceof HTMLElement))continue;const s=r.dataset.lineIndex;if(s==null)continue;const a=Number(s);let o=r.getBoundingClientRect().height,h=!1;r.nextElementSibling instanceof HTMLElement&&("lineAnnotation"in r.nextElementSibling.dataset||"noNewline"in r.nextElementSibling.dataset)&&("noNewline"in r.nextElementSibling.dataset&&(h=!0),o+=r.nextElementSibling.getBoundingClientRect().height);const d=this.getLineHeight(a,h);o!==d&&(i=!0,o===this.metrics.lineHeight*(h?2:1)?this.cache.heights.delete(a):this.cache.heights.set(a,o))}return(i||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),i}onRender=i=>this.fileContainer==null||this.file==null?!1:(i&&(this.top=this.getVirtualizedTop()),this.render({file:this.file}));prepareCodeViewItem(i,e,t,n){const r=this.syncLineAnnotations(n);let s=t?.resetFileLayoutCache===!0||r;t?.metrics!=null&&(this.metrics=t.metrics,s=!0);const{collapsed:a=!1}=this.options;return this.currentCollapsed!==a&&(this.currentCollapsed=a,s=!0),s&&this.resetLayoutCache(),this.file!==i&&(this.layoutDirty=!0),this.file=i,this.top=e,this.computeApproximateSize(),this.height}getLinePosition(i){if(this.file==null||i<1)return;const{disableFileHeader:e=!1,collapsed:t=!1}=this.options,n=this.fileRenderer.getLineCount(this.file)-1;let r=B(this.metrics,e);if(t||n<0)return{top:r,height:0};const s=Math.min(Math.max(i-1,0),n),{overflow:a="scroll"}=this.options,{lineHeight:o}=this.metrics;if(r+=this.cache.fileAnnotationHeight,a==="scroll"&&!this.hasLineAnnotations())return{top:r+s*o,height:o};const h=this.getLayoutCheckpointBeforeLineIndex(s);r=h?.top??r;for(let d=h?.lineIndex??0;d<s;d++)r+=this.getLineHeight(d,!1);return{top:r,height:this.getLineHeight(s,!1)}}getNumericScrollAnchor(i){if(this.file==null||this.renderRange==null)return;const{disableFileHeader:e=!1,collapsed:t=!1,overflow:n="scroll"}=this.options;if(t||this.renderRange.totalLines<=0)return;const r=this.fileRenderer.getLineCount(this.file)-1;if(r<0)return;const s=B(this.metrics,e),a=Math.min(this.renderRange.startingLine,r),o=Math.min(a+this.renderRange.totalLines-1,r);if(o<a)return;const{fileAnnotationHeight:h}=this.cache;if(n==="scroll"&&!this.hasLineAnnotations()){const{lineHeight:l}=this.metrics,c=s+(a===0?h:this.renderRange.bufferBefore),u=a+Math.max(Math.ceil((i-c)/l),0);return u>o?void 0:{lineNumber:u+1,top:s+h+u*l}}let d=s+(a===0?h:this.renderRange.bufferBefore);for(let l=a;l<=o;l++){if(d>=i)return{lineNumber:l+1,top:d};d+=this.getLineHeight(l)}}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(i){if(this.top==null||this.file==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};const e=i!=null?this.computeRenderRangeFromWindow(this.file,this.top,i):this.renderRange;if(e==null)return;const{bufferBefore:t,bufferAfter:n,totalLines:r}=e;let s=0;if(r===0){const a=i??this.virtualizer.getWindowSpecs();this.top<a.top&&(s=n)}return{topOffset:this.top+t+s,height:this.height-(t+n)}}cleanUp(i=!1){this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),i||this.resetLayoutCache(),this.isSetup=!1,super.cleanUp(i)}computeApproximateSize(i=!1){const e=this.isResizeDebuggingEnabled();if(!i&&!this.layoutDirty&&!e)return;const t=this.height===0;if(this.height=0,this.cache.checkpoints=[],this.file==null){this.layoutDirty=!1;return}const{disableFileHeader:n=!1,collapsed:r=!1,overflow:s="scroll"}=this.options,{lineHeight:a}=this.metrics,o=this.fileRenderer.getLineCount(this.file),h=B(this.metrics,n),d=fe(this.metrics);if(this.height+=h,r){this.layoutDirty=!1;return}if(this.height+=this.cache.fileAnnotationHeight,s==="scroll"&&!this.hasLineAnnotations())this.height+=o*a;else for(let l=0;l<o;l++)this.addLayoutCheckpoint(l,this.height),this.height+=this.getLineHeight(l,!1);if(o>0&&(this.height+=d),this.fileContainer!=null&&e&&!t){const l=this.fileContainer.getBoundingClientRect();l.height!==this.height?console.log("VirtualizedFile.computeApproximateSize: computed height doesnt match",{name:this.file.name,elementHeight:l.height,computedHeight:this.height}):console.log("VirtualizedFile.computeApproximateSize: computed height IS CORRECT")}this.layoutDirty=!1}setVisibility(i){this.isAdvancedMode()||this.fileContainer==null||(i&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!i&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){!this.enabled||this.file==null||(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!1))}applyDocumentChange(i,e,t=!1){const{heights:n,checkpoints:r}=this.cache,s=this.renderRange;if(super.applyDocumentChange(i,e),this.getSimpleVirtualizer()?.markDOMDirty(),this.layoutDirty=!0,n.size>0&&n.clear(),r.length>0&&(r.length=0),this.isSimpleMode()&&this.computeApproximateSize(),t&&s!==void 0&&this.file!==void 0){const a=this.virtualizer.getWindowSpecs(),o=this.computeRenderRangeFromWindow(this.file,this.top??0,a);o.bufferAfter!==s.bufferAfter&&this.updateBuffers(o)}}render({fileContainer:i,file:e,forceRender:t=!1,lineAnnotations:n,...r}){const s=this.file==null||!M(this.file,e),{forceRenderOverride:a,isSetup:o}=this;this.forceRenderOverride=void 0;const h=this.syncLineAnnotations(n);if(h&&this.resetLayoutCache(),this.file=e,i=this.getOrCreateFileContainerNode(i),this.file==null)return console.error("VirtualizedFile.render: attempting to virtually render when we dont have file"),!1;if(o)this.top??=this.getVirtualizedTop(),s&&this.isSimpleMode()&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache(!0));else{this.computeApproximateSize();const u=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(u==null)throw new Error("VirtualizedFile.render: simple virtualizer is not available");u.connect(i,this),this.isVisible=u.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode())return this.renderPlaceholder(this.height);const d=this.virtualizer.getWindowSpecs(),l=this.top??0,c=this.computeRenderRangeFromWindow(this.file,l,d);return super.render({file:this.file,fileContainer:i,renderRange:c,lineAnnotations:n,forceRender:(a??t)||h,...r})}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}addLayoutCheckpoint(i,e){i%Ht===0&&this.cache.checkpoints.push({lineIndex:i,top:e})}getLayoutCheckpointBeforeLineIndex(i){if(i<=0||this.cache.checkpoints.length===0)return;let e=0,t=this.cache.checkpoints.length-1,n;for(;e<=t;){const r=e+t>>1,s=this.cache.checkpoints[r];if(s==null)throw new Error("VirtualizedFile: invalid checkpoint index");s.lineIndex<=i?(n=s,e=r+1):t=r-1}return n}getLayoutCheckpointBeforeTop(i,e){let t=0,n=this.cache.checkpoints.length-1,r=-1;for(;t<=n;){const s=t+n>>1,a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");a.top<=i?(r=s,t=s+1):n=s-1}if(e==null)return r>=0?this.cache.checkpoints[r]:void 0;for(let s=r;s>=0;s--){const a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");if(a.lineIndex%e===0)return a}}getVirtualizedTop(){return this.virtualizer.type==="advanced"?this.virtualizer.getLocalTopForInstance(this):this.fileContainer!=null?this.virtualizer.getOffsetInScrollContainer(this.fileContainer):0}getSimpleVirtualizer(){return this.virtualizer.type==="simple"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}computeRenderRangeFromWindow(i,e,{top:t,bottom:n}){const{disableFileHeader:r=!1,overflow:s="scroll"}=this.options,{hunkLineCount:a,lineHeight:o}=this.metrics,h=this.fileRenderer.getLineCount(i),d=this.height,l=B(this.metrics,r),c=h>0?fe(this.metrics):0,{fileAnnotationHeight:u}=this.cache,p=l+u,f=Math.max(0,d-l-u-c),S=he(this.lineAnnotations),g=e+l,y=u>0&&S&&g<n&&g+u>t;if(e<t-d||e>n)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};if(h<=a)return{startingLine:0,totalLines:a,bufferBefore:0,bufferAfter:0};const m=Math.ceil(Math.max(n-t,0)/o),v=Math.ceil(m/a)*a+a*2,z=v/a,D=(t+n)/2;if(s==="scroll"&&!this.hasLineAnnotations()){const R=e+p,V=R+f;if(!y&&!(R<n&&V>t))return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};const w=Math.floor(y&&D<e+p?0:(D-(e+p))/o),b=Math.floor(w/a)-Math.floor(z/2),xe=Math.ceil(h/a),E=Math.max(0,Math.min(b,xe))*a,Q=b<0?v+b*a:v,we=E===0?0:u+E*o,Ee=Math.min(Q,h-E);return{startingLine:E,totalLines:Q,bufferBefore:we,bufferAfter:Math.max(0,(h-E-Ee)*o)}}const be=z,N=[],U=this.getLayoutCheckpointBeforeTop(Math.max(0,t-e-v*o*2),a);let T=e+(U?.top??p),_=U?.lineIndex??0,O,P,x;const Re=U?.lineIndex??0;for(let R=Re;R<h;R++){const V=_%a===0,w=Math.floor(_/a);if(V&&(N[w]=T-(e+p),x!=null)){if(x<=0)break;x--}const b=this.getLineHeight(R,!1);T>t-b&&T<n&&(O??=w),T+b>D&&(P??=w),x==null&&T>=n&&V&&(x=be),_++,T+=b}if(O==null)if(y)O=0,P=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};P??=O;const W=Math.round(P-z/2),Le=Math.max(0,Math.ceil(h/a)-z),G=Math.max(0,Math.min(W,Le)),J=G*a,Y=W<0?v+W*a:v,Me=N[G]??0,He=J===0?0:u+Me,X=G+Y/a,Ae=X<N.length?f-N[X]:f-(T-e-p);return{startingLine:J,totalLines:Y,bufferBefore:He,bufferAfter:Math.max(0,Ae)}}};function Et(i){let e;for(const t of i.children)t instanceof HTMLElement&&t.dataset.lineAnnotation===st&&(e=Math.max(e??0,t.getBoundingClientRect().height));return e}function Ft({file:i,renderCustomHeader:e,renderHeaderPrefix:t,renderHeaderFilenameSuffix:n,renderHeaderMetadata:r,renderAnnotation:s,lineAnnotations:a,renderGutterUtility:o,getHoveredLine:h}){const d=e?.(i),l=t?.(i),c=n?.(i),u=r?.(i);return C.jsxs(C.Fragment,{children:[d!=null?C.jsx("div",{slot:Ce,children:d}):C.jsxs(C.Fragment,{children:[l!=null&&C.jsx("div",{slot:"header-prefix",children:l}),c!=null&&C.jsx("div",{slot:"header-filename-suffix",children:c}),u!=null&&C.jsx("div",{slot:"header-metadata",children:u})]}),s!=null&&a?.map((p,f)=>C.jsx("div",{slot:I(p),children:s(p)},f)),o!=null&&C.jsx("div",{slot:"gutter-utility-slot",style:at,children:o(h)})]})}const me=typeof window>"u"?k.useEffect:k.useLayoutEffect;function kt({file:i,options:e,lineAnnotations:t,selectedLines:n,prerenderedHTML:r,metrics:s,hasGutterRenderUtility:a,hasCustomHeader:o,disableWorkerPool:h,contentEditable:d}){const l=ot(),c=n!==void 0,u=k.useContext(ht),p=lt(),f=k.useRef(null),S=dt(g=>{if(g!=null){if(f.current!=null)throw new Error("File: An instance should not already exist when a node is created");l!=null?f.current=new wt(q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),l,s,h?void 0:u,!0):f.current=new Te(q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),h?void 0:u,!0),f.current.hydrate({file:i,fileContainer:g,lineAnnotations:t,prerenderedHTML:r})}else{if(f.current==null)throw new Error("File: A File instance should exist when unmounting");f.current.cleanUp(),f.current=null}});return me(()=>{if(f.current==null)return;const g=q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),y=!ye(f.current.options,g);f.current.setOptions(g),f.current.render({file:i,lineAnnotations:t,forceRender:y}),n!==void 0&&f.current.setSelectedLines(n)}),me(()=>{if(d&&f.current!=null){if(p===void 0)throw new Error("File: Editor is not attached");return p.edit(f.current)}},[d,p]),{ref:S,getHoveredLine:k.useCallback(()=>f.current?.getHoveredLine(),[])}}function q({options:i,controlledSelection:e,contentEditable:t,hasCustomHeader:n,hasEditor:r,hasGutterRenderUtility:s}){const a=t&&r,o=e||s||n;if(!o&&!a)return i;let h={...i};return o&&(h={...h,controlledSelection:e,renderCustomHeader:n?le:i?.renderCustomHeader,renderGutterUtility:s?le:i?.renderGutterUtility}),a&&(h={...h,useTokenTransformer:!0,enableGutterUtility:!1,enableLineSelection:!1,lineHoverHighlight:"disabled"}),h}function _t({file:i,lineAnnotations:e,selectedLines:t,options:n,metrics:r,className:s,style:a,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:d,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c,prerenderedHTML:u,renderGutterUtility:p,disableWorkerPool:f=!1,contentEditable:S=!1}){const{ref:g,getHoveredLine:y}=kt({file:i,options:n,metrics:r,lineAnnotations:e,selectedLines:t,prerenderedHTML:u,hasGutterRenderUtility:p!=null,hasCustomHeader:h!=null,disableWorkerPool:f,contentEditable:S});return C.jsx(Oe,{ref:g,className:s,style:a,children:ct(Ft({file:i,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:d,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c,renderGutterUtility:p,lineAnnotations:e,getHoveredLine:y}),u)})}const Wt=L.memo(function({jsonString:e,className:t,maxHeight:n="100%",initiallyExpandedDepth:r=2}){const s=L.useRef(null),[a,o]=L.useState(null),h=L.useMemo(()=>{try{const c=e.trim();if(!c)return o("Empty JSON content"),null;const u=JSON.parse(c);return o(null),u}catch(c){return o(c instanceof Error?c.message:"Invalid JSON"),null}},[e]),d=L.useCallback(()=>{s.current?.expandAll()},[]),l=L.useCallback(()=>{s.current?.collapseAll()},[]);return a?C.jsx("div",{className:t,children:C.jsxs("div",{className:"rounded-md border border-[var(--interactive-border)] bg-[var(--syntax-base-background)] p-4",children:[C.jsx("div",{className:"mb-1 font-medium text-[var(--surface-foreground)]",children:"Invalid JSON"}),C.jsx("div",{className:"font-mono text-xs text-[var(--surface-mutedForeground)]",children:a})]})}):h===null?null:C.jsxs("div",{className:t,children:[C.jsxs("div",{className:"flex items-center gap-1 border-b border-[var(--interactive-border)] px-2 py-1",children:[C.jsxs(ee,{variant:"ghost",size:"xs",onClick:d,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-down-s",className:"h-3 w-3"}),"Expand all"]}),C.jsxs(ee,{variant:"ghost",size:"xs",onClick:l,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-up-s",className:"h-3 w-3"}),"Collapse all"]})]}),C.jsx("div",{className:"bg-[var(--syntax-base-background)] py-1",style:{maxHeight:n,overflow:"auto"},children:C.jsx(Pe,{ref:s,data:h,maxHeight:n,initiallyExpandedDepth:r})})]})});export{_t as F,Wt as J};
1
+ import{dm as H,dP as Z,dQ as Fe,dR as Ce,dS as ke,dT as Ie,dU as ze,dn as Ne,dV as Oe,B as ee,I as te,dW as Ve}from"./useAppFontEffects-BFgKpDYT.js";import{a as ie,s as Pe,b as Se,c as ne,d as ve,g as Be,e as re,f as I,h as De,i as Ue,j as _e,k as We,R as Ge,I as je,p as se,l as $e,m as qe,n as Ke,o as Je,w as Ye,q as ae,u as Xe,r as Qe,t as Ze,v as et,x as oe,S as tt,y as it,z as nt,A as rt,B as ye,C as he,F as st}from"./web-components-B_NMC-2c.js";import{G as at,u as ot,W as ht,a as lt,b as dt,n as le,t as ct}from"./Virtualizer-okhy9Aq3.js";import{j as C}from"./vendor-boot-3SaHYVb1.js";import{o as ut,i as j,f as M,a as ft,q as de,s as pt,t as ce,d as gt,u as ue,b as mt,w as B,x as fe}from"./computeVirtualFileMetrics-g1aOl5nF.js";import{a as F,i as K,l as pe,h as Ct,r as St}from"./renderFileWithHighlighter-tJRUQWjE.js";import{t as A}from"./vendor-hast-util-to-html-O3stl53j.js";import{a as k,R as L}from"./vendor-react-Bz1tRBxM.js";let vt=-1;var yt=class{options;onRenderUpdate;workerManager;__id=`file-renderer:${++vt}`;highlighter;renderCache;computedLang="text";lineAnnotations={};lineCache;textDoucmentCache=new WeakMap;constructor(i={theme:H},e,t){this.options=i,this.onRenderUpdate=e,this.workerManager=t,t?.isWorkingPool()!==!0&&(this.highlighter=ie(i.theme??H)?ut():void 0)}setOptions(i){this.options=i}mergeOptions(i){this.options={...this.options,...i}}setLineAnnotations(i){this.lineAnnotations={};for(const e of i){const t=this.lineAnnotations[e.lineNumber]??[];this.lineAnnotations[e.lineNumber]=t,t.push(e)}}cleanUp(){this.recycle(),this.workerManager=void 0,this.onRenderUpdate=void 0}recycle(){this.clearRenderCache(),this.highlighter=void 0,this.workerManager?.cleanUpTasks(this),this.lineCache=void 0}clearRenderCache(){const i=this.renderCache;this.renderCache=void 0,i!=null&&i.isDirty===!0&&i.file.cacheKey!=null&&this.workerManager?.evictFileFromCache(i.file.cacheKey)}hydrate(i){const{options:e}=this.getRenderOptions(i),t=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());let n=this.workerManager?.getFileResultCache(i);n!=null&&!F(e,n.options)&&(n=void 0),this.renderCache??={file:i,options:e,highlighted:!t&&!K(i),result:t?void 0:n?.result,renderRange:void 0},this.workerManager?.isWorkingPool()===!0?this.renderCache.result==null&&!t&&this.workerManager.highlightFileAST(this,i):this.highlighter==null&&(this.computedLang=i.lang??j(i.name),this.initializeHighlighter())}getRenderOptions(i){const e=(()=>{if(this.workerManager?.isWorkingPool()===!0)return this.workerManager.getFileRenderOptions();const{theme:n=H,tokenizeMaxLineLength:r=1e3}=this.options;return{theme:n,useTokenTransformer:Pe(this.options),tokenizeMaxLineLength:r}})(),{renderCache:t}=this;return t?.result==null?{options:e,forceHighlight:!0}:!M(i,t.file)||!F(e,t.options)?{options:e,forceHighlight:!0}:{options:e,forceHighlight:!1}}getOrCreateLineCache(i){if(i.cacheKey==null)return this.lineCache=void 0,pe(i.contents);let{lineCache:e}=this;return(e==null||e.cacheKey!==i.cacheKey)&&(e={cacheKey:i.cacheKey,lines:pe(i.contents)}),this.lineCache=e,e.lines}getLineCount(i){return this.textDoucmentCache.get(i)?.lineCount??this.getOrCreateLineCache(i).length}updateRenderCache(i,e){if(this.renderCache==null)return;const{result:t}=this.renderCache;if(t!=null){for(const[n,r]of i)t.code[n]={type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:r.map(([s,a,o])=>s===0&&a===""?o===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:o}:{type:"element",tagName:"span",properties:{"data-char":s,style:`--diffs-token-${e}:${a};`},children:[{type:"text",value:o}]})};t.baseThemeType=e,this.renderCache.isDirty=!0}}applyDocumentChange(i){if(this.renderCache==null)return;const{file:e,result:t}=this.renderCache;if(t!=null&&t.code.length!==i.lineCount){t.code.length=Math.min(t.code.length,i.lineCount);for(let n=t.code.length;n<i.lineCount;n++)t.code.push({type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:[{type:"element",tagName:"span",properties:{"data-char":0},children:[{type:"text",value:i.getLineText(n)}]}]});this.renderCache.isDirty=!0}this.textDoucmentCache.set(e,i)}renderFile(i=this.renderCache?.file,e=Z){if(i==null)return;let{options:t,forceHighlight:n}=this.getRenderOptions(i);const r=this.getMatchingWorkerResultCache(i,t);r!=null&&!this.hasHighlightedRenderCache(i,t)&&(this.renderCache={file:i,highlighted:!0,renderRange:void 0,...r},n=!1),this.renderCache??={file:i,highlighted:!1,options:t,result:void 0,renderRange:void 0};const s=this.getOrCreateLineCache(i),a=i.contents.length>0,o=!a||K(i)||$(s.length,this.getTokenizeMaxLength()),h=!M(i,this.renderCache.file),d=!Se(this.renderCache.renderRange,e);if(this.workerManager?.isWorkingPool()===!0)(o||this.renderCache.result==null||!this.renderCache.highlighted&&(h||d))&&(this.renderCache.file=i,this.renderCache.options=t,this.renderCache.highlighted=!1,(this.renderCache.result==null||h||d||n)&&(this.renderCache.result=this.workerManager.getPlainFileAST(i,e.startingLine,e.totalLines,s)),this.renderCache.renderRange=e),!o&&a&&(!this.renderCache.highlighted||n)&&this.workerManager.highlightFileAST(this,i);else{this.computedLang=i.lang??j(i.name);const l=this.highlighter!=null&&ie(t.theme),c=this.highlighter!=null&&ne(this.computedLang),u=!o&&c;if(this.highlighter!=null&&l&&(n||o||!this.renderCache.highlighted&&u||this.renderCache.result==null)){const{result:p,options:f}=this.renderFileWithHighlighter(i,this.highlighter,o||!c);this.renderCache={file:i,options:f,highlighted:u,result:p,renderRange:void 0}}(!l||!o&&!c)&&this.asyncHighlight(i).then(({result:p,options:f})=>{this.renderCache!=null&&(this.renderCache.highlighted=!1),this.onHighlightSuccess(i,p,f,!o)})}return this.renderCache.result!=null?this.processFileResult(this.renderCache.file,e,this.renderCache.result):void 0}async asyncRender(i,e=Z){const{result:t}=await this.asyncHighlight(i);return this.processFileResult(i,e,t)}async asyncHighlight(i){const e=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());this.computedLang=e?"text":i.lang??j(i.name);const t=this.highlighter!=null&&Ct(ft(this.options.theme)),n=e||this.highlighter!=null&&ne(this.computedLang);return(this.highlighter==null||!t||!n)&&(this.highlighter=await this.initializeHighlighter()),this.renderFileWithHighlighter(i,this.highlighter,e)}renderFileWithHighlighter(i,e,t=!1){const{options:n}=this.getRenderOptions(i);return{result:St(i,e,n,{forcePlainText:t}),options:n}}processFileResult(i,e,{code:t,themeStyles:n,baseThemeType:r}){const s=this.getLineCount(i),{disableFileHeader:a=!1}=this.options,o=[],h=ue(),d=Math.min(e.startingLine+e.totalLines,s);let l=0;const c=ve(e)?Be(this.lineAnnotations):void 0;c!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:-1,lineIndex:-1,annotations:c.map(u=>I(u))})),l++);for(let u=e.startingLine;u<d;u++){const p=u+1,f=t[u];if(f==null){const g="FileRenderer.processFileResult: Line doesnt exist";throw console.error(g,{name:i.name,lineIndex:u,lineNumber:p}),new Error(g)}h.children.push(pt("context",p,`${u}`)),o.push(f),l++;const S=this.lineAnnotations[p];S!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:0,lineIndex:p,annotations:S.map(g=>I(g))})),l++)}return h.properties.style=`grid-row: span ${l}`,{gutterAST:h.children??[],contentAST:o,preAST:this.createPreElement(s),headerAST:a?void 0:this.renderHeader(i),totalLines:s,rowCount:l,themeStyles:n,baseThemeType:r,bufferBefore:e.bufferBefore,bufferAfter:e.bufferAfter,css:""}}renderHeader(i){const{headerRenderMode:e="default",stickyHeader:t=!1}=this.options;return De({fileOrDiff:i,mode:e,stickyHeader:t})}renderFullHTML(i){return A(this.renderFullAST(i))}renderFullAST(i,e=[]){return e.push(ce({tagName:"code",children:this.renderCodeAST(i),properties:{"data-code":""}})),{...i.preAST,children:e}}renderCodeAST(i){const e=ue();return e.children=i.gutterAST,e.properties.style=`grid-row: span ${i.rowCount}`,[e,Ue(i.contentAST,i.rowCount)]}renderPartialHTML(i,e=!1){return e?A(ce({tagName:"code",children:i,properties:{"data-code":""}})):A(i)}async initializeHighlighter(){return this.highlighter=await gt(_e(this.computedLang,this.options)),this.highlighter}onHighlightSuccess(i,e,t,n=!0){if(this.renderCache==null)return;const r=!M(i,this.renderCache.file)||!this.renderCache.highlighted||!F(t,this.renderCache.options);this.renderCache={file:i,options:t,highlighted:n,result:e,renderRange:void 0},r&&this.onRenderUpdate?.()}getMatchingWorkerResultCache(i,e){const t=this.workerManager?.getFileResultCache(i);if(!(t==null||!F(e,t.options)))return t}hasHighlightedRenderCache(i,e){const{renderCache:t}=this;return t?.result!=null&&t.highlighted&&M(i,t.file)&&F(e,t.options)}onHighlightError(i){console.error(i)}getTokenizeMaxLength(){return this.options.tokenizeMaxLength??1e5}createPreElement(i){const{disableLineNumbers:e=!1,overflow:t="scroll"}=this.options;return We({type:"file",diffIndicators:"none",disableBackground:!0,disableLineNumbers:e,overflow:t,split:!1,totalLines:i})}};function $(i,e){return i>e}function Tt(i,e){return i.lineNumber===e.lineNumber&&i.metadata===e.metadata}function ge(i){return{theme:i?.theme,disableLineNumbers:i?.disableLineNumbers,overflow:i?.overflow,themeType:i?.themeType,collapsed:i?.collapsed,disableFileHeader:i?.disableFileHeader,disableVirtualizationBuffers:i?.disableVirtualizationBuffers,stickyHeader:i?.stickyHeader,preferredHighlighter:i?.preferredHighlighter,useCSSClasses:i?.useCSSClasses,useTokenTransformer:i?.useTokenTransformer,tokenizeMaxLineLength:i?.tokenizeMaxLineLength,tokenizeMaxLength:i?.tokenizeMaxLength,unsafeCSS:i?.unsafeCSS,headerRenderMode:i?.renderCustomHeader!=null?"custom":"default"}}const bt=[""];let Rt=-1;var Te=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file:${++Rt}`;type="file";fileContainer;spriteSVG;pre;code;bufferBefore;bufferAfter;themeCSSStyle;appliedThemeCSS;hasAdoptedThemeCSS=!1;unsafeCSSStyle;appliedUnsafeCSS;gutterUtilityContent;errorWrapper;placeHolder;lastRenderedHeaderHTML;cachedHeaderHTML;appliedPreAttributes;lastRowCount;mounted=!1;headerElement;headerCustom;headerPrefix;headerFilenameSuffix;headerMetadata;fileRenderer;resizeManager;interactionManager;annotationCache=new Map;lineAnnotations=[];managersDirty=!1;file;renderRange;enabled=!0;editor;constructor(e={theme:H},t,n=!1){this.options=e,this.workerManager=t,this.isContainerManaged=n,this.fileRenderer=new yt(e,this.handleHighlightRender,this.workerManager),this.resizeManager=new Ge,this.interactionManager=new je("file",se(e)),this.workerManager?.subscribeToThemeChanges(this)}handleHighlightRender=()=>{this.rerender()};rerender(){!this.enabled||this.file==null||this.render({file:this.file,forceRender:!0,renderRange:this.renderRange})}onThemeChange(){this.fileRenderer.clearRenderCache(),this.rerender()}setOptions(e){e!=null&&(this.options=e,this.cachedHeaderHTML=void 0,this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(se(this.options))}mergeOptions(e){this.options={...this.options,...e}}setThemeType(e){(this.options.themeType??"system")!==e&&(this.mergeOptions({themeType:e}),this.applyCachedThemeState(e))}applyCachedThemeState(e){if(typeof this.options.theme=="string"||this.fileContainer==null||this.appliedThemeCSS==null)return!1;const t=this.appliedThemeCSS.baseThemeType??e;return this.appliedThemeCSS.themeType===t?!1:(this.applyThemeState(this.fileContainer,this.appliedThemeCSS.themeStyles,e,this.appliedThemeCSS.baseThemeType),!0)}hasThemeChanged(){return this.appliedThemeCSS!=null&&!mt(this.appliedThemeCSS.theme,this.options.theme??H)}getHoveredLine=()=>this.interactionManager.getHoveredLine();setLineAnnotations(e){this.lineAnnotations=e}setSelectedLines(e,t){this.interactionManager.setSelection(e,t)}flushManagers(){if(!this.managersDirty||this.pre==null){this.managersDirty=!1;return}const{overflow:e="scroll"}=this.options;this.interactionManager.setup(this.pre),this.resizeManager.setup(this.pre,e==="wrap"),this.managersDirty=!1}cleanUp(e=!1){this.emitPostRender(!0),this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.isContainerManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,e||(this.lineAnnotations=[]),this.annotationCache.clear(),this.pre=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.lastRenderedHeaderHTML=void 0,e||(this.cachedHeaderHTML=void 0),this.errorWrapper=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.placeHolder=void 0,this.unsafeCSSStyle=void 0,e?this.fileRenderer.recycle():(this.fileRenderer.cleanUp(),this.workerManager=void 0,this.file=void 0),this.enabled=!1,this.editor?.cleanUp(),this.editor=void 0}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate(e){const{fileContainer:t,prerenderedHTML:n,preventEmit:r=!1,file:s,lineAnnotations:a}=e;this.hydrateElements(t,n),Lt(this.pre,s,this.options.collapsed)||Mt(this.headerElement,s,this.options.disableFileHeader)?this.render({...e,preventEmit:!0}):this.hydrationSetup({file:s,lineAnnotations:a}),r||this.emitPostRender()}hydrateElements(e,t){this.fileContainer!==e&&this.emitPostRender(!0),$e(e,t);for(const n of Array.from(e.shadowRoot?.children??[])){if(n instanceof SVGElement){this.spriteSVG=n;continue}if(n instanceof HTMLElement){if(n instanceof HTMLPreElement){this.pre=n,this.appliedPreAttributes=void 0;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-theme-css")){this.themeCSSStyle=n;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-unsafe-css")){this.unsafeCSSStyle=n,this.appliedUnsafeCSS=n.textContent;continue}if("diffsHeader"in n.dataset){this.headerElement=n,this.lastRenderedHeaderHTML=void 0;continue}}}this.pre!=null&&(this.syncCodeNodeFromPre(this.pre),this.pre.removeAttribute("data-dehydrated")),this.fileContainer=e,this.hydrateMeasuredScrollbar()}hydrationSetup({file:e,lineAnnotations:t}){this.lineAnnotations=t??this.lineAnnotations,this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),this.pre!=null&&(this.fileRenderer.hydrate(e),this.renderAnnotations(),this.renderGutterUtility(),this.injectUnsafeCSS(),this.managersDirty=!0,this.flushManagers())}getOrCreateLineCache(e=this.file){return e!=null?this.fileRenderer.getOrCreateLineCache(e):bt}updateBuffers(e){this.pre!=null&&this.applyBuffers(this.pre,e)}syncRenderViewToEditor(){const e=this.editor,t=this.fileContainer,n=this.file;e!=null&&t!=null&&n!=null&&this.fileRenderer.initializeHighlighter().then(r=>{e.__syncRenderView(r,t,n,this.lineAnnotations,this.renderRange)})}attachEditor(e){return this.editor?.cleanUp(),this.editor=e,this.interactionManager.setEditorAttached(!0),this.syncRenderViewToEditor(),()=>{this.editor=void 0,this.interactionManager.setEditorAttached(!1)}}applyDocumentChange(e,t){this.fileRenderer.applyDocumentChange(e),t!=null&&t!==this.lineAnnotations&&this.file!=null&&(this.setLineAnnotations(t),this.fileRenderer.setLineAnnotations(this.lineAnnotations),this.renderAnnotations())}updateRenderCache(e,t){this.fileRenderer.updateRenderCache(e,t)}render({file:e,fileContainer:t,forceRender:n=!1,preventEmit:r=!1,containerWrapper:s,deferManagers:a=!1,lineAnnotations:o,renderRange:h}){if(!this.enabled)throw new Error("File.render: attempting to call render after cleaned up");this.editor?.__postponeBackgroundTokenizeToNextFrame();const{collapsed:d=!1,themeType:l="system"}=this.options,c=d?void 0:h,u=this.renderRange,p=this.hasThemeChanged(),f=o!=null&&(o.length>0||this.lineAnnotations.length>0)?o!==this.lineAnnotations:!1,S=!M(this.file,e);if(!d&&!n&&Se(c,this.renderRange)&&!S&&!f&&!p)return this.applyCachedThemeState(l);this.renderRange=c,S&&(this.cachedHeaderHTML=void 0),this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),o!=null&&this.setLineAnnotations(o),this.fileRenderer.setLineAnnotations(this.lineAnnotations);const{disableErrorHandling:g=!1,disableFileHeader:y=!1}=this.options;if(y&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),t=this.getOrCreateFileContainerNode(t,s),this.applyCachedThemeState(l),d){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const m=this.fileRenderer.renderFile(e,Fe);m!=null&&this.applyThemeState(t,m.themeStyles,l,m.baseThemeType),m?.headerAST!=null&&this.applyHeaderToDOM(m.headerAST,t),this.injectUnsafeCSS()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}try{const m=this.getOrCreatePreNode(t);if(!this.canPartiallyRender(n,f,S||p)||!this.applyPartialRender(u,c)){const v=this.fileRenderer.renderFile(e,c);if(v==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(t,v.themeStyles,l,v.baseThemeType),v.headerAST!=null&&this.applyHeaderToDOM(v.headerAST,t),this.applyFullRender(v,m)}this.applyBuffers(m,c),this.injectUnsafeCSS(),this.managersDirty=!0,a||this.flushManagers(),this.renderAnnotations(),this.renderGutterUtility(),this.editor!=null&&this.syncRenderViewToEditor()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}emitPostRender(e=!1){const{fileContainer:t,options:{onPostRender:n}}=this;if(e){if(!this.mounted||(this.mounted=!1,t==null))return;n?.(t,this,"unmount");return}if(t==null)return;const r=this.mounted?"update":"mount";this.mounted=!0,n?.(t,this,r)}removeRenderedCode(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.code?.remove(),this.code=void 0,this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0}clearAuxiliaryNodes(){for(const{element:e}of this.annotationCache.values())e.remove();this.annotationCache.clear(),this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0}canPartiallyRender(e,t,n){return!(e||t||n)}renderPlaceholder(e){if(this.fileContainer==null)return!1;if(this.emitPostRender(!0),this.cleanChildNodes(),this.placeHolder==null){const t=this.fileContainer.shadowRoot??this.fileContainer.attachShadow({mode:"open"});this.placeHolder=document.createElement("div"),this.placeHolder.dataset.placeholder="",t.appendChild(this.placeHolder)}return this.placeHolder.style.setProperty("height",`${e}px`),!0}primeHighlightCache(){const{file:e,workerManager:t}=this;e==null||e.cacheKey==null||t==null||K(e)||this.fileRenderer.getOrCreateLineCache(e).length>(this.options.tokenizeMaxLength??1e5)||t.primeFileHighlightCache(e)}cleanChildNodes(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.code?.remove(),this.errorWrapper?.remove(),this.headerElement?.remove(),this.gutterUtilityContent?.remove(),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.pre?.remove(),this.spriteSVG?.remove(),this.themeCSSStyle?.remove(),this.unsafeCSSStyle?.remove(),this.bufferAfter=void 0,this.bufferBefore=void 0,this.code=void 0,this.errorWrapper=void 0,this.headerElement=void 0,this.gutterUtilityContent=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.pre=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.lastRenderedHeaderHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderAnnotations(){if(this.isContainerManaged||this.fileContainer==null){for(const{element:n}of this.annotationCache.values())n.remove();this.annotationCache.clear();return}const e=new Map(this.annotationCache),{renderAnnotation:t}=this.options;if(t!=null&&this.lineAnnotations.length>0)for(const[n,r]of this.lineAnnotations.entries()){const s=`${n}-${I(r)}`;let a=this.annotationCache.get(s);if(a==null||!Tt(r,a.annotation)){a?.element.remove();const o=t(r);if(o==null)continue;a={element:qe(I(r)),annotation:r},a.element.appendChild(o),this.fileContainer.appendChild(a.element),this.annotationCache.set(s,a)}e.delete(s)}for(const[n,{element:r}]of e.entries())this.annotationCache.delete(n),r.remove()}renderGutterUtility(){const{renderGutterUtility:e}=this.options;if(this.fileContainer==null||e==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const t=e(this.interactionManager.getHoveredLine);if(t!=null&&this.gutterUtilityContent!=null)return;if(t==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const n=Ke();n.appendChild(t),this.fileContainer.appendChild(n),this.gutterUtilityContent=n}injectUnsafeCSS(){const{unsafeCSS:e}=this.options,t=this.fileContainer?.shadowRoot;if(t!=null){if(e==null||e===""){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}this.unsafeCSSStyle?.parentNode===t&&this.appliedUnsafeCSS===e||(this.unsafeCSSStyle??=Je(),this.unsafeCSSStyle.parentNode!==t&&t.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=Ye(e),this.appliedUnsafeCSS=e)}}applyThemeState(e,t,n,r){const s=e.shadowRoot??e.attachShadow({mode:"open"}),a=r??n,o=this.options.theme??H,h=typeof o=="string"?o:{...o},d=ae(s);if(this.themeCSSStyle?.parentNode===s&&this.appliedThemeCSS?.themeStyles===t&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===d){this.appliedThemeCSS.theme=h;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===s){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:d};return}this.themeCSSStyle=Xe({shadowRoot:s,currentNode:this.themeCSSStyle,themeCSS:Qe(t,a,d)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:d}:void 0}hydrateMeasuredScrollbar(){const e=this.fileContainer?.shadowRoot;e==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=Ze(this.themeCSSStyle.textContent??"",ae(e)))}applyFullRender(e,t){this.cleanupErrorWrapper(),this.applyPreNodeAttributes(t,e),this.code=et({code:this.code});const n=this.fileRenderer.renderCodeAST(e);if(this.code.childElementCount>=2)for(let r=0;r<2;r++){const s=this.code.children[r],a=n[r];s.innerHTML=A(a.children),s.style.cssText=a.properties.style}else this.code.innerHTML=A(n);t.contains(this.code)||t.replaceChildren(this.code),this.lastRowCount=e.rowCount}applyPartialRender(e,t){if(e==null||t==null)return!1;const{file:n,code:r}=this,s=r!=null?this.getColumns(r):void 0;if(n==null||r==null||s==null)return!1;const a=e.startingLine,o=t.startingLine,h=e.totalLines===1/0?Number.POSITIVE_INFINITY:a+e.totalLines,d=t.totalLines===1/0?Number.POSITIVE_INFINITY:o+t.totalLines,l=Math.max(a,o),c=Math.min(h,d);if(c<=l||!this.trimDOMToOverlap(s.gutter,l,c)||!this.trimDOMToOverlap(s.content,l,c))return!1;let{length:u}=s.content.children;const p=(y,m)=>{if(!(m<=0))return this.fileRenderer.renderFile(n,{startingLine:y,totalLines:m,bufferBefore:0,bufferAfter:0})},f=o<l?p(o,l-o):void 0;if(f===void 0&&o<l)return!1;const S=d===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,d-c),g=d>c?p(c,S):void 0;return g===void 0&&d>c?!1:(this.cleanupErrorWrapper(),f!=null&&(s.gutter.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.gutterAST)),s.content.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.contentAST)),u+=f.rowCount),g!=null&&(s.gutter.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.gutterAST)),s.content.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.contentAST)),u+=g.rowCount),this.lastRowCount!==u&&(s.gutter.style.setProperty("grid-row",`span ${u}`),s.content.style.setProperty("grid-row",`span ${u}`),this.lastRowCount=u),!0)}getColumns(e){const t=e.children[0],n=e.children[1];if(!(!(t instanceof HTMLElement)||!(n instanceof HTMLElement)||t.dataset.gutter==null||n.dataset.content==null))return{gutter:t,content:n}}trimDOMToOverlap(e,t,n){const r=this.getDOMBoundaryIndices(e,[t,n]),s=r.get(t)??e.children.length,a=r.get(n)??e.children.length;if(s>a)return!1;for(let o=e.children.length-1;o>=a;o-=1)e.children[o]?.remove();for(let o=s-1;o>=0;o-=1)e.children[o]?.remove();return!0}getDOMBoundaryIndices(e,t){const n=[...new Set(t)].sort((h,d)=>h-d),r=new Map;if(n.length===0)return r;let s=0,a=n[s];const{children:o}=e;a===0&&(r.set(0,0),s+=1,a=n[s]);for(let h=0;h<o.length;h+=1){const d=o[h];if(!(d instanceof HTMLElement))continue;const l=this.getLineIndexFromDOMNode(d);if(l!=null){for(;a!=null&&l>=a;)r.set(a,h),s+=1,a=n[s];if(s>=n.length)break}}for(const h of n)r.has(h)||r.set(h,o.length);return r}getLineIndexFromDOMNode(e){const t=e.dataset.lineIndex;if(t==null)return;const n=Number(t);return Number.isNaN(n)?void 0:n}applyBuffers(e,t){if(t==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}t.bufferBefore>0?(this.bufferBefore==null&&(this.bufferBefore=document.createElement("div"),this.bufferBefore.dataset.virtualizerBuffer="before",e.before(this.bufferBefore)),this.bufferBefore.style.setProperty("height",`${t.bufferBefore}px`),this.bufferBefore.style.setProperty("contain","strict")):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),t.bufferAfter>0?(this.bufferAfter==null&&(this.bufferAfter=document.createElement("div"),this.bufferAfter.dataset.virtualizerBuffer="after",e.after(this.bufferAfter)),this.bufferAfter.style.setProperty("height",`${t.bufferAfter}px`),this.bufferAfter.style.setProperty("contain","strict")):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyHeaderToDOM(e,t){const{file:n}=this;if(n==null)return;this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;const r=this.cachedHeaderHTML??A(e);if(this.cachedHeaderHTML=r,r!==this.lastRenderedHeaderHTML){const d=document.createElement("div");d.innerHTML=r;const l=d.firstElementChild;if(!(l instanceof HTMLElement))return;this.headerElement!=null?t.shadowRoot?.replaceChild(l,this.headerElement):t.shadowRoot?.prepend(l),this.headerElement=l,this.lastRenderedHeaderHTML=r}if(this.isContainerManaged)return;const{renderHeaderPrefix:s,renderHeaderFilenameSuffix:a,renderCustomHeader:o,renderHeaderMetadata:h}=this.options;if(o!=null){const d=o(n)??void 0;this.headerCustom=this.upsertHeaderSlotElement(t,this.headerCustom,Ce,d),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0}else{const d=s?.(n)??void 0,l=a?.(n)??void 0,c=h?.(n)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(t,this.headerPrefix,ke,d),this.headerFilenameSuffix=this.upsertHeaderSlotElement(t,this.headerFilenameSuffix,Ie,l),this.headerMetadata=this.upsertHeaderSlotElement(t,this.headerMetadata,ze,c),this.headerCustom?.remove(),this.headerCustom=void 0}}clearHeaderSlots(){this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0}upsertHeaderSlotElement(e,t,n,r){if(r==null){t?.remove();return}const s=t??this.createHeaderSlotElement(n);return t==null&&e.appendChild(s),this.replaceHeaderSlotContent(s,r),s}replaceHeaderSlotContent(e,t){e.replaceChildren(),t instanceof Element?e.appendChild(t):e.innerText=`${t}`}createHeaderSlotElement(e){const t=document.createElement("div");return t.slot=e,t}getOrCreateFileContainerNode(e,t){const{fileContainer:n}=this,r=e??n??document.createElement("diffs-container"),s=n!==r;return s&&this.emitPostRender(!0),this.fileContainer=r,n!=null&&s&&(this.lastRenderedHeaderHTML=void 0,this.headerElement=void 0),t!=null&&this.fileContainer.parentNode!==t&&t.appendChild(this.fileContainer),s&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(e){const{shadowRoot:t}=e;if(t!=null)for(const n of t.children)n instanceof SVGElement?this.spriteSVG??=n:oe(n)&&n.hasAttribute("data-theme-css")?(this.themeCSSStyle??=n,this.hasAdoptedThemeCSS=!0):oe(n)&&n.hasAttribute("data-unsafe-css")&&(this.unsafeCSSStyle??=n,this.appliedUnsafeCSS??=this.options.unsafeCSS??void 0)}ensureSpriteSVG(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});if(this.spriteSVG==null){const n=document.createElement("div");n.innerHTML=tt;const r=n.firstChild;r instanceof SVGElement&&(this.spriteSVG=r)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==t&&t.appendChild(this.spriteSVG)}getOrCreatePreNode(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});return this.pre==null?(this.pre=document.createElement("pre"),this.appliedPreAttributes=void 0,this.code=void 0,t.appendChild(this.pre)):this.pre.parentNode!==t&&(e.shadowRoot?.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodeFromPre(e){this.code=void 0;for(const t of Array.from(e.children))if(t instanceof HTMLElement&&t.hasAttribute("data-code")){this.code=t;return}}applyPreNodeAttributes(e,{totalLines:t}){const{overflow:n="scroll",disableLineNumbers:r=!1}=this.options,s={type:"file",split:!1,overflow:n,disableLineNumbers:r,diffIndicators:"none",disableBackground:!0,totalLines:t};it(s,this.appliedPreAttributes)||(nt(e,s),this.appliedPreAttributes=s)}applyErrorToDOM(e,t){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;const n=t.shadowRoot??t.attachShadow({mode:"open"});this.errorWrapper??=document.createElement("div"),this.errorWrapper.dataset.errorWrapper="",this.errorWrapper.textContent="",n.appendChild(this.errorWrapper);const r=document.createElement("div");r.dataset.errorMessage="",r.innerText=e.message,this.errorWrapper.appendChild(r);const s=document.createElement("pre");s.dataset.errorStack="",s.innerText=e.stack??"No Error Stack",this.errorWrapper.appendChild(s)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function Lt(i,e,t=!1){return!t&&i==null&&e!=null}function Mt(i,e,t=!1){return i==null&&e!=null&&!t}const Ht=5e3;let At=-1;function xt(i,e){return(i.overflow??"scroll")!==(e.overflow??"scroll")||(i.collapsed??!1)!==(e.collapsed??!1)||(i.disableLineNumbers??!1)!==(e.disableLineNumbers??!1)||(i.disableFileHeader??!1)!==(e.disableFileHeader??!1)||i.unsafeCSS!==e.unsafeCSS}var wt=class extends Te{virtualizer;metrics;__id=`virtualized-file:${++At}`;top;height=0;cache={heights:new Map,checkpoints:[],fileAnnotationHeight:0};isVisible=!1;isSetup=!1;layoutDirty=!0;forceRenderOverride;currentCollapsed;constructor(i,e,t=Ne,n,r=!1){super(i,n,r),this.virtualizer=e,this.metrics=t}setMetrics(i,e=!1){!e&&rt(this.metrics,i)||(this.metrics=i,this.resetLayoutCache())}setLineAnnotations(i){this.syncLineAnnotations(i)&&this.resetLayoutCache()}syncLineAnnotations(i){return i==null||i===this.lineAnnotations||i.length===0&&this.lineAnnotations.length===0?!1:(super.setLineAnnotations(i),!0)}hasLineAnnotations(){return this.lineAnnotations.some(i=>i.lineNumber>0)}getLineHeight(i,e=!1){const t=this.cache.heights.get(i);if(t!=null)return t;const n=e?2:1;return this.metrics.lineHeight*n}setOptions(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setOptions cannot be used inside CodeView. Update CodeView options instead.");if(i==null)return;const{options:e}=this,t=!ye(e,i),n=xt(e,i);super.setOptions(i),n&&this.resetLayoutCache(!0),t&&(this.forceRenderOverride=!0),t&&this.virtualizer.instanceChanged(this,n)}setThemeType(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setThemeType cannot be used inside CodeView. Update CodeView options instead.");super.setThemeType(i)}resetLayoutCache(i=!1){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heights.size>0&&this.cache.heights.clear(),this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.renderRange!=null&&(this.renderRange=void 0),i&&this.isSimpleMode()&&this.computeApproximateSize()}reconcileHeights(){let i=!1;if(this.fileContainer==null||this.file==null)return this.height!==0&&(i=!0),this.height=0,i;const{overflow:e="scroll"}=this.options;if(this.top=this.getVirtualizedTop(),e==="scroll"&&this.lineAnnotations.length===0&&!this.isResizeDebuggingEnabled()||this.code==null)return i;const t=this.code.children[1];if(!(t instanceof HTMLElement))return i;const n=he(this.lineAnnotations);if(this.renderRange!=null&&n&&ve(this.renderRange)){const r=Et(t)??0;r!==this.cache.fileAnnotationHeight&&(this.cache.fileAnnotationHeight=r,i=!0)}else!n&&this.cache.fileAnnotationHeight!==0&&(this.cache.fileAnnotationHeight=0,i=!0);for(const r of t.children){if(!(r instanceof HTMLElement))continue;const s=r.dataset.lineIndex;if(s==null)continue;const a=Number(s);let o=r.getBoundingClientRect().height,h=!1;r.nextElementSibling instanceof HTMLElement&&("lineAnnotation"in r.nextElementSibling.dataset||"noNewline"in r.nextElementSibling.dataset)&&("noNewline"in r.nextElementSibling.dataset&&(h=!0),o+=r.nextElementSibling.getBoundingClientRect().height);const d=this.getLineHeight(a,h);o!==d&&(i=!0,o===this.metrics.lineHeight*(h?2:1)?this.cache.heights.delete(a):this.cache.heights.set(a,o))}return(i||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),i}onRender=i=>this.fileContainer==null||this.file==null?!1:(i&&(this.top=this.getVirtualizedTop()),this.render({file:this.file}));prepareCodeViewItem(i,e,t,n){const r=this.syncLineAnnotations(n);let s=t?.resetFileLayoutCache===!0||r;t?.metrics!=null&&(this.metrics=t.metrics,s=!0);const{collapsed:a=!1}=this.options;return this.currentCollapsed!==a&&(this.currentCollapsed=a,s=!0),s&&this.resetLayoutCache(),this.file!==i&&(this.layoutDirty=!0),this.file=i,this.top=e,this.computeApproximateSize(),this.height}getLinePosition(i){if(this.file==null||i<1)return;const{disableFileHeader:e=!1,collapsed:t=!1}=this.options,n=this.fileRenderer.getLineCount(this.file)-1;let r=B(this.metrics,e);if(t||n<0)return{top:r,height:0};const s=Math.min(Math.max(i-1,0),n),{overflow:a="scroll"}=this.options,{lineHeight:o}=this.metrics;if(r+=this.cache.fileAnnotationHeight,a==="scroll"&&!this.hasLineAnnotations())return{top:r+s*o,height:o};const h=this.getLayoutCheckpointBeforeLineIndex(s);r=h?.top??r;for(let d=h?.lineIndex??0;d<s;d++)r+=this.getLineHeight(d,!1);return{top:r,height:this.getLineHeight(s,!1)}}getNumericScrollAnchor(i){if(this.file==null||this.renderRange==null)return;const{disableFileHeader:e=!1,collapsed:t=!1,overflow:n="scroll"}=this.options;if(t||this.renderRange.totalLines<=0)return;const r=this.fileRenderer.getLineCount(this.file)-1;if(r<0)return;const s=B(this.metrics,e),a=Math.min(this.renderRange.startingLine,r),o=Math.min(a+this.renderRange.totalLines-1,r);if(o<a)return;const{fileAnnotationHeight:h}=this.cache;if(n==="scroll"&&!this.hasLineAnnotations()){const{lineHeight:l}=this.metrics,c=s+(a===0?h:this.renderRange.bufferBefore),u=a+Math.max(Math.ceil((i-c)/l),0);return u>o?void 0:{lineNumber:u+1,top:s+h+u*l}}let d=s+(a===0?h:this.renderRange.bufferBefore);for(let l=a;l<=o;l++){if(d>=i)return{lineNumber:l+1,top:d};d+=this.getLineHeight(l)}}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(i){if(this.top==null||this.file==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};const e=i!=null?this.computeRenderRangeFromWindow(this.file,this.top,i):this.renderRange;if(e==null)return;const{bufferBefore:t,bufferAfter:n,totalLines:r}=e;let s=0;if(r===0){const a=i??this.virtualizer.getWindowSpecs();this.top<a.top&&(s=n)}return{topOffset:this.top+t+s,height:this.height-(t+n)}}cleanUp(i=!1){this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),i||this.resetLayoutCache(),this.isSetup=!1,super.cleanUp(i)}computeApproximateSize(i=!1){const e=this.isResizeDebuggingEnabled();if(!i&&!this.layoutDirty&&!e)return;const t=this.height===0;if(this.height=0,this.cache.checkpoints=[],this.file==null){this.layoutDirty=!1;return}const{disableFileHeader:n=!1,collapsed:r=!1,overflow:s="scroll"}=this.options,{lineHeight:a}=this.metrics,o=this.fileRenderer.getLineCount(this.file),h=B(this.metrics,n),d=fe(this.metrics);if(this.height+=h,r){this.layoutDirty=!1;return}if(this.height+=this.cache.fileAnnotationHeight,s==="scroll"&&!this.hasLineAnnotations())this.height+=o*a;else for(let l=0;l<o;l++)this.addLayoutCheckpoint(l,this.height),this.height+=this.getLineHeight(l,!1);if(o>0&&(this.height+=d),this.fileContainer!=null&&e&&!t){const l=this.fileContainer.getBoundingClientRect();l.height!==this.height?console.log("VirtualizedFile.computeApproximateSize: computed height doesnt match",{name:this.file.name,elementHeight:l.height,computedHeight:this.height}):console.log("VirtualizedFile.computeApproximateSize: computed height IS CORRECT")}this.layoutDirty=!1}setVisibility(i){this.isAdvancedMode()||this.fileContainer==null||(i&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!i&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){!this.enabled||this.file==null||(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!1))}applyDocumentChange(i,e,t=!1){const{heights:n,checkpoints:r}=this.cache,s=this.renderRange;if(super.applyDocumentChange(i,e),this.getSimpleVirtualizer()?.markDOMDirty(),this.layoutDirty=!0,n.size>0&&n.clear(),r.length>0&&(r.length=0),this.isSimpleMode()&&this.computeApproximateSize(),t&&s!==void 0&&this.file!==void 0){const a=this.virtualizer.getWindowSpecs(),o=this.computeRenderRangeFromWindow(this.file,this.top??0,a);o.bufferAfter!==s.bufferAfter&&this.updateBuffers(o)}}render({fileContainer:i,file:e,forceRender:t=!1,lineAnnotations:n,...r}){const s=this.file==null||!M(this.file,e),{forceRenderOverride:a,isSetup:o}=this;this.forceRenderOverride=void 0;const h=this.syncLineAnnotations(n);if(h&&this.resetLayoutCache(),this.file=e,i=this.getOrCreateFileContainerNode(i),this.file==null)return console.error("VirtualizedFile.render: attempting to virtually render when we dont have file"),!1;if(o)this.top??=this.getVirtualizedTop(),s&&this.isSimpleMode()&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache(!0));else{this.computeApproximateSize();const u=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(u==null)throw new Error("VirtualizedFile.render: simple virtualizer is not available");u.connect(i,this),this.isVisible=u.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode())return this.renderPlaceholder(this.height);const d=this.virtualizer.getWindowSpecs(),l=this.top??0,c=this.computeRenderRangeFromWindow(this.file,l,d);return super.render({file:this.file,fileContainer:i,renderRange:c,lineAnnotations:n,forceRender:(a??t)||h,...r})}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}addLayoutCheckpoint(i,e){i%Ht===0&&this.cache.checkpoints.push({lineIndex:i,top:e})}getLayoutCheckpointBeforeLineIndex(i){if(i<=0||this.cache.checkpoints.length===0)return;let e=0,t=this.cache.checkpoints.length-1,n;for(;e<=t;){const r=e+t>>1,s=this.cache.checkpoints[r];if(s==null)throw new Error("VirtualizedFile: invalid checkpoint index");s.lineIndex<=i?(n=s,e=r+1):t=r-1}return n}getLayoutCheckpointBeforeTop(i,e){let t=0,n=this.cache.checkpoints.length-1,r=-1;for(;t<=n;){const s=t+n>>1,a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");a.top<=i?(r=s,t=s+1):n=s-1}if(e==null)return r>=0?this.cache.checkpoints[r]:void 0;for(let s=r;s>=0;s--){const a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");if(a.lineIndex%e===0)return a}}getVirtualizedTop(){return this.virtualizer.type==="advanced"?this.virtualizer.getLocalTopForInstance(this):this.fileContainer!=null?this.virtualizer.getOffsetInScrollContainer(this.fileContainer):0}getSimpleVirtualizer(){return this.virtualizer.type==="simple"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}computeRenderRangeFromWindow(i,e,{top:t,bottom:n}){const{disableFileHeader:r=!1,overflow:s="scroll"}=this.options,{hunkLineCount:a,lineHeight:o}=this.metrics,h=this.fileRenderer.getLineCount(i),d=this.height,l=B(this.metrics,r),c=h>0?fe(this.metrics):0,{fileAnnotationHeight:u}=this.cache,p=l+u,f=Math.max(0,d-l-u-c),S=he(this.lineAnnotations),g=e+l,y=u>0&&S&&g<n&&g+u>t;if(e<t-d||e>n)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};if(h<=a)return{startingLine:0,totalLines:a,bufferBefore:0,bufferAfter:0};const m=Math.ceil(Math.max(n-t,0)/o),v=Math.ceil(m/a)*a+a*2,z=v/a,D=(t+n)/2;if(s==="scroll"&&!this.hasLineAnnotations()){const R=e+p,P=R+f;if(!y&&!(R<n&&P>t))return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};const w=Math.floor(y&&D<e+p?0:(D-(e+p))/o),b=Math.floor(w/a)-Math.floor(z/2),xe=Math.ceil(h/a),E=Math.max(0,Math.min(b,xe))*a,Q=b<0?v+b*a:v,we=E===0?0:u+E*o,Ee=Math.min(Q,h-E);return{startingLine:E,totalLines:Q,bufferBefore:we,bufferAfter:Math.max(0,(h-E-Ee)*o)}}const be=z,N=[],U=this.getLayoutCheckpointBeforeTop(Math.max(0,t-e-v*o*2),a);let T=e+(U?.top??p),_=U?.lineIndex??0,O,V,x;const Re=U?.lineIndex??0;for(let R=Re;R<h;R++){const P=_%a===0,w=Math.floor(_/a);if(P&&(N[w]=T-(e+p),x!=null)){if(x<=0)break;x--}const b=this.getLineHeight(R,!1);T>t-b&&T<n&&(O??=w),T+b>D&&(V??=w),x==null&&T>=n&&P&&(x=be),_++,T+=b}if(O==null)if(y)O=0,V=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};V??=O;const W=Math.round(V-z/2),Le=Math.max(0,Math.ceil(h/a)-z),G=Math.max(0,Math.min(W,Le)),J=G*a,Y=W<0?v+W*a:v,Me=N[G]??0,He=J===0?0:u+Me,X=G+Y/a,Ae=X<N.length?f-N[X]:f-(T-e-p);return{startingLine:J,totalLines:Y,bufferBefore:He,bufferAfter:Math.max(0,Ae)}}};function Et(i){let e;for(const t of i.children)t instanceof HTMLElement&&t.dataset.lineAnnotation===st&&(e=Math.max(e??0,t.getBoundingClientRect().height));return e}function Ft({file:i,renderCustomHeader:e,renderHeaderPrefix:t,renderHeaderFilenameSuffix:n,renderHeaderMetadata:r,renderAnnotation:s,lineAnnotations:a,renderGutterUtility:o,getHoveredLine:h}){const d=e?.(i),l=t?.(i),c=n?.(i),u=r?.(i);return C.jsxs(C.Fragment,{children:[d!=null?C.jsx("div",{slot:Ce,children:d}):C.jsxs(C.Fragment,{children:[l!=null&&C.jsx("div",{slot:"header-prefix",children:l}),c!=null&&C.jsx("div",{slot:"header-filename-suffix",children:c}),u!=null&&C.jsx("div",{slot:"header-metadata",children:u})]}),s!=null&&a?.map((p,f)=>C.jsx("div",{slot:I(p),children:s(p)},f)),o!=null&&C.jsx("div",{slot:"gutter-utility-slot",style:at,children:o(h)})]})}const me=typeof window>"u"?k.useEffect:k.useLayoutEffect;function kt({file:i,options:e,lineAnnotations:t,selectedLines:n,prerenderedHTML:r,metrics:s,hasGutterRenderUtility:a,hasCustomHeader:o,disableWorkerPool:h,contentEditable:d}){const l=ot(),c=n!==void 0,u=k.useContext(ht),p=lt(),f=k.useRef(null),S=dt(g=>{if(g!=null){if(f.current!=null)throw new Error("File: An instance should not already exist when a node is created");l!=null?f.current=new wt(q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),l,s,h?void 0:u,!0):f.current=new Te(q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),h?void 0:u,!0),f.current.hydrate({file:i,fileContainer:g,lineAnnotations:t,prerenderedHTML:r})}else{if(f.current==null)throw new Error("File: A File instance should exist when unmounting");f.current.cleanUp(),f.current=null}});return me(()=>{if(f.current==null)return;const g=q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),y=!ye(f.current.options,g);f.current.setOptions(g),f.current.render({file:i,lineAnnotations:t,forceRender:y}),n!==void 0&&f.current.setSelectedLines(n)}),me(()=>{if(d&&f.current!=null){if(p===void 0)throw new Error("File: Editor is not attached");return p.edit(f.current)}},[d,p]),{ref:S,getHoveredLine:k.useCallback(()=>f.current?.getHoveredLine(),[])}}function q({options:i,controlledSelection:e,contentEditable:t,hasCustomHeader:n,hasEditor:r,hasGutterRenderUtility:s}){const a=t&&r,o=e||s||n;if(!o&&!a)return i;let h={...i};return o&&(h={...h,controlledSelection:e,renderCustomHeader:n?le:i?.renderCustomHeader,renderGutterUtility:s?le:i?.renderGutterUtility}),a&&(h={...h,useTokenTransformer:!0,enableGutterUtility:!1,enableLineSelection:!1,lineHoverHighlight:"disabled"}),h}function _t({file:i,lineAnnotations:e,selectedLines:t,options:n,metrics:r,className:s,style:a,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:d,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c,prerenderedHTML:u,renderGutterUtility:p,disableWorkerPool:f=!1,contentEditable:S=!1}){const{ref:g,getHoveredLine:y}=kt({file:i,options:n,metrics:r,lineAnnotations:e,selectedLines:t,prerenderedHTML:u,hasGutterRenderUtility:p!=null,hasCustomHeader:h!=null,disableWorkerPool:f,contentEditable:S});return C.jsx(Oe,{ref:g,className:s,style:a,children:ct(Ft({file:i,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:d,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c,renderGutterUtility:p,lineAnnotations:e,getHoveredLine:y}),u)})}const Wt=L.memo(function({jsonString:e,className:t,maxHeight:n="100%",initiallyExpandedDepth:r=2}){const s=L.useRef(null),[a,o]=L.useState(null),h=L.useMemo(()=>{try{const c=e.trim();if(!c)return o("Empty JSON content"),null;const u=JSON.parse(c);return o(null),u}catch(c){return o(c instanceof Error?c.message:"Invalid JSON"),null}},[e]),d=L.useCallback(()=>{s.current?.expandAll()},[]),l=L.useCallback(()=>{s.current?.collapseAll()},[]);return a?C.jsx("div",{className:t,children:C.jsxs("div",{className:"rounded-md border border-[var(--interactive-border)] bg-[var(--syntax-base-background)] p-4",children:[C.jsx("div",{className:"mb-1 font-medium text-[var(--surface-foreground)]",children:"Invalid JSON"}),C.jsx("div",{className:"font-mono text-xs text-[var(--surface-mutedForeground)]",children:a})]})}):h===null?null:C.jsxs("div",{className:t,children:[C.jsxs("div",{className:"flex items-center gap-1 border-b border-[var(--interactive-border)] px-2 py-1",children:[C.jsxs(ee,{variant:"ghost",size:"xs",onClick:d,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-down-s",className:"h-3 w-3"}),"Expand all"]}),C.jsxs(ee,{variant:"ghost",size:"xs",onClick:l,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-up-s",className:"h-3 w-3"}),"Collapse all"]})]}),C.jsx("div",{className:"bg-[var(--syntax-base-background)] py-1",style:{maxHeight:n,overflow:"auto"},children:C.jsx(Ve,{ref:s,data:h,maxHeight:n,initiallyExpandedDepth:r})})]})});export{_t as F,Wt as J};