@pi-chamber/web 1.0.4-rc.1 → 1.0.4-rc.2

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 (76) hide show
  1. package/dist/assets/{DiagramView-DfZMQkXY.js → DiagramView-GKGxPczP.js} +1 -1
  2. package/dist/assets/{DiffView-BjWUdbL5.js → DiffView-Cay8VAqL.js} +1 -1
  3. package/dist/assets/{FileSaveConflictDialog-u5L4k_5k.js → FileSaveConflictDialog-BRM9TJo0.js} +1 -1
  4. package/dist/assets/{FilesView-qP1ypN9J.js → FilesView-CEeQzjc6.js} +1 -1
  5. package/dist/assets/{GitHubDetailScaffold-zCKCy5OJ.js → GitHubDetailScaffold-q4YP8iyJ.js} +1 -1
  6. package/dist/assets/{GitHubLinkPicker-CwxKY3lN.js → GitHubLinkPicker-B9xgIW8y.js} +1 -1
  7. package/dist/assets/{GitHubListPrimitives-Ck3zllel.js → GitHubListPrimitives-XkALat1v.js} +1 -1
  8. package/dist/assets/{GitView-y2k2i4gR.js → GitView-DV3d0oSJ.js} +3 -3
  9. package/dist/assets/{IssuesSurface-HWgR87N3.js → IssuesSurface-OTyt9f3A.js} +3 -3
  10. package/dist/assets/{JsonTreeView-DSuC4naV.js → JsonTreeView-X2Auiy_q.js} +1 -1
  11. package/dist/assets/{MarkdownRendererImpl-CT5ln9em.js → MarkdownRendererImpl-1HameF6j.js} +12 -12
  12. package/dist/assets/{PatchDiff-DArTeWeK.js → PatchDiff-GMQAv4en.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-DQKujzLb.js → PierreDiffViewer-0X__nypk.js} +2 -2
  14. package/dist/assets/PullRequestsSurface-Dec20SIg.js +2 -0
  15. package/dist/assets/{SessionSwitcherContent-DEGJyZBl.js → SessionSwitcherContent-DEw4nz7K.js} +1 -1
  16. package/dist/assets/{SessionSwitcherDropdown-cC9wVBH7.js → SessionSwitcherDropdown-DmLhbRzE.js} +2 -2
  17. package/dist/assets/SessionUnreadDot-CJFawQpo.js +1 -0
  18. package/dist/assets/SettingsView-CwSspvq-.js +6 -0
  19. package/dist/assets/{SettingsWindow-CZM1dmVb.js → SettingsWindow-DkPv9MaU.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-DClOSbJc.js → ToolOutputDialog-DDwbOpTO.js} +3 -3
  21. package/dist/assets/{ToolPartDiffPreview-BaFiGUDE.js → ToolPartDiffPreview-DZRP7p-Q.js} +1 -1
  22. package/dist/assets/{VirtualizedFileDiff-D6KbvKc6.js → VirtualizedFileDiff-CUWx7JVZ.js} +1 -1
  23. package/dist/assets/{collapsible-DhV9d4dT.js → collapsible-Ce85nuXX.js} +1 -1
  24. package/dist/assets/{computeVirtualFileMetrics-CeMpF2xC.js → computeVirtualFileMetrics-3PpRLd5B.js} +1 -1
  25. package/dist/assets/{contextFileOpenGuard-Ck5u_kAP.js → contextFileOpenGuard-PoBklHMz.js} +1 -1
  26. package/dist/assets/{gitStatusPredicates-DEBSqUNE.js → gitStatusPredicates-BvzxqidP.js} +1 -1
  27. package/dist/assets/{githubLink-DT7i2NlH.js → githubLink-iQ51wqRa.js} +1 -1
  28. package/dist/assets/{index-eDf4LKLY.js → index-CkMnC_GK.js} +1 -1
  29. package/dist/assets/{index-6IO1AcJI.js → index-Dd2OcIUY.js} +9 -9
  30. package/dist/assets/index-DvN8zlLT.css +1 -0
  31. package/dist/assets/{main-BczEScAA.js → main-FasHq7Ck.js} +2 -2
  32. package/dist/assets/{main-CHLNMYeJ.js → main-PSCt716b.js} +8 -8
  33. package/dist/assets/{markdownCore-C4Gk5Zht.js → markdownCore-BH56o6Wu.js} +1 -1
  34. package/dist/assets/{miniChat-Do3hE87Z.js → miniChat-BzfobBDq.js} +2 -2
  35. package/dist/assets/{mobile-CTnihwfa.js → mobile-DAzZE2EL.js} +2 -2
  36. package/dist/assets/{pi-session-focus-preference-LDVCJ_YR.js → pi-session-focus-preference-D2-1HWmY.js} +3 -3
  37. package/dist/assets/{renderDiffWithHighlighter-CDsgOnkH.js → renderDiffWithHighlighter-l8hZWWBO.js} +1 -1
  38. package/dist/assets/{renderElectronMiniChatApp-DSa3gYqR.js → renderElectronMiniChatApp-DGYSIihR.js} +2 -2
  39. package/dist/assets/{renderFileWithHighlighter-TpKRyfCY.js → renderFileWithHighlighter-BvDoP7ob.js} +1 -1
  40. package/dist/assets/renderMobileApp-CwgWG0lU.js +11 -0
  41. package/dist/assets/runtimeEndpointReset-CmI6dBKM.js +62 -0
  42. package/dist/assets/{runtimeSurface-DW_Ia4q3.js → runtimeSurface-B1GRkkKC.js} +1 -1
  43. package/dist/assets/{useAppFontEffects-CG3_yteE.js → useAppFontEffects--lKKtKVo.js} +62 -62
  44. package/dist/assets/{useFilesViewSearch-C_LzYIgD.js → useFilesViewSearch-D1jsGQrN.js} +3 -3
  45. package/dist/assets/{useGitHubRemoteSearch-DsxWOzKZ.js → useGitHubRemoteSearch-zNgy2bSt.js} +1 -1
  46. package/dist/assets/{useSwitcherItems-BmoCnS9W.js → useSwitcherItems-OCRYcHeu.js} +1 -1
  47. package/dist/assets/{web-components-CH3-XV-n.js → web-components-v9fuidaX.js} +1 -1
  48. package/dist/index.html +4 -4
  49. package/dist/mini-chat.html +3 -3
  50. package/dist/mobile.html +3 -3
  51. package/package.json +2 -2
  52. package/server/lib/pi/session-daemon/DOCUMENTATION.md +21 -8
  53. package/server/lib/pi/session-daemon/builtin-extensions.js +37 -0
  54. package/server/lib/pi/session-daemon/daemon-process.js +6 -0
  55. package/server/lib/pi/session-daemon/extension-theme.js +75 -0
  56. package/server/lib/pi/session-daemon/extension-theme.test.js +47 -0
  57. package/server/lib/pi/session-daemon/prompt-operations.test.js +3 -3
  58. package/server/lib/pi/session-daemon/prompt-preflight.test.js +12 -14
  59. package/server/lib/pi/session-daemon/sdk-upgrade.test.js +118 -2
  60. package/server/lib/pi/session-daemon/send-operation-dedup.test.js +1 -1
  61. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +1 -1
  62. package/server/lib/pi/session-daemon/session-daemon-mcp.e2e.test.js +638 -0
  63. package/server/lib/pi/session-daemon/session-daemon-turn.e2e.test.js +437 -0
  64. package/server/lib/pi/session-daemon/session-daemon.js +61 -42
  65. package/server/lib/pi/session-daemon/session-daemon.test.js +53 -5
  66. package/server/lib/pi/session-daemon/session-idle-residency.test.js +1 -1
  67. package/server/lib/pi/session-daemon/session-replay.test.js +1 -1
  68. package/server/lib/pi/session-persistence-gap.test.js +2 -3
  69. package/server/lib/pi/ui-settings-store.js +1 -0
  70. package/server/lib/pi/ui-settings-store.test.js +27 -0
  71. package/dist/assets/PullRequestsSurface-Cfb1wSvC.js +0 -2
  72. package/dist/assets/SessionUnreadDot-CELKNVIM.js +0 -1
  73. package/dist/assets/SettingsView-CZvRRgJe.js +0 -6
  74. package/dist/assets/index-BAmzAlNx.css +0 -1
  75. package/dist/assets/renderMobileApp-CPE-3uMl.js +0 -11
  76. package/dist/assets/runtimeEndpointReset-CzJfovWI.js +0 -62
@@ -1,7 +1,7 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-6IO1AcJI.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-react-DASdDPIk.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BAmzAlNx.css"])))=>i.map(i=>d[i]);
2
- import{j as t}from"./vendor-boot-DyL2td56.js";import{R as u}from"./vendor-react-DASdDPIk.js";import{i as Pe,j as ot,p as lt,l as it,m as ct,r as ut,b as dt,c as mt,G as ht,h as Ne,u as ft,n as bt,o as gt}from"./useGitHubRemoteSearch-DsxWOzKZ.js";import{a4 as pt,B as j,I as R,ak as xt,al as yt,am as vt,an as Ct,ao as jt,ap as wt,p as $e,f as kt,t as P,cH as St,o as ye,ai as Oe,a8 as Re,ab as Le,ad as Ee,cu as Nt,cv as Rt,af as pe,ag as Lt,n as Et}from"./useAppFontEffects-CG3_yteE.js";import{ad as It,ae as Ie,af as xe,ag as Ae,ah as ce,ai as At,aj as ue,R as Dt,Z as _e,a3 as Gt,a0 as Tt,ak as Ht}from"./runtimeEndpointReset-CzJfovWI.js";import{_ as Bt}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as Ft,d as Mt}from"./vendor-zustand-CUi8eEds.js";import{v as Ue,A as zt}from"./index-6IO1AcJI.js";import{a as Ke,u as Pt,p as $t,r as Ot,t as De,x as _t,z as Ut,A as Kt,w as ie,y as Wt,B as oe,C as We,D as qt,R as Vt,E as Ge,G as Qt,H as Jt,I as Zt,J as Yt,K as Te}from"./GitHubDetailScaffold-zCKCy5OJ.js";import{I as He,a as Xt,b as es,i as qe,c as ts,d as ss,s as as,g as le,e as ns,f as rs,h as Be,j as Fe,C as os,k as ls,v as is}from"./githubLink-DT7i2NlH.js";import{a as cs,b as us}from"./GitHubListPrimitives-Ck3zllel.js";import"./vendor-clsx-B-dksMZM.js";import"./runtimeSurface-DW_Ia4q3.js";import"./SessionUnreadDot-CELKNVIM.js";/* empty css */import"./permissionStore-B9Hkrqny.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-dompurify-r8glNMJW.js";const ve={state:"open",involvement:"all",labels:"",search:"",sort:"updated"},ds=3e4,ms=100,hs=50,Ve=(e,s)=>ue([e,"issues-collection",s]),Qe=(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"?C.setState(s=>{const n={filtersByScope:s.filtersByScope,selectionByDirectory:s.selectionByDirectory};return e(n)}):C.setState(e)},get:()=>{const e=C.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},g=At({openCollection:"open",closedCollection:"closed",defaultFilters:ve,freshWindowMs:ds,serverKind:"issues",errorFallback:"Issue request failed",collectionKeyFor:Ve,remoteKeyFor:Qe,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),C=Ft()(Mt((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(p=>({actingActions:{...p.actingActions,[b]:!0},actionErrorByDetail:{...p.actionErrorByDetail,[b]:null}}));const c=g.resources.details.getEntry(o)?.data?.detail??null,y=c?.issue??null,w=y?{...y,title:a.title??y.title,body:a.body??y.body,state:a.state??y.state,stateReason:a.state!==void 0?a.stateReason??null:y.stateReason,labels:a.labels!==void 0?a.labels.map(p=>({name:p})):y.labels,assignees:a.assignees!==void 0?a.assignees.map(p=>({login:p})):y.assignees}:null;w&&c&&await g.resources.details.refresh(o,async()=>({detail:{...c,issue:w}})).catch(()=>null);try{return await d.issueUpdate(n,r,l,a),await xe(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(p=>({actingActions:{...p.actingActions,[b]:!1}})),{ok:!0}}catch(p){const S=g.toStoreError(p);return c&&await g.resources.details.refresh(o,async()=>({detail:c})).catch(()=>null),e(f=>({actingActions:{...f.actingActions,[b]:!1},actionErrorByDetail:{...f.actionErrorByDetail,[b]:S}})),{ok:!1,error:S}}},addComment:async(n,r,l,a,d)=>{const b=Ae(r,l),o=je(r,l),c=a.trim(),y={id:-Date.now(),url:"",body:c,author:null,createdAt:new Date().toISOString(),updatedAt:null},w=g.resources.comments.getEntry(o)?.data??null;if(w){const p={comments:[...w.comments,y],nextCursor:w.nextCursor,fetchedAt:w.fetchedAt};await g.resources.comments.refresh(o,async()=>p).catch(()=>null)}try{return await d.issueComment(n,r,l,c),await xe(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(p){const S=g.toStoreError(p);return w?await g.resources.comments.refresh(o,async()=>w).catch(()=>null):g.resources.comments.remove(o),e(f=>({actionErrorByDetail:{...f.actionErrorByDetail,[b]:S}})),{ok:!1,error:S}}},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 xe(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=Ue((n||"").trim());if(!r)return;const l=s().selectionByDirectory[r];!l?.repo||typeof l.number!="number"||(g.markCollectionsStale(l.repo),Bt(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-6IO1AcJI.js").then(d=>d.cv);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([0,1,2,3,4,5,6])).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"&&zt(()=>{C.getState().resetForRuntimeSwitch()});const ps=e=>g.getLocalIndex(e),xs=(e,s)=>g.getLocalIndex(e).find(n=>n.number===s)??null,Me=(e,s)=>ce(g.resources.collections,e?Ve(e,s):null),ys=(e,s)=>ce(g.resources.remote,e?Qe(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)=>C(n=>!e||!s?ve:n.filtersByScope[It(e,s)]??ve),ws=e=>C(s=>e?s.selectionByDirectory[Ue(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,countComplete:o=!0,incompleteNotice:c=null,remote:y=null,numberJump:w=null,onFiltersChange:p,onClearFilters:S,onLoadMore:f,onRetry:x,onOpen:N,onNewIssue:k,headerActionsSlot:T=null,headerActionsPresentation:H="drawer"})=>{const z=b.state==="open"&&b.involvement==="all"&&!b.search.trim()&&!b.labels.trim(),{isMobile:D,isTablet:I}=pt(),B=D||I,G=T!=null,A=H??"drawer",$=G?A==="desktop"?t.jsxs(j,{type:"button",variant:"ghost",size:"sm",onClick:k,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-4"}),"New issue"]}):t.jsxs(j,{type:"button",variant:"ghost",size:"default",onClick:k,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-4"}),"New issue"]}):t.jsxs(j,{type:"button",variant:"ghost",size:B?"sm":"xs",onClick:k,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-3.5"}),"New issue"]}),O=u.useCallback(h=>t.jsx("li",{role:"listitem",children:t.jsx(Pe,{glyph:t.jsx(Ke,{kind:"issue",state:h.state}),number:`#${h.number}`,title:h.title,signals:ks(h.comments),meta:t.jsxs(t.Fragment,{children:[t.jsx(ot,{login:h.author?.login,avatarUrl:h.author?.avatarUrl}),t.jsx(lt,{labels:h.labels??[]})]}),updatedAt:h.updatedAt,onOpen:()=>N(h.number),ariaLabel:`Open issue #${h.number} ${h.title}`})},h.number),[N]);return t.jsx(it,{items:e,renderRow:O,hasMore:s,isLoadingMore:n,isLoading:r,isRefreshing:l,stale:a,error:d,searchValue:b.search,onSearchChange:h=>p({search:h}),searchPlaceholder:"Search issues, or label:bug",searchAriaLabel:"Search issues",toolbarControls:t.jsx(ct,{stateValue:b.state,stateOptions:He.map(h=>({id:h.id,label:h.label})),onStateChange:h=>p({state:h}),involvementValue:b.involvement,involvementOptions:es.map(h=>({id:h.id,label:h.label})),onInvolvementChange:h=>p({involvement:h}),labelsValue:b.labels,onLabelsChange:h=>p({labels:h}),sortValue:b.sort,sortOptions:Xt.map(h=>({id:h.id,label:h.label})),onSortChange:h=>p({sort:h}),sortAriaLabel:"Sort issues"}),primaryAction:$,headerActionsSlot:T,headerActionsPresentation:A,isDefaultFilters:z,stateLabel:He.find(h=>h.id===b.state)?.label??b.state,kindSingular:"issue",kindPlural:"issues",noItemsTitle:b.state==="open"?"No open issues":"No issues yet",noItemsBody:"Issues for this repository appear here.",noItemsIcon:"inbox-archive",noItemsAction:t.jsxs(j,{type:"button",variant:"outline",size:"sm",onClick:k,children:[t.jsx(R,{name:"add",className:"size-3.5"}),"New issue"]}),listAriaLabel:"Issues",skeletonLabel:"Loading issues",updatedAtOf:h=>h.updatedAt,countComplete:o,incompleteNotice:c,remote:y,numberJump:w,numberJumpKind:"issue",onClearFilters:S,onLoadMore:f,onRetry:x,onOpen:N})},Je=(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(y=>{c||(l(y.labels??[]),d(y.assignees??[]))}).catch(()=>{c||(l([]),d([]))}).finally(()=>{c||o(!1)}),()=>{c=!0}},[n,e,s]),{labels:r,assignees:a,loading:b}},Ze=(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(j,{type:"button",variant:"chip",size:"xs","aria-pressed":a,onClick:()=>r(Ze(n,l.name)),children:l.name},l.name)})}),Xe=({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(j,{type:"button",variant:"chip",size:"xs","aria-pressed":d,onClick:()=>{a&&r(Ze(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=qe(n,r);return t.jsx(xt,{open:e,onOpenChange:s,children:t.jsxs(yt,{className:"max-w-md w-[calc(100vw-2rem)]",children:[t.jsxs(vt,{children:[t.jsxs(Ct,{children:["Start session from issue #",n]}),t.jsx(jt,{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(wt,{children:[t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:()=>s(!1),disabled:l,children:"Cancel"}),t.jsx(j,{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"})]})]})})},ze=e=>{const s=as(e.title);return e.kind==="pr"?`pr-${e.number}-${s}`:qe(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-Dd2OcIUY.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-react-DASdDPIk.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-DvN8zlLT.css"])))=>i.map(i=>d[i]);
2
+ import{j as t}from"./vendor-boot-DyL2td56.js";import{R as u}from"./vendor-react-DASdDPIk.js";import{i as Pe,j as ot,p as lt,l as it,m as ct,r as ut,b as dt,c as mt,G as ht,h as Ne,u as ft,n as bt,o as gt}from"./useGitHubRemoteSearch-zNgy2bSt.js";import{a4 as xt,B as j,I as R,ak as pt,al as yt,am as vt,an as Ct,ao as jt,ap as wt,p as $e,f as kt,t as P,cH as St,o as ye,ai as Oe,a8 as Re,ab as Le,ad as Ee,cu as Nt,cv as Rt,af as xe,ag as Lt,n as Et}from"./useAppFontEffects--lKKtKVo.js";import{ae as It,af as Ie,ag as pe,ah as Ae,ai as ce,aj as At,ak as ue,U as Dt,_ as _e,a4 as Gt,a1 as Tt,al as Ht}from"./runtimeEndpointReset-CmI6dBKM.js";import{_ as Bt}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as Ft,d as Mt}from"./vendor-zustand-CUi8eEds.js";import{v as Ue,A as zt}from"./index-Dd2OcIUY.js";import{a as Ke,u as Pt,p as $t,r as Ot,t as De,x as _t,z as Ut,A as Kt,w as ie,y as Wt,B as oe,C as We,D as qt,R as Vt,E as Ge,G as Qt,H as Jt,I as Yt,J as Zt,K as Te}from"./GitHubDetailScaffold-q4YP8iyJ.js";import{I as He,a as Xt,b as es,i as qe,c as ts,d as ss,s as as,g as le,e as ns,f as rs,h as Be,j as Fe,C as os,k as ls,v as is}from"./githubLink-iQ51wqRa.js";import{a as cs,b as us}from"./GitHubListPrimitives-XkALat1v.js";import"./vendor-clsx-B-dksMZM.js";import"./runtimeSurface-B1GRkkKC.js";import"./SessionUnreadDot-CJFawQpo.js";/* empty css */import"./permissionStore-B9Hkrqny.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-dompurify-r8glNMJW.js";const ve={state:"open",involvement:"all",labels:"",search:"",sort:"updated"},ds=3e4,ms=100,hs=50,Ve=(e,s)=>ue([e,"issues-collection",s]),Qe=(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"?C.setState(s=>{const n={filtersByScope:s.filtersByScope,selectionByDirectory:s.selectionByDirectory};return e(n)}):C.setState(e)},get:()=>{const e=C.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},g=At({openCollection:"open",closedCollection:"closed",defaultFilters:ve,freshWindowMs:ds,serverKind:"issues",errorFallback:"Issue request failed",collectionKeyFor:Ve,remoteKeyFor:Qe,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),C=Ft()(Mt((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(x=>({actingActions:{...x.actingActions,[b]:!0},actionErrorByDetail:{...x.actionErrorByDetail,[b]:null}}));const c=g.resources.details.getEntry(o)?.data?.detail??null,y=c?.issue??null,w=y?{...y,title:a.title??y.title,body:a.body??y.body,state:a.state??y.state,stateReason:a.state!==void 0?a.stateReason??null:y.stateReason,labels:a.labels!==void 0?a.labels.map(x=>({name:x})):y.labels,assignees:a.assignees!==void 0?a.assignees.map(x=>({login:x})):y.assignees}:null;w&&c&&await g.resources.details.refresh(o,async()=>({detail:{...c,issue:w}})).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(x=>({actingActions:{...x.actingActions,[b]:!1}})),{ok:!0}}catch(x){const S=g.toStoreError(x);return c&&await g.resources.details.refresh(o,async()=>({detail:c})).catch(()=>null),e(f=>({actingActions:{...f.actingActions,[b]:!1},actionErrorByDetail:{...f.actionErrorByDetail,[b]:S}})),{ok:!1,error:S}}},addComment:async(n,r,l,a,d)=>{const b=Ae(r,l),o=je(r,l),c=a.trim(),y={id:-Date.now(),url:"",body:c,author:null,createdAt:new Date().toISOString(),updatedAt:null},w=g.resources.comments.getEntry(o)?.data??null;if(w){const x={comments:[...w.comments,y],nextCursor:w.nextCursor,fetchedAt:w.fetchedAt};await g.resources.comments.refresh(o,async()=>x).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(x){const S=g.toStoreError(x);return w?await g.resources.comments.refresh(o,async()=>w).catch(()=>null):g.resources.comments.remove(o),e(f=>({actionErrorByDetail:{...f.actionErrorByDetail,[b]:S}})),{ok:!1,error:S}}},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=Ue((n||"").trim());if(!r)return;const l=s().selectionByDirectory[r];!l?.repo||typeof l.number!="number"||(g.markCollectionsStale(l.repo),Bt(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-Dd2OcIUY.js").then(d=>d.cx);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([0,1,2,3,4,5,6])).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"&&zt(()=>{C.getState().resetForRuntimeSwitch()});const xs=e=>g.getLocalIndex(e),ps=(e,s)=>g.getLocalIndex(e).find(n=>n.number===s)??null,Me=(e,s)=>ce(g.resources.collections,e?Ve(e,s):null),ys=(e,s)=>ce(g.resources.remote,e?Qe(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)=>C(n=>!e||!s?ve:n.filtersByScope[It(e,s)]??ve),ws=e=>C(s=>e?s.selectionByDirectory[Ue(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,countComplete:o=!0,incompleteNotice:c=null,remote:y=null,numberJump:w=null,onFiltersChange:x,onClearFilters:S,onLoadMore:f,onRetry:p,onOpen:N,onNewIssue:k,headerActionsSlot:T=null,headerActionsPresentation:H="drawer"})=>{const z=b.state==="open"&&b.involvement==="all"&&!b.search.trim()&&!b.labels.trim(),{isMobile:D,isTablet:I}=xt(),B=D||I,G=T!=null,A=H??"drawer",$=G?A==="desktop"?t.jsxs(j,{type:"button",variant:"ghost",size:"sm",onClick:k,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-4"}),"New issue"]}):t.jsxs(j,{type:"button",variant:"ghost",size:"default",onClick:k,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-4"}),"New issue"]}):t.jsxs(j,{type:"button",variant:"ghost",size:B?"sm":"xs",onClick:k,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-3.5"}),"New issue"]}),O=u.useCallback(h=>t.jsx("li",{role:"listitem",children:t.jsx(Pe,{glyph:t.jsx(Ke,{kind:"issue",state:h.state}),number:`#${h.number}`,title:h.title,signals:ks(h.comments),meta:t.jsxs(t.Fragment,{children:[t.jsx(ot,{login:h.author?.login,avatarUrl:h.author?.avatarUrl}),t.jsx(lt,{labels:h.labels??[]})]}),updatedAt:h.updatedAt,onOpen:()=>N(h.number),ariaLabel:`Open issue #${h.number} ${h.title}`})},h.number),[N]);return t.jsx(it,{items:e,renderRow:O,hasMore:s,isLoadingMore:n,isLoading:r,isRefreshing:l,stale:a,error:d,searchValue:b.search,onSearchChange:h=>x({search:h}),searchPlaceholder:"Search issues, or label:bug",searchAriaLabel:"Search issues",toolbarControls:t.jsx(ct,{stateValue:b.state,stateOptions:He.map(h=>({id:h.id,label:h.label})),onStateChange:h=>x({state:h}),involvementValue:b.involvement,involvementOptions:es.map(h=>({id:h.id,label:h.label})),onInvolvementChange:h=>x({involvement:h}),labelsValue:b.labels,onLabelsChange:h=>x({labels:h}),sortValue:b.sort,sortOptions:Xt.map(h=>({id:h.id,label:h.label})),onSortChange:h=>x({sort:h}),sortAriaLabel:"Sort issues"}),primaryAction:$,headerActionsSlot:T,headerActionsPresentation:A,isDefaultFilters:z,stateLabel:He.find(h=>h.id===b.state)?.label??b.state,kindSingular:"issue",kindPlural:"issues",noItemsTitle:b.state==="open"?"No open issues":"No issues yet",noItemsBody:"Issues for this repository appear here.",noItemsIcon:"inbox-archive",noItemsAction:t.jsxs(j,{type:"button",variant:"outline",size:"sm",onClick:k,children:[t.jsx(R,{name:"add",className:"size-3.5"}),"New issue"]}),listAriaLabel:"Issues",skeletonLabel:"Loading issues",updatedAtOf:h=>h.updatedAt,countComplete:o,incompleteNotice:c,remote:y,numberJump:w,numberJumpKind:"issue",onClearFilters:S,onLoadMore:f,onRetry:p,onOpen:N})},Je=(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(y=>{c||(l(y.labels??[]),d(y.assignees??[]))}).catch(()=>{c||(l([]),d([]))}).finally(()=>{c||o(!1)}),()=>{c=!0}},[n,e,s]),{labels:r,assignees:a,loading:b}},Ye=(e,s)=>e.includes(s)?e.filter(n=>n!==s):[...e,s],Ze=({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(j,{type:"button",variant:"chip",size:"xs","aria-pressed":a,onClick:()=>r(Ye(n,l.name)),children:l.name},l.name)})}),Xe=({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(j,{type:"button",variant:"chip",size:"xs","aria-pressed":d,onClick:()=>{a&&r(Ye(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=qe(n,r);return t.jsx(pt,{open:e,onOpenChange:s,children:t.jsxs(yt,{className:"max-w-md w-[calc(100vw-2rem)]",children:[t.jsxs(vt,{children:[t.jsxs(Ct,{children:["Start session from issue #",n]}),t.jsx(jt,{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(wt,{children:[t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:()=>s(!1),disabled:l,children:"Cancel"}),t.jsx(j,{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"})]})]})})},ze=e=>{const s=as(e.title);return e.kind==="pr"?`pr-${e.number}-${s}`:qe(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(p){return{ok:!1,error:p instanceof Error?p.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}),y=[{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:y}),{ok:!0,directory:e.directory};if(!r?.getGitBranches||!r?.createGitWorktree)return{ok:!1,error:"Worktree creation is not available in this runtime"};let w,p=!1;try{const x=await r.getGitBranches(e.directory);if(w=x.current?.trim()??"",!w)throw new Error("no current branch");p=Array.isArray(x.all)&&x.all.includes(ze(e))}catch{return{ok:!1,error:"Could not determine the current branch to start the worktree from"}}const S=ze(e);let f;try{if(p){let x=null;if(r.listGitWorktrees)try{const N=await r.listGitWorktrees(e.directory);x=Array.isArray(N)?N.find(k=>!k?.prunable&&k?.branch===S)?.path??null:null}catch{x=null}if(x)f=x;else if(f=(await r.createGitWorktree(e.directory,{mode:"existing",existingBranch:S})).path,!f)throw new Error("worktree path missing")}else if(f=(await r.createGitWorktree(e.directory,{mode:"new",startRef:w,branchName:S})).path,!f)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:f,title:o,initialPrompt:c,syntheticParts:y}),{ok:!0,directory:f}},Ls=()=>{const e=$e(),s=kt(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=>ut(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(We,{login:e.author?.login,avatarUrl:e.author?.avatarUrl,size:"xs"}),e.author?.login??"ghost"]}),e.createdAt?` · opened ${Te(e.createdAt)}`:"",e.updatedAt&&e.updatedAt!==e.createdAt?` · updated ${Te(e.updatedAt)}`:""]}),Is=({number:e,closed:s,closeReason:n,onCloseReasonChange:r,closeAllowed:l,closeReasonText:a,reopenAllowed:d,reopenReasonText:b,acting:o,onStateAction:c,askSending:y,onAskAgent:w,onEditTitle:p,editAllowed:S,editReasonText:f,onCopyLink:x,url:N})=>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:Fe("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:Fe(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(j,{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(Nt,{value:n,onValueChange:k=>r(k),children:os.map(k=>t.jsx(Rt,{value:k.id,children:k.id==="completed"?"Close as completed":"Close as not planned"},k.id))})})]})]}),t.jsxs(j,{type:"button",variant:"outline",size:"xs",className:"shrink-0",onClick:w,disabled:y,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"}),y?"Asking…":"Ask agent"]}),t.jsxs(j,{type:"button",variant:"ghost",size:"xs",className:"shrink-0",onClick:()=>{ye(N)},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(j,{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(pe,{onClick:p,disabled:!S,title:f??"Edit title",children:[t.jsx(R,{name:"pencil",className:"size-3.5"}),"Edit title"]}),t.jsx(Lt,{}),t.jsxs(pe,{onClick:()=>{ye(N)},children:[t.jsx(R,{name:"external-link",className:"size-3.5"}),"Open on GitHub"]}),t.jsxs(pe,{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=C(i=>i.updateIssue),b=C(i=>i.addComment),o=C(i=>i.actionErrorByDetail[`${n}#${r}`]??null),c=C(i=>i.actingActions[`${n}#${r}`]??!1),{start:y,startingKey:w}=Ls(),p=Pt(s,n),[S,f]=u.useState("completed"),[x,N]=u.useState(!1),[k,T]=u.useState(""),[H,z]=u.useState(!1),[D,I]=u.useState(""),[B,G]=u.useState(!1),[A,$]=u.useState([]),[O,h]=u.useState([]),{draft:v,onDraftChange:L,flushDraft:_}=dt(n,r),{busy:W,error:de,submit:X}=mt({postComment:i=>b(s,n,r,i,l),runFollowUp:i=>d(s,n,r,Be(i==="reopen"?"reopen":S==="not_planned"?"close-not-planned":"close-completed"),l),verbs:{close:"close",reopen:"reopen"},doneLabels:{close:"Closed with comment",reopen:"Reopened with comment"},afterPost:()=>{L(""),ft.getState().clearCommentDraft(n,r)}}),[Q,me]=u.useState("newest"),[he,J]=u.useState(!1),[Z,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),M=le("edit",a,U),te=le("labels",a,U),se=le("comment",a,U),ae=St(s),Y=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=>{Y.has(i.repoRef.toLowerCase())?Dt(s,i.repoRef,i.number):ye(i.url)},[s,Y]),{labels:q,assignees:et,loading:we}=Je(s,n,l),ne=i=>{a&&(i==="title"?(T(a.title),N(!0)):i==="body"?(I(a.body??""),z(!0)):($((a.labels??[]).map(E=>E.name)),h((a.assignees??[]).map(E=>E.login).filter(Boolean)),G(!0)))},fe=u.useCallback(async i=>{const E=await d(s,n,r,i,l);return E.ok?(N(!1),z(!1),G(!1),!0):(P.error(E.error?.kind==="failed"?E.error.message:"Update failed"),!1)},[d,s,n,r,l]),tt=u.useCallback(async i=>{const E=Be(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]),st=Ot(a?.url),at=u.useCallback(async()=>{if(!(!a||Z)){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,Z,l,s,n,r]),K=u.useMemo(()=>{const i=[...e.comments];return Q==="newest"&&i.reverse(),i},[e.comments,Q]),nt=u.useMemo(()=>K.filter(i=>!De(i.author?.login)),[K]),rt=u.useMemo(()=>K.filter(i=>De(i.author?.login)),[K]),ke=a?.state==="closed",Se=w!==null,V=a??(e.seed&&e.seed.number===r?e.seed:null),be=t.jsxs(t.Fragment,{children:[t.jsx(_t,{onBack:e.onBack,backLabel:"Back to issues",repoName:p,number:r,url:V?.url,numberTintClass:Kt("issue",V?.state??"open",!1,a?.stateReason),statePill:V?t.jsx(Ut,{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:M.allowed?null:M.reason,meta:V?t.jsx(Es,{issue:V}):void 0,primary:a?t.jsxs(j,{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:S,onCloseReasonChange:f,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=>tt(i),askSending:Z,onAskAgent:()=>{at()},onEditTitle:()=>ne("title"),editAllowed:M.allowed,editReasonText:M.reason,onCopyLink:st,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(j,{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(Wt,{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(Oe,{value:k,onChange:i=>T(i.target.value),"aria-label":"Issue title",className:"h-7"}),t.jsx(j,{type:"button",variant:"default",size:"xs",onClick:()=>{fe({title:k})},disabled:c||!k.trim(),children:"Save"}),t.jsx(j,{type:"button",variant:"ghost",size:"xs",onClick:()=>N(!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(We,{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(qt,{name:i.name,color:i.color},i.name)),t.jsx(j,{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(j,{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=Y.has(i.repoRef.toLowerCase());return t.jsx("li",{children:t.jsx(Pe,{glyph:t.jsx(Ke,{kind:"pr",state:i.state,draft:i.draft}),number:`#${i.number}`,title:i.title||"(no title)",meta:t.jsxs("span",{className:"truncate",children:[Vt(i.repoRef),E?"":" · GitHub"]}),onOpen:()=>m(i),ariaLabel:`Open linked pull request #${i.number}: ${i.title}`})},`${i.repoRef}#${i.number}`)})})})}),B?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:A,onChange:$}),t.jsx("p",{className:"typography-micro font-medium text-muted-foreground",children:"Assignees"}),t.jsx(Xe,{candidates:et,loading:we,selected:O,onChange:h}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(j,{type:"button",size:"sm",onClick:()=>{fe({labels:A,assignees:O})},disabled:c,children:"Save"}),t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:()=>G(!1),disabled:c,children:"Cancel"})]})]}):null]}),t.jsx(Ge,{id:`issue-${r}-description`,title:"Description",action:H?void 0:t.jsx(j,{type:"button",variant:"ghost",size:"xs",onClick:()=>ne("body"),"aria-label":"Edit issue body",title:M.reason??"Edit issue body",disabled:!M.allowed,children:"Edit"}),children:H?t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(_e,{value:D,onChange:i=>I(i.target.value),"aria-label":"Issue body",rows:6}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(j,{type:"button",size:"sm",onClick:()=>{fe({body:D})},disabled:c,children:"Save"}),t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:()=>z(!1),disabled:c,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(Qt,{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(Ge,{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."}):nt.map(i=>t.jsx(Jt,{comment:i},i.id)),t.jsx(Zt,{comments:rt}),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(ht,{draft:v,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,v)},allowed:F.allowed,reason:F.reason},onSubmitComment:()=>{X("comment",v)}}):null]})})]}),a?t.jsx(Ns,{open:he,onOpenChange:J,issueNumber:r,issueTitle:a.title,busy:Se,onChoose:i=>{J(!1),y({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=C(v=>v.createIssue),[d,b]=u.useState(""),[o,c]=u.useState(""),[y,w]=u.useState([]),[p,S]=u.useState([]),[f,x]=u.useState(""),[N,k]=u.useState([]),[T,H]=u.useState(null),{labels:z,assignees:D,loading:I}=Je(e,s,n),[B,G]=u.useState(!1),[A,$]=u.useState({});u.useEffect(()=>{let v=!1;return n.issueTemplates(e,s).then(L=>{v||(k(L.templates),H(L.templates.length===0?"No markdown templates in this repository. YAML issue forms are not supported.":null))}).catch(()=>{v||H("Issue templates are unavailable.")}),()=>{v=!0}},[n,e,s]);const O=v=>{if(x(v),!v)return;const L=N.find(_=>_.filename===v);L&&c(_=>ls(_,L.body))},h=async()=>{const v=is({title:d,body:o});if($(v.errors),!!v.ok){G(!0);try{const L=await a({directory:e,repo:s,title:d.trim(),body:o.trim()?o:void 0,labels:y.length>0?y:void 0,assignees:p.length>0?p: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{G(!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(j,{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(Oe,{id:"new-issue-title",value:d,onChange:v=>b(v.target.value),placeholder:"Short summary","aria-label":"Issue title",className:"h-8",maxLength:300}),A.title?t.jsx("p",{className:"typography-micro text-[var(--status-error)]",role:"alert",children:A.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:f,onChange:v=>O(v.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"}),N.map(v=>t.jsx("option",{value:v.filename,children:v.name},v.filename))]}),T?t.jsx("p",{className:"typography-micro text-muted-foreground",children:T}):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(_e,{id:"new-issue-body",value:o,onChange:v=>c(v.target.value),placeholder:"Describe the issue","aria-label":"Issue body",rows:8}),A.body?t.jsx("p",{className:"typography-micro text-[var(--status-error)]",role:"alert",children:A.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:z,loading:I,selected:y,onChange:w})]}),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(Xe,{candidates:D,loading:I,selected:p,onChange:S})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(j,{type:"button",size:"sm",onClick:h,disabled:B||!d.trim(),"aria-label":"Create issue",children:B?"Creating…":"Create issue"}),t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:B,children:"Cancel"})]})]})})},Gs=({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),y=ws(e),w=Gt(),[p,S]=u.useState(!1),f=y.repo===s&&typeof y.number=="number"?y.number:null,x=c.state==="open"?"open":c.state==="all"?"both":"closed",N=u.useCallback(()=>{o&&(l(!0),C.getState().refreshAllForScope(e,s,o).catch(()=>null).finally(()=>l(!1)))},[o,e,s,l]);u.useEffect(()=>(r(N),()=>r(null)),[r,N]),u.useEffect(()=>{o&&(l(!0),C.getState().ensureCollectionsFresh(e,s,x,o).catch(()=>null).finally(()=>l(!1)))},[o,e,s,x]),u.useEffect(()=>{if(!o||f===null)return;const m=C.getState();m.ensureDetail(e,s,f,o),m.ensureComments(e,s,f,o)},[o,e,s,f]),u.useEffect(()=>{if(!o)return;const m=()=>{typeof document<"u"&&document.hidden||C.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=>{C.getState().notifyAgentTurnComplete(m)}),[]);const k=Me(s,"open"),T=Me(s,"closed"),H=u.useMemo(()=>ps(s),[s,k?.data,T?.data]),z=u.useMemo(()=>new Set(H.map(m=>m.number)),[H]),D=u.useMemo(()=>Ht(H,{state:c.state,involvement:c.involvement,labels:c.labels,search:c.search,sort:c.sort,viewerLogin:w}),[H,c.state,c.involvement,c.labels,c.search,c.sort,w]),I=x==="both"?[k,T]:[x==="open"?k:T],B=I.some(m=>m?.data!=null),G=B&&I.every(m=>m?.data?.nextCursor==null),A=I.reduce((m,q)=>m+(q?.data?.items.length??0),0),$=I.find(m=>m?.error)?.error??null,O=I.some(m=>m?.stale),h=c.search.trim(),v=c.labels.trim(),L=c.involvement!=="all"&&!w||c.involvement==="mentioned",_=h.length>0||v.length>0||c.involvement!=="all",W=u.useMemo(()=>({state:c.state,involvement:c.involvement,labels:v,q:h}),[c.state,c.involvement,v,h]),de=`${W.state}|${W.involvement}|${W.labels}|${W.q}`,X=!G&&B&&(D.length===0||L)&&(h.length>0||v.length>0||L),Q=u.useCallback(m=>o?C.getState().searchRemote(e,s,m,o):Promise.resolve(null),[e,s,o]),me=u.useCallback(m=>o?C.getState().loadMoreRemote(e,s,m,o):Promise.resolve(null),[e,s,o]),{remoteView:he,numberJump:J,remotePending:Z,handleSearchAll:ee}=gt({repo:s,query:W,queryKey:de,autoRemote:X,indexNumbers:z,visibleItems:D,searchText:h,useRemoteEntry:ys,runSearch:Q,runLoadMore:me}),U=u.useMemo(()=>{if(G||!B||!_)return null;const m=D.length===1?"1 match":`${D.length} matches`,q=A===1?"1 most recent loaded issue":`${A} most recent loaded issues`;return`Showing ${m} from the ${q}`},[G,B,_,D.length,A]),F=vs(s,f),M=Cs(s,f),te=u.useCallback(()=>{!o||f===null||C.getState().loadMoreComments(e,s,f,o)},[o,e,s,f]),se=u.useCallback(()=>{C.getState().selectIssue(e,null,null)},[e]),ae=u.useCallback(()=>{!o||f===null||C.getState().refreshDetail(e,s,f,o)},[o,e,s,f]),Y=u.useCallback(()=>{!o||f===null||C.getState().refreshComments(e,s,f,o)},[o,e,s,f]);if(!o)return null;if(p)return t.jsx(Ds,{directory:e,repo:s,github:o,onCancel:()=>S(!1),onCreated:m=>{S(!1),C.getState().selectIssue(e,s,m)}});if(f!==null){const m=F?.data?.detail??null;return t.jsx(As,{directory:e,repo:s,number:f,github:o,seed:xs(s,f),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:M?.data?.comments??[],commentsHasMore:!!M?.data?.nextCursor,commentsLoading:M?.isLoading??!1,onLoadMoreComments:te,onBack:se,onRetryDetail:ae,onRetryComments:Y})}return t.jsx(Ss,{items:D,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:O,error:$,filters:c,countComplete:G,incompleteNotice:U?{summary:U,searching:Z,onSearchAll:ee}:null,remote:he,numberJump:J,onFiltersChange:m=>C.getState().setFilters(e,s,m),onClearFilters:()=>C.getState().resetFilters(e,s),onLoadMore:()=>{const m=x==="both"?["open","closed"]:[x];Promise.all(m.map(q=>C.getState().loadMoreCollection(e,s,q,o)))},onRetry:()=>N(),onOpen:m=>C.getState().selectIssue(e,s,m),onNewIssue:()=>S(!0)})},Xs=({headerActionsSlot:e=null,headerActionsPresentation:s="drawer"})=>{const n=Et()??"",[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(bt,{directory:n,isRefreshing:r,onRefresh:()=>a.current?.(),children:({repo:o,directory:c})=>t.jsx(Gs,{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{Xs as IssuesSurface};
7
+ ${d}`:ts({repo:e.repo,number:e.number,title:e.title,url:e.url,contextText:d}),y=[{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:y}),{ok:!0,directory:e.directory};if(!r?.getGitBranches||!r?.createGitWorktree)return{ok:!1,error:"Worktree creation is not available in this runtime"};let w,x=!1;try{const p=await r.getGitBranches(e.directory);if(w=p.current?.trim()??"",!w)throw new Error("no current branch");x=Array.isArray(p.all)&&p.all.includes(ze(e))}catch{return{ok:!1,error:"Could not determine the current branch to start the worktree from"}}const S=ze(e);let f;try{if(x){let p=null;if(r.listGitWorktrees)try{const N=await r.listGitWorktrees(e.directory);p=Array.isArray(N)?N.find(k=>!k?.prunable&&k?.branch===S)?.path??null:null}catch{p=null}if(p)f=p;else if(f=(await r.createGitWorktree(e.directory,{mode:"existing",existingBranch:S})).path,!f)throw new Error("worktree path missing")}else if(f=(await r.createGitWorktree(e.directory,{mode:"new",startRef:w,branchName:S})).path,!f)throw new Error("worktree path missing")}catch(p){return{ok:!1,error:p instanceof Error?p.message:"Worktree creation failed"}}return await a?.(e.directory),l({directoryOverride:f,title:o,initialPrompt:c,syntheticParts:y}),{ok:!0,directory:f}},Ls=()=>{const e=$e(),s=kt(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=>ut(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(We,{login:e.author?.login,avatarUrl:e.author?.avatarUrl,size:"xs"}),e.author?.login??"ghost"]}),e.createdAt?` · opened ${Te(e.createdAt)}`:"",e.updatedAt&&e.updatedAt!==e.createdAt?` · updated ${Te(e.updatedAt)}`:""]}),Is=({number:e,closed:s,closeReason:n,onCloseReasonChange:r,closeAllowed:l,closeReasonText:a,reopenAllowed:d,reopenReasonText:b,acting:o,onStateAction:c,askSending:y,onAskAgent:w,onEditTitle:x,editAllowed:S,editReasonText:f,onCopyLink:p,url:N})=>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:Fe("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:Fe(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(j,{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(Nt,{value:n,onValueChange:k=>r(k),children:os.map(k=>t.jsx(Rt,{value:k.id,children:k.id==="completed"?"Close as completed":"Close as not planned"},k.id))})})]})]}),t.jsxs(j,{type:"button",variant:"outline",size:"xs",className:"shrink-0",onClick:w,disabled:y,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"}),y?"Asking…":"Ask agent"]}),t.jsxs(j,{type:"button",variant:"ghost",size:"xs",className:"shrink-0",onClick:()=>{ye(N)},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(j,{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:x,disabled:!S,title:f??"Edit title",children:[t.jsx(R,{name:"pencil",className:"size-3.5"}),"Edit title"]}),t.jsx(Lt,{}),t.jsxs(xe,{onClick:()=>{ye(N)},children:[t.jsx(R,{name:"external-link",className:"size-3.5"}),"Open on GitHub"]}),t.jsxs(xe,{onClick:p,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=C(i=>i.updateIssue),b=C(i=>i.addComment),o=C(i=>i.actionErrorByDetail[`${n}#${r}`]??null),c=C(i=>i.actingActions[`${n}#${r}`]??!1),{start:y,startingKey:w}=Ls(),x=Pt(s,n),[S,f]=u.useState("completed"),[p,N]=u.useState(!1),[k,T]=u.useState(""),[H,z]=u.useState(!1),[D,I]=u.useState(""),[B,G]=u.useState(!1),[A,$]=u.useState([]),[O,h]=u.useState([]),{draft:v,onDraftChange:L,flushDraft:_}=dt(n,r),{busy:W,error:de,submit:X}=mt({postComment:i=>b(s,n,r,i,l),runFollowUp:i=>d(s,n,r,Be(i==="reopen"?"reopen":S==="not_planned"?"close-not-planned":"close-completed"),l),verbs:{close:"close",reopen:"reopen"},doneLabels:{close:"Closed with comment",reopen:"Reopened with comment"},afterPost:()=>{L(""),ft.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),M=le("edit",a,U),te=le("labels",a,U),se=le("comment",a,U),ae=St(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())?Dt(s,i.repoRef,i.number):ye(i.url)},[s,Z]),{labels:q,assignees:et,loading:we}=Je(s,n,l),ne=i=>{a&&(i==="title"?(T(a.title),N(!0)):i==="body"?(I(a.body??""),z(!0)):($((a.labels??[]).map(E=>E.name)),h((a.assignees??[]).map(E=>E.login).filter(Boolean)),G(!0)))},fe=u.useCallback(async i=>{const E=await d(s,n,r,i,l);return E.ok?(N(!1),z(!1),G(!1),!0):(P.error(E.error?.kind==="failed"?E.error.message:"Update failed"),!1)},[d,s,n,r,l]),tt=u.useCallback(async i=>{const E=Be(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]),st=Ot(a?.url),at=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]),nt=u.useMemo(()=>K.filter(i=>!De(i.author?.login)),[K]),rt=u.useMemo(()=>K.filter(i=>De(i.author?.login)),[K]),ke=a?.state==="closed",Se=w!==null,V=a??(e.seed&&e.seed.number===r?e.seed:null),be=t.jsxs(t.Fragment,{children:[t.jsx(_t,{onBack:e.onBack,backLabel:"Back to issues",repoName:x,number:r,url:V?.url,numberTintClass:Kt("issue",V?.state??"open",!1,a?.stateReason),statePill:V?t.jsx(Ut,{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:M.allowed?null:M.reason,meta:V?t.jsx(Es,{issue:V}):void 0,primary:a?t.jsxs(j,{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:S,onCloseReasonChange:f,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=>tt(i),askSending:Y,onAskAgent:()=>{at()},onEditTitle:()=>ne("title"),editAllowed:M.allowed,editReasonText:M.reason,onCopyLink:st,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(j,{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(Wt,{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,p?t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1 py-1",children:[t.jsx(Oe,{value:k,onChange:i=>T(i.target.value),"aria-label":"Issue title",className:"h-7"}),t.jsx(j,{type:"button",variant:"default",size:"xs",onClick:()=>{fe({title:k})},disabled:c||!k.trim(),children:"Save"}),t.jsx(j,{type:"button",variant:"ghost",size:"xs",onClick:()=>N(!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(We,{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(qt,{name:i.name,color:i.color},i.name)),t.jsx(j,{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(j,{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(Pe,{glyph:t.jsx(Ke,{kind:"pr",state:i.state,draft:i.draft}),number:`#${i.number}`,title:i.title||"(no title)",meta:t.jsxs("span",{className:"truncate",children:[Vt(i.repoRef),E?"":" · GitHub"]}),onOpen:()=>m(i),ariaLabel:`Open linked pull request #${i.number}: ${i.title}`})},`${i.repoRef}#${i.number}`)})})})}),B?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(Ze,{candidates:q,loading:we,selected:A,onChange:$}),t.jsx("p",{className:"typography-micro font-medium text-muted-foreground",children:"Assignees"}),t.jsx(Xe,{candidates:et,loading:we,selected:O,onChange:h}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(j,{type:"button",size:"sm",onClick:()=>{fe({labels:A,assignees:O})},disabled:c,children:"Save"}),t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:()=>G(!1),disabled:c,children:"Cancel"})]})]}):null]}),t.jsx(Ge,{id:`issue-${r}-description`,title:"Description",action:H?void 0:t.jsx(j,{type:"button",variant:"ghost",size:"xs",onClick:()=>ne("body"),"aria-label":"Edit issue body",title:M.reason??"Edit issue body",disabled:!M.allowed,children:"Edit"}),children:H?t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(_e,{value:D,onChange:i=>I(i.target.value),"aria-label":"Issue body",rows:6}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(j,{type:"button",size:"sm",onClick:()=>{fe({body:D})},disabled:c,children:"Save"}),t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:()=>z(!1),disabled:c,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(Qt,{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(Ge,{id:`issue-${r}-comments`,title:`Comments${K.length?` (${K.length})`:""}`,action:t.jsx(Zt,{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."}):nt.map(i=>t.jsx(Jt,{comment:i},i.id)),t.jsx(Yt,{comments:rt}),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(ht,{draft:v,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,v)},allowed:F.allowed,reason:F.reason},onSubmitComment:()=>{X("comment",v)}}):null]})})]}),a?t.jsx(Ns,{open:he,onOpenChange:J,issueNumber:r,issueTitle:a.title,busy:Se,onChoose:i=>{J(!1),y({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=C(v=>v.createIssue),[d,b]=u.useState(""),[o,c]=u.useState(""),[y,w]=u.useState([]),[x,S]=u.useState([]),[f,p]=u.useState(""),[N,k]=u.useState([]),[T,H]=u.useState(null),{labels:z,assignees:D,loading:I}=Je(e,s,n),[B,G]=u.useState(!1),[A,$]=u.useState({});u.useEffect(()=>{let v=!1;return n.issueTemplates(e,s).then(L=>{v||(k(L.templates),H(L.templates.length===0?"No markdown templates in this repository. YAML issue forms are not supported.":null))}).catch(()=>{v||H("Issue templates are unavailable.")}),()=>{v=!0}},[n,e,s]);const O=v=>{if(p(v),!v)return;const L=N.find(_=>_.filename===v);L&&c(_=>ls(_,L.body))},h=async()=>{const v=is({title:d,body:o});if($(v.errors),!!v.ok){G(!0);try{const L=await a({directory:e,repo:s,title:d.trim(),body:o.trim()?o:void 0,labels:y.length>0?y:void 0,assignees:x.length>0?x: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{G(!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(j,{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(Oe,{id:"new-issue-title",value:d,onChange:v=>b(v.target.value),placeholder:"Short summary","aria-label":"Issue title",className:"h-8",maxLength:300}),A.title?t.jsx("p",{className:"typography-micro text-[var(--status-error)]",role:"alert",children:A.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:f,onChange:v=>O(v.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"}),N.map(v=>t.jsx("option",{value:v.filename,children:v.name},v.filename))]}),T?t.jsx("p",{className:"typography-micro text-muted-foreground",children:T}):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(_e,{id:"new-issue-body",value:o,onChange:v=>c(v.target.value),placeholder:"Describe the issue","aria-label":"Issue body",rows:8}),A.body?t.jsx("p",{className:"typography-micro text-[var(--status-error)]",role:"alert",children:A.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(Ze,{candidates:z,loading:I,selected:y,onChange:w})]}),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(Xe,{candidates:D,loading:I,selected:x,onChange:S})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(j,{type:"button",size:"sm",onClick:h,disabled:B||!d.trim(),"aria-label":"Create issue",children:B?"Creating…":"Create issue"}),t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:B,children:"Cancel"})]})]})})},Gs=({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),y=ws(e),w=Gt(),[x,S]=u.useState(!1),f=y.repo===s&&typeof y.number=="number"?y.number:null,p=c.state==="open"?"open":c.state==="all"?"both":"closed",N=u.useCallback(()=>{o&&(l(!0),C.getState().refreshAllForScope(e,s,o).catch(()=>null).finally(()=>l(!1)))},[o,e,s,l]);u.useEffect(()=>(r(N),()=>r(null)),[r,N]),u.useEffect(()=>{o&&(l(!0),C.getState().ensureCollectionsFresh(e,s,p,o).catch(()=>null).finally(()=>l(!1)))},[o,e,s,p]),u.useEffect(()=>{if(!o||f===null)return;const m=C.getState();m.ensureDetail(e,s,f,o),m.ensureComments(e,s,f,o)},[o,e,s,f]),u.useEffect(()=>{if(!o)return;const m=()=>{typeof document<"u"&&document.hidden||C.getState().ensureCollectionsFresh(e,s,p,o).catch(()=>{})};return window.addEventListener("focus",m),document.addEventListener("visibilitychange",m),()=>{window.removeEventListener("focus",m),document.removeEventListener("visibilitychange",m)}},[o,e,s,p]),u.useEffect(()=>Tt(m=>{C.getState().notifyAgentTurnComplete(m)}),[]);const k=Me(s,"open"),T=Me(s,"closed"),H=u.useMemo(()=>xs(s),[s,k?.data,T?.data]),z=u.useMemo(()=>new Set(H.map(m=>m.number)),[H]),D=u.useMemo(()=>Ht(H,{state:c.state,involvement:c.involvement,labels:c.labels,search:c.search,sort:c.sort,viewerLogin:w}),[H,c.state,c.involvement,c.labels,c.search,c.sort,w]),I=p==="both"?[k,T]:[p==="open"?k:T],B=I.some(m=>m?.data!=null),G=B&&I.every(m=>m?.data?.nextCursor==null),A=I.reduce((m,q)=>m+(q?.data?.items.length??0),0),$=I.find(m=>m?.error)?.error??null,O=I.some(m=>m?.stale),h=c.search.trim(),v=c.labels.trim(),L=c.involvement!=="all"&&!w||c.involvement==="mentioned",_=h.length>0||v.length>0||c.involvement!=="all",W=u.useMemo(()=>({state:c.state,involvement:c.involvement,labels:v,q:h}),[c.state,c.involvement,v,h]),de=`${W.state}|${W.involvement}|${W.labels}|${W.q}`,X=!G&&B&&(D.length===0||L)&&(h.length>0||v.length>0||L),Q=u.useCallback(m=>o?C.getState().searchRemote(e,s,m,o):Promise.resolve(null),[e,s,o]),me=u.useCallback(m=>o?C.getState().loadMoreRemote(e,s,m,o):Promise.resolve(null),[e,s,o]),{remoteView:he,numberJump:J,remotePending:Y,handleSearchAll:ee}=gt({repo:s,query:W,queryKey:de,autoRemote:X,indexNumbers:z,visibleItems:D,searchText:h,useRemoteEntry:ys,runSearch:Q,runLoadMore:me}),U=u.useMemo(()=>{if(G||!B||!_)return null;const m=D.length===1?"1 match":`${D.length} matches`,q=A===1?"1 most recent loaded issue":`${A} most recent loaded issues`;return`Showing ${m} from the ${q}`},[G,B,_,D.length,A]),F=vs(s,f),M=Cs(s,f),te=u.useCallback(()=>{!o||f===null||C.getState().loadMoreComments(e,s,f,o)},[o,e,s,f]),se=u.useCallback(()=>{C.getState().selectIssue(e,null,null)},[e]),ae=u.useCallback(()=>{!o||f===null||C.getState().refreshDetail(e,s,f,o)},[o,e,s,f]),Z=u.useCallback(()=>{!o||f===null||C.getState().refreshComments(e,s,f,o)},[o,e,s,f]);if(!o)return null;if(x)return t.jsx(Ds,{directory:e,repo:s,github:o,onCancel:()=>S(!1),onCreated:m=>{S(!1),C.getState().selectIssue(e,s,m)}});if(f!==null){const m=F?.data?.detail??null;return t.jsx(As,{directory:e,repo:s,number:f,github:o,seed:ps(s,f),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:M?.data?.comments??[],commentsHasMore:!!M?.data?.nextCursor,commentsLoading:M?.isLoading??!1,onLoadMoreComments:te,onBack:se,onRetryDetail:ae,onRetryComments:Z})}return t.jsx(Ss,{items:D,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:O,error:$,filters:c,countComplete:G,incompleteNotice:U?{summary:U,searching:Y,onSearchAll:ee}:null,remote:he,numberJump:J,onFiltersChange:m=>C.getState().setFilters(e,s,m),onClearFilters:()=>C.getState().resetFilters(e,s),onLoadMore:()=>{const m=p==="both"?["open","closed"]:[p];Promise.all(m.map(q=>C.getState().loadMoreCollection(e,s,q,o)))},onRetry:()=>N(),onOpen:m=>C.getState().selectIssue(e,s,m),onNewIssue:()=>S(!0)})},Xs=({headerActionsSlot:e=null,headerActionsPresentation:s="drawer"})=>{const n=Et()??"",[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(bt,{directory:n,isRefreshing:r,onRefresh:()=>a.current?.(),children:({repo:o,directory:c})=>t.jsx(Gs,{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{Xs as IssuesSurface};
@@ -1 +1 @@
1
- import{c5 as M,di as Z,dj as Fe,dk as Ce,dl as ke,dm as Ie,dn as ze,dd as Ne,dp as Oe,B as ee,I as te,dq as Ve}from"./useAppFontEffects-CG3_yteE.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-CH3-XV-n.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-wpC51ZBQ.js";import{j as C}from"./vendor-boot-DyL2td56.js";import{o as ut,i as j,f as A,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-CeMpF2xC.js";import{a as F,i as K,l as pe,h as Ct,r as St}from"./renderFileWithHighlighter-TpKRyfCY.js";import{t as H}from"./vendor-hast-util-to-html-BKBhbTDb.js";import{a as k,R as L}from"./vendor-react-DASdDPIk.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:M},e,t){this.options=i,this.onRenderUpdate=e,this.workerManager=t,t?.isWorkingPool()!==!0&&(this.highlighter=ie(i.theme??M)?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=M,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}:!A(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=!A(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 H(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?H(ce({tagName:"code",children:i,properties:{"data-code":""}})):H(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=!A(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&&A(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:M},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??M)}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)||At(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=!A(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??M,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=H(a.children),s.style.cssText=a.properties.style}else this.code.innerHTML=H(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??H(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 At(i,e,t=!1){return i==null&&e!=null&&!t}const Mt=5e3;let Ht=-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:${++Ht}`;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||!A(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%Mt===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,Ae=N[G]??0,Me=J===0?0:u+Ae,X=G+Y/a,He=X<N.length?f-N[X]:f-(T-e-p);return{startingLine:J,totalLines:Y,bufferBefore:Me,bufferAfter:Math.max(0,He)}}};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};
1
+ import{c5 as M,di as Z,dj as Fe,dk as Ce,dl as ke,dm as Ie,dn as ze,dd as Ne,dp as Oe,B as ee,I as te,dq as Ve}from"./useAppFontEffects--lKKtKVo.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-v9fuidaX.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-wpC51ZBQ.js";import{j as C}from"./vendor-boot-DyL2td56.js";import{o as ut,i as j,f as A,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-3PpRLd5B.js";import{a as F,i as K,l as pe,h as Ct,r as St}from"./renderFileWithHighlighter-BvDoP7ob.js";import{t as H}from"./vendor-hast-util-to-html-BKBhbTDb.js";import{a as k,R as L}from"./vendor-react-DASdDPIk.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:M},e,t){this.options=i,this.onRenderUpdate=e,this.workerManager=t,t?.isWorkingPool()!==!0&&(this.highlighter=ie(i.theme??M)?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=M,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}:!A(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=!A(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 H(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?H(ce({tagName:"code",children:i,properties:{"data-code":""}})):H(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=!A(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&&A(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:M},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??M)}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)||At(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=!A(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??M,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=H(a.children),s.style.cssText=a.properties.style}else this.code.innerHTML=H(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??H(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 At(i,e,t=!1){return i==null&&e!=null&&!t}const Mt=5e3;let Ht=-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:${++Ht}`;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||!A(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%Mt===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,Ae=N[G]??0,Me=J===0?0:u+Ae,X=G+Y/a,He=X<N.length?f-N[X]:f-(T-e-p);return{startingLine:J,totalLines:Y,bufferBefore:Me,bufferAfter:Math.max(0,He)}}};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};