zidane-gui 9.3.1 → 9.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/out/main/chunks/{remote-hosts-B8_tzg_n.js → remote-hosts-CSiGJAfm.js} +1 -1
  2. package/out/main/chunks/{session-search-sql-2EUzjHAT.js → session-search-sql-D51BmAO2.js} +5 -5
  3. package/out/main/index.js +4397 -4086
  4. package/out/main/session-search-worker.js +1 -1
  5. package/out/preload/index.mjs +36 -2
  6. package/out/renderer/assets/{24BXRY42-eTlQfl4v.js → 24BXRY42-0UXaaWjY.js} +1 -1
  7. package/out/renderer/assets/{4FHPYW2L-BHx1bBmw.js → 4FHPYW2L-BWpHahlW.js} +1 -1
  8. package/out/renderer/assets/{4LWW3ZNH-D7lTurDT.js → 4LWW3ZNH-CPyJ9o9Y.js} +1 -1
  9. package/out/renderer/assets/{5XYWFMKW-e04QMbw9.js → 5XYWFMKW-ZZpHHfGa.js} +1 -1
  10. package/out/renderer/assets/{64PMEAB3-DTIFpDpU.js → 64PMEAB3-DOEnEuzl.js} +1 -1
  11. package/out/renderer/assets/{6BEWHPQE-BrYtHcZG.js → 6BEWHPQE-C2ZZckdj.js} +1 -1
  12. package/out/renderer/assets/{6PIGVMFT-CoAPPYTl.js → 6PIGVMFT-CRGq6eh3.js} +1 -1
  13. package/out/renderer/assets/{75JW6PN6-JbXPfJg4.js → 75JW6PN6-CYzAa9yx.js} +1 -1
  14. package/out/renderer/assets/{7XWI72E6-CFY3Kecs.js → 7XWI72E6-C_GZbyIF.js} +1 -1
  15. package/out/renderer/assets/{BGW36YJW-DhmSG9tb.js → BGW36YJW-BAwgTZ_z.js} +1 -1
  16. package/out/renderer/assets/{CGIZI67J-Cr9B0EmW.js → CGIZI67J-BxXITbQC.js} +1 -1
  17. package/out/renderer/assets/{CodeEditor-C6EJBlGG.js → CodeEditor-CLsAw7eu.js} +2 -2
  18. package/out/renderer/assets/{ComposerEditor-oFIdMkLB.js → ComposerEditor-BqnIn2NQ.js} +1 -1
  19. package/out/renderer/assets/{DNNCRC2E-CMqlK0W6.js → DNNCRC2E-kbsNJgPT.js} +1 -1
  20. package/out/renderer/assets/DiffsTab--BHt7StP.js +3 -0
  21. package/out/renderer/assets/{E67EBMDD-C_T2QnwF.js → E67EBMDD-BOeJkFNZ.js} +1 -1
  22. package/out/renderer/assets/{EFYWJBJK-Cbn-VZcb.js → EFYWJBJK-CFT5CQUG.js} +1 -1
  23. package/out/renderer/assets/{EXE5EH6O-SXdUe5We.js → EXE5EH6O-Cbj5xPKl.js} +1 -1
  24. package/out/renderer/assets/{EditorWorkers-bVeEZI8X.js → EditorWorkers-CXBU_HFf.js} +1 -1
  25. package/out/renderer/assets/{FilesTab-DtM2Q5R0.js → FilesTab-CZHD0eBx.js} +4 -4
  26. package/out/renderer/assets/{G6GPDDNC-XfFyRa0j.js → G6GPDDNC-Ax6dML4i.js} +1 -1
  27. package/out/renderer/assets/{G76NGGFM-Bj_m2WLJ.js → G76NGGFM-BxPXXNt_.js} +1 -1
  28. package/out/renderer/assets/{GH6G3TJC-wPRy41Zv.js → GH6G3TJC-CiCXY2r6.js} +1 -1
  29. package/out/renderer/assets/{HPNUA7RO-BhLNmX-t.js → HPNUA7RO-DiyW9VGu.js} +1 -1
  30. package/out/renderer/assets/{HQRGC5D7-dvTAT1Uv.js → HQRGC5D7-ArfvIYAC.js} +1 -1
  31. package/out/renderer/assets/{IX6Z2TVR-CzV_umYo.js → IX6Z2TVR-Df9chdw8.js} +1 -1
  32. package/out/renderer/assets/IconButtonTip-D0dQOfg6.js +1 -0
  33. package/out/renderer/assets/{J77NQRCJ-DTwwq3Ci.js → J77NQRCJ-DOWauTsf.js} +1 -1
  34. package/out/renderer/assets/{JAD36DTZ-DArKsMUT.js → JAD36DTZ-CJDdMCD5.js} +1 -1
  35. package/out/renderer/assets/{LF3NJQAX-DjYdE7YV.js → LF3NJQAX-B89ZqOpY.js} +1 -1
  36. package/out/renderer/assets/{LRZCOFJZ-C7m8fw-0.js → LRZCOFJZ-BBX_wZ5T.js} +1 -1
  37. package/out/renderer/assets/{N5NF2FGY-CqGhgjNF.js → N5NF2FGY-BoIFu-8L.js} +1 -1
  38. package/out/renderer/assets/{N7OWWQHY-BRk68LVa.js → N7OWWQHY-CloOgGu1.js} +1 -1
  39. package/out/renderer/assets/{NT5JY5WP-B1NtxJ-K.js → NT5JY5WP-BhjzefjG.js} +1 -1
  40. package/out/renderer/assets/{OT7W3RNY-CtDQ--Ld.js → OT7W3RNY-BRzBqtKB.js} +1 -1
  41. package/out/renderer/assets/{P67P66DB-LeAz_z3Z.js → P67P66DB-Dw-K1Ghu.js} +1 -1
  42. package/out/renderer/assets/{PFLLLM7K-CgODCVD8.js → PFLLLM7K-DfSPUrIT.js} +1 -1
  43. package/out/renderer/assets/{PUAMC4MJ-9REX_vGK.js → PUAMC4MJ-BnY1F2cF.js} +1 -1
  44. package/out/renderer/assets/{PVFCHRLY-CK5jTRjy.js → PVFCHRLY-BcyVPS3n.js} +1 -1
  45. package/out/renderer/assets/{PinnedSavedView-Dtdra7Gq.js → PinnedSavedView-ciRhY0cN.js} +1 -1
  46. package/out/renderer/assets/{QQW2P742-B2snHr_6.js → QQW2P742-D6aitZ24.js} +1 -1
  47. package/out/renderer/assets/{S63OEDPG-BeWWF1tc.js → S63OEDPG-Dlz1a9cD.js} +1 -1
  48. package/out/renderer/assets/{SG5TVYLW-ClCsbQ87.js → SG5TVYLW-Bu7LZZpx.js} +1 -1
  49. package/out/renderer/assets/{SavedViewArtifact-ATjDgAUF.js → SavedViewArtifact-CM9L4mc8.js} +1 -1
  50. package/out/renderer/assets/{SidebarPreviewPane-DHllX0GN.js → SidebarPreviewPane-DkOCt7Gb.js} +1 -1
  51. package/out/renderer/assets/{TranscriptViews-DD_JshFH.js → TranscriptViews-aYvP71ow.js} +1 -1
  52. package/out/renderer/assets/{UGRSUGA2-jP6nv8HL.js → UGRSUGA2-avwOtJG1.js} +1 -1
  53. package/out/renderer/assets/{V44WA6U7-Dr_tS3uH.js → V44WA6U7-DMF87Y7j.js} +1 -1
  54. package/out/renderer/assets/{V67O4WWV-BRn52u9c.js → V67O4WWV-BsDLuBDb.js} +1 -1
  55. package/out/renderer/assets/{VBUCM3YD-0sLtn_Zp.js → VBUCM3YD-C6FrRswP.js} +1 -1
  56. package/out/renderer/assets/{VINGRCPA-n98Gf7V0.js → VINGRCPA-Do3Pv3Tc.js} +1 -1
  57. package/out/renderer/assets/{ViewBlock-DdcTHRu3.js → ViewBlock-B-ppjb34.js} +3 -3
  58. package/out/renderer/assets/{ViewCharts-BAw6tExV.js → ViewCharts-jvS22ppO.js} +2 -2
  59. package/out/renderer/assets/{ViewCustom-BzwMbjqg.js → ViewCustom-yFkoy6a-.js} +1 -1
  60. package/out/renderer/assets/{ViewExtension-Ch5_33Ra.js → ViewExtension-DuHxho6W.js} +1 -1
  61. package/out/renderer/assets/{ViewInputs-BHooAs2f.js → ViewInputs-VAMDh56H.js} +1 -1
  62. package/out/renderer/assets/{ViewMcpApp-CJnOESMk.js → ViewMcpApp-CH_W9CZt.js} +1 -1
  63. package/out/renderer/assets/{ViewSessionAction-BHJv5QNb.js → ViewSessionAction-66veqRhO.js} +1 -1
  64. package/out/renderer/assets/{ViewTables-DBTupg46.js → ViewTables-CKKDcYKH.js} +1 -1
  65. package/out/renderer/assets/{WL6DNKX4-Csfp__Nw.js → WL6DNKX4-Cq-YK4Uf.js} +1 -1
  66. package/out/renderer/assets/{WQ63CJYP-oSbguA5n.js → WQ63CJYP-fjrhTSVs.js} +1 -1
  67. package/out/renderer/assets/{XOYAOB3S-DfDDKmX8.js → XOYAOB3S-CAQPI0he.js} +1 -1
  68. package/out/renderer/assets/{Y5LQLG3M-BnZ8APdi.js → Y5LQLG3M-DKntYAaW.js} +1 -1
  69. package/out/renderer/assets/{YIK6JTN6-Bunk5CDx.js → YIK6JTN6-CcjcC5JX.js} +1 -1
  70. package/out/renderer/assets/{core-BbPUgmX7.js → core-Cj89wpQh.js} +4 -4
  71. package/out/renderer/assets/{file-tabs-CFdJBYJ9.js → file-tabs-PoAgFa7v.js} +1 -1
  72. package/out/renderer/assets/{ghostty-web-Dn7o-dzQ.js → ghostty-web-DiMuvUtH.js} +1 -1
  73. package/out/renderer/assets/{highlights-eTGcn9lP.js → highlights-7WH0ppQl.js} +1 -1
  74. package/out/renderer/assets/{highlights-D4Jo_Sz0.js → highlights-DnSmFBdQ.js} +1 -1
  75. package/out/renderer/assets/index-CiuUSFeC.js +11 -0
  76. package/out/renderer/assets/kit-CD3F-f6F.js +147 -0
  77. package/out/renderer/assets/{langs-CXhlGiW6.js → langs-D5CRC9qz.js} +1 -1
  78. package/out/renderer/assets/{lazy-D3tN-GAO.js → lazy-CUmWiDAP.js} +3 -3
  79. package/out/renderer/assets/{loader-DGyfh0zB.js → loader-CPY9efuc.js} +1 -1
  80. package/out/renderer/assets/{pierre-theme-BZvsTYqQ.js → pierre-theme-BrzM0xZU.js} +3 -3
  81. package/out/renderer/assets/setting-demos-BW7cG2_G.css +1 -0
  82. package/out/renderer/assets/setting-demos-DEURBrvf.js +1 -0
  83. package/out/renderer/assets/{shiki-Wqv4XEGM.js → shiki-DFrbO9j3.js} +1 -1
  84. package/out/renderer/assets/{sidebar-layout-sK8ujsHX.js → sidebar-layout-fobokay5.js} +1 -1
  85. package/out/renderer/assets/{stream-tokenizer-C18hljKL.js → stream-tokenizer-CT1HAjvR.js} +1 -1
  86. package/out/renderer/assets/{themes-Dfx1_kFe.js → themes-Cj62ov9J.js} +1 -1
  87. package/out/renderer/assets/{useFind-BBxfQuQ2.js → useFind-Cdl0rVJO.js} +3 -3
  88. package/out/renderer/assets/{useFolderChanges-BcfSJoBT.js → useFolderChanges-C9L_NOgw.js} +2 -2
  89. package/out/renderer/assets/{view-preview-B2Rj--lZ.js → view-preview-BvCO9WZH.js} +1 -1
  90. package/out/renderer/assets/{zoom-reset-l-YVDJrI.js → zoom-reset-COqHFP45.js} +1 -1
  91. package/out/renderer/index.html +5 -5
  92. package/out/renderer/view-preview.html +6 -6
  93. package/package.json +2 -2
  94. package/out/renderer/assets/DiffsTab-D690H0Dy.js +0 -3
  95. package/out/renderer/assets/IconButtonTip-P9QUxPjA.js +0 -1
  96. package/out/renderer/assets/index-c95EBMdk.js +0 -8
  97. package/out/renderer/assets/kit-C9O_D5xC.js +0 -147
  98. package/out/renderer/assets/setting-demos-B0787McX.js +0 -1
  99. package/out/renderer/assets/setting-demos-vtrBsYTd.css +0 -1
@@ -1,4 +1,4 @@
1
- import{j as jsxRuntimeExports,r as reactExports,c as reactDomExports}from"./vendor-react-CxJ4vs-5.js";import{t as useLabels,bC as TabPill,bD as usePresence,bE as readMenuExitMs,bF as useCodeHighlight,bB as Tooltip,I as IconButton,bA as useEditorPrefs,av as useFilesHost,aw as useFilesLabels,bG as useCodeDocument,bH as excerptFromContents,bI as serializeDiagnostic,bs as languageFor,bt as rangeLabel,bv as attachmentName,aF as useAppearanceReducedMotion,aM as PanelLoading,Y as useLinkRouter,Z as useLightbox,au as mediaTypeOfPath,bJ as Markdown,n as RowActionsMenu,bK as useGitHost,bu as serializeCodeSnippet,bL as copyImage,bM as copyImageBase64,bN as copyImageDataUrl,bO as mediaSiblings,bP as ReorderTabs,bQ as Breadcrumb,aL as IconToggle,aN as PanelEmpty,bR as readPanelMs,bS as usePanelSettled,bT as useResizeDrag,N as Notice,j as useOptionalConfirm,bU as entryRefusalText,bV as topLevelPaths,bW as parentOf,bX as inFolder,bY as nameOf,bZ as droppedItems,ax as filesRootOf,b_ as movedPath,b$ as isUnder,c0 as filesScopeKey,c1 as createMemoryFilesLayout,aA as usePanelVisible,c2 as useAppearanceState,c3 as useReadable,aI as steppedIndex}from"./kit-C9O_D5xC.js";import{c as createFileTreeIconResolver,g as getBuiltInSpriteSheet,n as normalizeFileTreeIcons,i as isColoredBuiltInIconSet,F as FileIcon}from"./FileIcon-DECOEMOz.js";import{aE as TREES_HOST_STYLE,aF as TREES_UNSAFE_CSS,u as useWorkerPool}from"./pierre-theme-BZvsTYqQ.js";import{C as CodeEditor,E as EditStateManager}from"./CodeEditor-C6EJBlGG.js";import{g as DIAGNOSTIC_GLYPH,h as fileActionItems,i as useFilesChat,j as useCodeReview,k as diagnosticsByLine,l as diagnosticMarkers,m as diagnosticsAt,D as DiffScroller,R as ReviewableDiff,p as parseFilePatch,o as noChatItem,c as countBySeverity,u as useDiagnosticsRun,q as absolutePath,r as MediaFrame,M as MediaView,a as useFolderChanges,e as useNoKeyScope,n as nameMatches,F as FilesChatContext,S as SearchPanel,d as useNoEdits}from"./useFolderChanges-BcfSJoBT.js";import{ad as REVEAL_FALLBACK_MS,d as diffLines,u as useFind,F as FindBar}from"./useFind-BBxfQuQ2.js";import"./vendor-motion-C2jPaSqL.js";import"./vendor-owxl31sT.js";import"./core-BbPUgmX7.js";import"./vendor-editor-gVJMCtGz.js";import"./utils-qCteL8MB.js";import"./hastToHtml-C4ea9WpN.js";import"./index-C-yjveB4.js";const FILE_TREE_TAG_NAME="file-tree-container",FILE_TREE_STYLE_ATTRIBUTE="data-file-tree-style",FILE_TREE_UNSAFE_CSS_ATTRIBUTE="data-file-tree-unsafe-css",FILE_TREE_SCROLLBAR_MEASURE_ATTRIBUTE="data-file-tree-scrollbar-measure",FILE_TREE_SCROLLBAR_GUTTER_STYLE_ATTRIBUTE="data-file-tree-scrollbar-gutter-measured",FILE_TREE_SCROLLBAR_GUTTER_MEASURED_PROPERTY="--trees-scrollbar-gutter-measured",HEADER_SLOT_NAME="header",CONTEXT_MENU_SLOT_NAME="context-menu",CONTEXT_MENU_TRIGGER_TYPE="context-menu-trigger",PATH_STORE_CHILD_INDEX_CHUNK_SHIFT=5,PATH_STORE_CHILD_INDEX_CHUNK_SIZE=1<<PATH_STORE_CHILD_INDEX_CHUNK_SHIFT,PATH_STORE_CHILD_INDEX_CHUNK_THRESHOLD=PATH_STORE_CHILD_INDEX_CHUNK_SIZE*4;function createDirectoryChildIndex(){return{childIdByNameId:new Map,childIds:[],childPositionById:new Map,childVisibleChunkSums:null,totalChildSubtreeNodeCount:0,totalChildVisibleSubtreeCount:0}}function createPresortedDirectoryChildIndex(){return{childIdByNameId:null,childIds:[],childPositionById:null,childVisibleChunkSums:null,totalChildSubtreeNodeCount:0,totalChildVisibleSubtreeCount:0}}function ensureChildIdByNameId(nodes,index){if(index.childIdByNameId!=null)return index.childIdByNameId;const map=new Map;for(const childId of index.childIds){const childNode=nodes[childId];childNode!=null&&map.set(childNode.nameId,childId)}return index.childIdByNameId=map,map}function ensureChildPositions(index){if(index.childPositionById!=null)return index.childPositionById;const positions=new Map;for(let i2=0;i2<index.childIds.length;i2++){const childId=index.childIds[i2];childId!=null&&positions.set(childId,i2)}return index.childPositionById=positions,positions}function appendChildReference(index,childId){index.childPositionById!=null&&index.childPositionById.set(childId,index.childIds.length),index.childIds.push(childId)}function updateChildPositionsFrom(index,startIndex){if(index.childPositionById!=null)for(let position=startIndex;position<index.childIds.length;position++){const childId=index.childIds[position];childId!=null&&index.childPositionById.set(childId,position)}}function rebuildDirectoryChildAggregates(nodes,index){let totalChildSubtreeNodeCount=0,totalChildVisibleSubtreeCount=0;for(const childId of index.childIds){const childNode=nodes[childId];childNode!=null&&(totalChildSubtreeNodeCount+=childNode.subtreeNodeCount,totalChildVisibleSubtreeCount+=childNode.visibleSubtreeCount)}index.totalChildSubtreeNodeCount=totalChildSubtreeNodeCount,index.totalChildVisibleSubtreeCount=totalChildVisibleSubtreeCount,rebuildVisibleChildChunks(nodes,index)}function applyChildAggregateDelta(index,childId,subtreeNodeDelta,visibleSubtreeDelta){if(index.totalChildSubtreeNodeCount+=subtreeNodeDelta,index.totalChildVisibleSubtreeCount+=visibleSubtreeDelta,index.childVisibleChunkSums==null||visibleSubtreeDelta===0)return;const childPosition=ensureChildPositions(index).get(childId);if(childPosition===void 0)return;const chunkIndex=childPosition>>PATH_STORE_CHILD_INDEX_CHUNK_SHIFT;index.childVisibleChunkSums[chunkIndex]+=visibleSubtreeDelta}function selectChildIndexByVisibleIndex(nodes,index,visibleIndex){const chunkSums=index.childVisibleChunkSums;if(chunkSums!=null){let remainingIndex2=visibleIndex,childIndex=0;for(const chunkVisibleCount of chunkSums){if(remainingIndex2<chunkVisibleCount){const selected=selectChildIndexWithinChunk(nodes,index,childIndex,remainingIndex2);return{...selected,childVisibleIndex:visibleIndex-selected.localVisibleIndex}}remainingIndex2-=chunkVisibleCount,childIndex+=PATH_STORE_CHILD_INDEX_CHUNK_SIZE}throw new Error(`Visible child index ${String(visibleIndex)} is out of range`)}let remainingIndex=visibleIndex;for(let childIndex=0;childIndex<index.childIds.length;childIndex++){const childId=index.childIds[childIndex];if(childId==null)continue;const childNode=nodes[childId];if(childNode!=null){if(remainingIndex<childNode.visibleSubtreeCount)return{childIndex,childVisibleIndex:visibleIndex-remainingIndex,localVisibleIndex:remainingIndex};remainingIndex-=childNode.visibleSubtreeCount}}throw new Error(`Visible child index ${String(visibleIndex)} is out of range`)}function getVisibleChildPrefixCount(nodes,index,childPosition){let visibleCount=0;const chunkSums=index.childVisibleChunkSums;let scanStart=0;if(chunkSums!=null){const chunkIndex=childPosition>>PATH_STORE_CHILD_INDEX_CHUNK_SHIFT;for(let chunkOffset=0;chunkOffset<chunkIndex;chunkOffset+=1)visibleCount+=chunkSums[chunkOffset]??0;scanStart=chunkIndex<<PATH_STORE_CHILD_INDEX_CHUNK_SHIFT}for(let childIndex=scanStart;childIndex<childPosition;childIndex+=1){const childId=index.childIds[childIndex];if(childId==null)continue;const childNode=nodes[childId];childNode!=null&&(visibleCount+=childNode.visibleSubtreeCount)}return visibleCount}function rebuildVisibleChildChunks(nodes,index){if(index.childIds.length<PATH_STORE_CHILD_INDEX_CHUNK_THRESHOLD){index.childVisibleChunkSums=null;return}const chunkCount=Math.ceil(index.childIds.length/PATH_STORE_CHILD_INDEX_CHUNK_SIZE),chunkSums=new Int32Array(chunkCount);for(let childIndex=0;childIndex<index.childIds.length;childIndex++){const childId=index.childIds[childIndex];if(childId==null)continue;const childNode=nodes[childId];childNode!=null&&(chunkSums[childIndex>>PATH_STORE_CHILD_INDEX_CHUNK_SHIFT]+=childNode.visibleSubtreeCount)}index.childVisibleChunkSums=chunkSums}function selectChildIndexWithinChunk(nodes,index,chunkStartIndex,visibleIndex){const chunkEndIndex=Math.min(index.childIds.length,chunkStartIndex+PATH_STORE_CHILD_INDEX_CHUNK_SIZE);let remainingIndex=visibleIndex;for(let childIndex=chunkStartIndex;childIndex<chunkEndIndex;childIndex++){const childId=index.childIds[childIndex];if(childId==null)continue;const childNode=nodes[childId];if(childNode!=null){if(remainingIndex<childNode.visibleSubtreeCount)return{childIndex,localVisibleIndex:remainingIndex};remainingIndex-=childNode.visibleSubtreeCount}}throw new Error(`Visible child index ${String(visibleIndex)} is out of range`)}const PATH_STORE_NODE_FLAGS_MASK=7,PATH_STORE_NODE_KIND_SHIFT=3,PATH_STORE_NODE_KIND_MASK=1<<PATH_STORE_NODE_KIND_SHIFT,PATH_STORE_NODE_DEPTH_SHIFT=4;function createNodeDepthAndFlags(depth,flags,kind=0){return depth<<PATH_STORE_NODE_DEPTH_SHIFT|kind<<PATH_STORE_NODE_KIND_SHIFT|flags}function getNodeDepth(node){return node.depthAndFlags>>>PATH_STORE_NODE_DEPTH_SHIFT}function getNodeKind(node){return(node.depthAndFlags&PATH_STORE_NODE_KIND_MASK)>>PATH_STORE_NODE_KIND_SHIFT}function isDirectoryNode(node){return(node.depthAndFlags&PATH_STORE_NODE_KIND_MASK)!==0}function getNodeFlags(node){return node.depthAndFlags&PATH_STORE_NODE_FLAGS_MASK}function hasNodeFlag(node,flag){return(getNodeFlags(node)&flag)!==0}function addNodeFlag(node,flag){node.depthAndFlags|=flag}function setNodeDepth(node,depth){node.depthAndFlags=createNodeDepthAndFlags(depth,getNodeFlags(node),getNodeKind(node))}const BENCHMARK_INSTRUMENTATION=Symbol("benchmarkInstrumentation");function attachBenchmarkInstrumentation(value,instrumentation){return instrumentation==null||Object.defineProperty(value,BENCHMARK_INSTRUMENTATION,{configurable:!0,enumerable:!1,value:instrumentation,writable:!1}),value}function getBenchmarkInstrumentation(value){return value==null?null:value[BENCHMARK_INSTRUMENTATION]??null}function withBenchmarkPhase(instrumentation,name,fn){return instrumentation==null?fn():instrumentation.measurePhase(name,fn)}function setBenchmarkCounter(instrumentation,name,value){!Number.isFinite(value)||instrumentation==null||instrumentation.setCounter(name,value)}function isDigitCode(characterCode){return characterCode>=48&&characterCode<=57}function splitIntoNaturalTokens(value){const tokens=[];let tokenStart=0,index=0;for(;index<value.length;){for(;index<value.length&&!isDigitCode(value.charCodeAt(index));)index+=1;if(index>=value.length)break;index>tokenStart&&tokens.push(value.slice(tokenStart,index));let numberValue=0;for(;index<value.length&&isDigitCode(value.charCodeAt(index));)numberValue=numberValue*10+(value.charCodeAt(index)-48),index+=1;tokens.push(numberValue),tokenStart=index}return(tokenStart<value.length||tokens.length===0)&&tokens.push(value.slice(tokenStart)),tokens}function createSegmentSortKey(value){const lowerValue=value.toLowerCase();return{lowerValue,tokens:splitIntoNaturalTokens(lowerValue)}}function compareNaturalTokens(leftTokens,rightTokens){const tokenCount=Math.min(leftTokens.length,rightTokens.length);for(let index=0;index<tokenCount;index++){const leftToken=leftTokens[index],rightToken=rightTokens[index];if(leftToken===rightToken)continue;if(typeof leftToken=="number"&&typeof rightToken=="number")return leftToken<rightToken?-1:1;const leftString=String(leftToken),rightString=String(rightToken);if(leftString!==rightString)return leftString<rightString?-1:1}return leftTokens.length!==rightTokens.length?leftTokens.length<rightTokens.length?-1:1:0}function compareSegmentSortKeys(leftKey,rightKey){if(leftKey.tokens.length===1&&rightKey.tokens.length===1&&typeof leftKey.tokens[0]=="string"&&typeof rightKey.tokens[0]=="string")return leftKey.lowerValue===rightKey.lowerValue?0:leftKey.lowerValue<rightKey.lowerValue?-1:1;const tokenComparison=compareNaturalTokens(leftKey.tokens,rightKey.tokens);return tokenComparison!==0?tokenComparison:leftKey.lowerValue!==rightKey.lowerValue?leftKey.lowerValue<rightKey.lowerValue?-1:1:0}function compareSegmentValuesWithSortKeyLookup(left,right,getSortKey){const comparison=compareSegmentSortKeys(getSortKey(left),getSortKey(right));return comparison!==0?comparison:left===right?0:left<right?-1:1}function compareSegmentValues(left,right){return compareSegmentValuesWithSortKeyLookup(left,right,createSegmentSortKey)}function getKindAtDepth(entry,depth){return depth!==entry.segments.length-1||entry.isDirectory?1:0}function comparePreparedEntries(left,right){const sharedDepth=Math.min(left.segments.length,right.segments.length);for(let depth=0;depth<sharedDepth;depth++){const leftSegment=left.segments[depth],rightSegment=right.segments[depth];if(leftSegment===rightSegment)continue;const leftKind=getKindAtDepth(left,depth);return leftKind!==getKindAtDepth(right,depth)?leftKind===1?-1:1:compareSegmentValues(leftSegment,rightSegment)}return left.segments.length!==right.segments.length?left.segments.length<right.segments.length?-1:1:left.isDirectory===right.isDirectory?0:left.isDirectory?-1:1}function comparePreparedPaths(left,right){return comparePreparedEntries(left,right)}function comparePreparedPathsWithCachedSortKeys(left,right,cache){const getCachedSortKey=value=>{const existingKey=cache.get(value);if(existingKey!=null)return existingKey;const nextKey=createSegmentSortKey(value);return cache.set(value,nextKey),nextKey},sharedDepth=Math.min(left.segments.length,right.segments.length);for(let depth=0;depth<sharedDepth;depth++){const leftSegment=left.segments[depth],rightSegment=right.segments[depth];if(leftSegment===rightSegment)continue;const leftKind=getKindAtDepth(left,depth);return leftKind!==getKindAtDepth(right,depth)?leftKind===1?-1:1:compareSegmentValuesWithSortKeyLookup(leftSegment,rightSegment,getCachedSortKey)}return left.segments.length!==right.segments.length?left.segments.length<right.segments.length?-1:1:left.isDirectory===right.isDirectory?0:left.isDirectory?-1:1}function getSegmentSortKey(segmentTable,segmentId){const existingKey=segmentTable.sortKeyById[segmentId];if(existingKey!==void 0)return existingKey;const value=segmentTable.valueById[segmentId],nextKey=createSegmentSortKey(value);return segmentTable.sortKeyById[segmentId]=nextKey,nextKey}function resolvePathStoreOptions(options={}){return{flattenEmptyDirectories:options.flattenEmptyDirectories!==!1,sort:options.sort??"default"}}function splitCanonicalPath(inputPath){const hasTrailingSlash=inputPath.length>0&&inputPath.charCodeAt(inputPath.length-1)===47,endIndex=hasTrailingSlash?inputPath.length-1:inputPath.length,segments=[];let segmentStart=0;for(let index=0;index<endIndex;index++)inputPath.charCodeAt(index)===47&&(segments.push(inputPath.slice(segmentStart,index)),segmentStart=index+1);return segments.push(inputPath.slice(segmentStart,endIndex)),{hasTrailingSlash,segments}}function parseInputPath(inputPath){const{hasTrailingSlash,segments}=splitCanonicalPath(inputPath);return{basename:segments[segments.length-1]??"",isDirectory:hasTrailingSlash,path:inputPath,segments}}function parseLookupPath(inputPath){if(inputPath.length===0)return{requiresDirectory:!1,segments:[]};const{hasTrailingSlash,segments}=splitCanonicalPath(inputPath);return{requiresDirectory:hasTrailingSlash,segments}}function createSegmentTable(){const idByValue=new Map;return idByValue.set("",0),{idByValue,valueById:[""],sortKeyById:[createSegmentSortKey("")]}}function internSegment(segmentTable,value){const existingId=segmentTable.idByValue.get(value);if(existingId!==void 0)return existingId;const nextId=segmentTable.valueById.length;return segmentTable.idByValue.set(value,nextId),segmentTable.valueById.push(value),nextId}function getSegmentValue(segmentTable,segmentId){const value=segmentTable.valueById[segmentId];if(value===void 0)throw new Error(`Unknown segment ID: ${String(segmentId)}`);return value}const PREPARED_INPUT_KIND=Symbol("pathStorePreparedInputKind");function attachPreparedInputKind(value,kind){return value[PREPARED_INPUT_KIND]=kind,value}function createCompareEntry$1(preparedPath){return{basename:preparedPath.basename,depth:preparedPath.segments.length,isDirectory:preparedPath.isDirectory,path:preparedPath.path,segments:preparedPath.segments}}function compareWithSortOption(left,right,sort){return sort==="default"?comparePreparedPaths(left,right):sort(createCompareEntry$1(left),createCompareEntry$1(right))}function createRootNode(){return{depthAndFlags:createNodeDepthAndFlags(0,3,1),nameId:0,parentId:0,subtreeNodeCount:1,visibleSubtreeCount:1}}function computeSharedPrefixLength(left,right){const maxLength=Math.min(left.length,right.length);for(let index=0;index<maxLength;index++)if(left[index]!==right[index])return index;return maxLength}function getDirectoryDepth(preparedPath){return preparedPath.isDirectory?preparedPath.segments.length:preparedPath.segments.length-1}function isPreparedPathArray(value){return Array.isArray(value)&&value.every(entry=>entry!=null&&typeof entry=="object"&&typeof entry.path=="string"&&Array.isArray(entry.segments)&&typeof entry.basename=="string"&&typeof entry.isDirectory=="boolean")}function isStringArray(value){return Array.isArray(value)&&value.every(entry=>typeof entry=="string")}function preparePaths(paths,options={}){return preparePathEntries(paths,options).map(entry=>entry.path)}function prepareInput(paths,options={}){const preparedPaths=preparePathEntries(paths,options);return attachPreparedInputKind({paths:preparedPaths.map(entry=>entry.path),preparedPaths},"prepared")}function preparePresortedInput(paths){const pathCount=paths.length;let presortedPathsContainDirectories=!1;for(let index=0;index<pathCount;index+=1){const path=paths[index];if(path.length>0&&path.charCodeAt(path.length-1)===47){presortedPathsContainDirectories=!0;break}}return attachPreparedInputKind({paths,presortedPaths:paths,presortedPathsContainDirectories},"presorted")}function getPreparedInputEntries(preparedInput){const internalPreparedInput=preparedInput,preparedPaths=internalPreparedInput.preparedPaths;if(internalPreparedInput[PREPARED_INPUT_KIND]==="prepared"&&preparedPaths!=null)return preparedPaths;if(!isPreparedPathArray(preparedPaths))throw new Error("preparedInput must come from PathStore.prepareInput()");return preparedPaths}function getPreparedInputPresortedPaths(preparedInput){const internalPreparedInput=preparedInput;return internalPreparedInput[PREPARED_INPUT_KIND]==="presorted"&&internalPreparedInput.presortedPaths!=null||isStringArray(internalPreparedInput.presortedPaths)?internalPreparedInput.presortedPaths:null}function getPreparedInputPresortedPathsContainDirectories(preparedInput){const internalPreparedInput=preparedInput;return typeof internalPreparedInput.presortedPathsContainDirectories=="boolean"?internalPreparedInput.presortedPathsContainDirectories:null}function preparePathEntries(paths,options={}){const resolvedOptions=resolvePathStoreOptions(options),instrumentation=getBenchmarkInstrumentation(options);setBenchmarkCounter(instrumentation,"workload.inputFiles",paths.length);const preparedPaths=withBenchmarkPhase(instrumentation,"store.preparePathEntries.parse",()=>paths.map(path=>parseInputPath(path)));return withBenchmarkPhase(instrumentation,"store.preparePathEntries.sort",()=>preparedPaths.sort((left,right)=>compareWithSortOption(left,right,resolvedOptions.sort))),preparedPaths}var PathStoreBuilder=class{directories=new Map;directoryStack=[0];presortedDirectoryNodeIds=[];initialExpandedPathSet;createdDirectoriesAllExpanded=!1;createdDirectoryCount=0;lastPreparedPath=null;nodes=[createRootNode()];options;instrumentation;segmentSortKeyCache=new Map;segmentTable=createSegmentTable();hasDeferredDirectoryIndexes=!1;constructor(options={}){this.instrumentation=getBenchmarkInstrumentation(options),this.options=resolvePathStoreOptions(options);const initialExpandedPaths=options.initialExpandedPaths??null;if(initialExpandedPaths==null||initialExpandedPaths.length===0)this.initialExpandedPathSet=null;else{const normalizedPaths=new Set,hintCount=initialExpandedPaths.length;for(let index=0;index<hintCount;index+=1){const path=initialExpandedPaths[index],length=path.length;normalizedPaths.add(length>0&&path.charCodeAt(length-1)===47?path.slice(0,length-1):path)}this.initialExpandedPathSet=normalizedPaths,this.createdDirectoriesAllExpanded=!0}this.directories.set(0,createDirectoryChildIndex())}appendPaths(paths){return withBenchmarkPhase(this.instrumentation,"store.builder.appendPaths.parse",()=>this.appendPreparedPaths(paths.map(path=>parseInputPath(path))))}appendPreparedPaths(preparedPaths,validateOrder=!0){return this.createdDirectoriesAllExpanded=!1,withBenchmarkPhase(this.instrumentation,"store.builder.appendPreparedPaths",()=>{for(const preparedPath of preparedPaths)this.appendPreparedPath(preparedPath,validateOrder)}),this}appendPresortedPaths(paths,containsDirectories=null){return withBenchmarkPhase(this.instrumentation,"store.builder.appendPresortedPaths",()=>{if(containsDirectories===!1){this.appendPresortedFilePaths(paths);return}this.createdDirectoriesAllExpanded=!1;let previousPath=null,currentDepth=0;const nodes=this.nodes,segmentTable=this.segmentTable,idByValue=segmentTable.idByValue,valueById=segmentTable.valueById,dirStack=this.directoryStack;let stackTop=0,cachedDirPrefix="",cachedDirDepth=0;for(const path of paths){if(previousPath===path)throw new Error(`Duplicate path: "${path}"`);const hasTrailingSlash=path.length>0&&path.charCodeAt(path.length-1)===47,endIndex=hasTrailingSlash?path.length-1:path.length;let sharedDirectoryDepth=0,unsharedSegmentStart=0;if(previousPath!=null)if(cachedDirPrefix.length>0&&path.length>cachedDirPrefix.length&&path.startsWith(cachedDirPrefix))sharedDirectoryDepth=cachedDirDepth,unsharedSegmentStart=cachedDirPrefix.length;else{const compareLength=Math.min(endIndex,previousPath.length);let prefixMatched=!0;for(let ci=0;ci<compareLength;ci++){const cc=path.charCodeAt(ci);if(cc!==previousPath.charCodeAt(ci)){prefixMatched=!1;break}cc===47&&(sharedDirectoryDepth++,unsharedSegmentStart=ci+1)}prefixMatched&&hasTrailingSlash&&compareLength===endIndex&&previousPath.length>endIndex&&previousPath.charCodeAt(endIndex)===47&&(sharedDirectoryDepth++,unsharedSegmentStart=endIndex+1)}stackTop=sharedDirectoryDepth,currentDepth=sharedDirectoryDepth;let segmentStart=unsharedSegmentStart,slashPos=path.indexOf("/",segmentStart);for(;slashPos>=0&&slashPos<endIndex;){const parentId=dirStack[stackTop];if(parentId===void 0)throw new Error("Directory stack underflow while building the path store");currentDepth++;const dirSeg=path.slice(segmentStart,slashPos);let dirNameId=idByValue.get(dirSeg);dirNameId===void 0&&(dirNameId=valueById.length,idByValue.set(dirSeg,dirNameId),valueById.push(dirSeg));const nodeId=nodes.length;nodes.push({depthAndFlags:createNodeDepthAndFlags(currentDepth,0,1),nameId:dirNameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),this.recordCreatedDirectoryPath(path.slice(0,slashPos)),stackTop++,dirStack[stackTop]=nodeId,segmentStart=slashPos+1,slashPos=path.indexOf("/",segmentStart)}if(hasTrailingSlash){if(segmentStart<endIndex){const parentId=dirStack[stackTop];if(parentId===void 0)throw new Error(`Unable to resolve directory parent for "${path}"`);currentDepth++;const trailSeg=path.slice(segmentStart,endIndex);let trailNameId=idByValue.get(trailSeg);trailNameId===void 0&&(trailNameId=valueById.length,idByValue.set(trailSeg,trailNameId),valueById.push(trailSeg));const nodeId=nodes.length;nodes.push({depthAndFlags:createNodeDepthAndFlags(currentDepth,0,1),nameId:trailNameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),stackTop++,dirStack[stackTop]=nodeId,segmentStart=endIndex+1}const directoryId=dirStack[stackTop];if(directoryId===void 0)throw new Error(`Unable to resolve directory node for "${path}"`);this.promoteDirectoryToExplicit(directoryId,path)}else{const parentId=dirStack[stackTop];if(parentId===void 0)throw new Error(`Unable to resolve file parent for "${path}"`);const fileSeg=path.slice(segmentStart);let fileNameId=idByValue.get(fileSeg);fileNameId===void 0&&(fileNameId=valueById.length,idByValue.set(fileSeg,fileNameId),valueById.push(fileSeg)),nodes.push({depthAndFlags:createNodeDepthAndFlags(currentDepth+1,0),nameId:fileNameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1})}segmentStart!==cachedDirPrefix.length&&(cachedDirPrefix=path.substring(0,segmentStart),cachedDirDepth=currentDepth),previousPath=path}dirStack.length=stackTop+1,previousPath!=null&&(this.lastPreparedPath=parseInputPath(previousPath)),this.hasDeferredDirectoryIndexes=!0}),this}appendPresortedFilePaths(paths){let previousPath=null,currentDepth=0;const nodes=this.nodes,segmentTable=this.segmentTable,idByValue=segmentTable.idByValue,valueById=segmentTable.valueById,dirStack=this.directoryStack;let stackTop=0,cachedDirPrefix="",cachedDirDepth=0;for(const path of paths){if(previousPath===path)throw new Error(`Duplicate path: "${path}"`);const endIndex=path.length;let sharedDirectoryDepth=0,unsharedSegmentStart=0;if(previousPath!=null)if(cachedDirPrefix.length>0&&path.length>cachedDirPrefix.length&&path.startsWith(cachedDirPrefix))sharedDirectoryDepth=cachedDirDepth,unsharedSegmentStart=cachedDirPrefix.length;else{const compareLength=Math.min(endIndex,previousPath.length);for(let ci=0;ci<compareLength;ci++){const cc=path.charCodeAt(ci);if(cc!==previousPath.charCodeAt(ci))break;cc===47&&(sharedDirectoryDepth++,unsharedSegmentStart=ci+1)}}stackTop=sharedDirectoryDepth,currentDepth=sharedDirectoryDepth;let segmentStart=unsharedSegmentStart,slashPos=path.indexOf("/",segmentStart);for(;slashPos>=0;){const parentId2=dirStack[stackTop];if(parentId2===void 0)throw new Error("Directory stack underflow while building the path store");currentDepth++;const dirSeg=path.slice(segmentStart,slashPos);let dirNameId=idByValue.get(dirSeg);dirNameId===void 0&&(dirNameId=valueById.length,idByValue.set(dirSeg,dirNameId),valueById.push(dirSeg));const nodeId=nodes.length;nodes.push({depthAndFlags:createNodeDepthAndFlags(currentDepth,0,1),nameId:dirNameId,parentId:parentId2,subtreeNodeCount:1,visibleSubtreeCount:1}),this.recordCreatedDirectoryPath(path.slice(0,slashPos)),this.presortedDirectoryNodeIds.push(nodeId),stackTop++,dirStack[stackTop]=nodeId,segmentStart=slashPos+1,slashPos=path.indexOf("/",segmentStart)}const parentId=dirStack[stackTop];if(parentId===void 0)throw new Error(`Unable to resolve file parent for "${path}"`);const fileSeg=path.slice(segmentStart);let fileNameId=idByValue.get(fileSeg);fileNameId===void 0&&(fileNameId=valueById.length,idByValue.set(fileSeg,fileNameId),valueById.push(fileSeg)),nodes.push({depthAndFlags:createNodeDepthAndFlags(currentDepth+1,0),nameId:fileNameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),segmentStart!==cachedDirPrefix.length&&(cachedDirPrefix=path.substring(0,segmentStart),cachedDirDepth=currentDepth),previousPath=path}dirStack.length=stackTop+1,previousPath!=null&&(this.lastPreparedPath=parseInputPath(previousPath)),this.hasDeferredDirectoryIndexes=!0}finish(options={}){const skipSubtreeCountPass=options.skipSubtreeCountPass===!0;return this.hasDeferredDirectoryIndexes?(withBenchmarkPhase(this.instrumentation,"store.builder.buildDirectoryIndexes",()=>this.buildPresortedFinish(skipSubtreeCountPass)),this.hasDeferredDirectoryIndexes=!1):skipSubtreeCountPass||withBenchmarkPhase(this.instrumentation,"store.builder.computeSubtreeCounts",()=>this.computeSubtreeCounts(0)),{directories:this.directories,nodes:this.nodes,options:this.options,rootId:0,segmentTable:this.segmentTable,presortedDirectoryNodeIds:this.presortedDirectoryNodeIds.length>0?this.presortedDirectoryNodeIds:null}}didMatchAllInitialExpandedPaths(){return this.createdDirectoriesAllExpanded&&this.initialExpandedPathSet!=null&&this.createdDirectoryCount===this.initialExpandedPathSet.size}appendPreparedPath(preparedPath,validateOrder){if(this.hasDeferredDirectoryIndexes&&(this.buildDirectoryIndexes(),this.hasDeferredDirectoryIndexes=!1),this.lastPreparedPath!=null){if(preparedPath.path===this.lastPreparedPath.path)throw new Error(`Duplicate path: "${preparedPath.path}"`);if(validateOrder&&(this.options.sort==="default"?comparePreparedPathsWithCachedSortKeys(this.lastPreparedPath,preparedPath,this.segmentSortKeyCache):compareWithSortOption(this.lastPreparedPath,preparedPath,this.options.sort))>0)throw new Error(`Builder input must be sorted before appendPaths(): "${preparedPath.path}"`)}const previousPath=this.lastPreparedPath,currentDirectoryDepth=getDirectoryDepth(preparedPath),previousDirectoryDepth=previousPath==null?0:getDirectoryDepth(previousPath),sharedPrefixLength=previousPath==null?0:computeSharedPrefixLength(previousPath.segments,preparedPath.segments),sharedDirectoryDepth=Math.min(sharedPrefixLength,currentDirectoryDepth,previousDirectoryDepth);this.directoryStack.length=sharedDirectoryDepth+1;for(let segmentIndex=sharedDirectoryDepth;segmentIndex<currentDirectoryDepth;segmentIndex++){const parentId2=this.directoryStack[this.directoryStack.length-1];if(parentId2===void 0)throw new Error("Directory stack underflow while building the path store");const childId=validateOrder?this.getOrCreateDirectoryChild(parentId2,preparedPath.segments[segmentIndex]):this.createDirectoryChild(parentId2,preparedPath.segments[segmentIndex]);this.directoryStack.push(childId)}if(preparedPath.isDirectory){const directoryId=this.directoryStack[this.directoryStack.length-1];if(directoryId===void 0)throw new Error(`Unable to resolve directory node for "${preparedPath.path}"`);this.promoteDirectoryToExplicit(directoryId,preparedPath.path),this.lastPreparedPath=preparedPath;return}const parentId=this.directoryStack[this.directoryStack.length-1];if(parentId===void 0)throw new Error(`Unable to resolve file parent for "${preparedPath.path}"`);validateOrder?this.createFileChild(parentId,preparedPath.basename,preparedPath.path):this.createFileChildUnchecked(parentId,preparedPath.basename),this.lastPreparedPath=preparedPath}recordCreatedDirectoryPath(path){!this.createdDirectoriesAllExpanded||this.initialExpandedPathSet==null||(this.createdDirectoryCount+=1,this.initialExpandedPathSet.has(path)||(this.createdDirectoriesAllExpanded=!1))}createFileChild(parentId,basename,path){const nameId=internSegment(this.segmentTable,basename),parentIndex=this.getDirectoryIndex(parentId),nameMap=parentIndex.childIdByNameId;if(nameMap!=null&&nameMap.get(nameId)!==void 0)throw new Error(`Path collides with an existing entry: "${path}"`);const parentNode=this.nodes[parentId];if(parentNode===void 0)throw new Error(`Unknown parent node ID: ${String(parentId)}`);const nodeId=this.nodes.length;return this.nodes.push({depthAndFlags:createNodeDepthAndFlags(getNodeDepth(parentNode)+1,0),nameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),nameMap?.set(nameId,nodeId),appendChildReference(parentIndex,nodeId),nodeId}createFileChildUnchecked(parentId,basename){const nameId=internSegment(this.segmentTable,basename),parentIndex=this.getDirectoryIndex(parentId),parentNode=this.nodes[parentId];if(parentNode===void 0)throw new Error(`Unknown parent node ID: ${String(parentId)}`);const nodeId=this.nodes.length;return this.nodes.push({depthAndFlags:createNodeDepthAndFlags(getNodeDepth(parentNode)+1,0),nameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),parentIndex.childIdByNameId!=null&&parentIndex.childIdByNameId.set(nameId,nodeId),appendChildReference(parentIndex,nodeId),nodeId}getOrCreateDirectoryChild(parentId,segment){const nameId=internSegment(this.segmentTable,segment),parentIndex=this.getDirectoryIndex(parentId);if(parentIndex.childIdByNameId!=null){const existingChildId=parentIndex.childIdByNameId.get(nameId);if(existingChildId!==void 0){const existingNode=this.nodes[existingChildId];if(existingNode!=null&&!isDirectoryNode(existingNode))throw new Error(`Path collides with an existing file while creating directory "${segment}"`);return existingChildId}}const parentNode=this.nodes[parentId];if(parentNode===void 0)throw new Error(`Unknown parent node ID: ${String(parentId)}`);const nodeId=this.nodes.length;return this.nodes.push({depthAndFlags:createNodeDepthAndFlags(getNodeDepth(parentNode)+1,0,1),nameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),parentIndex.childIdByNameId!=null&&parentIndex.childIdByNameId.set(nameId,nodeId),appendChildReference(parentIndex,nodeId),this.directories.set(nodeId,createDirectoryChildIndex()),nodeId}createDirectoryChild(parentId,segment){const nameId=internSegment(this.segmentTable,segment),parentIndex=this.getDirectoryIndex(parentId),parentNode=this.nodes[parentId];if(parentNode===void 0)throw new Error(`Unknown parent node ID: ${String(parentId)}`);const nodeId=this.nodes.length;return this.nodes.push({depthAndFlags:createNodeDepthAndFlags(getNodeDepth(parentNode)+1,0,1),nameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),parentIndex.childIdByNameId!=null&&parentIndex.childIdByNameId.set(nameId,nodeId),appendChildReference(parentIndex,nodeId),this.directories.set(nodeId,createDirectoryChildIndex()),nodeId}promoteDirectoryToExplicit(directoryId,path){const directoryNode=this.nodes[directoryId];if(directoryNode===void 0)throw new Error(`Unknown directory node ID: ${String(directoryId)}`);if(!isDirectoryNode(directoryNode))throw new Error(`Path is not a directory: "${path}"`);if(hasNodeFlag(directoryNode,1))throw new Error(`Duplicate path: "${path}"`);addNodeFlag(directoryNode,1)}getDirectoryIndex(directoryId){const existingIndex=this.directories.get(directoryId);if(existingIndex!==void 0)return existingIndex;throw new Error(`Unknown directory child index for node ${String(directoryId)}`)}buildPresortedFinish(skipSubtreeCountPass){const nodes=this.nodes,directories=this.directories;directories.set(0,createPresortedDirectoryChildIndex());let cachedParentId=-1,cachedParentIndex=null;for(let nodeId=1;nodeId<nodes.length;nodeId++){const node=nodes[nodeId];if(node==null)continue;if(isDirectoryNode(node)){const dirIndex=createPresortedDirectoryChildIndex();directories.set(nodeId,dirIndex),cachedParentId=nodeId,cachedParentIndex=dirIndex}let parentIndex;node.parentId===cachedParentId?parentIndex=cachedParentIndex:(parentIndex=directories.get(node.parentId),cachedParentId=node.parentId,cachedParentIndex=parentIndex??null),parentIndex?.childIds.push(nodeId)}if(!skipSubtreeCountPass)for(let nodeId=nodes.length-1;nodeId>=1;nodeId--){const node=nodes[nodeId];if(node==null)continue;const parentNode=nodes[node.parentId];parentNode!=null&&(parentNode.subtreeNodeCount+=node.subtreeNodeCount,parentNode.visibleSubtreeCount+=node.visibleSubtreeCount)}}buildDirectoryIndexes(){const nodes=this.nodes;for(let nodeId=1;nodeId<nodes.length;nodeId++){const node=nodes[nodeId];if(node==null)continue;isDirectoryNode(node)&&this.directories.set(nodeId,createDirectoryChildIndex());const parentIndex=this.directories.get(node.parentId);parentIndex!=null&&(parentIndex.childIdByNameId!=null&&parentIndex.childIdByNameId.set(node.nameId,nodeId),appendChildReference(parentIndex,nodeId))}}computeSubtreeCounts(nodeId){const node=this.nodes[nodeId];if(node===void 0)throw new Error(`Unknown node ID: ${String(nodeId)}`);if(!isDirectoryNode(node))return node.subtreeNodeCount=1,node.visibleSubtreeCount=1,1;const directoryIndex=this.getDirectoryIndex(nodeId);let subtreeNodeCount=1;for(const childId of directoryIndex.childIds)subtreeNodeCount+=this.computeSubtreeCounts(childId);return rebuildDirectoryChildAggregates(this.nodes,directoryIndex),node.subtreeNodeCount=subtreeNodeCount,node.visibleSubtreeCount=subtreeNodeCount,subtreeNodeCount}};function createPathStoreState(snapshot,initialExpansion="closed",instrumentation=null){const defaultExpansion=resolveInitialExpansion(initialExpansion);return{activeNodeCount:snapshot.nodes.length-1,collapsedDirectoryIds:new Set,collapseNewDirectoriesByDefault:!1,defaultExpansion,directoriesOpenByDefault:defaultExpansion==="open",hasCollapsedDirectoryOverrides:!1,directoryLoadInfoById:new Map,expandedDirectoryIds:new Set,instrumentation,listeners:new Map,pathCacheByNodeId:new Map([[snapshot.rootId,{path:"",version:0}]]),pathCacheVersion:0,snapshot,transactionStack:[]}}function createTransactionFrame(){return{affectedAncestorIds:new Set,affectedNodeIds:new Set,events:[]}}function resolveInitialExpansion(initialExpansion){if(typeof initialExpansion!="number")return initialExpansion;if(!Number.isInteger(initialExpansion)||initialExpansion<0)throw new Error(`initialExpansion must be "open", "closed", or a non-negative integer depth. Received: ${String(initialExpansion)}`);return initialExpansion}function isDirectoryExpandedByDefault(state,node){return hasNodeFlag(node,2)||state.defaultExpansion==="open"?!0:state.defaultExpansion==="closed"?!1:getNodeDepth(node)<=state.defaultExpansion}function isDirectoryExpanded(state,nodeId,node=state.snapshot.nodes[nodeId]){return node==null||!isDirectoryNode(node)?!1:state.directoriesOpenByDefault&&!state.hasCollapsedDirectoryOverrides?!0:state.collapsedDirectoryIds.has(nodeId)?!1:state.expandedDirectoryIds.has(nodeId)?!0:isDirectoryExpandedByDefault(state,node)}function setDirectoryExpanded(state,nodeId,expanded,node=state.snapshot.nodes[nodeId]){if(node==null||!isDirectoryNode(node))return;const expandedByDefault=isDirectoryExpandedByDefault(state,node);if(expanded){if(expandedByDefault){state.collapsedDirectoryIds.delete(nodeId),state.hasCollapsedDirectoryOverrides=state.collapsedDirectoryIds.size>0;return}state.expandedDirectoryIds.add(nodeId);return}if(expandedByDefault){state.collapsedDirectoryIds.add(nodeId),state.hasCollapsedDirectoryOverrides=!0;return}state.expandedDirectoryIds.delete(nodeId)}function getOrCreateDirectoryLoadInfo(state,nodeId){const existingInfo=state.directoryLoadInfoById.get(nodeId);if(existingInfo!=null)return existingInfo;const nextInfo={activeAttemptId:null,errorMessage:null,nextAttemptId:1,state:"loaded"};return state.directoryLoadInfoById.set(nodeId,nextInfo),nextInfo}function getDirectoryLoadState(state,nodeId){return state.directoryLoadInfoById.get(nodeId)?.state??"loaded"}function beginDirectoryLoad(state,nodeId){const loadInfo=getOrCreateDirectoryLoadInfo(state,nodeId);if(loadInfo.state==="loading"&&loadInfo.activeAttemptId!=null)return{attemptId:loadInfo.activeAttemptId,nodeId,reused:!0};const attemptId=loadInfo.nextAttemptId;return loadInfo.activeAttemptId=attemptId,loadInfo.errorMessage=null,loadInfo.nextAttemptId+=1,loadInfo.state="loading",{attemptId,nodeId,reused:!1}}function markDirectoryUnloadedState(state,nodeId){const loadInfo=getOrCreateDirectoryLoadInfo(state,nodeId);loadInfo.activeAttemptId=null,loadInfo.errorMessage=null,loadInfo.state="unloaded"}function completeDirectoryLoad(state,nodeId,attemptId){const loadInfo=state.directoryLoadInfoById.get(nodeId);return loadInfo==null||loadInfo.activeAttemptId!==attemptId?!1:(loadInfo.activeAttemptId=null,loadInfo.errorMessage=null,loadInfo.state="loaded",!0)}function isDirectoryLoadAttemptCurrent(state,nodeId,attemptId){return state.directoryLoadInfoById.get(nodeId)?.activeAttemptId===attemptId}function failDirectoryLoad(state,nodeId,attemptId,errorMessage){const loadInfo=state.directoryLoadInfoById.get(nodeId);return loadInfo==null||loadInfo.activeAttemptId!==attemptId?!1:(loadInfo.activeAttemptId=null,loadInfo.errorMessage=errorMessage??null,loadInfo.state="error",!0)}function clearDirectoryLoadInfo(state,nodeId){state.directoryLoadInfoById.delete(nodeId)}function subscribe(state,type,handler){const rawHandler=handler,existingListeners=state.listeners.get(type);return existingListeners!=null?existingListeners.add(rawHandler):state.listeners.set(type,new Set([rawHandler])),()=>{const listeners=state.listeners.get(type);listeners!=null&&(listeners.delete(rawHandler),listeners.size===0&&state.listeners.delete(type))}}function createAddEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],canonicalChanged:!0,operation:"add",path:args.path,projectionChanged:args.projectionChanged,visibleCountDelta:null}}function createRemoveEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],canonicalChanged:!0,operation:"remove",path:args.path,projectionChanged:args.projectionChanged,recursive:args.recursive,visibleCountDelta:null}}function createMoveEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],canonicalChanged:!0,from:args.from,operation:"move",projectionChanged:args.projectionChanged,to:args.to,visibleCountDelta:null}}function createExpandEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],canonicalChanged:!1,operation:"expand",path:args.path,projectionChanged:!0,visibleCountDelta:null}}function createCollapseEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],canonicalChanged:!1,operation:"collapse",path:args.path,projectionChanged:!0,visibleCountDelta:null}}function createMarkDirectoryUnloadedEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],canonicalChanged:!1,operation:"mark-directory-unloaded",path:args.path,projectionChanged:args.projectionChanged,visibleCountDelta:null}}function createBeginChildLoadEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],attemptId:args.attemptId,canonicalChanged:!1,operation:"begin-child-load",path:args.path,projectionChanged:args.projectionChanged,reused:args.reused,visibleCountDelta:null}}function createApplyChildPatchEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],attemptId:args.attemptId,canonicalChanged:args.childEvents.some(event=>event.canonicalChanged),childEvents:args.childEvents,operation:"apply-child-patch",path:args.path,projectionChanged:args.projectionChanged,visibleCountDelta:null}}function createCompleteChildLoadEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],attemptId:args.attemptId,canonicalChanged:!1,operation:"complete-child-load",path:args.path,projectionChanged:args.projectionChanged,stale:args.stale,visibleCountDelta:null}}function createFailChildLoadEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],attemptId:args.attemptId,canonicalChanged:!1,errorMessage:args.errorMessage,operation:"fail-child-load",path:args.path,projectionChanged:args.projectionChanged,stale:args.stale,visibleCountDelta:null}}function createCleanupEvent(args){return{activeNodeCountAfter:args.activeNodeCountAfter,activeNodeCountBefore:args.activeNodeCountBefore,affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],cachedPathEntryCountAfter:args.cachedPathEntryCountAfter,cachedPathEntryCountBefore:args.cachedPathEntryCountBefore,canonicalChanged:!1,idsPreserved:args.idsPreserved,loadInfoEntryCountAfter:args.loadInfoEntryCountAfter,loadInfoEntryCountBefore:args.loadInfoEntryCountBefore,mode:args.mode,operation:"cleanup",projectionChanged:args.projectionChanged,reclaimedCachedPathEntryCount:args.reclaimedCachedPathEntryCount,reclaimedLoadInfoEntryCount:args.reclaimedLoadInfoEntryCount,reclaimedNodeSlotCount:args.reclaimedNodeSlotCount,reclaimedSegmentCount:args.reclaimedSegmentCount,segmentCountAfter:args.segmentCountAfter,segmentCountBefore:args.segmentCountBefore,totalNodeSlotCountAfter:args.totalNodeSlotCountAfter,totalNodeSlotCountBefore:args.totalNodeSlotCountBefore,visibleCountDelta:null}}function finalizeEvent(state,previousVisibleCount,event){return{...event,visibleCountDelta:getCurrentVisibleCount(state)-previousVisibleCount}}function batchEvents(state,run){const previousVisibleCount=getCurrentVisibleCount(state),frame=createTransactionFrame();state.transactionStack.push(frame);try{run()}catch(error){throw finishTransaction(state,frame,!1),error}finishTransaction(state,frame,!0,getCurrentVisibleCount(state)-previousVisibleCount)}function recordEvent(state,event){const instrumentation=state.instrumentation;if(instrumentation==null){recordEventNow(state,event);return}withBenchmarkPhase(instrumentation,"store.events.record",()=>recordEventNow(state,event))}function recordEventNow(state,event){const currentFrame=state.transactionStack[state.transactionStack.length-1]??null;if(currentFrame==null){emitEvent(state,event);return}currentFrame.events.push(event),mergeEventMetadataIntoFrame(currentFrame,event)}function finishTransaction(state,frame,emit,visibleCountDelta=null){if(state.transactionStack.pop()!==frame)throw new Error("Transaction stack underflow");if(!emit)return;const parentFrame=state.transactionStack[state.transactionStack.length-1]??null;if(parentFrame!=null){const instrumentation2=state.instrumentation;instrumentation2==null?mergeBatchFrameIntoParent(parentFrame,frame):withBenchmarkPhase(instrumentation2,"store.events.batch.merge",()=>mergeBatchFrameIntoParent(parentFrame,frame));return}const batchEvent=createBatchEvent(frame,visibleCountDelta),instrumentation=state.instrumentation;if(instrumentation==null){emitEvent(state,batchEvent);return}withBenchmarkPhase(instrumentation,"store.events.batch.commit",()=>emitEvent(state,batchEvent))}function createBatchEvent(frame,visibleCountDelta){return{affectedAncestorIds:[...frame.affectedAncestorIds],affectedNodeIds:[...frame.affectedNodeIds],canonicalChanged:frame.events.some(event=>event.canonicalChanged),events:[...frame.events],operation:"batch",projectionChanged:frame.events.some(event=>event.projectionChanged),visibleCountDelta}}function mergeFrameMetadata(target,source){for(const nodeId of source.affectedAncestorIds)target.affectedAncestorIds.add(nodeId);for(const nodeId of source.affectedNodeIds)target.affectedNodeIds.add(nodeId)}function mergeBatchFrameIntoParent(parentFrame,frame){for(const event of frame.events)parentFrame.events.push(event);mergeFrameMetadata(parentFrame,frame)}function mergeEventMetadataIntoFrame(frame,event){for(const nodeId of event.affectedNodeIds)frame.affectedNodeIds.add(nodeId);for(const nodeId of event.affectedAncestorIds)frame.affectedAncestorIds.add(nodeId)}function emitEvent(state,event){const instrumentation=state.instrumentation;if(instrumentation==null){emitEventNow(state,event);return}withBenchmarkPhase(instrumentation,"store.events.emit",()=>emitEventNow(state,event))}function emitEventNow(state,event){state.listeners.get(event.operation)?.forEach(handler=>handler(event)),state.listeners.get("*")?.forEach(handler=>handler(event))}function getCurrentVisibleCount(state){return state.snapshot.nodes[state.snapshot.rootId]?.visibleSubtreeCount??0}function getFlattenedChildDirectoryId(state,directoryNodeId){if(state.snapshot.options.flattenEmptyDirectories!==!0)return null;const directoryNode=state.snapshot.nodes[directoryNodeId];if(directoryNode==null||!isDirectoryNode(directoryNode)||hasNodeFlag(directoryNode,2))return null;const directoryIndex=state.snapshot.directories.get(directoryNodeId);if(directoryIndex==null||directoryIndex.childIds.length!==1)return null;const childId=directoryIndex.childIds[0];if(childId==null)return null;const childNode=state.snapshot.nodes[childId];return childNode==null||!isDirectoryNode(childNode)?null:childId}function getFlattenedTerminalDirectoryId(state,directoryNodeId){let currentDirectoryId=directoryNodeId;for(;;){const nextDirectoryId=getFlattenedChildDirectoryId(state,currentDirectoryId);if(nextDirectoryId==null)return currentDirectoryId;currentDirectoryId=nextDirectoryId}}function collectFlattenedDirectoryChainIds(state,directoryNodeId){const chainIds=[directoryNodeId];let currentDirectoryId=directoryNodeId;for(;;){const nextDirectoryId=getFlattenedChildDirectoryId(state,currentDirectoryId);if(nextDirectoryId==null)return chainIds;chainIds.push(nextDirectoryId),currentDirectoryId=nextDirectoryId}}function listPaths(state,path){const nodeId=path==null?state.snapshot.rootId:findNodeId(state,path);return nodeId==null?[]:collectCanonicalEntries(state,nodeId)}function addPath(state,path){const preparedPath=parseInputPath(path),parentSegments=preparedPath.isDirectory?preparedPath.segments:preparedPath.segments.slice(0,-1),previousProjectionSignature=getCollapsedProjectionSignature(state,findDeepestExistingDirectoryId(state,parentSegments)),{createdNodeIds,directoryId}=ensureDirectoryChain(state,parentSegments),affectedNodeIds=new Set(createdNodeIds);let addedNodeId=directoryId;if(preparedPath.isDirectory){const directoryNode=requireNode(state,directoryId);if(hasNodeFlag(directoryNode,1))throw new Error(`Path already exists: "${path}"`);addNodeFlag(directoryNode,1),state.pathCacheByNodeId.set(directoryId,{path,version:state.pathCacheVersion}),affectedNodeIds.add(directoryId)}else addedNodeId=createFileNode(state,directoryId,preparedPath.basename),affectedNodeIds.add(addedNodeId);recomputeCountsUpwardFrom(state,directoryId);const nextProjectionSignature=getCollapsedProjectionSignature(state,directoryId);return createAddEvent({affectedAncestorIds:collectAncestorIds(state,addedNodeId),affectedNodeIds:[...affectedNodeIds],path,projectionChanged:didProjectionChange(previousProjectionSignature,nextProjectionSignature)})}function removePath(state,path,options){const nodeId=findNodeId(state,path);if(nodeId==null)throw new Error(`Path does not exist: "${path}"`);const node=requireNode(state,nodeId);if(hasNodeFlag(node,2))throw new Error("The root node cannot be removed");if(isDirectoryNode(node)&&getDirectoryIndex(state,nodeId).childIds.length>0&&options.recursive!==!0)throw new Error(`Cannot remove a non-empty directory without recursive: "${path}"`);const parentId=node.parentId,previousProjectionSignature=getCollapsedProjectionSignature(state,parentId),removedNodeIds=removeSubtree(state,nodeId);removeChildReference(state,parentId,nodeId,node.nameId),promoteEmptyAncestorsToExplicit(state,parentId),recomputeCountsUpwardFrom(state,parentId);const nextProjectionSignature=getCollapsedProjectionSignature(state,parentId);return createRemoveEvent({affectedAncestorIds:collectAncestorIds(state,parentId),affectedNodeIds:removedNodeIds,path,projectionChanged:didProjectionChange(previousProjectionSignature,nextProjectionSignature),recursive:options.recursive===!0})}function movePath(state,fromPath,toPath,options){const sourceNodeId=findNodeId(state,fromPath);if(sourceNodeId==null)throw new Error(`Source path does not exist: "${fromPath}"`);const sourceNode=requireNode(state,sourceNodeId);if(hasNodeFlag(sourceNode,2))throw new Error("The root node cannot be moved");const collision=options.collision??"error",moveTarget=resolveMoveTarget(state,sourceNodeId,toPath),previousSourceProjectionSignature=getCollapsedProjectionSignature(state,sourceNode.parentId),previousTargetProjectionSignature=getCollapsedProjectionSignature(state,moveTarget.parentId),sourceName=getSegmentValue(state.snapshot.segmentTable,sourceNode.nameId),targetNameId=internSegment(state.snapshot.segmentTable,moveTarget.basename);if(moveTarget.parentId===sourceNode.parentId&&sourceName===moveTarget.basename)return null;if(isDirectoryNode(sourceNode)&&isAncestor(state,sourceNodeId,moveTarget.parentId))throw new Error("Cannot move a directory into one of its descendants");const siblingCollisionId=ensureChildIdByNameId(state.snapshot.nodes,getDirectoryIndex(state,moveTarget.parentId)).get(targetNameId),collisionNodeId=moveTarget.existingNodeId??siblingCollisionId??null;if(collisionNodeId!=null&&collisionNodeId!==sourceNodeId&&handleMoveCollision(state,collisionNodeId,collision,getNodeKind(sourceNode))==="skip")return null;const previousParentId=sourceNode.parentId;removeChildReference(state,previousParentId,sourceNodeId,sourceNode.nameId),sourceNode.parentId=moveTarget.parentId,sourceNode.nameId=targetNameId,state.pathCacheByNodeId.delete(sourceNodeId),recomputeDepths(state,sourceNodeId),insertChildReference(state,moveTarget.parentId,sourceNodeId),promoteEmptyAncestorsToExplicit(state,previousParentId),state.pathCacheVersion++,recomputeCountsUpwardFrom(state,previousParentId),moveTarget.parentId!==previousParentId&&recomputeCountsUpwardFrom(state,moveTarget.parentId);const nextSourceProjectionSignature=getCollapsedProjectionSignature(state,previousParentId),nextTargetProjectionSignature=getCollapsedProjectionSignature(state,moveTarget.parentId);return createMoveEvent({affectedAncestorIds:[...new Set([...collectAncestorIds(state,previousParentId),...collectAncestorIds(state,moveTarget.parentId)])],affectedNodeIds:[sourceNodeId],from:fromPath,projectionChanged:didAnyProjectionChange([previousSourceProjectionSignature,previousTargetProjectionSignature],[nextSourceProjectionSignature,nextTargetProjectionSignature]),to:materializeNodePath(state,sourceNodeId)})}function getCachedNodePath(state,nodeId){const cachedEntry=state.pathCacheByNodeId.get(nodeId);return cachedEntry!=null&&cachedEntry.version===state.pathCacheVersion?cachedEntry.path:null}function setCachedNodePath(state,nodeId,path){return state.pathCacheByNodeId.set(nodeId,{path,version:state.pathCacheVersion}),path}function materializeNodePath(state,nodeId){const node=requireNode(state,nodeId),cachedPath=getCachedNodePath(state,nodeId);if(cachedPath!=null)return cachedPath;if(hasNodeFlag(node,2))return setCachedNodePath(state,nodeId,"");const parentPath=materializeNodePath(state,node.parentId),nodeName=getSegmentValue(state.snapshot.segmentTable,node.nameId),path=parentPath.length===0?nodeName:`${parentPath}${nodeName}`;return setCachedNodePath(state,nodeId,isDirectoryNode(node)?`${path}/`:path)}function recomputeCountsUpwardFrom(state,startNodeId){const instrumentation=state.instrumentation;if(instrumentation==null){recomputeCountsUpwardFromNow(state,startNodeId);return}withBenchmarkPhase(instrumentation,"store.recomputeCountsUpwardFrom",()=>recomputeCountsUpwardFromNow(state,startNodeId))}function recomputeCountsRecursive(state,nodeId){const stack=[[nodeId,0]],{nodes,directories}=state.snapshot;for(;stack.length>0;){const frame=stack[stack.length-1],nid=frame[0],node=nodes[nid];if(node==null||!isDirectoryNode(node)){recomputeNodeCounts(state,nid,node,!0),stack.pop();continue}const dirIndex=directories.get(nid);if(dirIndex==null||frame[1]>=dirIndex.childIds.length){recomputeNodeCounts(state,nid,node,!0),stack.pop();continue}const childId=dirIndex.childIds[frame[1]++];stack.push([childId,0])}}function collectAncestorIds(state,nodeId){const ancestorIds=[];let currentNodeId=nodeId;for(;currentNodeId!=null;){const currentNode=requireNode(state,currentNodeId);if(ancestorIds.push(currentNodeId),currentNodeId===state.snapshot.rootId)break;currentNodeId=currentNode.parentId}return ancestorIds}function findNodeId(state,path){if(path.length===0)return state.snapshot.rootId;const lookupPath=parseLookupPath(path);return findNodeIdBySegments(state,lookupPath.segments,lookupPath.requiresDirectory)}function findNodeIdBySegments(state,segments,requireDirectory){let currentNodeId=state.snapshot.rootId;for(const segment of segments){const segmentId=state.snapshot.segmentTable.idByValue.get(segment);if(segmentId===void 0)return null;const currentIndex=getDirectoryIndex(state,currentNodeId),nextNodeId=ensureChildIdByNameId(state.snapshot.nodes,currentIndex).get(segmentId);if(nextNodeId===void 0)return null;currentNodeId=nextNodeId}const currentNode=requireNode(state,currentNodeId);return requireDirectory&&!isDirectoryNode(currentNode)?null:currentNodeId}function getDirectoryIndex(state,directoryId){const directoryIndex=state.snapshot.directories.get(directoryId);if(directoryIndex===void 0)throw new Error(`Unknown directory child index for node ${String(directoryId)}`);return directoryIndex}function requireNode(state,nodeId){const node=state.snapshot.nodes[nodeId];if(node===void 0||hasNodeFlag(node,4))throw new Error(`Unknown node ID: ${String(nodeId)}`);return node}function collectCanonicalEntries(state,nodeId){const rootNode=state.snapshot.nodes[nodeId];if(rootNode===void 0||hasNodeFlag(rootNode,4))return[];if(!isDirectoryNode(rootNode))return[materializeNodePath(state,nodeId)];if(getDirectoryIndex(state,nodeId).childIds.length===0)return hasNodeFlag(rootNode,1)&&!hasNodeFlag(rootNode,2)?[materializeNodePath(state,nodeId)]:[];const entries=[],stack=[{childIndex:0,nodeId}];for(;stack.length>0;){const frame=stack[stack.length-1];if(frame==null)break;const currentNode=state.snapshot.nodes[frame.nodeId];if(currentNode===void 0||hasNodeFlag(currentNode,4)){stack.pop();continue}if(!isDirectoryNode(currentNode)){entries.push(materializeNodePath(state,frame.nodeId)),stack.pop();continue}const currentIndex=getDirectoryIndex(state,frame.nodeId);if(currentIndex.childIds.length===0){hasNodeFlag(currentNode,1)&&!hasNodeFlag(currentNode,2)&&entries.push(materializeNodePath(state,frame.nodeId)),stack.pop();continue}const nextChildId=currentIndex.childIds[frame.childIndex];if(nextChildId==null){stack.pop();continue}frame.childIndex++,stack.push({childIndex:0,nodeId:nextChildId})}return entries}function ensureDirectoryChain(state,directorySegments){const createdNodeIds=[];let currentDirectoryId=state.snapshot.rootId;for(const segment of directorySegments){const segmentId=internSegment(state.snapshot.segmentTable,segment),currentIndex=getDirectoryIndex(state,currentDirectoryId),existingChildId=ensureChildIdByNameId(state.snapshot.nodes,currentIndex).get(segmentId);if(existingChildId!==void 0){if(!isDirectoryNode(requireNode(state,existingChildId)))throw new Error(`Cannot create a directory that collides with an existing file: "${segment}"`);currentDirectoryId=existingChildId;continue}currentDirectoryId=createDirectoryNode(state,currentDirectoryId,segmentId),createdNodeIds.push(currentDirectoryId)}return{createdNodeIds,directoryId:currentDirectoryId}}function createDirectoryNode(state,parentId,nameId){const parentNode=requireNode(state,parentId),nodeId=state.snapshot.nodes.length;return state.snapshot.nodes.push({depthAndFlags:createNodeDepthAndFlags(getNodeDepth(parentNode)+1,0,1),nameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),state.snapshot.directories.set(nodeId,createDirectoryChildIndex()),insertChildReference(state,parentId,nodeId),state.collapseNewDirectoriesByDefault&&(state.collapsedDirectoryIds.add(nodeId),state.hasCollapsedDirectoryOverrides=!0),state.activeNodeCount++,nodeId}function createFileNode(state,parentId,basename){const nameId=internSegment(state.snapshot.segmentTable,basename),parentIndex=getDirectoryIndex(state,parentId);if(ensureChildIdByNameId(state.snapshot.nodes,parentIndex).has(nameId))throw new Error(`Path already exists: "${buildPathPreview(state,parentId,basename)}"`);const parentNode=requireNode(state,parentId),nodeId=state.snapshot.nodes.length;return state.snapshot.nodes.push({depthAndFlags:createNodeDepthAndFlags(getNodeDepth(parentNode)+1,0),nameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),insertChildReference(state,parentId,nodeId),state.activeNodeCount++,nodeId}function findChildInsertIndex(state,parentIndex,childId){let low=0,high=parentIndex.childIds.length;for(;low<high;){const middle=low+high>>>1,existingChildId=parentIndex.childIds[middle];if(existingChildId==null){high=middle;continue}compareSiblingNodes(state,childId,existingChildId)<0?high=middle:low=middle+1}return low}function insertChildReference(state,parentId,childId){const parentIndex=getDirectoryIndex(state,parentId),childNode=requireNode(state,childId);ensureChildIdByNameId(state.snapshot.nodes,parentIndex).set(childNode.nameId,childId),applyChildAggregateDelta(parentIndex,childId,childNode.subtreeNodeCount,childNode.visibleSubtreeCount);const insertIndex=findChildInsertIndex(state,parentIndex,childId);parentIndex.childIds.splice(insertIndex,0,childId),updateChildPositionsFrom(parentIndex,insertIndex),rebuildVisibleChildChunks(state.snapshot.nodes,parentIndex)}function removeChildReference(state,parentId,childId,childNameId){const parentIndex=getDirectoryIndex(state,parentId),positions=ensureChildPositions(parentIndex),childIndex=positions.get(childId)??-1;ensureChildIdByNameId(state.snapshot.nodes,parentIndex).delete(childNameId),positions.delete(childId);const childNode=state.snapshot.nodes[childId];childNode!=null&&applyChildAggregateDelta(parentIndex,childId,-childNode.subtreeNodeCount,-childNode.visibleSubtreeCount),childIndex>=0&&(parentIndex.childIds.splice(childIndex,1),updateChildPositionsFrom(parentIndex,childIndex),rebuildVisibleChildChunks(state.snapshot.nodes,parentIndex))}function compareSiblingNodes(state,leftId,rightId){const sortOption=state.snapshot.options.sort;return sortOption==="default"?compareSiblingNodesDefault(state,leftId,rightId):sortOption(createCompareEntry(state,leftId),createCompareEntry(state,rightId))}function compareSiblingNodesDefault(state,leftId,rightId){const leftNode=requireNode(state,leftId),rightNode=requireNode(state,rightId),leftIsDirectory=isDirectoryNode(leftNode);if(leftIsDirectory!==isDirectoryNode(rightNode))return leftIsDirectory?-1:1;const comparison=compareSegmentSortKeys(getSegmentSortKey(state.snapshot.segmentTable,leftNode.nameId),getSegmentSortKey(state.snapshot.segmentTable,rightNode.nameId));if(comparison!==0)return comparison;const leftName=getSegmentValue(state.snapshot.segmentTable,leftNode.nameId),rightName=getSegmentValue(state.snapshot.segmentTable,rightNode.nameId);return leftName!==rightName?leftName<rightName?-1:1:leftId<rightId?-1:1}function createCompareEntry(state,nodeId){const node=requireNode(state,nodeId),path=materializeNodePath(state,nodeId),isDirectory=isDirectoryNode(node),normalizedPath=isDirectory?path.slice(0,-1):path;return{basename:getSegmentValue(state.snapshot.segmentTable,node.nameId),depth:getNodeDepth(node),isDirectory,path,segments:normalizedPath.length===0?[]:normalizedPath.split("/")}}function resolveMoveTarget(state,sourceNodeId,toPath){const sourceNode=requireNode(state,sourceNodeId),existingDestinationId=findNodeId(state,toPath);if(existingDestinationId!=null){const existingDestination=requireNode(state,existingDestinationId);if(isDirectoryNode(existingDestination))return{basename:getSegmentValue(state.snapshot.segmentTable,sourceNode.nameId),existingNodeId:null,parentId:existingDestinationId};const destinationSegments=parseLookupPath(toPath).segments;return{basename:destinationSegments[destinationSegments.length-1]??"",existingNodeId:existingDestinationId,parentId:existingDestination.parentId}}const destinationLookup=parseLookupPath(toPath),basename=destinationLookup.segments[destinationLookup.segments.length-1]??"",parentSegments=destinationLookup.segments.slice(0,-1),parentId=parentSegments.length===0?state.snapshot.rootId:findNodeIdBySegments(state,parentSegments,!0);if(parentId==null)throw new Error(`Destination parent does not exist: "${toPath}"`);return{basename,existingNodeId:null,parentId}}function handleMoveCollision(state,collisionNodeId,strategy,sourceKind){if(strategy==="skip")return"skip";if(strategy==="error")throw new Error(`Destination already exists: "${materializeNodePath(state,collisionNodeId)}"`);const collisionNode=requireNode(state,collisionNodeId);if(getNodeKind(collisionNode)!==sourceKind)throw new Error("replace collision requires the same source and destination kinds");if(isDirectoryNode(collisionNode)&&getDirectoryIndex(state,collisionNodeId).childIds.length>0)throw new Error("replace collision does not support non-empty directories");const collisionParentId=collisionNode.parentId,collisionNameId=collisionNode.nameId;return removeSubtree(state,collisionNodeId),removeChildReference(state,collisionParentId,collisionNodeId,collisionNameId),promoteEmptyAncestorsToExplicit(state,collisionParentId),recomputeCountsUpwardFrom(state,collisionParentId),"handled"}function removeSubtree(state,nodeId){const removedNodeIds=[],stack=[{nodeId,visitedChildren:!1}];for(;stack.length>0;){const frame=stack.pop();if(frame==null)break;const node=requireNode(state,frame.nodeId);if(frame.visitedChildren||!isDirectoryNode(node)){isDirectoryNode(node)&&state.snapshot.directories.delete(frame.nodeId),addNodeFlag(node,4),state.pathCacheByNodeId.delete(frame.nodeId),state.collapsedDirectoryIds.delete(frame.nodeId)&&(state.hasCollapsedDirectoryOverrides=state.collapsedDirectoryIds.size>0),state.expandedDirectoryIds.delete(frame.nodeId),clearDirectoryLoadInfo(state,frame.nodeId),state.activeNodeCount--,removedNodeIds.push(frame.nodeId);continue}stack.push({nodeId:frame.nodeId,visitedChildren:!0});const directoryIndex=getDirectoryIndex(state,frame.nodeId);for(let childIndex=directoryIndex.childIds.length-1;childIndex>=0;childIndex--){const childId=directoryIndex.childIds[childIndex];childId!=null&&stack.push({nodeId:childId,visitedChildren:!1})}}return removedNodeIds}function promoteEmptyAncestorsToExplicit(state,startDirectoryId){let currentDirectoryId=startDirectoryId;for(;currentDirectoryId!=null;){const currentNode=requireNode(state,currentDirectoryId);if(!isDirectoryNode(currentNode)||hasNodeFlag(currentNode,2)||getDirectoryIndex(state,currentDirectoryId).childIds.length>0)return;addNodeFlag(currentNode,1),currentDirectoryId=currentNode.parentId===currentDirectoryId?null:currentNode.parentId}}function findDeepestExistingDirectoryId(state,segments){let currentDirectoryId=state.snapshot.rootId;for(const segment of segments){const segmentId=state.snapshot.segmentTable.idByValue.get(segment);if(segmentId==null)break;const nextNodeId=ensureChildIdByNameId(state.snapshot.nodes,getDirectoryIndex(state,currentDirectoryId)).get(segmentId);if(nextNodeId==null||!isDirectoryNode(requireNode(state,nextNodeId)))break;currentDirectoryId=nextNodeId}return currentDirectoryId}function getCollapsedProjectionSignature(state,startDirectoryId){const collapsedAncestorId=findNearestCollapsedAncestor(state,startDirectoryId);if(collapsedAncestorId==null)return null;const terminalDirectoryId=getFlattenedTerminalDirectoryId(state,collapsedAncestorId),terminalNode=requireNode(state,terminalDirectoryId),flattenedSegmentPaths=collapsedAncestorId===terminalDirectoryId?null:collectFlattenedDirectoryChainIds(state,collapsedAncestorId).map(nodeId=>materializeNodePath(state,nodeId));return JSON.stringify({flattenedSegmentPaths,hasChildren:getDirectoryIndex(state,terminalDirectoryId).childIds.length>0,path:materializeNodePath(state,terminalDirectoryId),terminalKind:getNodeKind(terminalNode)})}function didProjectionChange(previousProjectionSignature,nextProjectionSignature){return didAnyProjectionChange([previousProjectionSignature],[nextProjectionSignature])}function didAnyProjectionChange(previousProjectionSignatures,nextProjectionSignatures){for(let index=0;index<previousProjectionSignatures.length;index+=1){const previousProjectionSignature=previousProjectionSignatures[index],nextProjectionSignature=nextProjectionSignatures[index];if(previousProjectionSignature==null||nextProjectionSignature==null||previousProjectionSignature!==nextProjectionSignature)return!0}return!1}function findNearestCollapsedAncestor(state,startDirectoryId){let currentDirectoryId=startDirectoryId;for(;currentDirectoryId!=null;){const currentNode=requireNode(state,currentDirectoryId);if(!isDirectoryNode(currentNode)||hasNodeFlag(currentNode,2))return null;if(!isDirectoryExpanded(state,currentDirectoryId,currentNode))return currentDirectoryId;currentDirectoryId=currentNode.parentId}return null}function recomputeDepths(state,nodeId){const node=requireNode(state,nodeId);if(setNodeDepth(node,(nodeId===state.snapshot.rootId?-1:getNodeDepth(requireNode(state,node.parentId)))+1),!isDirectoryNode(node))return;const directoryIndex=getDirectoryIndex(state,nodeId);for(const childId of directoryIndex.childIds)recomputeDepths(state,childId)}function isAncestor(state,ancestorNodeId,nodeId){let currentNodeId=nodeId;for(;currentNodeId!=null;){if(currentNodeId===ancestorNodeId)return!0;const currentNode=requireNode(state,currentNodeId);if(currentNodeId===state.snapshot.rootId)return!1;currentNodeId=currentNode.parentId}return!1}function recomputeNodeCounts(state,nodeId,currentNode=requireNode(state,nodeId),rebuildChildAggregates=!1){const instrumentation=state.instrumentation;if(instrumentation==null){recomputeNodeCountsNow(state,nodeId,currentNode,rebuildChildAggregates);return}withBenchmarkPhase(instrumentation,"store.recomputeNodeCounts",()=>recomputeNodeCountsNow(state,nodeId,currentNode,rebuildChildAggregates))}function recomputeCountsUpwardFromNow(state,startNodeId){let currentNodeId=startNodeId;for(;currentNodeId!=null;){const currentNode=requireNode(state,currentNodeId),previousSubtreeNodeCount=currentNode.subtreeNodeCount,previousVisibleSubtreeCount=currentNode.visibleSubtreeCount;if(recomputeNodeCounts(state,currentNodeId,currentNode),currentNodeId===state.snapshot.rootId)return;const subtreeNodeDelta=currentNode.subtreeNodeCount-previousSubtreeNodeCount,visibleSubtreeDelta=currentNode.visibleSubtreeCount-previousVisibleSubtreeCount,parentId=currentNode.parentId;(subtreeNodeDelta!==0||visibleSubtreeDelta!==0)&&applyChildAggregateDelta(getDirectoryIndex(state,parentId),currentNodeId,subtreeNodeDelta,visibleSubtreeDelta),currentNodeId=parentId}}function recomputeNodeCountsNow(state,nodeId,currentNode,rebuildChildAggregates){if(!isDirectoryNode(currentNode)){currentNode.subtreeNodeCount=1,currentNode.visibleSubtreeCount=1;return}const currentIndex=getDirectoryIndex(state,nodeId);if(rebuildChildAggregates){const instrumentation=state.instrumentation;instrumentation==null?rebuildDirectoryChildAggregates(state.snapshot.nodes,currentIndex):withBenchmarkPhase(instrumentation,"store.recomputeNodeCounts.rebuildChildAggregates",()=>rebuildDirectoryChildAggregates(state.snapshot.nodes,currentIndex))}const subtreeNodeCount=1+currentIndex.totalChildSubtreeNodeCount,visibleChildCount=currentIndex.totalChildVisibleSubtreeCount;if(currentNode.subtreeNodeCount=subtreeNodeCount,hasNodeFlag(currentNode,2)){currentNode.visibleSubtreeCount=visibleChildCount;return}currentNode.visibleSubtreeCount=getFlattenedChildDirectoryId(state,nodeId)!=null?visibleChildCount:isDirectoryExpanded(state,nodeId,currentNode)?1+visibleChildCount:1}function buildPathPreview(state,parentId,basename){const parentPath=materializeNodePath(state,parentId);return parentPath.length===0?basename:`${parentPath}${basename}`}function isLiveNode(node){return node!=null&&!hasNodeFlag(node,4)}function isLiveDirectoryNode(state,nodeId){const node=state.snapshot.nodes[nodeId];return!isLiveNode(node)||!isDirectoryNode(node)||hasNodeFlag(node,2)?null:node}function countCachedPathEntries(state){let cachedPathEntryCount=0;for(const[nodeId,cachedEntry]of state.pathCacheByNodeId)cachedEntry.version===state.pathCacheVersion&&isLiveNode(state.snapshot.nodes[nodeId])&&(cachedPathEntryCount+=1);return cachedPathEntryCount}function countSegmentEntries(segmentTable){return Math.max(0,segmentTable.valueById.length-1)}function createCleanupMetricSnapshot(state){return{activeNodeCount:state.activeNodeCount,cachedPathEntryCount:countCachedPathEntries(state),loadInfoEntryCount:state.directoryLoadInfoById.size,segmentCount:countSegmentEntries(state.snapshot.segmentTable),totalNodeSlotCount:Math.max(0,state.snapshot.nodes.length-1)}}function createCleanupResult(mode,idsPreserved,before2,after){return{activeNodeCountAfter:after.activeNodeCount,activeNodeCountBefore:before2.activeNodeCount,cachedPathEntryCountAfter:after.cachedPathEntryCount,cachedPathEntryCountBefore:before2.cachedPathEntryCount,idsPreserved,loadInfoEntryCountAfter:after.loadInfoEntryCount,loadInfoEntryCountBefore:before2.loadInfoEntryCount,mode,reclaimedCachedPathEntryCount:before2.cachedPathEntryCount-after.cachedPathEntryCount,reclaimedLoadInfoEntryCount:before2.loadInfoEntryCount-after.loadInfoEntryCount,reclaimedNodeSlotCount:before2.totalNodeSlotCount-after.totalNodeSlotCount,reclaimedSegmentCount:before2.segmentCount-after.segmentCount,segmentCountAfter:after.segmentCount,segmentCountBefore:before2.segmentCount,totalNodeSlotCountAfter:after.totalNodeSlotCount,totalNodeSlotCountBefore:before2.totalNodeSlotCount}}function collectExpansionOverridePaths(state){const collapsedPaths=[],expandedPaths=[];for(const nodeId of state.collapsedDirectoryIds)isLiveDirectoryNode(state,nodeId)!=null&&collapsedPaths.push(materializeNodePath(state,nodeId));for(const nodeId of state.expandedDirectoryIds)isLiveDirectoryNode(state,nodeId)!=null&&expandedPaths.push(materializeNodePath(state,nodeId));return{collapsedPaths,expandedPaths}}function collectDirectoryLoadInfos(state){const retainedInfos=[];for(const[nodeId,info]of state.directoryLoadInfoById)isLiveDirectoryNode(state,nodeId)==null||getDirectoryLoadState(state,nodeId)==="loaded"||retainedInfos.push({info:{activeAttemptId:null,errorMessage:info.errorMessage,nextAttemptId:info.nextAttemptId,state:info.state},path:materializeNodePath(state,nodeId)});return retainedInfos}function restoreExpansionOverridePaths(state,persistedExpansionState){state.collapsedDirectoryIds.clear(),state.hasCollapsedDirectoryOverrides=!1,state.expandedDirectoryIds.clear();for(const path of persistedExpansionState.expandedPaths){const nodeId=findNodeId(state,path);nodeId!=null&&setDirectoryExpanded(state,nodeId,!0,requireNode(state,nodeId))}for(const path of persistedExpansionState.collapsedPaths){const nodeId=findNodeId(state,path);nodeId!=null&&setDirectoryExpanded(state,nodeId,!1,requireNode(state,nodeId))}}function restoreDirectoryLoadInfos(state,persistedLoadInfos){state.directoryLoadInfoById.clear();for(const retainedInfo of persistedLoadInfos){const nodeId=findNodeId(state,retainedInfo.path);nodeId!=null&&isLiveDirectoryNode(state,nodeId)!=null&&state.directoryLoadInfoById.set(nodeId,{activeAttemptId:null,errorMessage:retainedInfo.info.errorMessage,nextAttemptId:retainedInfo.info.nextAttemptId,state:retainedInfo.info.state})}}function clearPathCaches(state){state.pathCacheVersion+=1,state.pathCacheByNodeId.clear(),state.pathCacheByNodeId.set(state.snapshot.rootId,{path:"",version:state.pathCacheVersion})}function rebuildSegmentTablePreservingNodeIds(state){const previousSegmentTable=state.snapshot.segmentTable,nextSegmentTable=createSegmentTable();for(const node of state.snapshot.nodes)if(isLiveNode(node)){if(hasNodeFlag(node,2)){node.nameId=0;continue}node.nameId=internSegment(nextSegmentTable,getSegmentValue(previousSegmentTable,node.nameId))}state.snapshot.segmentTable=nextSegmentTable}function rebuildDirectoryIndexes(state){for(const[directoryId,directoryIndex]of state.snapshot.directories){const directoryNode=state.snapshot.nodes[directoryId];if(!isLiveNode(directoryNode)||!isDirectoryNode(directoryNode)){state.snapshot.directories.delete(directoryId);continue}const liveChildIds=directoryIndex.childIds.filter(childId=>{const childNode=state.snapshot.nodes[childId];return isLiveNode(childNode)&&childNode.parentId===directoryId});directoryIndex.childIds=liveChildIds,directoryIndex.childIdByNameId=new Map(liveChildIds.map(childId=>[requireNode(state,childId).nameId,childId])),directoryIndex.childPositionById=new Map(liveChildIds.map((childId,childIndex)=>[childId,childIndex])),rebuildDirectoryChildAggregates(state.snapshot.nodes,directoryIndex)}}function trimTrailingRemovedNodeSlots(state){let lastNodeIndex=state.snapshot.nodes.length-1;for(;lastNodeIndex>state.snapshot.rootId;){const node=state.snapshot.nodes[lastNodeIndex];if(isLiveNode(node))break;lastNodeIndex-=1}state.snapshot.nodes.length=lastNodeIndex+1}function runStableCleanup(state){const persistedExpansionState=collectExpansionOverridePaths(state),persistedLoadInfos=collectDirectoryLoadInfos(state);withBenchmarkPhase(state.instrumentation,"store.cleanup.stable.clearPathCaches",()=>clearPathCaches(state)),withBenchmarkPhase(state.instrumentation,"store.cleanup.stable.rebuildSegmentTable",()=>rebuildSegmentTablePreservingNodeIds(state)),withBenchmarkPhase(state.instrumentation,"store.cleanup.stable.rebuildDirectoryIndexes",()=>rebuildDirectoryIndexes(state)),withBenchmarkPhase(state.instrumentation,"store.cleanup.stable.trimTrailingRemovedNodeSlots",()=>trimTrailingRemovedNodeSlots(state)),withBenchmarkPhase(state.instrumentation,"store.cleanup.stable.restoreExpansionOverrides",()=>restoreExpansionOverridePaths(state,persistedExpansionState)),withBenchmarkPhase(state.instrumentation,"store.cleanup.stable.restoreDirectoryLoadInfos",()=>restoreDirectoryLoadInfos(state,persistedLoadInfos)),withBenchmarkPhase(state.instrumentation,"store.cleanup.stable.recomputeCounts",()=>recomputeCountsRecursive(state,state.snapshot.rootId))}function runAggressiveCleanup(state){const persistedExpansionState=collectExpansionOverridePaths(state),persistedLoadInfos=collectDirectoryLoadInfos(state),canonicalPaths=withBenchmarkPhase(state.instrumentation,"store.cleanup.aggressive.listPaths",()=>listPaths(state)),builderOptions=attachBenchmarkInstrumentation({...state.snapshot.options},state.instrumentation),rebuiltSnapshot=withBenchmarkPhase(state.instrumentation,"store.cleanup.aggressive.rebuildSnapshot",()=>{const builder=new PathStoreBuilder(builderOptions);return builder.appendPaths(canonicalPaths),builder.finish()});state.snapshot=rebuiltSnapshot,state.activeNodeCount=rebuiltSnapshot.nodes.length-1,state.pathCacheByNodeId=new Map([[rebuiltSnapshot.rootId,{path:"",version:0}]]),state.pathCacheVersion=0,withBenchmarkPhase(state.instrumentation,"store.cleanup.aggressive.restoreExpansionOverrides",()=>restoreExpansionOverridePaths(state,persistedExpansionState)),withBenchmarkPhase(state.instrumentation,"store.cleanup.aggressive.restoreDirectoryLoadInfos",()=>restoreDirectoryLoadInfos(state,persistedLoadInfos)),withBenchmarkPhase(state.instrumentation,"store.cleanup.aggressive.recomputeCounts",()=>recomputeCountsRecursive(state,state.snapshot.rootId))}function hasActiveCleanupBlockingLoads(state){for(const loadInfo of state.directoryLoadInfoById.values())if(loadInfo.state==="loading"&&loadInfo.activeAttemptId!=null)return!0;return!1}function cleanupPathStoreState(state,mode){const before2=createCleanupMetricSnapshot(state);mode==="stable"?withBenchmarkPhase(state.instrumentation,"store.cleanup.stable",()=>runStableCleanup(state)):withBenchmarkPhase(state.instrumentation,"store.cleanup.aggressive",()=>runAggressiveCleanup(state));const after=createCleanupMetricSnapshot(state);return createCleanupResult(mode,mode==="stable",before2,after)}const INITIAL_PROJECTION_DEPTH_CAPACITY=64;function ensureProjectionDepthCapacity(depthTable,depth){const requiredLength=depth+2;if(requiredLength<=depthTable.length)return depthTable;let nextLength=depthTable.length;for(;nextLength<requiredLength;)nextLength*=2;const nextDepthTable=new Int32Array(nextLength);return nextDepthTable.fill(-1),nextDepthTable.set(depthTable),nextDepthTable}function getVisibleCount(state){return requireNode(state,state.snapshot.rootId).visibleSubtreeCount}function getVisibleRowSubtreeEndIndex(state,cursor,index,totalVisibleCount){const terminalNode=requireNode(state,cursor.terminalNodeId),subtreeSize=Math.max(1,terminalNode.visibleSubtreeCount);return Math.min(totalVisibleCount-1,index+subtreeSize-1)}function materializeVisibleAncestorRow(state,entry,totalVisibleCount,ancestorPaths){return{ancestorPaths,index:entry.index,posInSet:entry.posInSet,row:materializeVisibleRow(state,entry.cursor),setSize:entry.setSize,subtreeEndIndex:getVisibleRowSubtreeEndIndex(state,entry.cursor,entry.index,totalVisibleCount)}}function selectVisibleRowContextWithinDirectory(state,directoryNodeId,index,directoryStartIndex,parentVisibleDepth,ancestors){const directoryIndex=getDirectoryIndex(state,directoryNodeId),{childIndex,childVisibleIndex,localVisibleIndex}=selectChildIndexByVisibleIndex(state.snapshot.nodes,directoryIndex,index),childId=directoryIndex.childIds[childIndex];if(childId==null)throw new Error(`Visible index ${String(index)} is out of range`);return selectVisibleRowContextWithinSubtree(state,childId,localVisibleIndex,directoryStartIndex+childVisibleIndex,parentVisibleDepth+1,childIndex,directoryIndex.childIds.length,ancestors)}function selectVisibleRowContextWithinSubtree(state,nodeId,index,rowIndex,visibleDepth,posInSet,setSize,ancestors){if(!isDirectoryNode(requireNode(state,nodeId))){if(index===0)return{ancestors,cursor:{headNodeId:nodeId,terminalNodeId:nodeId,visibleDepth},index:rowIndex,posInSet,setSize};throw new Error(`Visible index ${String(index)} is out of range for file`)}const currentCursor=createVisibleRowCursor(state,nodeId,visibleDepth);if(index===0)return{ancestors,cursor:currentCursor,index:rowIndex,posInSet,setSize};const terminalNode=requireNode(state,currentCursor.terminalNodeId);if(!isDirectoryNode(terminalNode)||!isDirectoryExpanded(state,currentCursor.terminalNodeId,terminalNode))throw new Error(`Visible index ${String(index)} is out of range for collapsed directory`);return selectVisibleRowContextWithinDirectory(state,currentCursor.terminalNodeId,index-1,rowIndex+1,currentCursor.visibleDepth,[...ancestors,{cursor:currentCursor,index:rowIndex,posInSet,setSize}])}function getVisibleRowContext(state,index){const totalVisibleCount=getVisibleCount(state);if(index<0||index>=totalVisibleCount)return null;const selected=selectVisibleRowContextWithinDirectory(state,state.snapshot.rootId,index,0,-1,[]),ancestorPaths=selected.ancestors.map(ancestor=>materializeNodePath(state,ancestor.cursor.terminalNodeId));let cachedAncestorRows=null;return{ancestorPaths,get ancestorRows(){if(cachedAncestorRows!=null)return cachedAncestorRows;const ancestorRows=[],rowAncestorPaths=[];for(const ancestor of selected.ancestors){const ancestorRow=materializeVisibleAncestorRow(state,ancestor,totalVisibleCount,[...rowAncestorPaths]);ancestorRows.push(ancestorRow),rowAncestorPaths.push(ancestorRow.row.path)}return cachedAncestorRows=ancestorRows,cachedAncestorRows},index:selected.index,posInSet:selected.posInSet,row:materializeVisibleRow(state,selected.cursor),setSize:selected.setSize,subtreeEndIndex:getVisibleRowSubtreeEndIndex(state,selected.cursor,selected.index,totalVisibleCount)}}function getVisibleSlice(state,start,end){const instrumentation=state.instrumentation,totalVisibleCount=getVisibleCount(state);if(totalVisibleCount<=0||end<start)return[];const normalizedStart=Math.max(0,Math.min(start,totalVisibleCount-1)),normalizedEnd=Math.max(normalizedStart,Math.min(end,totalVisibleCount-1));if(instrumentation==null){if(normalizedStart===0)return collectVisibleRowsDFS(state,normalizedEnd+1);const rows2=[];let currentCursor2=selectVisibleRow(state,normalizedStart);for(let visibleIndex=normalizedStart;visibleIndex<=normalizedEnd&&currentCursor2!=null;visibleIndex++){const row=materializeVisibleRow(state,currentCursor2);rows2.push(row),currentCursor2=getNextVisibleRowCursor(state,currentCursor2)}return rows2}const rows=[];let flattenedRowCount=0,flattenedSegmentCount=0,currentCursor=withBenchmarkPhase(instrumentation,"store.getVisibleSlice.selectFirstRow",()=>selectVisibleRow(state,normalizedStart));for(let visibleIndex=normalizedStart;visibleIndex<=normalizedEnd&&currentCursor!=null;visibleIndex++){const row=withBenchmarkPhase(instrumentation,"store.getVisibleSlice.materializeRow",()=>materializeVisibleRow(state,currentCursor));rows.push(row),row.isFlattened&&(flattenedRowCount++,flattenedSegmentCount+=row.flattenedSegments?.length??0),currentCursor=withBenchmarkPhase(instrumentation,"store.getVisibleSlice.advanceCursor",()=>getNextVisibleRowCursor(state,currentCursor))}return setBenchmarkCounter(instrumentation,"workload.visibleRowsRead",rows.length),setBenchmarkCounter(instrumentation,"workload.flattenedRowsRead",flattenedRowCount),setBenchmarkCounter(instrumentation,"workload.flattenedSegmentsRead",flattenedSegmentCount),rows}function getVisibleTreeProjectionData(state,maxRows=getVisibleCount(state)){const instrumentation=state.instrumentation;return instrumentation==null?buildVisibleTreeProjectionDataDFS(state,maxRows):withBenchmarkPhase(instrumentation,"store.getVisibleTreeProjection",()=>buildVisibleTreeProjectionDataDFS(state,maxRows))}function getVisibleTreeProjection(state){return createVisibleTreeProjectionFromData(getVisibleTreeProjectionData(state))}function getVisibleIndexByPath(state,path){const nodeId=findNodeId(state,path);if(nodeId==null||nodeId===state.snapshot.rootId||isDirectoryNode(requireNode(state,nodeId))&&getFlattenedTerminalDirectoryId(state,nodeId)!==nodeId)return null;let visibleIndex=0,currentNodeId=nodeId;const{nodes,rootId}=state.snapshot;for(;currentNodeId!==rootId;){const parentId=requireNode(state,currentNodeId).parentId,parentIndex=getDirectoryIndex(state,parentId),childPosition=ensureChildPositions(parentIndex).get(currentNodeId);if(childPosition==null)throw new Error(`Child ${String(currentNodeId)} was not found in its parent index`);if(visibleIndex+=getVisibleChildPrefixCount(nodes,parentIndex,childPosition),parentId!==rootId){const parentNode=requireNode(state,parentId),flattenedChildDirectoryId=getFlattenedChildDirectoryId(state,parentId);if(!isDirectoryExpanded(state,parentId,parentNode)&&flattenedChildDirectoryId!==currentNodeId)return null;getFlattenedTerminalDirectoryId(state,parentId)===parentId&&(visibleIndex+=1)}currentNodeId=parentId}return visibleIndex}function expandPath(state,path){const directoryNodeId=findNodeId(state,path);if(directoryNodeId==null)throw new Error(`Path does not exist: "${path}"`);const directoryNode=requireNode(state,directoryNodeId);if(!isDirectoryNode(directoryNode))throw new Error(`Path is not a directory: "${path}"`);return isDirectoryExpanded(state,directoryNodeId,directoryNode)?null:(setDirectoryExpanded(state,directoryNodeId,!0,directoryNode),recomputeCountsUpwardFrom(state,directoryNodeId),createExpandEvent({affectedAncestorIds:collectAncestorIds(state,directoryNodeId),affectedNodeIds:[directoryNodeId],path}))}function collapsePath(state,path){const directoryNodeId=findNodeId(state,path);if(directoryNodeId==null)throw new Error(`Path does not exist: "${path}"`);const directoryNode=requireNode(state,directoryNodeId);if(!isDirectoryNode(directoryNode))throw new Error(`Path is not a directory: "${path}"`);return isDirectoryExpanded(state,directoryNodeId,directoryNode)?(setDirectoryExpanded(state,directoryNodeId,!1,directoryNode),recomputeCountsUpwardFrom(state,directoryNodeId),createCollapseEvent({affectedAncestorIds:collectAncestorIds(state,directoryNodeId),affectedNodeIds:[directoryNodeId],path})):null}function selectVisibleRow(state,index){return index<0||index>=getVisibleCount(state)?null:selectVisibleRowWithinDirectory(state,state.snapshot.rootId,index,-1)}function selectVisibleRowWithinDirectory(state,directoryNodeId,index,parentVisibleDepth){const directoryIndex=getDirectoryIndex(state,directoryNodeId),instrumentation=state.instrumentation,{childIndex,localVisibleIndex}=instrumentation==null?selectChildIndexByVisibleIndex(state.snapshot.nodes,directoryIndex,index):withBenchmarkPhase(instrumentation,"store.getVisibleSlice.selectChildIndex",()=>selectChildIndexByVisibleIndex(state.snapshot.nodes,directoryIndex,index)),childId=directoryIndex.childIds[childIndex];if(childId!=null)return selectVisibleRowWithinSubtree(state,childId,localVisibleIndex,parentVisibleDepth+1);throw new Error(`Visible index ${String(index)} is out of range`)}function selectVisibleRowWithinSubtree(state,nodeId,index,visibleDepth){if(!isDirectoryNode(requireNode(state,nodeId))){if(index===0)return{headNodeId:nodeId,terminalNodeId:nodeId,visibleDepth};throw new Error(`Visible index ${String(index)} is out of range for file`)}const currentCursor=createVisibleRowCursor(state,nodeId,visibleDepth);if(index===0)return currentCursor;const terminalNode=requireNode(state,currentCursor.terminalNodeId);if(!isDirectoryNode(terminalNode)||!isDirectoryExpanded(state,currentCursor.terminalNodeId,terminalNode))throw new Error(`Visible index ${String(index)} is out of range for collapsed directory`);return selectVisibleRowWithinDirectory(state,currentCursor.terminalNodeId,index-1,currentCursor.visibleDepth)}function createVisibleRowCursor(state,nodeId,visibleDepth){return isDirectoryNode(requireNode(state,nodeId))?state.instrumentation==null?{headNodeId:nodeId,terminalNodeId:getFlattenedTerminalDirectoryId(state,nodeId),visibleDepth}:{headNodeId:nodeId,terminalNodeId:withBenchmarkPhase(state.instrumentation,"store.getVisibleSlice.flatten.resolveTerminalDirectory",()=>getFlattenedTerminalDirectoryId(state,nodeId)),visibleDepth}:{headNodeId:nodeId,terminalNodeId:nodeId,visibleDepth}}function isVisibleRowHeadNode(state,nodeId){const node=requireNode(state,nodeId);if(!isDirectoryNode(node))return!0;const parentId=node.parentId;return parentId===state.snapshot.rootId?!0:getFlattenedChildDirectoryId(state,parentId)!==nodeId}function getNextVisibleRowCursor(state,currentCursor){const terminalNode=requireNode(state,currentCursor.terminalNodeId);if(isDirectoryNode(terminalNode)){const currentIndex=getDirectoryIndex(state,currentCursor.terminalNodeId);if(isDirectoryExpanded(state,currentCursor.terminalNodeId,terminalNode)&&currentIndex.childIds.length>0){const firstChildId=currentIndex.childIds[0];return firstChildId==null?null:selectVisibleRowWithinSubtree(state,firstChildId,0,currentCursor.visibleDepth+1)}}let currentNodeId=currentCursor.terminalNodeId,currentVisibleDepth=currentCursor.visibleDepth;for(;;){const currentNode=requireNode(state,currentNodeId);if(currentNodeId===state.snapshot.rootId)return null;const parentId=currentNode.parentId,parentIndex=getDirectoryIndex(state,parentId),siblingIndex=ensureChildPositions(parentIndex).get(currentNodeId)??-1;if(siblingIndex<0)throw new Error(`Child ${String(currentNodeId)} was not found in its parent index`);const nextSiblingId=parentIndex.childIds[siblingIndex+1]??null;if(nextSiblingId!=null)return selectVisibleRowWithinSubtree(state,nextSiblingId,0,currentVisibleDepth);isVisibleRowHeadNode(state,currentNodeId)&&currentVisibleDepth--,currentNodeId=parentId}}function createVisibleTreeProjectionFromData(projection){const rowCount=projection.paths.length,projectionRows=new Array(rowCount);for(let rowIndex=0;rowIndex<rowCount;rowIndex+=1){const parentIndex=projection.getParentIndex(rowIndex);projectionRows[rowIndex]={index:rowIndex,parentPath:parentIndex>=0?projection.paths[parentIndex]??null:null,path:projection.paths[rowIndex]??"",posInSet:projection.posInSetByIndex[rowIndex]??0,setSize:projection.setSizeByIndex[rowIndex]??0}}return{getParentIndex:projection.getParentIndex,rows:projectionRows,get visibleIndexByPath(){return projection.visibleIndexByPath}}}function buildVisibleTreeProjectionDataDFS(state,maxRows){const paths=new Array(maxRows),parentRowIndex=new Int32Array(maxRows),posInSetByIndex=new Int32Array(maxRows),setSizeByIndex=new Int32Array(maxRows);let lastRowAtDepth=new Int32Array(INITIAL_PROJECTION_DEPTH_CAPACITY);lastRowAtDepth.fill(-1);let rowCount=0;const{nodes,directories,segmentTable}=state.snapshot,stack=[[directories.get(state.snapshot.rootId),0,-1,""]],flattenEnabled=state.snapshot.options.flattenEmptyDirectories,pathCacheByNodeId=state.pathCacheByNodeId,pathCacheVersion=state.pathCacheVersion,segmentValues=segmentTable.valueById;for(;stack.length>0&&rowCount<maxRows;){const frame=stack[stack.length-1],dirIndex=frame[0];if(frame[1]>=dirIndex.childIds.length){stack.pop();continue}const childOffset=frame[1],childId=dirIndex.childIds[frame[1]++],childNode=nodes[childId],visibleDepth=frame[2]+1,parentPath=frame[3];lastRowAtDepth=ensureProjectionDepthCapacity(lastRowAtDepth,visibleDepth);let path,terminalNodeId=childId;if(isDirectoryNode(childNode))terminalNodeId=flattenEnabled?getFlattenedTerminalDirectoryId(state,childId):childId,path=terminalNodeId===childId?`${parentPath}${segmentValues[childNode.nameId]}/`:materializeNodePath(state,terminalNodeId);else{const cachedPathEntry=pathCacheByNodeId.get(childId);path=cachedPathEntry!=null&&cachedPathEntry.version===pathCacheVersion?cachedPathEntry.path:`${parentPath}${segmentValues[childNode.nameId]}`}parentRowIndex[rowCount]=lastRowAtDepth[visibleDepth],paths[rowCount]=path,posInSetByIndex[rowCount]=childOffset,setSizeByIndex[rowCount]=dirIndex.childIds.length,lastRowAtDepth[visibleDepth+1]=rowCount,rowCount+=1;const terminalNode=nodes[terminalNodeId];terminalNode!=null&&isDirectoryNode(terminalNode)&&isDirectoryExpanded(state,terminalNodeId,terminalNode)&&stack.push([directories.get(terminalNodeId),0,visibleDepth,path])}rowCount<maxRows&&(paths.length=rowCount);const finalParentRowIndex=parentRowIndex.subarray(0,rowCount),finalPosInSetByIndex=posInSetByIndex.subarray(0,rowCount),finalSetSizeByIndex=setSizeByIndex.subarray(0,rowCount);let cachedVisibleIndexByPath=null;return{getParentIndex(index){return index<0||index>=rowCount?-1:finalParentRowIndex[index]??-1},paths,posInSetByIndex:finalPosInSetByIndex,setSizeByIndex:finalSetSizeByIndex,get visibleIndexByPath(){if(cachedVisibleIndexByPath==null){cachedVisibleIndexByPath=new Map;for(let rowIndex=0;rowIndex<rowCount;rowIndex+=1)cachedVisibleIndexByPath.set(paths[rowIndex]??"",rowIndex)}return cachedVisibleIndexByPath}}}function collectVisibleRowsDFS(state,maxRows){const rows=new Array(maxRows);let rowCount=0;const{nodes,directories,segmentTable}=state.snapshot,stack=[[directories.get(state.snapshot.rootId),0,-1]],segmentValues=segmentTable.valueById,flattenEnabled=state.snapshot.options.flattenEmptyDirectories,pathCacheByNodeId=state.pathCacheByNodeId,pathCacheVersion=state.pathCacheVersion;for(;stack.length>0&&rowCount<maxRows;){const frame=stack[stack.length-1],dirIndex=frame[0];if(frame[1]>=dirIndex.childIds.length){stack.pop();continue}const childId=dirIndex.childIds[frame[1]++],childNode=nodes[childId],visibleDepth=frame[2]+1;if(!isDirectoryNode(childNode)){const cachedPathEntry=pathCacheByNodeId.get(childId);rows[rowCount++]={depth:visibleDepth,flattenedSegments:void 0,hasChildren:!1,id:childId,isExpanded:!1,isFlattened:!1,isLoading:!1,kind:"file",loadState:void 0,name:segmentValues[childNode.nameId],path:cachedPathEntry!=null&&cachedPathEntry.version===pathCacheVersion?cachedPathEntry.path:materializeNodePath(state,childId)};continue}const terminalNodeId=flattenEnabled?getFlattenedTerminalDirectoryId(state,childId):childId,cursor={headNodeId:childId,terminalNodeId,visibleDepth};rows[rowCount++]=materializeVisibleRow(state,cursor);const terminalNode=nodes[terminalNodeId];terminalNode!=null&&isDirectoryNode(terminalNode)&&isDirectoryExpanded(state,terminalNodeId,terminalNode)&&stack.push([directories.get(terminalNodeId),0,visibleDepth])}return rowCount<maxRows&&(rows.length=rowCount),rows}function materializeVisibleRow(state,cursor){const terminalNode=requireNode(state,cursor.terminalNodeId),loadState=isDirectoryNode(terminalNode)?getVisibleRowLoadState(state,cursor):null,path=materializeNodePath(state,cursor.terminalNodeId),name=getSegmentValue(state.snapshot.segmentTable,terminalNode.nameId),hasChildren=isDirectoryNode(terminalNode)&&getDirectoryIndex(state,cursor.terminalNodeId).childIds.length>0,isFlattened=cursor.headNodeId!==cursor.terminalNodeId,instrumentation=state.instrumentation,flattenedSegments=isFlattened?instrumentation==null?collectFlattenedDirectoryChainIds(state,cursor.headNodeId).map(nodeId=>{const node=requireNode(state,nodeId);return{isTerminal:nodeId===cursor.terminalNodeId,name:getSegmentValue(state.snapshot.segmentTable,node.nameId),nodeId,path:materializeNodePath(state,nodeId)}}):withBenchmarkPhase(instrumentation,"store.getVisibleSlice.flatten.collectSegments",()=>collectFlattenedDirectoryChainIds(state,cursor.headNodeId).map(nodeId=>{const node=requireNode(state,nodeId);return{isTerminal:nodeId===cursor.terminalNodeId,name:getSegmentValue(state.snapshot.segmentTable,node.nameId),nodeId,path:materializeNodePath(state,nodeId)}})):void 0;return{depth:cursor.visibleDepth,flattenedSegments,hasChildren,id:cursor.terminalNodeId,isExpanded:isDirectoryNode(terminalNode)&&isDirectoryExpanded(state,cursor.terminalNodeId,terminalNode),isFlattened,isLoading:loadState==="loading",kind:isDirectoryNode(terminalNode)?"directory":"file",loadState:loadState==null||loadState==="loaded"?void 0:loadState,name,path}}function getVisibleRowLoadState(state,cursor){if(cursor.headNodeId===cursor.terminalNodeId)return getDirectoryLoadState(state,cursor.terminalNodeId);const chainNodeIds=collectFlattenedDirectoryChainIds(state,cursor.headNodeId);let hasUnloaded=!1,hasError=!1;for(const nodeId of chainNodeIds){const loadState=getDirectoryLoadState(state,nodeId);if(loadState==="loading")return"loading";if(loadState==="error"){hasError=!0;continue}loadState==="unloaded"&&(hasUnloaded=!0)}return hasError?"error":hasUnloaded?"unloaded":"loaded"}const KIND_MASK=8;function buildSoaNodeStore(snapshot){const{nodes,directories,rootId,options}=snapshot,nodeCount=nodes.length,parentId=new Int32Array(nodeCount),nameId=new Int32Array(nodeCount),depthAndFlags=new Int32Array(nodeCount),subtreeNodeCount=new Int32Array(nodeCount),visibleSubtreeCount=new Int32Array(nodeCount),childStart=new Int32Array(nodeCount),childCount=new Int32Array(nodeCount);for(let id=0;id<nodeCount;id+=1){const node=nodes[id];node!=null&&(parentId[id]=node.parentId,nameId[id]=node.nameId,depthAndFlags[id]=node.depthAndFlags,subtreeNodeCount[id]=node.subtreeNodeCount,visibleSubtreeCount[id]=node.visibleSubtreeCount)}let totalChildren=0;for(const index of directories.values())totalChildren+=index.childIds.length;const childIdsFlat=new Int32Array(totalChildren);let cursor=0;for(const[dirId,index]of directories){const ids=index.childIds;childStart[dirId]=cursor,childCount[dirId]=ids.length;for(let i2=0;i2<ids.length;i2+=1)childIdsFlat[cursor]=ids[i2],cursor+=1}return{nodeCount,rootId,flattenEmptyDirectories:options.flattenEmptyDirectories===!0,parentId,nameId,depthAndFlags,subtreeNodeCount,visibleSubtreeCount,childStart,childCount,childIdsFlat}}function sweepOpenVisibleCountsSoa(store){const{nodeCount,rootId,flattenEmptyDirectories,depthAndFlags,subtreeNodeCount,visibleSubtreeCount,childStart,childCount,childIdsFlat}=store;for(let id=nodeCount-1;id>=1;id-=1){if((depthAndFlags[id]&KIND_MASK)===0)continue;const base=childStart[id],count=childCount[id];let totalChildSubtreeNodeCount=0,totalChildVisibleSubtreeCount=0;for(let ci=0;ci<count;ci+=1){const childId=childIdsFlat[base+ci];totalChildSubtreeNodeCount+=subtreeNodeCount[childId],totalChildVisibleSubtreeCount+=visibleSubtreeCount[childId]}subtreeNodeCount[id]=1+totalChildSubtreeNodeCount;let newVisibleSubtreeCount;flattenEmptyDirectories&&count===1?newVisibleSubtreeCount=(depthAndFlags[childIdsFlat[base]]&KIND_MASK)!==0?totalChildVisibleSubtreeCount:1+totalChildVisibleSubtreeCount:newVisibleSubtreeCount=1+totalChildVisibleSubtreeCount,visibleSubtreeCount[id]=newVisibleSubtreeCount}const rootBase=childStart[rootId],rootCount=childCount[rootId];let rootTotalChildSubtreeNodeCount=0,rootTotalChildVisibleSubtreeCount=0;for(let ci=0;ci<rootCount;ci+=1){const childId=childIdsFlat[rootBase+ci];rootTotalChildSubtreeNodeCount+=subtreeNodeCount[childId],rootTotalChildVisibleSubtreeCount+=visibleSubtreeCount[childId]}subtreeNodeCount[rootId]=1+rootTotalChildSubtreeNodeCount,visibleSubtreeCount[rootId]=rootTotalChildVisibleSubtreeCount}function initializeOpenVisibleCounts(state){const{directories,nodes,options,rootId,presortedDirectoryNodeIds}=state.snapshot,flattenEmptyDirectories=options.flattenEmptyDirectories===!0,walkDirectory=nodeId=>{const currentNode=nodes[nodeId];if(currentNode==null||!isDirectoryNode(currentNode))return;const currentIndex=directories.get(nodeId);if(currentIndex==null)throw new Error(`Unknown directory child index for node ${String(nodeId)}`);const childIds=currentIndex.childIds,childCount=childIds.length;let totalChildSubtreeNodeCount=0,totalChildVisibleSubtreeCount=0;for(let ci=0;ci<childCount;ci++){const childId=childIds[ci];if(childId==null)continue;const childNode=nodes[childId];totalChildSubtreeNodeCount+=childNode.subtreeNodeCount,totalChildVisibleSubtreeCount+=childNode.visibleSubtreeCount}currentIndex.totalChildSubtreeNodeCount=totalChildSubtreeNodeCount,currentIndex.totalChildVisibleSubtreeCount=totalChildVisibleSubtreeCount,childCount>=128&&rebuildVisibleChildChunks(nodes,currentIndex),currentNode.subtreeNodeCount=1+totalChildSubtreeNodeCount;let newVisibleSubtreeCount;if(flattenEmptyDirectories&&childCount===1){const onlyChild=nodes[childIds[0]];newVisibleSubtreeCount=onlyChild!=null&&isDirectoryNode(onlyChild)?totalChildVisibleSubtreeCount:1+totalChildVisibleSubtreeCount}else newVisibleSubtreeCount=1+totalChildVisibleSubtreeCount;currentNode.visibleSubtreeCount=newVisibleSubtreeCount};if(presortedDirectoryNodeIds!=null)for(let i2=presortedDirectoryNodeIds.length-1;i2>=0;i2--)walkDirectory(presortedDirectoryNodeIds[i2]);else for(let nodeId=nodes.length-1;nodeId>=1;nodeId--)walkDirectory(nodeId);const rootNode=nodes[rootId],rootIndex=directories.get(rootId);if(rootNode==null||rootIndex==null)return;const rootChildIds=rootIndex.childIds;let rootTotalChildSubtreeNodeCount=0,rootTotalChildVisibleSubtreeCount=0;for(let ci=0;ci<rootChildIds.length;ci++){const childId=rootChildIds[ci];if(childId==null)continue;const childNode=nodes[childId];rootTotalChildSubtreeNodeCount+=childNode.subtreeNodeCount,rootTotalChildVisibleSubtreeCount+=childNode.visibleSubtreeCount}rootIndex.totalChildSubtreeNodeCount=rootTotalChildSubtreeNodeCount,rootIndex.totalChildVisibleSubtreeCount=rootTotalChildVisibleSubtreeCount,rebuildVisibleChildChunks(nodes,rootIndex),rootNode.subtreeNodeCount=1+rootTotalChildSubtreeNodeCount,rootNode.visibleSubtreeCount=rootTotalChildVisibleSubtreeCount}function initializeOpenVisibleCountsViaSoa(state){const{directories,nodes,rootId}=state.snapshot,soa=buildSoaNodeStore(state.snapshot);sweepOpenVisibleCountsSoa(soa);const subtreeNodeCount=soa.subtreeNodeCount,visibleSubtreeCount=soa.visibleSubtreeCount;for(let id=0;id<nodes.length;id+=1){const node=nodes[id];node!=null&&(node.subtreeNodeCount=subtreeNodeCount[id],node.visibleSubtreeCount=visibleSubtreeCount[id])}for(const[dirId,currentIndex]of directories){const childIds=currentIndex.childIds,childCount=childIds.length;let totalChildSubtreeNodeCount=0,totalChildVisibleSubtreeCount=0;for(let ci=0;ci<childCount;ci++){const childId=childIds[ci];if(childId==null)continue;const childNode=nodes[childId];totalChildSubtreeNodeCount+=childNode.subtreeNodeCount,totalChildVisibleSubtreeCount+=childNode.visibleSubtreeCount}currentIndex.totalChildSubtreeNodeCount=totalChildSubtreeNodeCount,currentIndex.totalChildVisibleSubtreeCount=totalChildVisibleSubtreeCount,(dirId===rootId||childCount>=128)&&rebuildVisibleChildChunks(nodes,currentIndex)}}function canInitializeOpenVisibleCounts(options){return options.initialExpansion==="open"&&(options.initialExpandedPaths==null||options.initialExpandedPaths.length===0)}var PathStore=class PathStore2{#state;constructor(options={}){const instrumentation=getBenchmarkInstrumentation(options),builder=withBenchmarkPhase(instrumentation,"store.builder.create",()=>new PathStoreBuilder(options));if(options.preparedInput!=null){const presortedPaths=getPreparedInputPresortedPaths(options.preparedInput);presortedPaths!=null?builder.appendPresortedPaths(presortedPaths,getPreparedInputPresortedPathsContainDirectories(options.preparedInput)):builder.appendPreparedPaths(getPreparedInputEntries(options.preparedInput),!1)}else{const inputPaths=options.paths??[];options.presorted===!0?builder.appendPaths(inputPaths):builder.appendPreparedPaths(withBenchmarkPhase(instrumentation,"store.preparePathEntries",()=>preparePathEntries(inputPaths,options)))}const snapshot=withBenchmarkPhase(instrumentation,"store.builder.finish",()=>builder.finish({skipSubtreeCountPass:!0})),useExplicitOpenExpansionFastPath=withBenchmarkPhase(instrumentation,"store.state.detectAllDirectoriesExpanded",()=>(options.initialExpansion??"closed")==="closed"&&builder.didMatchAllInitialExpandedPaths());this.#state=withBenchmarkPhase(instrumentation,"store.state.create",()=>createPathStoreState(snapshot,useExplicitOpenExpansionFastPath?"open":options.initialExpansion??"closed",instrumentation)),useExplicitOpenExpansionFastPath&&(this.#state.collapseNewDirectoriesByDefault=!0);const expandedDirectoryCount=useExplicitOpenExpansionFastPath?this.#state.snapshot.directories.size-1:withBenchmarkPhase(instrumentation,"store.state.initializeExpandedPaths",()=>this.initializeExpandedPaths(options.initialExpandedPaths));useExplicitOpenExpansionFastPath||canInitializeOpenVisibleCounts(options)||(options.initialExpansion??"closed")==="closed"&&expandedDirectoryCount===this.#state.snapshot.directories.size-1||(options.initialExpandedPaths?.length??0)>0&&withBenchmarkPhase(instrumentation,"store.state.checkAllDirectoriesExpanded",()=>this.hasAllDirectoriesExpanded())?options.useSoaCountSweep===!0?withBenchmarkPhase(instrumentation,"store.state.initializeOpenVisibleCountsViaSoa",()=>initializeOpenVisibleCountsViaSoa(this.#state)):withBenchmarkPhase(instrumentation,"store.state.initializeOpenVisibleCounts",()=>initializeOpenVisibleCounts(this.#state)):withBenchmarkPhase(instrumentation,"store.state.recomputeCounts",()=>recomputeCountsRecursive(this.#state,this.#state.snapshot.rootId))}static preparePaths(paths,options={}){return preparePaths(paths,options)}static prepareInput(paths,options={}){return prepareInput(paths,options)}static preparePresortedInput(paths){return preparePresortedInput(paths)}list(path){return withBenchmarkPhase(this.#state.instrumentation,"store.list",()=>listPaths(this.#state,path))}add(path){withBenchmarkPhase(this.#state.instrumentation,"store.add",()=>{const previousVisibleCount=getVisibleCount(this.#state);recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,addPath(this.#state,path)))})}remove(path,options={}){withBenchmarkPhase(this.#state.instrumentation,"store.remove",()=>{const previousVisibleCount=getVisibleCount(this.#state);recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,removePath(this.#state,path,options)))})}move(fromPath,toPath,options={}){withBenchmarkPhase(this.#state.instrumentation,"store.move",()=>{const previousVisibleCount=getVisibleCount(this.#state),event=movePath(this.#state,fromPath,toPath,options);event!=null&&recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,event))})}batch(operations){batchEvents(this.#state,()=>{if(typeof operations=="function"){operations(this);return}for(const operation of operations)switch(operation.type){case"add":this.add(operation.path);break;case"remove":this.remove(operation.path,{recursive:operation.recursive});break;case"move":this.move(operation.from,operation.to,{collision:operation.collision});break}})}getVisibleCount(){return withBenchmarkPhase(this.#state.instrumentation,"store.getVisibleCount",()=>getVisibleCount(this.#state))}getVisibleSlice(start,end){return withBenchmarkPhase(this.#state.instrumentation,"store.getVisibleSlice",()=>getVisibleSlice(this.#state,start,end))}getVisibleRowContext(index){return withBenchmarkPhase(this.#state.instrumentation,"store.getVisibleRowContext",()=>getVisibleRowContext(this.#state,index))}getVisibleTreeProjection(){return getVisibleTreeProjection(this.#state)}getVisibleTreeProjectionData(maxRows){return getVisibleTreeProjectionData(this.#state,maxRows)}getVisibleIndex(path){return withBenchmarkPhase(this.#state.instrumentation,"store.getVisibleIndex",()=>getVisibleIndexByPath(this.#state,path))}getPathInfo(path){return withBenchmarkPhase(this.#state.instrumentation,"store.getPathInfo",()=>{const nodeId=findNodeId(this.#state,path);if(nodeId==null)return null;const node=requireNode(this.#state,nodeId);return{depth:getNodeDepth(node),kind:isDirectoryNode(node)?"directory":"file",path:materializeNodePath(this.#state,nodeId)}})}isExpanded(path){return withBenchmarkPhase(this.#state.instrumentation,"store.isExpanded",()=>{const directoryNodeId=this.requireDirectoryNodeId(path),directoryNode=requireNode(this.#state,directoryNodeId);return isDirectoryExpanded(this.#state,directoryNodeId,directoryNode)})}expand(path){withBenchmarkPhase(this.#state.instrumentation,"store.expand",()=>{const previousVisibleCount=getVisibleCount(this.#state),event=expandPath(this.#state,path);event!=null&&recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,event))})}collapse(path){withBenchmarkPhase(this.#state.instrumentation,"store.collapse",()=>{const previousVisibleCount=getVisibleCount(this.#state),event=collapsePath(this.#state,path);event!=null&&recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,event))})}on(type,handler){return subscribe(this.#state,type,handler)}getDirectoryLoadState(path){const directoryNodeId=this.requireDirectoryNodeId(path);return getDirectoryLoadState(this.#state,directoryNodeId)}markDirectoryUnloaded(path){withBenchmarkPhase(this.#state.instrumentation,"store.markDirectoryUnloaded",()=>{const directoryNodeId=this.requireDirectoryNodeId(path);if(getDirectoryIndex(this.#state,directoryNodeId).childIds.length>0)throw new Error(`Cannot mark a directory with known children as unloaded: "${path}"`);const previousVisibleCount=getVisibleCount(this.#state);markDirectoryUnloadedState(this.#state,directoryNodeId),recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,createMarkDirectoryUnloadedEvent({affectedAncestorIds:collectAncestorIds(this.#state,directoryNodeId),affectedNodeIds:[directoryNodeId],path,projectionChanged:this.isDirectoryProjectionVisible(directoryNodeId)})))})}beginChildLoad(path){return withBenchmarkPhase(this.#state.instrumentation,"store.beginChildLoad",()=>{const directoryNodeId=this.requireDirectoryNodeId(path),previousVisibleCount=getVisibleCount(this.#state),attempt=beginDirectoryLoad(this.#state,directoryNodeId);return recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,createBeginChildLoadEvent({affectedAncestorIds:collectAncestorIds(this.#state,directoryNodeId),affectedNodeIds:[directoryNodeId],attemptId:attempt.attemptId,path,projectionChanged:this.isDirectoryProjectionVisible(directoryNodeId),reused:attempt.reused}))),attempt})}applyChildPatch(attempt,patch){return withBenchmarkPhase(this.#state.instrumentation,"store.applyChildPatch",()=>{const directoryNodeId=this.resolveActiveDirectoryNodeId(attempt.nodeId);if(directoryNodeId==null||getDirectoryLoadState(this.#state,directoryNodeId)!=="loading"||!isDirectoryLoadAttemptCurrent(this.#state,directoryNodeId,attempt.attemptId))return!1;const directoryPath=materializeNodePath(this.#state,directoryNodeId);this.validateChildPatch(directoryPath,patch);const previousVisibleCount=getVisibleCount(this.#state),childEvents=[];for(const operation of patch.operations){assertOperationTargetsDirectory(directoryPath,operation);const operationVisibleCount=getVisibleCount(this.#state);switch(operation.type){case"add":childEvents.push(finalizeEvent(this.#state,operationVisibleCount,addPath(this.#state,operation.path)));break;case"remove":childEvents.push(finalizeEvent(this.#state,operationVisibleCount,removePath(this.#state,operation.path,{recursive:operation.recursive})));break;case"move":{const event=movePath(this.#state,operation.from,operation.to,{collision:operation.collision});event!=null&&childEvents.push(finalizeEvent(this.#state,operationVisibleCount,event));break}}}const projectionChanged=childEvents.some(event=>event.projectionChanged)||this.isDirectoryProjectionVisible(directoryNodeId);return recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,createApplyChildPatchEvent({affectedAncestorIds:collectAncestorIds(this.#state,directoryNodeId),affectedNodeIds:[directoryNodeId],attemptId:attempt.attemptId,childEvents,path:materializeNodePath(this.#state,directoryNodeId),projectionChanged}))),!0})}completeChildLoad(attempt){return withBenchmarkPhase(this.#state.instrumentation,"store.completeChildLoad",()=>{const directoryNodeId=this.resolveActiveDirectoryNodeId(attempt.nodeId);if(directoryNodeId==null)return!1;const previousVisibleCount=getVisibleCount(this.#state),applied=completeDirectoryLoad(this.#state,directoryNodeId,attempt.attemptId);return recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,createCompleteChildLoadEvent({affectedAncestorIds:collectAncestorIds(this.#state,directoryNodeId),affectedNodeIds:[directoryNodeId],attemptId:attempt.attemptId,path:materializeNodePath(this.#state,directoryNodeId),projectionChanged:this.isDirectoryProjectionVisible(directoryNodeId),stale:!applied}))),applied})}failChildLoad(attempt,errorMessage){return withBenchmarkPhase(this.#state.instrumentation,"store.failChildLoad",()=>{const directoryNodeId=this.resolveActiveDirectoryNodeId(attempt.nodeId);if(directoryNodeId==null)return!1;const previousVisibleCount=getVisibleCount(this.#state),applied=failDirectoryLoad(this.#state,directoryNodeId,attempt.attemptId,errorMessage);return recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,createFailChildLoadEvent({affectedAncestorIds:collectAncestorIds(this.#state,directoryNodeId),affectedNodeIds:[directoryNodeId],attemptId:attempt.attemptId,errorMessage,path:materializeNodePath(this.#state,directoryNodeId),projectionChanged:this.isDirectoryProjectionVisible(directoryNodeId),stale:!applied}))),applied})}cleanup(options={}){return withBenchmarkPhase(this.#state.instrumentation,"store.cleanup",()=>{if(this.#state.transactionStack.length>0)throw new Error("Cleanup cannot run during an open batch or transaction.");if(hasActiveCleanupBlockingLoads(this.#state))throw new Error("Cleanup cannot run while directory loads are active.");const previousVisibleCount=getVisibleCount(this.#state),result=cleanupPathStoreState(this.#state,options.mode??"stable");return recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,createCleanupEvent({...result,affectedAncestorIds:[],affectedNodeIds:[],projectionChanged:result.idsPreserved===!1}))),result})}getNodeCount(){return this.#state.activeNodeCount}initializeExpandedPaths(expandedPaths){if(expandedPaths==null||expandedPaths.length===0)return 0;let expandedDirectoryCount=0;const previousChildOffsets=[],previousNodeIds=[];let previousEndIndex=0,previousPath=null;const segmentTable=this.#state.snapshot.segmentTable,segmentValues=segmentTable.valueById,nodes=this.#state.snapshot.nodes,targetSegmentSortKeyCache=new Map;for(const path of expandedPaths){previousPath!=null&&path<previousPath&&(previousPath=null,previousEndIndex=0,previousChildOffsets.length=0,previousNodeIds.length=0);const endIndex=path.length>0&&path.charCodeAt(path.length-1)===47?path.length-1:path.length;if(endIndex===0){previousPath=path,previousEndIndex=endIndex,previousChildOffsets.length=0,previousNodeIds.length=0;continue}let sharedDepth=0,unsharedSegmentStart=0;if(previousPath!=null){const compareLength=Math.min(endIndex,previousEndIndex);let prefixMatched=!0;for(let charIndex=0;charIndex<compareLength;charIndex+=1){const charCode=path.charCodeAt(charIndex);if(charCode!==previousPath.charCodeAt(charIndex)){prefixMatched=!1;break}charCode===47&&(sharedDepth+=1,unsharedSegmentStart=charIndex+1)}prefixMatched&&(compareLength===previousEndIndex&&endIndex>compareLength&&path.charCodeAt(compareLength)===47?(sharedDepth+=1,unsharedSegmentStart=compareLength+1):compareLength===endIndex&&previousEndIndex>compareLength&&previousPath.charCodeAt(compareLength)===47&&(sharedDepth+=1,unsharedSegmentStart=endIndex+1)),sharedDepth=Math.min(sharedDepth,previousNodeIds.length)}let currentDirectoryId=sharedDepth===0?this.#state.snapshot.rootId:previousNodeIds[sharedDepth-1]??this.#state.snapshot.rootId,resolvedDepth=sharedDepth,foundDirectory=!0,segmentStart=unsharedSegmentStart;for(;segmentStart<=endIndex;){const slashIndex=path.indexOf("/",segmentStart),segmentEnd=slashIndex===-1||slashIndex>endIndex?endIndex:slashIndex,segment=path.slice(segmentStart,segmentEnd),childIds=getDirectoryIndex(this.#state,currentDirectoryId).childIds,searchStartIndex=resolvedDepth===sharedDepth?previousChildOffsets[resolvedDepth]??0:0;let nextChildOffset=searchStartIndex,nextNodeId;const targetSegmentSortKey=targetSegmentSortKeyCache.get(segment)??createSegmentSortKey(segment);targetSegmentSortKeyCache.set(segment,targetSegmentSortKey);const searchForSegment=(startIndex,endIndex2)=>{for(nextChildOffset=startIndex;nextChildOffset<endIndex2;nextChildOffset+=1){const candidateNodeId=childIds[nextChildOffset],candidateNode=nodes[candidateNodeId],candidateSegment=segmentValues[candidateNode.nameId];if(candidateSegment===segment)return nextNodeId=candidateNodeId,!0;const orderComparison=compareSegmentSortKeys(getSegmentSortKey(segmentTable,candidateNode.nameId),targetSegmentSortKey);if(orderComparison>0||orderComparison===0&&candidateSegment>segment)return!1}return!1};if(!searchForSegment(searchStartIndex,childIds.length)&&searchStartIndex>0&&searchForSegment(0,searchStartIndex),nextNodeId===void 0){foundDirectory=!1;break}if(!isDirectoryNode(requireNode(this.#state,nextNodeId))){foundDirectory=!1;break}if(previousChildOffsets[resolvedDepth]=nextChildOffset,previousNodeIds[resolvedDepth]=nextNodeId,currentDirectoryId=nextNodeId,resolvedDepth+=1,segmentEnd===endIndex)break;segmentStart=segmentEnd+1}if(previousPath=path,previousEndIndex=endIndex,previousChildOffsets.length=resolvedDepth,previousNodeIds.length=resolvedDepth,!foundDirectory){previousPath=null,previousEndIndex=0,previousChildOffsets.length=0,previousNodeIds.length=0;continue}for(let depthIndex=sharedDepth;depthIndex<resolvedDepth;depthIndex+=1){const directoryNodeId=previousNodeIds[depthIndex];if(directoryNodeId==null)continue;const directoryNode=requireNode(this.#state,directoryNodeId);isDirectoryExpanded(this.#state,directoryNodeId,directoryNode)||(setDirectoryExpanded(this.#state,directoryNodeId,!0,directoryNode),expandedDirectoryCount+=1)}}return expandedDirectoryCount}hasAllDirectoriesExpanded(){for(const directoryNodeId of this.#state.snapshot.directories.keys()){if(directoryNodeId===this.#state.snapshot.rootId)continue;const directoryNode=requireNode(this.#state,directoryNodeId);if(!isDirectoryExpanded(this.#state,directoryNodeId,directoryNode))return!1}return!0}requireDirectoryNodeId(path){const directoryNodeId=findNodeId(this.#state,path);if(directoryNodeId==null)throw new Error(`Path does not exist: "${path}"`);if(!isDirectoryNode(requireNode(this.#state,directoryNodeId)))throw new Error(`Path is not a directory: "${path}"`);return directoryNodeId}resolveActiveDirectoryNodeId(directoryNodeId){try{if(!isDirectoryNode(requireNode(this.#state,directoryNodeId)))throw new Error(`Node is not a directory: ${String(directoryNodeId)}`);return directoryNodeId}catch{return null}}isDirectoryProjectionVisible(directoryNodeId){let currentNodeId=directoryNodeId;for(;currentNodeId!==this.#state.snapshot.rootId;){const parentId=requireNode(this.#state,currentNodeId).parentId;if(parentId!==this.#state.snapshot.rootId){const parentNode=requireNode(this.#state,parentId),flattenedChildDirectoryId=getFlattenedChildDirectoryId(this.#state,parentId);if(!isDirectoryExpanded(this.#state,parentId,parentNode)&&flattenedChildDirectoryId!==currentNodeId)return!1}currentNodeId=parentId}return!0}validateChildPatch(directoryPath,patch){new PathStore2({paths:this.list(directoryPath),presorted:!0,sort:this.#state.snapshot.options.sort}).batch(patch.operations)}};function assertOperationTargetsDirectory(directoryPath,operation){switch(operation.type){case"add":case"remove":if(!operation.path.startsWith(directoryPath)||operation.path===directoryPath)throw new Error(`Child patch operation must stay within ${directoryPath}: "${operation.path}"`);break;case"move":if(!operation.from.startsWith(directoryPath)||!operation.to.startsWith(directoryPath)||operation.from===directoryPath||operation.to===directoryPath)throw new Error(`Child patch move must stay within ${directoryPath}: "${operation.from}" -> "${operation.to}"`);break}}const FILE_TREE_DENSITY_PRESETS={compact:{itemHeight:24,factor:.8},default:{itemHeight:30,factor:1},relaxed:{itemHeight:36,factor:1.2}};function resolveFileTreeDensity(density,explicitItemHeight){if(typeof density=="number")return{itemHeight:explicitItemHeight??FILE_TREE_DENSITY_PRESETS.default.itemHeight,factor:density};const preset=FILE_TREE_DENSITY_PRESETS[density??"default"];return{itemHeight:explicitItemHeight??preset.itemHeight,factor:preset.factor}}const FILE_TREE_DEFAULT_ITEM_HEIGHT=FILE_TREE_DENSITY_PRESETS.default.itemHeight;var style_default=`@layer base {
1
+ import{j as jsxRuntimeExports,r as reactExports,c as reactDomExports}from"./vendor-react-CxJ4vs-5.js";import{t as useLabels,bE as TabPill,bF as usePresence,bG as readMenuExitMs,bH as useCodeHighlight,bD as Tooltip,I as IconButton,bC as useEditorPrefs,av as useFilesHost,aw as useFilesLabels,bI as useCodeDocument,bJ as excerptFromContents,bK as serializeDiagnostic,bu as languageFor,bv as rangeLabel,bx as attachmentName,aG as useAppearanceReducedMotion,aN as PanelLoading,Y as useLinkRouter,Z as useLightbox,au as mediaTypeOfPath,bL as Markdown,n as RowActionsMenu,bM as useGitHost,bw as serializeCodeSnippet,bN as copyImage,bO as copyImageBase64,bP as copyImageDataUrl,bQ as mediaSiblings,bR as ReorderTabs,bS as Breadcrumb,aM as IconToggle,aO as PanelEmpty,bT as readPanelMs,bU as usePanelSettled,bV as useResizeDrag,N as Notice,j as useOptionalConfirm,bW as entryRefusalText,bX as topLevelPaths,bY as parentOf,bZ as inFolder,b_ as nameOf,b$ as droppedItems,ay as filesRootOf,c0 as movedPath,c1 as isUnder,c2 as filesScopeKey,c3 as createMemoryFilesLayout,aB as usePanelVisible,c4 as useAppearanceState,c5 as useReadable,aJ as steppedIndex}from"./kit-CD3F-f6F.js";import{c as createFileTreeIconResolver,g as getBuiltInSpriteSheet,n as normalizeFileTreeIcons,i as isColoredBuiltInIconSet,F as FileIcon}from"./FileIcon-DECOEMOz.js";import{aE as TREES_HOST_STYLE,aF as TREES_UNSAFE_CSS,u as useWorkerPool}from"./pierre-theme-BrzM0xZU.js";import{C as CodeEditor,E as EditStateManager}from"./CodeEditor-CLsAw7eu.js";import{g as DIAGNOSTIC_GLYPH,h as fileActionItems,i as useFilesChat,j as useCodeReview,k as diagnosticsByLine,l as diagnosticMarkers,m as diagnosticsAt,D as DiffScroller,R as ReviewableDiff,p as parseFilePatch,o as noChatItem,c as countBySeverity,u as useDiagnosticsRun,q as absolutePath,r as MediaFrame,M as MediaView,a as useFolderChanges,e as useNoKeyScope,n as nameMatches,F as FilesChatContext,S as SearchPanel,d as useNoEdits}from"./useFolderChanges-C9L_NOgw.js";import{ad as REVEAL_FALLBACK_MS,d as diffLines,u as useFind,F as FindBar}from"./useFind-Cdl0rVJO.js";import"./vendor-motion-C2jPaSqL.js";import"./vendor-owxl31sT.js";import"./core-Cj89wpQh.js";import"./vendor-editor-gVJMCtGz.js";import"./utils-qCteL8MB.js";import"./hastToHtml-C4ea9WpN.js";import"./index-C-yjveB4.js";const FILE_TREE_TAG_NAME="file-tree-container",FILE_TREE_STYLE_ATTRIBUTE="data-file-tree-style",FILE_TREE_UNSAFE_CSS_ATTRIBUTE="data-file-tree-unsafe-css",FILE_TREE_SCROLLBAR_MEASURE_ATTRIBUTE="data-file-tree-scrollbar-measure",FILE_TREE_SCROLLBAR_GUTTER_STYLE_ATTRIBUTE="data-file-tree-scrollbar-gutter-measured",FILE_TREE_SCROLLBAR_GUTTER_MEASURED_PROPERTY="--trees-scrollbar-gutter-measured",HEADER_SLOT_NAME="header",CONTEXT_MENU_SLOT_NAME="context-menu",CONTEXT_MENU_TRIGGER_TYPE="context-menu-trigger",PATH_STORE_CHILD_INDEX_CHUNK_SHIFT=5,PATH_STORE_CHILD_INDEX_CHUNK_SIZE=1<<PATH_STORE_CHILD_INDEX_CHUNK_SHIFT,PATH_STORE_CHILD_INDEX_CHUNK_THRESHOLD=PATH_STORE_CHILD_INDEX_CHUNK_SIZE*4;function createDirectoryChildIndex(){return{childIdByNameId:new Map,childIds:[],childPositionById:new Map,childVisibleChunkSums:null,totalChildSubtreeNodeCount:0,totalChildVisibleSubtreeCount:0}}function createPresortedDirectoryChildIndex(){return{childIdByNameId:null,childIds:[],childPositionById:null,childVisibleChunkSums:null,totalChildSubtreeNodeCount:0,totalChildVisibleSubtreeCount:0}}function ensureChildIdByNameId(nodes,index){if(index.childIdByNameId!=null)return index.childIdByNameId;const map=new Map;for(const childId of index.childIds){const childNode=nodes[childId];childNode!=null&&map.set(childNode.nameId,childId)}return index.childIdByNameId=map,map}function ensureChildPositions(index){if(index.childPositionById!=null)return index.childPositionById;const positions=new Map;for(let i2=0;i2<index.childIds.length;i2++){const childId=index.childIds[i2];childId!=null&&positions.set(childId,i2)}return index.childPositionById=positions,positions}function appendChildReference(index,childId){index.childPositionById!=null&&index.childPositionById.set(childId,index.childIds.length),index.childIds.push(childId)}function updateChildPositionsFrom(index,startIndex){if(index.childPositionById!=null)for(let position=startIndex;position<index.childIds.length;position++){const childId=index.childIds[position];childId!=null&&index.childPositionById.set(childId,position)}}function rebuildDirectoryChildAggregates(nodes,index){let totalChildSubtreeNodeCount=0,totalChildVisibleSubtreeCount=0;for(const childId of index.childIds){const childNode=nodes[childId];childNode!=null&&(totalChildSubtreeNodeCount+=childNode.subtreeNodeCount,totalChildVisibleSubtreeCount+=childNode.visibleSubtreeCount)}index.totalChildSubtreeNodeCount=totalChildSubtreeNodeCount,index.totalChildVisibleSubtreeCount=totalChildVisibleSubtreeCount,rebuildVisibleChildChunks(nodes,index)}function applyChildAggregateDelta(index,childId,subtreeNodeDelta,visibleSubtreeDelta){if(index.totalChildSubtreeNodeCount+=subtreeNodeDelta,index.totalChildVisibleSubtreeCount+=visibleSubtreeDelta,index.childVisibleChunkSums==null||visibleSubtreeDelta===0)return;const childPosition=ensureChildPositions(index).get(childId);if(childPosition===void 0)return;const chunkIndex=childPosition>>PATH_STORE_CHILD_INDEX_CHUNK_SHIFT;index.childVisibleChunkSums[chunkIndex]+=visibleSubtreeDelta}function selectChildIndexByVisibleIndex(nodes,index,visibleIndex){const chunkSums=index.childVisibleChunkSums;if(chunkSums!=null){let remainingIndex2=visibleIndex,childIndex=0;for(const chunkVisibleCount of chunkSums){if(remainingIndex2<chunkVisibleCount){const selected=selectChildIndexWithinChunk(nodes,index,childIndex,remainingIndex2);return{...selected,childVisibleIndex:visibleIndex-selected.localVisibleIndex}}remainingIndex2-=chunkVisibleCount,childIndex+=PATH_STORE_CHILD_INDEX_CHUNK_SIZE}throw new Error(`Visible child index ${String(visibleIndex)} is out of range`)}let remainingIndex=visibleIndex;for(let childIndex=0;childIndex<index.childIds.length;childIndex++){const childId=index.childIds[childIndex];if(childId==null)continue;const childNode=nodes[childId];if(childNode!=null){if(remainingIndex<childNode.visibleSubtreeCount)return{childIndex,childVisibleIndex:visibleIndex-remainingIndex,localVisibleIndex:remainingIndex};remainingIndex-=childNode.visibleSubtreeCount}}throw new Error(`Visible child index ${String(visibleIndex)} is out of range`)}function getVisibleChildPrefixCount(nodes,index,childPosition){let visibleCount=0;const chunkSums=index.childVisibleChunkSums;let scanStart=0;if(chunkSums!=null){const chunkIndex=childPosition>>PATH_STORE_CHILD_INDEX_CHUNK_SHIFT;for(let chunkOffset=0;chunkOffset<chunkIndex;chunkOffset+=1)visibleCount+=chunkSums[chunkOffset]??0;scanStart=chunkIndex<<PATH_STORE_CHILD_INDEX_CHUNK_SHIFT}for(let childIndex=scanStart;childIndex<childPosition;childIndex+=1){const childId=index.childIds[childIndex];if(childId==null)continue;const childNode=nodes[childId];childNode!=null&&(visibleCount+=childNode.visibleSubtreeCount)}return visibleCount}function rebuildVisibleChildChunks(nodes,index){if(index.childIds.length<PATH_STORE_CHILD_INDEX_CHUNK_THRESHOLD){index.childVisibleChunkSums=null;return}const chunkCount=Math.ceil(index.childIds.length/PATH_STORE_CHILD_INDEX_CHUNK_SIZE),chunkSums=new Int32Array(chunkCount);for(let childIndex=0;childIndex<index.childIds.length;childIndex++){const childId=index.childIds[childIndex];if(childId==null)continue;const childNode=nodes[childId];childNode!=null&&(chunkSums[childIndex>>PATH_STORE_CHILD_INDEX_CHUNK_SHIFT]+=childNode.visibleSubtreeCount)}index.childVisibleChunkSums=chunkSums}function selectChildIndexWithinChunk(nodes,index,chunkStartIndex,visibleIndex){const chunkEndIndex=Math.min(index.childIds.length,chunkStartIndex+PATH_STORE_CHILD_INDEX_CHUNK_SIZE);let remainingIndex=visibleIndex;for(let childIndex=chunkStartIndex;childIndex<chunkEndIndex;childIndex++){const childId=index.childIds[childIndex];if(childId==null)continue;const childNode=nodes[childId];if(childNode!=null){if(remainingIndex<childNode.visibleSubtreeCount)return{childIndex,localVisibleIndex:remainingIndex};remainingIndex-=childNode.visibleSubtreeCount}}throw new Error(`Visible child index ${String(visibleIndex)} is out of range`)}const PATH_STORE_NODE_FLAGS_MASK=7,PATH_STORE_NODE_KIND_SHIFT=3,PATH_STORE_NODE_KIND_MASK=1<<PATH_STORE_NODE_KIND_SHIFT,PATH_STORE_NODE_DEPTH_SHIFT=4;function createNodeDepthAndFlags(depth,flags,kind=0){return depth<<PATH_STORE_NODE_DEPTH_SHIFT|kind<<PATH_STORE_NODE_KIND_SHIFT|flags}function getNodeDepth(node){return node.depthAndFlags>>>PATH_STORE_NODE_DEPTH_SHIFT}function getNodeKind(node){return(node.depthAndFlags&PATH_STORE_NODE_KIND_MASK)>>PATH_STORE_NODE_KIND_SHIFT}function isDirectoryNode(node){return(node.depthAndFlags&PATH_STORE_NODE_KIND_MASK)!==0}function getNodeFlags(node){return node.depthAndFlags&PATH_STORE_NODE_FLAGS_MASK}function hasNodeFlag(node,flag){return(getNodeFlags(node)&flag)!==0}function addNodeFlag(node,flag){node.depthAndFlags|=flag}function setNodeDepth(node,depth){node.depthAndFlags=createNodeDepthAndFlags(depth,getNodeFlags(node),getNodeKind(node))}const BENCHMARK_INSTRUMENTATION=Symbol("benchmarkInstrumentation");function attachBenchmarkInstrumentation(value,instrumentation){return instrumentation==null||Object.defineProperty(value,BENCHMARK_INSTRUMENTATION,{configurable:!0,enumerable:!1,value:instrumentation,writable:!1}),value}function getBenchmarkInstrumentation(value){return value==null?null:value[BENCHMARK_INSTRUMENTATION]??null}function withBenchmarkPhase(instrumentation,name,fn){return instrumentation==null?fn():instrumentation.measurePhase(name,fn)}function setBenchmarkCounter(instrumentation,name,value){!Number.isFinite(value)||instrumentation==null||instrumentation.setCounter(name,value)}function isDigitCode(characterCode){return characterCode>=48&&characterCode<=57}function splitIntoNaturalTokens(value){const tokens=[];let tokenStart=0,index=0;for(;index<value.length;){for(;index<value.length&&!isDigitCode(value.charCodeAt(index));)index+=1;if(index>=value.length)break;index>tokenStart&&tokens.push(value.slice(tokenStart,index));let numberValue=0;for(;index<value.length&&isDigitCode(value.charCodeAt(index));)numberValue=numberValue*10+(value.charCodeAt(index)-48),index+=1;tokens.push(numberValue),tokenStart=index}return(tokenStart<value.length||tokens.length===0)&&tokens.push(value.slice(tokenStart)),tokens}function createSegmentSortKey(value){const lowerValue=value.toLowerCase();return{lowerValue,tokens:splitIntoNaturalTokens(lowerValue)}}function compareNaturalTokens(leftTokens,rightTokens){const tokenCount=Math.min(leftTokens.length,rightTokens.length);for(let index=0;index<tokenCount;index++){const leftToken=leftTokens[index],rightToken=rightTokens[index];if(leftToken===rightToken)continue;if(typeof leftToken=="number"&&typeof rightToken=="number")return leftToken<rightToken?-1:1;const leftString=String(leftToken),rightString=String(rightToken);if(leftString!==rightString)return leftString<rightString?-1:1}return leftTokens.length!==rightTokens.length?leftTokens.length<rightTokens.length?-1:1:0}function compareSegmentSortKeys(leftKey,rightKey){if(leftKey.tokens.length===1&&rightKey.tokens.length===1&&typeof leftKey.tokens[0]=="string"&&typeof rightKey.tokens[0]=="string")return leftKey.lowerValue===rightKey.lowerValue?0:leftKey.lowerValue<rightKey.lowerValue?-1:1;const tokenComparison=compareNaturalTokens(leftKey.tokens,rightKey.tokens);return tokenComparison!==0?tokenComparison:leftKey.lowerValue!==rightKey.lowerValue?leftKey.lowerValue<rightKey.lowerValue?-1:1:0}function compareSegmentValuesWithSortKeyLookup(left,right,getSortKey){const comparison=compareSegmentSortKeys(getSortKey(left),getSortKey(right));return comparison!==0?comparison:left===right?0:left<right?-1:1}function compareSegmentValues(left,right){return compareSegmentValuesWithSortKeyLookup(left,right,createSegmentSortKey)}function getKindAtDepth(entry,depth){return depth!==entry.segments.length-1||entry.isDirectory?1:0}function comparePreparedEntries(left,right){const sharedDepth=Math.min(left.segments.length,right.segments.length);for(let depth=0;depth<sharedDepth;depth++){const leftSegment=left.segments[depth],rightSegment=right.segments[depth];if(leftSegment===rightSegment)continue;const leftKind=getKindAtDepth(left,depth);return leftKind!==getKindAtDepth(right,depth)?leftKind===1?-1:1:compareSegmentValues(leftSegment,rightSegment)}return left.segments.length!==right.segments.length?left.segments.length<right.segments.length?-1:1:left.isDirectory===right.isDirectory?0:left.isDirectory?-1:1}function comparePreparedPaths(left,right){return comparePreparedEntries(left,right)}function comparePreparedPathsWithCachedSortKeys(left,right,cache){const getCachedSortKey=value=>{const existingKey=cache.get(value);if(existingKey!=null)return existingKey;const nextKey=createSegmentSortKey(value);return cache.set(value,nextKey),nextKey},sharedDepth=Math.min(left.segments.length,right.segments.length);for(let depth=0;depth<sharedDepth;depth++){const leftSegment=left.segments[depth],rightSegment=right.segments[depth];if(leftSegment===rightSegment)continue;const leftKind=getKindAtDepth(left,depth);return leftKind!==getKindAtDepth(right,depth)?leftKind===1?-1:1:compareSegmentValuesWithSortKeyLookup(leftSegment,rightSegment,getCachedSortKey)}return left.segments.length!==right.segments.length?left.segments.length<right.segments.length?-1:1:left.isDirectory===right.isDirectory?0:left.isDirectory?-1:1}function getSegmentSortKey(segmentTable,segmentId){const existingKey=segmentTable.sortKeyById[segmentId];if(existingKey!==void 0)return existingKey;const value=segmentTable.valueById[segmentId],nextKey=createSegmentSortKey(value);return segmentTable.sortKeyById[segmentId]=nextKey,nextKey}function resolvePathStoreOptions(options={}){return{flattenEmptyDirectories:options.flattenEmptyDirectories!==!1,sort:options.sort??"default"}}function splitCanonicalPath(inputPath){const hasTrailingSlash=inputPath.length>0&&inputPath.charCodeAt(inputPath.length-1)===47,endIndex=hasTrailingSlash?inputPath.length-1:inputPath.length,segments=[];let segmentStart=0;for(let index=0;index<endIndex;index++)inputPath.charCodeAt(index)===47&&(segments.push(inputPath.slice(segmentStart,index)),segmentStart=index+1);return segments.push(inputPath.slice(segmentStart,endIndex)),{hasTrailingSlash,segments}}function parseInputPath(inputPath){const{hasTrailingSlash,segments}=splitCanonicalPath(inputPath);return{basename:segments[segments.length-1]??"",isDirectory:hasTrailingSlash,path:inputPath,segments}}function parseLookupPath(inputPath){if(inputPath.length===0)return{requiresDirectory:!1,segments:[]};const{hasTrailingSlash,segments}=splitCanonicalPath(inputPath);return{requiresDirectory:hasTrailingSlash,segments}}function createSegmentTable(){const idByValue=new Map;return idByValue.set("",0),{idByValue,valueById:[""],sortKeyById:[createSegmentSortKey("")]}}function internSegment(segmentTable,value){const existingId=segmentTable.idByValue.get(value);if(existingId!==void 0)return existingId;const nextId=segmentTable.valueById.length;return segmentTable.idByValue.set(value,nextId),segmentTable.valueById.push(value),nextId}function getSegmentValue(segmentTable,segmentId){const value=segmentTable.valueById[segmentId];if(value===void 0)throw new Error(`Unknown segment ID: ${String(segmentId)}`);return value}const PREPARED_INPUT_KIND=Symbol("pathStorePreparedInputKind");function attachPreparedInputKind(value,kind){return value[PREPARED_INPUT_KIND]=kind,value}function createCompareEntry$1(preparedPath){return{basename:preparedPath.basename,depth:preparedPath.segments.length,isDirectory:preparedPath.isDirectory,path:preparedPath.path,segments:preparedPath.segments}}function compareWithSortOption(left,right,sort){return sort==="default"?comparePreparedPaths(left,right):sort(createCompareEntry$1(left),createCompareEntry$1(right))}function createRootNode(){return{depthAndFlags:createNodeDepthAndFlags(0,3,1),nameId:0,parentId:0,subtreeNodeCount:1,visibleSubtreeCount:1}}function computeSharedPrefixLength(left,right){const maxLength=Math.min(left.length,right.length);for(let index=0;index<maxLength;index++)if(left[index]!==right[index])return index;return maxLength}function getDirectoryDepth(preparedPath){return preparedPath.isDirectory?preparedPath.segments.length:preparedPath.segments.length-1}function isPreparedPathArray(value){return Array.isArray(value)&&value.every(entry=>entry!=null&&typeof entry=="object"&&typeof entry.path=="string"&&Array.isArray(entry.segments)&&typeof entry.basename=="string"&&typeof entry.isDirectory=="boolean")}function isStringArray(value){return Array.isArray(value)&&value.every(entry=>typeof entry=="string")}function preparePaths(paths,options={}){return preparePathEntries(paths,options).map(entry=>entry.path)}function prepareInput(paths,options={}){const preparedPaths=preparePathEntries(paths,options);return attachPreparedInputKind({paths:preparedPaths.map(entry=>entry.path),preparedPaths},"prepared")}function preparePresortedInput(paths){const pathCount=paths.length;let presortedPathsContainDirectories=!1;for(let index=0;index<pathCount;index+=1){const path=paths[index];if(path.length>0&&path.charCodeAt(path.length-1)===47){presortedPathsContainDirectories=!0;break}}return attachPreparedInputKind({paths,presortedPaths:paths,presortedPathsContainDirectories},"presorted")}function getPreparedInputEntries(preparedInput){const internalPreparedInput=preparedInput,preparedPaths=internalPreparedInput.preparedPaths;if(internalPreparedInput[PREPARED_INPUT_KIND]==="prepared"&&preparedPaths!=null)return preparedPaths;if(!isPreparedPathArray(preparedPaths))throw new Error("preparedInput must come from PathStore.prepareInput()");return preparedPaths}function getPreparedInputPresortedPaths(preparedInput){const internalPreparedInput=preparedInput;return internalPreparedInput[PREPARED_INPUT_KIND]==="presorted"&&internalPreparedInput.presortedPaths!=null||isStringArray(internalPreparedInput.presortedPaths)?internalPreparedInput.presortedPaths:null}function getPreparedInputPresortedPathsContainDirectories(preparedInput){const internalPreparedInput=preparedInput;return typeof internalPreparedInput.presortedPathsContainDirectories=="boolean"?internalPreparedInput.presortedPathsContainDirectories:null}function preparePathEntries(paths,options={}){const resolvedOptions=resolvePathStoreOptions(options),instrumentation=getBenchmarkInstrumentation(options);setBenchmarkCounter(instrumentation,"workload.inputFiles",paths.length);const preparedPaths=withBenchmarkPhase(instrumentation,"store.preparePathEntries.parse",()=>paths.map(path=>parseInputPath(path)));return withBenchmarkPhase(instrumentation,"store.preparePathEntries.sort",()=>preparedPaths.sort((left,right)=>compareWithSortOption(left,right,resolvedOptions.sort))),preparedPaths}var PathStoreBuilder=class{directories=new Map;directoryStack=[0];presortedDirectoryNodeIds=[];initialExpandedPathSet;createdDirectoriesAllExpanded=!1;createdDirectoryCount=0;lastPreparedPath=null;nodes=[createRootNode()];options;instrumentation;segmentSortKeyCache=new Map;segmentTable=createSegmentTable();hasDeferredDirectoryIndexes=!1;constructor(options={}){this.instrumentation=getBenchmarkInstrumentation(options),this.options=resolvePathStoreOptions(options);const initialExpandedPaths=options.initialExpandedPaths??null;if(initialExpandedPaths==null||initialExpandedPaths.length===0)this.initialExpandedPathSet=null;else{const normalizedPaths=new Set,hintCount=initialExpandedPaths.length;for(let index=0;index<hintCount;index+=1){const path=initialExpandedPaths[index],length=path.length;normalizedPaths.add(length>0&&path.charCodeAt(length-1)===47?path.slice(0,length-1):path)}this.initialExpandedPathSet=normalizedPaths,this.createdDirectoriesAllExpanded=!0}this.directories.set(0,createDirectoryChildIndex())}appendPaths(paths){return withBenchmarkPhase(this.instrumentation,"store.builder.appendPaths.parse",()=>this.appendPreparedPaths(paths.map(path=>parseInputPath(path))))}appendPreparedPaths(preparedPaths,validateOrder=!0){return this.createdDirectoriesAllExpanded=!1,withBenchmarkPhase(this.instrumentation,"store.builder.appendPreparedPaths",()=>{for(const preparedPath of preparedPaths)this.appendPreparedPath(preparedPath,validateOrder)}),this}appendPresortedPaths(paths,containsDirectories=null){return withBenchmarkPhase(this.instrumentation,"store.builder.appendPresortedPaths",()=>{if(containsDirectories===!1){this.appendPresortedFilePaths(paths);return}this.createdDirectoriesAllExpanded=!1;let previousPath=null,currentDepth=0;const nodes=this.nodes,segmentTable=this.segmentTable,idByValue=segmentTable.idByValue,valueById=segmentTable.valueById,dirStack=this.directoryStack;let stackTop=0,cachedDirPrefix="",cachedDirDepth=0;for(const path of paths){if(previousPath===path)throw new Error(`Duplicate path: "${path}"`);const hasTrailingSlash=path.length>0&&path.charCodeAt(path.length-1)===47,endIndex=hasTrailingSlash?path.length-1:path.length;let sharedDirectoryDepth=0,unsharedSegmentStart=0;if(previousPath!=null)if(cachedDirPrefix.length>0&&path.length>cachedDirPrefix.length&&path.startsWith(cachedDirPrefix))sharedDirectoryDepth=cachedDirDepth,unsharedSegmentStart=cachedDirPrefix.length;else{const compareLength=Math.min(endIndex,previousPath.length);let prefixMatched=!0;for(let ci=0;ci<compareLength;ci++){const cc=path.charCodeAt(ci);if(cc!==previousPath.charCodeAt(ci)){prefixMatched=!1;break}cc===47&&(sharedDirectoryDepth++,unsharedSegmentStart=ci+1)}prefixMatched&&hasTrailingSlash&&compareLength===endIndex&&previousPath.length>endIndex&&previousPath.charCodeAt(endIndex)===47&&(sharedDirectoryDepth++,unsharedSegmentStart=endIndex+1)}stackTop=sharedDirectoryDepth,currentDepth=sharedDirectoryDepth;let segmentStart=unsharedSegmentStart,slashPos=path.indexOf("/",segmentStart);for(;slashPos>=0&&slashPos<endIndex;){const parentId=dirStack[stackTop];if(parentId===void 0)throw new Error("Directory stack underflow while building the path store");currentDepth++;const dirSeg=path.slice(segmentStart,slashPos);let dirNameId=idByValue.get(dirSeg);dirNameId===void 0&&(dirNameId=valueById.length,idByValue.set(dirSeg,dirNameId),valueById.push(dirSeg));const nodeId=nodes.length;nodes.push({depthAndFlags:createNodeDepthAndFlags(currentDepth,0,1),nameId:dirNameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),this.recordCreatedDirectoryPath(path.slice(0,slashPos)),stackTop++,dirStack[stackTop]=nodeId,segmentStart=slashPos+1,slashPos=path.indexOf("/",segmentStart)}if(hasTrailingSlash){if(segmentStart<endIndex){const parentId=dirStack[stackTop];if(parentId===void 0)throw new Error(`Unable to resolve directory parent for "${path}"`);currentDepth++;const trailSeg=path.slice(segmentStart,endIndex);let trailNameId=idByValue.get(trailSeg);trailNameId===void 0&&(trailNameId=valueById.length,idByValue.set(trailSeg,trailNameId),valueById.push(trailSeg));const nodeId=nodes.length;nodes.push({depthAndFlags:createNodeDepthAndFlags(currentDepth,0,1),nameId:trailNameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),stackTop++,dirStack[stackTop]=nodeId,segmentStart=endIndex+1}const directoryId=dirStack[stackTop];if(directoryId===void 0)throw new Error(`Unable to resolve directory node for "${path}"`);this.promoteDirectoryToExplicit(directoryId,path)}else{const parentId=dirStack[stackTop];if(parentId===void 0)throw new Error(`Unable to resolve file parent for "${path}"`);const fileSeg=path.slice(segmentStart);let fileNameId=idByValue.get(fileSeg);fileNameId===void 0&&(fileNameId=valueById.length,idByValue.set(fileSeg,fileNameId),valueById.push(fileSeg)),nodes.push({depthAndFlags:createNodeDepthAndFlags(currentDepth+1,0),nameId:fileNameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1})}segmentStart!==cachedDirPrefix.length&&(cachedDirPrefix=path.substring(0,segmentStart),cachedDirDepth=currentDepth),previousPath=path}dirStack.length=stackTop+1,previousPath!=null&&(this.lastPreparedPath=parseInputPath(previousPath)),this.hasDeferredDirectoryIndexes=!0}),this}appendPresortedFilePaths(paths){let previousPath=null,currentDepth=0;const nodes=this.nodes,segmentTable=this.segmentTable,idByValue=segmentTable.idByValue,valueById=segmentTable.valueById,dirStack=this.directoryStack;let stackTop=0,cachedDirPrefix="",cachedDirDepth=0;for(const path of paths){if(previousPath===path)throw new Error(`Duplicate path: "${path}"`);const endIndex=path.length;let sharedDirectoryDepth=0,unsharedSegmentStart=0;if(previousPath!=null)if(cachedDirPrefix.length>0&&path.length>cachedDirPrefix.length&&path.startsWith(cachedDirPrefix))sharedDirectoryDepth=cachedDirDepth,unsharedSegmentStart=cachedDirPrefix.length;else{const compareLength=Math.min(endIndex,previousPath.length);for(let ci=0;ci<compareLength;ci++){const cc=path.charCodeAt(ci);if(cc!==previousPath.charCodeAt(ci))break;cc===47&&(sharedDirectoryDepth++,unsharedSegmentStart=ci+1)}}stackTop=sharedDirectoryDepth,currentDepth=sharedDirectoryDepth;let segmentStart=unsharedSegmentStart,slashPos=path.indexOf("/",segmentStart);for(;slashPos>=0;){const parentId2=dirStack[stackTop];if(parentId2===void 0)throw new Error("Directory stack underflow while building the path store");currentDepth++;const dirSeg=path.slice(segmentStart,slashPos);let dirNameId=idByValue.get(dirSeg);dirNameId===void 0&&(dirNameId=valueById.length,idByValue.set(dirSeg,dirNameId),valueById.push(dirSeg));const nodeId=nodes.length;nodes.push({depthAndFlags:createNodeDepthAndFlags(currentDepth,0,1),nameId:dirNameId,parentId:parentId2,subtreeNodeCount:1,visibleSubtreeCount:1}),this.recordCreatedDirectoryPath(path.slice(0,slashPos)),this.presortedDirectoryNodeIds.push(nodeId),stackTop++,dirStack[stackTop]=nodeId,segmentStart=slashPos+1,slashPos=path.indexOf("/",segmentStart)}const parentId=dirStack[stackTop];if(parentId===void 0)throw new Error(`Unable to resolve file parent for "${path}"`);const fileSeg=path.slice(segmentStart);let fileNameId=idByValue.get(fileSeg);fileNameId===void 0&&(fileNameId=valueById.length,idByValue.set(fileSeg,fileNameId),valueById.push(fileSeg)),nodes.push({depthAndFlags:createNodeDepthAndFlags(currentDepth+1,0),nameId:fileNameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),segmentStart!==cachedDirPrefix.length&&(cachedDirPrefix=path.substring(0,segmentStart),cachedDirDepth=currentDepth),previousPath=path}dirStack.length=stackTop+1,previousPath!=null&&(this.lastPreparedPath=parseInputPath(previousPath)),this.hasDeferredDirectoryIndexes=!0}finish(options={}){const skipSubtreeCountPass=options.skipSubtreeCountPass===!0;return this.hasDeferredDirectoryIndexes?(withBenchmarkPhase(this.instrumentation,"store.builder.buildDirectoryIndexes",()=>this.buildPresortedFinish(skipSubtreeCountPass)),this.hasDeferredDirectoryIndexes=!1):skipSubtreeCountPass||withBenchmarkPhase(this.instrumentation,"store.builder.computeSubtreeCounts",()=>this.computeSubtreeCounts(0)),{directories:this.directories,nodes:this.nodes,options:this.options,rootId:0,segmentTable:this.segmentTable,presortedDirectoryNodeIds:this.presortedDirectoryNodeIds.length>0?this.presortedDirectoryNodeIds:null}}didMatchAllInitialExpandedPaths(){return this.createdDirectoriesAllExpanded&&this.initialExpandedPathSet!=null&&this.createdDirectoryCount===this.initialExpandedPathSet.size}appendPreparedPath(preparedPath,validateOrder){if(this.hasDeferredDirectoryIndexes&&(this.buildDirectoryIndexes(),this.hasDeferredDirectoryIndexes=!1),this.lastPreparedPath!=null){if(preparedPath.path===this.lastPreparedPath.path)throw new Error(`Duplicate path: "${preparedPath.path}"`);if(validateOrder&&(this.options.sort==="default"?comparePreparedPathsWithCachedSortKeys(this.lastPreparedPath,preparedPath,this.segmentSortKeyCache):compareWithSortOption(this.lastPreparedPath,preparedPath,this.options.sort))>0)throw new Error(`Builder input must be sorted before appendPaths(): "${preparedPath.path}"`)}const previousPath=this.lastPreparedPath,currentDirectoryDepth=getDirectoryDepth(preparedPath),previousDirectoryDepth=previousPath==null?0:getDirectoryDepth(previousPath),sharedPrefixLength=previousPath==null?0:computeSharedPrefixLength(previousPath.segments,preparedPath.segments),sharedDirectoryDepth=Math.min(sharedPrefixLength,currentDirectoryDepth,previousDirectoryDepth);this.directoryStack.length=sharedDirectoryDepth+1;for(let segmentIndex=sharedDirectoryDepth;segmentIndex<currentDirectoryDepth;segmentIndex++){const parentId2=this.directoryStack[this.directoryStack.length-1];if(parentId2===void 0)throw new Error("Directory stack underflow while building the path store");const childId=validateOrder?this.getOrCreateDirectoryChild(parentId2,preparedPath.segments[segmentIndex]):this.createDirectoryChild(parentId2,preparedPath.segments[segmentIndex]);this.directoryStack.push(childId)}if(preparedPath.isDirectory){const directoryId=this.directoryStack[this.directoryStack.length-1];if(directoryId===void 0)throw new Error(`Unable to resolve directory node for "${preparedPath.path}"`);this.promoteDirectoryToExplicit(directoryId,preparedPath.path),this.lastPreparedPath=preparedPath;return}const parentId=this.directoryStack[this.directoryStack.length-1];if(parentId===void 0)throw new Error(`Unable to resolve file parent for "${preparedPath.path}"`);validateOrder?this.createFileChild(parentId,preparedPath.basename,preparedPath.path):this.createFileChildUnchecked(parentId,preparedPath.basename),this.lastPreparedPath=preparedPath}recordCreatedDirectoryPath(path){!this.createdDirectoriesAllExpanded||this.initialExpandedPathSet==null||(this.createdDirectoryCount+=1,this.initialExpandedPathSet.has(path)||(this.createdDirectoriesAllExpanded=!1))}createFileChild(parentId,basename,path){const nameId=internSegment(this.segmentTable,basename),parentIndex=this.getDirectoryIndex(parentId),nameMap=parentIndex.childIdByNameId;if(nameMap!=null&&nameMap.get(nameId)!==void 0)throw new Error(`Path collides with an existing entry: "${path}"`);const parentNode=this.nodes[parentId];if(parentNode===void 0)throw new Error(`Unknown parent node ID: ${String(parentId)}`);const nodeId=this.nodes.length;return this.nodes.push({depthAndFlags:createNodeDepthAndFlags(getNodeDepth(parentNode)+1,0),nameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),nameMap?.set(nameId,nodeId),appendChildReference(parentIndex,nodeId),nodeId}createFileChildUnchecked(parentId,basename){const nameId=internSegment(this.segmentTable,basename),parentIndex=this.getDirectoryIndex(parentId),parentNode=this.nodes[parentId];if(parentNode===void 0)throw new Error(`Unknown parent node ID: ${String(parentId)}`);const nodeId=this.nodes.length;return this.nodes.push({depthAndFlags:createNodeDepthAndFlags(getNodeDepth(parentNode)+1,0),nameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),parentIndex.childIdByNameId!=null&&parentIndex.childIdByNameId.set(nameId,nodeId),appendChildReference(parentIndex,nodeId),nodeId}getOrCreateDirectoryChild(parentId,segment){const nameId=internSegment(this.segmentTable,segment),parentIndex=this.getDirectoryIndex(parentId);if(parentIndex.childIdByNameId!=null){const existingChildId=parentIndex.childIdByNameId.get(nameId);if(existingChildId!==void 0){const existingNode=this.nodes[existingChildId];if(existingNode!=null&&!isDirectoryNode(existingNode))throw new Error(`Path collides with an existing file while creating directory "${segment}"`);return existingChildId}}const parentNode=this.nodes[parentId];if(parentNode===void 0)throw new Error(`Unknown parent node ID: ${String(parentId)}`);const nodeId=this.nodes.length;return this.nodes.push({depthAndFlags:createNodeDepthAndFlags(getNodeDepth(parentNode)+1,0,1),nameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),parentIndex.childIdByNameId!=null&&parentIndex.childIdByNameId.set(nameId,nodeId),appendChildReference(parentIndex,nodeId),this.directories.set(nodeId,createDirectoryChildIndex()),nodeId}createDirectoryChild(parentId,segment){const nameId=internSegment(this.segmentTable,segment),parentIndex=this.getDirectoryIndex(parentId),parentNode=this.nodes[parentId];if(parentNode===void 0)throw new Error(`Unknown parent node ID: ${String(parentId)}`);const nodeId=this.nodes.length;return this.nodes.push({depthAndFlags:createNodeDepthAndFlags(getNodeDepth(parentNode)+1,0,1),nameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),parentIndex.childIdByNameId!=null&&parentIndex.childIdByNameId.set(nameId,nodeId),appendChildReference(parentIndex,nodeId),this.directories.set(nodeId,createDirectoryChildIndex()),nodeId}promoteDirectoryToExplicit(directoryId,path){const directoryNode=this.nodes[directoryId];if(directoryNode===void 0)throw new Error(`Unknown directory node ID: ${String(directoryId)}`);if(!isDirectoryNode(directoryNode))throw new Error(`Path is not a directory: "${path}"`);if(hasNodeFlag(directoryNode,1))throw new Error(`Duplicate path: "${path}"`);addNodeFlag(directoryNode,1)}getDirectoryIndex(directoryId){const existingIndex=this.directories.get(directoryId);if(existingIndex!==void 0)return existingIndex;throw new Error(`Unknown directory child index for node ${String(directoryId)}`)}buildPresortedFinish(skipSubtreeCountPass){const nodes=this.nodes,directories=this.directories;directories.set(0,createPresortedDirectoryChildIndex());let cachedParentId=-1,cachedParentIndex=null;for(let nodeId=1;nodeId<nodes.length;nodeId++){const node=nodes[nodeId];if(node==null)continue;if(isDirectoryNode(node)){const dirIndex=createPresortedDirectoryChildIndex();directories.set(nodeId,dirIndex),cachedParentId=nodeId,cachedParentIndex=dirIndex}let parentIndex;node.parentId===cachedParentId?parentIndex=cachedParentIndex:(parentIndex=directories.get(node.parentId),cachedParentId=node.parentId,cachedParentIndex=parentIndex??null),parentIndex?.childIds.push(nodeId)}if(!skipSubtreeCountPass)for(let nodeId=nodes.length-1;nodeId>=1;nodeId--){const node=nodes[nodeId];if(node==null)continue;const parentNode=nodes[node.parentId];parentNode!=null&&(parentNode.subtreeNodeCount+=node.subtreeNodeCount,parentNode.visibleSubtreeCount+=node.visibleSubtreeCount)}}buildDirectoryIndexes(){const nodes=this.nodes;for(let nodeId=1;nodeId<nodes.length;nodeId++){const node=nodes[nodeId];if(node==null)continue;isDirectoryNode(node)&&this.directories.set(nodeId,createDirectoryChildIndex());const parentIndex=this.directories.get(node.parentId);parentIndex!=null&&(parentIndex.childIdByNameId!=null&&parentIndex.childIdByNameId.set(node.nameId,nodeId),appendChildReference(parentIndex,nodeId))}}computeSubtreeCounts(nodeId){const node=this.nodes[nodeId];if(node===void 0)throw new Error(`Unknown node ID: ${String(nodeId)}`);if(!isDirectoryNode(node))return node.subtreeNodeCount=1,node.visibleSubtreeCount=1,1;const directoryIndex=this.getDirectoryIndex(nodeId);let subtreeNodeCount=1;for(const childId of directoryIndex.childIds)subtreeNodeCount+=this.computeSubtreeCounts(childId);return rebuildDirectoryChildAggregates(this.nodes,directoryIndex),node.subtreeNodeCount=subtreeNodeCount,node.visibleSubtreeCount=subtreeNodeCount,subtreeNodeCount}};function createPathStoreState(snapshot,initialExpansion="closed",instrumentation=null){const defaultExpansion=resolveInitialExpansion(initialExpansion);return{activeNodeCount:snapshot.nodes.length-1,collapsedDirectoryIds:new Set,collapseNewDirectoriesByDefault:!1,defaultExpansion,directoriesOpenByDefault:defaultExpansion==="open",hasCollapsedDirectoryOverrides:!1,directoryLoadInfoById:new Map,expandedDirectoryIds:new Set,instrumentation,listeners:new Map,pathCacheByNodeId:new Map([[snapshot.rootId,{path:"",version:0}]]),pathCacheVersion:0,snapshot,transactionStack:[]}}function createTransactionFrame(){return{affectedAncestorIds:new Set,affectedNodeIds:new Set,events:[]}}function resolveInitialExpansion(initialExpansion){if(typeof initialExpansion!="number")return initialExpansion;if(!Number.isInteger(initialExpansion)||initialExpansion<0)throw new Error(`initialExpansion must be "open", "closed", or a non-negative integer depth. Received: ${String(initialExpansion)}`);return initialExpansion}function isDirectoryExpandedByDefault(state,node){return hasNodeFlag(node,2)||state.defaultExpansion==="open"?!0:state.defaultExpansion==="closed"?!1:getNodeDepth(node)<=state.defaultExpansion}function isDirectoryExpanded(state,nodeId,node=state.snapshot.nodes[nodeId]){return node==null||!isDirectoryNode(node)?!1:state.directoriesOpenByDefault&&!state.hasCollapsedDirectoryOverrides?!0:state.collapsedDirectoryIds.has(nodeId)?!1:state.expandedDirectoryIds.has(nodeId)?!0:isDirectoryExpandedByDefault(state,node)}function setDirectoryExpanded(state,nodeId,expanded,node=state.snapshot.nodes[nodeId]){if(node==null||!isDirectoryNode(node))return;const expandedByDefault=isDirectoryExpandedByDefault(state,node);if(expanded){if(expandedByDefault){state.collapsedDirectoryIds.delete(nodeId),state.hasCollapsedDirectoryOverrides=state.collapsedDirectoryIds.size>0;return}state.expandedDirectoryIds.add(nodeId);return}if(expandedByDefault){state.collapsedDirectoryIds.add(nodeId),state.hasCollapsedDirectoryOverrides=!0;return}state.expandedDirectoryIds.delete(nodeId)}function getOrCreateDirectoryLoadInfo(state,nodeId){const existingInfo=state.directoryLoadInfoById.get(nodeId);if(existingInfo!=null)return existingInfo;const nextInfo={activeAttemptId:null,errorMessage:null,nextAttemptId:1,state:"loaded"};return state.directoryLoadInfoById.set(nodeId,nextInfo),nextInfo}function getDirectoryLoadState(state,nodeId){return state.directoryLoadInfoById.get(nodeId)?.state??"loaded"}function beginDirectoryLoad(state,nodeId){const loadInfo=getOrCreateDirectoryLoadInfo(state,nodeId);if(loadInfo.state==="loading"&&loadInfo.activeAttemptId!=null)return{attemptId:loadInfo.activeAttemptId,nodeId,reused:!0};const attemptId=loadInfo.nextAttemptId;return loadInfo.activeAttemptId=attemptId,loadInfo.errorMessage=null,loadInfo.nextAttemptId+=1,loadInfo.state="loading",{attemptId,nodeId,reused:!1}}function markDirectoryUnloadedState(state,nodeId){const loadInfo=getOrCreateDirectoryLoadInfo(state,nodeId);loadInfo.activeAttemptId=null,loadInfo.errorMessage=null,loadInfo.state="unloaded"}function completeDirectoryLoad(state,nodeId,attemptId){const loadInfo=state.directoryLoadInfoById.get(nodeId);return loadInfo==null||loadInfo.activeAttemptId!==attemptId?!1:(loadInfo.activeAttemptId=null,loadInfo.errorMessage=null,loadInfo.state="loaded",!0)}function isDirectoryLoadAttemptCurrent(state,nodeId,attemptId){return state.directoryLoadInfoById.get(nodeId)?.activeAttemptId===attemptId}function failDirectoryLoad(state,nodeId,attemptId,errorMessage){const loadInfo=state.directoryLoadInfoById.get(nodeId);return loadInfo==null||loadInfo.activeAttemptId!==attemptId?!1:(loadInfo.activeAttemptId=null,loadInfo.errorMessage=errorMessage??null,loadInfo.state="error",!0)}function clearDirectoryLoadInfo(state,nodeId){state.directoryLoadInfoById.delete(nodeId)}function subscribe(state,type,handler){const rawHandler=handler,existingListeners=state.listeners.get(type);return existingListeners!=null?existingListeners.add(rawHandler):state.listeners.set(type,new Set([rawHandler])),()=>{const listeners=state.listeners.get(type);listeners!=null&&(listeners.delete(rawHandler),listeners.size===0&&state.listeners.delete(type))}}function createAddEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],canonicalChanged:!0,operation:"add",path:args.path,projectionChanged:args.projectionChanged,visibleCountDelta:null}}function createRemoveEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],canonicalChanged:!0,operation:"remove",path:args.path,projectionChanged:args.projectionChanged,recursive:args.recursive,visibleCountDelta:null}}function createMoveEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],canonicalChanged:!0,from:args.from,operation:"move",projectionChanged:args.projectionChanged,to:args.to,visibleCountDelta:null}}function createExpandEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],canonicalChanged:!1,operation:"expand",path:args.path,projectionChanged:!0,visibleCountDelta:null}}function createCollapseEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],canonicalChanged:!1,operation:"collapse",path:args.path,projectionChanged:!0,visibleCountDelta:null}}function createMarkDirectoryUnloadedEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],canonicalChanged:!1,operation:"mark-directory-unloaded",path:args.path,projectionChanged:args.projectionChanged,visibleCountDelta:null}}function createBeginChildLoadEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],attemptId:args.attemptId,canonicalChanged:!1,operation:"begin-child-load",path:args.path,projectionChanged:args.projectionChanged,reused:args.reused,visibleCountDelta:null}}function createApplyChildPatchEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],attemptId:args.attemptId,canonicalChanged:args.childEvents.some(event=>event.canonicalChanged),childEvents:args.childEvents,operation:"apply-child-patch",path:args.path,projectionChanged:args.projectionChanged,visibleCountDelta:null}}function createCompleteChildLoadEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],attemptId:args.attemptId,canonicalChanged:!1,operation:"complete-child-load",path:args.path,projectionChanged:args.projectionChanged,stale:args.stale,visibleCountDelta:null}}function createFailChildLoadEvent(args){return{affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],attemptId:args.attemptId,canonicalChanged:!1,errorMessage:args.errorMessage,operation:"fail-child-load",path:args.path,projectionChanged:args.projectionChanged,stale:args.stale,visibleCountDelta:null}}function createCleanupEvent(args){return{activeNodeCountAfter:args.activeNodeCountAfter,activeNodeCountBefore:args.activeNodeCountBefore,affectedAncestorIds:args.affectedAncestorIds??[],affectedNodeIds:args.affectedNodeIds??[],cachedPathEntryCountAfter:args.cachedPathEntryCountAfter,cachedPathEntryCountBefore:args.cachedPathEntryCountBefore,canonicalChanged:!1,idsPreserved:args.idsPreserved,loadInfoEntryCountAfter:args.loadInfoEntryCountAfter,loadInfoEntryCountBefore:args.loadInfoEntryCountBefore,mode:args.mode,operation:"cleanup",projectionChanged:args.projectionChanged,reclaimedCachedPathEntryCount:args.reclaimedCachedPathEntryCount,reclaimedLoadInfoEntryCount:args.reclaimedLoadInfoEntryCount,reclaimedNodeSlotCount:args.reclaimedNodeSlotCount,reclaimedSegmentCount:args.reclaimedSegmentCount,segmentCountAfter:args.segmentCountAfter,segmentCountBefore:args.segmentCountBefore,totalNodeSlotCountAfter:args.totalNodeSlotCountAfter,totalNodeSlotCountBefore:args.totalNodeSlotCountBefore,visibleCountDelta:null}}function finalizeEvent(state,previousVisibleCount,event){return{...event,visibleCountDelta:getCurrentVisibleCount(state)-previousVisibleCount}}function batchEvents(state,run){const previousVisibleCount=getCurrentVisibleCount(state),frame=createTransactionFrame();state.transactionStack.push(frame);try{run()}catch(error){throw finishTransaction(state,frame,!1),error}finishTransaction(state,frame,!0,getCurrentVisibleCount(state)-previousVisibleCount)}function recordEvent(state,event){const instrumentation=state.instrumentation;if(instrumentation==null){recordEventNow(state,event);return}withBenchmarkPhase(instrumentation,"store.events.record",()=>recordEventNow(state,event))}function recordEventNow(state,event){const currentFrame=state.transactionStack[state.transactionStack.length-1]??null;if(currentFrame==null){emitEvent(state,event);return}currentFrame.events.push(event),mergeEventMetadataIntoFrame(currentFrame,event)}function finishTransaction(state,frame,emit,visibleCountDelta=null){if(state.transactionStack.pop()!==frame)throw new Error("Transaction stack underflow");if(!emit)return;const parentFrame=state.transactionStack[state.transactionStack.length-1]??null;if(parentFrame!=null){const instrumentation2=state.instrumentation;instrumentation2==null?mergeBatchFrameIntoParent(parentFrame,frame):withBenchmarkPhase(instrumentation2,"store.events.batch.merge",()=>mergeBatchFrameIntoParent(parentFrame,frame));return}const batchEvent=createBatchEvent(frame,visibleCountDelta),instrumentation=state.instrumentation;if(instrumentation==null){emitEvent(state,batchEvent);return}withBenchmarkPhase(instrumentation,"store.events.batch.commit",()=>emitEvent(state,batchEvent))}function createBatchEvent(frame,visibleCountDelta){return{affectedAncestorIds:[...frame.affectedAncestorIds],affectedNodeIds:[...frame.affectedNodeIds],canonicalChanged:frame.events.some(event=>event.canonicalChanged),events:[...frame.events],operation:"batch",projectionChanged:frame.events.some(event=>event.projectionChanged),visibleCountDelta}}function mergeFrameMetadata(target,source){for(const nodeId of source.affectedAncestorIds)target.affectedAncestorIds.add(nodeId);for(const nodeId of source.affectedNodeIds)target.affectedNodeIds.add(nodeId)}function mergeBatchFrameIntoParent(parentFrame,frame){for(const event of frame.events)parentFrame.events.push(event);mergeFrameMetadata(parentFrame,frame)}function mergeEventMetadataIntoFrame(frame,event){for(const nodeId of event.affectedNodeIds)frame.affectedNodeIds.add(nodeId);for(const nodeId of event.affectedAncestorIds)frame.affectedAncestorIds.add(nodeId)}function emitEvent(state,event){const instrumentation=state.instrumentation;if(instrumentation==null){emitEventNow(state,event);return}withBenchmarkPhase(instrumentation,"store.events.emit",()=>emitEventNow(state,event))}function emitEventNow(state,event){state.listeners.get(event.operation)?.forEach(handler=>handler(event)),state.listeners.get("*")?.forEach(handler=>handler(event))}function getCurrentVisibleCount(state){return state.snapshot.nodes[state.snapshot.rootId]?.visibleSubtreeCount??0}function getFlattenedChildDirectoryId(state,directoryNodeId){if(state.snapshot.options.flattenEmptyDirectories!==!0)return null;const directoryNode=state.snapshot.nodes[directoryNodeId];if(directoryNode==null||!isDirectoryNode(directoryNode)||hasNodeFlag(directoryNode,2))return null;const directoryIndex=state.snapshot.directories.get(directoryNodeId);if(directoryIndex==null||directoryIndex.childIds.length!==1)return null;const childId=directoryIndex.childIds[0];if(childId==null)return null;const childNode=state.snapshot.nodes[childId];return childNode==null||!isDirectoryNode(childNode)?null:childId}function getFlattenedTerminalDirectoryId(state,directoryNodeId){let currentDirectoryId=directoryNodeId;for(;;){const nextDirectoryId=getFlattenedChildDirectoryId(state,currentDirectoryId);if(nextDirectoryId==null)return currentDirectoryId;currentDirectoryId=nextDirectoryId}}function collectFlattenedDirectoryChainIds(state,directoryNodeId){const chainIds=[directoryNodeId];let currentDirectoryId=directoryNodeId;for(;;){const nextDirectoryId=getFlattenedChildDirectoryId(state,currentDirectoryId);if(nextDirectoryId==null)return chainIds;chainIds.push(nextDirectoryId),currentDirectoryId=nextDirectoryId}}function listPaths(state,path){const nodeId=path==null?state.snapshot.rootId:findNodeId(state,path);return nodeId==null?[]:collectCanonicalEntries(state,nodeId)}function addPath(state,path){const preparedPath=parseInputPath(path),parentSegments=preparedPath.isDirectory?preparedPath.segments:preparedPath.segments.slice(0,-1),previousProjectionSignature=getCollapsedProjectionSignature(state,findDeepestExistingDirectoryId(state,parentSegments)),{createdNodeIds,directoryId}=ensureDirectoryChain(state,parentSegments),affectedNodeIds=new Set(createdNodeIds);let addedNodeId=directoryId;if(preparedPath.isDirectory){const directoryNode=requireNode(state,directoryId);if(hasNodeFlag(directoryNode,1))throw new Error(`Path already exists: "${path}"`);addNodeFlag(directoryNode,1),state.pathCacheByNodeId.set(directoryId,{path,version:state.pathCacheVersion}),affectedNodeIds.add(directoryId)}else addedNodeId=createFileNode(state,directoryId,preparedPath.basename),affectedNodeIds.add(addedNodeId);recomputeCountsUpwardFrom(state,directoryId);const nextProjectionSignature=getCollapsedProjectionSignature(state,directoryId);return createAddEvent({affectedAncestorIds:collectAncestorIds(state,addedNodeId),affectedNodeIds:[...affectedNodeIds],path,projectionChanged:didProjectionChange(previousProjectionSignature,nextProjectionSignature)})}function removePath(state,path,options){const nodeId=findNodeId(state,path);if(nodeId==null)throw new Error(`Path does not exist: "${path}"`);const node=requireNode(state,nodeId);if(hasNodeFlag(node,2))throw new Error("The root node cannot be removed");if(isDirectoryNode(node)&&getDirectoryIndex(state,nodeId).childIds.length>0&&options.recursive!==!0)throw new Error(`Cannot remove a non-empty directory without recursive: "${path}"`);const parentId=node.parentId,previousProjectionSignature=getCollapsedProjectionSignature(state,parentId),removedNodeIds=removeSubtree(state,nodeId);removeChildReference(state,parentId,nodeId,node.nameId),promoteEmptyAncestorsToExplicit(state,parentId),recomputeCountsUpwardFrom(state,parentId);const nextProjectionSignature=getCollapsedProjectionSignature(state,parentId);return createRemoveEvent({affectedAncestorIds:collectAncestorIds(state,parentId),affectedNodeIds:removedNodeIds,path,projectionChanged:didProjectionChange(previousProjectionSignature,nextProjectionSignature),recursive:options.recursive===!0})}function movePath(state,fromPath,toPath,options){const sourceNodeId=findNodeId(state,fromPath);if(sourceNodeId==null)throw new Error(`Source path does not exist: "${fromPath}"`);const sourceNode=requireNode(state,sourceNodeId);if(hasNodeFlag(sourceNode,2))throw new Error("The root node cannot be moved");const collision=options.collision??"error",moveTarget=resolveMoveTarget(state,sourceNodeId,toPath),previousSourceProjectionSignature=getCollapsedProjectionSignature(state,sourceNode.parentId),previousTargetProjectionSignature=getCollapsedProjectionSignature(state,moveTarget.parentId),sourceName=getSegmentValue(state.snapshot.segmentTable,sourceNode.nameId),targetNameId=internSegment(state.snapshot.segmentTable,moveTarget.basename);if(moveTarget.parentId===sourceNode.parentId&&sourceName===moveTarget.basename)return null;if(isDirectoryNode(sourceNode)&&isAncestor(state,sourceNodeId,moveTarget.parentId))throw new Error("Cannot move a directory into one of its descendants");const siblingCollisionId=ensureChildIdByNameId(state.snapshot.nodes,getDirectoryIndex(state,moveTarget.parentId)).get(targetNameId),collisionNodeId=moveTarget.existingNodeId??siblingCollisionId??null;if(collisionNodeId!=null&&collisionNodeId!==sourceNodeId&&handleMoveCollision(state,collisionNodeId,collision,getNodeKind(sourceNode))==="skip")return null;const previousParentId=sourceNode.parentId;removeChildReference(state,previousParentId,sourceNodeId,sourceNode.nameId),sourceNode.parentId=moveTarget.parentId,sourceNode.nameId=targetNameId,state.pathCacheByNodeId.delete(sourceNodeId),recomputeDepths(state,sourceNodeId),insertChildReference(state,moveTarget.parentId,sourceNodeId),promoteEmptyAncestorsToExplicit(state,previousParentId),state.pathCacheVersion++,recomputeCountsUpwardFrom(state,previousParentId),moveTarget.parentId!==previousParentId&&recomputeCountsUpwardFrom(state,moveTarget.parentId);const nextSourceProjectionSignature=getCollapsedProjectionSignature(state,previousParentId),nextTargetProjectionSignature=getCollapsedProjectionSignature(state,moveTarget.parentId);return createMoveEvent({affectedAncestorIds:[...new Set([...collectAncestorIds(state,previousParentId),...collectAncestorIds(state,moveTarget.parentId)])],affectedNodeIds:[sourceNodeId],from:fromPath,projectionChanged:didAnyProjectionChange([previousSourceProjectionSignature,previousTargetProjectionSignature],[nextSourceProjectionSignature,nextTargetProjectionSignature]),to:materializeNodePath(state,sourceNodeId)})}function getCachedNodePath(state,nodeId){const cachedEntry=state.pathCacheByNodeId.get(nodeId);return cachedEntry!=null&&cachedEntry.version===state.pathCacheVersion?cachedEntry.path:null}function setCachedNodePath(state,nodeId,path){return state.pathCacheByNodeId.set(nodeId,{path,version:state.pathCacheVersion}),path}function materializeNodePath(state,nodeId){const node=requireNode(state,nodeId),cachedPath=getCachedNodePath(state,nodeId);if(cachedPath!=null)return cachedPath;if(hasNodeFlag(node,2))return setCachedNodePath(state,nodeId,"");const parentPath=materializeNodePath(state,node.parentId),nodeName=getSegmentValue(state.snapshot.segmentTable,node.nameId),path=parentPath.length===0?nodeName:`${parentPath}${nodeName}`;return setCachedNodePath(state,nodeId,isDirectoryNode(node)?`${path}/`:path)}function recomputeCountsUpwardFrom(state,startNodeId){const instrumentation=state.instrumentation;if(instrumentation==null){recomputeCountsUpwardFromNow(state,startNodeId);return}withBenchmarkPhase(instrumentation,"store.recomputeCountsUpwardFrom",()=>recomputeCountsUpwardFromNow(state,startNodeId))}function recomputeCountsRecursive(state,nodeId){const stack=[[nodeId,0]],{nodes,directories}=state.snapshot;for(;stack.length>0;){const frame=stack[stack.length-1],nid=frame[0],node=nodes[nid];if(node==null||!isDirectoryNode(node)){recomputeNodeCounts(state,nid,node,!0),stack.pop();continue}const dirIndex=directories.get(nid);if(dirIndex==null||frame[1]>=dirIndex.childIds.length){recomputeNodeCounts(state,nid,node,!0),stack.pop();continue}const childId=dirIndex.childIds[frame[1]++];stack.push([childId,0])}}function collectAncestorIds(state,nodeId){const ancestorIds=[];let currentNodeId=nodeId;for(;currentNodeId!=null;){const currentNode=requireNode(state,currentNodeId);if(ancestorIds.push(currentNodeId),currentNodeId===state.snapshot.rootId)break;currentNodeId=currentNode.parentId}return ancestorIds}function findNodeId(state,path){if(path.length===0)return state.snapshot.rootId;const lookupPath=parseLookupPath(path);return findNodeIdBySegments(state,lookupPath.segments,lookupPath.requiresDirectory)}function findNodeIdBySegments(state,segments,requireDirectory){let currentNodeId=state.snapshot.rootId;for(const segment of segments){const segmentId=state.snapshot.segmentTable.idByValue.get(segment);if(segmentId===void 0)return null;const currentIndex=getDirectoryIndex(state,currentNodeId),nextNodeId=ensureChildIdByNameId(state.snapshot.nodes,currentIndex).get(segmentId);if(nextNodeId===void 0)return null;currentNodeId=nextNodeId}const currentNode=requireNode(state,currentNodeId);return requireDirectory&&!isDirectoryNode(currentNode)?null:currentNodeId}function getDirectoryIndex(state,directoryId){const directoryIndex=state.snapshot.directories.get(directoryId);if(directoryIndex===void 0)throw new Error(`Unknown directory child index for node ${String(directoryId)}`);return directoryIndex}function requireNode(state,nodeId){const node=state.snapshot.nodes[nodeId];if(node===void 0||hasNodeFlag(node,4))throw new Error(`Unknown node ID: ${String(nodeId)}`);return node}function collectCanonicalEntries(state,nodeId){const rootNode=state.snapshot.nodes[nodeId];if(rootNode===void 0||hasNodeFlag(rootNode,4))return[];if(!isDirectoryNode(rootNode))return[materializeNodePath(state,nodeId)];if(getDirectoryIndex(state,nodeId).childIds.length===0)return hasNodeFlag(rootNode,1)&&!hasNodeFlag(rootNode,2)?[materializeNodePath(state,nodeId)]:[];const entries=[],stack=[{childIndex:0,nodeId}];for(;stack.length>0;){const frame=stack[stack.length-1];if(frame==null)break;const currentNode=state.snapshot.nodes[frame.nodeId];if(currentNode===void 0||hasNodeFlag(currentNode,4)){stack.pop();continue}if(!isDirectoryNode(currentNode)){entries.push(materializeNodePath(state,frame.nodeId)),stack.pop();continue}const currentIndex=getDirectoryIndex(state,frame.nodeId);if(currentIndex.childIds.length===0){hasNodeFlag(currentNode,1)&&!hasNodeFlag(currentNode,2)&&entries.push(materializeNodePath(state,frame.nodeId)),stack.pop();continue}const nextChildId=currentIndex.childIds[frame.childIndex];if(nextChildId==null){stack.pop();continue}frame.childIndex++,stack.push({childIndex:0,nodeId:nextChildId})}return entries}function ensureDirectoryChain(state,directorySegments){const createdNodeIds=[];let currentDirectoryId=state.snapshot.rootId;for(const segment of directorySegments){const segmentId=internSegment(state.snapshot.segmentTable,segment),currentIndex=getDirectoryIndex(state,currentDirectoryId),existingChildId=ensureChildIdByNameId(state.snapshot.nodes,currentIndex).get(segmentId);if(existingChildId!==void 0){if(!isDirectoryNode(requireNode(state,existingChildId)))throw new Error(`Cannot create a directory that collides with an existing file: "${segment}"`);currentDirectoryId=existingChildId;continue}currentDirectoryId=createDirectoryNode(state,currentDirectoryId,segmentId),createdNodeIds.push(currentDirectoryId)}return{createdNodeIds,directoryId:currentDirectoryId}}function createDirectoryNode(state,parentId,nameId){const parentNode=requireNode(state,parentId),nodeId=state.snapshot.nodes.length;return state.snapshot.nodes.push({depthAndFlags:createNodeDepthAndFlags(getNodeDepth(parentNode)+1,0,1),nameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),state.snapshot.directories.set(nodeId,createDirectoryChildIndex()),insertChildReference(state,parentId,nodeId),state.collapseNewDirectoriesByDefault&&(state.collapsedDirectoryIds.add(nodeId),state.hasCollapsedDirectoryOverrides=!0),state.activeNodeCount++,nodeId}function createFileNode(state,parentId,basename){const nameId=internSegment(state.snapshot.segmentTable,basename),parentIndex=getDirectoryIndex(state,parentId);if(ensureChildIdByNameId(state.snapshot.nodes,parentIndex).has(nameId))throw new Error(`Path already exists: "${buildPathPreview(state,parentId,basename)}"`);const parentNode=requireNode(state,parentId),nodeId=state.snapshot.nodes.length;return state.snapshot.nodes.push({depthAndFlags:createNodeDepthAndFlags(getNodeDepth(parentNode)+1,0),nameId,parentId,subtreeNodeCount:1,visibleSubtreeCount:1}),insertChildReference(state,parentId,nodeId),state.activeNodeCount++,nodeId}function findChildInsertIndex(state,parentIndex,childId){let low=0,high=parentIndex.childIds.length;for(;low<high;){const middle=low+high>>>1,existingChildId=parentIndex.childIds[middle];if(existingChildId==null){high=middle;continue}compareSiblingNodes(state,childId,existingChildId)<0?high=middle:low=middle+1}return low}function insertChildReference(state,parentId,childId){const parentIndex=getDirectoryIndex(state,parentId),childNode=requireNode(state,childId);ensureChildIdByNameId(state.snapshot.nodes,parentIndex).set(childNode.nameId,childId),applyChildAggregateDelta(parentIndex,childId,childNode.subtreeNodeCount,childNode.visibleSubtreeCount);const insertIndex=findChildInsertIndex(state,parentIndex,childId);parentIndex.childIds.splice(insertIndex,0,childId),updateChildPositionsFrom(parentIndex,insertIndex),rebuildVisibleChildChunks(state.snapshot.nodes,parentIndex)}function removeChildReference(state,parentId,childId,childNameId){const parentIndex=getDirectoryIndex(state,parentId),positions=ensureChildPositions(parentIndex),childIndex=positions.get(childId)??-1;ensureChildIdByNameId(state.snapshot.nodes,parentIndex).delete(childNameId),positions.delete(childId);const childNode=state.snapshot.nodes[childId];childNode!=null&&applyChildAggregateDelta(parentIndex,childId,-childNode.subtreeNodeCount,-childNode.visibleSubtreeCount),childIndex>=0&&(parentIndex.childIds.splice(childIndex,1),updateChildPositionsFrom(parentIndex,childIndex),rebuildVisibleChildChunks(state.snapshot.nodes,parentIndex))}function compareSiblingNodes(state,leftId,rightId){const sortOption=state.snapshot.options.sort;return sortOption==="default"?compareSiblingNodesDefault(state,leftId,rightId):sortOption(createCompareEntry(state,leftId),createCompareEntry(state,rightId))}function compareSiblingNodesDefault(state,leftId,rightId){const leftNode=requireNode(state,leftId),rightNode=requireNode(state,rightId),leftIsDirectory=isDirectoryNode(leftNode);if(leftIsDirectory!==isDirectoryNode(rightNode))return leftIsDirectory?-1:1;const comparison=compareSegmentSortKeys(getSegmentSortKey(state.snapshot.segmentTable,leftNode.nameId),getSegmentSortKey(state.snapshot.segmentTable,rightNode.nameId));if(comparison!==0)return comparison;const leftName=getSegmentValue(state.snapshot.segmentTable,leftNode.nameId),rightName=getSegmentValue(state.snapshot.segmentTable,rightNode.nameId);return leftName!==rightName?leftName<rightName?-1:1:leftId<rightId?-1:1}function createCompareEntry(state,nodeId){const node=requireNode(state,nodeId),path=materializeNodePath(state,nodeId),isDirectory=isDirectoryNode(node),normalizedPath=isDirectory?path.slice(0,-1):path;return{basename:getSegmentValue(state.snapshot.segmentTable,node.nameId),depth:getNodeDepth(node),isDirectory,path,segments:normalizedPath.length===0?[]:normalizedPath.split("/")}}function resolveMoveTarget(state,sourceNodeId,toPath){const sourceNode=requireNode(state,sourceNodeId),existingDestinationId=findNodeId(state,toPath);if(existingDestinationId!=null){const existingDestination=requireNode(state,existingDestinationId);if(isDirectoryNode(existingDestination))return{basename:getSegmentValue(state.snapshot.segmentTable,sourceNode.nameId),existingNodeId:null,parentId:existingDestinationId};const destinationSegments=parseLookupPath(toPath).segments;return{basename:destinationSegments[destinationSegments.length-1]??"",existingNodeId:existingDestinationId,parentId:existingDestination.parentId}}const destinationLookup=parseLookupPath(toPath),basename=destinationLookup.segments[destinationLookup.segments.length-1]??"",parentSegments=destinationLookup.segments.slice(0,-1),parentId=parentSegments.length===0?state.snapshot.rootId:findNodeIdBySegments(state,parentSegments,!0);if(parentId==null)throw new Error(`Destination parent does not exist: "${toPath}"`);return{basename,existingNodeId:null,parentId}}function handleMoveCollision(state,collisionNodeId,strategy,sourceKind){if(strategy==="skip")return"skip";if(strategy==="error")throw new Error(`Destination already exists: "${materializeNodePath(state,collisionNodeId)}"`);const collisionNode=requireNode(state,collisionNodeId);if(getNodeKind(collisionNode)!==sourceKind)throw new Error("replace collision requires the same source and destination kinds");if(isDirectoryNode(collisionNode)&&getDirectoryIndex(state,collisionNodeId).childIds.length>0)throw new Error("replace collision does not support non-empty directories");const collisionParentId=collisionNode.parentId,collisionNameId=collisionNode.nameId;return removeSubtree(state,collisionNodeId),removeChildReference(state,collisionParentId,collisionNodeId,collisionNameId),promoteEmptyAncestorsToExplicit(state,collisionParentId),recomputeCountsUpwardFrom(state,collisionParentId),"handled"}function removeSubtree(state,nodeId){const removedNodeIds=[],stack=[{nodeId,visitedChildren:!1}];for(;stack.length>0;){const frame=stack.pop();if(frame==null)break;const node=requireNode(state,frame.nodeId);if(frame.visitedChildren||!isDirectoryNode(node)){isDirectoryNode(node)&&state.snapshot.directories.delete(frame.nodeId),addNodeFlag(node,4),state.pathCacheByNodeId.delete(frame.nodeId),state.collapsedDirectoryIds.delete(frame.nodeId)&&(state.hasCollapsedDirectoryOverrides=state.collapsedDirectoryIds.size>0),state.expandedDirectoryIds.delete(frame.nodeId),clearDirectoryLoadInfo(state,frame.nodeId),state.activeNodeCount--,removedNodeIds.push(frame.nodeId);continue}stack.push({nodeId:frame.nodeId,visitedChildren:!0});const directoryIndex=getDirectoryIndex(state,frame.nodeId);for(let childIndex=directoryIndex.childIds.length-1;childIndex>=0;childIndex--){const childId=directoryIndex.childIds[childIndex];childId!=null&&stack.push({nodeId:childId,visitedChildren:!1})}}return removedNodeIds}function promoteEmptyAncestorsToExplicit(state,startDirectoryId){let currentDirectoryId=startDirectoryId;for(;currentDirectoryId!=null;){const currentNode=requireNode(state,currentDirectoryId);if(!isDirectoryNode(currentNode)||hasNodeFlag(currentNode,2)||getDirectoryIndex(state,currentDirectoryId).childIds.length>0)return;addNodeFlag(currentNode,1),currentDirectoryId=currentNode.parentId===currentDirectoryId?null:currentNode.parentId}}function findDeepestExistingDirectoryId(state,segments){let currentDirectoryId=state.snapshot.rootId;for(const segment of segments){const segmentId=state.snapshot.segmentTable.idByValue.get(segment);if(segmentId==null)break;const nextNodeId=ensureChildIdByNameId(state.snapshot.nodes,getDirectoryIndex(state,currentDirectoryId)).get(segmentId);if(nextNodeId==null||!isDirectoryNode(requireNode(state,nextNodeId)))break;currentDirectoryId=nextNodeId}return currentDirectoryId}function getCollapsedProjectionSignature(state,startDirectoryId){const collapsedAncestorId=findNearestCollapsedAncestor(state,startDirectoryId);if(collapsedAncestorId==null)return null;const terminalDirectoryId=getFlattenedTerminalDirectoryId(state,collapsedAncestorId),terminalNode=requireNode(state,terminalDirectoryId),flattenedSegmentPaths=collapsedAncestorId===terminalDirectoryId?null:collectFlattenedDirectoryChainIds(state,collapsedAncestorId).map(nodeId=>materializeNodePath(state,nodeId));return JSON.stringify({flattenedSegmentPaths,hasChildren:getDirectoryIndex(state,terminalDirectoryId).childIds.length>0,path:materializeNodePath(state,terminalDirectoryId),terminalKind:getNodeKind(terminalNode)})}function didProjectionChange(previousProjectionSignature,nextProjectionSignature){return didAnyProjectionChange([previousProjectionSignature],[nextProjectionSignature])}function didAnyProjectionChange(previousProjectionSignatures,nextProjectionSignatures){for(let index=0;index<previousProjectionSignatures.length;index+=1){const previousProjectionSignature=previousProjectionSignatures[index],nextProjectionSignature=nextProjectionSignatures[index];if(previousProjectionSignature==null||nextProjectionSignature==null||previousProjectionSignature!==nextProjectionSignature)return!0}return!1}function findNearestCollapsedAncestor(state,startDirectoryId){let currentDirectoryId=startDirectoryId;for(;currentDirectoryId!=null;){const currentNode=requireNode(state,currentDirectoryId);if(!isDirectoryNode(currentNode)||hasNodeFlag(currentNode,2))return null;if(!isDirectoryExpanded(state,currentDirectoryId,currentNode))return currentDirectoryId;currentDirectoryId=currentNode.parentId}return null}function recomputeDepths(state,nodeId){const node=requireNode(state,nodeId);if(setNodeDepth(node,(nodeId===state.snapshot.rootId?-1:getNodeDepth(requireNode(state,node.parentId)))+1),!isDirectoryNode(node))return;const directoryIndex=getDirectoryIndex(state,nodeId);for(const childId of directoryIndex.childIds)recomputeDepths(state,childId)}function isAncestor(state,ancestorNodeId,nodeId){let currentNodeId=nodeId;for(;currentNodeId!=null;){if(currentNodeId===ancestorNodeId)return!0;const currentNode=requireNode(state,currentNodeId);if(currentNodeId===state.snapshot.rootId)return!1;currentNodeId=currentNode.parentId}return!1}function recomputeNodeCounts(state,nodeId,currentNode=requireNode(state,nodeId),rebuildChildAggregates=!1){const instrumentation=state.instrumentation;if(instrumentation==null){recomputeNodeCountsNow(state,nodeId,currentNode,rebuildChildAggregates);return}withBenchmarkPhase(instrumentation,"store.recomputeNodeCounts",()=>recomputeNodeCountsNow(state,nodeId,currentNode,rebuildChildAggregates))}function recomputeCountsUpwardFromNow(state,startNodeId){let currentNodeId=startNodeId;for(;currentNodeId!=null;){const currentNode=requireNode(state,currentNodeId),previousSubtreeNodeCount=currentNode.subtreeNodeCount,previousVisibleSubtreeCount=currentNode.visibleSubtreeCount;if(recomputeNodeCounts(state,currentNodeId,currentNode),currentNodeId===state.snapshot.rootId)return;const subtreeNodeDelta=currentNode.subtreeNodeCount-previousSubtreeNodeCount,visibleSubtreeDelta=currentNode.visibleSubtreeCount-previousVisibleSubtreeCount,parentId=currentNode.parentId;(subtreeNodeDelta!==0||visibleSubtreeDelta!==0)&&applyChildAggregateDelta(getDirectoryIndex(state,parentId),currentNodeId,subtreeNodeDelta,visibleSubtreeDelta),currentNodeId=parentId}}function recomputeNodeCountsNow(state,nodeId,currentNode,rebuildChildAggregates){if(!isDirectoryNode(currentNode)){currentNode.subtreeNodeCount=1,currentNode.visibleSubtreeCount=1;return}const currentIndex=getDirectoryIndex(state,nodeId);if(rebuildChildAggregates){const instrumentation=state.instrumentation;instrumentation==null?rebuildDirectoryChildAggregates(state.snapshot.nodes,currentIndex):withBenchmarkPhase(instrumentation,"store.recomputeNodeCounts.rebuildChildAggregates",()=>rebuildDirectoryChildAggregates(state.snapshot.nodes,currentIndex))}const subtreeNodeCount=1+currentIndex.totalChildSubtreeNodeCount,visibleChildCount=currentIndex.totalChildVisibleSubtreeCount;if(currentNode.subtreeNodeCount=subtreeNodeCount,hasNodeFlag(currentNode,2)){currentNode.visibleSubtreeCount=visibleChildCount;return}currentNode.visibleSubtreeCount=getFlattenedChildDirectoryId(state,nodeId)!=null?visibleChildCount:isDirectoryExpanded(state,nodeId,currentNode)?1+visibleChildCount:1}function buildPathPreview(state,parentId,basename){const parentPath=materializeNodePath(state,parentId);return parentPath.length===0?basename:`${parentPath}${basename}`}function isLiveNode(node){return node!=null&&!hasNodeFlag(node,4)}function isLiveDirectoryNode(state,nodeId){const node=state.snapshot.nodes[nodeId];return!isLiveNode(node)||!isDirectoryNode(node)||hasNodeFlag(node,2)?null:node}function countCachedPathEntries(state){let cachedPathEntryCount=0;for(const[nodeId,cachedEntry]of state.pathCacheByNodeId)cachedEntry.version===state.pathCacheVersion&&isLiveNode(state.snapshot.nodes[nodeId])&&(cachedPathEntryCount+=1);return cachedPathEntryCount}function countSegmentEntries(segmentTable){return Math.max(0,segmentTable.valueById.length-1)}function createCleanupMetricSnapshot(state){return{activeNodeCount:state.activeNodeCount,cachedPathEntryCount:countCachedPathEntries(state),loadInfoEntryCount:state.directoryLoadInfoById.size,segmentCount:countSegmentEntries(state.snapshot.segmentTable),totalNodeSlotCount:Math.max(0,state.snapshot.nodes.length-1)}}function createCleanupResult(mode,idsPreserved,before2,after){return{activeNodeCountAfter:after.activeNodeCount,activeNodeCountBefore:before2.activeNodeCount,cachedPathEntryCountAfter:after.cachedPathEntryCount,cachedPathEntryCountBefore:before2.cachedPathEntryCount,idsPreserved,loadInfoEntryCountAfter:after.loadInfoEntryCount,loadInfoEntryCountBefore:before2.loadInfoEntryCount,mode,reclaimedCachedPathEntryCount:before2.cachedPathEntryCount-after.cachedPathEntryCount,reclaimedLoadInfoEntryCount:before2.loadInfoEntryCount-after.loadInfoEntryCount,reclaimedNodeSlotCount:before2.totalNodeSlotCount-after.totalNodeSlotCount,reclaimedSegmentCount:before2.segmentCount-after.segmentCount,segmentCountAfter:after.segmentCount,segmentCountBefore:before2.segmentCount,totalNodeSlotCountAfter:after.totalNodeSlotCount,totalNodeSlotCountBefore:before2.totalNodeSlotCount}}function collectExpansionOverridePaths(state){const collapsedPaths=[],expandedPaths=[];for(const nodeId of state.collapsedDirectoryIds)isLiveDirectoryNode(state,nodeId)!=null&&collapsedPaths.push(materializeNodePath(state,nodeId));for(const nodeId of state.expandedDirectoryIds)isLiveDirectoryNode(state,nodeId)!=null&&expandedPaths.push(materializeNodePath(state,nodeId));return{collapsedPaths,expandedPaths}}function collectDirectoryLoadInfos(state){const retainedInfos=[];for(const[nodeId,info]of state.directoryLoadInfoById)isLiveDirectoryNode(state,nodeId)==null||getDirectoryLoadState(state,nodeId)==="loaded"||retainedInfos.push({info:{activeAttemptId:null,errorMessage:info.errorMessage,nextAttemptId:info.nextAttemptId,state:info.state},path:materializeNodePath(state,nodeId)});return retainedInfos}function restoreExpansionOverridePaths(state,persistedExpansionState){state.collapsedDirectoryIds.clear(),state.hasCollapsedDirectoryOverrides=!1,state.expandedDirectoryIds.clear();for(const path of persistedExpansionState.expandedPaths){const nodeId=findNodeId(state,path);nodeId!=null&&setDirectoryExpanded(state,nodeId,!0,requireNode(state,nodeId))}for(const path of persistedExpansionState.collapsedPaths){const nodeId=findNodeId(state,path);nodeId!=null&&setDirectoryExpanded(state,nodeId,!1,requireNode(state,nodeId))}}function restoreDirectoryLoadInfos(state,persistedLoadInfos){state.directoryLoadInfoById.clear();for(const retainedInfo of persistedLoadInfos){const nodeId=findNodeId(state,retainedInfo.path);nodeId!=null&&isLiveDirectoryNode(state,nodeId)!=null&&state.directoryLoadInfoById.set(nodeId,{activeAttemptId:null,errorMessage:retainedInfo.info.errorMessage,nextAttemptId:retainedInfo.info.nextAttemptId,state:retainedInfo.info.state})}}function clearPathCaches(state){state.pathCacheVersion+=1,state.pathCacheByNodeId.clear(),state.pathCacheByNodeId.set(state.snapshot.rootId,{path:"",version:state.pathCacheVersion})}function rebuildSegmentTablePreservingNodeIds(state){const previousSegmentTable=state.snapshot.segmentTable,nextSegmentTable=createSegmentTable();for(const node of state.snapshot.nodes)if(isLiveNode(node)){if(hasNodeFlag(node,2)){node.nameId=0;continue}node.nameId=internSegment(nextSegmentTable,getSegmentValue(previousSegmentTable,node.nameId))}state.snapshot.segmentTable=nextSegmentTable}function rebuildDirectoryIndexes(state){for(const[directoryId,directoryIndex]of state.snapshot.directories){const directoryNode=state.snapshot.nodes[directoryId];if(!isLiveNode(directoryNode)||!isDirectoryNode(directoryNode)){state.snapshot.directories.delete(directoryId);continue}const liveChildIds=directoryIndex.childIds.filter(childId=>{const childNode=state.snapshot.nodes[childId];return isLiveNode(childNode)&&childNode.parentId===directoryId});directoryIndex.childIds=liveChildIds,directoryIndex.childIdByNameId=new Map(liveChildIds.map(childId=>[requireNode(state,childId).nameId,childId])),directoryIndex.childPositionById=new Map(liveChildIds.map((childId,childIndex)=>[childId,childIndex])),rebuildDirectoryChildAggregates(state.snapshot.nodes,directoryIndex)}}function trimTrailingRemovedNodeSlots(state){let lastNodeIndex=state.snapshot.nodes.length-1;for(;lastNodeIndex>state.snapshot.rootId;){const node=state.snapshot.nodes[lastNodeIndex];if(isLiveNode(node))break;lastNodeIndex-=1}state.snapshot.nodes.length=lastNodeIndex+1}function runStableCleanup(state){const persistedExpansionState=collectExpansionOverridePaths(state),persistedLoadInfos=collectDirectoryLoadInfos(state);withBenchmarkPhase(state.instrumentation,"store.cleanup.stable.clearPathCaches",()=>clearPathCaches(state)),withBenchmarkPhase(state.instrumentation,"store.cleanup.stable.rebuildSegmentTable",()=>rebuildSegmentTablePreservingNodeIds(state)),withBenchmarkPhase(state.instrumentation,"store.cleanup.stable.rebuildDirectoryIndexes",()=>rebuildDirectoryIndexes(state)),withBenchmarkPhase(state.instrumentation,"store.cleanup.stable.trimTrailingRemovedNodeSlots",()=>trimTrailingRemovedNodeSlots(state)),withBenchmarkPhase(state.instrumentation,"store.cleanup.stable.restoreExpansionOverrides",()=>restoreExpansionOverridePaths(state,persistedExpansionState)),withBenchmarkPhase(state.instrumentation,"store.cleanup.stable.restoreDirectoryLoadInfos",()=>restoreDirectoryLoadInfos(state,persistedLoadInfos)),withBenchmarkPhase(state.instrumentation,"store.cleanup.stable.recomputeCounts",()=>recomputeCountsRecursive(state,state.snapshot.rootId))}function runAggressiveCleanup(state){const persistedExpansionState=collectExpansionOverridePaths(state),persistedLoadInfos=collectDirectoryLoadInfos(state),canonicalPaths=withBenchmarkPhase(state.instrumentation,"store.cleanup.aggressive.listPaths",()=>listPaths(state)),builderOptions=attachBenchmarkInstrumentation({...state.snapshot.options},state.instrumentation),rebuiltSnapshot=withBenchmarkPhase(state.instrumentation,"store.cleanup.aggressive.rebuildSnapshot",()=>{const builder=new PathStoreBuilder(builderOptions);return builder.appendPaths(canonicalPaths),builder.finish()});state.snapshot=rebuiltSnapshot,state.activeNodeCount=rebuiltSnapshot.nodes.length-1,state.pathCacheByNodeId=new Map([[rebuiltSnapshot.rootId,{path:"",version:0}]]),state.pathCacheVersion=0,withBenchmarkPhase(state.instrumentation,"store.cleanup.aggressive.restoreExpansionOverrides",()=>restoreExpansionOverridePaths(state,persistedExpansionState)),withBenchmarkPhase(state.instrumentation,"store.cleanup.aggressive.restoreDirectoryLoadInfos",()=>restoreDirectoryLoadInfos(state,persistedLoadInfos)),withBenchmarkPhase(state.instrumentation,"store.cleanup.aggressive.recomputeCounts",()=>recomputeCountsRecursive(state,state.snapshot.rootId))}function hasActiveCleanupBlockingLoads(state){for(const loadInfo of state.directoryLoadInfoById.values())if(loadInfo.state==="loading"&&loadInfo.activeAttemptId!=null)return!0;return!1}function cleanupPathStoreState(state,mode){const before2=createCleanupMetricSnapshot(state);mode==="stable"?withBenchmarkPhase(state.instrumentation,"store.cleanup.stable",()=>runStableCleanup(state)):withBenchmarkPhase(state.instrumentation,"store.cleanup.aggressive",()=>runAggressiveCleanup(state));const after=createCleanupMetricSnapshot(state);return createCleanupResult(mode,mode==="stable",before2,after)}const INITIAL_PROJECTION_DEPTH_CAPACITY=64;function ensureProjectionDepthCapacity(depthTable,depth){const requiredLength=depth+2;if(requiredLength<=depthTable.length)return depthTable;let nextLength=depthTable.length;for(;nextLength<requiredLength;)nextLength*=2;const nextDepthTable=new Int32Array(nextLength);return nextDepthTable.fill(-1),nextDepthTable.set(depthTable),nextDepthTable}function getVisibleCount(state){return requireNode(state,state.snapshot.rootId).visibleSubtreeCount}function getVisibleRowSubtreeEndIndex(state,cursor,index,totalVisibleCount){const terminalNode=requireNode(state,cursor.terminalNodeId),subtreeSize=Math.max(1,terminalNode.visibleSubtreeCount);return Math.min(totalVisibleCount-1,index+subtreeSize-1)}function materializeVisibleAncestorRow(state,entry,totalVisibleCount,ancestorPaths){return{ancestorPaths,index:entry.index,posInSet:entry.posInSet,row:materializeVisibleRow(state,entry.cursor),setSize:entry.setSize,subtreeEndIndex:getVisibleRowSubtreeEndIndex(state,entry.cursor,entry.index,totalVisibleCount)}}function selectVisibleRowContextWithinDirectory(state,directoryNodeId,index,directoryStartIndex,parentVisibleDepth,ancestors){const directoryIndex=getDirectoryIndex(state,directoryNodeId),{childIndex,childVisibleIndex,localVisibleIndex}=selectChildIndexByVisibleIndex(state.snapshot.nodes,directoryIndex,index),childId=directoryIndex.childIds[childIndex];if(childId==null)throw new Error(`Visible index ${String(index)} is out of range`);return selectVisibleRowContextWithinSubtree(state,childId,localVisibleIndex,directoryStartIndex+childVisibleIndex,parentVisibleDepth+1,childIndex,directoryIndex.childIds.length,ancestors)}function selectVisibleRowContextWithinSubtree(state,nodeId,index,rowIndex,visibleDepth,posInSet,setSize,ancestors){if(!isDirectoryNode(requireNode(state,nodeId))){if(index===0)return{ancestors,cursor:{headNodeId:nodeId,terminalNodeId:nodeId,visibleDepth},index:rowIndex,posInSet,setSize};throw new Error(`Visible index ${String(index)} is out of range for file`)}const currentCursor=createVisibleRowCursor(state,nodeId,visibleDepth);if(index===0)return{ancestors,cursor:currentCursor,index:rowIndex,posInSet,setSize};const terminalNode=requireNode(state,currentCursor.terminalNodeId);if(!isDirectoryNode(terminalNode)||!isDirectoryExpanded(state,currentCursor.terminalNodeId,terminalNode))throw new Error(`Visible index ${String(index)} is out of range for collapsed directory`);return selectVisibleRowContextWithinDirectory(state,currentCursor.terminalNodeId,index-1,rowIndex+1,currentCursor.visibleDepth,[...ancestors,{cursor:currentCursor,index:rowIndex,posInSet,setSize}])}function getVisibleRowContext(state,index){const totalVisibleCount=getVisibleCount(state);if(index<0||index>=totalVisibleCount)return null;const selected=selectVisibleRowContextWithinDirectory(state,state.snapshot.rootId,index,0,-1,[]),ancestorPaths=selected.ancestors.map(ancestor=>materializeNodePath(state,ancestor.cursor.terminalNodeId));let cachedAncestorRows=null;return{ancestorPaths,get ancestorRows(){if(cachedAncestorRows!=null)return cachedAncestorRows;const ancestorRows=[],rowAncestorPaths=[];for(const ancestor of selected.ancestors){const ancestorRow=materializeVisibleAncestorRow(state,ancestor,totalVisibleCount,[...rowAncestorPaths]);ancestorRows.push(ancestorRow),rowAncestorPaths.push(ancestorRow.row.path)}return cachedAncestorRows=ancestorRows,cachedAncestorRows},index:selected.index,posInSet:selected.posInSet,row:materializeVisibleRow(state,selected.cursor),setSize:selected.setSize,subtreeEndIndex:getVisibleRowSubtreeEndIndex(state,selected.cursor,selected.index,totalVisibleCount)}}function getVisibleSlice(state,start,end){const instrumentation=state.instrumentation,totalVisibleCount=getVisibleCount(state);if(totalVisibleCount<=0||end<start)return[];const normalizedStart=Math.max(0,Math.min(start,totalVisibleCount-1)),normalizedEnd=Math.max(normalizedStart,Math.min(end,totalVisibleCount-1));if(instrumentation==null){if(normalizedStart===0)return collectVisibleRowsDFS(state,normalizedEnd+1);const rows2=[];let currentCursor2=selectVisibleRow(state,normalizedStart);for(let visibleIndex=normalizedStart;visibleIndex<=normalizedEnd&&currentCursor2!=null;visibleIndex++){const row=materializeVisibleRow(state,currentCursor2);rows2.push(row),currentCursor2=getNextVisibleRowCursor(state,currentCursor2)}return rows2}const rows=[];let flattenedRowCount=0,flattenedSegmentCount=0,currentCursor=withBenchmarkPhase(instrumentation,"store.getVisibleSlice.selectFirstRow",()=>selectVisibleRow(state,normalizedStart));for(let visibleIndex=normalizedStart;visibleIndex<=normalizedEnd&&currentCursor!=null;visibleIndex++){const row=withBenchmarkPhase(instrumentation,"store.getVisibleSlice.materializeRow",()=>materializeVisibleRow(state,currentCursor));rows.push(row),row.isFlattened&&(flattenedRowCount++,flattenedSegmentCount+=row.flattenedSegments?.length??0),currentCursor=withBenchmarkPhase(instrumentation,"store.getVisibleSlice.advanceCursor",()=>getNextVisibleRowCursor(state,currentCursor))}return setBenchmarkCounter(instrumentation,"workload.visibleRowsRead",rows.length),setBenchmarkCounter(instrumentation,"workload.flattenedRowsRead",flattenedRowCount),setBenchmarkCounter(instrumentation,"workload.flattenedSegmentsRead",flattenedSegmentCount),rows}function getVisibleTreeProjectionData(state,maxRows=getVisibleCount(state)){const instrumentation=state.instrumentation;return instrumentation==null?buildVisibleTreeProjectionDataDFS(state,maxRows):withBenchmarkPhase(instrumentation,"store.getVisibleTreeProjection",()=>buildVisibleTreeProjectionDataDFS(state,maxRows))}function getVisibleTreeProjection(state){return createVisibleTreeProjectionFromData(getVisibleTreeProjectionData(state))}function getVisibleIndexByPath(state,path){const nodeId=findNodeId(state,path);if(nodeId==null||nodeId===state.snapshot.rootId||isDirectoryNode(requireNode(state,nodeId))&&getFlattenedTerminalDirectoryId(state,nodeId)!==nodeId)return null;let visibleIndex=0,currentNodeId=nodeId;const{nodes,rootId}=state.snapshot;for(;currentNodeId!==rootId;){const parentId=requireNode(state,currentNodeId).parentId,parentIndex=getDirectoryIndex(state,parentId),childPosition=ensureChildPositions(parentIndex).get(currentNodeId);if(childPosition==null)throw new Error(`Child ${String(currentNodeId)} was not found in its parent index`);if(visibleIndex+=getVisibleChildPrefixCount(nodes,parentIndex,childPosition),parentId!==rootId){const parentNode=requireNode(state,parentId),flattenedChildDirectoryId=getFlattenedChildDirectoryId(state,parentId);if(!isDirectoryExpanded(state,parentId,parentNode)&&flattenedChildDirectoryId!==currentNodeId)return null;getFlattenedTerminalDirectoryId(state,parentId)===parentId&&(visibleIndex+=1)}currentNodeId=parentId}return visibleIndex}function expandPath(state,path){const directoryNodeId=findNodeId(state,path);if(directoryNodeId==null)throw new Error(`Path does not exist: "${path}"`);const directoryNode=requireNode(state,directoryNodeId);if(!isDirectoryNode(directoryNode))throw new Error(`Path is not a directory: "${path}"`);return isDirectoryExpanded(state,directoryNodeId,directoryNode)?null:(setDirectoryExpanded(state,directoryNodeId,!0,directoryNode),recomputeCountsUpwardFrom(state,directoryNodeId),createExpandEvent({affectedAncestorIds:collectAncestorIds(state,directoryNodeId),affectedNodeIds:[directoryNodeId],path}))}function collapsePath(state,path){const directoryNodeId=findNodeId(state,path);if(directoryNodeId==null)throw new Error(`Path does not exist: "${path}"`);const directoryNode=requireNode(state,directoryNodeId);if(!isDirectoryNode(directoryNode))throw new Error(`Path is not a directory: "${path}"`);return isDirectoryExpanded(state,directoryNodeId,directoryNode)?(setDirectoryExpanded(state,directoryNodeId,!1,directoryNode),recomputeCountsUpwardFrom(state,directoryNodeId),createCollapseEvent({affectedAncestorIds:collectAncestorIds(state,directoryNodeId),affectedNodeIds:[directoryNodeId],path})):null}function selectVisibleRow(state,index){return index<0||index>=getVisibleCount(state)?null:selectVisibleRowWithinDirectory(state,state.snapshot.rootId,index,-1)}function selectVisibleRowWithinDirectory(state,directoryNodeId,index,parentVisibleDepth){const directoryIndex=getDirectoryIndex(state,directoryNodeId),instrumentation=state.instrumentation,{childIndex,localVisibleIndex}=instrumentation==null?selectChildIndexByVisibleIndex(state.snapshot.nodes,directoryIndex,index):withBenchmarkPhase(instrumentation,"store.getVisibleSlice.selectChildIndex",()=>selectChildIndexByVisibleIndex(state.snapshot.nodes,directoryIndex,index)),childId=directoryIndex.childIds[childIndex];if(childId!=null)return selectVisibleRowWithinSubtree(state,childId,localVisibleIndex,parentVisibleDepth+1);throw new Error(`Visible index ${String(index)} is out of range`)}function selectVisibleRowWithinSubtree(state,nodeId,index,visibleDepth){if(!isDirectoryNode(requireNode(state,nodeId))){if(index===0)return{headNodeId:nodeId,terminalNodeId:nodeId,visibleDepth};throw new Error(`Visible index ${String(index)} is out of range for file`)}const currentCursor=createVisibleRowCursor(state,nodeId,visibleDepth);if(index===0)return currentCursor;const terminalNode=requireNode(state,currentCursor.terminalNodeId);if(!isDirectoryNode(terminalNode)||!isDirectoryExpanded(state,currentCursor.terminalNodeId,terminalNode))throw new Error(`Visible index ${String(index)} is out of range for collapsed directory`);return selectVisibleRowWithinDirectory(state,currentCursor.terminalNodeId,index-1,currentCursor.visibleDepth)}function createVisibleRowCursor(state,nodeId,visibleDepth){return isDirectoryNode(requireNode(state,nodeId))?state.instrumentation==null?{headNodeId:nodeId,terminalNodeId:getFlattenedTerminalDirectoryId(state,nodeId),visibleDepth}:{headNodeId:nodeId,terminalNodeId:withBenchmarkPhase(state.instrumentation,"store.getVisibleSlice.flatten.resolveTerminalDirectory",()=>getFlattenedTerminalDirectoryId(state,nodeId)),visibleDepth}:{headNodeId:nodeId,terminalNodeId:nodeId,visibleDepth}}function isVisibleRowHeadNode(state,nodeId){const node=requireNode(state,nodeId);if(!isDirectoryNode(node))return!0;const parentId=node.parentId;return parentId===state.snapshot.rootId?!0:getFlattenedChildDirectoryId(state,parentId)!==nodeId}function getNextVisibleRowCursor(state,currentCursor){const terminalNode=requireNode(state,currentCursor.terminalNodeId);if(isDirectoryNode(terminalNode)){const currentIndex=getDirectoryIndex(state,currentCursor.terminalNodeId);if(isDirectoryExpanded(state,currentCursor.terminalNodeId,terminalNode)&&currentIndex.childIds.length>0){const firstChildId=currentIndex.childIds[0];return firstChildId==null?null:selectVisibleRowWithinSubtree(state,firstChildId,0,currentCursor.visibleDepth+1)}}let currentNodeId=currentCursor.terminalNodeId,currentVisibleDepth=currentCursor.visibleDepth;for(;;){const currentNode=requireNode(state,currentNodeId);if(currentNodeId===state.snapshot.rootId)return null;const parentId=currentNode.parentId,parentIndex=getDirectoryIndex(state,parentId),siblingIndex=ensureChildPositions(parentIndex).get(currentNodeId)??-1;if(siblingIndex<0)throw new Error(`Child ${String(currentNodeId)} was not found in its parent index`);const nextSiblingId=parentIndex.childIds[siblingIndex+1]??null;if(nextSiblingId!=null)return selectVisibleRowWithinSubtree(state,nextSiblingId,0,currentVisibleDepth);isVisibleRowHeadNode(state,currentNodeId)&&currentVisibleDepth--,currentNodeId=parentId}}function createVisibleTreeProjectionFromData(projection){const rowCount=projection.paths.length,projectionRows=new Array(rowCount);for(let rowIndex=0;rowIndex<rowCount;rowIndex+=1){const parentIndex=projection.getParentIndex(rowIndex);projectionRows[rowIndex]={index:rowIndex,parentPath:parentIndex>=0?projection.paths[parentIndex]??null:null,path:projection.paths[rowIndex]??"",posInSet:projection.posInSetByIndex[rowIndex]??0,setSize:projection.setSizeByIndex[rowIndex]??0}}return{getParentIndex:projection.getParentIndex,rows:projectionRows,get visibleIndexByPath(){return projection.visibleIndexByPath}}}function buildVisibleTreeProjectionDataDFS(state,maxRows){const paths=new Array(maxRows),parentRowIndex=new Int32Array(maxRows),posInSetByIndex=new Int32Array(maxRows),setSizeByIndex=new Int32Array(maxRows);let lastRowAtDepth=new Int32Array(INITIAL_PROJECTION_DEPTH_CAPACITY);lastRowAtDepth.fill(-1);let rowCount=0;const{nodes,directories,segmentTable}=state.snapshot,stack=[[directories.get(state.snapshot.rootId),0,-1,""]],flattenEnabled=state.snapshot.options.flattenEmptyDirectories,pathCacheByNodeId=state.pathCacheByNodeId,pathCacheVersion=state.pathCacheVersion,segmentValues=segmentTable.valueById;for(;stack.length>0&&rowCount<maxRows;){const frame=stack[stack.length-1],dirIndex=frame[0];if(frame[1]>=dirIndex.childIds.length){stack.pop();continue}const childOffset=frame[1],childId=dirIndex.childIds[frame[1]++],childNode=nodes[childId],visibleDepth=frame[2]+1,parentPath=frame[3];lastRowAtDepth=ensureProjectionDepthCapacity(lastRowAtDepth,visibleDepth);let path,terminalNodeId=childId;if(isDirectoryNode(childNode))terminalNodeId=flattenEnabled?getFlattenedTerminalDirectoryId(state,childId):childId,path=terminalNodeId===childId?`${parentPath}${segmentValues[childNode.nameId]}/`:materializeNodePath(state,terminalNodeId);else{const cachedPathEntry=pathCacheByNodeId.get(childId);path=cachedPathEntry!=null&&cachedPathEntry.version===pathCacheVersion?cachedPathEntry.path:`${parentPath}${segmentValues[childNode.nameId]}`}parentRowIndex[rowCount]=lastRowAtDepth[visibleDepth],paths[rowCount]=path,posInSetByIndex[rowCount]=childOffset,setSizeByIndex[rowCount]=dirIndex.childIds.length,lastRowAtDepth[visibleDepth+1]=rowCount,rowCount+=1;const terminalNode=nodes[terminalNodeId];terminalNode!=null&&isDirectoryNode(terminalNode)&&isDirectoryExpanded(state,terminalNodeId,terminalNode)&&stack.push([directories.get(terminalNodeId),0,visibleDepth,path])}rowCount<maxRows&&(paths.length=rowCount);const finalParentRowIndex=parentRowIndex.subarray(0,rowCount),finalPosInSetByIndex=posInSetByIndex.subarray(0,rowCount),finalSetSizeByIndex=setSizeByIndex.subarray(0,rowCount);let cachedVisibleIndexByPath=null;return{getParentIndex(index){return index<0||index>=rowCount?-1:finalParentRowIndex[index]??-1},paths,posInSetByIndex:finalPosInSetByIndex,setSizeByIndex:finalSetSizeByIndex,get visibleIndexByPath(){if(cachedVisibleIndexByPath==null){cachedVisibleIndexByPath=new Map;for(let rowIndex=0;rowIndex<rowCount;rowIndex+=1)cachedVisibleIndexByPath.set(paths[rowIndex]??"",rowIndex)}return cachedVisibleIndexByPath}}}function collectVisibleRowsDFS(state,maxRows){const rows=new Array(maxRows);let rowCount=0;const{nodes,directories,segmentTable}=state.snapshot,stack=[[directories.get(state.snapshot.rootId),0,-1]],segmentValues=segmentTable.valueById,flattenEnabled=state.snapshot.options.flattenEmptyDirectories,pathCacheByNodeId=state.pathCacheByNodeId,pathCacheVersion=state.pathCacheVersion;for(;stack.length>0&&rowCount<maxRows;){const frame=stack[stack.length-1],dirIndex=frame[0];if(frame[1]>=dirIndex.childIds.length){stack.pop();continue}const childId=dirIndex.childIds[frame[1]++],childNode=nodes[childId],visibleDepth=frame[2]+1;if(!isDirectoryNode(childNode)){const cachedPathEntry=pathCacheByNodeId.get(childId);rows[rowCount++]={depth:visibleDepth,flattenedSegments:void 0,hasChildren:!1,id:childId,isExpanded:!1,isFlattened:!1,isLoading:!1,kind:"file",loadState:void 0,name:segmentValues[childNode.nameId],path:cachedPathEntry!=null&&cachedPathEntry.version===pathCacheVersion?cachedPathEntry.path:materializeNodePath(state,childId)};continue}const terminalNodeId=flattenEnabled?getFlattenedTerminalDirectoryId(state,childId):childId,cursor={headNodeId:childId,terminalNodeId,visibleDepth};rows[rowCount++]=materializeVisibleRow(state,cursor);const terminalNode=nodes[terminalNodeId];terminalNode!=null&&isDirectoryNode(terminalNode)&&isDirectoryExpanded(state,terminalNodeId,terminalNode)&&stack.push([directories.get(terminalNodeId),0,visibleDepth])}return rowCount<maxRows&&(rows.length=rowCount),rows}function materializeVisibleRow(state,cursor){const terminalNode=requireNode(state,cursor.terminalNodeId),loadState=isDirectoryNode(terminalNode)?getVisibleRowLoadState(state,cursor):null,path=materializeNodePath(state,cursor.terminalNodeId),name=getSegmentValue(state.snapshot.segmentTable,terminalNode.nameId),hasChildren=isDirectoryNode(terminalNode)&&getDirectoryIndex(state,cursor.terminalNodeId).childIds.length>0,isFlattened=cursor.headNodeId!==cursor.terminalNodeId,instrumentation=state.instrumentation,flattenedSegments=isFlattened?instrumentation==null?collectFlattenedDirectoryChainIds(state,cursor.headNodeId).map(nodeId=>{const node=requireNode(state,nodeId);return{isTerminal:nodeId===cursor.terminalNodeId,name:getSegmentValue(state.snapshot.segmentTable,node.nameId),nodeId,path:materializeNodePath(state,nodeId)}}):withBenchmarkPhase(instrumentation,"store.getVisibleSlice.flatten.collectSegments",()=>collectFlattenedDirectoryChainIds(state,cursor.headNodeId).map(nodeId=>{const node=requireNode(state,nodeId);return{isTerminal:nodeId===cursor.terminalNodeId,name:getSegmentValue(state.snapshot.segmentTable,node.nameId),nodeId,path:materializeNodePath(state,nodeId)}})):void 0;return{depth:cursor.visibleDepth,flattenedSegments,hasChildren,id:cursor.terminalNodeId,isExpanded:isDirectoryNode(terminalNode)&&isDirectoryExpanded(state,cursor.terminalNodeId,terminalNode),isFlattened,isLoading:loadState==="loading",kind:isDirectoryNode(terminalNode)?"directory":"file",loadState:loadState==null||loadState==="loaded"?void 0:loadState,name,path}}function getVisibleRowLoadState(state,cursor){if(cursor.headNodeId===cursor.terminalNodeId)return getDirectoryLoadState(state,cursor.terminalNodeId);const chainNodeIds=collectFlattenedDirectoryChainIds(state,cursor.headNodeId);let hasUnloaded=!1,hasError=!1;for(const nodeId of chainNodeIds){const loadState=getDirectoryLoadState(state,nodeId);if(loadState==="loading")return"loading";if(loadState==="error"){hasError=!0;continue}loadState==="unloaded"&&(hasUnloaded=!0)}return hasError?"error":hasUnloaded?"unloaded":"loaded"}const KIND_MASK=8;function buildSoaNodeStore(snapshot){const{nodes,directories,rootId,options}=snapshot,nodeCount=nodes.length,parentId=new Int32Array(nodeCount),nameId=new Int32Array(nodeCount),depthAndFlags=new Int32Array(nodeCount),subtreeNodeCount=new Int32Array(nodeCount),visibleSubtreeCount=new Int32Array(nodeCount),childStart=new Int32Array(nodeCount),childCount=new Int32Array(nodeCount);for(let id=0;id<nodeCount;id+=1){const node=nodes[id];node!=null&&(parentId[id]=node.parentId,nameId[id]=node.nameId,depthAndFlags[id]=node.depthAndFlags,subtreeNodeCount[id]=node.subtreeNodeCount,visibleSubtreeCount[id]=node.visibleSubtreeCount)}let totalChildren=0;for(const index of directories.values())totalChildren+=index.childIds.length;const childIdsFlat=new Int32Array(totalChildren);let cursor=0;for(const[dirId,index]of directories){const ids=index.childIds;childStart[dirId]=cursor,childCount[dirId]=ids.length;for(let i2=0;i2<ids.length;i2+=1)childIdsFlat[cursor]=ids[i2],cursor+=1}return{nodeCount,rootId,flattenEmptyDirectories:options.flattenEmptyDirectories===!0,parentId,nameId,depthAndFlags,subtreeNodeCount,visibleSubtreeCount,childStart,childCount,childIdsFlat}}function sweepOpenVisibleCountsSoa(store){const{nodeCount,rootId,flattenEmptyDirectories,depthAndFlags,subtreeNodeCount,visibleSubtreeCount,childStart,childCount,childIdsFlat}=store;for(let id=nodeCount-1;id>=1;id-=1){if((depthAndFlags[id]&KIND_MASK)===0)continue;const base=childStart[id],count=childCount[id];let totalChildSubtreeNodeCount=0,totalChildVisibleSubtreeCount=0;for(let ci=0;ci<count;ci+=1){const childId=childIdsFlat[base+ci];totalChildSubtreeNodeCount+=subtreeNodeCount[childId],totalChildVisibleSubtreeCount+=visibleSubtreeCount[childId]}subtreeNodeCount[id]=1+totalChildSubtreeNodeCount;let newVisibleSubtreeCount;flattenEmptyDirectories&&count===1?newVisibleSubtreeCount=(depthAndFlags[childIdsFlat[base]]&KIND_MASK)!==0?totalChildVisibleSubtreeCount:1+totalChildVisibleSubtreeCount:newVisibleSubtreeCount=1+totalChildVisibleSubtreeCount,visibleSubtreeCount[id]=newVisibleSubtreeCount}const rootBase=childStart[rootId],rootCount=childCount[rootId];let rootTotalChildSubtreeNodeCount=0,rootTotalChildVisibleSubtreeCount=0;for(let ci=0;ci<rootCount;ci+=1){const childId=childIdsFlat[rootBase+ci];rootTotalChildSubtreeNodeCount+=subtreeNodeCount[childId],rootTotalChildVisibleSubtreeCount+=visibleSubtreeCount[childId]}subtreeNodeCount[rootId]=1+rootTotalChildSubtreeNodeCount,visibleSubtreeCount[rootId]=rootTotalChildVisibleSubtreeCount}function initializeOpenVisibleCounts(state){const{directories,nodes,options,rootId,presortedDirectoryNodeIds}=state.snapshot,flattenEmptyDirectories=options.flattenEmptyDirectories===!0,walkDirectory=nodeId=>{const currentNode=nodes[nodeId];if(currentNode==null||!isDirectoryNode(currentNode))return;const currentIndex=directories.get(nodeId);if(currentIndex==null)throw new Error(`Unknown directory child index for node ${String(nodeId)}`);const childIds=currentIndex.childIds,childCount=childIds.length;let totalChildSubtreeNodeCount=0,totalChildVisibleSubtreeCount=0;for(let ci=0;ci<childCount;ci++){const childId=childIds[ci];if(childId==null)continue;const childNode=nodes[childId];totalChildSubtreeNodeCount+=childNode.subtreeNodeCount,totalChildVisibleSubtreeCount+=childNode.visibleSubtreeCount}currentIndex.totalChildSubtreeNodeCount=totalChildSubtreeNodeCount,currentIndex.totalChildVisibleSubtreeCount=totalChildVisibleSubtreeCount,childCount>=128&&rebuildVisibleChildChunks(nodes,currentIndex),currentNode.subtreeNodeCount=1+totalChildSubtreeNodeCount;let newVisibleSubtreeCount;if(flattenEmptyDirectories&&childCount===1){const onlyChild=nodes[childIds[0]];newVisibleSubtreeCount=onlyChild!=null&&isDirectoryNode(onlyChild)?totalChildVisibleSubtreeCount:1+totalChildVisibleSubtreeCount}else newVisibleSubtreeCount=1+totalChildVisibleSubtreeCount;currentNode.visibleSubtreeCount=newVisibleSubtreeCount};if(presortedDirectoryNodeIds!=null)for(let i2=presortedDirectoryNodeIds.length-1;i2>=0;i2--)walkDirectory(presortedDirectoryNodeIds[i2]);else for(let nodeId=nodes.length-1;nodeId>=1;nodeId--)walkDirectory(nodeId);const rootNode=nodes[rootId],rootIndex=directories.get(rootId);if(rootNode==null||rootIndex==null)return;const rootChildIds=rootIndex.childIds;let rootTotalChildSubtreeNodeCount=0,rootTotalChildVisibleSubtreeCount=0;for(let ci=0;ci<rootChildIds.length;ci++){const childId=rootChildIds[ci];if(childId==null)continue;const childNode=nodes[childId];rootTotalChildSubtreeNodeCount+=childNode.subtreeNodeCount,rootTotalChildVisibleSubtreeCount+=childNode.visibleSubtreeCount}rootIndex.totalChildSubtreeNodeCount=rootTotalChildSubtreeNodeCount,rootIndex.totalChildVisibleSubtreeCount=rootTotalChildVisibleSubtreeCount,rebuildVisibleChildChunks(nodes,rootIndex),rootNode.subtreeNodeCount=1+rootTotalChildSubtreeNodeCount,rootNode.visibleSubtreeCount=rootTotalChildVisibleSubtreeCount}function initializeOpenVisibleCountsViaSoa(state){const{directories,nodes,rootId}=state.snapshot,soa=buildSoaNodeStore(state.snapshot);sweepOpenVisibleCountsSoa(soa);const subtreeNodeCount=soa.subtreeNodeCount,visibleSubtreeCount=soa.visibleSubtreeCount;for(let id=0;id<nodes.length;id+=1){const node=nodes[id];node!=null&&(node.subtreeNodeCount=subtreeNodeCount[id],node.visibleSubtreeCount=visibleSubtreeCount[id])}for(const[dirId,currentIndex]of directories){const childIds=currentIndex.childIds,childCount=childIds.length;let totalChildSubtreeNodeCount=0,totalChildVisibleSubtreeCount=0;for(let ci=0;ci<childCount;ci++){const childId=childIds[ci];if(childId==null)continue;const childNode=nodes[childId];totalChildSubtreeNodeCount+=childNode.subtreeNodeCount,totalChildVisibleSubtreeCount+=childNode.visibleSubtreeCount}currentIndex.totalChildSubtreeNodeCount=totalChildSubtreeNodeCount,currentIndex.totalChildVisibleSubtreeCount=totalChildVisibleSubtreeCount,(dirId===rootId||childCount>=128)&&rebuildVisibleChildChunks(nodes,currentIndex)}}function canInitializeOpenVisibleCounts(options){return options.initialExpansion==="open"&&(options.initialExpandedPaths==null||options.initialExpandedPaths.length===0)}var PathStore=class PathStore2{#state;constructor(options={}){const instrumentation=getBenchmarkInstrumentation(options),builder=withBenchmarkPhase(instrumentation,"store.builder.create",()=>new PathStoreBuilder(options));if(options.preparedInput!=null){const presortedPaths=getPreparedInputPresortedPaths(options.preparedInput);presortedPaths!=null?builder.appendPresortedPaths(presortedPaths,getPreparedInputPresortedPathsContainDirectories(options.preparedInput)):builder.appendPreparedPaths(getPreparedInputEntries(options.preparedInput),!1)}else{const inputPaths=options.paths??[];options.presorted===!0?builder.appendPaths(inputPaths):builder.appendPreparedPaths(withBenchmarkPhase(instrumentation,"store.preparePathEntries",()=>preparePathEntries(inputPaths,options)))}const snapshot=withBenchmarkPhase(instrumentation,"store.builder.finish",()=>builder.finish({skipSubtreeCountPass:!0})),useExplicitOpenExpansionFastPath=withBenchmarkPhase(instrumentation,"store.state.detectAllDirectoriesExpanded",()=>(options.initialExpansion??"closed")==="closed"&&builder.didMatchAllInitialExpandedPaths());this.#state=withBenchmarkPhase(instrumentation,"store.state.create",()=>createPathStoreState(snapshot,useExplicitOpenExpansionFastPath?"open":options.initialExpansion??"closed",instrumentation)),useExplicitOpenExpansionFastPath&&(this.#state.collapseNewDirectoriesByDefault=!0);const expandedDirectoryCount=useExplicitOpenExpansionFastPath?this.#state.snapshot.directories.size-1:withBenchmarkPhase(instrumentation,"store.state.initializeExpandedPaths",()=>this.initializeExpandedPaths(options.initialExpandedPaths));useExplicitOpenExpansionFastPath||canInitializeOpenVisibleCounts(options)||(options.initialExpansion??"closed")==="closed"&&expandedDirectoryCount===this.#state.snapshot.directories.size-1||(options.initialExpandedPaths?.length??0)>0&&withBenchmarkPhase(instrumentation,"store.state.checkAllDirectoriesExpanded",()=>this.hasAllDirectoriesExpanded())?options.useSoaCountSweep===!0?withBenchmarkPhase(instrumentation,"store.state.initializeOpenVisibleCountsViaSoa",()=>initializeOpenVisibleCountsViaSoa(this.#state)):withBenchmarkPhase(instrumentation,"store.state.initializeOpenVisibleCounts",()=>initializeOpenVisibleCounts(this.#state)):withBenchmarkPhase(instrumentation,"store.state.recomputeCounts",()=>recomputeCountsRecursive(this.#state,this.#state.snapshot.rootId))}static preparePaths(paths,options={}){return preparePaths(paths,options)}static prepareInput(paths,options={}){return prepareInput(paths,options)}static preparePresortedInput(paths){return preparePresortedInput(paths)}list(path){return withBenchmarkPhase(this.#state.instrumentation,"store.list",()=>listPaths(this.#state,path))}add(path){withBenchmarkPhase(this.#state.instrumentation,"store.add",()=>{const previousVisibleCount=getVisibleCount(this.#state);recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,addPath(this.#state,path)))})}remove(path,options={}){withBenchmarkPhase(this.#state.instrumentation,"store.remove",()=>{const previousVisibleCount=getVisibleCount(this.#state);recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,removePath(this.#state,path,options)))})}move(fromPath,toPath,options={}){withBenchmarkPhase(this.#state.instrumentation,"store.move",()=>{const previousVisibleCount=getVisibleCount(this.#state),event=movePath(this.#state,fromPath,toPath,options);event!=null&&recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,event))})}batch(operations){batchEvents(this.#state,()=>{if(typeof operations=="function"){operations(this);return}for(const operation of operations)switch(operation.type){case"add":this.add(operation.path);break;case"remove":this.remove(operation.path,{recursive:operation.recursive});break;case"move":this.move(operation.from,operation.to,{collision:operation.collision});break}})}getVisibleCount(){return withBenchmarkPhase(this.#state.instrumentation,"store.getVisibleCount",()=>getVisibleCount(this.#state))}getVisibleSlice(start,end){return withBenchmarkPhase(this.#state.instrumentation,"store.getVisibleSlice",()=>getVisibleSlice(this.#state,start,end))}getVisibleRowContext(index){return withBenchmarkPhase(this.#state.instrumentation,"store.getVisibleRowContext",()=>getVisibleRowContext(this.#state,index))}getVisibleTreeProjection(){return getVisibleTreeProjection(this.#state)}getVisibleTreeProjectionData(maxRows){return getVisibleTreeProjectionData(this.#state,maxRows)}getVisibleIndex(path){return withBenchmarkPhase(this.#state.instrumentation,"store.getVisibleIndex",()=>getVisibleIndexByPath(this.#state,path))}getPathInfo(path){return withBenchmarkPhase(this.#state.instrumentation,"store.getPathInfo",()=>{const nodeId=findNodeId(this.#state,path);if(nodeId==null)return null;const node=requireNode(this.#state,nodeId);return{depth:getNodeDepth(node),kind:isDirectoryNode(node)?"directory":"file",path:materializeNodePath(this.#state,nodeId)}})}isExpanded(path){return withBenchmarkPhase(this.#state.instrumentation,"store.isExpanded",()=>{const directoryNodeId=this.requireDirectoryNodeId(path),directoryNode=requireNode(this.#state,directoryNodeId);return isDirectoryExpanded(this.#state,directoryNodeId,directoryNode)})}expand(path){withBenchmarkPhase(this.#state.instrumentation,"store.expand",()=>{const previousVisibleCount=getVisibleCount(this.#state),event=expandPath(this.#state,path);event!=null&&recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,event))})}collapse(path){withBenchmarkPhase(this.#state.instrumentation,"store.collapse",()=>{const previousVisibleCount=getVisibleCount(this.#state),event=collapsePath(this.#state,path);event!=null&&recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,event))})}on(type,handler){return subscribe(this.#state,type,handler)}getDirectoryLoadState(path){const directoryNodeId=this.requireDirectoryNodeId(path);return getDirectoryLoadState(this.#state,directoryNodeId)}markDirectoryUnloaded(path){withBenchmarkPhase(this.#state.instrumentation,"store.markDirectoryUnloaded",()=>{const directoryNodeId=this.requireDirectoryNodeId(path);if(getDirectoryIndex(this.#state,directoryNodeId).childIds.length>0)throw new Error(`Cannot mark a directory with known children as unloaded: "${path}"`);const previousVisibleCount=getVisibleCount(this.#state);markDirectoryUnloadedState(this.#state,directoryNodeId),recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,createMarkDirectoryUnloadedEvent({affectedAncestorIds:collectAncestorIds(this.#state,directoryNodeId),affectedNodeIds:[directoryNodeId],path,projectionChanged:this.isDirectoryProjectionVisible(directoryNodeId)})))})}beginChildLoad(path){return withBenchmarkPhase(this.#state.instrumentation,"store.beginChildLoad",()=>{const directoryNodeId=this.requireDirectoryNodeId(path),previousVisibleCount=getVisibleCount(this.#state),attempt=beginDirectoryLoad(this.#state,directoryNodeId);return recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,createBeginChildLoadEvent({affectedAncestorIds:collectAncestorIds(this.#state,directoryNodeId),affectedNodeIds:[directoryNodeId],attemptId:attempt.attemptId,path,projectionChanged:this.isDirectoryProjectionVisible(directoryNodeId),reused:attempt.reused}))),attempt})}applyChildPatch(attempt,patch){return withBenchmarkPhase(this.#state.instrumentation,"store.applyChildPatch",()=>{const directoryNodeId=this.resolveActiveDirectoryNodeId(attempt.nodeId);if(directoryNodeId==null||getDirectoryLoadState(this.#state,directoryNodeId)!=="loading"||!isDirectoryLoadAttemptCurrent(this.#state,directoryNodeId,attempt.attemptId))return!1;const directoryPath=materializeNodePath(this.#state,directoryNodeId);this.validateChildPatch(directoryPath,patch);const previousVisibleCount=getVisibleCount(this.#state),childEvents=[];for(const operation of patch.operations){assertOperationTargetsDirectory(directoryPath,operation);const operationVisibleCount=getVisibleCount(this.#state);switch(operation.type){case"add":childEvents.push(finalizeEvent(this.#state,operationVisibleCount,addPath(this.#state,operation.path)));break;case"remove":childEvents.push(finalizeEvent(this.#state,operationVisibleCount,removePath(this.#state,operation.path,{recursive:operation.recursive})));break;case"move":{const event=movePath(this.#state,operation.from,operation.to,{collision:operation.collision});event!=null&&childEvents.push(finalizeEvent(this.#state,operationVisibleCount,event));break}}}const projectionChanged=childEvents.some(event=>event.projectionChanged)||this.isDirectoryProjectionVisible(directoryNodeId);return recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,createApplyChildPatchEvent({affectedAncestorIds:collectAncestorIds(this.#state,directoryNodeId),affectedNodeIds:[directoryNodeId],attemptId:attempt.attemptId,childEvents,path:materializeNodePath(this.#state,directoryNodeId),projectionChanged}))),!0})}completeChildLoad(attempt){return withBenchmarkPhase(this.#state.instrumentation,"store.completeChildLoad",()=>{const directoryNodeId=this.resolveActiveDirectoryNodeId(attempt.nodeId);if(directoryNodeId==null)return!1;const previousVisibleCount=getVisibleCount(this.#state),applied=completeDirectoryLoad(this.#state,directoryNodeId,attempt.attemptId);return recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,createCompleteChildLoadEvent({affectedAncestorIds:collectAncestorIds(this.#state,directoryNodeId),affectedNodeIds:[directoryNodeId],attemptId:attempt.attemptId,path:materializeNodePath(this.#state,directoryNodeId),projectionChanged:this.isDirectoryProjectionVisible(directoryNodeId),stale:!applied}))),applied})}failChildLoad(attempt,errorMessage){return withBenchmarkPhase(this.#state.instrumentation,"store.failChildLoad",()=>{const directoryNodeId=this.resolveActiveDirectoryNodeId(attempt.nodeId);if(directoryNodeId==null)return!1;const previousVisibleCount=getVisibleCount(this.#state),applied=failDirectoryLoad(this.#state,directoryNodeId,attempt.attemptId,errorMessage);return recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,createFailChildLoadEvent({affectedAncestorIds:collectAncestorIds(this.#state,directoryNodeId),affectedNodeIds:[directoryNodeId],attemptId:attempt.attemptId,errorMessage,path:materializeNodePath(this.#state,directoryNodeId),projectionChanged:this.isDirectoryProjectionVisible(directoryNodeId),stale:!applied}))),applied})}cleanup(options={}){return withBenchmarkPhase(this.#state.instrumentation,"store.cleanup",()=>{if(this.#state.transactionStack.length>0)throw new Error("Cleanup cannot run during an open batch or transaction.");if(hasActiveCleanupBlockingLoads(this.#state))throw new Error("Cleanup cannot run while directory loads are active.");const previousVisibleCount=getVisibleCount(this.#state),result=cleanupPathStoreState(this.#state,options.mode??"stable");return recordEvent(this.#state,finalizeEvent(this.#state,previousVisibleCount,createCleanupEvent({...result,affectedAncestorIds:[],affectedNodeIds:[],projectionChanged:result.idsPreserved===!1}))),result})}getNodeCount(){return this.#state.activeNodeCount}initializeExpandedPaths(expandedPaths){if(expandedPaths==null||expandedPaths.length===0)return 0;let expandedDirectoryCount=0;const previousChildOffsets=[],previousNodeIds=[];let previousEndIndex=0,previousPath=null;const segmentTable=this.#state.snapshot.segmentTable,segmentValues=segmentTable.valueById,nodes=this.#state.snapshot.nodes,targetSegmentSortKeyCache=new Map;for(const path of expandedPaths){previousPath!=null&&path<previousPath&&(previousPath=null,previousEndIndex=0,previousChildOffsets.length=0,previousNodeIds.length=0);const endIndex=path.length>0&&path.charCodeAt(path.length-1)===47?path.length-1:path.length;if(endIndex===0){previousPath=path,previousEndIndex=endIndex,previousChildOffsets.length=0,previousNodeIds.length=0;continue}let sharedDepth=0,unsharedSegmentStart=0;if(previousPath!=null){const compareLength=Math.min(endIndex,previousEndIndex);let prefixMatched=!0;for(let charIndex=0;charIndex<compareLength;charIndex+=1){const charCode=path.charCodeAt(charIndex);if(charCode!==previousPath.charCodeAt(charIndex)){prefixMatched=!1;break}charCode===47&&(sharedDepth+=1,unsharedSegmentStart=charIndex+1)}prefixMatched&&(compareLength===previousEndIndex&&endIndex>compareLength&&path.charCodeAt(compareLength)===47?(sharedDepth+=1,unsharedSegmentStart=compareLength+1):compareLength===endIndex&&previousEndIndex>compareLength&&previousPath.charCodeAt(compareLength)===47&&(sharedDepth+=1,unsharedSegmentStart=endIndex+1)),sharedDepth=Math.min(sharedDepth,previousNodeIds.length)}let currentDirectoryId=sharedDepth===0?this.#state.snapshot.rootId:previousNodeIds[sharedDepth-1]??this.#state.snapshot.rootId,resolvedDepth=sharedDepth,foundDirectory=!0,segmentStart=unsharedSegmentStart;for(;segmentStart<=endIndex;){const slashIndex=path.indexOf("/",segmentStart),segmentEnd=slashIndex===-1||slashIndex>endIndex?endIndex:slashIndex,segment=path.slice(segmentStart,segmentEnd),childIds=getDirectoryIndex(this.#state,currentDirectoryId).childIds,searchStartIndex=resolvedDepth===sharedDepth?previousChildOffsets[resolvedDepth]??0:0;let nextChildOffset=searchStartIndex,nextNodeId;const targetSegmentSortKey=targetSegmentSortKeyCache.get(segment)??createSegmentSortKey(segment);targetSegmentSortKeyCache.set(segment,targetSegmentSortKey);const searchForSegment=(startIndex,endIndex2)=>{for(nextChildOffset=startIndex;nextChildOffset<endIndex2;nextChildOffset+=1){const candidateNodeId=childIds[nextChildOffset],candidateNode=nodes[candidateNodeId],candidateSegment=segmentValues[candidateNode.nameId];if(candidateSegment===segment)return nextNodeId=candidateNodeId,!0;const orderComparison=compareSegmentSortKeys(getSegmentSortKey(segmentTable,candidateNode.nameId),targetSegmentSortKey);if(orderComparison>0||orderComparison===0&&candidateSegment>segment)return!1}return!1};if(!searchForSegment(searchStartIndex,childIds.length)&&searchStartIndex>0&&searchForSegment(0,searchStartIndex),nextNodeId===void 0){foundDirectory=!1;break}if(!isDirectoryNode(requireNode(this.#state,nextNodeId))){foundDirectory=!1;break}if(previousChildOffsets[resolvedDepth]=nextChildOffset,previousNodeIds[resolvedDepth]=nextNodeId,currentDirectoryId=nextNodeId,resolvedDepth+=1,segmentEnd===endIndex)break;segmentStart=segmentEnd+1}if(previousPath=path,previousEndIndex=endIndex,previousChildOffsets.length=resolvedDepth,previousNodeIds.length=resolvedDepth,!foundDirectory){previousPath=null,previousEndIndex=0,previousChildOffsets.length=0,previousNodeIds.length=0;continue}for(let depthIndex=sharedDepth;depthIndex<resolvedDepth;depthIndex+=1){const directoryNodeId=previousNodeIds[depthIndex];if(directoryNodeId==null)continue;const directoryNode=requireNode(this.#state,directoryNodeId);isDirectoryExpanded(this.#state,directoryNodeId,directoryNode)||(setDirectoryExpanded(this.#state,directoryNodeId,!0,directoryNode),expandedDirectoryCount+=1)}}return expandedDirectoryCount}hasAllDirectoriesExpanded(){for(const directoryNodeId of this.#state.snapshot.directories.keys()){if(directoryNodeId===this.#state.snapshot.rootId)continue;const directoryNode=requireNode(this.#state,directoryNodeId);if(!isDirectoryExpanded(this.#state,directoryNodeId,directoryNode))return!1}return!0}requireDirectoryNodeId(path){const directoryNodeId=findNodeId(this.#state,path);if(directoryNodeId==null)throw new Error(`Path does not exist: "${path}"`);if(!isDirectoryNode(requireNode(this.#state,directoryNodeId)))throw new Error(`Path is not a directory: "${path}"`);return directoryNodeId}resolveActiveDirectoryNodeId(directoryNodeId){try{if(!isDirectoryNode(requireNode(this.#state,directoryNodeId)))throw new Error(`Node is not a directory: ${String(directoryNodeId)}`);return directoryNodeId}catch{return null}}isDirectoryProjectionVisible(directoryNodeId){let currentNodeId=directoryNodeId;for(;currentNodeId!==this.#state.snapshot.rootId;){const parentId=requireNode(this.#state,currentNodeId).parentId;if(parentId!==this.#state.snapshot.rootId){const parentNode=requireNode(this.#state,parentId),flattenedChildDirectoryId=getFlattenedChildDirectoryId(this.#state,parentId);if(!isDirectoryExpanded(this.#state,parentId,parentNode)&&flattenedChildDirectoryId!==currentNodeId)return!1}currentNodeId=parentId}return!0}validateChildPatch(directoryPath,patch){new PathStore2({paths:this.list(directoryPath),presorted:!0,sort:this.#state.snapshot.options.sort}).batch(patch.operations)}};function assertOperationTargetsDirectory(directoryPath,operation){switch(operation.type){case"add":case"remove":if(!operation.path.startsWith(directoryPath)||operation.path===directoryPath)throw new Error(`Child patch operation must stay within ${directoryPath}: "${operation.path}"`);break;case"move":if(!operation.from.startsWith(directoryPath)||!operation.to.startsWith(directoryPath)||operation.from===directoryPath||operation.to===directoryPath)throw new Error(`Child patch move must stay within ${directoryPath}: "${operation.from}" -> "${operation.to}"`);break}}const FILE_TREE_DENSITY_PRESETS={compact:{itemHeight:24,factor:.8},default:{itemHeight:30,factor:1},relaxed:{itemHeight:36,factor:1.2}};function resolveFileTreeDensity(density,explicitItemHeight){if(typeof density=="number")return{itemHeight:explicitItemHeight??FILE_TREE_DENSITY_PRESETS.default.itemHeight,factor:density};const preset=FILE_TREE_DENSITY_PRESETS[density??"default"];return{itemHeight:explicitItemHeight??preset.itemHeight,factor:preset.factor}}const FILE_TREE_DEFAULT_ITEM_HEIGHT=FILE_TREE_DENSITY_PRESETS.default.itemHeight;var style_default=`@layer base {
2
2
  :host {
3
3
  --trees-accent: var(--trees-accent-override, #009fff);
4
4
  --trees-fg: var(--trees-fg-override, var(--trees-theme-sidebar-fg, light-dark(#6c6c71, #adadb1)));
@@ -1096,12 +1096,12 @@ import{j as jsxRuntimeExports,r as reactExports,c as reactDomExports}from"./vend
1096
1096
  }`}function wrapUnsafeCSS(unsafeCSS){return`${LAYER_ORDER}
1097
1097
  @layer unsafe {
1098
1098
  ${unsafeCSS}
1099
- }`}const measuredGutterCache=new WeakMap;function measureScrollbarGutter(shadowRoot){const cachedScrollbarGutter=measuredGutterCache.get(shadowRoot);if(cachedScrollbarGutter!=null)return cachedScrollbarGutter;const wrapper=document.createElement("div");wrapper.setAttribute(FILE_TREE_SCROLLBAR_MEASURE_ATTRIBUTE,"true");const child=document.createElement("div");child.style.position="relative",child.style.height="200%",wrapper.appendChild(child),shadowRoot.appendChild(wrapper);const measuredGutter=Math.max(wrapper.offsetWidth-wrapper.clientWidth,0);return wrapper.remove(),measuredGutterCache.set(shadowRoot,measuredGutter),measuredGutter}function ensureMeasuredScrollbarGutter(host,shadowRoot){if(!host.isConnected)return;const measuredScrollbarGutter=measureScrollbarGutter(shadowRoot);if(measuredScrollbarGutter==null)return;const existing=shadowRoot.querySelector(`style[${FILE_TREE_SCROLLBAR_GUTTER_STYLE_ATTRIBUTE}]`),styleEl=existing instanceof HTMLStyleElement?existing:document.createElement("style");existing instanceof HTMLStyleElement||(styleEl.setAttribute(FILE_TREE_SCROLLBAR_GUTTER_STYLE_ATTRIBUTE,""),shadowRoot.appendChild(styleEl)),styleEl.textContent=`:host { ${FILE_TREE_SCROLLBAR_GUTTER_MEASURED_PROPERTY}: ${measuredScrollbarGutter}px; }`}let sheet;function ensureFileTreeStyles(shadowRoot){if(typeof CSSStyleSheet<"u"&&typeof CSSStyleSheet.prototype.replaceSync=="function"&&"adoptedStyleSheets"in shadowRoot){sheet==null&&(sheet=new CSSStyleSheet,sheet.replaceSync(wrapCoreCSS(style_default)));let adopted=!1;try{shadowRoot.adoptedStyleSheets=[sheet],adopted=!0}catch{}if(adopted){shadowRoot.querySelector(`style[${FILE_TREE_STYLE_ATTRIBUTE}]`)?.remove();return}}if(shadowRoot.querySelector("style[data-file-tree-style]")==null){const styleEl=document.createElement("style");styleEl.setAttribute(FILE_TREE_STYLE_ATTRIBUTE,""),styleEl.textContent=wrapCoreCSS(style_default),shadowRoot.prepend(styleEl)}}function prepareFileTreeShadowRoot(host,shadowRoot){adoptDeclarativeShadowDom(host,shadowRoot),ensureFileTreeStyles(shadowRoot),ensureMeasuredScrollbarGutter(host,shadowRoot)}function adoptDeclarativeShadowDom(host,shadowRoot){const template=host.querySelector('template[shadowrootmode="open"], template[data-file-tree-shadowrootmode="open"]');template instanceof HTMLTemplateElement&&(shadowRoot.childNodes.length>0||(shadowRoot.appendChild(template.content.cloneNode(!0)),template.hasAttribute("shadowrootmode")&&template.remove()))}if(typeof HTMLElement<"u"&&customElements.get("file-tree-container")==null){class FileTreeContainer extends HTMLElement{constructor(){super()}connectedCallback(){const shadowRoot=this.shadowRoot??this.attachShadow({mode:"open"});prepareFileTreeShadowRoot(this,shadowRoot)}}if(customElements.define(FILE_TREE_TAG_NAME,FileTreeContainer),typeof document<"u")for(const el of Array.from(document.querySelectorAll(FILE_TREE_TAG_NAME)))el instanceof HTMLElement&&prepareFileTreeShadowRoot(el,el.shadowRoot??el.attachShadow({mode:"open"}))}const getSelectionPath=path=>path.startsWith("f::")?path.slice(3):path;function splitPath(path){const separatorIndex=path.lastIndexOf("/");return separatorIndex<0?{parentPath:"",baseName:path}:{parentPath:path.slice(0,separatorIndex),baseName:path.slice(separatorIndex+1)}}function joinPath(parentPath,baseName){return parentPath===""?baseName:`${parentPath}/${baseName}`}function renameFileTreePaths({files,path,isFolder,nextBasename}){const sourcePath=getSelectionPath(path),trimmedBasename=nextBasename.trim();if(trimmedBasename.length===0)return{error:"Name cannot be empty."};if(trimmedBasename.includes("/"))return{error:'Name cannot include "/".'};const{parentPath,baseName}=splitPath(sourcePath);if(trimmedBasename===baseName)return{nextFiles:files,sourcePath,destinationPath:sourcePath,isFolder};const destinationPath=joinPath(parentPath,trimmedBasename),nextFiles=new Array(files.length),seenPaths=new Set;if(!isFolder){const destinationPrefix2=`${destinationPath}/`;let renamed=!1;for(let index=0;index<files.length;index++){const file=files[index];if(file!==sourcePath&&file.startsWith(destinationPrefix2))return{error:`"${destinationPath}" already exists.`};const nextFile=file===sourcePath?destinationPath:file;if(seenPaths.has(nextFile))return{error:`"${destinationPath}" already exists.`};seenPaths.add(nextFile),nextFiles[index]=nextFile,file===sourcePath&&(renamed=!0)}return renamed?{nextFiles,sourcePath,destinationPath,isFolder}:{error:"Could not find the selected file to rename."}}const sourcePrefix=`${sourcePath}/`,destinationPrefix=`${destinationPath}/`;let renamedPathCount=0;for(let index=0;index<files.length;index++){const file=files[index],isWithinRenamedFolder=file===sourcePath||file.startsWith(sourcePrefix);if(!isWithinRenamedFolder&&(file===destinationPath||file.startsWith(destinationPrefix)))return{error:`"${destinationPath}" already exists.`};const nextFile=isWithinRenamedFolder?`${destinationPath}${file.slice(sourcePath.length)}`:file;if(seenPaths.has(nextFile))return{error:`"${destinationPath}" already exists.`};seenPaths.add(nextFile),nextFiles[index]=nextFile,isWithinRenamedFolder&&renamedPathCount++}return renamedPathCount===0?{error:"Could not find the selected folder to rename."}:{nextFiles,sourcePath,destinationPath,isFolder}}function isCanonicalDirectoryPath$1(path){return path.endsWith("/")}function getPathBasename(path){const trimmedPath=path.endsWith("/")?path.slice(0,-1):path,lastSlashIndex=trimmedPath.lastIndexOf("/"),basename=lastSlashIndex<0?trimmedPath:trimmedPath.slice(lastSlashIndex+1);return path.endsWith("/")?`${basename}/`:basename}function normalizeDraggedPaths(paths){const uniquePaths=[],seenPaths=new Set;for(const path of paths)seenPaths.has(path)||(seenPaths.add(path),uniquePaths.push(path));const keptPaths=new Set;for(const path of uniquePaths.toSorted((left,right)=>left.length!==right.length?left.length-right.length:left.localeCompare(right))){const segments=(path.endsWith("/")?path.slice(0,-1):path).split("/");let hasSelectedAncestor=!1;for(let index=0;index<segments.length-1;index+=1){const ancestorPath=`${segments.slice(0,index+1).join("/")}/`;if(keptPaths.has(ancestorPath)){hasSelectedAncestor=!0;break}}hasSelectedAncestor||keptPaths.add(path)}return uniquePaths.filter(path=>keptPaths.has(path))}function resolveDraggedPathsForStart(path,selectedPaths){return selectedPaths.includes(path)?normalizeDraggedPaths(selectedPaths):[path]}function dropTargetsEqual(left,right){return left===right?!0:left==null||right==null?!1:left.kind===right.kind&&left.directoryPath===right.directoryPath&&left.flattenedSegmentPath===right.flattenedSegmentPath&&left.hoveredPath===right.hoveredPath}function createDropContext(draggedPaths,target){return{draggedPaths,target}}function isSelfOrDescendantDrop(draggedPaths,target){if(target.kind!=="directory"||target.directoryPath==null)return!1;for(const draggedPath of draggedPaths)if(isCanonicalDirectoryPath$1(draggedPath)&&(target.directoryPath===draggedPath||target.directoryPath.startsWith(draggedPath)))return!0;return!1}function resolveMoveDestinationPath(sourcePath,target){return target.kind==="root"||target.directoryPath==null?getPathBasename(sourcePath):target.directoryPath}function buildDropOperations(draggedPaths,target){const operations=draggedPaths.map(draggedPath=>{const destinationPath=resolveMoveDestinationPath(draggedPath,target);return destinationPath===draggedPath?null:{from:draggedPath,to:destinationPath,type:"move"}}).filter(operation=>operation!=null);return operations.length===0?null:{operations,result:{draggedPaths,operation:operations.length===1?"move":"batch",target}}}function haveMatchingPaths(currentPaths,preparedPaths){if(currentPaths===preparedPaths)return!0;if(currentPaths.length!==preparedPaths.length)return!1;for(let index=0;index<currentPaths.length;index+=1)if(currentPaths[index]!==preparedPaths[index])return!1;return!0}function resolveFileTreeInput(options,context,sort){const{paths,preparedInput}=options;if(preparedInput==null){if(paths==null)throw new Error("FileTree requires paths or preparedInput");return{paths,preparedInput:void 0}}const preparedPaths=preparedInput.paths;if(paths==null)return{paths:preparedPaths,preparedInput};if(!haveMatchingPaths(PathStore.preparePaths(paths,sort==null?{}:{sort}),preparedPaths))throw new Error(`FileTree ${context} received paths and preparedInput for different path lists`);return{paths:preparedPaths,preparedInput}}function isPathMutationEvent(event){return event.operation==="add"||event.operation==="remove"||event.operation==="move"||event.operation==="batch"}function remapMovedPath(path,fromPath,toPath){if(path===fromPath)return toPath;const descendantPrefix=fromPath.endsWith("/")?fromPath:`${fromPath}/`;return path.startsWith(descendantPrefix)?`${toPath.endsWith("/")?toPath:`${toPath}/`}${path.slice(descendantPrefix.length)}`:path}function isPathRemoved(path,removedPath){if(path===removedPath)return!0;const descendantPrefix=removedPath.endsWith("/")?removedPath:`${removedPath}/`;return path.startsWith(descendantPrefix)}function remapPathThroughMutation(path,event,preserveRemovedPath=!1){if(path==null)return null;switch(event.operation){case"add":case"expand":case"collapse":case"mark-directory-unloaded":case"begin-child-load":case"apply-child-patch":case"complete-child-load":case"fail-child-load":case"cleanup":return path;case"remove":return isPathRemoved(path,event.path)?preserveRemovedPath?path:null:path;case"move":return remapMovedPath(path,event.from,event.to);case"batch":{let nextPath=path;for(const childEvent of event.events)if(nextPath=remapPathThroughMutation(nextPath,childEvent,preserveRemovedPath),nextPath==null)return null;return nextPath}}}function createMutationInvalidation(event){return{canonicalChanged:event.canonicalChanged,projectionChanged:event.projectionChanged,visibleCountDelta:event.visibleCountDelta}}function toTreesMutationSemanticEvent(event){switch(event.operation){case"add":return{...createMutationInvalidation(event),operation:"add",path:event.path};case"remove":return{...createMutationInvalidation(event),operation:"remove",path:event.path,recursive:event.recursive};case"move":return{...createMutationInvalidation(event),from:event.from,operation:"move",to:event.to}}}function toTreesBatchEvent(event){return{...createMutationInvalidation(event),events:event.events.filter(childEvent=>childEvent.operation==="add"||childEvent.operation==="remove"||childEvent.operation==="move").map(childEvent=>toTreesMutationSemanticEvent(childEvent)),operation:"batch"}}function toTreesMutationEvent(event){switch(event.operation){case"add":case"remove":case"move":return toTreesMutationSemanticEvent(event);case"batch":return toTreesBatchEvent(event);default:return null}}function arePathSetsEqual(currentPaths,nextPaths){if(currentPaths.size!==nextPaths.length)return!1;for(const path of nextPaths)if(!currentPaths.has(path))return!1;return!0}function getAncestorDirectoryPaths$1(path){const normalizedPath=path.endsWith("/")?path.slice(0,-1):path;if(normalizedPath.length===0)return[];const segments=normalizedPath.split("/");return segments.slice(0,-1).map((_2,index)=>`${segments.slice(0,index+1).join("/")}/`)}function getImmediateParentPath(path){return getAncestorDirectoryPaths$1(path).at(-1)??null}function getSiblingComparisonKey(path,parentPath){return parentPath==null?path:path.startsWith(parentPath)?path.slice(parentPath.length):path}function isCanonicalDirectoryPath(path){return path.endsWith("/")}const toLowerCaseSearchPath=path=>path.toLowerCase();function getRenameLeafName(path){const normalizedPath=path.endsWith("/")?path.slice(0,-1):path,separatorIndex=normalizedPath.lastIndexOf("/");return separatorIndex<0?normalizedPath:normalizedPath.slice(separatorIndex+1)}function toRenameHelperPath(path){return path.endsWith("/")?path.slice(0,-1):path}function toCanonicalRenamePath(path,isFolder){return isFolder&&!path.endsWith("/")?`${path}/`:path}const normalizeSearchQuery=value=>{const trimmedValue=value.trim();return trimmedValue.length===0?"":(trimmedValue.includes("\\")?trimmedValue.replaceAll("\\","/"):trimmedValue).toLowerCase()},FILE_TREE_RENAME_VIEW=Symbol("FILE_TREE_RENAME_VIEW"),INITIAL_PROJECTION_ROW_LIMIT=512,CONTEXT_VISIBLE_ROW_RANGE_LIMIT=512;function normalizeScrollOffset(offset){return offset==="top"||offset==="center"?offset:"nearest"}function resolveFocusedIndexByLookup(rowCount,getVisibleIndex,candidatePath){if(rowCount===0)return-1;if(candidatePath!=null){const directIndex=getVisibleIndex(candidatePath);if(directIndex!=null)return directIndex;const ancestorPaths=getAncestorDirectoryPaths$1(candidatePath);for(let index=ancestorPaths.length-1;index>=0;index-=1){const ancestorPath=ancestorPaths[index];if(ancestorPath==null)continue;const ancestorIndex=getVisibleIndex(ancestorPath);if(ancestorIndex!=null)return ancestorIndex}}return 0}function createVisibleProjection(projection,focusedPathCandidate,resolveVisibleIndexByPath){if(projection.paths.length===0)return{focusedIndex:-1,getParentIndex:projection.getParentIndex,paths:projection.paths,posInSetByIndex:projection.posInSetByIndex,setSizeByIndex:projection.setSizeByIndex};if(focusedPathCandidate==null)return{focusedIndex:0,getParentIndex:projection.getParentIndex,paths:projection.paths,posInSetByIndex:projection.posInSetByIndex,setSizeByIndex:projection.setSizeByIndex};const getVisibleIndex=resolveVisibleIndexByPath??(path=>projection.visibleIndexByPath.get(path)??null);return{focusedIndex:resolveFocusedIndexByLookup(projection.paths.length,getVisibleIndex,focusedPathCandidate),getParentIndex:projection.getParentIndex,paths:projection.paths,posInSetByIndex:projection.posInSetByIndex,setSizeByIndex:projection.setSizeByIndex}}var FileTreeController=class FileTreeController2{static{Object.defineProperty(FileTreeController2.prototype,FILE_TREE_RENAME_VIEW,{configurable:!0,value(){return{cancel:()=>{this.#cancelRenaming()},commit:()=>{this.#completeRenaming()},getPath:()=>this.#renamingPath,getValue:()=>this.#renamingValue,isActive:()=>this.#renamingPath!=null,setValue:value=>{this.#setRenamingValue(value)}}},writable:!0})}#baseOptions;#listeners=new Set;#mutationListeners=new Map;#dragAndDropConfig=null;#dragSession=null;#ancestorIndicesByIndex=new Map;#ancestorPathsByIndex=new Map;#focusedIndex=-1;#focusedPath=null;#hasFullProjection=!1;#getParentIndexForVisibleRow=_index=>-1;#itemHandles=new Map;#knownDirectoryPaths=null;#knownDirectoryPathsLowerCase=null;#knownPaths=null;#listedPaths=null;#listedPathsLowerCase=null;#onRename;#onRenameError;#onSearchChange;#projectionPaths=[];#projectionPosInSetByIndex=new Int32Array(0);#projectionSetSizeByIndex=new Int32Array(0);#renameCanRename=void 0;#renameEnabled=!1;#renamingPath=null;#renamingValue="";#removeRenamingPathIfCanceled=!1;#searchMatchPathSet=new Set;#searchMatchingPaths=[];#searchMode;#searchPreviousExpandedPaths=null;#searchValue=null;#searchVisiblePathSet=null;#searchVisibleIndexByPath=null;#searchVisibleIndices=null;#searchVisiblePaths=null;#scrollRequest=null;#scrollRequestId=0;#selectionAnchorPath=null;#selectedPaths=new Set;#selectionVersion=0;#store;#storeVisibleCount=0;#suppressStoreNotifications=!1;#visibleCount=0;#unsubscribe;constructor(options){const{dragAndDrop,fileTreeSearchMode,initialSearchQuery,initialSelectedPaths,renaming,onSearchChange,paths,preparedInput,...baseOptions}=options,resolvedInput=resolveFileTreeInput({paths,preparedInput},"constructor",baseOptions.sort);this.#baseOptions=baseOptions,dragAndDrop!=null&&dragAndDrop!==!1&&(this.#dragAndDropConfig=dragAndDrop===!0?{}:dragAndDrop),this.#renameEnabled=renaming!=null&&renaming!==!1,renaming!=null&&renaming!==!1&&renaming!==!0&&(this.#renameCanRename=renaming.canRename,this.#onRenameError=renaming.onError,this.#onRename=renaming.onRename),this.#onSearchChange=onSearchChange,this.#searchMode=fileTreeSearchMode??"hide-non-matches",this.#store=this.#createStore(resolvedInput.paths,resolvedInput.preparedInput);const resolvedInitialSelectedPaths=initialSelectedPaths?.map(path=>this.#resolveSelectionPath(path)).filter(resolved=>resolved!=null)??[],initialFocusedPath=resolvedInitialSelectedPaths.at(-1)??null;resolvedInitialSelectedPaths.length>0&&(this.#selectedPaths=new Set(resolvedInitialSelectedPaths),this.#selectionAnchorPath=initialFocusedPath,this.#selectionVersion=1),this.#rebuildVisibleProjection(initialFocusedPath,!1),initialSearchQuery!=null&&this.#setSearchState(initialSearchQuery,!1),this.#unsubscribe=this.#subscribe()}destroy(){this.#unsubscribe?.(),this.#unsubscribe=null,this.#mutationListeners.clear(),this.#listeners.clear(),this.#itemHandles.clear(),this.#dragSession=null,this.#invalidateKnownPathCaches()}focusFirstItem(){this.#getCurrentVisiblePaths().length>0&&this.#setFocusedIndex(0)}focusLastItem(){this.#visibleCount<=0||(this.#ensureFullProjection(),this.#setFocusedIndex(this.#visibleCount-1))}focusNextItem(){this.#moveFocus(1)}focusParentItem(){if(this.#focusedPath==null)return;const parentPath=getImmediateParentPath(this.#focusedPath);if(parentPath==null)return;const nextFocusedIndex=this.#resolveFocusedIndex(parentPath);nextFocusedIndex>=0&&this.#setFocusedIndex(nextFocusedIndex)}focusPath(path){const resolvedPath=this.#store.getPathInfo(path)?.path??null;if(resolvedPath==null)return;this.#ensureFullProjection();const nextFocusedIndex=this.#resolveFocusedIndex(resolvedPath);nextFocusedIndex>=0&&this.#setFocusedIndex(nextFocusedIndex)}scrollToPath(path,options){const resolvedPath=this.#store.getPathInfo(path)?.path??null;if(resolvedPath==null)return;this.#ensureFullProjection();const targetIndex=this.#getExactCurrentVisibleIndexByPath(resolvedPath);targetIndex<0||this.#resolveVisiblePathAtIndex(targetIndex)!=null&&(options?.focus!==!1&&this.#setFocusedIndex(targetIndex,!1),this.#scrollRequest={id:this.#scrollRequestId+=1,offset:normalizeScrollOffset(options?.offset),visibleIndex:targetIndex},this.#emit())}focusMountedPathFromInput(path){const resolvedPath=this.#store.getPathInfo(path)?.path??null;if(resolvedPath==null)return;const nextFocusedIndex=this.#resolveFocusedIndex(resolvedPath);nextFocusedIndex>=0&&this.#setFocusedIndex(nextFocusedIndex)}focusNearestPath(path){const nextPath=this.resolveNearestVisiblePath(path);if(nextPath==null)return null;const nextFocusedIndex=this.#resolveFocusedIndex(nextPath);return nextFocusedIndex>=0?(this.#setFocusedIndex(nextFocusedIndex),this.#getCurrentVisiblePaths()[nextFocusedIndex]??nextPath):null}focusPreviousItem(){this.#moveFocus(-1)}getFocusedIndex(){return this.#focusedIndex}getFocusedItem(){return this.#focusedPath==null?null:this.#getOrCreateItemHandle(this.#focusedPath)}getFocusedPath(){return this.#focusedPath}getScrollRequest(){return this.#scrollRequest}clearScrollRequest(id){this.#scrollRequest?.id===id&&(this.#scrollRequest=null)}resolveNearestVisiblePath(path){const currentVisiblePaths=this.#getCurrentVisiblePaths();if(this.#visibleCount===0)return null;if(path==null)return this.#focusedPath??currentVisiblePaths[0]??null;const resolvedPath=this.#store.getPathInfo(path)?.path??path,directIndex=this.#resolveFocusedIndex(resolvedPath);if(directIndex>=0)return currentVisiblePaths[directIndex]??resolvedPath;const siblingPath=this.#findNearestVisibleSiblingPath(resolvedPath);return siblingPath??this.#focusedPath??currentVisiblePaths[0]??null}getSelectedPaths(){return[...this.#selectedPaths]}getSelectionVersion(){return this.#selectionVersion}getVisibleCount(){return this.#visibleCount}getVisibleRows(start,end){if(end<start||this.#visibleCount===0)return[];const boundedStart=Math.max(0,start),boundedEnd=Math.min(this.#visibleCount-1,end);if(boundedEnd<boundedStart)return[];const boundedLength=boundedEnd-boundedStart+1;if(this.#searchVisibleIndices==null&&!this.#hasFullProjection&&boundedEnd>=this.#projectionPaths.length&&boundedLength<=CONTEXT_VISIBLE_ROW_RANGE_LIMIT){const rows=[];for(let index=boundedStart;index<=boundedEnd;index+=1){const context=this.#store.getVisibleRowContext(index);if(context==null)break;rows.push(this.#createVisibleRowFromContext(context))}return rows}if(!this.#hasFullProjection&&boundedEnd>=this.#projectionPaths.length&&this.#ensureFullProjection(),this.#searchVisibleIndices!=null){const projectionIndices=Array.from({length:boundedEnd-boundedStart+1},(_2,visibleOffset)=>this.#getProjectionIndexFromVisibleIndex(boundedStart+visibleOffset)),visibleRowByProjectionIndex=new Map;let runStartIndex=projectionIndices[0]??-1,runEndIndex=runStartIndex;for(let index=1;index<=projectionIndices.length;index+=1){const projectionIndex=projectionIndices[index];if(projectionIndex!=null&&projectionIndex===runEndIndex+1){runEndIndex=projectionIndex;continue}if(runStartIndex>=0&&this.#store.getVisibleSlice(runStartIndex,runEndIndex).forEach((row,offset)=>{visibleRowByProjectionIndex.set(runStartIndex+offset,row)}),projectionIndex==null){runStartIndex=-1,runEndIndex=-1;continue}runStartIndex=projectionIndex,runEndIndex=projectionIndex}return Array.from({length:boundedEnd-boundedStart+1},(_2,visibleOffset)=>{const visibleIndex=boundedStart+visibleOffset,projectionIndex=this.#getProjectionIndexFromVisibleIndex(visibleIndex),row=visibleRowByProjectionIndex.get(projectionIndex),projectionPath=this.#projectionPaths[projectionIndex];if(row==null||projectionPath==null)throw new Error(`Missing projection row for filtered visible index ${String(visibleIndex)}`);return this.#createVisibleRow(row,visibleIndex,projectionIndex,{ancestorPaths:this.#getAncestorPaths(projectionIndex),path:projectionPath})})}return this.#store.getVisibleSlice(boundedStart,boundedEnd).map((row,offset)=>{const index=boundedStart+offset,projectionPath=this.#projectionPaths[index];if(projectionPath==null)throw new Error(`Missing projection path for visible index ${String(index)}`);return this.#createVisibleRow(row,index,index,{ancestorPaths:this.#getAncestorPaths(index),path:projectionPath})})}getStickyRowCandidates(scrollTop,itemHeight){if(this.#searchVisibleIndices!=null)return null;if(this.#visibleCount===0||scrollTop<=0||itemHeight<=0)return[];const stickyRows=[];for(let slotDepth=0;slotDepth<this.#visibleCount;slotDepth+=1){const slotTop=scrollTop+slotDepth*itemHeight,thresholdIndex=Math.min(this.#visibleCount-1,Math.floor(slotTop/itemHeight)),candidateContext=this.#getStickyCandidateContextAt(thresholdIndex,slotDepth)??(thresholdIndex>0?this.#getStickyCandidateContextAt(thresholdIndex-1,slotDepth):void 0);if(candidateContext==null)break;stickyRows.push({row:this.#createVisibleRowFromContext(candidateContext),subtreeEndIndex:candidateContext.subtreeEndIndex})}return stickyRows}getItem(path){const itemInfo=this.#store.getPathInfo(path);return itemInfo==null?null:this.#getOrCreateItemHandle(itemInfo.path,itemInfo)}resolveMountedDirectoryPathFromInput(path){const pathInfo=this.#store.getPathInfo(path);return pathInfo?.kind==="directory"?pathInfo.path:null}toggleMountedDirectoryFromInput(path){const directoryPath=this.resolveMountedDirectoryPathFromInput(path);directoryPath!=null&&this.#toggleDirectory(directoryPath)}selectAllVisiblePaths(){this.#ensureFullProjection();const nextSelectedPaths=[...this.#getCurrentVisiblePaths()];this.#applySelection(nextSelectedPaths,this.#focusedPath??this.#selectionAnchorPath)}selectOnlyPath(path){const resolvedPath=this.#resolveSelectionPath(path);resolvedPath!=null&&this.#applySelection([resolvedPath],resolvedPath)}selectOnlyMountedPathFromInput(path){this.#applySelection([path],path)}selectPath(path){const resolvedPath=this.#resolveSelectionPath(path);resolvedPath==null||this.#selectedPaths.has(resolvedPath)||this.#applySelection([...this.#selectedPaths,resolvedPath])}deselectPath(path){const resolvedPath=this.#resolveSelectionPath(path);resolvedPath==null||!this.#selectedPaths.has(resolvedPath)||this.#applySelection([...this.#selectedPaths].filter(selectedPath=>selectedPath!==resolvedPath))}toggleFocusedSelection(){this.#focusedPath!=null&&this.togglePathSelectionFromInput(this.#focusedPath)}togglePathSelection(path){const resolvedPath=this.#resolveSelectionPath(path);if(resolvedPath!=null){if(this.#selectedPaths.has(resolvedPath)){this.deselectPath(resolvedPath);return}this.selectPath(resolvedPath)}}togglePathSelectionFromInput(path){const resolvedPath=this.#resolveSelectionPath(path);if(resolvedPath!=null){if(this.#selectedPaths.has(resolvedPath)){this.#applySelection([...this.#selectedPaths].filter(selectedPath=>selectedPath!==resolvedPath),resolvedPath);return}this.#applySelection([...this.#selectedPaths,resolvedPath],resolvedPath)}}selectPathRange(path,unionSelection){const resolvedPath=this.#resolveSelectionPath(path);if(resolvedPath==null)return;this.#ensureFullProjection();const anchorPath=this.#selectionAnchorPath,anchorIndex=anchorPath==null?-1:this.#getVisibleIndexByPath(anchorPath),targetIndex=this.#getVisibleIndexByPath(resolvedPath);if(anchorIndex===-1||targetIndex===-1){const nextSelectedPaths2=unionSelection?[...this.#selectedPaths,resolvedPath]:[resolvedPath];this.#applySelection(nextSelectedPaths2,resolvedPath);return}const[startIndex,endIndex]=anchorIndex<=targetIndex?[anchorIndex,targetIndex]:[targetIndex,anchorIndex],rangePaths=this.#getCurrentVisiblePaths().slice(startIndex,endIndex+1),nextSelectedPaths=unionSelection?[...this.#selectedPaths,...rangePaths]:rangePaths;this.#applySelection(nextSelectedPaths,anchorPath)}extendSelectionFromFocused(offset){if(this.#focusedPath==null)return;const focusedIndex=this.#focusedIndex;if(focusedIndex===-1)return;const nextIndex=Math.min(this.#visibleCount-1,Math.max(0,focusedIndex+offset));if(nextIndex===focusedIndex)return;!this.#hasFullProjection&&nextIndex>=this.#projectionPaths.length&&this.#ensureFullProjection();const visiblePaths=this.#getCurrentVisiblePaths(),currentPath=visiblePaths[focusedIndex]??null,nextPath=visiblePaths[nextIndex]??null;if(currentPath==null||nextPath==null)return;const nextSelectedPaths=new Set(this.#selectedPaths);nextSelectedPaths.has(currentPath)&&nextSelectedPaths.has(nextPath)?nextSelectedPaths.delete(currentPath):nextSelectedPaths.add(nextPath),this.#applySelection([...nextSelectedPaths],this.#selectionAnchorPath??currentPath,!1),this.#setFocusedIndex(nextIndex)}getDragAndDropConfig(){return this.#dragAndDropConfig}isDragAndDropEnabled(){return this.#dragAndDropConfig!=null}getDragSession(){return this.#dragSession==null?null:{draggedPaths:[...this.#dragSession.draggedPaths],primaryPath:this.#dragSession.primaryPath,target:this.#dragSession.target==null?null:{...this.#dragSession.target}}}startDrag(path){if(this.#dragAndDropConfig==null)return!1;const resolvedPath=this.#resolveSelectionPath(path);if(resolvedPath==null||this.#searchValue!=null&&this.#searchValue.length>0)return!1;const selectedPaths=this.getSelectedPaths(),draggedPaths=resolveDraggedPathsForStart(resolvedPath,selectedPaths);return this.#dragAndDropConfig.canDrag?.(draggedPaths)===!1?!1:(selectedPaths.includes(resolvedPath)||this.#applySelection([resolvedPath],resolvedPath,!1),this.#focusPathWithoutEmit(resolvedPath),this.#dragSession={draggedPaths,primaryPath:resolvedPath,target:null},this.#emit(),!0)}setDragTarget(target){const dragSession=this.#dragSession;if(dragSession==null)return;let nextTarget=target;if(nextTarget!=null){const context=createDropContext(dragSession.draggedPaths,nextTarget);(isSelfOrDescendantDrop(dragSession.draggedPaths,nextTarget)||this.#dragAndDropConfig?.canDrop?.(context)===!1)&&(nextTarget=null)}dropTargetsEqual(dragSession.target,nextTarget)||(this.#dragSession={...dragSession,target:nextTarget},this.#emit())}cancelDrag(){this.#dragSession!=null&&(this.#dragSession=null,this.#emit())}completeDrag(){const dragSession=this.#dragSession;if(dragSession==null)return!1;this.#dragSession=null;const target=dragSession.target==null?null:{...dragSession.target};if(target==null)return this.#emit(),!1;const dropContext=createDropContext(dragSession.draggedPaths,target);if(isSelfOrDescendantDrop(dragSession.draggedPaths,target)||this.#dragAndDropConfig?.canDrop?.(dropContext)===!1)return this.#emit(),!1;const dropPlan=buildDropOperations(dragSession.draggedPaths,target);if(dropPlan==null)return this.#emit(),!1;try{if(dropPlan.operations.length===1){const singleOperation=dropPlan.operations[0];if(singleOperation==null||singleOperation.type!=="move")throw new Error("Expected a single move operation for one-item drops");this.#store.move(singleOperation.from,singleOperation.to,{collision:singleOperation.collision})}else this.#validateBatchDropOperations(dropPlan.operations),this.#store.batch(dropPlan.operations)}catch(error){return this.#emit(),this.#dragAndDropConfig?.onDropError?.(error instanceof Error?error.message:String(error),dropContext),!1}return this.#dragAndDropConfig?.onDropComplete?.(dropPlan.result),!0}subscribe(listener){return this.#listeners.add(listener),listener(),()=>{this.#listeners.delete(listener)}}add(path){this.#store.add(path)}remove(path,options={}){this.#store.remove(path,options)}move(fromPath,toPath,options={}){this.#store.move(fromPath,toPath,options)}batch(operations){this.#store.batch(operations)}onMutation(type,handler){const key2=type,typedHandler=handler;let listenersForType=this.#mutationListeners.get(key2);return listenersForType==null&&(listenersForType=new Set,this.#mutationListeners.set(key2,listenersForType)),listenersForType.add(typedHandler),()=>{const registeredListeners=this.#mutationListeners.get(key2);registeredListeners?.delete(typedHandler),registeredListeners?.size===0&&this.#mutationListeners.delete(key2)}}setSearch(value){this.#setSearchState(value,!0)}openSearch(initialValue=""){this.#setSearchState(initialValue,!0)}closeSearch(){this.#setSearchState(null,!0)}isSearchOpen(){return this.#searchValue!==null}getSearchValue(){return this.#searchValue??""}getSearchMatchingPaths(){return this.#searchMatchingPaths}focusNextSearchMatch(){this.#focusRelativeSearchMatch(1)}focusPreviousSearchMatch(){this.#focusRelativeSearchMatch(-1)}startRenaming(path=this.#focusedPath??"",options={}){if(!this.#renameEnabled)return!1;const itemInfo=this.#store.getPathInfo(path);if(itemInfo==null)return!1;const canonicalPath=itemInfo.path,isFolder=isCanonicalDirectoryPath(canonicalPath),publicPath=toRenameHelperPath(canonicalPath);if(this.#renameCanRename?.({isFolder,path:publicPath})===!1)return!1;for(const ancestorPath of getAncestorDirectoryPaths$1(canonicalPath))this.#store.isExpanded(ancestorPath)||this.#store.expand(ancestorPath);return this.#applySelection([canonicalPath],canonicalPath,!1),this.#searchValue!=null&&(this.#setSearchState(null,!1),this.#onSearchChange?.(this.#searchValue)),this.#focusPathWithoutEmit(canonicalPath),this.#renamingPath=canonicalPath,this.#renamingValue=getRenameLeafName(canonicalPath),this.#removeRenamingPathIfCanceled=options.removeIfCanceled??!1,this.#emit(),!0}#cancelRenaming(){if(this.#renamingPath==null)return;const renamingPath=this.#renamingPath,removePlaceholderEntry=this.#removeRenamingPathIfCanceled;if(this.#renamingPath=null,this.#renamingValue="",this.#removeRenamingPathIfCanceled=!1,removePlaceholderEntry){this.remove(renamingPath,isCanonicalDirectoryPath(renamingPath)?{recursive:!0}:void 0);return}this.#focusPathWithoutEmit(renamingPath),this.#emit()}#completeRenaming(){const renamingPath=this.#renamingPath;if(renamingPath==null)return;if(this.#removeRenamingPathIfCanceled&&this.#renamingValue.trim().length===0){this.#renamingPath=null,this.#renamingValue="",this.#removeRenamingPathIfCanceled=!1,this.remove(renamingPath,isCanonicalDirectoryPath(renamingPath)?{recursive:!0}:void 0);return}const isFolder=isCanonicalDirectoryPath(renamingPath),result=renameFileTreePaths({files:this.#store.list(),isFolder,nextBasename:this.#renamingValue,path:toRenameHelperPath(renamingPath)});if(this.#renamingPath=null,this.#renamingValue="",this.#removeRenamingPathIfCanceled=!1,"error"in result){this.#focusPathWithoutEmit(renamingPath),this.#onRenameError?.(result.error),this.#emit();return}if(result.sourcePath===result.destinationPath){this.#focusPathWithoutEmit(renamingPath),this.#emit();return}this.#onRename?.({destinationPath:result.destinationPath,isFolder:result.isFolder,sourcePath:result.sourcePath}),this.move(toCanonicalRenamePath(result.sourcePath,isFolder),toCanonicalRenamePath(result.destinationPath,isFolder))}#setRenamingValue(value){this.#renamingPath==null||this.#renamingValue===value||(this.#renamingValue=value,this.#emit())}resetPaths(pathsOrOptions,maybeOptions={}){const usingPreparedOnlyOverload=!Array.isArray(pathsOrOptions),paths=usingPreparedOnlyOverload?void 0:pathsOrOptions,options=usingPreparedOnlyOverload?pathsOrOptions:maybeOptions,previousPathCount=this.#store.list().length,previousVisibleCount=this.#visibleCount,resolvedInput=resolveFileTreeInput({paths,preparedInput:options.preparedInput},"resetPaths",this.#baseOptions.sort),nextStore=this.#createStore(resolvedInput.paths,resolvedInput.preparedInput,options.initialExpandedPaths),previousFocusedPath=this.#focusedPath,previousRenamingPath=this.#renamingPath,previousSelectedPaths=this.getSelectedPaths(),previousSelectionAnchorPath=this.#selectionAnchorPath;this.#unsubscribe?.(),this.#store=nextStore,this.#itemHandles.clear(),this.#invalidateKnownPathCaches();const nextSelectedPaths=previousSelectedPaths.map(selectedPath=>nextStore.getPathInfo(selectedPath)?.path??null).filter(resolved=>resolved!=null),selectionChanged=!arePathSetsEqual(this.#selectedPaths,nextSelectedPaths);this.#selectedPaths=new Set(nextSelectedPaths),selectionChanged&&(this.#selectionVersion+=1),this.#selectionAnchorPath=previousSelectionAnchorPath==null?null:nextStore.getPathInfo(previousSelectionAnchorPath)?.path??null,this.#renamingPath=previousRenamingPath==null?null:nextStore.getPathInfo(previousRenamingPath)?.path??null,this.#renamingPath==null&&(this.#renamingValue="",this.#removeRenamingPathIfCanceled=!1),this.#rebuildVisibleProjection(previousFocusedPath,previousFocusedPath!=null||nextSelectedPaths.length>0||this.#selectionAnchorPath!=null),this.#unsubscribe=this.#subscribe(),this.#emit(),this.#emitMutation({canonicalChanged:!0,operation:"reset",pathCountAfter:resolvedInput.paths.length,pathCountBefore:previousPathCount,projectionChanged:!0,usedPreparedInput:options.preparedInput!=null,visibleCountDelta:this.#visibleCount-previousVisibleCount})}#findNearestVisibleSiblingPath(path){this.#ensureFullProjection();const parentPath=getImmediateParentPath(path),candidateKey=getSiblingComparisonKey(path,parentPath);let previousSiblingPath=null,nextSiblingPath=null;for(const siblingPath of this.#getCurrentVisiblePaths()){if(getImmediateParentPath(siblingPath)!==parentPath)continue;const siblingKey=getSiblingComparisonKey(siblingPath,parentPath);if(siblingKey<candidateKey){previousSiblingPath=siblingPath;continue}if(siblingKey>candidateKey){nextSiblingPath=siblingPath;break}}return previousSiblingPath??nextSiblingPath}#resolveFocusedIndex(path){const directIndex=this.#getVisibleIndexByPath(path);if(directIndex!==-1)return directIndex;const ancestorPaths=getAncestorDirectoryPaths$1(path);for(let index=ancestorPaths.length-1;index>=0;index-=1){const ancestorPath=ancestorPaths[index];if(ancestorPath==null)continue;const ancestorIndex=this.#getVisibleIndexByPath(ancestorPath);if(ancestorIndex!==-1)return ancestorIndex}return this.#getCurrentVisiblePaths().length>0?0:-1}#getOrCreateItemHandle(path,itemInfo){const cachedHandle=this.#itemHandles.get(path);if(cachedHandle!=null)return cachedHandle;const resolvedItemInfo=itemInfo??this.#store.getPathInfo(path);if(resolvedItemInfo==null)return null;const handle=resolvedItemInfo.kind==="directory"?this.#createDirectoryHandle(resolvedItemInfo.path):this.#createFileHandle(resolvedItemInfo.path);return this.#itemHandles.set(resolvedItemInfo.path,handle),handle}#createVisibleRow(row,visibleIndex,projectionIndex,projection){return{ancestorPaths:projection.ancestorPaths,depth:row.depth,flattenedSegments:row.flattenedSegments?.map(segment=>({isTerminal:segment.isTerminal,name:segment.name,path:segment.path})),hasChildren:row.hasChildren,index:visibleIndex,isExpanded:row.isExpanded,isFlattened:row.isFlattened,isFocused:projection.path===this.#focusedPath,isSelected:this.#selectedPaths.has(projection.path),kind:row.kind,level:row.depth,name:row.name,path:projection.path,posInSet:projection.posInSet??this.#projectionPosInSetByIndex[projectionIndex]??0,setSize:projection.setSize??this.#projectionSetSizeByIndex[projectionIndex]??0}}#createVisibleRowFromContext(context){return this.#createVisibleRow(context.row,context.index,context.index,{ancestorPaths:context.ancestorPaths,path:context.row.path,posInSet:context.posInSet,setSize:context.setSize})}#getStickyCandidateContextAt(index,slotDepth){const context=this.#store.getVisibleRowContext(index);if(context==null)return;const ancestorRow=context.ancestorRows[slotDepth];return ancestorRow??(slotDepth===context.ancestorRows.length&&context.row.kind==="directory"&&context.row.isExpanded?context:void 0)}#getAncestorIndices(index){const cached=this.#ancestorIndicesByIndex.get(index);if(cached!=null)return cached;const parentIndex=this.#getParentIndexForVisibleRow(index),ancestorIndices=parentIndex<0?[]:[...this.#getAncestorIndices(parentIndex),parentIndex];return this.#ancestorIndicesByIndex.set(index,ancestorIndices),ancestorIndices}#getAncestorPaths(index){const cached=this.#ancestorPathsByIndex.get(index);if(cached!=null)return cached;const ancestorPaths=this.#getAncestorIndices(index).map(ancestorIndex=>this.#projectionPaths[ancestorIndex]??"").filter(path=>path!=="");return this.#ancestorPathsByIndex.set(index,ancestorPaths),ancestorPaths}#collapseDirectory(path){this.#store.collapse(path)}#applySelection(nextSelectedPaths,nextAnchorPath=this.#selectionAnchorPath,emit=!0){const uniqueSelectedPaths=[...new Set(nextSelectedPaths)],selectionChanged=!arePathSetsEqual(this.#selectedPaths,uniqueSelectedPaths),anchorChanged=this.#selectionAnchorPath!==nextAnchorPath;!selectionChanged&&!anchorChanged||(this.#selectedPaths=new Set(uniqueSelectedPaths),this.#selectionAnchorPath=nextAnchorPath,selectionChanged&&(this.#selectionVersion+=1),emit&&this.#emit())}#createDirectoryHandle(path){return{collapse:()=>{this.#collapseDirectory(path)},deselect:()=>{this.deselectPath(path)},expand:()=>{this.#expandDirectory(path)},focus:()=>{this.focusPath(path)},getPath:()=>path,isDirectory:()=>!0,isExpanded:()=>this.#store.isExpanded(path),isFocused:()=>this.#focusedPath===path,isSelected:()=>this.#selectedPaths.has(path),select:()=>{this.selectPath(path)},toggleSelect:()=>{this.togglePathSelection(path)},toggle:()=>{this.#toggleDirectory(path)}}}#createFileHandle(path){return{deselect:()=>{this.deselectPath(path)},focus:()=>{this.focusPath(path)},getPath:()=>path,isDirectory:()=>!1,isFocused:()=>this.#focusedPath===path,isSelected:()=>this.#selectedPaths.has(path),select:()=>{this.selectPath(path)},toggleSelect:()=>{this.togglePathSelection(path)}}}#validateBatchDropOperations(operations){const currentPaths=this.#store.list();this.#createStore(currentPaths).batch(operations)}#createStore(paths,preparedInput,initialExpandedPathsOverride){return new PathStore({...this.#baseOptions,paths,preparedInput:preparedInput??void 0,...initialExpandedPathsOverride!==void 0?{initialExpandedPaths:initialExpandedPathsOverride}:{}})}#getListedPaths(){return this.#listedPaths!=null?this.#listedPaths:(this.#listedPaths=this.#store.list(),this.#listedPaths)}#getAllKnownPaths(){if(this.#knownPaths!=null)return this.#knownPaths;const knownPaths=new Set;for(const path of this.#getListedPaths()){knownPaths.add(path);for(const ancestorPath of getAncestorDirectoryPaths$1(path))knownPaths.add(ancestorPath)}return this.#knownPaths=[...knownPaths].sort(),this.#knownPaths}#getListedPathsLowerCase(){return this.#listedPathsLowerCase!=null?this.#listedPathsLowerCase:(this.#listedPathsLowerCase=this.#getListedPaths().map(toLowerCaseSearchPath),this.#listedPathsLowerCase)}#getAllKnownDirectoryPaths(){return this.#knownDirectoryPaths!=null?this.#knownDirectoryPaths:(this.#knownDirectoryPaths=this.#getAllKnownPaths().filter(path=>path.endsWith("/")),this.#knownDirectoryPaths)}#getAllKnownDirectoryPathsLowerCase(){return this.#knownDirectoryPathsLowerCase!=null?this.#knownDirectoryPathsLowerCase:(this.#knownDirectoryPathsLowerCase=this.#getAllKnownDirectoryPaths().map(toLowerCaseSearchPath),this.#knownDirectoryPathsLowerCase)}#invalidateKnownPathCaches(){this.#knownDirectoryPaths=null,this.#knownDirectoryPathsLowerCase=null,this.#knownPaths=null,this.#listedPaths=null,this.#listedPathsLowerCase=null}#getExpandedDirectoryPaths(){return this.#getAllKnownDirectoryPaths().filter(path=>this.#store.isExpanded(path))}#restoreSearchExpandedPaths(keepSelectedOpen){const expandedPaths=new Set(this.#searchPreviousExpandedPaths??[]);if(keepSelectedOpen)for(const selectedPath of this.#selectedPaths)for(const ancestorPath of getAncestorDirectoryPaths$1(selectedPath))expandedPaths.add(ancestorPath);this.#setExpandedPaths(expandedPaths)}#setExpandedPaths(expandedPaths){this.#suppressStoreNotifications=!0;try{for(const directoryPath of this.#getAllKnownDirectoryPaths()){const shouldExpand=expandedPaths.has(directoryPath),isExpanded=this.#store.isExpanded(directoryPath);shouldExpand&&!isExpanded?this.#store.expand(directoryPath):!shouldExpand&&isExpanded&&this.#store.collapse(directoryPath)}}finally{this.#suppressStoreNotifications=!1}}#syncSearchVisibilityState(){if(this.#searchValue==null||this.#searchValue.length===0){this.#searchMatchingPaths=[],this.#searchVisibleIndices=null,this.#searchVisiblePaths=null,this.#searchVisibleIndexByPath=null,this.#visibleCount=this.#storeVisibleCount;return}const currentVisiblePaths=this.#projectionPaths;if(this.#searchMatchingPaths=currentVisiblePaths.filter(path=>this.#searchMatchPathSet.has(path)),this.#searchMode!=="hide-non-matches"||this.#searchMatchPathSet.size===0){this.#searchVisibleIndices=null,this.#searchVisiblePaths=null,this.#searchVisibleIndexByPath=null,this.#visibleCount=this.#storeVisibleCount;return}const visibleIndices=[],visiblePaths=[],visibleIndexByPath=new Map;for(const[index,path]of currentVisiblePaths.entries())this.#searchVisiblePathSet?.has(path)===!0&&(visibleIndexByPath.set(path,visiblePaths.length),visibleIndices.push(index),visiblePaths.push(path));this.#searchVisibleIndices=visibleIndices,this.#searchVisiblePaths=visiblePaths,this.#searchVisibleIndexByPath=visibleIndexByPath,this.#visibleCount=visiblePaths.length}#getCurrentVisiblePaths(){return this.#searchVisiblePaths??this.#projectionPaths}#getExactCurrentVisibleIndexByPath(path){return this.#searchVisiblePaths!=null?this.#searchVisibleIndexByPath?.get(path)??-1:this.#store.getVisibleIndex(path)??-1}#getProjectionIndexFromVisibleIndex(index){return this.#searchVisibleIndices?.[index]??index}#getVisibleIndexByPath(path){const searchIndex=this.#searchVisibleIndexByPath?.get(path);return searchIndex??this.#store.getVisibleIndex(path)??-1}#focusRelativeSearchMatch(direction){const matchPaths=this.#searchMatchingPaths;if(matchPaths.length===0)return;const focusedPath=this.#focusedPath,currentIndex=focusedPath==null?-1:matchPaths.indexOf(focusedPath),nextPath=matchPaths[currentIndex<0?direction>0?0:matchPaths.length-1:Math.min(matchPaths.length-1,Math.max(0,currentIndex+direction))];nextPath!=null&&this.focusPath(nextPath)}#setSearchState(value,emitChange){const normalizedValue=value==null?null:normalizeSearchQuery(value),previousSearch=this.#searchValue;if(previousSearch!==normalizedValue){if(previousSearch==null&&normalizedValue!=null&&(this.#searchPreviousExpandedPaths=this.#getExpandedDirectoryPaths()),this.#searchValue=normalizedValue,normalizedValue==null)this.#restoreSearchExpandedPaths(!0),this.#searchPreviousExpandedPaths=null,this.#searchMatchPathSet.clear(),this.#searchVisiblePathSet=null,this.#rebuildVisibleProjection(this.#focusedPath,!0);else if(normalizedValue.length===0)this.#restoreSearchExpandedPaths(!1),this.#searchMatchPathSet.clear(),this.#searchVisiblePathSet=null,this.#rebuildVisibleProjection(this.#focusedPath,!0);else{const focusCandidate=this.#refreshActiveSearchState();this.#rebuildVisibleProjection(focusCandidate,!0)}emitChange&&(this.#onSearchChange?.(this.#searchValue),this.#emit())}}#refreshActiveSearchState(){if(this.#searchValue==null||this.#searchValue.length===0)return this.#searchMatchPathSet.clear(),this.#focusedPath;const searchValue=this.#searchValue,listedPaths=this.#getListedPaths(),listedPathsLowerCase=this.#getListedPathsLowerCase(),matchingPaths=[],matchingPathSet=new Set;let focusCandidate=null;for(let index=0;index<listedPaths.length;index+=1){if(!listedPathsLowerCase[index].includes(searchValue))continue;const path=listedPaths[index];matchingPaths.push(path),matchingPathSet.add(path),focusCandidate??=path}const knownDirectoryPaths=this.#getAllKnownDirectoryPaths(),knownDirectoryPathsLowerCase=this.#getAllKnownDirectoryPathsLowerCase();for(let index=0;index<knownDirectoryPaths.length;index+=1){if(!knownDirectoryPathsLowerCase[index].includes(searchValue))continue;const path=knownDirectoryPaths[index];matchingPathSet.has(path)||(matchingPaths.push(path),matchingPathSet.add(path),focusCandidate??=path)}this.#searchMatchPathSet=matchingPathSet;const searchVisiblePathSet=this.#searchMode==="hide-non-matches"&&matchingPaths.length>0?new Set:null;this.#searchVisiblePathSet=searchVisiblePathSet;const expandedPaths=this.#searchMode==="expand-matches"?new Set(this.#searchPreviousExpandedPaths??[]):new Set;for(const matchingPath of matchingPaths){searchVisiblePathSet?.add(matchingPath),matchingPath.endsWith("/")&&expandedPaths.add(matchingPath);for(const ancestorPath of getAncestorDirectoryPaths$1(matchingPath))expandedPaths.add(ancestorPath),searchVisiblePathSet?.add(ancestorPath)}return this.#setExpandedPaths(expandedPaths),focusCandidate??this.#focusedPath}#emit(){for(const listener of this.#listeners)listener()}#emitMutation(event){this.#mutationListeners.get(event.operation)?.forEach(listener=>{listener(event)}),this.#mutationListeners.get("*")?.forEach(listener=>{listener(event)})}#expandDirectory(path){for(const ancestorPath of getAncestorDirectoryPaths$1(path))this.#store.isExpanded(ancestorPath)||this.#store.expand(ancestorPath);this.#store.isExpanded(path)||this.#store.expand(path)}#moveFocus(offset){const itemCount=this.#visibleCount;if(itemCount===0)return;const currentIndex=this.#focusedIndex===-1?0:this.#focusedIndex,nextIndex=Math.min(itemCount-1,Math.max(0,currentIndex+offset));(nextIndex!==currentIndex||this.#focusedIndex===-1)&&(!this.#hasFullProjection&&this.#searchVisibleIndices==null&&nextIndex>=this.#projectionPaths.length&&this.#ensureFullProjection(),this.#setFocusedIndex(nextIndex))}#rebuildVisibleProjection(focusedPathCandidate,full=!0){const rawVisibleCount=this.#store.getVisibleCount();this.#storeVisibleCount=rawVisibleCount;const projection=createVisibleProjection(this.#store.getVisibleTreeProjectionData(full?void 0:Math.min(rawVisibleCount,INITIAL_PROJECTION_ROW_LIMIT)),focusedPathCandidate,full?path=>this.#store.getVisibleIndex(path):void 0);this.#ancestorIndicesByIndex.clear(),this.#ancestorPathsByIndex.clear(),this.#hasFullProjection=projection.paths.length>=rawVisibleCount,this.#getParentIndexForVisibleRow=projection.getParentIndex,this.#projectionPaths=projection.paths,this.#projectionPosInSetByIndex=projection.posInSetByIndex,this.#projectionSetSizeByIndex=projection.setSizeByIndex,this.#syncSearchVisibilityState(),this.#focusedIndex=focusedPathCandidate==null?this.#getCurrentVisiblePaths().length>0?0:-1:this.#resolveFocusedIndex(focusedPathCandidate),this.#focusedPath=this.#focusedIndex<0?null:this.#resolveVisiblePathAtIndex(this.#focusedIndex)}#resolveVisiblePathAtIndex(index){const projectedPath=this.#getCurrentVisiblePaths()[index];return projectedPath??(this.#searchVisibleIndices!=null?null:this.#store.getVisibleRowContext(index)?.row.path??null)}#resolveSelectionPath(path){return this.#store.getPathInfo(path)?.path??null}#focusPathWithoutEmit(path){if(path==null)return;const nextFocusedIndex=this.#resolveFocusedIndex(path);nextFocusedIndex>=0&&this.#setFocusedIndex(nextFocusedIndex,!1)}#setFocusedIndex(index,emit=!0){const nextPath=this.#resolveVisiblePathAtIndex(index);nextPath!=null&&(this.#focusedIndex===index&&this.#focusedPath===nextPath||(this.#focusedIndex=index,this.#focusedPath=nextPath,emit&&this.#emit()))}#ensureFullProjection(){this.#hasFullProjection||this.#rebuildVisibleProjection(this.#focusedPath,!0)}#applyMutationState(event){const nextRenamingPath=remapPathThroughMutation(this.#renamingPath,event);nextRenamingPath==null&&this.#renamingPath!=null&&(this.#renamingValue=""),this.#renamingPath=nextRenamingPath;const nextFocusedPath=remapPathThroughMutation(this.#focusedPath,event,!0),nextSelectedPaths=[...this.#selectedPaths].map(selectedPath=>remapPathThroughMutation(selectedPath,event)).filter(resolvedPath=>resolvedPath!=null).map(resolvedPath=>this.#store.getPathInfo(resolvedPath)?.path??null).filter(resolvedPath=>resolvedPath!=null),nextSelectionAnchorPath=remapPathThroughMutation(this.#selectionAnchorPath,event),canonicalAnchorPath=nextSelectionAnchorPath==null?null:this.#store.getPathInfo(nextSelectionAnchorPath)?.path??null,uniqueNextSelectedPaths=[...new Set(nextSelectedPaths)];return arePathSetsEqual(this.#selectedPaths,uniqueNextSelectedPaths)||(this.#selectedPaths=new Set(uniqueNextSelectedPaths),this.#selectionVersion+=1),this.#selectionAnchorPath=canonicalAnchorPath,nextFocusedPath}#subscribe(){return this.#store.on("*",event=>{if(this.#suppressStoreNotifications)return;event.canonicalChanged&&(this.#itemHandles.clear(),this.#invalidateKnownPathCaches()),this.#dragSession!=null&&isPathMutationEvent(event)&&(this.#dragSession=null);const focusPathCandidate=isPathMutationEvent(event)?this.#applyMutationState(event):this.#focusedPath,searchFocusCandidate=this.#searchValue!=null&&this.#searchValue.length>0?this.#refreshActiveSearchState():this.#searchValue===""?this.#focusedPath:focusPathCandidate,shouldBuildFullProjection=this.#searchValue!=null||event.operation!=="expand"&&event.operation!=="collapse";this.#rebuildVisibleProjection(searchFocusCandidate,shouldBuildFullProjection),this.#emit();const mutationEvent=toTreesMutationEvent(event);mutationEvent!=null&&this.#emitMutation(mutationEvent)})}#toggleDirectory(path){if(this.#store.isExpanded(path)){this.#collapseDirectory(path);return}this.#expandDirectory(path)}};const getGitStatusSignature=entries=>{if(entries==null||entries.length===0)return"0";let signature=`${entries.length}`;for(const entry of entries)signature+=`\0${entry.path}\0${entry.status}`;return signature};function normalizeInputPath(inputPath){const isDirectory=inputPath.endsWith("/");let normalizedPath="",segmentStart=-1;for(let i2=0;i2<=inputPath.length;i2+=1){if(!(inputPath[i2]==="/"||i2===inputPath.length)){segmentStart===-1&&(segmentStart=i2);continue}segmentStart!==-1&&(normalizedPath!==""&&(normalizedPath+="/"),normalizedPath+=inputPath.slice(segmentStart,i2),segmentStart=-1)}return normalizedPath===""?null:{isDirectory,path:normalizedPath}}function getAncestorDirectoryPaths(path){const normalizedPath=path.endsWith("/")?path.slice(0,-1):path;if(normalizedPath.length===0)return[];const ancestors=[];let searchIndex=0;for(;;){const slashIndex=normalizedPath.indexOf("/",searchIndex);if(slashIndex===-1)break;ancestors.push(normalizedPath.slice(0,slashIndex+1)),searchIndex=slashIndex+1}return ancestors}function getCanonicalGitStatusPath(path,isDirectory){return isDirectory?`${path}/`:path}function resolveFileTreeGitStatusState(entries,previous=null){const signature=getGitStatusSignature(entries==null?void 0:[...entries]);if(signature==="0")return null;if(previous?.signature===signature)return previous;const statusByPath=new Map,directoriesWithChanges=new Set,ignoredDirectoryPaths=new Set,changeCountByDirectoryPath=new Map;for(const entry of entries??[]){const resolved=resolveGitStatusEntry(entry);resolved!=null&&setGitStatusPath({canonicalPath:resolved.canonicalPath,changeCountByDirectoryPath,directoriesWithChanges,ignoredDirectoryPaths,isDirectory:resolved.isDirectory,status:entry.status,statusByPath})}return statusByPath.size===0?null:{changeCountByDirectoryPath,directoriesWithChanges,ignoredDirectoryPaths,signature,statusByPath}}function applyFileTreeGitStatusPatch(previous,patch){const removeEntries=patch?.remove??[],setEntries=patch?.set??[];if(removeEntries.length===0&&setEntries.length===0)return previous;const statusByPath=new Map(previous?.statusByPath),directoriesWithChanges=new Set(previous?.directoriesWithChanges),ignoredDirectoryPaths=new Set(previous?.ignoredDirectoryPaths),changeCountByDirectoryPath=new Map(previous?.changeCountByDirectoryPath);let changed=!1;for(const path of removeEntries){const resolved=resolveGitStatusPath(path);resolved!=null&&(changed=removeGitStatusPath({canonicalPath:resolved.canonicalPath,changeCountByDirectoryPath,directoriesWithChanges,ignoredDirectoryPaths,statusByPath})||changed)}for(const entry of setEntries){const resolved=resolveGitStatusEntry(entry);resolved!=null&&(changed=setGitStatusPath({canonicalPath:resolved.canonicalPath,changeCountByDirectoryPath,directoriesWithChanges,ignoredDirectoryPaths,isDirectory:resolved.isDirectory,status:entry.status,statusByPath})||changed)}return changed?statusByPath.size===0?null:{changeCountByDirectoryPath,directoriesWithChanges,ignoredDirectoryPaths,signature:getGitStatusStateSignature(statusByPath),statusByPath}:previous}function resolveGitStatusEntry(entry){return resolveGitStatusPath(entry.path)}function resolveGitStatusPath(path){const normalizedPath=normalizeInputPath(path);if(normalizedPath!=null)return{canonicalPath:getCanonicalGitStatusPath(normalizedPath.path,normalizedPath.isDirectory),isDirectory:normalizedPath.isDirectory}}function removeGitStatusPath({canonicalPath,changeCountByDirectoryPath,directoriesWithChanges,ignoredDirectoryPaths,statusByPath}){const previousStatus=statusByPath.get(canonicalPath);return previousStatus==null?!1:(statusByPath.delete(canonicalPath),previousStatus==="ignored"&&canonicalPath.endsWith("/")&&ignoredDirectoryPaths.delete(canonicalPath),decrementAncestorChangeCounts(changeCountByDirectoryPath,directoriesWithChanges,canonicalPath),!0)}function setGitStatusPath({canonicalPath,changeCountByDirectoryPath,directoriesWithChanges,ignoredDirectoryPaths,isDirectory,status,statusByPath}){const previousStatus=statusByPath.get(canonicalPath);return previousStatus===status?!1:(previousStatus==null&&incrementAncestorChangeCounts(changeCountByDirectoryPath,directoriesWithChanges,canonicalPath),statusByPath.set(canonicalPath,status),status==="ignored"&&isDirectory?ignoredDirectoryPaths.add(canonicalPath):isDirectory&&ignoredDirectoryPaths.delete(canonicalPath),!0)}function incrementAncestorChangeCounts(changeCountByDirectoryPath,directoriesWithChanges,path){for(const ancestorPath of getAncestorDirectoryPaths(path))changeCountByDirectoryPath.set(ancestorPath,(changeCountByDirectoryPath.get(ancestorPath)??0)+1),directoriesWithChanges.add(ancestorPath)}function decrementAncestorChangeCounts(changeCountByDirectoryPath,directoriesWithChanges,path){for(const ancestorPath of getAncestorDirectoryPaths(path)){const nextCount=(changeCountByDirectoryPath.get(ancestorPath)??0)-1;nextCount>0?changeCountByDirectoryPath.set(ancestorPath,nextCount):(changeCountByDirectoryPath.delete(ancestorPath),directoriesWithChanges.delete(ancestorPath))}}function getGitStatusStateSignature(statusByPath){let signature=`${statusByPath.size}`;for(const[path,status]of statusByPath)signature+=`\0${path}\0${status}`;return signature}var n,l$1,t$1,i$1,r$1,f$1,e$1,o$2,c$1,s$1,h$1={},p$1=[],v$1=Array.isArray,y$1=p$1.slice,w$1=Object.assign;function d$1(n2){n2&&n2.parentNode&&n2.remove()}function _$1(n2,l2,u2){var t2,i2,r2,f2={};for(r2 in l2)r2=="key"?t2=l2[r2]:r2=="ref"&&typeof n2!="function"?i2=l2[r2]:f2[r2]=l2[r2];return arguments.length>2&&(f2.children=arguments.length>3?y$1.call(arguments,2):u2),g$1(n2,f2,t2,i2,null)}function g$1(u2,t2,i2,r2,f2){var e2={type:u2,props:t2,key:i2,ref:r2,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:f2??++l$1,__i:-1,__u:0};return f2==null&&n.vnode!=null&&n.vnode(e2),e2}function k$1(n2){return n2.children}function m$1(n2,l2){this.props=n2,this.context=l2,this.__g=0}function M(n2,l2){if(l2==null)return n2.__?M(n2.__,n2.__i+1):null;for(var u2;l2<n2.__k.length;l2++)if((u2=n2.__k[l2])!=null&&u2.__e!=null)return u2.__e;return typeof n2.type=="function"?M(n2):null}function S(n2){var l2,u2;if((n2=n2.__)!=null&&n2.__c!=null){for(n2.__e=null,l2=0;l2<n2.__k.length;l2++)if((u2=n2.__k[l2])!=null&&u2.__e!=null){n2.__e=u2.__e;break}return S(n2)}}function $(l2){(8&l2.__g||!(l2.__g|=8)||!t$1.push(l2)||r$1++)&&i$1==n.debounceRendering||((i$1=n.debounceRendering)||queueMicrotask)(x)}function x(){for(var l2,u2,i2,e2,o2,c2,s2,a2,h2=1;t$1.length;)t$1.length>h2&&t$1.sort(f$1),l2=t$1.shift(),h2=t$1.length,8&l2.__g&&(i2=void 0,o2=(e2=(u2=l2).__v).__e,c2=[],s2=[],(a2=u2.__P)&&((i2=w$1({},e2)).__v=e2.__v+1,n.vnode&&n.vnode(i2),q$1(a2,i2,e2,u2.__n,a2.namespaceURI,32&e2.__u?[o2]:null,c2,o2??M(e2),!!(32&e2.__u),s2,a2.ownerDocument),i2.__v=e2.__v,i2.__.__k[i2.__i]=i2,P(c2,i2,s2),i2.__e!=o2&&S(i2)));r$1=0}function C$1(n2,l2,u2,t2,i2,r2,f2,e2,o2,c2,s2,a2){var v2,y2,w2,d2,_2,g2,b2,k2=t2&&t2.__k||p$1,m2=l2.length;for(o2=j(u2,l2,k2,o2,m2),v2=0;v2<m2;v2++)(w2=u2.__k[v2])!=null&&(y2=w2.__i==-1?h$1:k2[w2.__i]||h$1,w2.__i=v2,g2=q$1(n2,w2,y2,i2,r2,f2,e2,o2,c2,s2,a2),d2=w2.__e,w2.ref&&y2.ref!=w2.ref&&(y2.ref&&B$1(y2.ref,null,w2),s2.push(w2.ref,w2.__c||d2,w2)),_2==null&&d2!=null&&(_2=d2),(b2=!!(4&w2.__u))||y2.__k===w2.__k?o2=A$1(w2,o2,n2,b2):typeof w2.type=="function"&&g2!==void 0?o2=g2:d2&&(o2=d2.nextSibling),w2.__u&=-7);return u2.__e=_2,o2}function j(n2,l2,u2,t2,i2){var r2,f2,e2,o2,c2,s2=u2.length,a2=s2,h2=0;for(n2.__k=new Array(i2),r2=0;r2<i2;r2++)(f2=l2[r2])!=null&&typeof f2!="boolean"&&typeof f2!="function"?(o2=r2+h2,(f2=n2.__k[r2]=typeof f2=="string"||typeof f2=="number"||typeof f2=="bigint"||f2.constructor==String?g$1(null,f2,null,null,null):v$1(f2)?g$1(k$1,{children:f2},null,null,null):f2.constructor==null&&f2.__b>0?g$1(f2.type,f2.props,f2.key,f2.ref?f2.ref:null,f2.__v):f2).__=n2,f2.__b=n2.__b+1,e2=null,(c2=f2.__i=I(f2,u2,o2,a2))!=-1&&(a2--,(e2=u2[c2])&&(e2.__u|=2)),e2==null||e2.__v==null?(c2==-1&&(i2>s2?h2--:i2<s2&&h2++),typeof f2.type!="function"&&(f2.__u|=4)):c2!=o2&&(c2==o2-1?h2--:c2==o2+1?h2++:(c2>o2?h2--:h2++,f2.__u|=4))):n2.__k[r2]=null;if(a2)for(r2=0;r2<s2;r2++)(e2=u2[r2])!=null&&(2&e2.__u)==0&&(e2.__e==t2&&(t2=M(e2)),D$1(e2,e2));return t2}function A$1(n2,l2,u2,t2){var i2,r2;if(typeof n2.type=="function"){for(i2=n2.__k,r2=0;i2&&r2<i2.length;r2++)i2[r2]&&(i2[r2].__=n2,l2=A$1(i2[r2],l2,u2,t2));return l2}n2.__e!=l2&&(t2&&(l2&&n2.type&&!l2.parentNode&&(l2=M(n2)),u2.insertBefore(n2.__e,l2||null)),l2=n2.__e);do l2=l2&&l2.nextSibling;while(l2!=null&&l2.nodeType==8);return l2}function I(n2,l2,u2,t2){var i2,r2,f2,e2=n2.key,o2=n2.type,c2=l2[u2],s2=c2!=null&&(2&c2.__u)==0;if(c2===null&&n2.key==null||s2&&e2==c2.key&&o2==c2.type)return u2;if(t2>(s2?1:0)){for(i2=u2-1,r2=u2+1;i2>=0||r2<l2.length;)if((c2=l2[f2=i2>=0?i2--:r2++])!=null&&(2&c2.__u)==0&&e2==c2.key&&o2==c2.type)return f2}return-1}function L(n2,l2,u2){l2[0]=="-"?n2.setProperty(l2,u2??""):n2[l2]=u2??""}function O(n2,l2,u2,t2,i2){var r2;n:if(l2=="style")if(typeof u2=="string")n2.style.cssText=u2;else{if(typeof t2=="string"&&(n2.style.cssText=t2=""),t2)for(l2 in t2)u2&&l2 in u2||L(n2.style,l2,"");if(u2)for(l2 in u2)t2&&u2[l2]==t2[l2]||L(n2.style,l2,u2[l2])}else if(l2[0]=="o"&&l2[1]=="n")r2=l2!=(l2=l2.replace(e$1,"$1")),(l2=l2.slice(2))[0].toLowerCase()!=l2[0]&&(l2=l2.toLowerCase()),n2.__l||(n2.__l={}),n2.__l[l2+r2]=u2,u2?t2?u2.l=t2.l:(u2.l=o$2,n2.addEventListener(l2,r2?s$1:c$1,r2)):n2.removeEventListener(l2,r2?s$1:c$1,r2);else{if(i2=="http://www.w3.org/2000/svg")l2=l2.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(l2!="width"&&l2!="height"&&l2!="href"&&l2!="list"&&l2!="form"&&l2!="tabIndex"&&l2!="download"&&l2!="rowSpan"&&l2!="colSpan"&&l2!="role"&&l2!="popover"&&l2 in n2)try{n2[l2]=u2??"";break n}catch{}typeof u2=="function"||(u2==null||u2===!1&&l2[4]!="-"?n2.removeAttribute(l2):n2.setAttribute(l2,l2=="popover"&&u2==1?"":u2))}}function T(l2){return function(u2){if(this.__l){var t2=this.__l[u2.type+l2];if(u2.u==null)u2.u=o$2++;else if(u2.u<t2.l)return;return t2(n.event?n.event(u2):u2)}}}function q$1(l2,u2,t2,i2,r2,f2,e2,o2,c2,s2,a2){var h2,p2,y2,_2,g2,b2,M2,S2,$2,x2,j2,A2,H,I2,L2,O2,T2,q2,P2,B2,D2,F2=u2.type;if(u2.constructor!=null)return null;128&t2.__u&&(c2=!!(32&t2.__u),t2.__c.__z&&(o2=u2.__e=t2.__e=(f2=t2.__c.__z)[0],t2.__c.__z=null)),(h2=n.__b)&&h2(u2);n:if(typeof F2=="function")try{if(S2=u2.props,$2="prototype"in F2&&F2.prototype.render,x2=(h2=F2.contextType)&&i2[h2.__c],j2=h2?x2?x2.props.value:h2.__:i2,t2.__c?2&(p2=u2.__c=t2.__c).__g&&(p2.__g|=1,M2=!0):($2?u2.__c=p2=new F2(S2,j2):(u2.__c=p2=new m$1(S2,j2),p2.constructor=F2,p2.render=E),x2&&x2.sub(p2),p2.props=S2,p2.state||(p2.state={}),p2.context=j2,p2.__n=i2,y2=!0,p2.__g|=8,p2.__h=[],p2._sb=[]),$2&&p2.__s==null&&(p2.__s=p2.state),$2&&F2.getDerivedStateFromProps!=null&&(p2.__s==p2.state&&(p2.__s=w$1({},p2.__s)),w$1(p2.__s,F2.getDerivedStateFromProps(S2,p2.__s))),_2=p2.props,g2=p2.state,p2.__v=u2,y2)$2&&F2.getDerivedStateFromProps==null&&p2.componentWillMount!=null&&p2.componentWillMount(),$2&&p2.componentDidMount!=null&&p2.__h.push(p2.componentDidMount);else{if($2&&F2.getDerivedStateFromProps==null&&S2!==_2&&p2.componentWillReceiveProps!=null&&p2.componentWillReceiveProps(S2,j2),!(4&p2.__g)&&p2.shouldComponentUpdate!=null&&p2.shouldComponentUpdate(S2,p2.__s,j2)===!1||u2.__v==t2.__v){for(u2.__v!=t2.__v&&(p2.props=S2,p2.state=p2.__s,p2.__g&=-9),u2.__e=t2.__e,u2.__k=t2.__k,u2.__k.some(function(n2){n2&&(n2.__=u2)}),A2=0;A2<p2._sb.length;A2++)p2.__h.push(p2._sb[A2]);p2._sb=[],p2.__h.length&&e2.push(p2);break n}p2.componentWillUpdate!=null&&p2.componentWillUpdate(S2,p2.__s,j2),$2&&p2.componentDidUpdate!=null&&p2.__h.push(function(){p2.componentDidUpdate(_2,g2,b2)})}if(p2.context=j2,p2.props=S2,p2.__P=l2,p2.__g&=-5,H=n.__r,I2=0,$2){for(p2.state=p2.__s,p2.__g&=-9,H&&H(u2),h2=p2.render(p2.props,p2.state,p2.context),L2=0;L2<p2._sb.length;L2++)p2.__h.push(p2._sb[L2]);p2._sb=[]}else do p2.__g&=-9,H&&H(u2),h2=p2.render(p2.props,p2.state,p2.context),p2.state=p2.__s;while(8&p2.__g&&++I2<25);p2.state=p2.__s,p2.getChildContext!=null&&(i2=w$1({},i2,p2.getChildContext())),$2&&!y2&&p2.getSnapshotBeforeUpdate!=null&&(b2=p2.getSnapshotBeforeUpdate(_2,g2)),O2=h2,h2!=null&&h2.type===k$1&&h2.key==null&&(O2=V(h2.props.children)),o2=C$1(l2,v$1(O2)?O2:[O2],u2,t2,i2,r2,f2,e2,o2,c2,s2,a2),u2.__u&=-161,p2.__h.length&&e2.push(p2),M2&&(p2.__g&=-4)}catch(l3){if(u2.__v=null,c2||f2!=null)if(l3.then){for(T2=0,q2=!1,u2.__u|=c2?160:128,u2.__c.__z=[],P2=0;P2<f2.length;P2++)(B2=f2[P2])==null||q2||(B2.nodeType==8&&B2.data=="$s"?(T2>0&&u2.__c.__z.push(B2),T2++,f2[P2]=null):B2.nodeType==8&&B2.data=="/$s"?(--T2>0&&u2.__c.__z.push(B2),q2=T2===0,o2=f2[P2],f2[P2]=null):T2>0&&(u2.__c.__z.push(B2),f2[P2]=null));if(!q2){for(;o2&&o2.nodeType==8&&o2.nextSibling;)o2=o2.nextSibling;f2[f2.indexOf(o2)]=null,u2.__c.__z=[o2]}u2.__e=o2}else{for(D2=f2.length;D2--;)d$1(f2[D2]);N(u2)}else u2.__e=t2.__e,u2.__k=t2.__k,l3.then||N(u2);n.__e(l3,u2,t2)}else o2=u2.__e=z$1(t2.__e,u2,t2,i2,r2,f2,e2,c2,s2,a2);return(h2=n.diffed)&&h2(u2),128&u2.__u?void 0:o2}function N(n2){n2&&n2.__c&&(n2.__c.__g|=4),n2&&n2.__k&&n2.__k.forEach(N)}function P(l2,u2,t2){for(var i2=0;i2<t2.length;i2++)B$1(t2[i2],t2[++i2],t2[++i2]);n.__c&&n.__c(u2,l2),l2.some(function(u3){try{l2=u3.__h,u3.__h=[],l2.some(function(n2){n2.call(u3)})}catch(l3){n.__e(l3,u3.__v)}})}function V(n2){return typeof n2!="object"||n2==null||n2.__b&&n2.__b>0?n2:v$1(n2)?n2.map(V):w$1({},n2)}function z$1(l2,u2,t2,i2,r2,f2,e2,o2,c2,s2){var a2,p2,w2,_2,g2,b2,k2,m2,S2=t2.props,$2=u2.props,x2=u2.type;if(x2=="svg"?r2="http://www.w3.org/2000/svg":x2=="math"?r2="http://www.w3.org/1998/Math/MathML":r2||(r2="http://www.w3.org/1999/xhtml"),f2!=null){for(a2=0;a2<f2.length;a2++)if((g2=f2[a2])&&"setAttribute"in g2==!!x2&&(x2?g2.localName==x2:g2.nodeType==3)){l2=g2,f2[a2]=null;break}}if(l2==null){if(x2==null)return s2.createTextNode($2);l2=s2.createElementNS(r2,x2,$2.is&&$2),o2&&(n.__m&&n.__m(u2,f2),o2=!1),f2=null}if(x2==null)S2===$2||o2&&l2.data==$2||(l2.data=$2);else{if(f2=f2&&y$1.call(l2.childNodes),S2=t2.props||h$1,!o2&&f2!=null)for(S2={},a2=0;a2<l2.attributes.length;a2++)S2[(g2=l2.attributes[a2]).name]=g2.value;for(a2 in S2)if(g2=S2[a2],a2!="children"){if(a2=="dangerouslySetInnerHTML")w2=g2;else if(!(a2 in $2)){if(a2=="value"&&"defaultValue"in $2||a2=="checked"&&"defaultChecked"in $2)continue;O(l2,a2,null,g2,r2)}}for(a2 in m2=1&t2.__u,$2)g2=$2[a2],a2=="children"?_2=g2:a2=="dangerouslySetInnerHTML"?p2=g2:a2=="value"?b2=g2:a2=="checked"?k2=g2:o2&&typeof g2!="function"||S2[a2]===g2&&!m2||O(l2,a2,g2,S2[a2],r2);if(p2)o2||w2&&(p2.__html==w2.__html||p2.__html==l2.innerHTML)||(l2.innerHTML=p2.__html),u2.__k=[];else if(w2&&(l2.innerHTML=""),C$1(x2=="template"?l2.content:l2,v$1(_2)?_2:[_2],u2,t2,i2,x2=="foreignObject"?"http://www.w3.org/1999/xhtml":r2,f2,e2,f2?f2[0]:t2.__k&&M(t2,0),o2,c2,s2),f2!=null)for(a2=f2.length;a2--;)d$1(f2[a2]);o2||(a2="value",x2=="progress"&&b2==null?l2.removeAttribute("value"):b2==null||b2===l2[a2]&&(x2!=="progress"||b2)||O(l2,a2,b2,S2[a2],r2),a2="checked",k2!=null&&k2!=l2[a2]&&O(l2,a2,k2,S2[a2],r2))}return l2}function B$1(l2,u2,t2){try{if(typeof l2=="function"){var i2=typeof l2.__u=="function";i2&&l2.__u(),i2&&u2==null||(l2.__u=l2(u2))}else l2.current=u2}catch(l3){n.__e(l3,t2)}}function D$1(l2,u2,t2){var i2,r2;if(n.unmount&&n.unmount(l2),(i2=l2.ref)&&(i2.current&&i2.current!=l2.__e||B$1(i2,null,u2)),(i2=l2.__c)!=null){if(i2.componentWillUnmount)try{i2.componentWillUnmount()}catch(l3){n.__e(l3,u2)}i2.__P=null}if(i2=l2.__k)for(r2=0;r2<i2.length;r2++)i2[r2]&&D$1(i2[r2],u2,t2||typeof l2.type!="function");t2||d$1(l2.__e),l2.__e&&l2.__e.__l&&(l2.__e.__l=null),l2.__e=l2.__c=l2.__=null}function E(n2,l2,u2){return this.constructor(n2,u2)}function F$1(l2,u2){var t2,i2,r2,f2;u2==document&&(u2=document.documentElement),n.__&&n.__(l2,u2),i2=(t2=!!(l2&&32&l2.__u))?null:u2.__k,l2=u2.__k=_$1(k$1,null,[l2]),r2=[],f2=[],q$1(u2,l2,i2||h$1,h$1,u2.namespaceURI,i2?null:u2.firstChild?y$1.call(u2.childNodes):null,r2,i2?i2.__e:u2.firstChild,t2,f2,u2.ownerDocument),P(r2,l2,f2)}function G(n2,l2){n2.__u|=32,F$1(n2,l2)}n={__e:function(n2,l2,u2,t2){for(var i2,f2,e2;l2=l2.__;)if((i2=l2.__c)&&!(1&i2.__g)){i2.__g|=4;try{if((f2=i2.constructor)&&f2.getDerivedStateFromError!=null&&(i2.setState(f2.getDerivedStateFromError(n2)),e2=8&i2.__g),i2.componentDidCatch!=null&&(i2.componentDidCatch(n2,t2||{}),e2=8&i2.__g),e2)return void(i2.__g|=2)}catch(l3){n2=l3}}throw r$1=0,n2}},l$1=0,m$1.prototype.setState=function(n2,l2){var u2;u2=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=w$1({},this.state),typeof n2=="function"&&(n2=n2(w$1({},u2),this.props)),n2&&w$1(u2,n2),n2!=null&&this.__v&&(l2&&this._sb.push(l2),$(this))},m$1.prototype.forceUpdate=function(n2){this.__v&&(this.__g|=4,n2&&this.__h.push(n2),$(this))},m$1.prototype.render=k$1,t$1=[],r$1=0,f$1=function(n2,l2){return n2.__v.__b-l2.__v.__b},e$1=/(PointerCapture)$|Capture$/i,o$2=0,c$1=T(!1),s$1=T(!0);var o$1=0;function u$1(t2,e2,n$1,f2,u2,i2){e2||(e2={});var a2,c2,l2=e2;if("ref"in l2&&typeof t2!="function")for(c2 in l2={},e2)c2=="ref"?a2=e2[c2]:l2[c2]=e2[c2];var p2={type:t2,props:l2,key:n$1,ref:a2,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--o$1,__i:-1,__u:0,__source:u2,__self:i2};return n.vnode&&n.vnode(p2),p2}const DEFAULT_WIDTH=16,DEFAULT_HEIGHT=16,ICON_SIZE_OVERRIDES={};function Icon({name,remappedFrom,token,width:propWidth,height:propHeight,viewBox:propViewBox,label,alignCapitals=!1}){"use no memo";const href=`#${name.replace(/^#/,"")}`,{width:iconWidth,height:iconHeight,viewBox:overrideViewBox}=ICON_SIZE_OVERRIDES[name]??{width:DEFAULT_WIDTH,height:DEFAULT_HEIGHT},width=propWidth??iconWidth,height=propHeight??iconHeight,viewBox=propViewBox??overrideViewBox??`0 0 ${iconWidth} ${iconHeight}`;return u$1("svg",{"data-icon-name":remappedFrom??name,"data-icon-token":token,"data-align-capitals":alignCapitals,...label!=null?{"aria-label":label,role:"img"}:{"aria-hidden":!0},viewBox,width,height,children:u$1("use",{href})})}const isWhitespace=char=>char!==void 0&&/\s/.test(char),avoidWhitespaceBoundary=(contents,centerIndex)=>{const isOnBoundary=index=>isWhitespace(contents[index-1])||isWhitespace(contents[index]);if(!isOnBoundary(centerIndex))return centerIndex;for(let offset=1;offset<contents.length;offset++){const before2=centerIndex-offset;if(before2>0&&!isOnBoundary(before2))return before2;const after=centerIndex+offset;if(after<contents.length&&!isOnBoundary(after))return after}return centerIndex},centerSplitIndex=contents=>avoidWhitespaceBoundary(contents,Math.ceil(contents.length/2)),splitCenter=contents=>{if(contents.length<2)return[contents,""];const splitIndex=centerSplitIndex(contents);return[contents.slice(0,splitIndex),contents.slice(splitIndex)]},splitExtension=contents=>{if(contents.length<4)return[contents,""];const extensionIndex=contents.lastIndexOf(".")+1,isTooLong=contents.length-extensionIndex>10,splitIndex=extensionIndex>=1&&!isTooLong?extensionIndex:centerSplitIndex(contents);return[contents.slice(0,splitIndex),contents.slice(splitIndex)]},splitLeafPath=contents=>{if(contents.length<4)return[contents,""];const leafPathIndex=contents.lastIndexOf("/")+1,isTooLong=contents.length-leafPathIndex>25,splitIndex=leafPathIndex>=1&&!isTooLong?leafPathIndex:Math.ceil(contents.length/2);return[contents.slice(0,splitIndex),contents.slice(splitIndex)]},splitByIndex=(contents,{splitIndex}={})=>{if(typeof splitIndex!="number"){const centerIndex=Math.ceil(contents.length/2);return[contents.slice(0,centerIndex),contents.slice(centerIndex)]}return[contents.slice(0,splitIndex),contents.slice(splitIndex)]},splitLast=(contents,{splitOffset}={})=>{if(typeof splitOffset!="number"||splitOffset<=0||splitOffset>=contents.length){const centerIndex=Math.ceil(contents.length/2);return[contents.slice(0,centerIndex),contents.slice(centerIndex)]}const splitIndex=contents.length-splitOffset;return[contents.slice(0,splitIndex),contents.slice(splitIndex)]},splitFirst=(contents,{splitOffset}={})=>{if(typeof splitOffset!="number"||splitOffset<=0||splitOffset>=contents.length){const centerIndex=Math.ceil(contents.length/2);return[contents.slice(0,centerIndex),contents.slice(centerIndex)]}const splitIndex=splitOffset;return[contents.slice(0,splitIndex),contents.slice(splitIndex)]};function OverflowMarker({children,marker,variant="default"}){"use no memo";return u$1("div",{"aria-hidden":!0,"data-truncate-marker-cell":!0,children:u$1("div",{"data-truncate-marker":!0,children:typeof marker=="function"?marker({children}):variant==="fade"?u$1("span",{"data-truncate-fade":!0}):marker})})}function OverflowContent(options){"use no memo";const{mode,children}=options;return u$1("div",{children:[u$1("div",{"data-truncate-content":"visible",children:mode==="fruncate"?u$1("span",{children}):children}),u$1("div",{"data-truncate-content":"overflow","aria-hidden":!0,children:mode==="fruncate"?u$1("span",{children}):children})]})}function OverflowText({children,mode="truncate",marker="…",variant="default",...props}){"use no memo";const contentNode=u$1(OverflowContent,{mode,children},"content"),markerNode=u$1(OverflowMarker,{marker,mode,variant},"marker");return u$1("div",{"data-truncate-container":mode,"data-truncate-variant":variant,...props,children:u$1("div",{"data-truncate-grid":!0,children:mode==="truncate"?[contentNode,markerNode]:[markerNode,contentNode,u$1("div",{"data-truncate-fill":!0},"fill")]})})}function Truncate({children,...props}){"use no memo";return u$1(OverflowText,{mode:"truncate",...props,children})}function Fruncate({children,...props}){"use no memo";return u$1(OverflowText,{mode:"fruncate",...props,children})}function MiddleTruncate({children,contents,priority="end",split="center",minimumLength=12,className,style,...props}){"use no memo";let firstSegment=null,secondSegment=null;if(Array.isArray(contents)){if(contents.length!==2)return console.error("MiddleTruncate: contents must be an array of two items"),null;firstSegment=u$1(Truncate,{...props,children:contents[0]}),secondSegment=u$1(Fruncate,{...props,children:contents[1]})}else{if(typeof children!="string")return console.error("MiddleTruncate: children must be a string"),null;if(children.length===0)return u$1("div",{className,style});if(children.length<minimumLength)return priority==="end"?u$1(Fruncate,{...props,className,style,children}):u$1(Truncate,{...props,className,style,children});let splitFn=null,splitIndex=null,splitOffset=null;if(typeof split=="string")split==="center"?splitFn=splitCenter:split==="extension"?splitFn=splitExtension:split==="leaf-path"&&(splitFn=splitLeafPath);else if(typeof split=="number")splitFn=splitByIndex,splitIndex=split;else if(Array.isArray(split)){const[offsetType,offsetValue]=split;splitOffset=offsetValue,offsetType==="last"?splitFn=splitLast:offsetType==="first"&&(splitFn=splitFirst)}else typeof split=="function"&&(splitFn=split);splitFn??=splitCenter;const[firstHalfMessage,secondHalfMessage]=splitFn(children,{priority,variant:props.variant,splitIndex:typeof splitIndex=="number"?splitIndex:void 0,splitOffset:typeof splitOffset=="number"?splitOffset:void 0}),firstIsLarger=firstHalfMessage.length>=secondHalfMessage.length,firstCanBeSimple=priority==="equal"&&!firstIsLarger,secondCanBeSimple=priority==="equal"&&firstIsLarger,firstPropOverrides={},secondPropOverrides={};firstCanBeSimple&&(firstPropOverrides.marker=""),secondCanBeSimple&&(secondPropOverrides.marker=""),firstSegment=u$1(Truncate,{...props,...firstPropOverrides,children:firstHalfMessage}),secondSegment=u$1(Fruncate,{...props,...secondPropOverrides,children:secondHalfMessage})}return u$1("div",{"data-truncate-group-container":"middle",className,style,children:[u$1("div",{"data-truncate-segment-priority":priority==="start"||priority==="equal"?"1":"2",children:firstSegment}),u$1("div",{"data-truncate-segment-priority":priority==="end"||priority==="equal"?"1":"2",children:secondSegment})]})}const EMPTY_FILE_TREE_LAYOUT_RANGE={endIndex:-1,startIndex:-1};function clamp(value,minimum,maximum){return Math.min(Math.max(value,minimum),maximum)}function createRange(startIndex,endIndex){return startIndex<0||endIndex<startIndex?EMPTY_FILE_TREE_LAYOUT_RANGE:{endIndex,startIndex}}function isEmptyRange(range2){return range2.startIndex<0||range2.endIndex<range2.startIndex}function getRangeHeight(range2,itemHeight){return isEmptyRange(range2)?0:(range2.endIndex-range2.startIndex+1)*itemHeight}function getFirstIntersectingIndex(offset,itemCount,itemHeight){if(itemCount<=0)return-1;const totalHeight=itemCount*itemHeight;return offset<=0?0:offset>=totalHeight?itemCount:Math.floor(offset/itemHeight)}function getLastIntersectingIndex(bottomOffset,itemCount,itemHeight){return itemCount<=0||bottomOffset<=0?-1:bottomOffset>=itemCount*itemHeight?itemCount-1:Math.ceil(bottomOffset/itemHeight)-1}function getExpandedDirectoryIndicesByDepth(rows){const indicesByDepth=new Map;return rows.forEach((row,index)=>{if(row.kind!=="directory"||!row.isExpanded)return;const depth=row.ancestorPaths.length,indices=indicesByDepth.get(depth);if(indices==null){indicesByDepth.set(depth,[index]);return}indices.push(index)}),indicesByDepth}function findLastIndexAtOrBefore(indices,threshold){let lowerBound=0,upperBound=indices.length-1,match=-1;for(;lowerBound<=upperBound;){const midpoint=Math.floor((lowerBound+upperBound)/2),index=indices[midpoint];if(index==null)break;if(index<=threshold){match=midpoint,lowerBound=midpoint+1;continue}upperBound=midpoint-1}return match}function computeExpandedSubtreeEndIndices(rows){const endIndexByPath=new Map,openDirectoryPaths=[];for(let index=0;index<rows.length;index+=1){const row=rows[index];if(row==null)continue;const activePaths=row.kind==="directory"&&row.isExpanded?[...row.ancestorPaths,row.path]:row.ancestorPaths;let sharedPrefixLength=0;for(;sharedPrefixLength<openDirectoryPaths.length&&sharedPrefixLength<activePaths.length&&openDirectoryPaths[sharedPrefixLength]===activePaths[sharedPrefixLength];)sharedPrefixLength+=1;for(let openIndex=openDirectoryPaths.length-1;openIndex>=sharedPrefixLength;openIndex-=1){const path=openDirectoryPaths[openIndex];path!=null&&endIndexByPath.set(path,index-1)}openDirectoryPaths.length=sharedPrefixLength;for(let activeIndex=sharedPrefixLength;activeIndex<activePaths.length;activeIndex+=1){const path=activePaths[activeIndex];path!=null&&openDirectoryPaths.push(path)}}const lastIndex=rows.length-1;for(const path of openDirectoryPaths)endIndexByPath.set(path,lastIndex);return endIndexByPath}function computeStickyRows(rows,scrollTop,itemHeight){if(rows.length===0||scrollTop<=0)return[];const subtreeEndIndexByPath=computeExpandedSubtreeEndIndices(rows),expandedDirectoryIndicesByDepth=getExpandedDirectoryIndicesByDepth(rows),stickyRows=[];for(let slotDepth=0;slotDepth<rows.length;slotDepth+=1){const candidateIndices=expandedDirectoryIndicesByDepth.get(slotDepth);if(candidateIndices==null||candidateIndices.length===0)break;const slotTop=scrollTop+slotDepth*itemHeight;let candidateOffset=findLastIndexAtOrBefore(candidateIndices,Math.min(rows.length-1,Math.floor(slotTop/itemHeight))),candidate=null;for(;candidateOffset>=0;){const rowIndex=candidateIndices[candidateOffset],row=rowIndex==null?null:rows[rowIndex]??null;if(row!=null&&(slotDepth===0||row.ancestorPaths[slotDepth-1]===stickyRows[slotDepth-1]?.path)){candidate=row;break}candidateOffset-=1}if(candidate==null)break;stickyRows.push(candidate)}return stickyRows.map((row,slotDepth)=>{const defaultTop=slotDepth*itemHeight,nextBoundaryIndex=(subtreeEndIndexByPath.get(row.path)??rows.length-1)+1;if(nextBoundaryIndex>=rows.length)return{row,top:defaultTop};const nextBoundaryTop=nextBoundaryIndex*itemHeight-scrollTop;return{row,top:Math.min(defaultTop,nextBoundaryTop-itemHeight)}}).filter(entry=>entry.top+itemHeight>0)}function computeFileTreeLayout(rows,metrics){const totalRowCount=metrics.totalRowCount??rows.length,totalHeight=totalRowCount*metrics.itemHeight,viewportHeight=Math.max(0,metrics.viewportHeight),overscan=Math.max(0,Math.floor(metrics.overscan)),maxScrollTop=Math.max(0,totalHeight-viewportHeight),scrollTop=clamp(metrics.scrollTop,0,maxScrollTop),stickyRows=metrics.stickyRows??computeStickyRows(rows,scrollTop,metrics.itemHeight),stickyHeight=stickyRows.reduce((maximumBottom,entry)=>Math.max(maximumBottom,entry.top+metrics.itemHeight),0),paneTop=Math.min(totalHeight,scrollTop+stickyHeight),paneHeight=Math.max(0,viewportHeight-stickyHeight),contentHeight=Math.max(0,totalHeight-paneTop),firstVisiblePhysicalIndex=getFirstIntersectingIndex(scrollTop,totalRowCount,metrics.itemHeight),firstProjectedIndex=getFirstIntersectingIndex(paneTop,totalRowCount,metrics.itemHeight),firstOccludedIndex=stickyHeight<=0||firstVisiblePhysicalIndex<0||firstVisiblePhysicalIndex>=totalRowCount?-1:firstVisiblePhysicalIndex,lastOccludedIndex=firstOccludedIndex===-1?-1:Math.min(totalRowCount-1,firstProjectedIndex-1),occludedCount=firstOccludedIndex===-1||lastOccludedIndex<firstOccludedIndex?0:lastOccludedIndex-firstOccludedIndex+1,visible=paneHeight<=0||firstProjectedIndex>=totalRowCount?EMPTY_FILE_TREE_LAYOUT_RANGE:createRange(firstProjectedIndex,getLastIntersectingIndex(paneTop+paneHeight,totalRowCount,metrics.itemHeight)),minimumWindowStart=lastOccludedIndex+1,windowRange=isEmptyRange(visible)?EMPTY_FILE_TREE_LAYOUT_RANGE:createRange(Math.max(minimumWindowStart,visible.startIndex-overscan),Math.min(totalRowCount-1,visible.endIndex+overscan)),windowHeight=getRangeHeight(windowRange,metrics.itemHeight);return{occlusion:{firstOccludedIndex,lastOccludedIndex,occludedCount},physical:{itemHeight:metrics.itemHeight,maxScrollTop,overscan,scrollTop,totalHeight,totalRowCount,viewportHeight},projected:{contentHeight,paneHeight,paneTop},sticky:{height:stickyHeight,rows:stickyRows},visible,window:{endIndex:windowRange.endIndex,height:windowHeight,offsetTop:isEmptyRange(windowRange)?0:windowRange.startIndex*metrics.itemHeight,startIndex:windowRange.startIndex}}}const GIT_STATUS_LABEL={added:"A",deleted:"D",ignored:null,modified:"M",renamed:"R",untracked:"U"},GIT_STATUS_TITLE={added:"Git status: added",deleted:"Git status: deleted",ignored:"Git status: ignored",modified:"Git status: modified",renamed:"Git status: renamed",untracked:"Git status: untracked"},GIT_STATUS_DESCENDANT_TITLE="Contains git status items";function shouldBumpControllerRevision(hasSeenInitialSnapshot){return hasSeenInitialSnapshot.current?!0:(hasSeenInitialSnapshot.current=!0,!1)}function computeFocusedRowScrollIntoView(input){const{currentScrollTop,focusedIndex,itemHeight,topInset=0,viewportHeight}=input;if(focusedIndex<0)return null;const effectiveInset=Math.max(0,topInset),itemTop=focusedIndex*itemHeight,itemBottom=itemTop+itemHeight;if(itemTop<currentScrollTop+effectiveInset){const nextScrollTop=Math.max(0,itemTop-effectiveInset);return nextScrollTop===currentScrollTop?null:nextScrollTop}if(itemBottom>currentScrollTop+viewportHeight){const nextScrollTop=itemBottom-viewportHeight;return nextScrollTop===currentScrollTop?null:nextScrollTop}return null}function computeFocusedRowScrollTopForOffset(input){const{currentScrollTop,focusedIndex,itemHeight,offset,topInset=0,totalHeight,viewportHeight}=input;if(offset==="nearest")return computeFocusedRowScrollIntoView({currentScrollTop,focusedIndex,itemHeight,topInset,viewportHeight});if(focusedIndex<0)return null;const effectiveInset=Math.max(0,topInset),itemTop=focusedIndex*itemHeight,visibleHeight=Math.max(0,viewportHeight-effectiveInset),targetViewportOffset=offset==="center"?effectiveInset+Math.max(0,(visibleHeight-itemHeight)/2):effectiveInset,maxScrollTop=Math.max(0,totalHeight-viewportHeight),nextScrollTop=Math.max(0,Math.min(itemTop-targetViewportOffset,maxScrollTop));return nextScrollTop===currentScrollTop?null:nextScrollTop}function computeViewportOffsetScrollTop(input){const{currentScrollTop,focusedIndex,itemHeight,targetViewportOffset,totalHeight,viewportHeight}=input;if(focusedIndex<0)return null;const effectiveOffset=Math.max(0,targetViewportOffset),itemTop=focusedIndex*itemHeight,itemBottom=itemTop+itemHeight,currentViewportTop=currentScrollTop+effectiveOffset,currentViewportBottom=currentScrollTop+viewportHeight;if(itemTop>=currentViewportTop&&itemBottom<=currentViewportBottom)return null;const maxScrollTop=Math.max(0,totalHeight-viewportHeight),preservedScrollTop=Math.max(0,Math.min(itemTop-effectiveOffset,maxScrollTop));return preservedScrollTop===currentScrollTop?null:preservedScrollTop}function focusElement(element){if(element==null||!element.isConnected||element===document.body||element===document.documentElement)return!1;element.focus({preventScroll:!0});const rootNode=element.getRootNode();return rootNode instanceof ShadowRoot?rootNode.activeElement===element:document.activeElement===element}function getActiveTreeElement(rootElement){const rootNode=rootElement.getRootNode();if(rootNode instanceof ShadowRoot){const activeElement2=rootNode.activeElement;return activeElement2 instanceof HTMLElement?activeElement2:null}const activeElement=document.activeElement;return activeElement instanceof HTMLElement&&rootElement.contains(activeElement)?activeElement:null}function readMeasuredViewportHeight(scrollElement,fallbackViewportHeight){if(scrollElement==null)return fallbackViewportHeight;const rectHeight=scrollElement.getBoundingClientRect().height;return rectHeight>0?rectHeight:scrollElement.clientHeight>0?scrollElement.clientHeight:fallbackViewportHeight}function getCachedViewportHeight(cachedViewportHeight,fallbackViewportHeight){return cachedViewportHeight!=null&&cachedViewportHeight>0?cachedViewportHeight:fallbackViewportHeight}function getResizeObserverViewportHeight(entry){const borderBoxSize=entry.borderBoxSize,firstBorderBoxSize=Array.isArray(borderBoxSize)?borderBoxSize[0]:borderBoxSize;return firstBorderBoxSize!=null&&Number.isFinite(firstBorderBoxSize.blockSize)&&firstBorderBoxSize.blockSize>0?firstBorderBoxSize.blockSize:entry.contentRect.height>0?entry.contentRect.height:null}function scrollFocusedRowIntoView(scrollElement,focusedIndex,itemHeight,viewportHeight,topInset=0){const nextScrollTop=computeFocusedRowScrollIntoView({currentScrollTop:scrollElement.scrollTop,focusedIndex,itemHeight,topInset,viewportHeight});return nextScrollTop==null?!1:(scrollElement.scrollTop=nextScrollTop,!0)}function scrollFocusedRowToOffset(scrollElement,focusedIndex,itemHeight,viewportHeight,totalHeight,offset,topInset=0){const nextScrollTop=computeFocusedRowScrollTopForOffset({currentScrollTop:scrollElement.scrollTop,focusedIndex,itemHeight,offset,topInset,totalHeight,viewportHeight});return nextScrollTop==null?!1:(scrollElement.scrollTop=nextScrollTop,!0)}function scrollFocusedRowToViewportOffset(scrollElement,focusedIndex,itemHeight,viewportHeight,totalHeight,targetViewportOffset){const nextScrollTop=computeViewportOffsetScrollTop({currentScrollTop:scrollElement.scrollTop,focusedIndex,itemHeight,targetViewportOffset,totalHeight,viewportHeight});return nextScrollTop==null?!1:(scrollElement.scrollTop=nextScrollTop,!0)}function getParkedFocusedRowOffset(focusedIndex,itemHeight,range2,windowHeight){return range2.end<range2.start?null:focusedIndex<range2.start?-itemHeight:focusedIndex>range2.end?windowHeight:null}function classifyFileTreeRenameHandoff(input){const{renamingPath,previousRenamingPath,hasRenderedInput}=input;return renamingPath==null?"reset":hasRenderedInput?previousRenamingPath===renamingPath?"ignore":"focus-input":"reveal-canonical"}function RenameInput({ariaLabel,isFlattened=!1,ref,value,onBlur,onInput}){return u$1("input",{ref,"data-item-rename-input":!0,...isFlattened?{"data-item-flattened-rename-input":!0}:{},"aria-label":ariaLabel,value,onBlur,onInput,onClick:event=>event.stopPropagation(),onMouseDown:event=>event.stopPropagation(),onPointerDown:event=>event.stopPropagation()})}function computeFileTreeRowElementAttributes(input){const{row,mode,targetPath,ariaLabel,domId,isParked,itemHeight,features,state,extraStyle}=input,isSticky=mode==="sticky",parentPath=row.ancestorPaths.at(-1)??"",stateAttributes={};return state.isFocusRinged&&(stateAttributes["data-item-focused"]=!0),row.isSelected&&(stateAttributes["data-item-selected"]=!0),state.isContextHovered&&(stateAttributes["data-item-context-hover"]="true"),state.isDragTarget&&(stateAttributes["data-item-drag-target"]=!0),state.isDragging&&(stateAttributes["data-item-dragging"]=!0),state.effectiveGitStatus!=null&&(stateAttributes["data-item-git-status"]=state.effectiveGitStatus),state.containsGitChange&&(stateAttributes["data-item-contains-git-change"]="true"),{"aria-expanded":!isSticky&&row.kind==="directory"?row.isExpanded:void 0,"aria-haspopup":features.contextMenuEnabled?"menu":void 0,"aria-label":ariaLabel,"aria-level":isSticky?void 0:row.level+1,"aria-posinset":isSticky?void 0:row.posInSet+1,"aria-selected":isSticky?void 0:row.isSelected?"true":"false","aria-setsize":isSticky?void 0:row.setSize,"data-file-tree-sticky-path":isSticky?targetPath:void 0,"data-file-tree-sticky-row":isSticky?"true":void 0,"data-item-context-menu-button-visibility":features.actionLaneEnabled?features.contextMenuButtonVisibility:void 0,"data-item-context-menu-trigger-mode":features.contextMenuEnabled?features.contextMenuTriggerMode:void 0,"data-item-has-context-menu-action-lane":features.actionLaneEnabled?"true":void 0,"data-item-has-git-lane":features.gitLaneActive?"true":void 0,"data-item-parent-path":parentPath.length>0?parentPath:void 0,"data-item-parked":isParked?"true":void 0,"data-item-path":targetPath,"data-item-type":row.kind==="directory"?"folder":"file","data-type":"item",id:isSticky?void 0:domId,role:isSticky?void 0:"treeitem",style:{minHeight:`${itemHeight}px`,...extraStyle},tabIndex:!isSticky&&row.isFocused?0:-1,...stateAttributes}}function computeFileTreeRowClickPlan(input){const{event,mode,isSearchOpen,isDirectory}=input,additive=event.ctrlKey||event.metaKey,hasModifier=event.shiftKey||additive,selection=event.shiftKey?{additive,kind:"range"}:additive?{kind:"toggle"}:{kind:"single"};return{closeSearch:isSearchOpen,revealCanonical:mode==="sticky",selection,toggleDirectory:!hasModifier&&isDirectory}}var t,r,u,i,o=Object.is,f=0,c=[],e=n,a=e.__b,v=e.__r,l=e.diffed,m=e.__c,s=e.unmount,p=e.__;function d(n2,t2){e.__h&&e.__h(r,n2,f||t2),f=0;var u2=r.__H||(r.__H={__:[],__h:[]});return n2>=u2.__.length&&u2.__.push({}),u2.__[n2]}function h(n2){return f=1,y(D,n2)}function y(n2,u2,i2){var f2=d(t++,2);if(f2.t=n2,!f2.__c&&(f2.__=[D(void 0,u2),function(n3){var t2=f2.__N?f2.__N[0]:f2.__[0],r2=f2.t(t2,n3);o(t2,r2)||(f2.__N=[r2,f2.__[1]],f2.__c.setState({}))}],f2.__c=r,!r.__f)){var c2=function(n3,t2,r2){if(!f2.__c.__H)return!0;var u3=f2.__c.__H.__.filter(function(n4){return!!n4.__c});if(u3.every(function(n4){return!n4.__N}))return!e2||e2.call(this,n3,t2,r2);var i3=f2.__c.props!==n3;return u3.forEach(function(n4){if(n4.__N){var t3=n4.__[0];n4.__=n4.__N,n4.__N=void 0,o(t3,n4.__[0])||(i3=!0)}}),e2&&e2.call(this,n3,t2,r2)||i3};r.__f=!0;var e2=r.shouldComponentUpdate,a2=r.componentWillUpdate;r.componentWillUpdate=function(n3,t2,r2){if(4&this.__g){var u3=e2;e2=void 0,c2(n3,t2,r2),e2=u3}a2&&a2.call(this,n3,t2,r2)},r.shouldComponentUpdate=c2}return f2.__N||f2.__}function _(n2,u2){var i2=d(t++,3);!e.__s&&C(i2.__H,u2)&&(i2.__=n2,i2.u=u2,r.__H.__h.push(i2))}function A(n2,u2){var i2=d(t++,4);!e.__s&&C(i2.__H,u2)&&(i2.__=n2,i2.u=u2,r.__h.push(i2))}function F(n2){return f=5,q(function(){return{current:n2}},[])}function q(n2,r2){var u2=d(t++,7);return C(u2.__H,r2)&&(u2.__=n2(),u2.__H=r2,u2.__h=n2),u2.__}function b(n2,t2){return f=8,q(function(){return n2},t2)}function g(){for(var n2;n2=c.shift();)if(n2.__P&&n2.__H)try{n2.__H.__h.forEach(z),n2.__H.__h.forEach(B),n2.__H.__h=[]}catch(t2){n2.__H.__h=[],e.__e(t2,n2.__v)}}e.__b=function(n2){r=null,a&&a(n2)},e.__=function(n2,t2){n2&&t2.__k&&t2.__k.__m&&(n2.__m=t2.__k.__m),p&&p(n2,t2)},e.__r=function(n2){v&&v(n2),t=0;var i2=(r=n2.__c).__H;i2&&(u===r?(i2.__h=[],r.__h=[],i2.__.forEach(function(n3){n3.__N&&(n3.__=n3.__N),n3.u=n3.__N=void 0})):(i2.__h.forEach(z),i2.__h.forEach(B),i2.__h=[],t=0)),u=r},e.diffed=function(n2){l&&l(n2);var t2=n2.__c;t2&&t2.__H&&(t2.__H.__h.length&&(c.push(t2)!==1&&i===e.requestAnimationFrame||((i=e.requestAnimationFrame)||w)(g)),t2.__H.__.forEach(function(n3){n3.u&&(n3.__H=n3.u),n3.u=void 0})),u=r=null},e.__c=function(n2,t2){t2.some(function(n3){try{n3.__h.forEach(z),n3.__h=n3.__h.filter(function(n4){return!n4.__||B(n4)})}catch(r2){t2.some(function(n4){n4.__h&&(n4.__h=[])}),t2=[],e.__e(r2,n3.__v)}}),m&&m(n2,t2)},e.unmount=function(n2){s&&s(n2);var t2,r2=n2.__c;r2&&r2.__H&&(r2.__H.__.forEach(function(n3){try{z(n3)}catch(n4){t2=n4}}),r2.__H=void 0,t2&&e.__e(t2,r2.__v))};var k=typeof requestAnimationFrame=="function";function w(n2){var t2,r2=function(){clearTimeout(u2),k&&cancelAnimationFrame(t2),setTimeout(n2)},u2=setTimeout(r2,35);k&&(t2=requestAnimationFrame(r2))}function z(n2){var t2=r,u2=n2.__c;typeof u2=="function"&&(n2.__c=void 0,u2()),r=t2}function B(n2){var t2=r;n2.__c=n2.__(),r=t2}function C(n2,t2){return!n2||n2.length!==t2.length||t2.some(function(t3,r2){return!o(t3,n2[r2])})}function D(n2,t2){return typeof t2=="function"?t2(n2):t2}function formatFlattenedSegments(row,renameInput=null,dragTargetFlattenedSegmentPath=null){"use no memo";const segments=row.flattenedSegments;return segments==null||segments.length===0?renameInput??row.name:u$1("span",{"data-item-flattened-subitems":!0,children:segments.map((segment,index)=>{const isLast=index===segments.length-1;return u$1(k$1,{children:[u$1("span",{"data-item-flattened-subitem":segment.path,"data-item-flattened-subitem-drag-target":dragTargetFlattenedSegmentPath===segment.path?"true":void 0,children:isLast&&renameInput!=null?renameInput:u$1(Truncate,{children:segment.name})}),index<segments.length-1?" / ":""]},segment.path)})})}function getFileTreeRowPath(row){return row.isFlattened?row.flattenedSegments?.findLast(segment=>segment.isTerminal)?.path??row.path:row.path}function getFileTreeRowAriaLabel(row){const flattenedSegments=row.flattenedSegments;return flattenedSegments==null||flattenedSegments.length===0?row.name:flattenedSegments.map(segment=>segment.name).join(" / ")}function computeStickyRowsFromCandidates(candidates,scrollTop,itemHeight,totalRowCount){return candidates.map((candidate,slotDepth)=>{const defaultTop=slotDepth*itemHeight,nextBoundaryIndex=candidate.subtreeEndIndex+1;if(nextBoundaryIndex>=totalRowCount)return{row:candidate.row,top:defaultTop};const nextBoundaryTop=nextBoundaryIndex*itemHeight-scrollTop;return{row:candidate.row,top:Math.min(defaultTop,nextBoundaryTop-itemHeight)}}).filter(entry=>entry.top+itemHeight>0)}function computeFileTreeViewLayoutState({controller,itemHeight,overscan,scrollTop,stickyFolders,viewportHeight}){const visibleCount=controller.getVisibleCount(),stickyCandidates=stickyFolders&&visibleCount>0?controller.getStickyRowCandidates(scrollTop,itemHeight):[],visibleRows=stickyCandidates==null&&stickyFolders&&visibleCount>0?controller.getVisibleRows(0,visibleCount-1):[],snapshot=computeFileTreeLayout(visibleRows,{itemHeight,overscan,scrollTop,stickyRows:stickyCandidates==null?void 0:computeStickyRowsFromCandidates(stickyCandidates,scrollTop,itemHeight,visibleCount),totalRowCount:visibleCount,viewportHeight}),previewStickyCandidates=stickyFolders&&scrollTop<=0&&visibleCount>0?controller.getStickyRowCandidates(1,itemHeight):[],overlayRows=previewStickyCandidates!=null&&scrollTop<=0?computeStickyRowsFromCandidates(previewStickyCandidates,1,itemHeight,visibleCount):stickyFolders&&scrollTop<=0&&visibleRows.length>0?computeStickyRows(visibleRows,1,itemHeight):snapshot.sticky.rows;return{overlayHeight:overlayRows.reduce((maxBottom,entry)=>Math.max(maxBottom,entry.top+itemHeight),0),overlayRows,snapshot,visibleRows}}const TOUCH_LONG_PRESS_DELAY=400,TOUCH_LONG_PRESS_MOVE_THRESHOLD=10,DRAG_EDGE_SCROLL_THRESHOLD=40,DRAG_EDGE_SCROLL_MAX_SPEED=18;function getPointElement(rootNode,clientX,clientY){const pointRoot=rootNode,documentElementFromPoint=document.elementFromPoint?.bind(document)??null,element=pointRoot.elementFromPoint?.(clientX,clientY)??documentElementFromPoint?.(clientX,clientY)??null;return rootNode instanceof ShadowRoot&&(element==null||!rootNode.contains(element))?getShadowPointElementByGeometry(rootNode,clientX,clientY):element instanceof HTMLElement?element:null}function getShadowPointElementByGeometry(rootNode,clientX,clientY){const candidates=Array.from(rootNode.querySelectorAll('[data-type="item"], [data-item-flattened-subitem]'));for(let index=candidates.length-1;index>=0;index--){const candidate=candidates[index],rect=candidate.getBoundingClientRect();if(clientX>=rect.left&&clientX<=rect.right&&clientY>=rect.top&&clientY<=rect.bottom)return candidate}return null}function resolveDropTargetFromElement(target){const rowButton=target?.closest?.('[data-type="item"]');if(!(rowButton instanceof HTMLElement))return null;const hoveredPath=rowButton.dataset.itemPath??null;if(hoveredPath==null)return null;const flattenedSegment=target?.closest?.("[data-item-flattened-subitem]"),flattenedSegmentPath=flattenedSegment instanceof HTMLElement?flattenedSegment.getAttribute("data-item-flattened-subitem")??null:null;if(flattenedSegmentPath!=null&&flattenedSegmentPath.endsWith("/"))return{directoryPath:flattenedSegmentPath,flattenedSegmentPath,hoveredPath,kind:"directory"};if(rowButton.dataset.itemType==="folder")return{directoryPath:hoveredPath,flattenedSegmentPath:null,hoveredPath,kind:"directory"};const parentPath=rowButton.dataset.itemParentPath??null;return parentPath==null||parentPath.length===0?{directoryPath:null,flattenedSegmentPath:null,hoveredPath,kind:"root"}:{directoryPath:parentPath,flattenedSegmentPath:null,hoveredPath,kind:"directory"}}function createDragPreviewElement(sourceElement){const preview=sourceElement.cloneNode(!0);return preview.removeAttribute("id"),preview.dataset.fileTreeDragPreview="true",preview.setAttribute("aria-hidden","true"),preview.tabIndex=-1,Object.assign(preview.style,{boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",left:"0px",margin:"0",pointerEvents:"none",position:"fixed",top:"0px",willChange:"transform",zIndex:"10000"}),preview}function shouldUseCustomPointerDragImage(){return navigator.vendor!=="Apple Computer, Inc."}function getDragEdgeScrollDelta(clientY,scrollRect){const topDistance=clientY-scrollRect.top;if(topDistance<DRAG_EDGE_SCROLL_THRESHOLD)return-Math.ceil((DRAG_EDGE_SCROLL_THRESHOLD-Math.max(0,topDistance))/DRAG_EDGE_SCROLL_THRESHOLD*DRAG_EDGE_SCROLL_MAX_SPEED);const bottomDistance=scrollRect.bottom-clientY;return bottomDistance<DRAG_EDGE_SCROLL_THRESHOLD?Math.ceil((DRAG_EDGE_SCROLL_THRESHOLD-Math.max(0,bottomDistance))/DRAG_EDGE_SCROLL_THRESHOLD*DRAG_EDGE_SCROLL_MAX_SPEED):0}function getBuiltInGitStatusDecoration(gitStatus,containsGitChange){if(gitStatus!=null){const label=GIT_STATUS_LABEL[gitStatus];return label==null?null:{text:label,title:GIT_STATUS_TITLE[gitStatus]}}return containsGitChange?{icon:{name:"file-tree-icon-dot",width:6,height:6},title:GIT_STATUS_DESCENDANT_TITLE}:null}function getInheritedIgnoredGitStatus(ancestorPaths,ignoredDirectoryPaths,ignoredInheritanceCache){if(ignoredDirectoryPaths==null||ignoredDirectoryPaths.size===0)return null;const visitedAncestors=[];for(let index=ancestorPaths.length-1;index>=0;index-=1){const ancestorPath=ancestorPaths[index],cached=ignoredInheritanceCache.get(ancestorPath);if(cached!=null){for(const visitedAncestor of visitedAncestors)ignoredInheritanceCache.set(visitedAncestor,cached);return cached?"ignored":null}if(ignoredDirectoryPaths.has(ancestorPath)){ignoredInheritanceCache.set(ancestorPath,!0);for(const visitedAncestor of visitedAncestors)ignoredInheritanceCache.set(visitedAncestor,!0);return"ignored"}visitedAncestors.push(ancestorPath)}for(const visitedAncestor of visitedAncestors)ignoredInheritanceCache.set(visitedAncestor,!1);return null}function isFileTreeDirectoryHandle(item){return item!=null&&"toggle"in item}function isSpaceSelectionKey(event){return event.code==="Space"||event.key===" "||event.key==="Spacebar"}function isSearchOpenSeedKey(event){return event.key.length===1&&/^[\p{L}\p{N}]$/u.test(event.key)&&!event.ctrlKey&&!event.metaKey&&!event.altKey}function getFileTreeGuideStyleText(focusedParentPath){return focusedParentPath==null?"":`[data-item-section="spacing-item"][data-ancestor-path="${focusedParentPath.replaceAll("\\","\\\\").replaceAll('"','\\"')}"] { opacity: 1; }`}function isContextMenuOpenKey(event){return event.shiftKey&&event.key==="F10"||event.key==="ContextMenu"}function canKeyUseStickyKeyboardState(event,contextMenuEnabled){return contextMenuEnabled&&isContextMenuOpenKey(event)||(event.ctrlKey||event.metaKey)&&isSpaceSelectionKey(event)?!0:event.key==="ArrowDown"||event.key==="ArrowLeft"||event.key==="ArrowRight"||event.key==="ArrowUp"}const BLOCKED_CONTEXT_MENU_NAV_KEYS=new Set(["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","End","Home","PageDown","PageUp"]);function isEventInContextMenu(event){for(const entry of event.composedPath())if(entry instanceof HTMLElement&&(entry.dataset.fileTreeContextMenuRoot==="true"||entry.dataset.type==="context-menu-anchor"||entry.dataset.type==="context-menu-trigger"||entry.getAttribute("slot")==="context-menu"))return!0;return!1}function serializeAnchorRect(rect){return{bottom:rect.bottom,height:rect.height,left:rect.left,right:rect.right,top:rect.top,width:rect.width,x:rect.x,y:rect.y}}function createAnchorRectFromPoint(x2,y2){return{bottom:y2,height:0,left:x2,right:x2,top:y2,width:0,x:x2,y:y2}}function getContextMenuAnchorTop(rootElement,itemElement){if(rootElement==null)return itemElement.offsetTop;const itemRect=itemElement.getBoundingClientRect(),rootRect=rootElement.getBoundingClientRect();return itemRect.top-rootRect.top}function setButtonRef(buttonRefs,path,element){if(element==null){buttonRefs.delete(path);return}buttonRefs.set(path,element)}function getContextMenuAnchorButton(path,stickyButtonRefs,rowButtonRefs){if(path==null)return null;const stickyButton=stickyButtonRefs.get(path)??null;if(stickyButton!=null)return stickyButton;const rowButton=rowButtonRefs.get(path)??null;return rowButton?.dataset.itemParked==="true"?null:rowButton}function getMountedStickyRowPaths(rootElement){if(rootElement==null)return[];const paths=[];for(const element of rootElement.querySelectorAll('button[data-file-tree-sticky-row="true"]')){if(!(element instanceof HTMLElement))continue;const path=element.dataset.fileTreeStickyPath;path!=null&&paths.push(path)}return paths}function getFocusedParkedRowElement(rootElement,path){if(rootElement==null||path==null)return null;for(const element of rootElement.querySelectorAll('button[data-item-focused="true"][data-item-parked="true"]'))if(element instanceof HTMLElement&&element.dataset.itemPath===path)return element;return null}function getStickyKeyboardViewportOffset(rootElement,scrollElement,activeTreeElement,path,itemHeight,stickyOverlayHeight,viewportHeight){const minimumStickyKeyboardViewportOffset=Math.max(0,stickyOverlayHeight-itemHeight),scrollElementRect=scrollElement?.getBoundingClientRect()??null,activeElementTopWithinViewport=scrollElementRect==null||activeTreeElement==null?null:activeTreeElement.getBoundingClientRect().top-scrollElementRect.top,focusedParkedRowElement=getFocusedParkedRowElement(rootElement,path),parkedElementTopWithinViewport=scrollElementRect==null||focusedParkedRowElement==null?null:focusedParkedRowElement.getBoundingClientRect().top-scrollElementRect.top;return Math.max(0,Math.min(parkedElementTopWithinViewport??Math.max(activeElementTopWithinViewport??0,minimumStickyKeyboardViewportOffset),Math.max(0,viewportHeight-itemHeight)))}function createContextMenuItem(row,path){return{kind:row.kind,name:getFileTreeRowAriaLabel(row),path}}function getFileTreeRootDomId(instanceId){return instanceId==null?void 0:`${instanceId}__tree`}function getFileTreeFocusedRowDomId(instanceId,path,parked){if(instanceId!=null)return`${instanceId}__focused-item-${encodeURIComponent(path)}${parked?"__parked":""}`}function isBuiltInDecorationIconName(name){return name==="file-tree-icon-chevron"||name==="file-tree-icon-dot"||name==="file-tree-icon-file"||name==="file-tree-icon-lock"}function renderRowDecoration(decoration,resolveIcon){if(decoration==null)return null;if("text"in decoration)return decoration.parts!=null?u$1("span",{title:decoration.title,children:decoration.parts.map((part,index)=>u$1("span",{style:{color:part.color},children:part.text},index))}):u$1("span",{title:decoration.title,children:decoration.text});const icon=typeof decoration.icon=="string"?isBuiltInDecorationIconName(decoration.icon)?resolveIcon(decoration.icon):{name:decoration.icon}:isBuiltInDecorationIconName(decoration.icon.name)?(()=>{const resolvedIcon=resolveIcon(decoration.icon.name),{name:_ignoredName,...iconOverrides}=decoration.icon;return{...resolvedIcon,...iconOverrides}})():decoration.icon;return u$1("span",{title:decoration.title,children:u$1(Icon,{...icon})})}function focusFirstMenuElement(menuElement){menuElement!=null&&focusElement(menuElement.querySelector(["button:not([disabled])","[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", "))??menuElement)}function renderFileTreeRowContent(row,resolveIcon,{actionLaneEnabled=!1,customDecoration=null,decorationLaneEnabled=!1,dragTargetFlattenedSegmentPath=null,gitDecoration=null,gitLaneActive=!1,renameInput=null,showDecorativeActionAffordance=!1}={}){const targetPath=getFileTreeRowPath(row);return u$1(k$1,{children:[row.depth>0?u$1("div",{"data-item-section":"spacing",children:Array.from({length:row.depth}).map((_2,index)=>u$1("div",{"data-item-section":"spacing-item","data-ancestor-path":row.ancestorPaths[index]},index))}):null,u$1("div",{"data-item-section":"icon",children:row.kind==="directory"?u$1(Icon,{...resolveIcon("file-tree-icon-chevron")}):u$1(Icon,{...resolveIcon("file-tree-icon-file",targetPath)})}),u$1("div",{"data-item-section":"content",children:row.isFlattened?formatFlattenedSegments(row,renameInput,dragTargetFlattenedSegmentPath):renameInput??u$1(MiddleTruncate,{minimumLength:5,split:"extension",children:row.name})}),decorationLaneEnabled?u$1("div",{"data-item-section":"decoration",children:customDecoration!=null?renderRowDecoration(customDecoration,resolveIcon):null}):null,gitLaneActive?u$1("div",{"data-item-section":"git",children:renderRowDecoration(gitDecoration,resolveIcon)}):null,actionLaneEnabled?u$1("div",{"data-item-section":"action",children:showDecorativeActionAffordance?u$1("span",{"aria-hidden":"true","data-item-action-affordance":"decorative",children:u$1(Icon,{...resolveIcon("file-tree-icon-ellipsis")})}):null}):null]})}function renderStyledRow(frame,row,key2,options={}){const{controller,renameView,visualFocusPath,contextHoverPath,draggedPathSet,dragTarget,dragAndDropEnabled,shouldSuppressContextMenu,handleRowDragStart,handleRowDragEnd,handleRowTouchStart,instanceId,itemHeight,gitStatusByPath,ignoredGitDirectories,ignoredInheritanceCache,directoriesWithGitChanges,gitLaneActive,contextMenuEnabled,contextMenuTriggerMode,contextMenuButtonTriggerEnabled,contextMenuButtonVisibility,contextMenuRightClickEnabled,registerRenameInput,registerButton,resolveIcon,renderDecorationForRow,openContextMenuForRow,onRowClick,onKeyDown}=frame,targetPath=getFileTreeRowPath(row),{isParked=!1,mode="flow",style}=options,isSticky=mode==="sticky",effectiveGitStatus=gitStatusByPath?.get(targetPath)??null??getInheritedIgnoredGitStatus(row.ancestorPaths,ignoredGitDirectories,ignoredInheritanceCache),containsGitChange=row.kind==="directory"&&(directoriesWithGitChanges?.has(targetPath)??!1),customDecoration=renderDecorationForRow(row,targetPath),gitDecoration=getBuiltInGitStatusDecoration(effectiveGitStatus,containsGitChange),actionLaneEnabled=contextMenuEnabled&&contextMenuButtonTriggerEnabled,decorationLaneEnabled=customDecoration!=null||gitLaneActive||actionLaneEnabled,showDecorativeActionAffordance=actionLaneEnabled&&contextMenuButtonVisibility==="always",isRenamingRow=renameView.getPath()===targetPath,renamingValue=isRenamingRow?renameView.getValue():"",renameInput=isSticky||!isRenamingRow?null:u$1(RenameInput,{ref:registerRenameInput,ariaLabel:`Rename ${getFileTreeRowAriaLabel(row)}`,isFlattened:row.isFlattened,value:renamingValue,onBlur:()=>{renameView.commit()},onInput:event=>{renameView.setValue(event.currentTarget.value)}}),rowContent=renderFileTreeRowContent(row,resolveIcon,{actionLaneEnabled,customDecoration,decorationLaneEnabled,dragTargetFlattenedSegmentPath:dragTarget?.flattenedSegmentPath??null,gitDecoration,gitLaneActive,renameInput,showDecorativeActionAffordance}),commonProps={...computeFileTreeRowElementAttributes({ariaLabel:getFileTreeRowAriaLabel(row),domId:row.isFocused?getFileTreeFocusedRowDomId(instanceId,targetPath,isParked):void 0,extraStyle:style,features:{actionLaneEnabled,contextMenuButtonVisibility:actionLaneEnabled?contextMenuButtonVisibility:null,contextMenuEnabled,contextMenuTriggerMode:contextMenuEnabled?contextMenuTriggerMode:null,gitLaneActive},isParked,itemHeight,mode,row,state:{containsGitChange,effectiveGitStatus,isContextHovered:contextHoverPath===targetPath,isDragTarget:dragTarget?.kind==="directory"&&dragTarget.directoryPath===targetPath,isDragging:draggedPathSet?.has(targetPath)===!0,isFocusRinged:row.isFocused&&visualFocusPath===targetPath},targetPath}),key:key2,onContextMenu:contextMenuEnabled||dragAndDropEnabled?event=>{if(shouldSuppressContextMenu()){event.preventDefault();return}contextMenuEnabled&&(event.preventDefault(),contextMenuRightClickEnabled&&(controller.focusMountedPathFromInput(targetPath),openContextMenuForRow(row,targetPath,{anchorRect:createAnchorRectFromPoint(event.clientX,event.clientY),source:"right-click"})))}:void 0,onFocus:isSticky?void 0:()=>{controller.focusMountedPathFromInput(targetPath)},onKeyDown:isSticky?void 0:onKeyDown,ref:element=>{registerButton(targetPath,element)}};return!isSticky&&isRenamingRow?u$1("div",{...commonProps,children:rowContent}):u$1("button",{...commonProps,type:"button",draggable:dragAndDropEnabled&&!isParked,onDragEnd:dragAndDropEnabled&&!isParked?handleRowDragEnd:void 0,onDragStart:dragAndDropEnabled&&!isParked?event=>{handleRowDragStart(event,row,targetPath)}:void 0,onMouseDown:event=>{if(isSticky){event.preventDefault();return}controller.isSearchOpen()&&event.preventDefault()},onTouchStart:dragAndDropEnabled&&!isParked?event=>{handleRowTouchStart(event,row,targetPath)}:void 0,onClick:event=>{onRowClick(event,row,targetPath,mode)},children:rowContent})}function renderRangeChildren(frame,range2,hiddenRowPaths){return range2.end<range2.start?[]:frame.controller.getVisibleRows(range2.start,range2.end).filter(row=>!hiddenRowPaths.has(getFileTreeRowPath(row))).map((row,slotIndex)=>renderStyledRow(frame,row,range2.start+slotIndex))}function FileTreeView({composition,controller,gitStatusByPath,ignoredGitDirectories,directoriesWithGitChanges,icons,instanceId,itemHeight=FILE_TREE_DEFAULT_ITEM_HEIGHT,overscan=10,renamingEnabled=!1,renderRowDecoration:renderRowDecoration2,searchBlurBehavior="close",searchEnabled=!1,searchFakeFocus=!1,slotHost,stickyFolders=!1,initialViewportHeight=420}){"use no memo";const contextMenuAnchorRef=F(null),contextMenuTriggerRef=F(null),isScrollingRef=F(!1),listRef=F(null),renameInputRef=F(null),rootRef=F(null),scrollRef=F(null),searchInputRef=F(null),rowButtonRefs=F(new Map),stickyRowButtonRefs=F(new Map),updateViewportRef=F(()=>{}),measuredViewportHeightRef=F(null),processedScrollRequestIdRef=F(0),initialFocusedScrollAppliedRef=F(!1),initialFocusedScrollControllerRef=F(null);initialFocusedScrollControllerRef.current!==controller&&(initialFocusedScrollAppliedRef.current=!1,initialFocusedScrollControllerRef.current=controller);const domFocusOwnerRef=F(!1),previousFocusedPathRef=F(null),previousRenamingPathRef=F(null),restoreTreeFocusAfterSearchCloseRef=F(!1),restoreTreeFocusViewportOffsetRef=F(null),dragAutoScrollFrameRef=F(null),dragHoverOpenKeyRef=F(null),dragHoverOpenTimerRef=F(null),dragPointRef=F(null),dragPreviewRef=F(null),dragRowSnapshotRef=F(null),touchCleanupRef=F(null),touchDragActiveRef=F(!1),touchPreviewOffsetRef=F(null),touchSourceElementRef=F(null),touchStartPointRef=F(null),touchLongPressTimerRef=F(null),ignoredInheritanceCache=q(()=>new Map,[]),[,setControllerRevision]=h(0),hasSeenInitialControllerSnapshotRef=F(!1),[activeItemPath,setActiveItemPath]=h(null),[contextHoverPath,setContextHoverPath]=h(null),[contextMenuAnchorTop,setContextMenuAnchorTop]=h(null),[lastContextMenuInteraction,setLastContextMenuInteraction]=h(null),[scrollSettledRevision,setScrollSettledRevision]=h(0),[contextMenuState,setContextMenuState]=h(null),contextMenuStateRef=F(contextMenuState);contextMenuStateRef.current=contextMenuState;const pendingStickyFocusPathRef=F(null),pendingStickyKeyboardFocusPathRef=F(null),pendingStickyKeyboardViewportOffsetRef=F(null),pendingStickyKeyboardScrollTopRef=F(null),debugContextMenuTriggerPathRef=F(null),debugDisableScrollSuppressionRef=F(!1),clearPendingStickyKeyboardState=()=>{pendingStickyKeyboardFocusPathRef.current=null,pendingStickyKeyboardViewportOffsetRef.current=null,pendingStickyKeyboardScrollTopRef.current=null},preserveStickyKeyboardFocusAtScrollTop=(path,scrollTop)=>{pendingStickyKeyboardFocusPathRef.current=path,pendingStickyKeyboardViewportOffsetRef.current=null,pendingStickyKeyboardScrollTopRef.current=scrollTop==null?null:{path,scrollTop}},restoreStickyKeyboardViewportOffset=(path,viewportOffset)=>{pendingStickyKeyboardFocusPathRef.current=null,pendingStickyKeyboardViewportOffsetRef.current={path,viewportOffset},pendingStickyKeyboardScrollTopRef.current=null},skipInitialSearchAutoFocusRef=F(searchBlurBehavior==="retain"&&controller.isSearchOpen()),[fakeSearchFocusActive,setFakeSearchFocusActive]=h(searchFakeFocus);_(()=>{searchFakeFocus||setFakeSearchFocusActive(!1)},[searchFakeFocus]);const searchInputUserInteractedRef=F(!1),markSearchInputInteracted=b(()=>{searchInputUserInteractedRef.current=!0,setFakeSearchFocusActive(previous=>previous&&!1)},[]),[layoutState,setLayoutState]=h(()=>computeFileTreeViewLayoutState({controller,itemHeight,overscan,scrollTop:0,stickyFolders,viewportHeight:initialViewportHeight})),[hasStickyUiMount,setHasStickyUiMount]=h(!1);_(()=>{setHasStickyUiMount(!0)},[]);const contextMenuEnabled=composition?.contextMenu?.enabled===!0||composition?.contextMenu?.render!=null||composition?.contextMenu?.onOpen!=null||composition?.contextMenu?.onClose!=null,contextMenuTriggerMode=composition?.contextMenu?.triggerMode??(contextMenuEnabled?"right-click":"both"),contextMenuButtonTriggerEnabled=contextMenuTriggerMode==="both"||contextMenuTriggerMode==="button",contextMenuButtonVisibility=composition?.contextMenu?.buttonVisibility??"when-needed",contextMenuRightClickEnabled=contextMenuTriggerMode==="both"||contextMenuTriggerMode==="right-click";A(()=>{const rootElement=rootRef.current;if(rootElement==null)return;const handleDebugSetContextMenuTrigger=event=>{if(!(event instanceof CustomEvent))return;const nextPath=event.detail?.path??null;debugContextMenuTriggerPathRef.current=nextPath,setContextHoverPath(nextPath),setLastContextMenuInteraction(nextPath==null?null:"pointer")},handleDebugSetScrollSuppression=event=>{event instanceof CustomEvent&&(debugDisableScrollSuppressionRef.current=event.detail?.disabled===!0)};return rootElement.addEventListener("file-tree-debug-set-context-menu-trigger",handleDebugSetContextMenuTrigger),rootElement.addEventListener("file-tree-debug-set-scroll-suppression",handleDebugSetScrollSuppression),()=>{rootElement.removeEventListener("file-tree-debug-set-context-menu-trigger",handleDebugSetContextMenuTrigger),rootElement.removeEventListener("file-tree-debug-set-scroll-suppression",handleDebugSetScrollSuppression)}},[]);const registerRowButton=b((path,element)=>{setButtonRef(rowButtonRefs.current,path,element)},[]),registerStickyRowButton=b((path,element)=>{setButtonRef(stickyRowButtonRefs.current,path,element)},[]),registerRenameInput=b(element=>{renameInputRef.current=element},[]),getTriggerAnchorButton=b(path=>getContextMenuAnchorButton(path,stickyRowButtonRefs.current,rowButtonRefs.current),[]),gitLaneActive=gitStatusByPath!=null||ignoredGitDirectories!=null||directoriesWithGitChanges!=null,{resolveIcon}=q(()=>createFileTreeIconResolver(icons),[icons]),renameView=controller[FILE_TREE_RENAME_VIEW](),renamingPath=renameView.getPath(),isRenaming=renamingPath!=null,isSearchOpen=controller.isSearchOpen(),searchValue=controller.getSearchValue(),focusedPath=controller.getFocusedPath(),focusedIndex=controller.getFocusedIndex(),scrollRequest=controller.getScrollRequest(),dragAndDropEnabled=controller.isDragAndDropEnabled(),dragSession=controller.getDragSession(),draggedPathSet=q(()=>dragSession==null?null:new Set(dragSession.draggedPaths),[dragSession]),dragTarget=dragSession?.target??null,draggedPrimaryPath=dragSession?.primaryPath??null,treeDomId=getFileTreeRootDomId(instanceId),{overlayHeight:overlayRowsHeight,overlayRows,snapshot:layoutSnapshot,visibleRows}=layoutState,resolvedViewportHeight=layoutSnapshot.physical.viewportHeight,range2=q(()=>({end:layoutSnapshot.window.endIndex,start:layoutSnapshot.window.startIndex}),[layoutSnapshot.window.endIndex,layoutSnapshot.window.startIndex]),stickyRows=overlayRows,occludedStickyRows=layoutSnapshot.sticky.rows,totalScrollableHeight=layoutSnapshot.physical.totalHeight,stickyOverlayHeight=layoutSnapshot.sticky.height,stickyRowPathSet=q(()=>new Set(occludedStickyRows.map(entry=>getFileTreeRowPath(entry.row))),[occludedStickyRows]),focusedRowIsMounted=focusedIndex>=0&&focusedIndex>=range2.start&&focusedIndex<=range2.end,renderDecorationForRow=b((row,targetPath)=>renderRowDecoration2?.({item:createContextMenuItem(row,targetPath),row})??null,[renderRowDecoration2]),restoreContextMenuFocus=b(restorePath=>focusElement(restorePath==null?null:rowButtonRefs.current.get(restorePath)??null)?!0:focusElement(rootRef.current),[]),restoreFocusToTree=b(path=>{restoreContextMenuFocus(controller.focusNearestPath(path))},[controller,restoreContextMenuFocus]),restoreFocusToTreeRef=F(restoreFocusToTree);restoreFocusToTreeRef.current=restoreFocusToTree;const shouldRestoreContextMenuFocusRef=F(!0),closeContextMenuRef=F(()=>{}),closeContextMenu=b((restoreFocus=!0)=>{const currentContextMenuState=contextMenuStateRef.current;currentContextMenuState!=null&&(shouldRestoreContextMenuFocusRef.current=shouldRestoreContextMenuFocusRef.current&&restoreFocus,setContextMenuState(null),composition?.contextMenu?.onClose?.(),shouldRestoreContextMenuFocusRef.current&&restoreFocusToTree(currentContextMenuState.path))},[composition?.contextMenu,restoreFocusToTree]);closeContextMenuRef.current=closeContextMenu;const updateTriggerPosition=b(itemButton=>{const nextTop=itemButton==null?null:getContextMenuAnchorTop(rootRef.current,itemButton);setContextMenuAnchorTop(previousTop=>previousTop===nextTop?previousTop:nextTop)},[]),openContextMenuForRow=b((row,targetPath,options)=>{const item=controller.getItem(targetPath);if(item==null)return;const anchorButton=getTriggerAnchorButton(targetPath);if(anchorButton?.dataset.fileTreeStickyRow==="true"){const scrollElement=scrollRef.current;preserveStickyKeyboardFocusAtScrollTop(targetPath,scrollElement?.scrollTop??null),domFocusOwnerRef.current=!0,setActiveItemPath(previousPath=>previousPath===targetPath?previousPath:targetPath)}item.focus(),updateTriggerPosition(anchorButton),shouldRestoreContextMenuFocusRef.current=!0,setContextMenuState({anchorRect:options?.anchorRect??null,item:createContextMenuItem(row,targetPath),path:targetPath,source:options?.source??"keyboard"})},[controller,getTriggerAnchorButton,updateTriggerPosition]),startRenameFromPath=b(path=>{if(renamingEnabled){if(controller.isSearchOpen()){const scrollElement=scrollRef.current,viewportHeight=readMeasuredViewportHeight(scrollElement,resolvedViewportHeight);restoreTreeFocusViewportOffsetRef.current=focusedIndex<0||scrollElement==null?null:Math.max(0,Math.min(focusedIndex*itemHeight-scrollElement.scrollTop,Math.max(0,viewportHeight-itemHeight))),restoreTreeFocusAfterSearchCloseRef.current=!0}controller.startRenaming(path)!==!1&&(setLastContextMenuInteraction("focus"),setControllerRevision(revision=>revision+1))}},[controller,focusedIndex,itemHeight,renamingEnabled,resolvedViewportHeight]),revealCanonicalRowAtStickyOffset=b((path,{restoreTreeFocus=!0,targetOffset="live-overlay"}={})=>{const scrollElement=scrollRef.current;if(scrollElement==null)return!1;controller.focusPath(path);const visibleIndex=controller.getFocusedIndex();if(visibleIndex<0)return!1;const focusedRow=controller.getVisibleRows(visibleIndex,visibleIndex)[0]??null;if(focusedRow==null)return!1;const liveViewportHeight=readMeasuredViewportHeight(scrollElement,resolvedViewportHeight),liveTotalHeight=controller.getVisibleCount()*itemHeight,targetViewportOffset=targetOffset==="sticky-parents"?focusedRow.ancestorPaths.length*itemHeight:computeFileTreeViewLayoutState({controller,itemHeight,overscan,scrollTop:scrollElement.scrollTop,stickyFolders,viewportHeight:liveViewportHeight}).snapshot.sticky.height;return domFocusOwnerRef.current=!0,scrollFocusedRowToViewportOffset(scrollElement,visibleIndex,itemHeight,liveViewportHeight,liveTotalHeight,targetViewportOffset),updateViewportRef.current(),pendingStickyFocusPathRef.current=restoreTreeFocus?path:null,!0},[controller,itemHeight,overscan,resolvedViewportHeight,stickyFolders]),shouldSuppressContextMenu=()=>isScrollingRef.current===!0||touchLongPressTimerRef.current!=null||touchDragActiveRef.current===!0,requestDragAnimationFrame=callback=>typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(()=>{callback()}):window.setTimeout(callback,16),cancelDragAnimationFrame=handle=>{if(handle!=null){if(typeof window.cancelAnimationFrame=="function"){window.cancelAnimationFrame(handle);return}window.clearTimeout(handle)}},clearDragHoverOpen=()=>{dragHoverOpenTimerRef.current!=null&&(clearTimeout(dragHoverOpenTimerRef.current),dragHoverOpenTimerRef.current=null),dragHoverOpenKeyRef.current=null},clearDragPreview=()=>{dragPreviewRef.current?.remove(),dragPreviewRef.current=null},stopDragAutoScroll=()=>{cancelDragAnimationFrame(dragAutoScrollFrameRef.current),dragAutoScrollFrameRef.current=null,dragPointRef.current=null},mountDragPreview=preview=>{const rootNode=rootRef.current?.getRootNode();if(rootNode instanceof ShadowRoot){rootNode.append(preview);return}document.body.append(preview)},clearTouchDragResources=()=>{touchCleanupRef.current?.(),touchCleanupRef.current=null,touchLongPressTimerRef.current!=null&&(clearTimeout(touchLongPressTimerRef.current),touchLongPressTimerRef.current=null),touchDragActiveRef.current=!1,touchPreviewOffsetRef.current=null,touchStartPointRef.current=null,touchSourceElementRef.current!=null&&(touchSourceElementRef.current.setAttribute("draggable","true"),touchSourceElementRef.current.style.removeProperty("touch-action"),touchSourceElementRef.current=null),clearDragPreview(),clearDragHoverOpen(),stopDragAutoScroll(),dragRowSnapshotRef.current=null},syncDropTargetFromPoint=(clientX,clientY)=>{const rootNode=rootRef.current?.getRootNode(),nextTarget=resolveDropTargetFromElement(getPointElement(rootNode instanceof ShadowRoot?rootNode:document,clientX,clientY));return controller.setDragTarget(nextTarget),controller.getDragSession()?.target??null},scheduleDragHoverOpen=nextTarget=>{const openDelay=controller.getDragAndDropConfig()?.openOnDropDelay??800;if(nextTarget==null||nextTarget.kind!=="directory"||nextTarget.directoryPath==null||openDelay<=0){clearDragHoverOpen();return}const targetItem=controller.getItem(nextTarget.directoryPath),directoryItem=isFileTreeDirectoryHandle(targetItem)?targetItem:null;if(directoryItem==null||directoryItem.isExpanded()){clearDragHoverOpen();return}const nextKey=`${nextTarget.directoryPath}::${nextTarget.flattenedSegmentPath??""}`;dragHoverOpenKeyRef.current!==nextKey&&(clearDragHoverOpen(),dragHoverOpenKeyRef.current=nextKey,dragHoverOpenTimerRef.current=setTimeout(()=>{const currentTarget=controller.getDragSession()?.target;currentTarget?.kind!=="directory"||currentTarget.directoryPath!==nextTarget.directoryPath||currentTarget.flattenedSegmentPath!==nextTarget.flattenedSegmentPath||directoryItem.expand()},openDelay))},runDragAutoScroll=()=>{dragAutoScrollFrameRef.current=null;const dragPoint=dragPointRef.current,scrollElement=scrollRef.current;if(dragPoint==null||scrollElement==null||controller.getDragSession()==null)return;const scrollRect=scrollElement.getBoundingClientRect(),scrollDelta=getDragEdgeScrollDelta(dragPoint.clientY,scrollRect);if(scrollDelta===0)return;const maxScrollTop=Math.max(0,scrollElement.scrollHeight-scrollElement.clientHeight),boundedScrollTop=Math.max(0,Math.min(maxScrollTop,scrollElement.scrollTop+scrollDelta));boundedScrollTop!==scrollElement.scrollTop&&(scrollElement.scrollTop=boundedScrollTop,updateViewportRef.current()),scheduleDragHoverOpen(syncDropTargetFromPoint(dragPoint.clientX,dragPoint.clientY)),dragAutoScrollFrameRef.current=requestDragAnimationFrame(runDragAutoScroll)},updateDragPoint=(clientX,clientY)=>{dragPointRef.current={clientX,clientY},dragAutoScrollFrameRef.current??=requestDragAnimationFrame(runDragAutoScroll)},handleRowDragStart=(event,row,targetPath)=>{const dragSource=event.currentTarget;if(dragSource!=null){if(clearTouchDragResources(),clearDragPreview(),clearDragHoverOpen(),stopDragAutoScroll(),controller.startDrag(targetPath)===!1){event.preventDefault();return}if(dragRowSnapshotRef.current=row,event.dataTransfer!=null&&(event.dataTransfer.effectAllowed="move",event.dataTransfer.dropEffect="move",event.dataTransfer.setData("text/plain",targetPath),shouldUseCustomPointerDragImage())){const preview=createDragPreviewElement(dragSource),rect=dragSource.getBoundingClientRect();Object.assign(preview.style,{height:`${rect.height}px`,opacity:"0.85",transform:"translate3d(-9999px, 0px, 0)",width:`${rect.width}px`}),mountDragPreview(preview),dragPreviewRef.current=preview,event.dataTransfer.setDragImage(preview,Math.max(0,event.clientX-rect.left),Math.max(0,event.clientY-rect.top))}}},handleRowDragEnd=()=>{clearDragPreview(),clearDragHoverOpen(),stopDragAutoScroll(),dragRowSnapshotRef.current=null,controller.cancelDrag()},handleRowTouchStart=(event,row,targetPath)=>{if(touchLongPressTimerRef.current!=null||touchDragActiveRef.current)return;const touch=event.touches[0],dragSource=event.currentTarget;if(touch==null||dragSource==null)return;touchStartPointRef.current={clientX:touch.clientX,clientY:touch.clientY},touchSourceElementRef.current=dragSource,dragSource.setAttribute("draggable","false");const clearPendingTouchStart=(options={})=>{const restoreNativeDraggable=options.restoreNativeDraggable??!touchDragActiveRef.current;touchLongPressTimerRef.current!=null&&(clearTimeout(touchLongPressTimerRef.current),touchLongPressTimerRef.current=null),document.removeEventListener("touchmove",handlePendingTouchMove),document.removeEventListener("touchend",handlePendingTouchEnd),document.removeEventListener("touchcancel",handlePendingTouchEnd),touchCleanupRef.current===clearPendingTouchStart&&(touchCleanupRef.current=null),restoreNativeDraggable&&(dragSource.setAttribute("draggable","true"),touchSourceElementRef.current===dragSource&&(touchSourceElementRef.current=null),touchStartPointRef.current=null)},handlePendingTouchMove=moveEvent=>{const moveTouch=moveEvent.touches[0],startPoint=touchStartPointRef.current;if(moveTouch==null||startPoint==null)return;const deltaX=moveTouch.clientX-startPoint.clientX,deltaY=moveTouch.clientY-startPoint.clientY;deltaX*deltaX+deltaY*deltaY<=TOUCH_LONG_PRESS_MOVE_THRESHOLD*TOUCH_LONG_PRESS_MOVE_THRESHOLD||clearPendingTouchStart()},handlePendingTouchEnd=()=>{clearPendingTouchStart()};document.addEventListener("touchmove",handlePendingTouchMove,{passive:!0}),document.addEventListener("touchend",handlePendingTouchEnd),document.addEventListener("touchcancel",handlePendingTouchEnd),touchCleanupRef.current=clearPendingTouchStart,touchLongPressTimerRef.current=setTimeout(()=>{if(clearPendingTouchStart({restoreNativeDraggable:!1}),controller.startDrag(targetPath)===!1){dragSource.setAttribute("draggable","true"),touchSourceElementRef.current===dragSource&&(touchSourceElementRef.current=null),touchStartPointRef.current=null;return}touchDragActiveRef.current=!0,touchSourceElementRef.current=dragSource,dragSource.setAttribute("draggable","false"),dragSource.style.setProperty("touch-action","none"),dragRowSnapshotRef.current=row;const rect=dragSource.getBoundingClientRect(),preview=createDragPreviewElement(dragSource);Object.assign(preview.style,{height:`${rect.height}px`,opacity:"0.85",transform:`translate3d(${rect.left}px, ${rect.top}px, 0)`,width:`${rect.width}px`}),mountDragPreview(preview),dragPreviewRef.current=preview,touchPreviewOffsetRef.current={x:touch.clientX-rect.left,y:touch.clientY-rect.top};const handleActiveTouchMove=moveEvent=>{const moveTouch=moveEvent.touches[0];if(moveTouch==null)return;moveEvent.preventDefault();const previewOffset=touchPreviewOffsetRef.current;previewOffset!=null&&dragPreviewRef.current!=null&&(dragPreviewRef.current.style.transform=`translate3d(${moveTouch.clientX-previewOffset.x}px, ${moveTouch.clientY-previewOffset.y}px, 0)`),scheduleDragHoverOpen(syncDropTargetFromPoint(moveTouch.clientX,moveTouch.clientY)),updateDragPoint(moveTouch.clientX,moveTouch.clientY)},handleActiveTouchEnd=endEvent=>{const endTouch=endEvent.changedTouches[0];endTouch!=null&&syncDropTargetFromPoint(endTouch.clientX,endTouch.clientY),controller.completeDrag(),clearTouchDragResources()},handleActiveTouchCancel=()=>{controller.cancelDrag(),clearTouchDragResources()};touchCleanupRef.current=()=>{document.removeEventListener("touchmove",handleActiveTouchMove),document.removeEventListener("touchend",handleActiveTouchEnd),document.removeEventListener("touchcancel",handleActiveTouchCancel)},document.addEventListener("touchmove",handleActiveTouchMove,{passive:!1}),document.addEventListener("touchend",handleActiveTouchEnd),document.addEventListener("touchcancel",handleActiveTouchCancel)},TOUCH_LONG_PRESS_DELAY)},handleTreeKeyDown=event=>{if(contextMenuState!=null){if(event.key==="Escape"){closeContextMenu(),event.preventDefault(),event.stopPropagation();return}BLOCKED_CONTEXT_MENU_NAV_KEYS.has(event.key)&&(event.preventDefault(),event.stopPropagation());return}if(renameView.isActive()){if(event.isComposing||event.keyCode===229)return;if(event.key==="Escape")renameView.cancel();else if(event.key==="Enter")renameView.commit();else return;setLastContextMenuInteraction("focus"),setControllerRevision(revision=>revision+1),event.preventDefault(),event.stopPropagation();return}if(renamingEnabled&&event.key==="F2"){startRenameFromPath(focusedPath??void 0),event.preventDefault(),event.stopPropagation();return}if(isSearchOpen){if(event.key==="Escape")restoreTreeFocusAfterSearchCloseRef.current=!1,restoreTreeFocusViewportOffsetRef.current=null,controller.closeSearch();else if(event.key==="Enter"){const currentFocusedPath=controller.getFocusedPath();currentFocusedPath!=null&&controller.selectOnlyPath(currentFocusedPath);const scrollElement2=scrollRef.current,viewportHeight=readMeasuredViewportHeight(scrollElement2,resolvedViewportHeight);restoreTreeFocusViewportOffsetRef.current=focusedIndex<0||scrollElement2==null?null:Math.max(0,Math.min(focusedIndex*itemHeight-scrollElement2.scrollTop,Math.max(0,viewportHeight-itemHeight))),restoreTreeFocusAfterSearchCloseRef.current=!0,controller.closeSearch()}else if(event.key==="ArrowDown")controller.focusNextSearchMatch();else if(event.key==="ArrowUp")controller.focusPreviousSearchMatch();else return;setLastContextMenuInteraction("focus"),setControllerRevision(revision=>revision+1),event.preventDefault(),event.stopPropagation();return}if(searchEnabled&&isSearchOpenSeedKey(event)){controller.openSearch(event.key),setControllerRevision(revision=>revision+1),event.preventDefault(),event.stopPropagation();return}const isKeyboardContextMenuRequest=contextMenuEnabled&&isContextMenuOpenKey(event),shouldInspectStickyKeyboardState=canKeyUseStickyKeyboardState(event,contextMenuEnabled),activeTreeElement=shouldInspectStickyKeyboardState&&rootRef.current!=null?getActiveTreeElement(rootRef.current):null,mountedStickyRowPathSet=shouldInspectStickyKeyboardState?new Set(getMountedStickyRowPaths(rootRef.current)):new Set,activeStickyFocusPath=activeTreeElement?.dataset.fileTreeStickyPath??null,activeStickyRowOwnsFocus=activeTreeElement?.dataset.fileTreeStickyRow==="true"&&activeStickyFocusPath!=null;if(activeStickyRowOwnsFocus&&activeStickyFocusPath!==focusedPath&&mountedStickyRowPathSet.has(activeStickyFocusPath)){const scrollElement2=scrollRef.current;preserveStickyKeyboardFocusAtScrollTop(activeStickyFocusPath,scrollElement2?.scrollTop??null),controller.focusPath(activeStickyFocusPath)}const effectiveFocusedPath=controller.getFocusedPath(),effectiveFocusedIndex=controller.getFocusedIndex(),focusedItem=controller.getFocusedItem();if(focusedItem==null)return;const focusedDirectoryItem=isFileTreeDirectoryHandle(focusedItem)?focusedItem:null,startedFromStickyRow=effectiveFocusedPath!=null&&(stickyRowPathSet.has(effectiveFocusedPath)||activeStickyRowOwnsFocus&&activeStickyFocusPath===effectiveFocusedPath&&mountedStickyRowPathSet.has(effectiveFocusedPath)),shouldPreserveLocalStickyFocusMove=event.key==="ArrowDown"||event.key==="ArrowUp"||event.key==="ArrowRight"&&focusedDirectoryItem!=null&&focusedDirectoryItem.isExpanded(),shouldRestoreCollapsedStickyFocusViewport=event.key==="ArrowLeft"&&startedFromStickyRow&&focusedDirectoryItem!=null&&focusedDirectoryItem.isExpanded(),scrollElement=scrollRef.current;let handled=!0;if(event.shiftKey&&event.key==="ArrowDown")controller.extendSelectionFromFocused(1);else if(event.shiftKey&&event.key==="ArrowUp")controller.extendSelectionFromFocused(-1);else if(isKeyboardContextMenuRequest&&effectiveFocusedPath!=null&&effectiveFocusedIndex>=0){const focusedRow=controller.getVisibleRows(effectiveFocusedIndex,effectiveFocusedIndex)[0]??null,focusedButton=getContextMenuAnchorButton(effectiveFocusedPath,stickyRowButtonRefs.current,rowButtonRefs.current);focusedRow==null||focusedButton==null?handled=!1:openContextMenuForRow(focusedRow,effectiveFocusedPath)}else if((event.ctrlKey||event.metaKey)&&isSpaceSelectionKey(event))controller.toggleFocusedSelection();else if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==="a")controller.selectAllVisiblePaths();else switch(event.key){case"ArrowDown":controller.focusNextItem();break;case"ArrowUp":controller.focusPreviousItem();break;case"ArrowRight":focusedDirectoryItem==null||focusedDirectoryItem.isExpanded()?controller.focusNextItem():focusedDirectoryItem.expand();break;case"ArrowLeft":focusedDirectoryItem!=null&&focusedDirectoryItem.isExpanded()?focusedDirectoryItem.collapse():controller.focusParentItem();break;case"Home":controller.focusFirstItem();break;case"End":controller.focusLastItem();break;default:handled=!1}if(!handled)return;setLastContextMenuInteraction("focus");const nextFocusedPath=controller.getFocusedPath(),nextFocusedPathIsMountedSticky=nextFocusedPath!=null&&(stickyRowPathSet.has(nextFocusedPath)||mountedStickyRowPathSet.has(nextFocusedPath)),stickyKeyboardMoveLandsOnDifferentStickyRow=shouldPreserveLocalStickyFocusMove&&nextFocusedPath!==effectiveFocusedPath,stickyKeyboardMenuStaysOnStickyRow=isKeyboardContextMenuRequest&&activeStickyRowOwnsFocus&&activeStickyFocusPath===effectiveFocusedPath&&nextFocusedPath===effectiveFocusedPath;if((startedFromStickyRow||stickyKeyboardMenuStaysOnStickyRow)&&nextFocusedPath!=null&&(stickyKeyboardMoveLandsOnDifferentStickyRow&&nextFocusedPathIsMountedSticky||stickyKeyboardMenuStaysOnStickyRow))preserveStickyKeyboardFocusAtScrollTop(nextFocusedPath,scrollElement?.scrollTop??null),domFocusOwnerRef.current=!0,setActiveItemPath(previousPath=>previousPath===nextFocusedPath?previousPath:nextFocusedPath);else{const stickyArrowUpExitsStack=event.key==="ArrowUp"&&startedFromStickyRow&&nextFocusedPath!==effectiveFocusedPath;nextFocusedPath!=null&&(stickyArrowUpExitsStack||shouldRestoreCollapsedStickyFocusViewport&&nextFocusedPath===effectiveFocusedPath)?(restoreStickyKeyboardViewportOffset(nextFocusedPath,getStickyKeyboardViewportOffset(rootRef.current,scrollElement,activeTreeElement,effectiveFocusedPath,itemHeight,stickyOverlayHeight,resolvedViewportHeight)),domFocusOwnerRef.current=!0,setActiveItemPath(previousPath=>previousPath===nextFocusedPath?previousPath:nextFocusedPath)):clearPendingStickyKeyboardState()}setControllerRevision(revision=>revision+1),event.preventDefault(),event.stopPropagation()};A(()=>{if(!(!searchEnabled||!isSearchOpen)){if(skipInitialSearchAutoFocusRef.current){skipInitialSearchAutoFocusRef.current=!1;return}focusElement(searchInputRef.current)}},[isSearchOpen,searchEnabled]),A(()=>{const input=renameInputRef.current;switch(classifyFileTreeRenameHandoff({hasRenderedInput:input!=null,previousRenamingPath:previousRenamingPathRef.current,renamingPath})){case"reset":previousRenamingPathRef.current=null;return;case"reveal-canonical":renamingPath!=null&&revealCanonicalRowAtStickyOffset(renamingPath,{restoreTreeFocus:!1,targetOffset:"live-overlay"});return;case"ignore":return;case"focus-input":input!=null&&(pendingStickyFocusPathRef.current=null,previousRenamingPathRef.current=renamingPath,focusElement(input),input.select());return}},[range2.end,range2.start,renamingPath,revealCanonicalRowAtStickyOffset,stickyRowPathSet]),A(()=>{const rootElement=rootRef.current;if(rootElement==null)return;let nullFocusOutTimer=null;const clearNullFocusOutTimer=()=>{nullFocusOutTimer!=null&&(clearTimeout(nullFocusOutTimer),nullFocusOutTimer=null)},updateActiveItemPath=()=>{const nextActiveItemPath=getActiveTreeElement(rootElement)?.dataset.itemPath??null;setActiveItemPath(previousPath=>previousPath===nextActiveItemPath?previousPath:nextActiveItemPath)},onFocusIn=()=>{clearNullFocusOutTimer(),domFocusOwnerRef.current=!0,updateActiveItemPath()},onFocusOut=event=>{const nextTarget=event.relatedTarget;if(nextTarget==null){clearNullFocusOutTimer(),nullFocusOutTimer=setTimeout(()=>{if(nullFocusOutTimer=null,getActiveTreeElement(rootElement)!=null){updateActiveItemPath();return}domFocusOwnerRef.current=!1,setActiveItemPath(null)},0);return}if(!(nextTarget instanceof Node)||!rootElement.contains(nextTarget)){clearNullFocusOutTimer(),domFocusOwnerRef.current=!1,setActiveItemPath(null);return}const nextActiveItemPath=nextTarget instanceof HTMLElement?nextTarget.dataset.itemPath??null:null;setActiveItemPath(previousPath=>previousPath===nextActiveItemPath?previousPath:nextActiveItemPath)};return rootElement.addEventListener("focusin",onFocusIn),rootElement.addEventListener("focusout",onFocusOut),()=>{clearNullFocusOutTimer(),rootElement.removeEventListener("focusin",onFocusIn),rootElement.removeEventListener("focusout",onFocusOut)}},[]),A(()=>{const rootElement=rootRef.current;rootElement!=null&&(layoutSnapshot.physical.scrollTop<=0?rootElement.dataset.scrollAtTop="true":delete rootElement.dataset.scrollAtTop)},[layoutSnapshot.physical.scrollTop]),A(()=>{let scrollTimer=null;const scrollElement=scrollRef.current,listElement=listRef.current,rootElement=rootRef.current;if(scrollElement==null)return;measuredViewportHeightRef.current=readMeasuredViewportHeight(scrollElement,initialViewportHeight);const update=()=>{const nextItemCount=controller.getVisibleCount(),nextViewportHeight=getCachedViewportHeight(measuredViewportHeightRef.current,initialViewportHeight),maxScrollTop=Math.max(0,nextItemCount*itemHeight-nextViewportHeight);scrollElement.scrollTop>maxScrollTop&&(scrollElement.scrollTop=maxScrollTop),setLayoutState(computeFileTreeViewLayoutState({controller,itemHeight,overscan,scrollTop:Math.min(scrollElement.scrollTop,maxScrollTop),stickyFolders,viewportHeight:nextViewportHeight}))};if(!initialFocusedScrollAppliedRef.current){initialFocusedScrollAppliedRef.current=!0;const initialFocusedIndex=controller.getFocusedIndex();if(initialFocusedIndex>=0){const initialViewportHeightPx=getCachedViewportHeight(measuredViewportHeightRef.current,initialViewportHeight),initialFocusedRow=controller.getVisibleRows(initialFocusedIndex,initialFocusedIndex)[0]??null;scrollFocusedRowIntoView(scrollElement,initialFocusedIndex,itemHeight,initialViewportHeightPx,stickyFolders&&initialFocusedRow!=null?Math.max(0,Math.min(initialFocusedRow.ancestorPaths.length*itemHeight,Math.max(0,initialViewportHeightPx-itemHeight))):0)}}updateViewportRef.current=update;const unsubscribe=controller.subscribe(()=>{shouldBumpControllerRevision(hasSeenInitialControllerSnapshotRef)&&setControllerRevision(revision=>revision+1),update()}),markScrolling=()=>{debugDisableScrollSuppressionRef.current!==!0&&(listElement!=null&&(listElement.dataset.isScrolling??=""),rootElement!=null&&(rootElement.dataset.isScrolling??=""),isScrollingRef.current=!0,scrollTimer!=null&&clearTimeout(scrollTimer),scrollTimer=setTimeout(()=>{listElement!=null&&delete listElement.dataset.isScrolling,rootElement!=null&&delete rootElement.dataset.isScrolling,isScrollingRef.current=!1,setScrollSettledRevision(revision=>revision+1),scrollTimer=null},50))};let overlayRevealTimer=null;const clearOverlayReveal=()=>{rootElement!=null&&delete rootElement.dataset.overlayReveal,overlayRevealTimer!=null&&(clearTimeout(overlayRevealTimer),overlayRevealTimer=null)},markOverlayReveal=()=>{rootElement==null||debugDisableScrollSuppressionRef.current===!0||scrollElement.scrollTop>0||(rootElement.dataset.overlayReveal="true",overlayRevealTimer!=null&&clearTimeout(overlayRevealTimer),overlayRevealTimer=setTimeout(()=>{clearOverlayReveal()},200))},onScroll=()=>{if(update(),scrollElement.scrollTop>0&&clearOverlayReveal(),contextMenuStateRef.current!=null&&isScrollingRef.current&&closeContextMenuRef.current(),debugDisableScrollSuppressionRef.current===!0){isScrollingRef.current=!1;return}setContextHoverPath(previousPath=>previousPath==null?previousPath:null),markScrolling()},onPreScroll=()=>{markScrolling(),markOverlayReveal()},SCROLL_KEYS=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown","Home","End"," ","Spacebar"]),onKeyDownPreScroll=event=>{SCROLL_KEYS.has(event.key)&&onPreScroll()};scrollElement.addEventListener("scroll",onScroll,{passive:!0}),scrollElement.addEventListener("wheel",onPreScroll,{passive:!0}),scrollElement.addEventListener("touchmove",onPreScroll,{passive:!0}),scrollElement.addEventListener("keydown",onKeyDownPreScroll);const resizeObserver=typeof ResizeObserver<"u"?new ResizeObserver(entries=>{measuredViewportHeightRef.current=(entries[0]==null?null:getResizeObserverViewportHeight(entries[0]))??readMeasuredViewportHeight(scrollElement,initialViewportHeight),update()}):null;return resizeObserver?.observe(scrollElement),()=>{updateViewportRef.current=()=>{},unsubscribe(),scrollElement.removeEventListener("scroll",onScroll),scrollElement.removeEventListener("wheel",onPreScroll),scrollElement.removeEventListener("touchmove",onPreScroll),scrollElement.removeEventListener("keydown",onKeyDownPreScroll),scrollTimer!=null&&clearTimeout(scrollTimer),overlayRevealTimer!=null&&clearTimeout(overlayRevealTimer),listElement!=null&&delete listElement.dataset.isScrolling,rootElement!=null&&(delete rootElement.dataset.isScrolling,delete rootElement.dataset.overlayReveal),isScrollingRef.current=!1,measuredViewportHeightRef.current=null,resizeObserver?.disconnect()}},[controller,initialViewportHeight,itemHeight,overscan,stickyFolders]),A(()=>{contextMenuEnabled||contextMenuState==null||closeContextMenu(!1)},[closeContextMenu,contextMenuEnabled,contextMenuState]);const activeContextMenuKey=q(()=>contextMenuState==null?null:`${contextMenuState.path}::${contextMenuState.source}`,[contextMenuState]);A(()=>{if(activeContextMenuKey==null){slotHost?.clearSlotContent(CONTEXT_MENU_SLOT_NAME);return}const currentState=contextMenuStateRef.current;if(currentState==null)return;const anchorElement=contextMenuTriggerRef.current??contextMenuAnchorRef.current;if(anchorElement==null)return;const context={anchorElement,anchorRect:currentState.anchorRect??serializeAnchorRect(anchorElement.getBoundingClientRect()),close:options=>{closeContextMenuRef.current(options?.restoreFocus??!0)},restoreFocus:()=>{shouldRestoreContextMenuFocusRef.current&&restoreFocusToTreeRef.current(contextMenuStateRef.current?.path??null)}},menuContent=composition?.contextMenu?.render?.(currentState.item,context)??null;return slotHost?.setSlotContent(CONTEXT_MENU_SLOT_NAME,menuContent),composition?.contextMenu?.onOpen?.(currentState.item,context),focusFirstMenuElement(menuContent),queueMicrotask(()=>{menuContent==null||!menuContent.isConnected||document.activeElement===menuContent&&focusFirstMenuElement(menuContent)}),()=>{slotHost?.clearSlotContent(CONTEXT_MENU_SLOT_NAME)}},[activeContextMenuKey,composition?.contextMenu,slotHost]),A(()=>{contextMenuState!=null&&controller.getItem(contextMenuState.path)==null&&closeContextMenu()},[closeContextMenu,contextMenuState,controller]),A(()=>{if(contextMenuState==null)return;const rootNode=rootRef.current?.getRootNode(),host=rootNode instanceof ShadowRoot?rootNode.host:rootRef.current,onPointerDown=event=>{const target=event.target;target instanceof Node&&(isEventInContextMenu(event)||contextMenuAnchorRef.current?.contains(target)!==!0&&host?.contains(target)!==!0&&closeContextMenu())},onKeyDown=event=>{event.key==="Escape"&&(event.preventDefault(),event.stopPropagation(),closeContextMenu())};return document.addEventListener("mousedown",onPointerDown,!0),document.addEventListener("keydown",onKeyDown,!0),()=>{document.removeEventListener("mousedown",onPointerDown,!0),document.removeEventListener("keydown",onKeyDown,!0)}},[closeContextMenu,contextMenuState]),A(()=>{const scrollElement=scrollRef.current,rootElement=rootRef.current;if(scrollElement==null||rootElement==null){previousFocusedPathRef.current=focusedPath;return}const focusedButton=focusedPath==null?null:rowButtonRefs.current.get(focusedPath)??null,activeTreeElement=getActiveTreeElement(rootElement),activeTreeElementPath=activeTreeElement?.dataset.itemPath??null,renameInputOwnsFocus=isRenaming&&renameInputRef.current===activeTreeElement,searchInputOwnsFocus=searchEnabled&&searchInputRef.current===activeTreeElement,shouldRestoreTreeFocusAfterSearchClose=restoreTreeFocusAfterSearchCloseRef.current&&!isSearchOpen,preservedViewportOffset=restoreTreeFocusViewportOffsetRef.current??0,pendingStickyFocusPath=pendingStickyFocusPathRef.current,pendingStickyKeyboardFocusPath=pendingStickyKeyboardFocusPathRef.current,pendingStickyKeyboardViewportOffset=pendingStickyKeyboardViewportOffsetRef.current,pendingStickyKeyboardScrollTop=pendingStickyKeyboardScrollTopRef.current,focusWithinTree=activeTreeElement!=null,shouldOwnDomFocus=domFocusOwnerRef.current||focusWithinTree,focusedPathChanged=previousFocusedPathRef.current!==focusedPath,shouldPreserveStickyKeyboardFocusViewport=pendingStickyKeyboardFocusPath!=null&&pendingStickyKeyboardFocusPath===focusedPath&&focusedPath!=null;let shouldSuppressDomFocusForScrollRequest=!1,shouldUpdateViewportForScrollRequest=!1;if(scrollRequest!=null&&scrollRequest.id!==processedScrollRequestIdRef.current){processedScrollRequestIdRef.current=scrollRequest.id;const scrollRequestIndex=scrollRequest.visibleIndex,scrollRequestRow=controller.getVisibleRows(scrollRequestIndex,scrollRequestIndex)[0]??null;if(scrollRequestRow!=null){const scrollRequestTopInset=stickyFolders?Math.max(0,Math.min(scrollRequestRow.ancestorPaths.length*itemHeight,Math.max(0,resolvedViewportHeight-itemHeight))):stickyOverlayHeight;shouldSuppressDomFocusForScrollRequest=!0,shouldUpdateViewportForScrollRequest=scrollFocusedRowToOffset(scrollElement,scrollRequestIndex,itemHeight,resolvedViewportHeight,totalScrollableHeight,scrollRequest.offset,scrollRequestTopInset)}controller.clearScrollRequest(scrollRequest.id)}const shouldRestoreFocusedRowViewportOffset=!shouldSuppressDomFocusForScrollRequest&&shouldRestoreTreeFocusAfterSearchClose&&scrollFocusedRowToViewportOffset(scrollElement,focusedIndex,itemHeight,resolvedViewportHeight,totalScrollableHeight,preservedViewportOffset),shouldRestoreStickyFocusedRowViewportOffset=!shouldSuppressDomFocusForScrollRequest&&pendingStickyFocusPath!=null&&pendingStickyFocusPath===focusedPath&&scrollFocusedRowToViewportOffset(scrollElement,focusedIndex,itemHeight,resolvedViewportHeight,totalScrollableHeight,stickyOverlayHeight),shouldRestoreStickyKeyboardViewportOffset=!shouldSuppressDomFocusForScrollRequest&&pendingStickyKeyboardViewportOffset!=null&&pendingStickyKeyboardViewportOffset.path===focusedPath&&scrollFocusedRowToViewportOffset(scrollElement,focusedIndex,itemHeight,resolvedViewportHeight,totalScrollableHeight,pendingStickyKeyboardViewportOffset.viewportOffset),shouldRestoreStickyKeyboardScrollTop=!shouldSuppressDomFocusForScrollRequest&&pendingStickyKeyboardScrollTop!=null&&pendingStickyKeyboardScrollTop.path===focusedPath&&scrollElement.scrollTop!==pendingStickyKeyboardScrollTop.scrollTop;if(shouldRestoreStickyKeyboardScrollTop&&(scrollElement.scrollTop=pendingStickyKeyboardScrollTop.scrollTop),(shouldRestoreStickyKeyboardScrollTop||shouldUpdateViewportForScrollRequest||shouldRestoreStickyFocusedRowViewportOffset||shouldRestoreStickyKeyboardViewportOffset||shouldRestoreFocusedRowViewportOffset||shouldOwnDomFocus&&focusedPathChanged&&pendingStickyFocusPath!==focusedPath&&!shouldPreserveStickyKeyboardFocusViewport&&scrollFocusedRowIntoView(scrollElement,focusedIndex,itemHeight,resolvedViewportHeight,stickyOverlayHeight))&&updateViewportRef.current(),shouldSuppressDomFocusForScrollRequest){previousFocusedPathRef.current=focusedPath;return}if(!shouldOwnDomFocus){previousFocusedPathRef.current=focusedPath;return}if(renameInputOwnsFocus){previousFocusedPathRef.current=focusedPath;return}if(searchInputOwnsFocus&&!shouldRestoreTreeFocusAfterSearchClose){previousFocusedPathRef.current=focusedPath;return}if(focusedButton==null){shouldRestoreTreeFocusAfterSearchClose&&focusedIndex>=0&&(scrollFocusedRowToViewportOffset(scrollElement,focusedIndex,itemHeight,resolvedViewportHeight,totalScrollableHeight,preservedViewportOffset),updateViewportRef.current()),previousFocusedPathRef.current=focusedPath;return}(focusedPathChanged||shouldRestoreTreeFocusAfterSearchClose||pendingStickyFocusPath===focusedPath||pendingStickyKeyboardFocusPath===focusedPath||pendingStickyKeyboardViewportOffset?.path===focusedPath||pendingStickyKeyboardScrollTop?.path===focusedPath||activeTreeElementPath==null||activeTreeElementPath!==focusedPath)&&(focusElement(focusedButton),pendingStickyFocusPath===focusedPath&&(pendingStickyFocusPathRef.current=null),pendingStickyKeyboardFocusPath===focusedPath&&(pendingStickyKeyboardFocusPathRef.current=null),pendingStickyKeyboardViewportOffset?.path===focusedPath&&(pendingStickyKeyboardViewportOffsetRef.current=null),pendingStickyKeyboardScrollTop?.path===focusedPath&&(pendingStickyKeyboardScrollTopRef.current=null),restoreTreeFocusAfterSearchCloseRef.current=!1,restoreTreeFocusViewportOffsetRef.current=null),previousFocusedPathRef.current=focusedPath},[controller,focusedIndex,focusedPath,focusedRowIsMounted,itemHeight,isRenaming,isSearchOpen,range2,resolvedViewportHeight,searchEnabled,scrollRequest,stickyFolders,stickyOverlayHeight,totalScrollableHeight,visibleRows]);const focusedRowIsVisible=focusedIndex>=0&&focusedIndex>=layoutSnapshot.visible.startIndex&&focusedIndex<=layoutSnapshot.visible.endIndex,focusedRowIsSticky=focusedPath!=null&&stickyRows.some(entry=>getFileTreeRowPath(entry.row)===focusedPath),focusedRowHasVisibleAnchor=focusedRowIsVisible||focusedRowIsSticky,focusTriggerPath=contextMenuButtonTriggerEnabled&&domFocusOwnerRef.current===!0&&focusedRowHasVisibleAnchor?focusedPath:null,pointerTriggerPath=lastContextMenuInteraction==="pointer"?contextHoverPath:null,triggerPath=contextMenuState?.path??debugContextMenuTriggerPathRef.current??pointerTriggerPath??focusTriggerPath??contextHoverPath,isPointerContextMenuOpen=contextMenuState?.source==="right-click";A(()=>{isScrollingRef.current&&contextMenuState==null||updateTriggerPosition(getTriggerAnchorButton(triggerPath))},[contextMenuState,getTriggerAnchorButton,range2,resolvedViewportHeight,scrollSettledRevision,stickyRows,triggerPath,updateTriggerPosition,visibleRows]);const handleTreePointerOver=b(event=>{if(isScrollingRef.current||isEventInContextMenu(event))return;const target=event.target;if(!(target instanceof HTMLElement)||target.closest?.('[data-type="context-menu-trigger"]')!=null)return;const stickyRowButton=target.closest?.('[data-file-tree-sticky-row="true"]'),rowButton=target.closest?.('[data-type="item"]'),nextPath=stickyRowButton instanceof HTMLElement?stickyRowButton.dataset.fileTreeStickyPath??null:rowButton instanceof HTMLElement?rowButton.dataset.itemPath??null:null;nextPath!=null&&setLastContextMenuInteraction(previousMode=>previousMode==="pointer"?previousMode:"pointer"),setContextHoverPath(previousPath=>previousPath===nextPath?previousPath:nextPath)},[]),handleTreePointerLeave=b(()=>{setContextHoverPath(null)},[]);A(()=>{if(!dragAndDropEnabled)return;const handleWindowDragEnd=()=>{clearTouchDragResources(),controller.cancelDrag()};return window.addEventListener("dragend",handleWindowDragEnd),()=>{window.removeEventListener("dragend",handleWindowDragEnd),clearTouchDragResources(),controller.cancelDrag()}},[controller,dragAndDropEnabled]);const handleTreeDragOver=event=>{if(!dragAndDropEnabled||controller.getDragSession()==null||touchDragActiveRef.current)return;const nextTarget=resolveDropTargetFromElement(event.target instanceof HTMLElement?event.target:null);controller.setDragTarget(nextTarget),scheduleDragHoverOpen(controller.getDragSession()?.target??null),updateDragPoint(event.clientX,event.clientY),event.dataTransfer!=null&&(event.dataTransfer.dropEffect="move"),event.preventDefault()},handleTreeDragLeave=event=>{if(!dragAndDropEnabled||controller.getDragSession()==null||touchDragActiveRef.current)return;const nextTarget=event.relatedTarget;nextTarget instanceof Node&&rootRef.current?.contains(nextTarget)===!0||(clearDragHoverOpen(),stopDragAutoScroll(),controller.setDragTarget(null))},handleTreeDrop=event=>{!dragAndDropEnabled||controller.getDragSession()==null||touchDragActiveRef.current||(event.preventDefault(),syncDropTargetFromPoint(event.clientX,event.clientY),controller.completeDrag(),clearDragPreview(),clearDragHoverOpen(),stopDragAutoScroll(),dragRowSnapshotRef.current=null)},windowHeight=layoutSnapshot.window.height,windowOffsetTop=layoutSnapshot.window.offsetTop,windowStickyTopInset=Math.min(0,resolvedViewportHeight-windowHeight),windowStickyBottomInset=Math.min(0,resolvedViewportHeight-windowHeight-stickyOverlayHeight),shouldRenderParkedFocusedRow=activeItemPath===focusedPath||restoreTreeFocusAfterSearchCloseRef.current,parkedFocusedRow=focusedPath!=null&&shouldRenderParkedFocusedRow&&!focusedRowIsMounted&&focusedIndex>=0?visibleRows[focusedIndex]??controller.getVisibleRows(focusedIndex,focusedIndex)[0]??null:null,parkedFocusedRowOffset=parkedFocusedRow==null?null:getParkedFocusedRowOffset(focusedIndex,itemHeight,range2,windowHeight),draggedRowSnapshot=dragRowSnapshotRef.current,draggedRowIsMounted=draggedPrimaryPath!=null&&draggedRowSnapshot!=null&&draggedRowSnapshot.path===draggedPrimaryPath&&draggedRowSnapshot.index>=range2.start&&draggedRowSnapshot.index<=range2.end,parkedDraggedRow=draggedPrimaryPath!=null&&draggedRowSnapshot!=null&&draggedRowSnapshot.path===draggedPrimaryPath&&!draggedRowIsMounted&&draggedRowSnapshot.path!==parkedFocusedRow?.path?draggedRowSnapshot:null,parkedDraggedRowOffset=parkedDraggedRow==null?null:getParkedFocusedRowOffset(parkedDraggedRow.index,itemHeight,range2,windowHeight),guideStyleText=getFileTreeGuideStyleText((focusedIndex>=0?visibleRows[focusedIndex]??controller.getVisibleRows(focusedIndex,focusedIndex)[0]??null:null)?.ancestorPaths.at(-1)??null),activeDescendantId=isSearchOpen&&focusedPath!=null?getFileTreeFocusedRowDomId(instanceId,focusedPath,!focusedRowIsMounted):void 0,visualFocusPath=contextMenuState?.path??(isSearchOpen?focusedPath:activeItemPath),visualContextHoverPath=contextMenuState?.path??contextHoverPath,triggerButton=getTriggerAnchorButton(triggerPath),triggerButtonVisible=contextMenuEnabled&&contextMenuButtonTriggerEnabled&&!isPointerContextMenuOpen&&!isRenaming&&triggerButton!=null&&contextMenuAnchorTop!=null&&triggerPath!=null,contextMenuAnchorVisible=contextMenuEnabled&&(triggerButtonVisible||contextMenuState!=null),pointerAnchorRect=contextMenuState?.anchorRect,rowAnchorTop=pointerAnchorRect==null&&triggerButton!=null&&contextMenuAnchorTop!=null&&(contextMenuState!=null||triggerButtonVisible)?contextMenuAnchorTop:null,contextMenuAnchorStyle=pointerAnchorRect!=null?{left:`${pointerAnchorRect.left}px`,position:"fixed",right:"auto",top:`${pointerAnchorRect.top}px`}:rowAnchorTop!=null?{top:`${rowAnchorTop}px`}:void 0,contextMenuTriggerStyle=isPointerContextMenuOpen?{opacity:"0"}:void 0,handleRowClick=b((event,row,targetPath,mode)=>{const plan=computeFileTreeRowClickPlan({event:{ctrlKey:event.ctrlKey,metaKey:event.metaKey,shiftKey:event.shiftKey},isDirectory:row.kind==="directory",isSearchOpen,mode}),shouldToggleDirectory=plan.toggleDirectory&&row.kind==="directory",mountedDirectoryPath=shouldToggleDirectory?controller.resolveMountedDirectoryPathFromInput(targetPath):null;if(shouldToggleDirectory&&mountedDirectoryPath==null)return;const actionTargetPath=mountedDirectoryPath??targetPath;switch(plan.selection.kind){case"range":controller.selectPathRange(actionTargetPath,plan.selection.additive);break;case"toggle":controller.togglePathSelectionFromInput(actionTargetPath);break;case"single":controller.selectOnlyMountedPathFromInput(actionTargetPath);break}const clickedElement=event.currentTarget instanceof HTMLElement?event.currentTarget:null,clickedRowIsVisible=row.index>=layoutSnapshot.visible.startIndex&&row.index<=layoutSnapshot.visible.endIndex,shouldExposeFocusedTrigger=mode==="flow"&&clickedRowIsVisible&&clickedElement!=null&&clickedElement.dataset.itemParked!=="true";controller.focusMountedPathFromInput(actionTargetPath),shouldExposeFocusedTrigger&&(domFocusOwnerRef.current=!0,setActiveItemPath(previousPath=>previousPath===actionTargetPath?previousPath:actionTargetPath),setLastContextMenuInteraction("focus")),shouldToggleDirectory&&controller.toggleMountedDirectoryFromInput(actionTargetPath),plan.closeSearch&&controller.closeSearch(),plan.revealCanonical&&revealCanonicalRowAtStickyOffset(actionTargetPath,{targetOffset:"sticky-parents"})},[controller,isSearchOpen,layoutSnapshot.visible.endIndex,layoutSnapshot.visible.startIndex,revealCanonicalRowAtStickyOffset]),openMenuFromTrigger=()=>{if(isScrollingRef.current||!contextMenuButtonTriggerEnabled||triggerPath==null||triggerButton==null)return;const triggerItem=controller.getItem(triggerPath);triggerItem!=null&&(updateTriggerPosition(triggerButton),shouldRestoreContextMenuFocusRef.current=!0,setContextMenuState({anchorRect:null,item:{kind:triggerItem.isDirectory()?"directory":"file",name:triggerButton.getAttribute("aria-label")??triggerPath,path:triggerItem.getPath()},path:triggerItem.getPath(),source:"button"}))},flowRowFrame={contextHoverPath:visualContextHoverPath,contextMenuButtonTriggerEnabled,contextMenuButtonVisibility,contextMenuEnabled,contextMenuRightClickEnabled,contextMenuTriggerMode,controller,directoriesWithGitChanges,dragAndDropEnabled,draggedPathSet,dragTarget,gitLaneActive,gitStatusByPath,handleRowDragEnd,handleRowDragStart,handleRowTouchStart,ignoredGitDirectories,ignoredInheritanceCache,instanceId,itemHeight,onKeyDown:handleTreeKeyDown,onRowClick:handleRowClick,openContextMenuForRow,registerButton:registerRowButton,registerRenameInput,renameView,renderDecorationForRow,resolveIcon,shouldSuppressContextMenu,visualFocusPath},stickyRowFrame={...flowRowFrame,registerButton:registerStickyRowButton};return u$1("div",{ref:rootRef,id:treeDomId,"data-file-tree-context-menu-button-visibility":contextMenuEnabled&&contextMenuButtonTriggerEnabled?contextMenuButtonVisibility:void 0,"data-file-tree-context-menu-trigger-mode":contextMenuEnabled?contextMenuTriggerMode:void 0,"data-file-tree-has-context-menu-action-lane":contextMenuEnabled&&contextMenuButtonTriggerEnabled?"true":void 0,"data-file-tree-has-git-lane":gitLaneActive?"true":void 0,"data-file-tree-virtualized-root":"true",onDragLeave:dragAndDropEnabled?handleTreeDragLeave:void 0,onDragOver:dragAndDropEnabled?handleTreeDragOver:void 0,onDrop:dragAndDropEnabled?handleTreeDrop:void 0,onKeyDown:handleTreeKeyDown,onPointerLeave:contextMenuEnabled?handleTreePointerLeave:void 0,onPointerOver:contextMenuEnabled?handleTreePointerOver:void 0,role:"tree",tabIndex:-1,style:{outline:"none",position:"relative"},children:[u$1("style",{"data-file-tree-guide-style":"true",dangerouslySetInnerHTML:{__html:guideStyleText}}),u$1("slot",{name:HEADER_SLOT_NAME,"data-type":"header-slot"}),searchEnabled?u$1("div",{"data-file-tree-search-container":!0,"data-open":isSearchOpen?"true":"false",children:u$1("input",{ref:searchInputRef,"aria-activedescendant":activeDescendantId,"aria-controls":treeDomId,placeholder:"Search…","data-file-tree-search-input":!0,"data-file-tree-search-input-fake-focus":fakeSearchFocusActive?"true":void 0,value:searchValue,onBlur:()=>{searchBlurBehavior==="retain"&&!searchInputUserInteractedRef.current||controller.closeSearch()},onFocus:markSearchInputInteracted,onPointerDown:markSearchInputInteracted,onInput:event=>{markSearchInputInteracted();const target=event.currentTarget;controller.setSearch(target.value)}})}):null,u$1("div",{ref:scrollRef,"data-file-tree-virtualized-scroll":"true",children:[stickyFolders&&hasStickyUiMount&&stickyRows.length>0?u$1("div",{"aria-hidden":"true","data-file-tree-sticky-overlay":"true",children:u$1("div",{"data-file-tree-sticky-overlay-content":"true",style:{height:`${overlayRowsHeight}px`},children:stickyRows.map((entry,index)=>renderStyledRow(stickyRowFrame,entry.row,`sticky:${getFileTreeRowPath(entry.row)}`,{mode:"sticky",style:{left:"0",position:"absolute",right:"0",top:`${entry.top}px`,zIndex:`${stickyRows.length-index}`}}))})}):null,u$1("div",{ref:listRef,"data-file-tree-virtualized-list":"true",style:{height:`${totalScrollableHeight}px`},children:[u$1("div",{"data-file-tree-virtualized-sticky-offset":"true","aria-hidden":"true",style:{height:`${windowOffsetTop}px`}}),u$1("div",{"data-file-tree-virtualized-sticky":"true",style:{height:`${windowHeight}px`,top:`${windowStickyTopInset}px`,bottom:`${windowStickyBottomInset}px`},children:[renderRangeChildren(flowRowFrame,range2,stickyRowPathSet),parkedFocusedRow!=null&&parkedFocusedRowOffset!=null?renderStyledRow(flowRowFrame,parkedFocusedRow,`parked:${parkedFocusedRow.path}`,{isParked:!0,style:{left:"0",opacity:"0",pointerEvents:draggedPrimaryPath===parkedFocusedRow.path?"none":void 0,position:"absolute",right:"0",top:`${parkedFocusedRowOffset}px`}}):null,parkedDraggedRow!=null&&parkedDraggedRowOffset!=null?renderStyledRow(flowRowFrame,parkedDraggedRow,`parked-drag:${parkedDraggedRow.path}`,{isParked:!0,style:{left:"0",opacity:"0",pointerEvents:"none",position:"absolute",right:"0",top:`${parkedDraggedRowOffset}px`}}):null]})]})]}),contextMenuEnabled?u$1("div",{ref:contextMenuAnchorRef,"data-type":"context-menu-anchor","data-visible":contextMenuAnchorVisible?"true":"false",style:contextMenuAnchorStyle,children:[u$1("button",{ref:contextMenuTriggerRef,type:"button","data-type":CONTEXT_MENU_TRIGGER_TYPE,"aria-label":"Options","aria-haspopup":"menu","aria-expanded":contextMenuState!=null?"true":"false","data-visible":triggerButtonVisible?"true":"false",onMouseDown:event=>{event.preventDefault()},onClick:event=>{if(event.preventDefault(),event.stopPropagation(),contextMenuState!=null){closeContextMenu();return}openMenuFromTrigger()},tabIndex:-1,style:contextMenuTriggerStyle,children:u$1(Icon,{...resolveIcon("file-tree-icon-ellipsis")})}),contextMenuState!=null?u$1("slot",{name:CONTEXT_MENU_SLOT_NAME}):null]}):null,contextMenuState!=null?u$1("div",{"data-type":"context-menu-wash","aria-hidden":"true",onMouseDownCapture:event=>{event.preventDefault(),closeContextMenu()},onTouchStartCapture:event=>{event.preventDefault(),event.stopPropagation(),closeContextMenu()},onTouchMoveCapture:event=>{event.preventDefault(),event.stopPropagation()},onWheelCapture:event=>{event.preventDefault(),event.stopPropagation()}}):null]})}const fileTreeRenderer={hydrateRoot:(element,props)=>{G(_$1(FileTreeView,props),element)},renderRoot:(element,props)=>{F$1(_$1(FileTreeView,props),element)},unmountRoot:element=>{F$1(null,element)}};function renderFileTreeRoot(element,props){fileTreeRenderer.renderRoot(element,props)}function hydrateFileTreeRoot(element,props){fileTreeRenderer.hydrateRoot(element,props)}function unmountFileTreeRoot(element){fileTreeRenderer.unmountRoot(element)}var FileTreeManagedSlotHost=class{#contentBySlot=new Map;#host=null;clearAll(){for(const content of this.#contentBySlot.values())content.remove();this.#contentBySlot.clear()}clearSlotContent(slotName){const currentContent=this.#getCurrentContent(slotName);currentContent!=null&&(currentContent.remove(),this.#contentBySlot.delete(slotName))}setHost(host){if(this.#host=host,host!=null){this.#adoptExistingManagedContent(host);for(const[slotName,content]of this.#contentBySlot)this.#attachContent(slotName,content)}}setSlotContent(slotName,content){const currentContent=this.#getCurrentContent(slotName);if(currentContent===content){content!=null&&(this.#contentBySlot.set(slotName,content),this.#attachContent(slotName,content));return}if(currentContent?.remove(),content==null){this.#contentBySlot.delete(slotName);return}this.#contentBySlot.set(slotName,content),this.#attachContent(slotName,content)}setSlotHtml(slotName,html){const normalizedHtml=html?.trim()??"";if(normalizedHtml.length===0){this.setSlotContent(slotName,null);return}const currentContent=this.#getCurrentContent(slotName);if(currentContent!=null&&currentContent.innerHTML===normalizedHtml){this.#contentBySlot.set(slotName,currentContent),this.#attachContent(slotName,currentContent);return}const nextContent=document.createElement("div");nextContent.innerHTML=normalizedHtml,this.setSlotContent(slotName,nextContent)}#getCurrentContent(slotName){const trackedContent=this.#contentBySlot.get(slotName)??null;if(trackedContent!=null)return trackedContent;const host=this.#host;if(host==null)return null;for(const element of Array.from(host.children))if(element instanceof HTMLElement&&element.dataset.fileTreeManagedSlot===slotName)return element;return null}#attachContent(slotName,content){content.slot=slotName,content.dataset.fileTreeManagedSlot=slotName,this.#host!=null&&content.parentNode!==this.#host&&this.#host.appendChild(content)}#adoptExistingManagedContent(host){for(const element of Array.from(host.children)){if(!(element instanceof HTMLElement))continue;const slotName=element.dataset.fileTreeManagedSlot;slotName==null||this.#contentBySlot.has(slotName)||this.#contentBySlot.set(slotName,element)}}};let clientInstanceId=0;function createClientId(explicitId){return explicitId!=null&&explicitId.length>0?explicitId:(clientInstanceId+=1,`pst_ft_${clientInstanceId}`)}function resolveInitialViewportHeight({initialVisibleRowCount,itemHeight}){return initialVisibleRowCount==null?420:Math.max(0,initialVisibleRowCount)*(itemHeight??FILE_TREE_DEFAULT_ITEM_HEIGHT)}function parseSpriteSheet(spriteSheet){if(typeof document>"u")return;const wrapper=document.createElement("div");wrapper.innerHTML=spriteSheet;const svg=wrapper.querySelector("svg");return svg instanceof SVGElement?svg:void 0}function isBuiltInSpriteSheet(spriteSheet){return spriteSheet.querySelector("#file-tree-icon-chevron")instanceof SVGElement&&spriteSheet.querySelector("#file-tree-icon-file")instanceof SVGElement&&spriteSheet.querySelector("#file-tree-icon-dot")instanceof SVGElement&&spriteSheet.querySelector("#file-tree-icon-lock")instanceof SVGElement}function getTopLevelSpriteSheets(shadowRoot){return Array.from(shadowRoot.children).filter(element=>element instanceof SVGElement)}var FileTree$2=class{static LoadedCustomComponent=!0;#composition;#controller;#id;#onSelectionChange;#renderRowDecoration;#renamingEnabled;#searchBlurBehavior;#searchEnabled;#searchFakeFocus;#slotHost=new FileTreeManagedSlotHost;#density;#viewOptions;#fileTreeContainer;#gitStatusState;#icons;#unsafeCSS;#unsafeCSSStyle;#appliedUnsafeCSS;#selectionVersion;#selectionSubscription=null;#wrapper;#wroteHostItemHeight=!1;#wroteHostDensityFactor=!1;constructor(options){const{composition,density,fileTreeSearchMode,gitStatus,id,initialSearchQuery,icons,itemHeight,onSearchChange,onSelectionChange,overscan,renderRowDecoration:renderRowDecoration2,renaming,search,searchBlurBehavior,searchFakeFocus,stickyFolders,unsafeCSS,initialVisibleRowCount,...controllerOptions}=options;this.#composition=composition,this.#id=createClientId(id),this.#gitStatusState=resolveFileTreeGitStatusState(gitStatus),this.#icons=icons,this.#unsafeCSS=unsafeCSS,this.#onSelectionChange=onSelectionChange,this.#renderRowDecoration=renderRowDecoration2,this.#renamingEnabled=renaming!=null&&renaming!==!1,this.#searchBlurBehavior=searchBlurBehavior,this.#searchEnabled=search===!0,this.#searchFakeFocus=searchFakeFocus===!0,this.#density=resolveFileTreeDensity(density,itemHeight),this.#viewOptions={itemHeight:this.#density.itemHeight,overscan,stickyFolders,initialVisibleRowCount},this.#controller=new FileTreeController({...controllerOptions,fileTreeSearchMode,initialSearchQuery,onSearchChange,renaming}),this.#selectionVersion=this.#controller.getSelectionVersion(),this.#selectionSubscription=this.#onSelectionChange==null?null:this.subscribe(()=>{this.#emitSelectionChange()})}unmount(){this.#wrapper!=null&&(unmountFileTreeRoot(this.#wrapper),delete this.#wrapper.dataset.fileTreeVirtualizedWrapper,this.#wrapper=void 0),this.#slotHost.clearAll(),this.#slotHost.setHost(null),this.#fileTreeContainer!=null&&(delete this.#fileTreeContainer.dataset.fileTreeVirtualized,this.#removeOwnedDensityHostStyle(this.#fileTreeContainer),this.#fileTreeContainer=void 0)}cleanUp(){this.unmount(),this.#selectionSubscription?.(),this.#selectionSubscription=null,this.#controller.destroy()}getFileTreeContainer(){return this.#fileTreeContainer}getItem(path){return this.#controller.getItem(path)}getFocusedItem(){return this.#controller.getFocusedItem()}getFocusedPath(){return this.#controller.getFocusedPath()}getFocusedIndex(){return this.#controller.getFocusedIndex()}getVisibleCount(){return this.#controller.getVisibleCount()}getVisibleRows(start,end){return this.#controller.getVisibleRows(start,end)}getSelectedPaths(){return this.#controller.getSelectedPaths()}getComposition(){return this.#composition}getItemHeight(){return this.#density.itemHeight}getDensityFactor(){return this.#density.factor}subscribe(listener){let hasSeenInitialSnapshot=!1;return this.#controller.subscribe(()=>{if(!hasSeenInitialSnapshot){hasSeenInitialSnapshot=!0;return}listener()})}focusPath(path){this.#controller.focusPath(path)}focusFirstItem(){this.#controller.focusFirstItem()}focusLastItem(){this.#controller.focusLastItem()}focusNextItem(){this.#controller.focusNextItem()}focusPreviousItem(){this.#controller.focusPreviousItem()}focusParentItem(){this.#controller.focusParentItem()}scrollToPath(path,options){this.#controller.scrollToPath(path,options)}focusNearestPath(path){return this.#controller.focusNearestPath(path)}add(path){this.#controller.add(path)}batch(operations){this.#controller.batch(operations)}applyGitStatusPatch(patch){const nextGitStatusState=applyFileTreeGitStatusPatch(this.#gitStatusState,patch);if(nextGitStatusState===this.#gitStatusState)return;this.#gitStatusState=nextGitStatusState;const mountedTree=this.#getMountedTreeElements();mountedTree!=null&&renderFileTreeRoot(mountedTree.wrapper,this.#getViewProps())}move(fromPath,toPath,options){this.#controller.move(fromPath,toPath,options)}onMutation(type,handler){return this.#controller.onMutation(type,handler)}setSearch(value){this.#controller.setSearch(value)}openSearch(initialValue){this.#controller.openSearch(initialValue)}closeSearch(){this.#controller.closeSearch()}isSearchOpen(){return this.#controller.isSearchOpen()}getSearchValue(){return this.#controller.getSearchValue()}getSearchMatchingPaths(){return this.#controller.getSearchMatchingPaths()}focusNextSearchMatch(){this.#controller.focusNextSearchMatch()}focusPreviousSearchMatch(){this.#controller.focusPreviousSearchMatch()}startRenaming(path,options){return this.#controller.startRenaming(path,options)}remove(path,options){this.#controller.remove(path,options)}resetPaths(pathsOrOptions,options){Array.isArray(pathsOrOptions)?this.#controller.resetPaths(pathsOrOptions,options):this.#controller.resetPaths(pathsOrOptions)}setComposition(composition){this.#composition=composition;const mountedTree=this.#getMountedTreeElements();mountedTree!=null&&(this.#syncHeaderSlotContent(),renderFileTreeRoot(mountedTree.wrapper,this.#getViewProps()))}setGitStatus(gitStatus){const nextGitStatusState=resolveFileTreeGitStatusState(gitStatus,this.#gitStatusState);if(nextGitStatusState===this.#gitStatusState)return;this.#gitStatusState=nextGitStatusState;const mountedTree=this.#getMountedTreeElements();mountedTree!=null&&renderFileTreeRoot(mountedTree.wrapper,this.#getViewProps())}setIcons(icons){this.#icons=icons;const mountedTree=this.#getMountedTreeElements();mountedTree!=null&&(this.#syncIconSurface(mountedTree.host,mountedTree.wrapper),renderFileTreeRoot(mountedTree.wrapper,this.#getViewProps()))}hydrate({fileTreeContainer}){const host=this.#prepareHost(fileTreeContainer),wrapper=this.#getOrCreateWrapper(host);this.#syncHeaderSlotContent(),hydrateFileTreeRoot(wrapper,this.#getViewProps())}render({containerWrapper,fileTreeContainer}){const host=this.#prepareHost(fileTreeContainer??this.#fileTreeContainer,containerWrapper),wrapper=this.#getOrCreateWrapper(host);this.#syncHeaderSlotContent(),renderFileTreeRoot(wrapper,this.#getViewProps())}#getInitialViewOptions(){return{initialViewportHeight:resolveInitialViewportHeight({initialVisibleRowCount:this.#viewOptions.initialVisibleRowCount,itemHeight:this.#viewOptions.itemHeight}),itemHeight:this.#viewOptions.itemHeight,overscan:this.#viewOptions.overscan,stickyFolders:this.#viewOptions.stickyFolders}}#getViewProps(){return{composition:this.#composition,controller:this.#controller,gitStatusByPath:this.#gitStatusState?.statusByPath,ignoredGitDirectories:this.#gitStatusState?.ignoredDirectoryPaths,directoriesWithGitChanges:this.#gitStatusState?.directoriesWithChanges,icons:this.#icons,instanceId:this.#id,renamingEnabled:this.#renamingEnabled,renderRowDecoration:this.#renderRowDecoration,searchBlurBehavior:this.#searchBlurBehavior,searchEnabled:this.#searchEnabled,searchFakeFocus:this.#searchFakeFocus,slotHost:this.#slotHost,...this.#getInitialViewOptions()}}#getMountedTreeElements(){const host=this.#fileTreeContainer,wrapper=this.#wrapper;return host==null||wrapper==null?null:{host,wrapper}}#syncIconSurface(host,wrapper){const shadowRoot=host.shadowRoot;shadowRoot!=null&&(this.#syncBuiltInSpriteSheet(shadowRoot),this.#syncCustomSpriteSheet(shadowRoot)),this.#syncIconModeAttrs(wrapper)}#emitSelectionChange(){const onSelectionChange=this.#onSelectionChange;if(onSelectionChange==null)return;const nextSelectionVersion=this.#controller.getSelectionVersion();nextSelectionVersion!==this.#selectionVersion&&(this.#selectionVersion=nextSelectionVersion,onSelectionChange(this.#controller.getSelectedPaths()))}#syncHeaderSlotContent(){const renderHeader=this.#composition?.header?.render;if(renderHeader!=null){this.#slotHost.setSlotContent(HEADER_SLOT_NAME,renderHeader());return}this.#slotHost.setSlotHtml(HEADER_SLOT_NAME,this.#composition?.header?.html??null)}#syncBuiltInSpriteSheet(shadowRoot){const currentBuiltInSprite=getTopLevelSpriteSheets(shadowRoot).find(sprite=>isBuiltInSpriteSheet(sprite)),nextBuiltInSprite=parseSpriteSheet(getBuiltInSpriteSheet(normalizeFileTreeIcons(this.#icons).set));nextBuiltInSprite!=null&&(currentBuiltInSprite!=null&&currentBuiltInSprite.outerHTML===nextBuiltInSprite.outerHTML||(currentBuiltInSprite!=null?currentBuiltInSprite.replaceWith(nextBuiltInSprite):shadowRoot.prepend(nextBuiltInSprite)))}#syncCustomSpriteSheet(shadowRoot){const topLevelSprites=getTopLevelSpriteSheets(shadowRoot),builtInSprite=topLevelSprites.find(sprite=>isBuiltInSpriteSheet(sprite)),currentCustomSprites=topLevelSprites.filter(sprite=>sprite!==builtInSprite),customSpriteSheet=normalizeFileTreeIcons(this.#icons).spriteSheet?.trim()??"";if(customSpriteSheet.length===0){for(const currentCustomSprite of currentCustomSprites)currentCustomSprite.remove();return}const customSprite=parseSpriteSheet(customSpriteSheet);if(customSprite==null){for(const currentCustomSprite of currentCustomSprites)currentCustomSprite.remove();return}if(!(currentCustomSprites.length===1&&currentCustomSprites[0].outerHTML===customSprite.outerHTML)){for(const currentCustomSprite of currentCustomSprites)currentCustomSprite.remove();shadowRoot.appendChild(customSprite)}}#syncIconModeAttrs(wrapper){const normalizedIcons=normalizeFileTreeIcons(this.#icons);normalizedIcons.colored&&isColoredBuiltInIconSet(normalizedIcons.set)?wrapper.dataset.fileTreeColoredIcons="true":delete wrapper.dataset.fileTreeColoredIcons}#syncUnsafeCSS(shadowRoot){const existingUnsafeStyle=shadowRoot.querySelector(`style[${FILE_TREE_UNSAFE_CSS_ATTRIBUTE}]`);if(this.#unsafeCSSStyle==null&&existingUnsafeStyle instanceof HTMLStyleElement&&(this.#unsafeCSSStyle=existingUnsafeStyle),this.#unsafeCSS==null||this.#unsafeCSS===""){this.#unsafeCSSStyle?.remove(),this.#unsafeCSSStyle=void 0,this.#appliedUnsafeCSS=void 0;return}this.#unsafeCSSStyle?.parentNode===shadowRoot&&this.#appliedUnsafeCSS===this.#unsafeCSS||(this.#unsafeCSSStyle??=document.createElement("style"),this.#unsafeCSSStyle.setAttribute(FILE_TREE_UNSAFE_CSS_ATTRIBUTE,""),this.#unsafeCSSStyle.parentNode!==shadowRoot&&shadowRoot.appendChild(this.#unsafeCSSStyle),this.#unsafeCSSStyle.textContent=wrapUnsafeCSS(this.#unsafeCSS),this.#appliedUnsafeCSS=this.#unsafeCSS)}#getOrCreateWrapper(host){if(this.#wrapper!=null)return this.#wrapper;const shadowRoot=host.shadowRoot;if(shadowRoot==null)throw new Error("FileTree requires a shadow root");const wrapperCandidates=Array.from(shadowRoot.children).filter(element=>element instanceof HTMLDivElement&&typeof element.dataset.fileTreeId=="string"&&element.dataset.fileTreeId.length>0),existingWrapper=wrapperCandidates.find(element=>element.dataset.fileTreeId===this.#id)??wrapperCandidates[0];return existingWrapper!=null&&(this.#id=existingWrapper.dataset.fileTreeId??this.#id),this.#wrapper=existingWrapper??document.createElement("div"),this.#wrapper.dataset.fileTreeId=this.#id,this.#wrapper.dataset.fileTreeVirtualizedWrapper="true",this.#syncIconSurface(host,this.#wrapper),this.#wrapper.parentNode!==shadowRoot&&shadowRoot.appendChild(this.#wrapper),this.#wrapper}#prepareHost(fileTreeContainer,parentNode){const host=fileTreeContainer??this.#fileTreeContainer??document.createElement("file-tree-container");parentNode!=null&&host.parentNode!==parentNode&&parentNode.appendChild(host);const shadowRoot=host.shadowRoot??host.attachShadow({mode:"open"});return prepareFileTreeShadowRoot(host,shadowRoot),this.#syncUnsafeCSS(shadowRoot),host.dataset.fileTreeVirtualized="true",host.style.display="flex",this.#applyDensityHostStyle(host),this.#slotHost.setHost(host),this.#fileTreeContainer=host,host}#applyDensityHostStyle(host){host.style.getPropertyValue("--trees-item-height")===""&&(host.style.setProperty("--trees-item-height",`${String(this.#density.itemHeight)}px`),this.#wroteHostItemHeight=!0),host.style.getPropertyValue("--trees-density-override")===""&&(host.style.setProperty("--trees-density-override",String(this.#density.factor)),this.#wroteHostDensityFactor=!0)}#removeOwnedDensityHostStyle(host){this.#wroteHostItemHeight&&(host.style.removeProperty("--trees-item-height"),this.#wroteHostItemHeight=!1),this.#wroteHostDensityFactor&&(host.style.removeProperty("--trees-density-override"),this.#wroteHostDensityFactor=!1)}};function FileTabPill({path,label,title,active,dirty=!1,readOnly=!1,lifted=!1,glyph,onPick,onClose,onMove,onContextMenu,className,style}){const labels=useLabels(),name=label??path.split("/").pop()??path;return jsxRuntimeExports.jsx(TabPill,{size:"sm",label:name,selected:active,lifted,title:title??(dirty?labels.fileUnsavedTitle(path):readOnly?labels.fileReadOnly(path):path),onSelect:onPick,keyShortcuts:onMove?"Alt+Shift+ArrowLeft Alt+Shift+ArrowRight":void 0,onKeyDown:e2=>{!onMove||!e2.altKey||!e2.shiftKey||e2.key!=="ArrowLeft"&&e2.key!=="ArrowRight"||(e2.preventDefault(),onMove(e2.key==="ArrowLeft"?-1:1))},onAuxClick:e2=>{e2.button===1&&onClose()},onContextMenu:e2=>{onContextMenu&&(e2.preventDefault(),onContextMenu({x:e2.clientX,y:e2.clientY}))},leading:glyph??jsxRuntimeExports.jsx(FileIcon,{path}),marker:dirty&&jsxRuntimeExports.jsx("span",{"aria-label":labels.fileUnsaved,className:"absolute right-2.5 top-1/2 -translate-y-1/2 w-2 h-2 rounded-full bg-[var(--zg-accent)] pointer-events-none group-hover:opacity-0"}),closeLabel:labels.closeTab(name),onClose,closeAlways:active&&!dirty,className,style})}const useClientLayoutEffect=typeof window>"u"?reactExports.useEffect:reactExports.useLayoutEffect;function renderFileTreeChildren(header,renderContextMenu,activeContextMenu){const headerChild=header!=null?jsxRuntimeExports.jsx("div",{slot:HEADER_SLOT_NAME,children:header}):null,contextMenuChild=renderContextMenu!=null&&activeContextMenu!=null?jsxRuntimeExports.jsx("div",{slot:CONTEXT_MENU_SLOT_NAME,children:renderContextMenu(activeContextMenu.item,activeContextMenu.context)}):null;return headerChild==null&&contextMenuChild==null?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[headerChild,contextMenuChild]})}function renderPreloadedShadowDom(children,preloadedData){return typeof window>"u"&&preloadedData!=null?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("template",{shadowrootmode:"open",dangerouslySetInnerHTML:{__html:preloadedData.shadowHtml}}),children]}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children})}function hasExistingPreloadedContent(host){const shadowRoot=host.shadowRoot;return shadowRoot?.querySelector("[data-file-tree-id]")instanceof HTMLElement||shadowRoot?.querySelector("[data-file-tree-id]")instanceof SVGElement?!0:host.querySelector('template[shadowrootmode="open"]')instanceof HTMLTemplateElement}function resolveComposition(baselineComposition,header,hasContextMenu,onClose,onOpen){const nextComposition={...baselineComposition??{}};if(header!=null&&delete nextComposition.header,hasContextMenu){const baselineContextMenu=baselineComposition?.contextMenu,baselineOnClose=baselineContextMenu?.onClose,baselineOnOpen=baselineContextMenu?.onOpen;nextComposition.contextMenu={...baselineContextMenu??{},enabled:!0,onClose:()=>{baselineOnClose?.(),onClose()},onOpen:(item,context)=>{onOpen(item,context),baselineOnOpen?.(item,context)}},delete nextComposition.contextMenu.render}return nextComposition.header!=null||nextComposition.contextMenu!=null?nextComposition:void 0}function FileTree$1({header,id,model,preloadedData,renderContextMenu,...hostProps}){const[activeContextMenu,setActiveContextMenu]=reactExports.useState(null),[hostElement,setHostElement]=reactExports.useState(null),baselineCompositionRef=reactExports.useRef(model.getComposition()),baselineModelRef=reactExports.useRef(model);baselineModelRef.current!==model&&(baselineModelRef.current=model,baselineCompositionRef.current=model.getComposition());const hasContextMenu=renderContextMenu!=null,handleContextMenuClose=reactExports.useCallback(()=>{setActiveContextMenu(null)},[]),handleContextMenuOpen=reactExports.useCallback((item,context)=>{setActiveContextMenu({context,item})},[]),baselineComposition=baselineCompositionRef.current,composition=reactExports.useMemo(()=>resolveComposition(baselineComposition,header,hasContextMenu,handleContextMenuClose,handleContextMenuOpen),[baselineComposition,handleContextMenuClose,handleContextMenuOpen,hasContextMenu,header]),handleHostRef=reactExports.useCallback(node=>{setHostElement(node)},[]);reactExports.useEffect(()=>{hasContextMenu||setActiveContextMenu(null)},[hasContextMenu]),useClientLayoutEffect(()=>{model.setComposition(composition)},[composition,model]),useClientLayoutEffect(()=>{if(hostElement!=null)return preloadedData!=null&&hasExistingPreloadedContent(hostElement)?model.hydrate({fileTreeContainer:hostElement}):model.render({fileTreeContainer:hostElement}),()=>{model.unmount(),model.setComposition(baselineComposition)}},[baselineComposition,hostElement,model,preloadedData]);const children=renderPreloadedShadowDom(renderFileTreeChildren(header,renderContextMenu,activeContextMenu),preloadedData),resolvedHostId=id??preloadedData?.id,mergedStyle={"--trees-item-height":`${String(model.getItemHeight())}px`,"--trees-density-override":model.getDensityFactor(),...hostProps.style};return jsxRuntimeExports.jsx(FILE_TREE_TAG_NAME,{...hostProps,id:resolvedHostId,ref:handleHostRef,style:mergedStyle,suppressHydrationWarning:preloadedData!=null,children})}function useFileTree(options){const[model]=reactExports.useState(()=>new FileTree$2(options)),cleanUpRef=reactExports.useRef({timeout:null,model});return reactExports.useEffect(()=>{const{current}=cleanUpRef;return current.timeout!=null&&(clearTimeout(current.timeout),current.timeout=null),()=>{current.timeout=setTimeout(()=>current.model.cleanUp(),1)}},[]),{model}}const TREE_PATH_MIME="application/x-zidane-tree-path";function FileTree2({controlRef,entries,gitStatus,selectedPath,onSelect,onOpen,onContextMenu,className,style,openPaths,label,editing,onExpandFolder}){const labels=useLabels(),paths=reactExports.useMemo(()=>entries.map(e2=>e2.path),[entries]),editingRef=reactExports.useRef(editing);editingRef.current=editing;const pathsRef=reactExports.useRef(paths);pathsRef.current=paths;const creating=reactExports.useRef(null),copyDrag=reactExports.useRef(!1),[externalDrag,setExternalDrag]=reactExports.useState(!1),revealNext=reactExports.useRef(null),[editable]=reactExports.useState(()=>editing!==void 0),decorated=reactExports.useMemo(()=>[...gitStatus,...entries.filter(e2=>e2.ignored).map(e2=>({path:e2.path.replace(/\/$/,""),status:"ignored"}))],[entries,gitStatus]),[expanded]=reactExports.useState(()=>ancestorDirs(openPaths??[])),{model}=useFileTree({paths,initialExpansion:"closed",initialExpandedPaths:expanded,density:"compact",icons:{set:"complete",colored:!0},gitStatus:decorated,unsafeCSS:TREES_UNSAFE_CSS,onSelectionChange:selected=>onSelect(selected[0]??null),...editable?{renaming:{onRename:({sourcePath,destinationPath,isFolder})=>{const kind=isFolder?"folder":"file",from=bare(sourcePath),to=bare(destinationPath),pending=creating.current;if(pending&&bare(pending.path)===from){creating.current=null,editingRef.current?.onCreate(to,pending.kind);return}editingRef.current?.onRename(from,to,kind)},onError:message=>{const pending=creating.current;pending&&(creating.current=null,model.remove(pending.path,pending.kind==="folder"?{recursive:!0}:void 0)),editingRef.current?.onError?.(message)}},dragAndDrop:{onDropComplete:({draggedPaths,target})=>{const toDir=target.kind==="root"||!target.directoryPath?"":bare(target.directoryPath),moved=draggedPaths.map(bare),copy=copyDrag.current;copyDrag.current=!1,copy&&model.resetPaths(pathsRef.current),editingRef.current?.onMove(moved,toDir,copy)}}}:{}}),lazyDirs=reactExports.useMemo(()=>entries.filter(e2=>e2.ignored&&e2.kind==="dir"&&e2.path.endsWith("/")).map(e2=>e2.path),[entries]),lazyRef=reactExports.useRef({dirs:lazyDirs,onExpandFolder});lazyRef.current={dirs:lazyDirs,onExpandFolder},reactExports.useEffect(()=>{const open=new Set;return model.subscribe(()=>{const{dirs,onExpandFolder:report}=lazyRef.current;if(report)for(const path of dirs){const item=model.getItem(path);item!==null&&"isExpanded"in item&&item.isExpanded()?open.has(path)||(open.add(path),report(bare(path))):open.delete(path)}})},[model]),reactExports.useEffect(()=>{if(editable)return model.onMutation("remove",event=>{creating.current&&"path"in event&&event.path===creating.current.path&&(creating.current=null)})},[model,editable]),reactExports.useEffect(()=>{if(editable)return model.subscribe(()=>{const pending=creating.current;pending&&requestAnimationFrame(()=>{creating.current!==pending||!model.getItem(pending.path)||model.getFileTreeContainer()?.shadowRoot?.querySelector('input[aria-label^="Rename"]')||(creating.current=null,editingRef.current?.onCreate(bare(pending.path),pending.kind))})})},[model,editable]);const revealPath=reactExports.useCallback(path=>{const item=model.getItem(path)??model.getItem(`${path}/`);if(!item)return!1;"expand"in item&&item.expand();for(const selected of model.getSelectedPaths())selected!==item.getPath()&&model.getItem(selected)?.deselect();return item.select(),model.scrollToPath(item.getPath(),{focus:!0}),!0},[model]);reactExports.useEffect(()=>{if(controlRef)return controlRef.current={revealSoon:path=>{revealNext.current=revealPath(path)?null:path},startCreate:(dir,kind,name)=>{if(!editable||creating.current)return!1;const base=dir?`${bare(dir)}/`:"";let leaf=name;for(let n2=2;model.getItem(`${base}${leaf}`)||model.getItem(`${base}${leaf}/`);n2++)leaf=`${name} ${n2}`;const path=`${base}${leaf}${kind==="folder"?"/":""}`;return base&&model.getItem(base)?.expand?.(),model.add(path),creating.current={path,kind},model.startRenaming(path,{removeIfCanceled:!0})?!0:(creating.current=null,model.remove(path,kind==="folder"?{recursive:!0}:void 0),!1)},startRename:path=>{if(!editable)return!1;const item=model.getItem(path)??model.getItem(`${path}/`);return item?model.startRenaming(item.getPath()):!1},resync:()=>model.resetPaths(pathsRef.current),setSearch:value=>model.setSearch(value&&value.length>0?value:null),reveal:revealPath},()=>{controlRef.current=null}},[controlRef,model,editable,revealPath]);const initial=reactExports.useRef(!0);reactExports.useEffect(()=>{if(initial.current){initial.current=!1;return}const pending=creating.current?.path;model.resetPaths(pending&&!paths.includes(pending)?[...paths,pending]:paths);const next=revealNext.current;revealNext.current=null,next&&revealPath(next)},[model,paths,revealPath]),reactExports.useEffect(()=>{model.setGitStatus(decorated)},[model,decorated]);const rowOf=e2=>e2.nativeEvent.composedPath().find(el=>el instanceof Element&&el.hasAttribute?.("data-item-path")),rowPath=e2=>rowOf(e2)?.getAttribute("data-item-path")??null,onClickCapture=e2=>{if(e2.shiftKey||e2.button!==0)return;const path=rowPath(e2);if(!path)return;!path.endsWith("/")&&entries.some(en=>en.path===path&&en.kind==="file")&&onOpen(path,{metaKey:e2.metaKey,ctrlKey:e2.ctrlKey})},onKeyDown=e2=>{e2.key==="Enter"&&selectedPath&&!selectedPath.endsWith("/")&&onOpen(selectedPath,{metaKey:e2.metaKey,ctrlKey:e2.ctrlKey})},dropDir=e2=>{const row=e2.nativeEvent.composedPath().find(el=>el instanceof Element&&el.hasAttribute?.("data-item-path")),path=row?.getAttribute("data-item-path")??"";if(!path)return"";if(row?.getAttribute("data-item-type")==="folder")return bare(path);const at=path.lastIndexOf("/");return at<0?"":path.slice(0,at)},fromOutside=e2=>editable&&!!editingRef.current?.onDropFiles&&Array.from(e2.dataTransfer?.types??[]).includes("Files");return jsxRuntimeExports.jsx(FileTree$1,{model,className,style:style?{...TREES_HOST_STYLE,...style}:TREES_HOST_STYLE,"aria-label":label??labels.fileTree,"data-zg-file-drop":externalDrag?"true":void 0,onDragStart:e2=>{const path=e2.dataTransfer.getData("text/plain");path&&!path.endsWith("/")&&e2.dataTransfer.setData(TREE_PATH_MIME,path),e2.dataTransfer.effectAllowed="copyMove"},onDragOverCapture:editable?e2=>{copyDrag.current=e2.altKey}:void 0,onDropCapture:editable?e2=>{copyDrag.current=e2.altKey}:void 0,onDragOver:e2=>{fromOutside(e2)&&(e2.preventDefault(),e2.dataTransfer.dropEffect="copy",externalDrag||setExternalDrag(!0))},onDragLeave:e2=>{externalDrag&&!(e2.relatedTarget instanceof Node&&e2.currentTarget.contains(e2.relatedTarget))&&setExternalDrag(!1)},onDrop:e2=>{fromOutside(e2)&&(e2.preventDefault(),setExternalDrag(!1),editingRef.current?.onDropFiles?.(dropDir(e2),e2.dataTransfer))},onClickCapture,onContextMenu:e2=>{const row=rowOf(e2),path=row?.getAttribute("data-item-path");if(!onContextMenu)return;if((!row||!path)&&editable){e2.preventDefault(),onContextMenu({path:"",kind:"folder"},{x:e2.clientX,y:e2.clientY});return}if(!row||!path)return;e2.preventDefault();const kind=row.getAttribute("data-item-type")==="folder"?"folder":"file";onContextMenu({path:path.replace(/\/$/,""),kind},{x:e2.clientX,y:e2.clientY})},onKeyDown})}function bare(path){return path.replace(/\/$/,"")}function ancestorDirs(paths){const dirs=new Set;for(const path of paths){const parts=path.split("/").filter(Boolean);for(let i2=1;i2<parts.length;i2++)dirs.add(`${parts.slice(0,i2).join("/")}/`)}return[...dirs]}const MAX_SHOWN=100,ROW_PX=22,VISIBLE_ROWS=10,RESOLVE_DELAY_MS=120,BUSY_RETRY_MS$1=1500,BUSY_RETRIES$1=40,SETTLE_MS=400,WORD=/[\p{L}\p{N}_$]/u,KIND_ICON={method:"i-ph-function text-[var(--zg-accent)]",function:"i-ph-function text-[var(--zg-accent)]",constructor:"i-ph-function text-[var(--zg-accent)]",field:"i-ph-tag-simple text-zg-info",property:"i-ph-tag-simple text-zg-info",variable:"i-ph-cube-transparent text-zg-info",value:"i-ph-cube-transparent text-zg-info",class:"i-ph-cube text-zg-warn",struct:"i-ph-cube text-zg-warn",interface:"i-ph-plugs text-zg-warn",enum:"i-ph-list-bullets text-zg-warn","enum-member":"i-ph-list-dashes text-zg-warn","type-parameter":"i-ph-text-t text-zg-warn",module:"i-ph-package text-[var(--zg-text-muted)]",constant:"i-ph-lock-simple text-zg-info",keyword:"i-ph-key text-[var(--zg-text-muted)]",snippet:"i-ph-brackets-curly text-[var(--zg-text-muted)]",file:"i-ph-file text-[var(--zg-text-muted)]",folder:"i-ph-folder text-[var(--zg-text-muted)]"},DEFAULT_ICON="i-ph-circle text-[var(--zg-text-muted)]";function matchWord(text,typed){if(!typed)return{rank:0,positions:[]};if(text.startsWith(typed))return{rank:3,positions:range(typed.length)};const lower=text.toLowerCase(),want=typed.toLowerCase();if(lower.startsWith(want))return{rank:2,positions:range(typed.length)};const positions=[];let boundaryHits=0,from=0;for(let k2=0;k2<want.length;k2++){let found=-1;for(let i2=from;i2<lower.length;i2++)if(lower[i2]===want[k2]&&isBoundary(text,i2)){found=i2,boundaryHits++;break}if(found===-1&&(k2===0||(found=lower.indexOf(want[k2],from),found===-1)))return null;positions.push(found),from=found+1}return{rank:boundaryHits===want.length?1:0,positions}}function isBoundary(text,i2){if(i2===0)return!0;const prev=text[i2-1],c2=text[i2];return!WORD.test(prev)||prev==="_"||prev==="$"?!0:c2!==c2.toLowerCase()&&prev===prev.toLowerCase()}function range(n2){return Array.from({length:n2},(_2,i2)=>i2)}function rankCompletions(items,typed){const out=[];return items.forEach((item,index)=>{const m2=matchWord(item.filterText??item.label,typed);m2&&out.push({item,index,rank:m2.rank,matches:item.filterText?[]:m2.positions})}),out.sort((a2,b2)=>{if(a2.rank!==b2.rank)return b2.rank-a2.rank;const sa=a2.item.sortText??a2.item.label,sb=b2.item.sortText??b2.item.label;return sa<sb?-1:sa>sb?1:a2.index-b2.index}),out.slice(0,MAX_SHOWN).map(({item,index,matches})=>({item,index,matches}))}function lineOf(text,line){let start=0;for(let n2=0;n2<line;n2++){const nl=text.indexOf(`
1099
+ }`}const measuredGutterCache=new WeakMap;function measureScrollbarGutter(shadowRoot){const cachedScrollbarGutter=measuredGutterCache.get(shadowRoot);if(cachedScrollbarGutter!=null)return cachedScrollbarGutter;const wrapper=document.createElement("div");wrapper.setAttribute(FILE_TREE_SCROLLBAR_MEASURE_ATTRIBUTE,"true");const child=document.createElement("div");child.style.position="relative",child.style.height="200%",wrapper.appendChild(child),shadowRoot.appendChild(wrapper);const measuredGutter=Math.max(wrapper.offsetWidth-wrapper.clientWidth,0);return wrapper.remove(),measuredGutterCache.set(shadowRoot,measuredGutter),measuredGutter}function ensureMeasuredScrollbarGutter(host,shadowRoot){if(!host.isConnected)return;const measuredScrollbarGutter=measureScrollbarGutter(shadowRoot);if(measuredScrollbarGutter==null)return;const existing=shadowRoot.querySelector(`style[${FILE_TREE_SCROLLBAR_GUTTER_STYLE_ATTRIBUTE}]`),styleEl=existing instanceof HTMLStyleElement?existing:document.createElement("style");existing instanceof HTMLStyleElement||(styleEl.setAttribute(FILE_TREE_SCROLLBAR_GUTTER_STYLE_ATTRIBUTE,""),shadowRoot.appendChild(styleEl)),styleEl.textContent=`:host { ${FILE_TREE_SCROLLBAR_GUTTER_MEASURED_PROPERTY}: ${measuredScrollbarGutter}px; }`}let sheet;function ensureFileTreeStyles(shadowRoot){if(typeof CSSStyleSheet<"u"&&typeof CSSStyleSheet.prototype.replaceSync=="function"&&"adoptedStyleSheets"in shadowRoot){sheet==null&&(sheet=new CSSStyleSheet,sheet.replaceSync(wrapCoreCSS(style_default)));let adopted=!1;try{shadowRoot.adoptedStyleSheets=[sheet],adopted=!0}catch{}if(adopted){shadowRoot.querySelector(`style[${FILE_TREE_STYLE_ATTRIBUTE}]`)?.remove();return}}if(shadowRoot.querySelector("style[data-file-tree-style]")==null){const styleEl=document.createElement("style");styleEl.setAttribute(FILE_TREE_STYLE_ATTRIBUTE,""),styleEl.textContent=wrapCoreCSS(style_default),shadowRoot.prepend(styleEl)}}function prepareFileTreeShadowRoot(host,shadowRoot){adoptDeclarativeShadowDom(host,shadowRoot),ensureFileTreeStyles(shadowRoot),ensureMeasuredScrollbarGutter(host,shadowRoot)}function adoptDeclarativeShadowDom(host,shadowRoot){const template=host.querySelector('template[shadowrootmode="open"], template[data-file-tree-shadowrootmode="open"]');template instanceof HTMLTemplateElement&&(shadowRoot.childNodes.length>0||(shadowRoot.appendChild(template.content.cloneNode(!0)),template.hasAttribute("shadowrootmode")&&template.remove()))}if(typeof HTMLElement<"u"&&customElements.get("file-tree-container")==null){class FileTreeContainer extends HTMLElement{constructor(){super()}connectedCallback(){const shadowRoot=this.shadowRoot??this.attachShadow({mode:"open"});prepareFileTreeShadowRoot(this,shadowRoot)}}if(customElements.define(FILE_TREE_TAG_NAME,FileTreeContainer),typeof document<"u")for(const el of Array.from(document.querySelectorAll(FILE_TREE_TAG_NAME)))el instanceof HTMLElement&&prepareFileTreeShadowRoot(el,el.shadowRoot??el.attachShadow({mode:"open"}))}const getSelectionPath=path=>path.startsWith("f::")?path.slice(3):path;function splitPath(path){const separatorIndex=path.lastIndexOf("/");return separatorIndex<0?{parentPath:"",baseName:path}:{parentPath:path.slice(0,separatorIndex),baseName:path.slice(separatorIndex+1)}}function joinPath(parentPath,baseName){return parentPath===""?baseName:`${parentPath}/${baseName}`}function renameFileTreePaths({files,path,isFolder,nextBasename}){const sourcePath=getSelectionPath(path),trimmedBasename=nextBasename.trim();if(trimmedBasename.length===0)return{error:"Name cannot be empty."};if(trimmedBasename.includes("/"))return{error:'Name cannot include "/".'};const{parentPath,baseName}=splitPath(sourcePath);if(trimmedBasename===baseName)return{nextFiles:files,sourcePath,destinationPath:sourcePath,isFolder};const destinationPath=joinPath(parentPath,trimmedBasename),nextFiles=new Array(files.length),seenPaths=new Set;if(!isFolder){const destinationPrefix2=`${destinationPath}/`;let renamed=!1;for(let index=0;index<files.length;index++){const file=files[index];if(file!==sourcePath&&file.startsWith(destinationPrefix2))return{error:`"${destinationPath}" already exists.`};const nextFile=file===sourcePath?destinationPath:file;if(seenPaths.has(nextFile))return{error:`"${destinationPath}" already exists.`};seenPaths.add(nextFile),nextFiles[index]=nextFile,file===sourcePath&&(renamed=!0)}return renamed?{nextFiles,sourcePath,destinationPath,isFolder}:{error:"Could not find the selected file to rename."}}const sourcePrefix=`${sourcePath}/`,destinationPrefix=`${destinationPath}/`;let renamedPathCount=0;for(let index=0;index<files.length;index++){const file=files[index],isWithinRenamedFolder=file===sourcePath||file.startsWith(sourcePrefix);if(!isWithinRenamedFolder&&(file===destinationPath||file.startsWith(destinationPrefix)))return{error:`"${destinationPath}" already exists.`};const nextFile=isWithinRenamedFolder?`${destinationPath}${file.slice(sourcePath.length)}`:file;if(seenPaths.has(nextFile))return{error:`"${destinationPath}" already exists.`};seenPaths.add(nextFile),nextFiles[index]=nextFile,isWithinRenamedFolder&&renamedPathCount++}return renamedPathCount===0?{error:"Could not find the selected folder to rename."}:{nextFiles,sourcePath,destinationPath,isFolder}}function isCanonicalDirectoryPath$1(path){return path.endsWith("/")}function getPathBasename(path){const trimmedPath=path.endsWith("/")?path.slice(0,-1):path,lastSlashIndex=trimmedPath.lastIndexOf("/"),basename=lastSlashIndex<0?trimmedPath:trimmedPath.slice(lastSlashIndex+1);return path.endsWith("/")?`${basename}/`:basename}function normalizeDraggedPaths(paths){const uniquePaths=[],seenPaths=new Set;for(const path of paths)seenPaths.has(path)||(seenPaths.add(path),uniquePaths.push(path));const keptPaths=new Set;for(const path of uniquePaths.toSorted((left,right)=>left.length!==right.length?left.length-right.length:left.localeCompare(right))){const segments=(path.endsWith("/")?path.slice(0,-1):path).split("/");let hasSelectedAncestor=!1;for(let index=0;index<segments.length-1;index+=1){const ancestorPath=`${segments.slice(0,index+1).join("/")}/`;if(keptPaths.has(ancestorPath)){hasSelectedAncestor=!0;break}}hasSelectedAncestor||keptPaths.add(path)}return uniquePaths.filter(path=>keptPaths.has(path))}function resolveDraggedPathsForStart(path,selectedPaths){return selectedPaths.includes(path)?normalizeDraggedPaths(selectedPaths):[path]}function dropTargetsEqual(left,right){return left===right?!0:left==null||right==null?!1:left.kind===right.kind&&left.directoryPath===right.directoryPath&&left.flattenedSegmentPath===right.flattenedSegmentPath&&left.hoveredPath===right.hoveredPath}function createDropContext(draggedPaths,target){return{draggedPaths,target}}function isSelfOrDescendantDrop(draggedPaths,target){if(target.kind!=="directory"||target.directoryPath==null)return!1;for(const draggedPath of draggedPaths)if(isCanonicalDirectoryPath$1(draggedPath)&&(target.directoryPath===draggedPath||target.directoryPath.startsWith(draggedPath)))return!0;return!1}function resolveMoveDestinationPath(sourcePath,target){return target.kind==="root"||target.directoryPath==null?getPathBasename(sourcePath):target.directoryPath}function buildDropOperations(draggedPaths,target){const operations=draggedPaths.map(draggedPath=>{const destinationPath=resolveMoveDestinationPath(draggedPath,target);return destinationPath===draggedPath?null:{from:draggedPath,to:destinationPath,type:"move"}}).filter(operation=>operation!=null);return operations.length===0?null:{operations,result:{draggedPaths,operation:operations.length===1?"move":"batch",target}}}function haveMatchingPaths(currentPaths,preparedPaths){if(currentPaths===preparedPaths)return!0;if(currentPaths.length!==preparedPaths.length)return!1;for(let index=0;index<currentPaths.length;index+=1)if(currentPaths[index]!==preparedPaths[index])return!1;return!0}function resolveFileTreeInput(options,context,sort){const{paths,preparedInput}=options;if(preparedInput==null){if(paths==null)throw new Error("FileTree requires paths or preparedInput");return{paths,preparedInput:void 0}}const preparedPaths=preparedInput.paths;if(paths==null)return{paths:preparedPaths,preparedInput};if(!haveMatchingPaths(PathStore.preparePaths(paths,sort==null?{}:{sort}),preparedPaths))throw new Error(`FileTree ${context} received paths and preparedInput for different path lists`);return{paths:preparedPaths,preparedInput}}function isPathMutationEvent(event){return event.operation==="add"||event.operation==="remove"||event.operation==="move"||event.operation==="batch"}function remapMovedPath(path,fromPath,toPath){if(path===fromPath)return toPath;const descendantPrefix=fromPath.endsWith("/")?fromPath:`${fromPath}/`;return path.startsWith(descendantPrefix)?`${toPath.endsWith("/")?toPath:`${toPath}/`}${path.slice(descendantPrefix.length)}`:path}function isPathRemoved(path,removedPath){if(path===removedPath)return!0;const descendantPrefix=removedPath.endsWith("/")?removedPath:`${removedPath}/`;return path.startsWith(descendantPrefix)}function remapPathThroughMutation(path,event,preserveRemovedPath=!1){if(path==null)return null;switch(event.operation){case"add":case"expand":case"collapse":case"mark-directory-unloaded":case"begin-child-load":case"apply-child-patch":case"complete-child-load":case"fail-child-load":case"cleanup":return path;case"remove":return isPathRemoved(path,event.path)?preserveRemovedPath?path:null:path;case"move":return remapMovedPath(path,event.from,event.to);case"batch":{let nextPath=path;for(const childEvent of event.events)if(nextPath=remapPathThroughMutation(nextPath,childEvent,preserveRemovedPath),nextPath==null)return null;return nextPath}}}function createMutationInvalidation(event){return{canonicalChanged:event.canonicalChanged,projectionChanged:event.projectionChanged,visibleCountDelta:event.visibleCountDelta}}function toTreesMutationSemanticEvent(event){switch(event.operation){case"add":return{...createMutationInvalidation(event),operation:"add",path:event.path};case"remove":return{...createMutationInvalidation(event),operation:"remove",path:event.path,recursive:event.recursive};case"move":return{...createMutationInvalidation(event),from:event.from,operation:"move",to:event.to}}}function toTreesBatchEvent(event){return{...createMutationInvalidation(event),events:event.events.filter(childEvent=>childEvent.operation==="add"||childEvent.operation==="remove"||childEvent.operation==="move").map(childEvent=>toTreesMutationSemanticEvent(childEvent)),operation:"batch"}}function toTreesMutationEvent(event){switch(event.operation){case"add":case"remove":case"move":return toTreesMutationSemanticEvent(event);case"batch":return toTreesBatchEvent(event);default:return null}}function arePathSetsEqual(currentPaths,nextPaths){if(currentPaths.size!==nextPaths.length)return!1;for(const path of nextPaths)if(!currentPaths.has(path))return!1;return!0}function getAncestorDirectoryPaths$1(path){const normalizedPath=path.endsWith("/")?path.slice(0,-1):path;if(normalizedPath.length===0)return[];const segments=normalizedPath.split("/");return segments.slice(0,-1).map((_2,index)=>`${segments.slice(0,index+1).join("/")}/`)}function getImmediateParentPath(path){return getAncestorDirectoryPaths$1(path).at(-1)??null}function getSiblingComparisonKey(path,parentPath){return parentPath==null?path:path.startsWith(parentPath)?path.slice(parentPath.length):path}function isCanonicalDirectoryPath(path){return path.endsWith("/")}const toLowerCaseSearchPath=path=>path.toLowerCase();function getRenameLeafName(path){const normalizedPath=path.endsWith("/")?path.slice(0,-1):path,separatorIndex=normalizedPath.lastIndexOf("/");return separatorIndex<0?normalizedPath:normalizedPath.slice(separatorIndex+1)}function toRenameHelperPath(path){return path.endsWith("/")?path.slice(0,-1):path}function toCanonicalRenamePath(path,isFolder){return isFolder&&!path.endsWith("/")?`${path}/`:path}const normalizeSearchQuery=value=>{const trimmedValue=value.trim();return trimmedValue.length===0?"":(trimmedValue.includes("\\")?trimmedValue.replaceAll("\\","/"):trimmedValue).toLowerCase()},FILE_TREE_RENAME_VIEW=Symbol("FILE_TREE_RENAME_VIEW"),INITIAL_PROJECTION_ROW_LIMIT=512,CONTEXT_VISIBLE_ROW_RANGE_LIMIT=512;function normalizeScrollOffset(offset){return offset==="top"||offset==="center"?offset:"nearest"}function resolveFocusedIndexByLookup(rowCount,getVisibleIndex,candidatePath){if(rowCount===0)return-1;if(candidatePath!=null){const directIndex=getVisibleIndex(candidatePath);if(directIndex!=null)return directIndex;const ancestorPaths=getAncestorDirectoryPaths$1(candidatePath);for(let index=ancestorPaths.length-1;index>=0;index-=1){const ancestorPath=ancestorPaths[index];if(ancestorPath==null)continue;const ancestorIndex=getVisibleIndex(ancestorPath);if(ancestorIndex!=null)return ancestorIndex}}return 0}function createVisibleProjection(projection,focusedPathCandidate,resolveVisibleIndexByPath){if(projection.paths.length===0)return{focusedIndex:-1,getParentIndex:projection.getParentIndex,paths:projection.paths,posInSetByIndex:projection.posInSetByIndex,setSizeByIndex:projection.setSizeByIndex};if(focusedPathCandidate==null)return{focusedIndex:0,getParentIndex:projection.getParentIndex,paths:projection.paths,posInSetByIndex:projection.posInSetByIndex,setSizeByIndex:projection.setSizeByIndex};const getVisibleIndex=resolveVisibleIndexByPath??(path=>projection.visibleIndexByPath.get(path)??null);return{focusedIndex:resolveFocusedIndexByLookup(projection.paths.length,getVisibleIndex,focusedPathCandidate),getParentIndex:projection.getParentIndex,paths:projection.paths,posInSetByIndex:projection.posInSetByIndex,setSizeByIndex:projection.setSizeByIndex}}var FileTreeController=class FileTreeController2{static{Object.defineProperty(FileTreeController2.prototype,FILE_TREE_RENAME_VIEW,{configurable:!0,value(){return{cancel:()=>{this.#cancelRenaming()},commit:()=>{this.#completeRenaming()},getPath:()=>this.#renamingPath,getValue:()=>this.#renamingValue,isActive:()=>this.#renamingPath!=null,setValue:value=>{this.#setRenamingValue(value)}}},writable:!0})}#baseOptions;#listeners=new Set;#mutationListeners=new Map;#dragAndDropConfig=null;#dragSession=null;#ancestorIndicesByIndex=new Map;#ancestorPathsByIndex=new Map;#focusedIndex=-1;#focusedPath=null;#hasFullProjection=!1;#getParentIndexForVisibleRow=_index=>-1;#itemHandles=new Map;#knownDirectoryPaths=null;#knownDirectoryPathsLowerCase=null;#knownPaths=null;#listedPaths=null;#listedPathsLowerCase=null;#onRename;#onRenameError;#onSearchChange;#projectionPaths=[];#projectionPosInSetByIndex=new Int32Array(0);#projectionSetSizeByIndex=new Int32Array(0);#renameCanRename=void 0;#renameEnabled=!1;#renamingPath=null;#renamingValue="";#removeRenamingPathIfCanceled=!1;#searchMatchPathSet=new Set;#searchMatchingPaths=[];#searchMode;#searchPreviousExpandedPaths=null;#searchValue=null;#searchVisiblePathSet=null;#searchVisibleIndexByPath=null;#searchVisibleIndices=null;#searchVisiblePaths=null;#scrollRequest=null;#scrollRequestId=0;#selectionAnchorPath=null;#selectedPaths=new Set;#selectionVersion=0;#store;#storeVisibleCount=0;#suppressStoreNotifications=!1;#visibleCount=0;#unsubscribe;constructor(options){const{dragAndDrop,fileTreeSearchMode,initialSearchQuery,initialSelectedPaths,renaming,onSearchChange,paths,preparedInput,...baseOptions}=options,resolvedInput=resolveFileTreeInput({paths,preparedInput},"constructor",baseOptions.sort);this.#baseOptions=baseOptions,dragAndDrop!=null&&dragAndDrop!==!1&&(this.#dragAndDropConfig=dragAndDrop===!0?{}:dragAndDrop),this.#renameEnabled=renaming!=null&&renaming!==!1,renaming!=null&&renaming!==!1&&renaming!==!0&&(this.#renameCanRename=renaming.canRename,this.#onRenameError=renaming.onError,this.#onRename=renaming.onRename),this.#onSearchChange=onSearchChange,this.#searchMode=fileTreeSearchMode??"hide-non-matches",this.#store=this.#createStore(resolvedInput.paths,resolvedInput.preparedInput);const resolvedInitialSelectedPaths=initialSelectedPaths?.map(path=>this.#resolveSelectionPath(path)).filter(resolved=>resolved!=null)??[],initialFocusedPath=resolvedInitialSelectedPaths.at(-1)??null;resolvedInitialSelectedPaths.length>0&&(this.#selectedPaths=new Set(resolvedInitialSelectedPaths),this.#selectionAnchorPath=initialFocusedPath,this.#selectionVersion=1),this.#rebuildVisibleProjection(initialFocusedPath,!1),initialSearchQuery!=null&&this.#setSearchState(initialSearchQuery,!1),this.#unsubscribe=this.#subscribe()}destroy(){this.#unsubscribe?.(),this.#unsubscribe=null,this.#mutationListeners.clear(),this.#listeners.clear(),this.#itemHandles.clear(),this.#dragSession=null,this.#invalidateKnownPathCaches()}focusFirstItem(){this.#getCurrentVisiblePaths().length>0&&this.#setFocusedIndex(0)}focusLastItem(){this.#visibleCount<=0||(this.#ensureFullProjection(),this.#setFocusedIndex(this.#visibleCount-1))}focusNextItem(){this.#moveFocus(1)}focusParentItem(){if(this.#focusedPath==null)return;const parentPath=getImmediateParentPath(this.#focusedPath);if(parentPath==null)return;const nextFocusedIndex=this.#resolveFocusedIndex(parentPath);nextFocusedIndex>=0&&this.#setFocusedIndex(nextFocusedIndex)}focusPath(path){const resolvedPath=this.#store.getPathInfo(path)?.path??null;if(resolvedPath==null)return;this.#ensureFullProjection();const nextFocusedIndex=this.#resolveFocusedIndex(resolvedPath);nextFocusedIndex>=0&&this.#setFocusedIndex(nextFocusedIndex)}scrollToPath(path,options){const resolvedPath=this.#store.getPathInfo(path)?.path??null;if(resolvedPath==null)return;this.#ensureFullProjection();const targetIndex=this.#getExactCurrentVisibleIndexByPath(resolvedPath);targetIndex<0||this.#resolveVisiblePathAtIndex(targetIndex)!=null&&(options?.focus!==!1&&this.#setFocusedIndex(targetIndex,!1),this.#scrollRequest={id:this.#scrollRequestId+=1,offset:normalizeScrollOffset(options?.offset),visibleIndex:targetIndex},this.#emit())}focusMountedPathFromInput(path){const resolvedPath=this.#store.getPathInfo(path)?.path??null;if(resolvedPath==null)return;const nextFocusedIndex=this.#resolveFocusedIndex(resolvedPath);nextFocusedIndex>=0&&this.#setFocusedIndex(nextFocusedIndex)}focusNearestPath(path){const nextPath=this.resolveNearestVisiblePath(path);if(nextPath==null)return null;const nextFocusedIndex=this.#resolveFocusedIndex(nextPath);return nextFocusedIndex>=0?(this.#setFocusedIndex(nextFocusedIndex),this.#getCurrentVisiblePaths()[nextFocusedIndex]??nextPath):null}focusPreviousItem(){this.#moveFocus(-1)}getFocusedIndex(){return this.#focusedIndex}getFocusedItem(){return this.#focusedPath==null?null:this.#getOrCreateItemHandle(this.#focusedPath)}getFocusedPath(){return this.#focusedPath}getScrollRequest(){return this.#scrollRequest}clearScrollRequest(id){this.#scrollRequest?.id===id&&(this.#scrollRequest=null)}resolveNearestVisiblePath(path){const currentVisiblePaths=this.#getCurrentVisiblePaths();if(this.#visibleCount===0)return null;if(path==null)return this.#focusedPath??currentVisiblePaths[0]??null;const resolvedPath=this.#store.getPathInfo(path)?.path??path,directIndex=this.#resolveFocusedIndex(resolvedPath);if(directIndex>=0)return currentVisiblePaths[directIndex]??resolvedPath;const siblingPath=this.#findNearestVisibleSiblingPath(resolvedPath);return siblingPath??this.#focusedPath??currentVisiblePaths[0]??null}getSelectedPaths(){return[...this.#selectedPaths]}getSelectionVersion(){return this.#selectionVersion}getVisibleCount(){return this.#visibleCount}getVisibleRows(start,end){if(end<start||this.#visibleCount===0)return[];const boundedStart=Math.max(0,start),boundedEnd=Math.min(this.#visibleCount-1,end);if(boundedEnd<boundedStart)return[];const boundedLength=boundedEnd-boundedStart+1;if(this.#searchVisibleIndices==null&&!this.#hasFullProjection&&boundedEnd>=this.#projectionPaths.length&&boundedLength<=CONTEXT_VISIBLE_ROW_RANGE_LIMIT){const rows=[];for(let index=boundedStart;index<=boundedEnd;index+=1){const context=this.#store.getVisibleRowContext(index);if(context==null)break;rows.push(this.#createVisibleRowFromContext(context))}return rows}if(!this.#hasFullProjection&&boundedEnd>=this.#projectionPaths.length&&this.#ensureFullProjection(),this.#searchVisibleIndices!=null){const projectionIndices=Array.from({length:boundedEnd-boundedStart+1},(_2,visibleOffset)=>this.#getProjectionIndexFromVisibleIndex(boundedStart+visibleOffset)),visibleRowByProjectionIndex=new Map;let runStartIndex=projectionIndices[0]??-1,runEndIndex=runStartIndex;for(let index=1;index<=projectionIndices.length;index+=1){const projectionIndex=projectionIndices[index];if(projectionIndex!=null&&projectionIndex===runEndIndex+1){runEndIndex=projectionIndex;continue}if(runStartIndex>=0&&this.#store.getVisibleSlice(runStartIndex,runEndIndex).forEach((row,offset)=>{visibleRowByProjectionIndex.set(runStartIndex+offset,row)}),projectionIndex==null){runStartIndex=-1,runEndIndex=-1;continue}runStartIndex=projectionIndex,runEndIndex=projectionIndex}return Array.from({length:boundedEnd-boundedStart+1},(_2,visibleOffset)=>{const visibleIndex=boundedStart+visibleOffset,projectionIndex=this.#getProjectionIndexFromVisibleIndex(visibleIndex),row=visibleRowByProjectionIndex.get(projectionIndex),projectionPath=this.#projectionPaths[projectionIndex];if(row==null||projectionPath==null)throw new Error(`Missing projection row for filtered visible index ${String(visibleIndex)}`);return this.#createVisibleRow(row,visibleIndex,projectionIndex,{ancestorPaths:this.#getAncestorPaths(projectionIndex),path:projectionPath})})}return this.#store.getVisibleSlice(boundedStart,boundedEnd).map((row,offset)=>{const index=boundedStart+offset,projectionPath=this.#projectionPaths[index];if(projectionPath==null)throw new Error(`Missing projection path for visible index ${String(index)}`);return this.#createVisibleRow(row,index,index,{ancestorPaths:this.#getAncestorPaths(index),path:projectionPath})})}getStickyRowCandidates(scrollTop,itemHeight){if(this.#searchVisibleIndices!=null)return null;if(this.#visibleCount===0||scrollTop<=0||itemHeight<=0)return[];const stickyRows=[];for(let slotDepth=0;slotDepth<this.#visibleCount;slotDepth+=1){const slotTop=scrollTop+slotDepth*itemHeight,thresholdIndex=Math.min(this.#visibleCount-1,Math.floor(slotTop/itemHeight)),candidateContext=this.#getStickyCandidateContextAt(thresholdIndex,slotDepth)??(thresholdIndex>0?this.#getStickyCandidateContextAt(thresholdIndex-1,slotDepth):void 0);if(candidateContext==null)break;stickyRows.push({row:this.#createVisibleRowFromContext(candidateContext),subtreeEndIndex:candidateContext.subtreeEndIndex})}return stickyRows}getItem(path){const itemInfo=this.#store.getPathInfo(path);return itemInfo==null?null:this.#getOrCreateItemHandle(itemInfo.path,itemInfo)}resolveMountedDirectoryPathFromInput(path){const pathInfo=this.#store.getPathInfo(path);return pathInfo?.kind==="directory"?pathInfo.path:null}toggleMountedDirectoryFromInput(path){const directoryPath=this.resolveMountedDirectoryPathFromInput(path);directoryPath!=null&&this.#toggleDirectory(directoryPath)}selectAllVisiblePaths(){this.#ensureFullProjection();const nextSelectedPaths=[...this.#getCurrentVisiblePaths()];this.#applySelection(nextSelectedPaths,this.#focusedPath??this.#selectionAnchorPath)}selectOnlyPath(path){const resolvedPath=this.#resolveSelectionPath(path);resolvedPath!=null&&this.#applySelection([resolvedPath],resolvedPath)}selectOnlyMountedPathFromInput(path){this.#applySelection([path],path)}selectPath(path){const resolvedPath=this.#resolveSelectionPath(path);resolvedPath==null||this.#selectedPaths.has(resolvedPath)||this.#applySelection([...this.#selectedPaths,resolvedPath])}deselectPath(path){const resolvedPath=this.#resolveSelectionPath(path);resolvedPath==null||!this.#selectedPaths.has(resolvedPath)||this.#applySelection([...this.#selectedPaths].filter(selectedPath=>selectedPath!==resolvedPath))}toggleFocusedSelection(){this.#focusedPath!=null&&this.togglePathSelectionFromInput(this.#focusedPath)}togglePathSelection(path){const resolvedPath=this.#resolveSelectionPath(path);if(resolvedPath!=null){if(this.#selectedPaths.has(resolvedPath)){this.deselectPath(resolvedPath);return}this.selectPath(resolvedPath)}}togglePathSelectionFromInput(path){const resolvedPath=this.#resolveSelectionPath(path);if(resolvedPath!=null){if(this.#selectedPaths.has(resolvedPath)){this.#applySelection([...this.#selectedPaths].filter(selectedPath=>selectedPath!==resolvedPath),resolvedPath);return}this.#applySelection([...this.#selectedPaths,resolvedPath],resolvedPath)}}selectPathRange(path,unionSelection){const resolvedPath=this.#resolveSelectionPath(path);if(resolvedPath==null)return;this.#ensureFullProjection();const anchorPath=this.#selectionAnchorPath,anchorIndex=anchorPath==null?-1:this.#getVisibleIndexByPath(anchorPath),targetIndex=this.#getVisibleIndexByPath(resolvedPath);if(anchorIndex===-1||targetIndex===-1){const nextSelectedPaths2=unionSelection?[...this.#selectedPaths,resolvedPath]:[resolvedPath];this.#applySelection(nextSelectedPaths2,resolvedPath);return}const[startIndex,endIndex]=anchorIndex<=targetIndex?[anchorIndex,targetIndex]:[targetIndex,anchorIndex],rangePaths=this.#getCurrentVisiblePaths().slice(startIndex,endIndex+1),nextSelectedPaths=unionSelection?[...this.#selectedPaths,...rangePaths]:rangePaths;this.#applySelection(nextSelectedPaths,anchorPath)}extendSelectionFromFocused(offset){if(this.#focusedPath==null)return;const focusedIndex=this.#focusedIndex;if(focusedIndex===-1)return;const nextIndex=Math.min(this.#visibleCount-1,Math.max(0,focusedIndex+offset));if(nextIndex===focusedIndex)return;!this.#hasFullProjection&&nextIndex>=this.#projectionPaths.length&&this.#ensureFullProjection();const visiblePaths=this.#getCurrentVisiblePaths(),currentPath=visiblePaths[focusedIndex]??null,nextPath=visiblePaths[nextIndex]??null;if(currentPath==null||nextPath==null)return;const nextSelectedPaths=new Set(this.#selectedPaths);nextSelectedPaths.has(currentPath)&&nextSelectedPaths.has(nextPath)?nextSelectedPaths.delete(currentPath):nextSelectedPaths.add(nextPath),this.#applySelection([...nextSelectedPaths],this.#selectionAnchorPath??currentPath,!1),this.#setFocusedIndex(nextIndex)}getDragAndDropConfig(){return this.#dragAndDropConfig}isDragAndDropEnabled(){return this.#dragAndDropConfig!=null}getDragSession(){return this.#dragSession==null?null:{draggedPaths:[...this.#dragSession.draggedPaths],primaryPath:this.#dragSession.primaryPath,target:this.#dragSession.target==null?null:{...this.#dragSession.target}}}startDrag(path){if(this.#dragAndDropConfig==null)return!1;const resolvedPath=this.#resolveSelectionPath(path);if(resolvedPath==null||this.#searchValue!=null&&this.#searchValue.length>0)return!1;const selectedPaths=this.getSelectedPaths(),draggedPaths=resolveDraggedPathsForStart(resolvedPath,selectedPaths);return this.#dragAndDropConfig.canDrag?.(draggedPaths)===!1?!1:(selectedPaths.includes(resolvedPath)||this.#applySelection([resolvedPath],resolvedPath,!1),this.#focusPathWithoutEmit(resolvedPath),this.#dragSession={draggedPaths,primaryPath:resolvedPath,target:null},this.#emit(),!0)}setDragTarget(target){const dragSession=this.#dragSession;if(dragSession==null)return;let nextTarget=target;if(nextTarget!=null){const context=createDropContext(dragSession.draggedPaths,nextTarget);(isSelfOrDescendantDrop(dragSession.draggedPaths,nextTarget)||this.#dragAndDropConfig?.canDrop?.(context)===!1)&&(nextTarget=null)}dropTargetsEqual(dragSession.target,nextTarget)||(this.#dragSession={...dragSession,target:nextTarget},this.#emit())}cancelDrag(){this.#dragSession!=null&&(this.#dragSession=null,this.#emit())}completeDrag(){const dragSession=this.#dragSession;if(dragSession==null)return!1;this.#dragSession=null;const target=dragSession.target==null?null:{...dragSession.target};if(target==null)return this.#emit(),!1;const dropContext=createDropContext(dragSession.draggedPaths,target);if(isSelfOrDescendantDrop(dragSession.draggedPaths,target)||this.#dragAndDropConfig?.canDrop?.(dropContext)===!1)return this.#emit(),!1;const dropPlan=buildDropOperations(dragSession.draggedPaths,target);if(dropPlan==null)return this.#emit(),!1;try{if(dropPlan.operations.length===1){const singleOperation=dropPlan.operations[0];if(singleOperation==null||singleOperation.type!=="move")throw new Error("Expected a single move operation for one-item drops");this.#store.move(singleOperation.from,singleOperation.to,{collision:singleOperation.collision})}else this.#validateBatchDropOperations(dropPlan.operations),this.#store.batch(dropPlan.operations)}catch(error){return this.#emit(),this.#dragAndDropConfig?.onDropError?.(error instanceof Error?error.message:String(error),dropContext),!1}return this.#dragAndDropConfig?.onDropComplete?.(dropPlan.result),!0}subscribe(listener){return this.#listeners.add(listener),listener(),()=>{this.#listeners.delete(listener)}}add(path){this.#store.add(path)}remove(path,options={}){this.#store.remove(path,options)}move(fromPath,toPath,options={}){this.#store.move(fromPath,toPath,options)}batch(operations){this.#store.batch(operations)}onMutation(type,handler){const key2=type,typedHandler=handler;let listenersForType=this.#mutationListeners.get(key2);return listenersForType==null&&(listenersForType=new Set,this.#mutationListeners.set(key2,listenersForType)),listenersForType.add(typedHandler),()=>{const registeredListeners=this.#mutationListeners.get(key2);registeredListeners?.delete(typedHandler),registeredListeners?.size===0&&this.#mutationListeners.delete(key2)}}setSearch(value){this.#setSearchState(value,!0)}openSearch(initialValue=""){this.#setSearchState(initialValue,!0)}closeSearch(){this.#setSearchState(null,!0)}isSearchOpen(){return this.#searchValue!==null}getSearchValue(){return this.#searchValue??""}getSearchMatchingPaths(){return this.#searchMatchingPaths}focusNextSearchMatch(){this.#focusRelativeSearchMatch(1)}focusPreviousSearchMatch(){this.#focusRelativeSearchMatch(-1)}startRenaming(path=this.#focusedPath??"",options={}){if(!this.#renameEnabled)return!1;const itemInfo=this.#store.getPathInfo(path);if(itemInfo==null)return!1;const canonicalPath=itemInfo.path,isFolder=isCanonicalDirectoryPath(canonicalPath),publicPath=toRenameHelperPath(canonicalPath);if(this.#renameCanRename?.({isFolder,path:publicPath})===!1)return!1;for(const ancestorPath of getAncestorDirectoryPaths$1(canonicalPath))this.#store.isExpanded(ancestorPath)||this.#store.expand(ancestorPath);return this.#applySelection([canonicalPath],canonicalPath,!1),this.#searchValue!=null&&(this.#setSearchState(null,!1),this.#onSearchChange?.(this.#searchValue)),this.#focusPathWithoutEmit(canonicalPath),this.#renamingPath=canonicalPath,this.#renamingValue=getRenameLeafName(canonicalPath),this.#removeRenamingPathIfCanceled=options.removeIfCanceled??!1,this.#emit(),!0}#cancelRenaming(){if(this.#renamingPath==null)return;const renamingPath=this.#renamingPath,removePlaceholderEntry=this.#removeRenamingPathIfCanceled;if(this.#renamingPath=null,this.#renamingValue="",this.#removeRenamingPathIfCanceled=!1,removePlaceholderEntry){this.remove(renamingPath,isCanonicalDirectoryPath(renamingPath)?{recursive:!0}:void 0);return}this.#focusPathWithoutEmit(renamingPath),this.#emit()}#completeRenaming(){const renamingPath=this.#renamingPath;if(renamingPath==null)return;if(this.#removeRenamingPathIfCanceled&&this.#renamingValue.trim().length===0){this.#renamingPath=null,this.#renamingValue="",this.#removeRenamingPathIfCanceled=!1,this.remove(renamingPath,isCanonicalDirectoryPath(renamingPath)?{recursive:!0}:void 0);return}const isFolder=isCanonicalDirectoryPath(renamingPath),result=renameFileTreePaths({files:this.#store.list(),isFolder,nextBasename:this.#renamingValue,path:toRenameHelperPath(renamingPath)});if(this.#renamingPath=null,this.#renamingValue="",this.#removeRenamingPathIfCanceled=!1,"error"in result){this.#focusPathWithoutEmit(renamingPath),this.#onRenameError?.(result.error),this.#emit();return}if(result.sourcePath===result.destinationPath){this.#focusPathWithoutEmit(renamingPath),this.#emit();return}this.#onRename?.({destinationPath:result.destinationPath,isFolder:result.isFolder,sourcePath:result.sourcePath}),this.move(toCanonicalRenamePath(result.sourcePath,isFolder),toCanonicalRenamePath(result.destinationPath,isFolder))}#setRenamingValue(value){this.#renamingPath==null||this.#renamingValue===value||(this.#renamingValue=value,this.#emit())}resetPaths(pathsOrOptions,maybeOptions={}){const usingPreparedOnlyOverload=!Array.isArray(pathsOrOptions),paths=usingPreparedOnlyOverload?void 0:pathsOrOptions,options=usingPreparedOnlyOverload?pathsOrOptions:maybeOptions,previousPathCount=this.#store.list().length,previousVisibleCount=this.#visibleCount,resolvedInput=resolveFileTreeInput({paths,preparedInput:options.preparedInput},"resetPaths",this.#baseOptions.sort),nextStore=this.#createStore(resolvedInput.paths,resolvedInput.preparedInput,options.initialExpandedPaths),previousFocusedPath=this.#focusedPath,previousRenamingPath=this.#renamingPath,previousSelectedPaths=this.getSelectedPaths(),previousSelectionAnchorPath=this.#selectionAnchorPath;this.#unsubscribe?.(),this.#store=nextStore,this.#itemHandles.clear(),this.#invalidateKnownPathCaches();const nextSelectedPaths=previousSelectedPaths.map(selectedPath=>nextStore.getPathInfo(selectedPath)?.path??null).filter(resolved=>resolved!=null),selectionChanged=!arePathSetsEqual(this.#selectedPaths,nextSelectedPaths);this.#selectedPaths=new Set(nextSelectedPaths),selectionChanged&&(this.#selectionVersion+=1),this.#selectionAnchorPath=previousSelectionAnchorPath==null?null:nextStore.getPathInfo(previousSelectionAnchorPath)?.path??null,this.#renamingPath=previousRenamingPath==null?null:nextStore.getPathInfo(previousRenamingPath)?.path??null,this.#renamingPath==null&&(this.#renamingValue="",this.#removeRenamingPathIfCanceled=!1),this.#rebuildVisibleProjection(previousFocusedPath,previousFocusedPath!=null||nextSelectedPaths.length>0||this.#selectionAnchorPath!=null),this.#unsubscribe=this.#subscribe(),this.#emit(),this.#emitMutation({canonicalChanged:!0,operation:"reset",pathCountAfter:resolvedInput.paths.length,pathCountBefore:previousPathCount,projectionChanged:!0,usedPreparedInput:options.preparedInput!=null,visibleCountDelta:this.#visibleCount-previousVisibleCount})}#findNearestVisibleSiblingPath(path){this.#ensureFullProjection();const parentPath=getImmediateParentPath(path),candidateKey=getSiblingComparisonKey(path,parentPath);let previousSiblingPath=null,nextSiblingPath=null;for(const siblingPath of this.#getCurrentVisiblePaths()){if(getImmediateParentPath(siblingPath)!==parentPath)continue;const siblingKey=getSiblingComparisonKey(siblingPath,parentPath);if(siblingKey<candidateKey){previousSiblingPath=siblingPath;continue}if(siblingKey>candidateKey){nextSiblingPath=siblingPath;break}}return previousSiblingPath??nextSiblingPath}#resolveFocusedIndex(path){const directIndex=this.#getVisibleIndexByPath(path);if(directIndex!==-1)return directIndex;const ancestorPaths=getAncestorDirectoryPaths$1(path);for(let index=ancestorPaths.length-1;index>=0;index-=1){const ancestorPath=ancestorPaths[index];if(ancestorPath==null)continue;const ancestorIndex=this.#getVisibleIndexByPath(ancestorPath);if(ancestorIndex!==-1)return ancestorIndex}return this.#getCurrentVisiblePaths().length>0?0:-1}#getOrCreateItemHandle(path,itemInfo){const cachedHandle=this.#itemHandles.get(path);if(cachedHandle!=null)return cachedHandle;const resolvedItemInfo=itemInfo??this.#store.getPathInfo(path);if(resolvedItemInfo==null)return null;const handle=resolvedItemInfo.kind==="directory"?this.#createDirectoryHandle(resolvedItemInfo.path):this.#createFileHandle(resolvedItemInfo.path);return this.#itemHandles.set(resolvedItemInfo.path,handle),handle}#createVisibleRow(row,visibleIndex,projectionIndex,projection){return{ancestorPaths:projection.ancestorPaths,depth:row.depth,flattenedSegments:row.flattenedSegments?.map(segment=>({isTerminal:segment.isTerminal,name:segment.name,path:segment.path})),hasChildren:row.hasChildren,index:visibleIndex,isExpanded:row.isExpanded,isFlattened:row.isFlattened,isFocused:projection.path===this.#focusedPath,isSelected:this.#selectedPaths.has(projection.path),kind:row.kind,level:row.depth,name:row.name,path:projection.path,posInSet:projection.posInSet??this.#projectionPosInSetByIndex[projectionIndex]??0,setSize:projection.setSize??this.#projectionSetSizeByIndex[projectionIndex]??0}}#createVisibleRowFromContext(context){return this.#createVisibleRow(context.row,context.index,context.index,{ancestorPaths:context.ancestorPaths,path:context.row.path,posInSet:context.posInSet,setSize:context.setSize})}#getStickyCandidateContextAt(index,slotDepth){const context=this.#store.getVisibleRowContext(index);if(context==null)return;const ancestorRow=context.ancestorRows[slotDepth];return ancestorRow??(slotDepth===context.ancestorRows.length&&context.row.kind==="directory"&&context.row.isExpanded?context:void 0)}#getAncestorIndices(index){const cached=this.#ancestorIndicesByIndex.get(index);if(cached!=null)return cached;const parentIndex=this.#getParentIndexForVisibleRow(index),ancestorIndices=parentIndex<0?[]:[...this.#getAncestorIndices(parentIndex),parentIndex];return this.#ancestorIndicesByIndex.set(index,ancestorIndices),ancestorIndices}#getAncestorPaths(index){const cached=this.#ancestorPathsByIndex.get(index);if(cached!=null)return cached;const ancestorPaths=this.#getAncestorIndices(index).map(ancestorIndex=>this.#projectionPaths[ancestorIndex]??"").filter(path=>path!=="");return this.#ancestorPathsByIndex.set(index,ancestorPaths),ancestorPaths}#collapseDirectory(path){this.#store.collapse(path)}#applySelection(nextSelectedPaths,nextAnchorPath=this.#selectionAnchorPath,emit=!0){const uniqueSelectedPaths=[...new Set(nextSelectedPaths)],selectionChanged=!arePathSetsEqual(this.#selectedPaths,uniqueSelectedPaths),anchorChanged=this.#selectionAnchorPath!==nextAnchorPath;!selectionChanged&&!anchorChanged||(this.#selectedPaths=new Set(uniqueSelectedPaths),this.#selectionAnchorPath=nextAnchorPath,selectionChanged&&(this.#selectionVersion+=1),emit&&this.#emit())}#createDirectoryHandle(path){return{collapse:()=>{this.#collapseDirectory(path)},deselect:()=>{this.deselectPath(path)},expand:()=>{this.#expandDirectory(path)},focus:()=>{this.focusPath(path)},getPath:()=>path,isDirectory:()=>!0,isExpanded:()=>this.#store.isExpanded(path),isFocused:()=>this.#focusedPath===path,isSelected:()=>this.#selectedPaths.has(path),select:()=>{this.selectPath(path)},toggleSelect:()=>{this.togglePathSelection(path)},toggle:()=>{this.#toggleDirectory(path)}}}#createFileHandle(path){return{deselect:()=>{this.deselectPath(path)},focus:()=>{this.focusPath(path)},getPath:()=>path,isDirectory:()=>!1,isFocused:()=>this.#focusedPath===path,isSelected:()=>this.#selectedPaths.has(path),select:()=>{this.selectPath(path)},toggleSelect:()=>{this.togglePathSelection(path)}}}#validateBatchDropOperations(operations){const currentPaths=this.#store.list();this.#createStore(currentPaths).batch(operations)}#createStore(paths,preparedInput,initialExpandedPathsOverride){return new PathStore({...this.#baseOptions,paths,preparedInput:preparedInput??void 0,...initialExpandedPathsOverride!==void 0?{initialExpandedPaths:initialExpandedPathsOverride}:{}})}#getListedPaths(){return this.#listedPaths!=null?this.#listedPaths:(this.#listedPaths=this.#store.list(),this.#listedPaths)}#getAllKnownPaths(){if(this.#knownPaths!=null)return this.#knownPaths;const knownPaths=new Set;for(const path of this.#getListedPaths()){knownPaths.add(path);for(const ancestorPath of getAncestorDirectoryPaths$1(path))knownPaths.add(ancestorPath)}return this.#knownPaths=[...knownPaths].sort(),this.#knownPaths}#getListedPathsLowerCase(){return this.#listedPathsLowerCase!=null?this.#listedPathsLowerCase:(this.#listedPathsLowerCase=this.#getListedPaths().map(toLowerCaseSearchPath),this.#listedPathsLowerCase)}#getAllKnownDirectoryPaths(){return this.#knownDirectoryPaths!=null?this.#knownDirectoryPaths:(this.#knownDirectoryPaths=this.#getAllKnownPaths().filter(path=>path.endsWith("/")),this.#knownDirectoryPaths)}#getAllKnownDirectoryPathsLowerCase(){return this.#knownDirectoryPathsLowerCase!=null?this.#knownDirectoryPathsLowerCase:(this.#knownDirectoryPathsLowerCase=this.#getAllKnownDirectoryPaths().map(toLowerCaseSearchPath),this.#knownDirectoryPathsLowerCase)}#invalidateKnownPathCaches(){this.#knownDirectoryPaths=null,this.#knownDirectoryPathsLowerCase=null,this.#knownPaths=null,this.#listedPaths=null,this.#listedPathsLowerCase=null}#getExpandedDirectoryPaths(){return this.#getAllKnownDirectoryPaths().filter(path=>this.#store.isExpanded(path))}#restoreSearchExpandedPaths(keepSelectedOpen){const expandedPaths=new Set(this.#searchPreviousExpandedPaths??[]);if(keepSelectedOpen)for(const selectedPath of this.#selectedPaths)for(const ancestorPath of getAncestorDirectoryPaths$1(selectedPath))expandedPaths.add(ancestorPath);this.#setExpandedPaths(expandedPaths)}#setExpandedPaths(expandedPaths){this.#suppressStoreNotifications=!0;try{for(const directoryPath of this.#getAllKnownDirectoryPaths()){const shouldExpand=expandedPaths.has(directoryPath),isExpanded=this.#store.isExpanded(directoryPath);shouldExpand&&!isExpanded?this.#store.expand(directoryPath):!shouldExpand&&isExpanded&&this.#store.collapse(directoryPath)}}finally{this.#suppressStoreNotifications=!1}}#syncSearchVisibilityState(){if(this.#searchValue==null||this.#searchValue.length===0){this.#searchMatchingPaths=[],this.#searchVisibleIndices=null,this.#searchVisiblePaths=null,this.#searchVisibleIndexByPath=null,this.#visibleCount=this.#storeVisibleCount;return}const currentVisiblePaths=this.#projectionPaths;if(this.#searchMatchingPaths=currentVisiblePaths.filter(path=>this.#searchMatchPathSet.has(path)),this.#searchMode!=="hide-non-matches"||this.#searchMatchPathSet.size===0){this.#searchVisibleIndices=null,this.#searchVisiblePaths=null,this.#searchVisibleIndexByPath=null,this.#visibleCount=this.#storeVisibleCount;return}const visibleIndices=[],visiblePaths=[],visibleIndexByPath=new Map;for(const[index,path]of currentVisiblePaths.entries())this.#searchVisiblePathSet?.has(path)===!0&&(visibleIndexByPath.set(path,visiblePaths.length),visibleIndices.push(index),visiblePaths.push(path));this.#searchVisibleIndices=visibleIndices,this.#searchVisiblePaths=visiblePaths,this.#searchVisibleIndexByPath=visibleIndexByPath,this.#visibleCount=visiblePaths.length}#getCurrentVisiblePaths(){return this.#searchVisiblePaths??this.#projectionPaths}#getExactCurrentVisibleIndexByPath(path){return this.#searchVisiblePaths!=null?this.#searchVisibleIndexByPath?.get(path)??-1:this.#store.getVisibleIndex(path)??-1}#getProjectionIndexFromVisibleIndex(index){return this.#searchVisibleIndices?.[index]??index}#getVisibleIndexByPath(path){const searchIndex=this.#searchVisibleIndexByPath?.get(path);return searchIndex??this.#store.getVisibleIndex(path)??-1}#focusRelativeSearchMatch(direction){const matchPaths=this.#searchMatchingPaths;if(matchPaths.length===0)return;const focusedPath=this.#focusedPath,currentIndex=focusedPath==null?-1:matchPaths.indexOf(focusedPath),nextPath=matchPaths[currentIndex<0?direction>0?0:matchPaths.length-1:Math.min(matchPaths.length-1,Math.max(0,currentIndex+direction))];nextPath!=null&&this.focusPath(nextPath)}#setSearchState(value,emitChange){const normalizedValue=value==null?null:normalizeSearchQuery(value),previousSearch=this.#searchValue;if(previousSearch!==normalizedValue){if(previousSearch==null&&normalizedValue!=null&&(this.#searchPreviousExpandedPaths=this.#getExpandedDirectoryPaths()),this.#searchValue=normalizedValue,normalizedValue==null)this.#restoreSearchExpandedPaths(!0),this.#searchPreviousExpandedPaths=null,this.#searchMatchPathSet.clear(),this.#searchVisiblePathSet=null,this.#rebuildVisibleProjection(this.#focusedPath,!0);else if(normalizedValue.length===0)this.#restoreSearchExpandedPaths(!1),this.#searchMatchPathSet.clear(),this.#searchVisiblePathSet=null,this.#rebuildVisibleProjection(this.#focusedPath,!0);else{const focusCandidate=this.#refreshActiveSearchState();this.#rebuildVisibleProjection(focusCandidate,!0)}emitChange&&(this.#onSearchChange?.(this.#searchValue),this.#emit())}}#refreshActiveSearchState(){if(this.#searchValue==null||this.#searchValue.length===0)return this.#searchMatchPathSet.clear(),this.#focusedPath;const searchValue=this.#searchValue,listedPaths=this.#getListedPaths(),listedPathsLowerCase=this.#getListedPathsLowerCase(),matchingPaths=[],matchingPathSet=new Set;let focusCandidate=null;for(let index=0;index<listedPaths.length;index+=1){if(!listedPathsLowerCase[index].includes(searchValue))continue;const path=listedPaths[index];matchingPaths.push(path),matchingPathSet.add(path),focusCandidate??=path}const knownDirectoryPaths=this.#getAllKnownDirectoryPaths(),knownDirectoryPathsLowerCase=this.#getAllKnownDirectoryPathsLowerCase();for(let index=0;index<knownDirectoryPaths.length;index+=1){if(!knownDirectoryPathsLowerCase[index].includes(searchValue))continue;const path=knownDirectoryPaths[index];matchingPathSet.has(path)||(matchingPaths.push(path),matchingPathSet.add(path),focusCandidate??=path)}this.#searchMatchPathSet=matchingPathSet;const searchVisiblePathSet=this.#searchMode==="hide-non-matches"&&matchingPaths.length>0?new Set:null;this.#searchVisiblePathSet=searchVisiblePathSet;const expandedPaths=this.#searchMode==="expand-matches"?new Set(this.#searchPreviousExpandedPaths??[]):new Set;for(const matchingPath of matchingPaths){searchVisiblePathSet?.add(matchingPath),matchingPath.endsWith("/")&&expandedPaths.add(matchingPath);for(const ancestorPath of getAncestorDirectoryPaths$1(matchingPath))expandedPaths.add(ancestorPath),searchVisiblePathSet?.add(ancestorPath)}return this.#setExpandedPaths(expandedPaths),focusCandidate??this.#focusedPath}#emit(){for(const listener of this.#listeners)listener()}#emitMutation(event){this.#mutationListeners.get(event.operation)?.forEach(listener=>{listener(event)}),this.#mutationListeners.get("*")?.forEach(listener=>{listener(event)})}#expandDirectory(path){for(const ancestorPath of getAncestorDirectoryPaths$1(path))this.#store.isExpanded(ancestorPath)||this.#store.expand(ancestorPath);this.#store.isExpanded(path)||this.#store.expand(path)}#moveFocus(offset){const itemCount=this.#visibleCount;if(itemCount===0)return;const currentIndex=this.#focusedIndex===-1?0:this.#focusedIndex,nextIndex=Math.min(itemCount-1,Math.max(0,currentIndex+offset));(nextIndex!==currentIndex||this.#focusedIndex===-1)&&(!this.#hasFullProjection&&this.#searchVisibleIndices==null&&nextIndex>=this.#projectionPaths.length&&this.#ensureFullProjection(),this.#setFocusedIndex(nextIndex))}#rebuildVisibleProjection(focusedPathCandidate,full=!0){const rawVisibleCount=this.#store.getVisibleCount();this.#storeVisibleCount=rawVisibleCount;const projection=createVisibleProjection(this.#store.getVisibleTreeProjectionData(full?void 0:Math.min(rawVisibleCount,INITIAL_PROJECTION_ROW_LIMIT)),focusedPathCandidate,full?path=>this.#store.getVisibleIndex(path):void 0);this.#ancestorIndicesByIndex.clear(),this.#ancestorPathsByIndex.clear(),this.#hasFullProjection=projection.paths.length>=rawVisibleCount,this.#getParentIndexForVisibleRow=projection.getParentIndex,this.#projectionPaths=projection.paths,this.#projectionPosInSetByIndex=projection.posInSetByIndex,this.#projectionSetSizeByIndex=projection.setSizeByIndex,this.#syncSearchVisibilityState(),this.#focusedIndex=focusedPathCandidate==null?this.#getCurrentVisiblePaths().length>0?0:-1:this.#resolveFocusedIndex(focusedPathCandidate),this.#focusedPath=this.#focusedIndex<0?null:this.#resolveVisiblePathAtIndex(this.#focusedIndex)}#resolveVisiblePathAtIndex(index){const projectedPath=this.#getCurrentVisiblePaths()[index];return projectedPath??(this.#searchVisibleIndices!=null?null:this.#store.getVisibleRowContext(index)?.row.path??null)}#resolveSelectionPath(path){return this.#store.getPathInfo(path)?.path??null}#focusPathWithoutEmit(path){if(path==null)return;const nextFocusedIndex=this.#resolveFocusedIndex(path);nextFocusedIndex>=0&&this.#setFocusedIndex(nextFocusedIndex,!1)}#setFocusedIndex(index,emit=!0){const nextPath=this.#resolveVisiblePathAtIndex(index);nextPath!=null&&(this.#focusedIndex===index&&this.#focusedPath===nextPath||(this.#focusedIndex=index,this.#focusedPath=nextPath,emit&&this.#emit()))}#ensureFullProjection(){this.#hasFullProjection||this.#rebuildVisibleProjection(this.#focusedPath,!0)}#applyMutationState(event){const nextRenamingPath=remapPathThroughMutation(this.#renamingPath,event);nextRenamingPath==null&&this.#renamingPath!=null&&(this.#renamingValue=""),this.#renamingPath=nextRenamingPath;const nextFocusedPath=remapPathThroughMutation(this.#focusedPath,event,!0),nextSelectedPaths=[...this.#selectedPaths].map(selectedPath=>remapPathThroughMutation(selectedPath,event)).filter(resolvedPath=>resolvedPath!=null).map(resolvedPath=>this.#store.getPathInfo(resolvedPath)?.path??null).filter(resolvedPath=>resolvedPath!=null),nextSelectionAnchorPath=remapPathThroughMutation(this.#selectionAnchorPath,event),canonicalAnchorPath=nextSelectionAnchorPath==null?null:this.#store.getPathInfo(nextSelectionAnchorPath)?.path??null,uniqueNextSelectedPaths=[...new Set(nextSelectedPaths)];return arePathSetsEqual(this.#selectedPaths,uniqueNextSelectedPaths)||(this.#selectedPaths=new Set(uniqueNextSelectedPaths),this.#selectionVersion+=1),this.#selectionAnchorPath=canonicalAnchorPath,nextFocusedPath}#subscribe(){return this.#store.on("*",event=>{if(this.#suppressStoreNotifications)return;event.canonicalChanged&&(this.#itemHandles.clear(),this.#invalidateKnownPathCaches()),this.#dragSession!=null&&isPathMutationEvent(event)&&(this.#dragSession=null);const focusPathCandidate=isPathMutationEvent(event)?this.#applyMutationState(event):this.#focusedPath,searchFocusCandidate=this.#searchValue!=null&&this.#searchValue.length>0?this.#refreshActiveSearchState():this.#searchValue===""?this.#focusedPath:focusPathCandidate,shouldBuildFullProjection=this.#searchValue!=null||event.operation!=="expand"&&event.operation!=="collapse";this.#rebuildVisibleProjection(searchFocusCandidate,shouldBuildFullProjection),this.#emit();const mutationEvent=toTreesMutationEvent(event);mutationEvent!=null&&this.#emitMutation(mutationEvent)})}#toggleDirectory(path){if(this.#store.isExpanded(path)){this.#collapseDirectory(path);return}this.#expandDirectory(path)}};const getGitStatusSignature=entries=>{if(entries==null||entries.length===0)return"0";let signature=`${entries.length}`;for(const entry of entries)signature+=`\0${entry.path}\0${entry.status}`;return signature};function normalizeInputPath(inputPath){const isDirectory=inputPath.endsWith("/");let normalizedPath="",segmentStart=-1;for(let i2=0;i2<=inputPath.length;i2+=1){if(!(inputPath[i2]==="/"||i2===inputPath.length)){segmentStart===-1&&(segmentStart=i2);continue}segmentStart!==-1&&(normalizedPath!==""&&(normalizedPath+="/"),normalizedPath+=inputPath.slice(segmentStart,i2),segmentStart=-1)}return normalizedPath===""?null:{isDirectory,path:normalizedPath}}function getAncestorDirectoryPaths(path){const normalizedPath=path.endsWith("/")?path.slice(0,-1):path;if(normalizedPath.length===0)return[];const ancestors=[];let searchIndex=0;for(;;){const slashIndex=normalizedPath.indexOf("/",searchIndex);if(slashIndex===-1)break;ancestors.push(normalizedPath.slice(0,slashIndex+1)),searchIndex=slashIndex+1}return ancestors}function getCanonicalGitStatusPath(path,isDirectory){return isDirectory?`${path}/`:path}function resolveFileTreeGitStatusState(entries,previous=null){const signature=getGitStatusSignature(entries==null?void 0:[...entries]);if(signature==="0")return null;if(previous?.signature===signature)return previous;const statusByPath=new Map,directoriesWithChanges=new Set,ignoredDirectoryPaths=new Set,changeCountByDirectoryPath=new Map;for(const entry of entries??[]){const resolved=resolveGitStatusEntry(entry);resolved!=null&&setGitStatusPath({canonicalPath:resolved.canonicalPath,changeCountByDirectoryPath,directoriesWithChanges,ignoredDirectoryPaths,isDirectory:resolved.isDirectory,status:entry.status,statusByPath})}return statusByPath.size===0?null:{changeCountByDirectoryPath,directoriesWithChanges,ignoredDirectoryPaths,signature,statusByPath}}function applyFileTreeGitStatusPatch(previous,patch){const removeEntries=patch?.remove??[],setEntries=patch?.set??[];if(removeEntries.length===0&&setEntries.length===0)return previous;const statusByPath=new Map(previous?.statusByPath),directoriesWithChanges=new Set(previous?.directoriesWithChanges),ignoredDirectoryPaths=new Set(previous?.ignoredDirectoryPaths),changeCountByDirectoryPath=new Map(previous?.changeCountByDirectoryPath);let changed=!1;for(const path of removeEntries){const resolved=resolveGitStatusPath(path);resolved!=null&&(changed=removeGitStatusPath({canonicalPath:resolved.canonicalPath,changeCountByDirectoryPath,directoriesWithChanges,ignoredDirectoryPaths,statusByPath})||changed)}for(const entry of setEntries){const resolved=resolveGitStatusEntry(entry);resolved!=null&&(changed=setGitStatusPath({canonicalPath:resolved.canonicalPath,changeCountByDirectoryPath,directoriesWithChanges,ignoredDirectoryPaths,isDirectory:resolved.isDirectory,status:entry.status,statusByPath})||changed)}return changed?statusByPath.size===0?null:{changeCountByDirectoryPath,directoriesWithChanges,ignoredDirectoryPaths,signature:getGitStatusStateSignature(statusByPath),statusByPath}:previous}function resolveGitStatusEntry(entry){return resolveGitStatusPath(entry.path)}function resolveGitStatusPath(path){const normalizedPath=normalizeInputPath(path);if(normalizedPath!=null)return{canonicalPath:getCanonicalGitStatusPath(normalizedPath.path,normalizedPath.isDirectory),isDirectory:normalizedPath.isDirectory}}function removeGitStatusPath({canonicalPath,changeCountByDirectoryPath,directoriesWithChanges,ignoredDirectoryPaths,statusByPath}){const previousStatus=statusByPath.get(canonicalPath);return previousStatus==null?!1:(statusByPath.delete(canonicalPath),previousStatus==="ignored"&&canonicalPath.endsWith("/")&&ignoredDirectoryPaths.delete(canonicalPath),decrementAncestorChangeCounts(changeCountByDirectoryPath,directoriesWithChanges,canonicalPath),!0)}function setGitStatusPath({canonicalPath,changeCountByDirectoryPath,directoriesWithChanges,ignoredDirectoryPaths,isDirectory,status,statusByPath}){const previousStatus=statusByPath.get(canonicalPath);return previousStatus===status?!1:(previousStatus==null&&incrementAncestorChangeCounts(changeCountByDirectoryPath,directoriesWithChanges,canonicalPath),statusByPath.set(canonicalPath,status),status==="ignored"&&isDirectory?ignoredDirectoryPaths.add(canonicalPath):isDirectory&&ignoredDirectoryPaths.delete(canonicalPath),!0)}function incrementAncestorChangeCounts(changeCountByDirectoryPath,directoriesWithChanges,path){for(const ancestorPath of getAncestorDirectoryPaths(path))changeCountByDirectoryPath.set(ancestorPath,(changeCountByDirectoryPath.get(ancestorPath)??0)+1),directoriesWithChanges.add(ancestorPath)}function decrementAncestorChangeCounts(changeCountByDirectoryPath,directoriesWithChanges,path){for(const ancestorPath of getAncestorDirectoryPaths(path)){const nextCount=(changeCountByDirectoryPath.get(ancestorPath)??0)-1;nextCount>0?changeCountByDirectoryPath.set(ancestorPath,nextCount):(changeCountByDirectoryPath.delete(ancestorPath),directoriesWithChanges.delete(ancestorPath))}}function getGitStatusStateSignature(statusByPath){let signature=`${statusByPath.size}`;for(const[path,status]of statusByPath)signature+=`\0${path}\0${status}`;return signature}var n,l$1,t$1,i$1,r$1,f$1,e$1,o$2,c$1,s$1,h$1={},p$1=[],v$1=Array.isArray,y$1=p$1.slice,w$1=Object.assign;function d$1(n2){n2&&n2.parentNode&&n2.remove()}function _$1(n2,l2,u2){var t2,i2,r2,f2={};for(r2 in l2)r2=="key"?t2=l2[r2]:r2=="ref"&&typeof n2!="function"?i2=l2[r2]:f2[r2]=l2[r2];return arguments.length>2&&(f2.children=arguments.length>3?y$1.call(arguments,2):u2),g$1(n2,f2,t2,i2,null)}function g$1(u2,t2,i2,r2,f2){var e2={type:u2,props:t2,key:i2,ref:r2,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:f2??++l$1,__i:-1,__u:0};return f2==null&&n.vnode!=null&&n.vnode(e2),e2}function k$1(n2){return n2.children}function m$1(n2,l2){this.props=n2,this.context=l2,this.__g=0}function M(n2,l2){if(l2==null)return n2.__?M(n2.__,n2.__i+1):null;for(var u2;l2<n2.__k.length;l2++)if((u2=n2.__k[l2])!=null&&u2.__e!=null)return u2.__e;return typeof n2.type=="function"?M(n2):null}function S(n2){var l2,u2;if((n2=n2.__)!=null&&n2.__c!=null){for(n2.__e=null,l2=0;l2<n2.__k.length;l2++)if((u2=n2.__k[l2])!=null&&u2.__e!=null){n2.__e=u2.__e;break}return S(n2)}}function $(l2){(8&l2.__g||!(l2.__g|=8)||!t$1.push(l2)||r$1++)&&i$1==n.debounceRendering||((i$1=n.debounceRendering)||queueMicrotask)(x)}function x(){for(var l2,u2,i2,e2,o2,c2,s2,a2,h2=1;t$1.length;)t$1.length>h2&&t$1.sort(f$1),l2=t$1.shift(),h2=t$1.length,8&l2.__g&&(i2=void 0,o2=(e2=(u2=l2).__v).__e,c2=[],s2=[],(a2=u2.__P)&&((i2=w$1({},e2)).__v=e2.__v+1,n.vnode&&n.vnode(i2),q$1(a2,i2,e2,u2.__n,a2.namespaceURI,32&e2.__u?[o2]:null,c2,o2??M(e2),!!(32&e2.__u),s2,a2.ownerDocument),i2.__v=e2.__v,i2.__.__k[i2.__i]=i2,P(c2,i2,s2),i2.__e!=o2&&S(i2)));r$1=0}function C$1(n2,l2,u2,t2,i2,r2,f2,e2,o2,c2,s2,a2){var v2,y2,w2,d2,_2,g2,b2,k2=t2&&t2.__k||p$1,m2=l2.length;for(o2=j(u2,l2,k2,o2,m2),v2=0;v2<m2;v2++)(w2=u2.__k[v2])!=null&&(y2=w2.__i==-1?h$1:k2[w2.__i]||h$1,w2.__i=v2,g2=q$1(n2,w2,y2,i2,r2,f2,e2,o2,c2,s2,a2),d2=w2.__e,w2.ref&&y2.ref!=w2.ref&&(y2.ref&&B$1(y2.ref,null,w2),s2.push(w2.ref,w2.__c||d2,w2)),_2==null&&d2!=null&&(_2=d2),(b2=!!(4&w2.__u))||y2.__k===w2.__k?o2=A$1(w2,o2,n2,b2):typeof w2.type=="function"&&g2!==void 0?o2=g2:d2&&(o2=d2.nextSibling),w2.__u&=-7);return u2.__e=_2,o2}function j(n2,l2,u2,t2,i2){var r2,f2,e2,o2,c2,s2=u2.length,a2=s2,h2=0;for(n2.__k=new Array(i2),r2=0;r2<i2;r2++)(f2=l2[r2])!=null&&typeof f2!="boolean"&&typeof f2!="function"?(o2=r2+h2,(f2=n2.__k[r2]=typeof f2=="string"||typeof f2=="number"||typeof f2=="bigint"||f2.constructor==String?g$1(null,f2,null,null,null):v$1(f2)?g$1(k$1,{children:f2},null,null,null):f2.constructor==null&&f2.__b>0?g$1(f2.type,f2.props,f2.key,f2.ref?f2.ref:null,f2.__v):f2).__=n2,f2.__b=n2.__b+1,e2=null,(c2=f2.__i=I(f2,u2,o2,a2))!=-1&&(a2--,(e2=u2[c2])&&(e2.__u|=2)),e2==null||e2.__v==null?(c2==-1&&(i2>s2?h2--:i2<s2&&h2++),typeof f2.type!="function"&&(f2.__u|=4)):c2!=o2&&(c2==o2-1?h2--:c2==o2+1?h2++:(c2>o2?h2--:h2++,f2.__u|=4))):n2.__k[r2]=null;if(a2)for(r2=0;r2<s2;r2++)(e2=u2[r2])!=null&&(2&e2.__u)==0&&(e2.__e==t2&&(t2=M(e2)),D$1(e2,e2));return t2}function A$1(n2,l2,u2,t2){var i2,r2;if(typeof n2.type=="function"){for(i2=n2.__k,r2=0;i2&&r2<i2.length;r2++)i2[r2]&&(i2[r2].__=n2,l2=A$1(i2[r2],l2,u2,t2));return l2}n2.__e!=l2&&(t2&&(l2&&n2.type&&!l2.parentNode&&(l2=M(n2)),u2.insertBefore(n2.__e,l2||null)),l2=n2.__e);do l2=l2&&l2.nextSibling;while(l2!=null&&l2.nodeType==8);return l2}function I(n2,l2,u2,t2){var i2,r2,f2,e2=n2.key,o2=n2.type,c2=l2[u2],s2=c2!=null&&(2&c2.__u)==0;if(c2===null&&n2.key==null||s2&&e2==c2.key&&o2==c2.type)return u2;if(t2>(s2?1:0)){for(i2=u2-1,r2=u2+1;i2>=0||r2<l2.length;)if((c2=l2[f2=i2>=0?i2--:r2++])!=null&&(2&c2.__u)==0&&e2==c2.key&&o2==c2.type)return f2}return-1}function L(n2,l2,u2){l2[0]=="-"?n2.setProperty(l2,u2??""):n2[l2]=u2??""}function O(n2,l2,u2,t2,i2){var r2;n:if(l2=="style")if(typeof u2=="string")n2.style.cssText=u2;else{if(typeof t2=="string"&&(n2.style.cssText=t2=""),t2)for(l2 in t2)u2&&l2 in u2||L(n2.style,l2,"");if(u2)for(l2 in u2)t2&&u2[l2]==t2[l2]||L(n2.style,l2,u2[l2])}else if(l2[0]=="o"&&l2[1]=="n")r2=l2!=(l2=l2.replace(e$1,"$1")),(l2=l2.slice(2))[0].toLowerCase()!=l2[0]&&(l2=l2.toLowerCase()),n2.__l||(n2.__l={}),n2.__l[l2+r2]=u2,u2?t2?u2.l=t2.l:(u2.l=o$2,n2.addEventListener(l2,r2?s$1:c$1,r2)):n2.removeEventListener(l2,r2?s$1:c$1,r2);else{if(i2=="http://www.w3.org/2000/svg")l2=l2.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(l2!="width"&&l2!="height"&&l2!="href"&&l2!="list"&&l2!="form"&&l2!="tabIndex"&&l2!="download"&&l2!="rowSpan"&&l2!="colSpan"&&l2!="role"&&l2!="popover"&&l2 in n2)try{n2[l2]=u2??"";break n}catch{}typeof u2=="function"||(u2==null||u2===!1&&l2[4]!="-"?n2.removeAttribute(l2):n2.setAttribute(l2,l2=="popover"&&u2==1?"":u2))}}function T(l2){return function(u2){if(this.__l){var t2=this.__l[u2.type+l2];if(u2.u==null)u2.u=o$2++;else if(u2.u<t2.l)return;return t2(n.event?n.event(u2):u2)}}}function q$1(l2,u2,t2,i2,r2,f2,e2,o2,c2,s2,a2){var h2,p2,y2,_2,g2,b2,M2,S2,$2,x2,j2,A2,H,I2,L2,O2,T2,q2,P2,B2,D2,F2=u2.type;if(u2.constructor!=null)return null;128&t2.__u&&(c2=!!(32&t2.__u),t2.__c.__z&&(o2=u2.__e=t2.__e=(f2=t2.__c.__z)[0],t2.__c.__z=null)),(h2=n.__b)&&h2(u2);n:if(typeof F2=="function")try{if(S2=u2.props,$2="prototype"in F2&&F2.prototype.render,x2=(h2=F2.contextType)&&i2[h2.__c],j2=h2?x2?x2.props.value:h2.__:i2,t2.__c?2&(p2=u2.__c=t2.__c).__g&&(p2.__g|=1,M2=!0):($2?u2.__c=p2=new F2(S2,j2):(u2.__c=p2=new m$1(S2,j2),p2.constructor=F2,p2.render=E),x2&&x2.sub(p2),p2.props=S2,p2.state||(p2.state={}),p2.context=j2,p2.__n=i2,y2=!0,p2.__g|=8,p2.__h=[],p2._sb=[]),$2&&p2.__s==null&&(p2.__s=p2.state),$2&&F2.getDerivedStateFromProps!=null&&(p2.__s==p2.state&&(p2.__s=w$1({},p2.__s)),w$1(p2.__s,F2.getDerivedStateFromProps(S2,p2.__s))),_2=p2.props,g2=p2.state,p2.__v=u2,y2)$2&&F2.getDerivedStateFromProps==null&&p2.componentWillMount!=null&&p2.componentWillMount(),$2&&p2.componentDidMount!=null&&p2.__h.push(p2.componentDidMount);else{if($2&&F2.getDerivedStateFromProps==null&&S2!==_2&&p2.componentWillReceiveProps!=null&&p2.componentWillReceiveProps(S2,j2),!(4&p2.__g)&&p2.shouldComponentUpdate!=null&&p2.shouldComponentUpdate(S2,p2.__s,j2)===!1||u2.__v==t2.__v){for(u2.__v!=t2.__v&&(p2.props=S2,p2.state=p2.__s,p2.__g&=-9),u2.__e=t2.__e,u2.__k=t2.__k,u2.__k.some(function(n2){n2&&(n2.__=u2)}),A2=0;A2<p2._sb.length;A2++)p2.__h.push(p2._sb[A2]);p2._sb=[],p2.__h.length&&e2.push(p2);break n}p2.componentWillUpdate!=null&&p2.componentWillUpdate(S2,p2.__s,j2),$2&&p2.componentDidUpdate!=null&&p2.__h.push(function(){p2.componentDidUpdate(_2,g2,b2)})}if(p2.context=j2,p2.props=S2,p2.__P=l2,p2.__g&=-5,H=n.__r,I2=0,$2){for(p2.state=p2.__s,p2.__g&=-9,H&&H(u2),h2=p2.render(p2.props,p2.state,p2.context),L2=0;L2<p2._sb.length;L2++)p2.__h.push(p2._sb[L2]);p2._sb=[]}else do p2.__g&=-9,H&&H(u2),h2=p2.render(p2.props,p2.state,p2.context),p2.state=p2.__s;while(8&p2.__g&&++I2<25);p2.state=p2.__s,p2.getChildContext!=null&&(i2=w$1({},i2,p2.getChildContext())),$2&&!y2&&p2.getSnapshotBeforeUpdate!=null&&(b2=p2.getSnapshotBeforeUpdate(_2,g2)),O2=h2,h2!=null&&h2.type===k$1&&h2.key==null&&(O2=V(h2.props.children)),o2=C$1(l2,v$1(O2)?O2:[O2],u2,t2,i2,r2,f2,e2,o2,c2,s2,a2),u2.__u&=-161,p2.__h.length&&e2.push(p2),M2&&(p2.__g&=-4)}catch(l3){if(u2.__v=null,c2||f2!=null)if(l3.then){for(T2=0,q2=!1,u2.__u|=c2?160:128,u2.__c.__z=[],P2=0;P2<f2.length;P2++)(B2=f2[P2])==null||q2||(B2.nodeType==8&&B2.data=="$s"?(T2>0&&u2.__c.__z.push(B2),T2++,f2[P2]=null):B2.nodeType==8&&B2.data=="/$s"?(--T2>0&&u2.__c.__z.push(B2),q2=T2===0,o2=f2[P2],f2[P2]=null):T2>0&&(u2.__c.__z.push(B2),f2[P2]=null));if(!q2){for(;o2&&o2.nodeType==8&&o2.nextSibling;)o2=o2.nextSibling;f2[f2.indexOf(o2)]=null,u2.__c.__z=[o2]}u2.__e=o2}else{for(D2=f2.length;D2--;)d$1(f2[D2]);N(u2)}else u2.__e=t2.__e,u2.__k=t2.__k,l3.then||N(u2);n.__e(l3,u2,t2)}else o2=u2.__e=z$1(t2.__e,u2,t2,i2,r2,f2,e2,c2,s2,a2);return(h2=n.diffed)&&h2(u2),128&u2.__u?void 0:o2}function N(n2){n2&&n2.__c&&(n2.__c.__g|=4),n2&&n2.__k&&n2.__k.forEach(N)}function P(l2,u2,t2){for(var i2=0;i2<t2.length;i2++)B$1(t2[i2],t2[++i2],t2[++i2]);n.__c&&n.__c(u2,l2),l2.some(function(u3){try{l2=u3.__h,u3.__h=[],l2.some(function(n2){n2.call(u3)})}catch(l3){n.__e(l3,u3.__v)}})}function V(n2){return typeof n2!="object"||n2==null||n2.__b&&n2.__b>0?n2:v$1(n2)?n2.map(V):w$1({},n2)}function z$1(l2,u2,t2,i2,r2,f2,e2,o2,c2,s2){var a2,p2,w2,_2,g2,b2,k2,m2,S2=t2.props,$2=u2.props,x2=u2.type;if(x2=="svg"?r2="http://www.w3.org/2000/svg":x2=="math"?r2="http://www.w3.org/1998/Math/MathML":r2||(r2="http://www.w3.org/1999/xhtml"),f2!=null){for(a2=0;a2<f2.length;a2++)if((g2=f2[a2])&&"setAttribute"in g2==!!x2&&(x2?g2.localName==x2:g2.nodeType==3)){l2=g2,f2[a2]=null;break}}if(l2==null){if(x2==null)return s2.createTextNode($2);l2=s2.createElementNS(r2,x2,$2.is&&$2),o2&&(n.__m&&n.__m(u2,f2),o2=!1),f2=null}if(x2==null)S2===$2||o2&&l2.data==$2||(l2.data=$2);else{if(f2=f2&&y$1.call(l2.childNodes),S2=t2.props||h$1,!o2&&f2!=null)for(S2={},a2=0;a2<l2.attributes.length;a2++)S2[(g2=l2.attributes[a2]).name]=g2.value;for(a2 in S2)if(g2=S2[a2],a2!="children"){if(a2=="dangerouslySetInnerHTML")w2=g2;else if(!(a2 in $2)){if(a2=="value"&&"defaultValue"in $2||a2=="checked"&&"defaultChecked"in $2)continue;O(l2,a2,null,g2,r2)}}for(a2 in m2=1&t2.__u,$2)g2=$2[a2],a2=="children"?_2=g2:a2=="dangerouslySetInnerHTML"?p2=g2:a2=="value"?b2=g2:a2=="checked"?k2=g2:o2&&typeof g2!="function"||S2[a2]===g2&&!m2||O(l2,a2,g2,S2[a2],r2);if(p2)o2||w2&&(p2.__html==w2.__html||p2.__html==l2.innerHTML)||(l2.innerHTML=p2.__html),u2.__k=[];else if(w2&&(l2.innerHTML=""),C$1(x2=="template"?l2.content:l2,v$1(_2)?_2:[_2],u2,t2,i2,x2=="foreignObject"?"http://www.w3.org/1999/xhtml":r2,f2,e2,f2?f2[0]:t2.__k&&M(t2,0),o2,c2,s2),f2!=null)for(a2=f2.length;a2--;)d$1(f2[a2]);o2||(a2="value",x2=="progress"&&b2==null?l2.removeAttribute("value"):b2==null||b2===l2[a2]&&(x2!=="progress"||b2)||O(l2,a2,b2,S2[a2],r2),a2="checked",k2!=null&&k2!=l2[a2]&&O(l2,a2,k2,S2[a2],r2))}return l2}function B$1(l2,u2,t2){try{if(typeof l2=="function"){var i2=typeof l2.__u=="function";i2&&l2.__u(),i2&&u2==null||(l2.__u=l2(u2))}else l2.current=u2}catch(l3){n.__e(l3,t2)}}function D$1(l2,u2,t2){var i2,r2;if(n.unmount&&n.unmount(l2),(i2=l2.ref)&&(i2.current&&i2.current!=l2.__e||B$1(i2,null,u2)),(i2=l2.__c)!=null){if(i2.componentWillUnmount)try{i2.componentWillUnmount()}catch(l3){n.__e(l3,u2)}i2.__P=null}if(i2=l2.__k)for(r2=0;r2<i2.length;r2++)i2[r2]&&D$1(i2[r2],u2,t2||typeof l2.type!="function");t2||d$1(l2.__e),l2.__e&&l2.__e.__l&&(l2.__e.__l=null),l2.__e=l2.__c=l2.__=null}function E(n2,l2,u2){return this.constructor(n2,u2)}function F$1(l2,u2){var t2,i2,r2,f2;u2==document&&(u2=document.documentElement),n.__&&n.__(l2,u2),i2=(t2=!!(l2&&32&l2.__u))?null:u2.__k,l2=u2.__k=_$1(k$1,null,[l2]),r2=[],f2=[],q$1(u2,l2,i2||h$1,h$1,u2.namespaceURI,i2?null:u2.firstChild?y$1.call(u2.childNodes):null,r2,i2?i2.__e:u2.firstChild,t2,f2,u2.ownerDocument),P(r2,l2,f2)}function G(n2,l2){n2.__u|=32,F$1(n2,l2)}n={__e:function(n2,l2,u2,t2){for(var i2,f2,e2;l2=l2.__;)if((i2=l2.__c)&&!(1&i2.__g)){i2.__g|=4;try{if((f2=i2.constructor)&&f2.getDerivedStateFromError!=null&&(i2.setState(f2.getDerivedStateFromError(n2)),e2=8&i2.__g),i2.componentDidCatch!=null&&(i2.componentDidCatch(n2,t2||{}),e2=8&i2.__g),e2)return void(i2.__g|=2)}catch(l3){n2=l3}}throw r$1=0,n2}},l$1=0,m$1.prototype.setState=function(n2,l2){var u2;u2=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=w$1({},this.state),typeof n2=="function"&&(n2=n2(w$1({},u2),this.props)),n2&&w$1(u2,n2),n2!=null&&this.__v&&(l2&&this._sb.push(l2),$(this))},m$1.prototype.forceUpdate=function(n2){this.__v&&(this.__g|=4,n2&&this.__h.push(n2),$(this))},m$1.prototype.render=k$1,t$1=[],r$1=0,f$1=function(n2,l2){return n2.__v.__b-l2.__v.__b},e$1=/(PointerCapture)$|Capture$/i,o$2=0,c$1=T(!1),s$1=T(!0);var o$1=0;function u$1(t2,e2,n$1,f2,u2,i2){e2||(e2={});var a2,c2,l2=e2;if("ref"in l2&&typeof t2!="function")for(c2 in l2={},e2)c2=="ref"?a2=e2[c2]:l2[c2]=e2[c2];var p2={type:t2,props:l2,key:n$1,ref:a2,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--o$1,__i:-1,__u:0,__source:u2,__self:i2};return n.vnode&&n.vnode(p2),p2}const DEFAULT_WIDTH=16,DEFAULT_HEIGHT=16,ICON_SIZE_OVERRIDES={};function Icon({name,remappedFrom,token,width:propWidth,height:propHeight,viewBox:propViewBox,label,alignCapitals=!1}){"use no memo";const href=`#${name.replace(/^#/,"")}`,{width:iconWidth,height:iconHeight,viewBox:overrideViewBox}=ICON_SIZE_OVERRIDES[name]??{width:DEFAULT_WIDTH,height:DEFAULT_HEIGHT},width=propWidth??iconWidth,height=propHeight??iconHeight,viewBox=propViewBox??overrideViewBox??`0 0 ${iconWidth} ${iconHeight}`;return u$1("svg",{"data-icon-name":remappedFrom??name,"data-icon-token":token,"data-align-capitals":alignCapitals,...label!=null?{"aria-label":label,role:"img"}:{"aria-hidden":!0},viewBox,width,height,children:u$1("use",{href})})}const isWhitespace=char=>char!==void 0&&/\s/.test(char),avoidWhitespaceBoundary=(contents,centerIndex)=>{const isOnBoundary=index=>isWhitespace(contents[index-1])||isWhitespace(contents[index]);if(!isOnBoundary(centerIndex))return centerIndex;for(let offset=1;offset<contents.length;offset++){const before2=centerIndex-offset;if(before2>0&&!isOnBoundary(before2))return before2;const after=centerIndex+offset;if(after<contents.length&&!isOnBoundary(after))return after}return centerIndex},centerSplitIndex=contents=>avoidWhitespaceBoundary(contents,Math.ceil(contents.length/2)),splitCenter=contents=>{if(contents.length<2)return[contents,""];const splitIndex=centerSplitIndex(contents);return[contents.slice(0,splitIndex),contents.slice(splitIndex)]},splitExtension=contents=>{if(contents.length<4)return[contents,""];const extensionIndex=contents.lastIndexOf(".")+1,isTooLong=contents.length-extensionIndex>10,splitIndex=extensionIndex>=1&&!isTooLong?extensionIndex:centerSplitIndex(contents);return[contents.slice(0,splitIndex),contents.slice(splitIndex)]},splitLeafPath=contents=>{if(contents.length<4)return[contents,""];const leafPathIndex=contents.lastIndexOf("/")+1,isTooLong=contents.length-leafPathIndex>25,splitIndex=leafPathIndex>=1&&!isTooLong?leafPathIndex:Math.ceil(contents.length/2);return[contents.slice(0,splitIndex),contents.slice(splitIndex)]},splitByIndex=(contents,{splitIndex}={})=>{if(typeof splitIndex!="number"){const centerIndex=Math.ceil(contents.length/2);return[contents.slice(0,centerIndex),contents.slice(centerIndex)]}return[contents.slice(0,splitIndex),contents.slice(splitIndex)]},splitLast=(contents,{splitOffset}={})=>{if(typeof splitOffset!="number"||splitOffset<=0||splitOffset>=contents.length){const centerIndex=Math.ceil(contents.length/2);return[contents.slice(0,centerIndex),contents.slice(centerIndex)]}const splitIndex=contents.length-splitOffset;return[contents.slice(0,splitIndex),contents.slice(splitIndex)]},splitFirst=(contents,{splitOffset}={})=>{if(typeof splitOffset!="number"||splitOffset<=0||splitOffset>=contents.length){const centerIndex=Math.ceil(contents.length/2);return[contents.slice(0,centerIndex),contents.slice(centerIndex)]}const splitIndex=splitOffset;return[contents.slice(0,splitIndex),contents.slice(splitIndex)]};function OverflowMarker({children,marker,variant="default"}){"use no memo";return u$1("div",{"aria-hidden":!0,"data-truncate-marker-cell":!0,children:u$1("div",{"data-truncate-marker":!0,children:typeof marker=="function"?marker({children}):variant==="fade"?u$1("span",{"data-truncate-fade":!0}):marker})})}function OverflowContent(options){"use no memo";const{mode,children}=options;return u$1("div",{children:[u$1("div",{"data-truncate-content":"visible",children:mode==="fruncate"?u$1("span",{children}):children}),u$1("div",{"data-truncate-content":"overflow","aria-hidden":!0,children:mode==="fruncate"?u$1("span",{children}):children})]})}function OverflowText({children,mode="truncate",marker="…",variant="default",...props}){"use no memo";const contentNode=u$1(OverflowContent,{mode,children},"content"),markerNode=u$1(OverflowMarker,{marker,mode,variant},"marker");return u$1("div",{"data-truncate-container":mode,"data-truncate-variant":variant,...props,children:u$1("div",{"data-truncate-grid":!0,children:mode==="truncate"?[contentNode,markerNode]:[markerNode,contentNode,u$1("div",{"data-truncate-fill":!0},"fill")]})})}function Truncate({children,...props}){"use no memo";return u$1(OverflowText,{mode:"truncate",...props,children})}function Fruncate({children,...props}){"use no memo";return u$1(OverflowText,{mode:"fruncate",...props,children})}function MiddleTruncate({children,contents,priority="end",split="center",minimumLength=12,className,style,...props}){"use no memo";let firstSegment=null,secondSegment=null;if(Array.isArray(contents)){if(contents.length!==2)return console.error("MiddleTruncate: contents must be an array of two items"),null;firstSegment=u$1(Truncate,{...props,children:contents[0]}),secondSegment=u$1(Fruncate,{...props,children:contents[1]})}else{if(typeof children!="string")return console.error("MiddleTruncate: children must be a string"),null;if(children.length===0)return u$1("div",{className,style});if(children.length<minimumLength)return priority==="end"?u$1(Fruncate,{...props,className,style,children}):u$1(Truncate,{...props,className,style,children});let splitFn=null,splitIndex=null,splitOffset=null;if(typeof split=="string")split==="center"?splitFn=splitCenter:split==="extension"?splitFn=splitExtension:split==="leaf-path"&&(splitFn=splitLeafPath);else if(typeof split=="number")splitFn=splitByIndex,splitIndex=split;else if(Array.isArray(split)){const[offsetType,offsetValue]=split;splitOffset=offsetValue,offsetType==="last"?splitFn=splitLast:offsetType==="first"&&(splitFn=splitFirst)}else typeof split=="function"&&(splitFn=split);splitFn??=splitCenter;const[firstHalfMessage,secondHalfMessage]=splitFn(children,{priority,variant:props.variant,splitIndex:typeof splitIndex=="number"?splitIndex:void 0,splitOffset:typeof splitOffset=="number"?splitOffset:void 0}),firstIsLarger=firstHalfMessage.length>=secondHalfMessage.length,firstCanBeSimple=priority==="equal"&&!firstIsLarger,secondCanBeSimple=priority==="equal"&&firstIsLarger,firstPropOverrides={},secondPropOverrides={};firstCanBeSimple&&(firstPropOverrides.marker=""),secondCanBeSimple&&(secondPropOverrides.marker=""),firstSegment=u$1(Truncate,{...props,...firstPropOverrides,children:firstHalfMessage}),secondSegment=u$1(Fruncate,{...props,...secondPropOverrides,children:secondHalfMessage})}return u$1("div",{"data-truncate-group-container":"middle",className,style,children:[u$1("div",{"data-truncate-segment-priority":priority==="start"||priority==="equal"?"1":"2",children:firstSegment}),u$1("div",{"data-truncate-segment-priority":priority==="end"||priority==="equal"?"1":"2",children:secondSegment})]})}const EMPTY_FILE_TREE_LAYOUT_RANGE={endIndex:-1,startIndex:-1};function clamp(value,minimum,maximum){return Math.min(Math.max(value,minimum),maximum)}function createRange(startIndex,endIndex){return startIndex<0||endIndex<startIndex?EMPTY_FILE_TREE_LAYOUT_RANGE:{endIndex,startIndex}}function isEmptyRange(range2){return range2.startIndex<0||range2.endIndex<range2.startIndex}function getRangeHeight(range2,itemHeight){return isEmptyRange(range2)?0:(range2.endIndex-range2.startIndex+1)*itemHeight}function getFirstIntersectingIndex(offset,itemCount,itemHeight){if(itemCount<=0)return-1;const totalHeight=itemCount*itemHeight;return offset<=0?0:offset>=totalHeight?itemCount:Math.floor(offset/itemHeight)}function getLastIntersectingIndex(bottomOffset,itemCount,itemHeight){return itemCount<=0||bottomOffset<=0?-1:bottomOffset>=itemCount*itemHeight?itemCount-1:Math.ceil(bottomOffset/itemHeight)-1}function getExpandedDirectoryIndicesByDepth(rows){const indicesByDepth=new Map;return rows.forEach((row,index)=>{if(row.kind!=="directory"||!row.isExpanded)return;const depth=row.ancestorPaths.length,indices=indicesByDepth.get(depth);if(indices==null){indicesByDepth.set(depth,[index]);return}indices.push(index)}),indicesByDepth}function findLastIndexAtOrBefore(indices,threshold){let lowerBound=0,upperBound=indices.length-1,match=-1;for(;lowerBound<=upperBound;){const midpoint=Math.floor((lowerBound+upperBound)/2),index=indices[midpoint];if(index==null)break;if(index<=threshold){match=midpoint,lowerBound=midpoint+1;continue}upperBound=midpoint-1}return match}function computeExpandedSubtreeEndIndices(rows){const endIndexByPath=new Map,openDirectoryPaths=[];for(let index=0;index<rows.length;index+=1){const row=rows[index];if(row==null)continue;const activePaths=row.kind==="directory"&&row.isExpanded?[...row.ancestorPaths,row.path]:row.ancestorPaths;let sharedPrefixLength=0;for(;sharedPrefixLength<openDirectoryPaths.length&&sharedPrefixLength<activePaths.length&&openDirectoryPaths[sharedPrefixLength]===activePaths[sharedPrefixLength];)sharedPrefixLength+=1;for(let openIndex=openDirectoryPaths.length-1;openIndex>=sharedPrefixLength;openIndex-=1){const path=openDirectoryPaths[openIndex];path!=null&&endIndexByPath.set(path,index-1)}openDirectoryPaths.length=sharedPrefixLength;for(let activeIndex=sharedPrefixLength;activeIndex<activePaths.length;activeIndex+=1){const path=activePaths[activeIndex];path!=null&&openDirectoryPaths.push(path)}}const lastIndex=rows.length-1;for(const path of openDirectoryPaths)endIndexByPath.set(path,lastIndex);return endIndexByPath}function computeStickyRows(rows,scrollTop,itemHeight){if(rows.length===0||scrollTop<=0)return[];const subtreeEndIndexByPath=computeExpandedSubtreeEndIndices(rows),expandedDirectoryIndicesByDepth=getExpandedDirectoryIndicesByDepth(rows),stickyRows=[];for(let slotDepth=0;slotDepth<rows.length;slotDepth+=1){const candidateIndices=expandedDirectoryIndicesByDepth.get(slotDepth);if(candidateIndices==null||candidateIndices.length===0)break;const slotTop=scrollTop+slotDepth*itemHeight;let candidateOffset=findLastIndexAtOrBefore(candidateIndices,Math.min(rows.length-1,Math.floor(slotTop/itemHeight))),candidate=null;for(;candidateOffset>=0;){const rowIndex=candidateIndices[candidateOffset],row=rowIndex==null?null:rows[rowIndex]??null;if(row!=null&&(slotDepth===0||row.ancestorPaths[slotDepth-1]===stickyRows[slotDepth-1]?.path)){candidate=row;break}candidateOffset-=1}if(candidate==null)break;stickyRows.push(candidate)}return stickyRows.map((row,slotDepth)=>{const defaultTop=slotDepth*itemHeight,nextBoundaryIndex=(subtreeEndIndexByPath.get(row.path)??rows.length-1)+1;if(nextBoundaryIndex>=rows.length)return{row,top:defaultTop};const nextBoundaryTop=nextBoundaryIndex*itemHeight-scrollTop;return{row,top:Math.min(defaultTop,nextBoundaryTop-itemHeight)}}).filter(entry=>entry.top+itemHeight>0)}function computeFileTreeLayout(rows,metrics){const totalRowCount=metrics.totalRowCount??rows.length,totalHeight=totalRowCount*metrics.itemHeight,viewportHeight=Math.max(0,metrics.viewportHeight),overscan=Math.max(0,Math.floor(metrics.overscan)),maxScrollTop=Math.max(0,totalHeight-viewportHeight),scrollTop=clamp(metrics.scrollTop,0,maxScrollTop),stickyRows=metrics.stickyRows??computeStickyRows(rows,scrollTop,metrics.itemHeight),stickyHeight=stickyRows.reduce((maximumBottom,entry)=>Math.max(maximumBottom,entry.top+metrics.itemHeight),0),paneTop=Math.min(totalHeight,scrollTop+stickyHeight),paneHeight=Math.max(0,viewportHeight-stickyHeight),contentHeight=Math.max(0,totalHeight-paneTop),firstVisiblePhysicalIndex=getFirstIntersectingIndex(scrollTop,totalRowCount,metrics.itemHeight),firstProjectedIndex=getFirstIntersectingIndex(paneTop,totalRowCount,metrics.itemHeight),firstOccludedIndex=stickyHeight<=0||firstVisiblePhysicalIndex<0||firstVisiblePhysicalIndex>=totalRowCount?-1:firstVisiblePhysicalIndex,lastOccludedIndex=firstOccludedIndex===-1?-1:Math.min(totalRowCount-1,firstProjectedIndex-1),occludedCount=firstOccludedIndex===-1||lastOccludedIndex<firstOccludedIndex?0:lastOccludedIndex-firstOccludedIndex+1,visible=paneHeight<=0||firstProjectedIndex>=totalRowCount?EMPTY_FILE_TREE_LAYOUT_RANGE:createRange(firstProjectedIndex,getLastIntersectingIndex(paneTop+paneHeight,totalRowCount,metrics.itemHeight)),minimumWindowStart=lastOccludedIndex+1,windowRange=isEmptyRange(visible)?EMPTY_FILE_TREE_LAYOUT_RANGE:createRange(Math.max(minimumWindowStart,visible.startIndex-overscan),Math.min(totalRowCount-1,visible.endIndex+overscan)),windowHeight=getRangeHeight(windowRange,metrics.itemHeight);return{occlusion:{firstOccludedIndex,lastOccludedIndex,occludedCount},physical:{itemHeight:metrics.itemHeight,maxScrollTop,overscan,scrollTop,totalHeight,totalRowCount,viewportHeight},projected:{contentHeight,paneHeight,paneTop},sticky:{height:stickyHeight,rows:stickyRows},visible,window:{endIndex:windowRange.endIndex,height:windowHeight,offsetTop:isEmptyRange(windowRange)?0:windowRange.startIndex*metrics.itemHeight,startIndex:windowRange.startIndex}}}const GIT_STATUS_LABEL={added:"A",deleted:"D",ignored:null,modified:"M",renamed:"R",untracked:"U"},GIT_STATUS_TITLE={added:"Git status: added",deleted:"Git status: deleted",ignored:"Git status: ignored",modified:"Git status: modified",renamed:"Git status: renamed",untracked:"Git status: untracked"},GIT_STATUS_DESCENDANT_TITLE="Contains git status items";function shouldBumpControllerRevision(hasSeenInitialSnapshot){return hasSeenInitialSnapshot.current?!0:(hasSeenInitialSnapshot.current=!0,!1)}function computeFocusedRowScrollIntoView(input){const{currentScrollTop,focusedIndex,itemHeight,topInset=0,viewportHeight}=input;if(focusedIndex<0)return null;const effectiveInset=Math.max(0,topInset),itemTop=focusedIndex*itemHeight,itemBottom=itemTop+itemHeight;if(itemTop<currentScrollTop+effectiveInset){const nextScrollTop=Math.max(0,itemTop-effectiveInset);return nextScrollTop===currentScrollTop?null:nextScrollTop}if(itemBottom>currentScrollTop+viewportHeight){const nextScrollTop=itemBottom-viewportHeight;return nextScrollTop===currentScrollTop?null:nextScrollTop}return null}function computeFocusedRowScrollTopForOffset(input){const{currentScrollTop,focusedIndex,itemHeight,offset,topInset=0,totalHeight,viewportHeight}=input;if(offset==="nearest")return computeFocusedRowScrollIntoView({currentScrollTop,focusedIndex,itemHeight,topInset,viewportHeight});if(focusedIndex<0)return null;const effectiveInset=Math.max(0,topInset),itemTop=focusedIndex*itemHeight,visibleHeight=Math.max(0,viewportHeight-effectiveInset),targetViewportOffset=offset==="center"?effectiveInset+Math.max(0,(visibleHeight-itemHeight)/2):effectiveInset,maxScrollTop=Math.max(0,totalHeight-viewportHeight),nextScrollTop=Math.max(0,Math.min(itemTop-targetViewportOffset,maxScrollTop));return nextScrollTop===currentScrollTop?null:nextScrollTop}function computeViewportOffsetScrollTop(input){const{currentScrollTop,focusedIndex,itemHeight,targetViewportOffset,totalHeight,viewportHeight}=input;if(focusedIndex<0)return null;const effectiveOffset=Math.max(0,targetViewportOffset),itemTop=focusedIndex*itemHeight,itemBottom=itemTop+itemHeight,currentViewportTop=currentScrollTop+effectiveOffset,currentViewportBottom=currentScrollTop+viewportHeight;if(itemTop>=currentViewportTop&&itemBottom<=currentViewportBottom)return null;const maxScrollTop=Math.max(0,totalHeight-viewportHeight),preservedScrollTop=Math.max(0,Math.min(itemTop-effectiveOffset,maxScrollTop));return preservedScrollTop===currentScrollTop?null:preservedScrollTop}function focusElement(element){if(element==null||!element.isConnected||element===document.body||element===document.documentElement)return!1;element.focus({preventScroll:!0});const rootNode=element.getRootNode();return rootNode instanceof ShadowRoot?rootNode.activeElement===element:document.activeElement===element}function getActiveTreeElement(rootElement){const rootNode=rootElement.getRootNode();if(rootNode instanceof ShadowRoot){const activeElement2=rootNode.activeElement;return activeElement2 instanceof HTMLElement?activeElement2:null}const activeElement=document.activeElement;return activeElement instanceof HTMLElement&&rootElement.contains(activeElement)?activeElement:null}function readMeasuredViewportHeight(scrollElement,fallbackViewportHeight){if(scrollElement==null)return fallbackViewportHeight;const rectHeight=scrollElement.getBoundingClientRect().height;return rectHeight>0?rectHeight:scrollElement.clientHeight>0?scrollElement.clientHeight:fallbackViewportHeight}function getCachedViewportHeight(cachedViewportHeight,fallbackViewportHeight){return cachedViewportHeight!=null&&cachedViewportHeight>0?cachedViewportHeight:fallbackViewportHeight}function getResizeObserverViewportHeight(entry){const borderBoxSize=entry.borderBoxSize,firstBorderBoxSize=Array.isArray(borderBoxSize)?borderBoxSize[0]:borderBoxSize;return firstBorderBoxSize!=null&&Number.isFinite(firstBorderBoxSize.blockSize)&&firstBorderBoxSize.blockSize>0?firstBorderBoxSize.blockSize:entry.contentRect.height>0?entry.contentRect.height:null}function scrollFocusedRowIntoView(scrollElement,focusedIndex,itemHeight,viewportHeight,topInset=0){const nextScrollTop=computeFocusedRowScrollIntoView({currentScrollTop:scrollElement.scrollTop,focusedIndex,itemHeight,topInset,viewportHeight});return nextScrollTop==null?!1:(scrollElement.scrollTop=nextScrollTop,!0)}function scrollFocusedRowToOffset(scrollElement,focusedIndex,itemHeight,viewportHeight,totalHeight,offset,topInset=0){const nextScrollTop=computeFocusedRowScrollTopForOffset({currentScrollTop:scrollElement.scrollTop,focusedIndex,itemHeight,offset,topInset,totalHeight,viewportHeight});return nextScrollTop==null?!1:(scrollElement.scrollTop=nextScrollTop,!0)}function scrollFocusedRowToViewportOffset(scrollElement,focusedIndex,itemHeight,viewportHeight,totalHeight,targetViewportOffset){const nextScrollTop=computeViewportOffsetScrollTop({currentScrollTop:scrollElement.scrollTop,focusedIndex,itemHeight,targetViewportOffset,totalHeight,viewportHeight});return nextScrollTop==null?!1:(scrollElement.scrollTop=nextScrollTop,!0)}function getParkedFocusedRowOffset(focusedIndex,itemHeight,range2,windowHeight){return range2.end<range2.start?null:focusedIndex<range2.start?-itemHeight:focusedIndex>range2.end?windowHeight:null}function classifyFileTreeRenameHandoff(input){const{renamingPath,previousRenamingPath,hasRenderedInput}=input;return renamingPath==null?"reset":hasRenderedInput?previousRenamingPath===renamingPath?"ignore":"focus-input":"reveal-canonical"}function RenameInput({ariaLabel,isFlattened=!1,ref,value,onBlur,onInput}){return u$1("input",{ref,"data-item-rename-input":!0,...isFlattened?{"data-item-flattened-rename-input":!0}:{},"aria-label":ariaLabel,value,onBlur,onInput,onClick:event=>event.stopPropagation(),onMouseDown:event=>event.stopPropagation(),onPointerDown:event=>event.stopPropagation()})}function computeFileTreeRowElementAttributes(input){const{row,mode,targetPath,ariaLabel,domId,isParked,itemHeight,features,state,extraStyle}=input,isSticky=mode==="sticky",parentPath=row.ancestorPaths.at(-1)??"",stateAttributes={};return state.isFocusRinged&&(stateAttributes["data-item-focused"]=!0),row.isSelected&&(stateAttributes["data-item-selected"]=!0),state.isContextHovered&&(stateAttributes["data-item-context-hover"]="true"),state.isDragTarget&&(stateAttributes["data-item-drag-target"]=!0),state.isDragging&&(stateAttributes["data-item-dragging"]=!0),state.effectiveGitStatus!=null&&(stateAttributes["data-item-git-status"]=state.effectiveGitStatus),state.containsGitChange&&(stateAttributes["data-item-contains-git-change"]="true"),{"aria-expanded":!isSticky&&row.kind==="directory"?row.isExpanded:void 0,"aria-haspopup":features.contextMenuEnabled?"menu":void 0,"aria-label":ariaLabel,"aria-level":isSticky?void 0:row.level+1,"aria-posinset":isSticky?void 0:row.posInSet+1,"aria-selected":isSticky?void 0:row.isSelected?"true":"false","aria-setsize":isSticky?void 0:row.setSize,"data-file-tree-sticky-path":isSticky?targetPath:void 0,"data-file-tree-sticky-row":isSticky?"true":void 0,"data-item-context-menu-button-visibility":features.actionLaneEnabled?features.contextMenuButtonVisibility:void 0,"data-item-context-menu-trigger-mode":features.contextMenuEnabled?features.contextMenuTriggerMode:void 0,"data-item-has-context-menu-action-lane":features.actionLaneEnabled?"true":void 0,"data-item-has-git-lane":features.gitLaneActive?"true":void 0,"data-item-parent-path":parentPath.length>0?parentPath:void 0,"data-item-parked":isParked?"true":void 0,"data-item-path":targetPath,"data-item-type":row.kind==="directory"?"folder":"file","data-type":"item",id:isSticky?void 0:domId,role:isSticky?void 0:"treeitem",style:{minHeight:`${itemHeight}px`,...extraStyle},tabIndex:!isSticky&&row.isFocused?0:-1,...stateAttributes}}function computeFileTreeRowClickPlan(input){const{event,mode,isSearchOpen,isDirectory}=input,additive=event.ctrlKey||event.metaKey,hasModifier=event.shiftKey||additive,selection=event.shiftKey?{additive,kind:"range"}:additive?{kind:"toggle"}:{kind:"single"};return{closeSearch:isSearchOpen,revealCanonical:mode==="sticky",selection,toggleDirectory:!hasModifier&&isDirectory}}var t,r,u,i,o=Object.is,f=0,c=[],e=n,a=e.__b,v=e.__r,l=e.diffed,m=e.__c,s=e.unmount,p=e.__;function d(n2,t2){e.__h&&e.__h(r,n2,f||t2),f=0;var u2=r.__H||(r.__H={__:[],__h:[]});return n2>=u2.__.length&&u2.__.push({}),u2.__[n2]}function h(n2){return f=1,y(D,n2)}function y(n2,u2,i2){var f2=d(t++,2);if(f2.t=n2,!f2.__c&&(f2.__=[D(void 0,u2),function(n3){var t2=f2.__N?f2.__N[0]:f2.__[0],r2=f2.t(t2,n3);o(t2,r2)||(f2.__N=[r2,f2.__[1]],f2.__c.setState({}))}],f2.__c=r,!r.__f)){var c2=function(n3,t2,r2){if(!f2.__c.__H)return!0;var u3=f2.__c.__H.__.filter(function(n4){return!!n4.__c});if(u3.every(function(n4){return!n4.__N}))return!e2||e2.call(this,n3,t2,r2);var i3=f2.__c.props!==n3;return u3.forEach(function(n4){if(n4.__N){var t3=n4.__[0];n4.__=n4.__N,n4.__N=void 0,o(t3,n4.__[0])||(i3=!0)}}),e2&&e2.call(this,n3,t2,r2)||i3};r.__f=!0;var e2=r.shouldComponentUpdate,a2=r.componentWillUpdate;r.componentWillUpdate=function(n3,t2,r2){if(4&this.__g){var u3=e2;e2=void 0,c2(n3,t2,r2),e2=u3}a2&&a2.call(this,n3,t2,r2)},r.shouldComponentUpdate=c2}return f2.__N||f2.__}function _(n2,u2){var i2=d(t++,3);!e.__s&&C(i2.__H,u2)&&(i2.__=n2,i2.u=u2,r.__H.__h.push(i2))}function A(n2,u2){var i2=d(t++,4);!e.__s&&C(i2.__H,u2)&&(i2.__=n2,i2.u=u2,r.__h.push(i2))}function F(n2){return f=5,q(function(){return{current:n2}},[])}function q(n2,r2){var u2=d(t++,7);return C(u2.__H,r2)&&(u2.__=n2(),u2.__H=r2,u2.__h=n2),u2.__}function b(n2,t2){return f=8,q(function(){return n2},t2)}function g(){for(var n2;n2=c.shift();)if(n2.__P&&n2.__H)try{n2.__H.__h.forEach(z),n2.__H.__h.forEach(B),n2.__H.__h=[]}catch(t2){n2.__H.__h=[],e.__e(t2,n2.__v)}}e.__b=function(n2){r=null,a&&a(n2)},e.__=function(n2,t2){n2&&t2.__k&&t2.__k.__m&&(n2.__m=t2.__k.__m),p&&p(n2,t2)},e.__r=function(n2){v&&v(n2),t=0;var i2=(r=n2.__c).__H;i2&&(u===r?(i2.__h=[],r.__h=[],i2.__.forEach(function(n3){n3.__N&&(n3.__=n3.__N),n3.u=n3.__N=void 0})):(i2.__h.forEach(z),i2.__h.forEach(B),i2.__h=[],t=0)),u=r},e.diffed=function(n2){l&&l(n2);var t2=n2.__c;t2&&t2.__H&&(t2.__H.__h.length&&(c.push(t2)!==1&&i===e.requestAnimationFrame||((i=e.requestAnimationFrame)||w)(g)),t2.__H.__.forEach(function(n3){n3.u&&(n3.__H=n3.u),n3.u=void 0})),u=r=null},e.__c=function(n2,t2){t2.some(function(n3){try{n3.__h.forEach(z),n3.__h=n3.__h.filter(function(n4){return!n4.__||B(n4)})}catch(r2){t2.some(function(n4){n4.__h&&(n4.__h=[])}),t2=[],e.__e(r2,n3.__v)}}),m&&m(n2,t2)},e.unmount=function(n2){s&&s(n2);var t2,r2=n2.__c;r2&&r2.__H&&(r2.__H.__.forEach(function(n3){try{z(n3)}catch(n4){t2=n4}}),r2.__H=void 0,t2&&e.__e(t2,r2.__v))};var k=typeof requestAnimationFrame=="function";function w(n2){var t2,r2=function(){clearTimeout(u2),k&&cancelAnimationFrame(t2),setTimeout(n2)},u2=setTimeout(r2,35);k&&(t2=requestAnimationFrame(r2))}function z(n2){var t2=r,u2=n2.__c;typeof u2=="function"&&(n2.__c=void 0,u2()),r=t2}function B(n2){var t2=r;n2.__c=n2.__(),r=t2}function C(n2,t2){return!n2||n2.length!==t2.length||t2.some(function(t3,r2){return!o(t3,n2[r2])})}function D(n2,t2){return typeof t2=="function"?t2(n2):t2}function formatFlattenedSegments(row,renameInput=null,dragTargetFlattenedSegmentPath=null){"use no memo";const segments=row.flattenedSegments;return segments==null||segments.length===0?renameInput??row.name:u$1("span",{"data-item-flattened-subitems":!0,children:segments.map((segment,index)=>{const isLast=index===segments.length-1;return u$1(k$1,{children:[u$1("span",{"data-item-flattened-subitem":segment.path,"data-item-flattened-subitem-drag-target":dragTargetFlattenedSegmentPath===segment.path?"true":void 0,children:isLast&&renameInput!=null?renameInput:u$1(Truncate,{children:segment.name})}),index<segments.length-1?" / ":""]},segment.path)})})}function getFileTreeRowPath(row){return row.isFlattened?row.flattenedSegments?.findLast(segment=>segment.isTerminal)?.path??row.path:row.path}function getFileTreeRowAriaLabel(row){const flattenedSegments=row.flattenedSegments;return flattenedSegments==null||flattenedSegments.length===0?row.name:flattenedSegments.map(segment=>segment.name).join(" / ")}function computeStickyRowsFromCandidates(candidates,scrollTop,itemHeight,totalRowCount){return candidates.map((candidate,slotDepth)=>{const defaultTop=slotDepth*itemHeight,nextBoundaryIndex=candidate.subtreeEndIndex+1;if(nextBoundaryIndex>=totalRowCount)return{row:candidate.row,top:defaultTop};const nextBoundaryTop=nextBoundaryIndex*itemHeight-scrollTop;return{row:candidate.row,top:Math.min(defaultTop,nextBoundaryTop-itemHeight)}}).filter(entry=>entry.top+itemHeight>0)}function computeFileTreeViewLayoutState({controller,itemHeight,overscan,scrollTop,stickyFolders,viewportHeight}){const visibleCount=controller.getVisibleCount(),stickyCandidates=stickyFolders&&visibleCount>0?controller.getStickyRowCandidates(scrollTop,itemHeight):[],visibleRows=stickyCandidates==null&&stickyFolders&&visibleCount>0?controller.getVisibleRows(0,visibleCount-1):[],snapshot=computeFileTreeLayout(visibleRows,{itemHeight,overscan,scrollTop,stickyRows:stickyCandidates==null?void 0:computeStickyRowsFromCandidates(stickyCandidates,scrollTop,itemHeight,visibleCount),totalRowCount:visibleCount,viewportHeight}),previewStickyCandidates=stickyFolders&&scrollTop<=0&&visibleCount>0?controller.getStickyRowCandidates(1,itemHeight):[],overlayRows=previewStickyCandidates!=null&&scrollTop<=0?computeStickyRowsFromCandidates(previewStickyCandidates,1,itemHeight,visibleCount):stickyFolders&&scrollTop<=0&&visibleRows.length>0?computeStickyRows(visibleRows,1,itemHeight):snapshot.sticky.rows;return{overlayHeight:overlayRows.reduce((maxBottom,entry)=>Math.max(maxBottom,entry.top+itemHeight),0),overlayRows,snapshot,visibleRows}}const TOUCH_LONG_PRESS_DELAY=400,TOUCH_LONG_PRESS_MOVE_THRESHOLD=10,DRAG_EDGE_SCROLL_THRESHOLD=40,DRAG_EDGE_SCROLL_MAX_SPEED=18;function getPointElement(rootNode,clientX,clientY){const pointRoot=rootNode,documentElementFromPoint=document.elementFromPoint?.bind(document)??null,element=pointRoot.elementFromPoint?.(clientX,clientY)??documentElementFromPoint?.(clientX,clientY)??null;return rootNode instanceof ShadowRoot&&(element==null||!rootNode.contains(element))?getShadowPointElementByGeometry(rootNode,clientX,clientY):element instanceof HTMLElement?element:null}function getShadowPointElementByGeometry(rootNode,clientX,clientY){const candidates=Array.from(rootNode.querySelectorAll('[data-type="item"], [data-item-flattened-subitem]'));for(let index=candidates.length-1;index>=0;index--){const candidate=candidates[index],rect=candidate.getBoundingClientRect();if(clientX>=rect.left&&clientX<=rect.right&&clientY>=rect.top&&clientY<=rect.bottom)return candidate}return null}function resolveDropTargetFromElement(target){const rowButton=target?.closest?.('[data-type="item"]');if(!(rowButton instanceof HTMLElement))return null;const hoveredPath=rowButton.dataset.itemPath??null;if(hoveredPath==null)return null;const flattenedSegment=target?.closest?.("[data-item-flattened-subitem]"),flattenedSegmentPath=flattenedSegment instanceof HTMLElement?flattenedSegment.getAttribute("data-item-flattened-subitem")??null:null;if(flattenedSegmentPath!=null&&flattenedSegmentPath.endsWith("/"))return{directoryPath:flattenedSegmentPath,flattenedSegmentPath,hoveredPath,kind:"directory"};if(rowButton.dataset.itemType==="folder")return{directoryPath:hoveredPath,flattenedSegmentPath:null,hoveredPath,kind:"directory"};const parentPath=rowButton.dataset.itemParentPath??null;return parentPath==null||parentPath.length===0?{directoryPath:null,flattenedSegmentPath:null,hoveredPath,kind:"root"}:{directoryPath:parentPath,flattenedSegmentPath:null,hoveredPath,kind:"directory"}}function createDragPreviewElement(sourceElement){const preview=sourceElement.cloneNode(!0);return preview.removeAttribute("id"),preview.dataset.fileTreeDragPreview="true",preview.setAttribute("aria-hidden","true"),preview.tabIndex=-1,Object.assign(preview.style,{boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",left:"0px",margin:"0",pointerEvents:"none",position:"fixed",top:"0px",willChange:"transform",zIndex:"10000"}),preview}function shouldUseCustomPointerDragImage(){return navigator.vendor!=="Apple Computer, Inc."}function getDragEdgeScrollDelta(clientY,scrollRect){const topDistance=clientY-scrollRect.top;if(topDistance<DRAG_EDGE_SCROLL_THRESHOLD)return-Math.ceil((DRAG_EDGE_SCROLL_THRESHOLD-Math.max(0,topDistance))/DRAG_EDGE_SCROLL_THRESHOLD*DRAG_EDGE_SCROLL_MAX_SPEED);const bottomDistance=scrollRect.bottom-clientY;return bottomDistance<DRAG_EDGE_SCROLL_THRESHOLD?Math.ceil((DRAG_EDGE_SCROLL_THRESHOLD-Math.max(0,bottomDistance))/DRAG_EDGE_SCROLL_THRESHOLD*DRAG_EDGE_SCROLL_MAX_SPEED):0}function getBuiltInGitStatusDecoration(gitStatus,containsGitChange){if(gitStatus!=null){const label=GIT_STATUS_LABEL[gitStatus];return label==null?null:{text:label,title:GIT_STATUS_TITLE[gitStatus]}}return containsGitChange?{icon:{name:"file-tree-icon-dot",width:6,height:6},title:GIT_STATUS_DESCENDANT_TITLE}:null}function getInheritedIgnoredGitStatus(ancestorPaths,ignoredDirectoryPaths,ignoredInheritanceCache){if(ignoredDirectoryPaths==null||ignoredDirectoryPaths.size===0)return null;const visitedAncestors=[];for(let index=ancestorPaths.length-1;index>=0;index-=1){const ancestorPath=ancestorPaths[index],cached=ignoredInheritanceCache.get(ancestorPath);if(cached!=null){for(const visitedAncestor of visitedAncestors)ignoredInheritanceCache.set(visitedAncestor,cached);return cached?"ignored":null}if(ignoredDirectoryPaths.has(ancestorPath)){ignoredInheritanceCache.set(ancestorPath,!0);for(const visitedAncestor of visitedAncestors)ignoredInheritanceCache.set(visitedAncestor,!0);return"ignored"}visitedAncestors.push(ancestorPath)}for(const visitedAncestor of visitedAncestors)ignoredInheritanceCache.set(visitedAncestor,!1);return null}function isFileTreeDirectoryHandle(item){return item!=null&&"toggle"in item}function isSpaceSelectionKey(event){return event.code==="Space"||event.key===" "||event.key==="Spacebar"}function isSearchOpenSeedKey(event){return event.key.length===1&&/^[\p{L}\p{N}]$/u.test(event.key)&&!event.ctrlKey&&!event.metaKey&&!event.altKey}function getFileTreeGuideStyleText(focusedParentPath){return focusedParentPath==null?"":`[data-item-section="spacing-item"][data-ancestor-path="${focusedParentPath.replaceAll("\\","\\\\").replaceAll('"','\\"')}"] { opacity: 1; }`}function isContextMenuOpenKey(event){return event.shiftKey&&event.key==="F10"||event.key==="ContextMenu"}function canKeyUseStickyKeyboardState(event,contextMenuEnabled){return contextMenuEnabled&&isContextMenuOpenKey(event)||(event.ctrlKey||event.metaKey)&&isSpaceSelectionKey(event)?!0:event.key==="ArrowDown"||event.key==="ArrowLeft"||event.key==="ArrowRight"||event.key==="ArrowUp"}const BLOCKED_CONTEXT_MENU_NAV_KEYS=new Set(["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","End","Home","PageDown","PageUp"]);function isEventInContextMenu(event){for(const entry of event.composedPath())if(entry instanceof HTMLElement&&(entry.dataset.fileTreeContextMenuRoot==="true"||entry.dataset.type==="context-menu-anchor"||entry.dataset.type==="context-menu-trigger"||entry.getAttribute("slot")==="context-menu"))return!0;return!1}function serializeAnchorRect(rect){return{bottom:rect.bottom,height:rect.height,left:rect.left,right:rect.right,top:rect.top,width:rect.width,x:rect.x,y:rect.y}}function createAnchorRectFromPoint(x2,y2){return{bottom:y2,height:0,left:x2,right:x2,top:y2,width:0,x:x2,y:y2}}function getContextMenuAnchorTop(rootElement,itemElement){if(rootElement==null)return itemElement.offsetTop;const itemRect=itemElement.getBoundingClientRect(),rootRect=rootElement.getBoundingClientRect();return itemRect.top-rootRect.top}function setButtonRef(buttonRefs,path,element){if(element==null){buttonRefs.delete(path);return}buttonRefs.set(path,element)}function getContextMenuAnchorButton(path,stickyButtonRefs,rowButtonRefs){if(path==null)return null;const stickyButton=stickyButtonRefs.get(path)??null;if(stickyButton!=null)return stickyButton;const rowButton=rowButtonRefs.get(path)??null;return rowButton?.dataset.itemParked==="true"?null:rowButton}function getMountedStickyRowPaths(rootElement){if(rootElement==null)return[];const paths=[];for(const element of rootElement.querySelectorAll('button[data-file-tree-sticky-row="true"]')){if(!(element instanceof HTMLElement))continue;const path=element.dataset.fileTreeStickyPath;path!=null&&paths.push(path)}return paths}function getFocusedParkedRowElement(rootElement,path){if(rootElement==null||path==null)return null;for(const element of rootElement.querySelectorAll('button[data-item-focused="true"][data-item-parked="true"]'))if(element instanceof HTMLElement&&element.dataset.itemPath===path)return element;return null}function getStickyKeyboardViewportOffset(rootElement,scrollElement,activeTreeElement,path,itemHeight,stickyOverlayHeight,viewportHeight){const minimumStickyKeyboardViewportOffset=Math.max(0,stickyOverlayHeight-itemHeight),scrollElementRect=scrollElement?.getBoundingClientRect()??null,activeElementTopWithinViewport=scrollElementRect==null||activeTreeElement==null?null:activeTreeElement.getBoundingClientRect().top-scrollElementRect.top,focusedParkedRowElement=getFocusedParkedRowElement(rootElement,path),parkedElementTopWithinViewport=scrollElementRect==null||focusedParkedRowElement==null?null:focusedParkedRowElement.getBoundingClientRect().top-scrollElementRect.top;return Math.max(0,Math.min(parkedElementTopWithinViewport??Math.max(activeElementTopWithinViewport??0,minimumStickyKeyboardViewportOffset),Math.max(0,viewportHeight-itemHeight)))}function createContextMenuItem(row,path){return{kind:row.kind,name:getFileTreeRowAriaLabel(row),path}}function getFileTreeRootDomId(instanceId){return instanceId==null?void 0:`${instanceId}__tree`}function getFileTreeFocusedRowDomId(instanceId,path,parked){if(instanceId!=null)return`${instanceId}__focused-item-${encodeURIComponent(path)}${parked?"__parked":""}`}function isBuiltInDecorationIconName(name){return name==="file-tree-icon-chevron"||name==="file-tree-icon-dot"||name==="file-tree-icon-file"||name==="file-tree-icon-lock"}function renderRowDecoration(decoration,resolveIcon){if(decoration==null)return null;if("text"in decoration)return decoration.parts!=null?u$1("span",{title:decoration.title,children:decoration.parts.map((part,index)=>u$1("span",{style:{color:part.color},children:part.text},index))}):u$1("span",{title:decoration.title,children:decoration.text});const icon=typeof decoration.icon=="string"?isBuiltInDecorationIconName(decoration.icon)?resolveIcon(decoration.icon):{name:decoration.icon}:isBuiltInDecorationIconName(decoration.icon.name)?(()=>{const resolvedIcon=resolveIcon(decoration.icon.name),{name:_ignoredName,...iconOverrides}=decoration.icon;return{...resolvedIcon,...iconOverrides}})():decoration.icon;return u$1("span",{title:decoration.title,children:u$1(Icon,{...icon})})}function focusFirstMenuElement(menuElement){menuElement!=null&&focusElement(menuElement.querySelector(["button:not([disabled])","[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", "))??menuElement)}function renderFileTreeRowContent(row,resolveIcon,{actionLaneEnabled=!1,customDecoration=null,decorationLaneEnabled=!1,dragTargetFlattenedSegmentPath=null,gitDecoration=null,gitLaneActive=!1,renameInput=null,showDecorativeActionAffordance=!1}={}){const targetPath=getFileTreeRowPath(row);return u$1(k$1,{children:[row.depth>0?u$1("div",{"data-item-section":"spacing",children:Array.from({length:row.depth}).map((_2,index)=>u$1("div",{"data-item-section":"spacing-item","data-ancestor-path":row.ancestorPaths[index]},index))}):null,u$1("div",{"data-item-section":"icon",children:row.kind==="directory"?u$1(Icon,{...resolveIcon("file-tree-icon-chevron")}):u$1(Icon,{...resolveIcon("file-tree-icon-file",targetPath)})}),u$1("div",{"data-item-section":"content",children:row.isFlattened?formatFlattenedSegments(row,renameInput,dragTargetFlattenedSegmentPath):renameInput??u$1(MiddleTruncate,{minimumLength:5,split:"extension",children:row.name})}),decorationLaneEnabled?u$1("div",{"data-item-section":"decoration",children:customDecoration!=null?renderRowDecoration(customDecoration,resolveIcon):null}):null,gitLaneActive?u$1("div",{"data-item-section":"git",children:renderRowDecoration(gitDecoration,resolveIcon)}):null,actionLaneEnabled?u$1("div",{"data-item-section":"action",children:showDecorativeActionAffordance?u$1("span",{"aria-hidden":"true","data-item-action-affordance":"decorative",children:u$1(Icon,{...resolveIcon("file-tree-icon-ellipsis")})}):null}):null]})}function renderStyledRow(frame,row,key2,options={}){const{controller,renameView,visualFocusPath,contextHoverPath,draggedPathSet,dragTarget,dragAndDropEnabled,shouldSuppressContextMenu,handleRowDragStart,handleRowDragEnd,handleRowTouchStart,instanceId,itemHeight,gitStatusByPath,ignoredGitDirectories,ignoredInheritanceCache,directoriesWithGitChanges,gitLaneActive,contextMenuEnabled,contextMenuTriggerMode,contextMenuButtonTriggerEnabled,contextMenuButtonVisibility,contextMenuRightClickEnabled,registerRenameInput,registerButton,resolveIcon,renderDecorationForRow,openContextMenuForRow,onRowClick,onKeyDown}=frame,targetPath=getFileTreeRowPath(row),{isParked=!1,mode="flow",style}=options,isSticky=mode==="sticky",effectiveGitStatus=gitStatusByPath?.get(targetPath)??null??getInheritedIgnoredGitStatus(row.ancestorPaths,ignoredGitDirectories,ignoredInheritanceCache),containsGitChange=row.kind==="directory"&&(directoriesWithGitChanges?.has(targetPath)??!1),customDecoration=renderDecorationForRow(row,targetPath),gitDecoration=getBuiltInGitStatusDecoration(effectiveGitStatus,containsGitChange),actionLaneEnabled=contextMenuEnabled&&contextMenuButtonTriggerEnabled,decorationLaneEnabled=customDecoration!=null||gitLaneActive||actionLaneEnabled,showDecorativeActionAffordance=actionLaneEnabled&&contextMenuButtonVisibility==="always",isRenamingRow=renameView.getPath()===targetPath,renamingValue=isRenamingRow?renameView.getValue():"",renameInput=isSticky||!isRenamingRow?null:u$1(RenameInput,{ref:registerRenameInput,ariaLabel:`Rename ${getFileTreeRowAriaLabel(row)}`,isFlattened:row.isFlattened,value:renamingValue,onBlur:()=>{renameView.commit()},onInput:event=>{renameView.setValue(event.currentTarget.value)}}),rowContent=renderFileTreeRowContent(row,resolveIcon,{actionLaneEnabled,customDecoration,decorationLaneEnabled,dragTargetFlattenedSegmentPath:dragTarget?.flattenedSegmentPath??null,gitDecoration,gitLaneActive,renameInput,showDecorativeActionAffordance}),commonProps={...computeFileTreeRowElementAttributes({ariaLabel:getFileTreeRowAriaLabel(row),domId:row.isFocused?getFileTreeFocusedRowDomId(instanceId,targetPath,isParked):void 0,extraStyle:style,features:{actionLaneEnabled,contextMenuButtonVisibility:actionLaneEnabled?contextMenuButtonVisibility:null,contextMenuEnabled,contextMenuTriggerMode:contextMenuEnabled?contextMenuTriggerMode:null,gitLaneActive},isParked,itemHeight,mode,row,state:{containsGitChange,effectiveGitStatus,isContextHovered:contextHoverPath===targetPath,isDragTarget:dragTarget?.kind==="directory"&&dragTarget.directoryPath===targetPath,isDragging:draggedPathSet?.has(targetPath)===!0,isFocusRinged:row.isFocused&&visualFocusPath===targetPath},targetPath}),key:key2,onContextMenu:contextMenuEnabled||dragAndDropEnabled?event=>{if(shouldSuppressContextMenu()){event.preventDefault();return}contextMenuEnabled&&(event.preventDefault(),contextMenuRightClickEnabled&&(controller.focusMountedPathFromInput(targetPath),openContextMenuForRow(row,targetPath,{anchorRect:createAnchorRectFromPoint(event.clientX,event.clientY),source:"right-click"})))}:void 0,onFocus:isSticky?void 0:()=>{controller.focusMountedPathFromInput(targetPath)},onKeyDown:isSticky?void 0:onKeyDown,ref:element=>{registerButton(targetPath,element)}};return!isSticky&&isRenamingRow?u$1("div",{...commonProps,children:rowContent}):u$1("button",{...commonProps,type:"button",draggable:dragAndDropEnabled&&!isParked,onDragEnd:dragAndDropEnabled&&!isParked?handleRowDragEnd:void 0,onDragStart:dragAndDropEnabled&&!isParked?event=>{handleRowDragStart(event,row,targetPath)}:void 0,onMouseDown:event=>{if(isSticky){event.preventDefault();return}controller.isSearchOpen()&&event.preventDefault()},onTouchStart:dragAndDropEnabled&&!isParked?event=>{handleRowTouchStart(event,row,targetPath)}:void 0,onClick:event=>{onRowClick(event,row,targetPath,mode)},children:rowContent})}function renderRangeChildren(frame,range2,hiddenRowPaths){return range2.end<range2.start?[]:frame.controller.getVisibleRows(range2.start,range2.end).filter(row=>!hiddenRowPaths.has(getFileTreeRowPath(row))).map((row,slotIndex)=>renderStyledRow(frame,row,range2.start+slotIndex))}function FileTreeView({composition,controller,gitStatusByPath,ignoredGitDirectories,directoriesWithGitChanges,icons,instanceId,itemHeight=FILE_TREE_DEFAULT_ITEM_HEIGHT,overscan=10,renamingEnabled=!1,renderRowDecoration:renderRowDecoration2,searchBlurBehavior="close",searchEnabled=!1,searchFakeFocus=!1,slotHost,stickyFolders=!1,initialViewportHeight=420}){"use no memo";const contextMenuAnchorRef=F(null),contextMenuTriggerRef=F(null),isScrollingRef=F(!1),listRef=F(null),renameInputRef=F(null),rootRef=F(null),scrollRef=F(null),searchInputRef=F(null),rowButtonRefs=F(new Map),stickyRowButtonRefs=F(new Map),updateViewportRef=F(()=>{}),measuredViewportHeightRef=F(null),processedScrollRequestIdRef=F(0),initialFocusedScrollAppliedRef=F(!1),initialFocusedScrollControllerRef=F(null);initialFocusedScrollControllerRef.current!==controller&&(initialFocusedScrollAppliedRef.current=!1,initialFocusedScrollControllerRef.current=controller);const domFocusOwnerRef=F(!1),previousFocusedPathRef=F(null),previousRenamingPathRef=F(null),restoreTreeFocusAfterSearchCloseRef=F(!1),restoreTreeFocusViewportOffsetRef=F(null),dragAutoScrollFrameRef=F(null),dragHoverOpenKeyRef=F(null),dragHoverOpenTimerRef=F(null),dragPointRef=F(null),dragPreviewRef=F(null),dragRowSnapshotRef=F(null),touchCleanupRef=F(null),touchDragActiveRef=F(!1),touchPreviewOffsetRef=F(null),touchSourceElementRef=F(null),touchStartPointRef=F(null),touchLongPressTimerRef=F(null),ignoredInheritanceCache=q(()=>new Map,[]),[,setControllerRevision]=h(0),hasSeenInitialControllerSnapshotRef=F(!1),[activeItemPath,setActiveItemPath]=h(null),[contextHoverPath,setContextHoverPath]=h(null),[contextMenuAnchorTop,setContextMenuAnchorTop]=h(null),[lastContextMenuInteraction,setLastContextMenuInteraction]=h(null),[scrollSettledRevision,setScrollSettledRevision]=h(0),[contextMenuState,setContextMenuState]=h(null),contextMenuStateRef=F(contextMenuState);contextMenuStateRef.current=contextMenuState;const pendingStickyFocusPathRef=F(null),pendingStickyKeyboardFocusPathRef=F(null),pendingStickyKeyboardViewportOffsetRef=F(null),pendingStickyKeyboardScrollTopRef=F(null),debugContextMenuTriggerPathRef=F(null),debugDisableScrollSuppressionRef=F(!1),clearPendingStickyKeyboardState=()=>{pendingStickyKeyboardFocusPathRef.current=null,pendingStickyKeyboardViewportOffsetRef.current=null,pendingStickyKeyboardScrollTopRef.current=null},preserveStickyKeyboardFocusAtScrollTop=(path,scrollTop)=>{pendingStickyKeyboardFocusPathRef.current=path,pendingStickyKeyboardViewportOffsetRef.current=null,pendingStickyKeyboardScrollTopRef.current=scrollTop==null?null:{path,scrollTop}},restoreStickyKeyboardViewportOffset=(path,viewportOffset)=>{pendingStickyKeyboardFocusPathRef.current=null,pendingStickyKeyboardViewportOffsetRef.current={path,viewportOffset},pendingStickyKeyboardScrollTopRef.current=null},skipInitialSearchAutoFocusRef=F(searchBlurBehavior==="retain"&&controller.isSearchOpen()),[fakeSearchFocusActive,setFakeSearchFocusActive]=h(searchFakeFocus);_(()=>{searchFakeFocus||setFakeSearchFocusActive(!1)},[searchFakeFocus]);const searchInputUserInteractedRef=F(!1),markSearchInputInteracted=b(()=>{searchInputUserInteractedRef.current=!0,setFakeSearchFocusActive(previous=>previous&&!1)},[]),[layoutState,setLayoutState]=h(()=>computeFileTreeViewLayoutState({controller,itemHeight,overscan,scrollTop:0,stickyFolders,viewportHeight:initialViewportHeight})),[hasStickyUiMount,setHasStickyUiMount]=h(!1);_(()=>{setHasStickyUiMount(!0)},[]);const contextMenuEnabled=composition?.contextMenu?.enabled===!0||composition?.contextMenu?.render!=null||composition?.contextMenu?.onOpen!=null||composition?.contextMenu?.onClose!=null,contextMenuTriggerMode=composition?.contextMenu?.triggerMode??(contextMenuEnabled?"right-click":"both"),contextMenuButtonTriggerEnabled=contextMenuTriggerMode==="both"||contextMenuTriggerMode==="button",contextMenuButtonVisibility=composition?.contextMenu?.buttonVisibility??"when-needed",contextMenuRightClickEnabled=contextMenuTriggerMode==="both"||contextMenuTriggerMode==="right-click";A(()=>{const rootElement=rootRef.current;if(rootElement==null)return;const handleDebugSetContextMenuTrigger=event=>{if(!(event instanceof CustomEvent))return;const nextPath=event.detail?.path??null;debugContextMenuTriggerPathRef.current=nextPath,setContextHoverPath(nextPath),setLastContextMenuInteraction(nextPath==null?null:"pointer")},handleDebugSetScrollSuppression=event=>{event instanceof CustomEvent&&(debugDisableScrollSuppressionRef.current=event.detail?.disabled===!0)};return rootElement.addEventListener("file-tree-debug-set-context-menu-trigger",handleDebugSetContextMenuTrigger),rootElement.addEventListener("file-tree-debug-set-scroll-suppression",handleDebugSetScrollSuppression),()=>{rootElement.removeEventListener("file-tree-debug-set-context-menu-trigger",handleDebugSetContextMenuTrigger),rootElement.removeEventListener("file-tree-debug-set-scroll-suppression",handleDebugSetScrollSuppression)}},[]);const registerRowButton=b((path,element)=>{setButtonRef(rowButtonRefs.current,path,element)},[]),registerStickyRowButton=b((path,element)=>{setButtonRef(stickyRowButtonRefs.current,path,element)},[]),registerRenameInput=b(element=>{renameInputRef.current=element},[]),getTriggerAnchorButton=b(path=>getContextMenuAnchorButton(path,stickyRowButtonRefs.current,rowButtonRefs.current),[]),gitLaneActive=gitStatusByPath!=null||ignoredGitDirectories!=null||directoriesWithGitChanges!=null,{resolveIcon}=q(()=>createFileTreeIconResolver(icons),[icons]),renameView=controller[FILE_TREE_RENAME_VIEW](),renamingPath=renameView.getPath(),isRenaming=renamingPath!=null,isSearchOpen=controller.isSearchOpen(),searchValue=controller.getSearchValue(),focusedPath=controller.getFocusedPath(),focusedIndex=controller.getFocusedIndex(),scrollRequest=controller.getScrollRequest(),dragAndDropEnabled=controller.isDragAndDropEnabled(),dragSession=controller.getDragSession(),draggedPathSet=q(()=>dragSession==null?null:new Set(dragSession.draggedPaths),[dragSession]),dragTarget=dragSession?.target??null,draggedPrimaryPath=dragSession?.primaryPath??null,treeDomId=getFileTreeRootDomId(instanceId),{overlayHeight:overlayRowsHeight,overlayRows,snapshot:layoutSnapshot,visibleRows}=layoutState,resolvedViewportHeight=layoutSnapshot.physical.viewportHeight,range2=q(()=>({end:layoutSnapshot.window.endIndex,start:layoutSnapshot.window.startIndex}),[layoutSnapshot.window.endIndex,layoutSnapshot.window.startIndex]),stickyRows=overlayRows,occludedStickyRows=layoutSnapshot.sticky.rows,totalScrollableHeight=layoutSnapshot.physical.totalHeight,stickyOverlayHeight=layoutSnapshot.sticky.height,stickyRowPathSet=q(()=>new Set(occludedStickyRows.map(entry=>getFileTreeRowPath(entry.row))),[occludedStickyRows]),focusedRowIsMounted=focusedIndex>=0&&focusedIndex>=range2.start&&focusedIndex<=range2.end,renderDecorationForRow=b((row,targetPath)=>renderRowDecoration2?.({item:createContextMenuItem(row,targetPath),row})??null,[renderRowDecoration2]),restoreContextMenuFocus=b(restorePath=>focusElement(restorePath==null?null:rowButtonRefs.current.get(restorePath)??null)?!0:focusElement(rootRef.current),[]),restoreFocusToTree=b(path=>{restoreContextMenuFocus(controller.focusNearestPath(path))},[controller,restoreContextMenuFocus]),restoreFocusToTreeRef=F(restoreFocusToTree);restoreFocusToTreeRef.current=restoreFocusToTree;const shouldRestoreContextMenuFocusRef=F(!0),closeContextMenuRef=F(()=>{}),closeContextMenu=b((restoreFocus=!0)=>{const currentContextMenuState=contextMenuStateRef.current;currentContextMenuState!=null&&(shouldRestoreContextMenuFocusRef.current=shouldRestoreContextMenuFocusRef.current&&restoreFocus,setContextMenuState(null),composition?.contextMenu?.onClose?.(),shouldRestoreContextMenuFocusRef.current&&restoreFocusToTree(currentContextMenuState.path))},[composition?.contextMenu,restoreFocusToTree]);closeContextMenuRef.current=closeContextMenu;const updateTriggerPosition=b(itemButton=>{const nextTop=itemButton==null?null:getContextMenuAnchorTop(rootRef.current,itemButton);setContextMenuAnchorTop(previousTop=>previousTop===nextTop?previousTop:nextTop)},[]),openContextMenuForRow=b((row,targetPath,options)=>{const item=controller.getItem(targetPath);if(item==null)return;const anchorButton=getTriggerAnchorButton(targetPath);if(anchorButton?.dataset.fileTreeStickyRow==="true"){const scrollElement=scrollRef.current;preserveStickyKeyboardFocusAtScrollTop(targetPath,scrollElement?.scrollTop??null),domFocusOwnerRef.current=!0,setActiveItemPath(previousPath=>previousPath===targetPath?previousPath:targetPath)}item.focus(),updateTriggerPosition(anchorButton),shouldRestoreContextMenuFocusRef.current=!0,setContextMenuState({anchorRect:options?.anchorRect??null,item:createContextMenuItem(row,targetPath),path:targetPath,source:options?.source??"keyboard"})},[controller,getTriggerAnchorButton,updateTriggerPosition]),startRenameFromPath=b(path=>{if(renamingEnabled){if(controller.isSearchOpen()){const scrollElement=scrollRef.current,viewportHeight=readMeasuredViewportHeight(scrollElement,resolvedViewportHeight);restoreTreeFocusViewportOffsetRef.current=focusedIndex<0||scrollElement==null?null:Math.max(0,Math.min(focusedIndex*itemHeight-scrollElement.scrollTop,Math.max(0,viewportHeight-itemHeight))),restoreTreeFocusAfterSearchCloseRef.current=!0}controller.startRenaming(path)!==!1&&(setLastContextMenuInteraction("focus"),setControllerRevision(revision=>revision+1))}},[controller,focusedIndex,itemHeight,renamingEnabled,resolvedViewportHeight]),revealCanonicalRowAtStickyOffset=b((path,{restoreTreeFocus=!0,targetOffset="live-overlay"}={})=>{const scrollElement=scrollRef.current;if(scrollElement==null)return!1;controller.focusPath(path);const visibleIndex=controller.getFocusedIndex();if(visibleIndex<0)return!1;const focusedRow=controller.getVisibleRows(visibleIndex,visibleIndex)[0]??null;if(focusedRow==null)return!1;const liveViewportHeight=readMeasuredViewportHeight(scrollElement,resolvedViewportHeight),liveTotalHeight=controller.getVisibleCount()*itemHeight,targetViewportOffset=targetOffset==="sticky-parents"?focusedRow.ancestorPaths.length*itemHeight:computeFileTreeViewLayoutState({controller,itemHeight,overscan,scrollTop:scrollElement.scrollTop,stickyFolders,viewportHeight:liveViewportHeight}).snapshot.sticky.height;return domFocusOwnerRef.current=!0,scrollFocusedRowToViewportOffset(scrollElement,visibleIndex,itemHeight,liveViewportHeight,liveTotalHeight,targetViewportOffset),updateViewportRef.current(),pendingStickyFocusPathRef.current=restoreTreeFocus?path:null,!0},[controller,itemHeight,overscan,resolvedViewportHeight,stickyFolders]),shouldSuppressContextMenu=()=>isScrollingRef.current===!0||touchLongPressTimerRef.current!=null||touchDragActiveRef.current===!0,requestDragAnimationFrame=callback=>typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(()=>{callback()}):window.setTimeout(callback,16),cancelDragAnimationFrame=handle=>{if(handle!=null){if(typeof window.cancelAnimationFrame=="function"){window.cancelAnimationFrame(handle);return}window.clearTimeout(handle)}},clearDragHoverOpen=()=>{dragHoverOpenTimerRef.current!=null&&(clearTimeout(dragHoverOpenTimerRef.current),dragHoverOpenTimerRef.current=null),dragHoverOpenKeyRef.current=null},clearDragPreview=()=>{dragPreviewRef.current?.remove(),dragPreviewRef.current=null},stopDragAutoScroll=()=>{cancelDragAnimationFrame(dragAutoScrollFrameRef.current),dragAutoScrollFrameRef.current=null,dragPointRef.current=null},mountDragPreview=preview=>{const rootNode=rootRef.current?.getRootNode();if(rootNode instanceof ShadowRoot){rootNode.append(preview);return}document.body.append(preview)},clearTouchDragResources=()=>{touchCleanupRef.current?.(),touchCleanupRef.current=null,touchLongPressTimerRef.current!=null&&(clearTimeout(touchLongPressTimerRef.current),touchLongPressTimerRef.current=null),touchDragActiveRef.current=!1,touchPreviewOffsetRef.current=null,touchStartPointRef.current=null,touchSourceElementRef.current!=null&&(touchSourceElementRef.current.setAttribute("draggable","true"),touchSourceElementRef.current.style.removeProperty("touch-action"),touchSourceElementRef.current=null),clearDragPreview(),clearDragHoverOpen(),stopDragAutoScroll(),dragRowSnapshotRef.current=null},syncDropTargetFromPoint=(clientX,clientY)=>{const rootNode=rootRef.current?.getRootNode(),nextTarget=resolveDropTargetFromElement(getPointElement(rootNode instanceof ShadowRoot?rootNode:document,clientX,clientY));return controller.setDragTarget(nextTarget),controller.getDragSession()?.target??null},scheduleDragHoverOpen=nextTarget=>{const openDelay=controller.getDragAndDropConfig()?.openOnDropDelay??800;if(nextTarget==null||nextTarget.kind!=="directory"||nextTarget.directoryPath==null||openDelay<=0){clearDragHoverOpen();return}const targetItem=controller.getItem(nextTarget.directoryPath),directoryItem=isFileTreeDirectoryHandle(targetItem)?targetItem:null;if(directoryItem==null||directoryItem.isExpanded()){clearDragHoverOpen();return}const nextKey=`${nextTarget.directoryPath}::${nextTarget.flattenedSegmentPath??""}`;dragHoverOpenKeyRef.current!==nextKey&&(clearDragHoverOpen(),dragHoverOpenKeyRef.current=nextKey,dragHoverOpenTimerRef.current=setTimeout(()=>{const currentTarget=controller.getDragSession()?.target;currentTarget?.kind!=="directory"||currentTarget.directoryPath!==nextTarget.directoryPath||currentTarget.flattenedSegmentPath!==nextTarget.flattenedSegmentPath||directoryItem.expand()},openDelay))},runDragAutoScroll=()=>{dragAutoScrollFrameRef.current=null;const dragPoint=dragPointRef.current,scrollElement=scrollRef.current;if(dragPoint==null||scrollElement==null||controller.getDragSession()==null)return;const scrollRect=scrollElement.getBoundingClientRect(),scrollDelta=getDragEdgeScrollDelta(dragPoint.clientY,scrollRect);if(scrollDelta===0)return;const maxScrollTop=Math.max(0,scrollElement.scrollHeight-scrollElement.clientHeight),boundedScrollTop=Math.max(0,Math.min(maxScrollTop,scrollElement.scrollTop+scrollDelta));boundedScrollTop!==scrollElement.scrollTop&&(scrollElement.scrollTop=boundedScrollTop,updateViewportRef.current()),scheduleDragHoverOpen(syncDropTargetFromPoint(dragPoint.clientX,dragPoint.clientY)),dragAutoScrollFrameRef.current=requestDragAnimationFrame(runDragAutoScroll)},updateDragPoint=(clientX,clientY)=>{dragPointRef.current={clientX,clientY},dragAutoScrollFrameRef.current??=requestDragAnimationFrame(runDragAutoScroll)},handleRowDragStart=(event,row,targetPath)=>{const dragSource=event.currentTarget;if(dragSource!=null){if(clearTouchDragResources(),clearDragPreview(),clearDragHoverOpen(),stopDragAutoScroll(),controller.startDrag(targetPath)===!1){event.preventDefault();return}if(dragRowSnapshotRef.current=row,event.dataTransfer!=null&&(event.dataTransfer.effectAllowed="move",event.dataTransfer.dropEffect="move",event.dataTransfer.setData("text/plain",targetPath),shouldUseCustomPointerDragImage())){const preview=createDragPreviewElement(dragSource),rect=dragSource.getBoundingClientRect();Object.assign(preview.style,{height:`${rect.height}px`,opacity:"0.85",transform:"translate3d(-9999px, 0px, 0)",width:`${rect.width}px`}),mountDragPreview(preview),dragPreviewRef.current=preview,event.dataTransfer.setDragImage(preview,Math.max(0,event.clientX-rect.left),Math.max(0,event.clientY-rect.top))}}},handleRowDragEnd=()=>{clearDragPreview(),clearDragHoverOpen(),stopDragAutoScroll(),dragRowSnapshotRef.current=null,controller.cancelDrag()},handleRowTouchStart=(event,row,targetPath)=>{if(touchLongPressTimerRef.current!=null||touchDragActiveRef.current)return;const touch=event.touches[0],dragSource=event.currentTarget;if(touch==null||dragSource==null)return;touchStartPointRef.current={clientX:touch.clientX,clientY:touch.clientY},touchSourceElementRef.current=dragSource,dragSource.setAttribute("draggable","false");const clearPendingTouchStart=(options={})=>{const restoreNativeDraggable=options.restoreNativeDraggable??!touchDragActiveRef.current;touchLongPressTimerRef.current!=null&&(clearTimeout(touchLongPressTimerRef.current),touchLongPressTimerRef.current=null),document.removeEventListener("touchmove",handlePendingTouchMove),document.removeEventListener("touchend",handlePendingTouchEnd),document.removeEventListener("touchcancel",handlePendingTouchEnd),touchCleanupRef.current===clearPendingTouchStart&&(touchCleanupRef.current=null),restoreNativeDraggable&&(dragSource.setAttribute("draggable","true"),touchSourceElementRef.current===dragSource&&(touchSourceElementRef.current=null),touchStartPointRef.current=null)},handlePendingTouchMove=moveEvent=>{const moveTouch=moveEvent.touches[0],startPoint=touchStartPointRef.current;if(moveTouch==null||startPoint==null)return;const deltaX=moveTouch.clientX-startPoint.clientX,deltaY=moveTouch.clientY-startPoint.clientY;deltaX*deltaX+deltaY*deltaY<=TOUCH_LONG_PRESS_MOVE_THRESHOLD*TOUCH_LONG_PRESS_MOVE_THRESHOLD||clearPendingTouchStart()},handlePendingTouchEnd=()=>{clearPendingTouchStart()};document.addEventListener("touchmove",handlePendingTouchMove,{passive:!0}),document.addEventListener("touchend",handlePendingTouchEnd),document.addEventListener("touchcancel",handlePendingTouchEnd),touchCleanupRef.current=clearPendingTouchStart,touchLongPressTimerRef.current=setTimeout(()=>{if(clearPendingTouchStart({restoreNativeDraggable:!1}),controller.startDrag(targetPath)===!1){dragSource.setAttribute("draggable","true"),touchSourceElementRef.current===dragSource&&(touchSourceElementRef.current=null),touchStartPointRef.current=null;return}touchDragActiveRef.current=!0,touchSourceElementRef.current=dragSource,dragSource.setAttribute("draggable","false"),dragSource.style.setProperty("touch-action","none"),dragRowSnapshotRef.current=row;const rect=dragSource.getBoundingClientRect(),preview=createDragPreviewElement(dragSource);Object.assign(preview.style,{height:`${rect.height}px`,opacity:"0.85",transform:`translate3d(${rect.left}px, ${rect.top}px, 0)`,width:`${rect.width}px`}),mountDragPreview(preview),dragPreviewRef.current=preview,touchPreviewOffsetRef.current={x:touch.clientX-rect.left,y:touch.clientY-rect.top};const handleActiveTouchMove=moveEvent=>{const moveTouch=moveEvent.touches[0];if(moveTouch==null)return;moveEvent.preventDefault();const previewOffset=touchPreviewOffsetRef.current;previewOffset!=null&&dragPreviewRef.current!=null&&(dragPreviewRef.current.style.transform=`translate3d(${moveTouch.clientX-previewOffset.x}px, ${moveTouch.clientY-previewOffset.y}px, 0)`),scheduleDragHoverOpen(syncDropTargetFromPoint(moveTouch.clientX,moveTouch.clientY)),updateDragPoint(moveTouch.clientX,moveTouch.clientY)},handleActiveTouchEnd=endEvent=>{const endTouch=endEvent.changedTouches[0];endTouch!=null&&syncDropTargetFromPoint(endTouch.clientX,endTouch.clientY),controller.completeDrag(),clearTouchDragResources()},handleActiveTouchCancel=()=>{controller.cancelDrag(),clearTouchDragResources()};touchCleanupRef.current=()=>{document.removeEventListener("touchmove",handleActiveTouchMove),document.removeEventListener("touchend",handleActiveTouchEnd),document.removeEventListener("touchcancel",handleActiveTouchCancel)},document.addEventListener("touchmove",handleActiveTouchMove,{passive:!1}),document.addEventListener("touchend",handleActiveTouchEnd),document.addEventListener("touchcancel",handleActiveTouchCancel)},TOUCH_LONG_PRESS_DELAY)},handleTreeKeyDown=event=>{if(contextMenuState!=null){if(event.key==="Escape"){closeContextMenu(),event.preventDefault(),event.stopPropagation();return}BLOCKED_CONTEXT_MENU_NAV_KEYS.has(event.key)&&(event.preventDefault(),event.stopPropagation());return}if(renameView.isActive()){if(event.isComposing||event.keyCode===229)return;if(event.key==="Escape")renameView.cancel();else if(event.key==="Enter")renameView.commit();else return;setLastContextMenuInteraction("focus"),setControllerRevision(revision=>revision+1),event.preventDefault(),event.stopPropagation();return}if(renamingEnabled&&event.key==="F2"){startRenameFromPath(focusedPath??void 0),event.preventDefault(),event.stopPropagation();return}if(isSearchOpen){if(event.key==="Escape")restoreTreeFocusAfterSearchCloseRef.current=!1,restoreTreeFocusViewportOffsetRef.current=null,controller.closeSearch();else if(event.key==="Enter"){const currentFocusedPath=controller.getFocusedPath();currentFocusedPath!=null&&controller.selectOnlyPath(currentFocusedPath);const scrollElement2=scrollRef.current,viewportHeight=readMeasuredViewportHeight(scrollElement2,resolvedViewportHeight);restoreTreeFocusViewportOffsetRef.current=focusedIndex<0||scrollElement2==null?null:Math.max(0,Math.min(focusedIndex*itemHeight-scrollElement2.scrollTop,Math.max(0,viewportHeight-itemHeight))),restoreTreeFocusAfterSearchCloseRef.current=!0,controller.closeSearch()}else if(event.key==="ArrowDown")controller.focusNextSearchMatch();else if(event.key==="ArrowUp")controller.focusPreviousSearchMatch();else return;setLastContextMenuInteraction("focus"),setControllerRevision(revision=>revision+1),event.preventDefault(),event.stopPropagation();return}if(searchEnabled&&isSearchOpenSeedKey(event)){controller.openSearch(event.key),setControllerRevision(revision=>revision+1),event.preventDefault(),event.stopPropagation();return}const isKeyboardContextMenuRequest=contextMenuEnabled&&isContextMenuOpenKey(event),shouldInspectStickyKeyboardState=canKeyUseStickyKeyboardState(event,contextMenuEnabled),activeTreeElement=shouldInspectStickyKeyboardState&&rootRef.current!=null?getActiveTreeElement(rootRef.current):null,mountedStickyRowPathSet=shouldInspectStickyKeyboardState?new Set(getMountedStickyRowPaths(rootRef.current)):new Set,activeStickyFocusPath=activeTreeElement?.dataset.fileTreeStickyPath??null,activeStickyRowOwnsFocus=activeTreeElement?.dataset.fileTreeStickyRow==="true"&&activeStickyFocusPath!=null;if(activeStickyRowOwnsFocus&&activeStickyFocusPath!==focusedPath&&mountedStickyRowPathSet.has(activeStickyFocusPath)){const scrollElement2=scrollRef.current;preserveStickyKeyboardFocusAtScrollTop(activeStickyFocusPath,scrollElement2?.scrollTop??null),controller.focusPath(activeStickyFocusPath)}const effectiveFocusedPath=controller.getFocusedPath(),effectiveFocusedIndex=controller.getFocusedIndex(),focusedItem=controller.getFocusedItem();if(focusedItem==null)return;const focusedDirectoryItem=isFileTreeDirectoryHandle(focusedItem)?focusedItem:null,startedFromStickyRow=effectiveFocusedPath!=null&&(stickyRowPathSet.has(effectiveFocusedPath)||activeStickyRowOwnsFocus&&activeStickyFocusPath===effectiveFocusedPath&&mountedStickyRowPathSet.has(effectiveFocusedPath)),shouldPreserveLocalStickyFocusMove=event.key==="ArrowDown"||event.key==="ArrowUp"||event.key==="ArrowRight"&&focusedDirectoryItem!=null&&focusedDirectoryItem.isExpanded(),shouldRestoreCollapsedStickyFocusViewport=event.key==="ArrowLeft"&&startedFromStickyRow&&focusedDirectoryItem!=null&&focusedDirectoryItem.isExpanded(),scrollElement=scrollRef.current;let handled=!0;if(event.shiftKey&&event.key==="ArrowDown")controller.extendSelectionFromFocused(1);else if(event.shiftKey&&event.key==="ArrowUp")controller.extendSelectionFromFocused(-1);else if(isKeyboardContextMenuRequest&&effectiveFocusedPath!=null&&effectiveFocusedIndex>=0){const focusedRow=controller.getVisibleRows(effectiveFocusedIndex,effectiveFocusedIndex)[0]??null,focusedButton=getContextMenuAnchorButton(effectiveFocusedPath,stickyRowButtonRefs.current,rowButtonRefs.current);focusedRow==null||focusedButton==null?handled=!1:openContextMenuForRow(focusedRow,effectiveFocusedPath)}else if((event.ctrlKey||event.metaKey)&&isSpaceSelectionKey(event))controller.toggleFocusedSelection();else if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==="a")controller.selectAllVisiblePaths();else switch(event.key){case"ArrowDown":controller.focusNextItem();break;case"ArrowUp":controller.focusPreviousItem();break;case"ArrowRight":focusedDirectoryItem==null||focusedDirectoryItem.isExpanded()?controller.focusNextItem():focusedDirectoryItem.expand();break;case"ArrowLeft":focusedDirectoryItem!=null&&focusedDirectoryItem.isExpanded()?focusedDirectoryItem.collapse():controller.focusParentItem();break;case"Home":controller.focusFirstItem();break;case"End":controller.focusLastItem();break;default:handled=!1}if(!handled)return;setLastContextMenuInteraction("focus");const nextFocusedPath=controller.getFocusedPath(),nextFocusedPathIsMountedSticky=nextFocusedPath!=null&&(stickyRowPathSet.has(nextFocusedPath)||mountedStickyRowPathSet.has(nextFocusedPath)),stickyKeyboardMoveLandsOnDifferentStickyRow=shouldPreserveLocalStickyFocusMove&&nextFocusedPath!==effectiveFocusedPath,stickyKeyboardMenuStaysOnStickyRow=isKeyboardContextMenuRequest&&activeStickyRowOwnsFocus&&activeStickyFocusPath===effectiveFocusedPath&&nextFocusedPath===effectiveFocusedPath;if((startedFromStickyRow||stickyKeyboardMenuStaysOnStickyRow)&&nextFocusedPath!=null&&(stickyKeyboardMoveLandsOnDifferentStickyRow&&nextFocusedPathIsMountedSticky||stickyKeyboardMenuStaysOnStickyRow))preserveStickyKeyboardFocusAtScrollTop(nextFocusedPath,scrollElement?.scrollTop??null),domFocusOwnerRef.current=!0,setActiveItemPath(previousPath=>previousPath===nextFocusedPath?previousPath:nextFocusedPath);else{const stickyArrowUpExitsStack=event.key==="ArrowUp"&&startedFromStickyRow&&nextFocusedPath!==effectiveFocusedPath;nextFocusedPath!=null&&(stickyArrowUpExitsStack||shouldRestoreCollapsedStickyFocusViewport&&nextFocusedPath===effectiveFocusedPath)?(restoreStickyKeyboardViewportOffset(nextFocusedPath,getStickyKeyboardViewportOffset(rootRef.current,scrollElement,activeTreeElement,effectiveFocusedPath,itemHeight,stickyOverlayHeight,resolvedViewportHeight)),domFocusOwnerRef.current=!0,setActiveItemPath(previousPath=>previousPath===nextFocusedPath?previousPath:nextFocusedPath)):clearPendingStickyKeyboardState()}setControllerRevision(revision=>revision+1),event.preventDefault(),event.stopPropagation()};A(()=>{if(!(!searchEnabled||!isSearchOpen)){if(skipInitialSearchAutoFocusRef.current){skipInitialSearchAutoFocusRef.current=!1;return}focusElement(searchInputRef.current)}},[isSearchOpen,searchEnabled]),A(()=>{const input=renameInputRef.current;switch(classifyFileTreeRenameHandoff({hasRenderedInput:input!=null,previousRenamingPath:previousRenamingPathRef.current,renamingPath})){case"reset":previousRenamingPathRef.current=null;return;case"reveal-canonical":renamingPath!=null&&revealCanonicalRowAtStickyOffset(renamingPath,{restoreTreeFocus:!1,targetOffset:"live-overlay"});return;case"ignore":return;case"focus-input":input!=null&&(pendingStickyFocusPathRef.current=null,previousRenamingPathRef.current=renamingPath,focusElement(input),input.select());return}},[range2.end,range2.start,renamingPath,revealCanonicalRowAtStickyOffset,stickyRowPathSet]),A(()=>{const rootElement=rootRef.current;if(rootElement==null)return;let nullFocusOutTimer=null;const clearNullFocusOutTimer=()=>{nullFocusOutTimer!=null&&(clearTimeout(nullFocusOutTimer),nullFocusOutTimer=null)},updateActiveItemPath=()=>{const nextActiveItemPath=getActiveTreeElement(rootElement)?.dataset.itemPath??null;setActiveItemPath(previousPath=>previousPath===nextActiveItemPath?previousPath:nextActiveItemPath)},onFocusIn=()=>{clearNullFocusOutTimer(),domFocusOwnerRef.current=!0,updateActiveItemPath()},onFocusOut=event=>{const nextTarget=event.relatedTarget;if(nextTarget==null){clearNullFocusOutTimer(),nullFocusOutTimer=setTimeout(()=>{if(nullFocusOutTimer=null,getActiveTreeElement(rootElement)!=null){updateActiveItemPath();return}domFocusOwnerRef.current=!1,setActiveItemPath(null)},0);return}if(!(nextTarget instanceof Node)||!rootElement.contains(nextTarget)){clearNullFocusOutTimer(),domFocusOwnerRef.current=!1,setActiveItemPath(null);return}const nextActiveItemPath=nextTarget instanceof HTMLElement?nextTarget.dataset.itemPath??null:null;setActiveItemPath(previousPath=>previousPath===nextActiveItemPath?previousPath:nextActiveItemPath)};return rootElement.addEventListener("focusin",onFocusIn),rootElement.addEventListener("focusout",onFocusOut),()=>{clearNullFocusOutTimer(),rootElement.removeEventListener("focusin",onFocusIn),rootElement.removeEventListener("focusout",onFocusOut)}},[]),A(()=>{const rootElement=rootRef.current;rootElement!=null&&(layoutSnapshot.physical.scrollTop<=0?rootElement.dataset.scrollAtTop="true":delete rootElement.dataset.scrollAtTop)},[layoutSnapshot.physical.scrollTop]),A(()=>{let scrollTimer=null;const scrollElement=scrollRef.current,listElement=listRef.current,rootElement=rootRef.current;if(scrollElement==null)return;measuredViewportHeightRef.current=readMeasuredViewportHeight(scrollElement,initialViewportHeight);const update=()=>{const nextItemCount=controller.getVisibleCount(),nextViewportHeight=getCachedViewportHeight(measuredViewportHeightRef.current,initialViewportHeight),maxScrollTop=Math.max(0,nextItemCount*itemHeight-nextViewportHeight);scrollElement.scrollTop>maxScrollTop&&(scrollElement.scrollTop=maxScrollTop),setLayoutState(computeFileTreeViewLayoutState({controller,itemHeight,overscan,scrollTop:Math.min(scrollElement.scrollTop,maxScrollTop),stickyFolders,viewportHeight:nextViewportHeight}))};if(!initialFocusedScrollAppliedRef.current){initialFocusedScrollAppliedRef.current=!0;const initialFocusedIndex=controller.getFocusedIndex();if(initialFocusedIndex>=0){const initialViewportHeightPx=getCachedViewportHeight(measuredViewportHeightRef.current,initialViewportHeight),initialFocusedRow=controller.getVisibleRows(initialFocusedIndex,initialFocusedIndex)[0]??null;scrollFocusedRowIntoView(scrollElement,initialFocusedIndex,itemHeight,initialViewportHeightPx,stickyFolders&&initialFocusedRow!=null?Math.max(0,Math.min(initialFocusedRow.ancestorPaths.length*itemHeight,Math.max(0,initialViewportHeightPx-itemHeight))):0)}}updateViewportRef.current=update;const unsubscribe=controller.subscribe(()=>{shouldBumpControllerRevision(hasSeenInitialControllerSnapshotRef)&&setControllerRevision(revision=>revision+1),update()}),markScrolling=()=>{debugDisableScrollSuppressionRef.current!==!0&&(listElement!=null&&(listElement.dataset.isScrolling??=""),rootElement!=null&&(rootElement.dataset.isScrolling??=""),isScrollingRef.current=!0,scrollTimer!=null&&clearTimeout(scrollTimer),scrollTimer=setTimeout(()=>{listElement!=null&&delete listElement.dataset.isScrolling,rootElement!=null&&delete rootElement.dataset.isScrolling,isScrollingRef.current=!1,setScrollSettledRevision(revision=>revision+1),scrollTimer=null},50))};let overlayRevealTimer=null;const clearOverlayReveal=()=>{rootElement!=null&&delete rootElement.dataset.overlayReveal,overlayRevealTimer!=null&&(clearTimeout(overlayRevealTimer),overlayRevealTimer=null)},markOverlayReveal=()=>{rootElement==null||debugDisableScrollSuppressionRef.current===!0||scrollElement.scrollTop>0||(rootElement.dataset.overlayReveal="true",overlayRevealTimer!=null&&clearTimeout(overlayRevealTimer),overlayRevealTimer=setTimeout(()=>{clearOverlayReveal()},200))},onScroll=()=>{if(update(),scrollElement.scrollTop>0&&clearOverlayReveal(),contextMenuStateRef.current!=null&&isScrollingRef.current&&closeContextMenuRef.current(),debugDisableScrollSuppressionRef.current===!0){isScrollingRef.current=!1;return}setContextHoverPath(previousPath=>previousPath==null?previousPath:null),markScrolling()},onPreScroll=()=>{markScrolling(),markOverlayReveal()},SCROLL_KEYS=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown","Home","End"," ","Spacebar"]),onKeyDownPreScroll=event=>{SCROLL_KEYS.has(event.key)&&onPreScroll()};scrollElement.addEventListener("scroll",onScroll,{passive:!0}),scrollElement.addEventListener("wheel",onPreScroll,{passive:!0}),scrollElement.addEventListener("touchmove",onPreScroll,{passive:!0}),scrollElement.addEventListener("keydown",onKeyDownPreScroll);const resizeObserver=typeof ResizeObserver<"u"?new ResizeObserver(entries=>{measuredViewportHeightRef.current=(entries[0]==null?null:getResizeObserverViewportHeight(entries[0]))??readMeasuredViewportHeight(scrollElement,initialViewportHeight),update()}):null;return resizeObserver?.observe(scrollElement),()=>{updateViewportRef.current=()=>{},unsubscribe(),scrollElement.removeEventListener("scroll",onScroll),scrollElement.removeEventListener("wheel",onPreScroll),scrollElement.removeEventListener("touchmove",onPreScroll),scrollElement.removeEventListener("keydown",onKeyDownPreScroll),scrollTimer!=null&&clearTimeout(scrollTimer),overlayRevealTimer!=null&&clearTimeout(overlayRevealTimer),listElement!=null&&delete listElement.dataset.isScrolling,rootElement!=null&&(delete rootElement.dataset.isScrolling,delete rootElement.dataset.overlayReveal),isScrollingRef.current=!1,measuredViewportHeightRef.current=null,resizeObserver?.disconnect()}},[controller,initialViewportHeight,itemHeight,overscan,stickyFolders]),A(()=>{contextMenuEnabled||contextMenuState==null||closeContextMenu(!1)},[closeContextMenu,contextMenuEnabled,contextMenuState]);const activeContextMenuKey=q(()=>contextMenuState==null?null:`${contextMenuState.path}::${contextMenuState.source}`,[contextMenuState]);A(()=>{if(activeContextMenuKey==null){slotHost?.clearSlotContent(CONTEXT_MENU_SLOT_NAME);return}const currentState=contextMenuStateRef.current;if(currentState==null)return;const anchorElement=contextMenuTriggerRef.current??contextMenuAnchorRef.current;if(anchorElement==null)return;const context={anchorElement,anchorRect:currentState.anchorRect??serializeAnchorRect(anchorElement.getBoundingClientRect()),close:options=>{closeContextMenuRef.current(options?.restoreFocus??!0)},restoreFocus:()=>{shouldRestoreContextMenuFocusRef.current&&restoreFocusToTreeRef.current(contextMenuStateRef.current?.path??null)}},menuContent=composition?.contextMenu?.render?.(currentState.item,context)??null;return slotHost?.setSlotContent(CONTEXT_MENU_SLOT_NAME,menuContent),composition?.contextMenu?.onOpen?.(currentState.item,context),focusFirstMenuElement(menuContent),queueMicrotask(()=>{menuContent==null||!menuContent.isConnected||document.activeElement===menuContent&&focusFirstMenuElement(menuContent)}),()=>{slotHost?.clearSlotContent(CONTEXT_MENU_SLOT_NAME)}},[activeContextMenuKey,composition?.contextMenu,slotHost]),A(()=>{contextMenuState!=null&&controller.getItem(contextMenuState.path)==null&&closeContextMenu()},[closeContextMenu,contextMenuState,controller]),A(()=>{if(contextMenuState==null)return;const rootNode=rootRef.current?.getRootNode(),host=rootNode instanceof ShadowRoot?rootNode.host:rootRef.current,onPointerDown=event=>{const target=event.target;target instanceof Node&&(isEventInContextMenu(event)||contextMenuAnchorRef.current?.contains(target)!==!0&&host?.contains(target)!==!0&&closeContextMenu())},onKeyDown=event=>{event.key==="Escape"&&(event.preventDefault(),event.stopPropagation(),closeContextMenu())};return document.addEventListener("mousedown",onPointerDown,!0),document.addEventListener("keydown",onKeyDown,!0),()=>{document.removeEventListener("mousedown",onPointerDown,!0),document.removeEventListener("keydown",onKeyDown,!0)}},[closeContextMenu,contextMenuState]),A(()=>{const scrollElement=scrollRef.current,rootElement=rootRef.current;if(scrollElement==null||rootElement==null){previousFocusedPathRef.current=focusedPath;return}const focusedButton=focusedPath==null?null:rowButtonRefs.current.get(focusedPath)??null,activeTreeElement=getActiveTreeElement(rootElement),activeTreeElementPath=activeTreeElement?.dataset.itemPath??null,renameInputOwnsFocus=isRenaming&&renameInputRef.current===activeTreeElement,searchInputOwnsFocus=searchEnabled&&searchInputRef.current===activeTreeElement,shouldRestoreTreeFocusAfterSearchClose=restoreTreeFocusAfterSearchCloseRef.current&&!isSearchOpen,preservedViewportOffset=restoreTreeFocusViewportOffsetRef.current??0,pendingStickyFocusPath=pendingStickyFocusPathRef.current,pendingStickyKeyboardFocusPath=pendingStickyKeyboardFocusPathRef.current,pendingStickyKeyboardViewportOffset=pendingStickyKeyboardViewportOffsetRef.current,pendingStickyKeyboardScrollTop=pendingStickyKeyboardScrollTopRef.current,focusWithinTree=activeTreeElement!=null,shouldOwnDomFocus=domFocusOwnerRef.current||focusWithinTree,focusedPathChanged=previousFocusedPathRef.current!==focusedPath,shouldPreserveStickyKeyboardFocusViewport=pendingStickyKeyboardFocusPath!=null&&pendingStickyKeyboardFocusPath===focusedPath&&focusedPath!=null;let shouldSuppressDomFocusForScrollRequest=!1,shouldUpdateViewportForScrollRequest=!1;if(scrollRequest!=null&&scrollRequest.id!==processedScrollRequestIdRef.current){processedScrollRequestIdRef.current=scrollRequest.id;const scrollRequestIndex=scrollRequest.visibleIndex,scrollRequestRow=controller.getVisibleRows(scrollRequestIndex,scrollRequestIndex)[0]??null;if(scrollRequestRow!=null){const scrollRequestTopInset=stickyFolders?Math.max(0,Math.min(scrollRequestRow.ancestorPaths.length*itemHeight,Math.max(0,resolvedViewportHeight-itemHeight))):stickyOverlayHeight;shouldSuppressDomFocusForScrollRequest=!0,shouldUpdateViewportForScrollRequest=scrollFocusedRowToOffset(scrollElement,scrollRequestIndex,itemHeight,resolvedViewportHeight,totalScrollableHeight,scrollRequest.offset,scrollRequestTopInset)}controller.clearScrollRequest(scrollRequest.id)}const shouldRestoreFocusedRowViewportOffset=!shouldSuppressDomFocusForScrollRequest&&shouldRestoreTreeFocusAfterSearchClose&&scrollFocusedRowToViewportOffset(scrollElement,focusedIndex,itemHeight,resolvedViewportHeight,totalScrollableHeight,preservedViewportOffset),shouldRestoreStickyFocusedRowViewportOffset=!shouldSuppressDomFocusForScrollRequest&&pendingStickyFocusPath!=null&&pendingStickyFocusPath===focusedPath&&scrollFocusedRowToViewportOffset(scrollElement,focusedIndex,itemHeight,resolvedViewportHeight,totalScrollableHeight,stickyOverlayHeight),shouldRestoreStickyKeyboardViewportOffset=!shouldSuppressDomFocusForScrollRequest&&pendingStickyKeyboardViewportOffset!=null&&pendingStickyKeyboardViewportOffset.path===focusedPath&&scrollFocusedRowToViewportOffset(scrollElement,focusedIndex,itemHeight,resolvedViewportHeight,totalScrollableHeight,pendingStickyKeyboardViewportOffset.viewportOffset),shouldRestoreStickyKeyboardScrollTop=!shouldSuppressDomFocusForScrollRequest&&pendingStickyKeyboardScrollTop!=null&&pendingStickyKeyboardScrollTop.path===focusedPath&&scrollElement.scrollTop!==pendingStickyKeyboardScrollTop.scrollTop;if(shouldRestoreStickyKeyboardScrollTop&&(scrollElement.scrollTop=pendingStickyKeyboardScrollTop.scrollTop),(shouldRestoreStickyKeyboardScrollTop||shouldUpdateViewportForScrollRequest||shouldRestoreStickyFocusedRowViewportOffset||shouldRestoreStickyKeyboardViewportOffset||shouldRestoreFocusedRowViewportOffset||shouldOwnDomFocus&&focusedPathChanged&&pendingStickyFocusPath!==focusedPath&&!shouldPreserveStickyKeyboardFocusViewport&&scrollFocusedRowIntoView(scrollElement,focusedIndex,itemHeight,resolvedViewportHeight,stickyOverlayHeight))&&updateViewportRef.current(),shouldSuppressDomFocusForScrollRequest){previousFocusedPathRef.current=focusedPath;return}if(!shouldOwnDomFocus){previousFocusedPathRef.current=focusedPath;return}if(renameInputOwnsFocus){previousFocusedPathRef.current=focusedPath;return}if(searchInputOwnsFocus&&!shouldRestoreTreeFocusAfterSearchClose){previousFocusedPathRef.current=focusedPath;return}if(focusedButton==null){shouldRestoreTreeFocusAfterSearchClose&&focusedIndex>=0&&(scrollFocusedRowToViewportOffset(scrollElement,focusedIndex,itemHeight,resolvedViewportHeight,totalScrollableHeight,preservedViewportOffset),updateViewportRef.current()),previousFocusedPathRef.current=focusedPath;return}(focusedPathChanged||shouldRestoreTreeFocusAfterSearchClose||pendingStickyFocusPath===focusedPath||pendingStickyKeyboardFocusPath===focusedPath||pendingStickyKeyboardViewportOffset?.path===focusedPath||pendingStickyKeyboardScrollTop?.path===focusedPath||activeTreeElementPath==null||activeTreeElementPath!==focusedPath)&&(focusElement(focusedButton),pendingStickyFocusPath===focusedPath&&(pendingStickyFocusPathRef.current=null),pendingStickyKeyboardFocusPath===focusedPath&&(pendingStickyKeyboardFocusPathRef.current=null),pendingStickyKeyboardViewportOffset?.path===focusedPath&&(pendingStickyKeyboardViewportOffsetRef.current=null),pendingStickyKeyboardScrollTop?.path===focusedPath&&(pendingStickyKeyboardScrollTopRef.current=null),restoreTreeFocusAfterSearchCloseRef.current=!1,restoreTreeFocusViewportOffsetRef.current=null),previousFocusedPathRef.current=focusedPath},[controller,focusedIndex,focusedPath,focusedRowIsMounted,itemHeight,isRenaming,isSearchOpen,range2,resolvedViewportHeight,searchEnabled,scrollRequest,stickyFolders,stickyOverlayHeight,totalScrollableHeight,visibleRows]);const focusedRowIsVisible=focusedIndex>=0&&focusedIndex>=layoutSnapshot.visible.startIndex&&focusedIndex<=layoutSnapshot.visible.endIndex,focusedRowIsSticky=focusedPath!=null&&stickyRows.some(entry=>getFileTreeRowPath(entry.row)===focusedPath),focusedRowHasVisibleAnchor=focusedRowIsVisible||focusedRowIsSticky,focusTriggerPath=contextMenuButtonTriggerEnabled&&domFocusOwnerRef.current===!0&&focusedRowHasVisibleAnchor?focusedPath:null,pointerTriggerPath=lastContextMenuInteraction==="pointer"?contextHoverPath:null,triggerPath=contextMenuState?.path??debugContextMenuTriggerPathRef.current??pointerTriggerPath??focusTriggerPath??contextHoverPath,isPointerContextMenuOpen=contextMenuState?.source==="right-click";A(()=>{isScrollingRef.current&&contextMenuState==null||updateTriggerPosition(getTriggerAnchorButton(triggerPath))},[contextMenuState,getTriggerAnchorButton,range2,resolvedViewportHeight,scrollSettledRevision,stickyRows,triggerPath,updateTriggerPosition,visibleRows]);const handleTreePointerOver=b(event=>{if(isScrollingRef.current||isEventInContextMenu(event))return;const target=event.target;if(!(target instanceof HTMLElement)||target.closest?.('[data-type="context-menu-trigger"]')!=null)return;const stickyRowButton=target.closest?.('[data-file-tree-sticky-row="true"]'),rowButton=target.closest?.('[data-type="item"]'),nextPath=stickyRowButton instanceof HTMLElement?stickyRowButton.dataset.fileTreeStickyPath??null:rowButton instanceof HTMLElement?rowButton.dataset.itemPath??null:null;nextPath!=null&&setLastContextMenuInteraction(previousMode=>previousMode==="pointer"?previousMode:"pointer"),setContextHoverPath(previousPath=>previousPath===nextPath?previousPath:nextPath)},[]),handleTreePointerLeave=b(()=>{setContextHoverPath(null)},[]);A(()=>{if(!dragAndDropEnabled)return;const handleWindowDragEnd=()=>{clearTouchDragResources(),controller.cancelDrag()};return window.addEventListener("dragend",handleWindowDragEnd),()=>{window.removeEventListener("dragend",handleWindowDragEnd),clearTouchDragResources(),controller.cancelDrag()}},[controller,dragAndDropEnabled]);const handleTreeDragOver=event=>{if(!dragAndDropEnabled||controller.getDragSession()==null||touchDragActiveRef.current)return;const nextTarget=resolveDropTargetFromElement(event.target instanceof HTMLElement?event.target:null);controller.setDragTarget(nextTarget),scheduleDragHoverOpen(controller.getDragSession()?.target??null),updateDragPoint(event.clientX,event.clientY),event.dataTransfer!=null&&(event.dataTransfer.dropEffect="move"),event.preventDefault()},handleTreeDragLeave=event=>{if(!dragAndDropEnabled||controller.getDragSession()==null||touchDragActiveRef.current)return;const nextTarget=event.relatedTarget;nextTarget instanceof Node&&rootRef.current?.contains(nextTarget)===!0||(clearDragHoverOpen(),stopDragAutoScroll(),controller.setDragTarget(null))},handleTreeDrop=event=>{!dragAndDropEnabled||controller.getDragSession()==null||touchDragActiveRef.current||(event.preventDefault(),syncDropTargetFromPoint(event.clientX,event.clientY),controller.completeDrag(),clearDragPreview(),clearDragHoverOpen(),stopDragAutoScroll(),dragRowSnapshotRef.current=null)},windowHeight=layoutSnapshot.window.height,windowOffsetTop=layoutSnapshot.window.offsetTop,windowStickyTopInset=Math.min(0,resolvedViewportHeight-windowHeight),windowStickyBottomInset=Math.min(0,resolvedViewportHeight-windowHeight-stickyOverlayHeight),shouldRenderParkedFocusedRow=activeItemPath===focusedPath||restoreTreeFocusAfterSearchCloseRef.current,parkedFocusedRow=focusedPath!=null&&shouldRenderParkedFocusedRow&&!focusedRowIsMounted&&focusedIndex>=0?visibleRows[focusedIndex]??controller.getVisibleRows(focusedIndex,focusedIndex)[0]??null:null,parkedFocusedRowOffset=parkedFocusedRow==null?null:getParkedFocusedRowOffset(focusedIndex,itemHeight,range2,windowHeight),draggedRowSnapshot=dragRowSnapshotRef.current,draggedRowIsMounted=draggedPrimaryPath!=null&&draggedRowSnapshot!=null&&draggedRowSnapshot.path===draggedPrimaryPath&&draggedRowSnapshot.index>=range2.start&&draggedRowSnapshot.index<=range2.end,parkedDraggedRow=draggedPrimaryPath!=null&&draggedRowSnapshot!=null&&draggedRowSnapshot.path===draggedPrimaryPath&&!draggedRowIsMounted&&draggedRowSnapshot.path!==parkedFocusedRow?.path?draggedRowSnapshot:null,parkedDraggedRowOffset=parkedDraggedRow==null?null:getParkedFocusedRowOffset(parkedDraggedRow.index,itemHeight,range2,windowHeight),guideStyleText=getFileTreeGuideStyleText((focusedIndex>=0?visibleRows[focusedIndex]??controller.getVisibleRows(focusedIndex,focusedIndex)[0]??null:null)?.ancestorPaths.at(-1)??null),activeDescendantId=isSearchOpen&&focusedPath!=null?getFileTreeFocusedRowDomId(instanceId,focusedPath,!focusedRowIsMounted):void 0,visualFocusPath=contextMenuState?.path??(isSearchOpen?focusedPath:activeItemPath),visualContextHoverPath=contextMenuState?.path??contextHoverPath,triggerButton=getTriggerAnchorButton(triggerPath),triggerButtonVisible=contextMenuEnabled&&contextMenuButtonTriggerEnabled&&!isPointerContextMenuOpen&&!isRenaming&&triggerButton!=null&&contextMenuAnchorTop!=null&&triggerPath!=null,contextMenuAnchorVisible=contextMenuEnabled&&(triggerButtonVisible||contextMenuState!=null),pointerAnchorRect=contextMenuState?.anchorRect,rowAnchorTop=pointerAnchorRect==null&&triggerButton!=null&&contextMenuAnchorTop!=null&&(contextMenuState!=null||triggerButtonVisible)?contextMenuAnchorTop:null,contextMenuAnchorStyle=pointerAnchorRect!=null?{left:`${pointerAnchorRect.left}px`,position:"fixed",right:"auto",top:`${pointerAnchorRect.top}px`}:rowAnchorTop!=null?{top:`${rowAnchorTop}px`}:void 0,contextMenuTriggerStyle=isPointerContextMenuOpen?{opacity:"0"}:void 0,handleRowClick=b((event,row,targetPath,mode)=>{const plan=computeFileTreeRowClickPlan({event:{ctrlKey:event.ctrlKey,metaKey:event.metaKey,shiftKey:event.shiftKey},isDirectory:row.kind==="directory",isSearchOpen,mode}),shouldToggleDirectory=plan.toggleDirectory&&row.kind==="directory",mountedDirectoryPath=shouldToggleDirectory?controller.resolveMountedDirectoryPathFromInput(targetPath):null;if(shouldToggleDirectory&&mountedDirectoryPath==null)return;const actionTargetPath=mountedDirectoryPath??targetPath;switch(plan.selection.kind){case"range":controller.selectPathRange(actionTargetPath,plan.selection.additive);break;case"toggle":controller.togglePathSelectionFromInput(actionTargetPath);break;case"single":controller.selectOnlyMountedPathFromInput(actionTargetPath);break}const clickedElement=event.currentTarget instanceof HTMLElement?event.currentTarget:null,clickedRowIsVisible=row.index>=layoutSnapshot.visible.startIndex&&row.index<=layoutSnapshot.visible.endIndex,shouldExposeFocusedTrigger=mode==="flow"&&clickedRowIsVisible&&clickedElement!=null&&clickedElement.dataset.itemParked!=="true";controller.focusMountedPathFromInput(actionTargetPath),shouldExposeFocusedTrigger&&(domFocusOwnerRef.current=!0,setActiveItemPath(previousPath=>previousPath===actionTargetPath?previousPath:actionTargetPath),setLastContextMenuInteraction("focus")),shouldToggleDirectory&&controller.toggleMountedDirectoryFromInput(actionTargetPath),plan.closeSearch&&controller.closeSearch(),plan.revealCanonical&&revealCanonicalRowAtStickyOffset(actionTargetPath,{targetOffset:"sticky-parents"})},[controller,isSearchOpen,layoutSnapshot.visible.endIndex,layoutSnapshot.visible.startIndex,revealCanonicalRowAtStickyOffset]),openMenuFromTrigger=()=>{if(isScrollingRef.current||!contextMenuButtonTriggerEnabled||triggerPath==null||triggerButton==null)return;const triggerItem=controller.getItem(triggerPath);triggerItem!=null&&(updateTriggerPosition(triggerButton),shouldRestoreContextMenuFocusRef.current=!0,setContextMenuState({anchorRect:null,item:{kind:triggerItem.isDirectory()?"directory":"file",name:triggerButton.getAttribute("aria-label")??triggerPath,path:triggerItem.getPath()},path:triggerItem.getPath(),source:"button"}))},flowRowFrame={contextHoverPath:visualContextHoverPath,contextMenuButtonTriggerEnabled,contextMenuButtonVisibility,contextMenuEnabled,contextMenuRightClickEnabled,contextMenuTriggerMode,controller,directoriesWithGitChanges,dragAndDropEnabled,draggedPathSet,dragTarget,gitLaneActive,gitStatusByPath,handleRowDragEnd,handleRowDragStart,handleRowTouchStart,ignoredGitDirectories,ignoredInheritanceCache,instanceId,itemHeight,onKeyDown:handleTreeKeyDown,onRowClick:handleRowClick,openContextMenuForRow,registerButton:registerRowButton,registerRenameInput,renameView,renderDecorationForRow,resolveIcon,shouldSuppressContextMenu,visualFocusPath},stickyRowFrame={...flowRowFrame,registerButton:registerStickyRowButton};return u$1("div",{ref:rootRef,id:treeDomId,"data-file-tree-context-menu-button-visibility":contextMenuEnabled&&contextMenuButtonTriggerEnabled?contextMenuButtonVisibility:void 0,"data-file-tree-context-menu-trigger-mode":contextMenuEnabled?contextMenuTriggerMode:void 0,"data-file-tree-has-context-menu-action-lane":contextMenuEnabled&&contextMenuButtonTriggerEnabled?"true":void 0,"data-file-tree-has-git-lane":gitLaneActive?"true":void 0,"data-file-tree-virtualized-root":"true",onDragLeave:dragAndDropEnabled?handleTreeDragLeave:void 0,onDragOver:dragAndDropEnabled?handleTreeDragOver:void 0,onDrop:dragAndDropEnabled?handleTreeDrop:void 0,onKeyDown:handleTreeKeyDown,onPointerLeave:contextMenuEnabled?handleTreePointerLeave:void 0,onPointerOver:contextMenuEnabled?handleTreePointerOver:void 0,role:"tree",tabIndex:-1,style:{outline:"none",position:"relative"},children:[u$1("style",{"data-file-tree-guide-style":"true",dangerouslySetInnerHTML:{__html:guideStyleText}}),u$1("slot",{name:HEADER_SLOT_NAME,"data-type":"header-slot"}),searchEnabled?u$1("div",{"data-file-tree-search-container":!0,"data-open":isSearchOpen?"true":"false",children:u$1("input",{ref:searchInputRef,"aria-activedescendant":activeDescendantId,"aria-controls":treeDomId,placeholder:"Search…","data-file-tree-search-input":!0,"data-file-tree-search-input-fake-focus":fakeSearchFocusActive?"true":void 0,value:searchValue,onBlur:()=>{searchBlurBehavior==="retain"&&!searchInputUserInteractedRef.current||controller.closeSearch()},onFocus:markSearchInputInteracted,onPointerDown:markSearchInputInteracted,onInput:event=>{markSearchInputInteracted();const target=event.currentTarget;controller.setSearch(target.value)}})}):null,u$1("div",{ref:scrollRef,"data-file-tree-virtualized-scroll":"true",children:[stickyFolders&&hasStickyUiMount&&stickyRows.length>0?u$1("div",{"aria-hidden":"true","data-file-tree-sticky-overlay":"true",children:u$1("div",{"data-file-tree-sticky-overlay-content":"true",style:{height:`${overlayRowsHeight}px`},children:stickyRows.map((entry,index)=>renderStyledRow(stickyRowFrame,entry.row,`sticky:${getFileTreeRowPath(entry.row)}`,{mode:"sticky",style:{left:"0",position:"absolute",right:"0",top:`${entry.top}px`,zIndex:`${stickyRows.length-index}`}}))})}):null,u$1("div",{ref:listRef,"data-file-tree-virtualized-list":"true",style:{height:`${totalScrollableHeight}px`},children:[u$1("div",{"data-file-tree-virtualized-sticky-offset":"true","aria-hidden":"true",style:{height:`${windowOffsetTop}px`}}),u$1("div",{"data-file-tree-virtualized-sticky":"true",style:{height:`${windowHeight}px`,top:`${windowStickyTopInset}px`,bottom:`${windowStickyBottomInset}px`},children:[renderRangeChildren(flowRowFrame,range2,stickyRowPathSet),parkedFocusedRow!=null&&parkedFocusedRowOffset!=null?renderStyledRow(flowRowFrame,parkedFocusedRow,`parked:${parkedFocusedRow.path}`,{isParked:!0,style:{left:"0",opacity:"0",pointerEvents:draggedPrimaryPath===parkedFocusedRow.path?"none":void 0,position:"absolute",right:"0",top:`${parkedFocusedRowOffset}px`}}):null,parkedDraggedRow!=null&&parkedDraggedRowOffset!=null?renderStyledRow(flowRowFrame,parkedDraggedRow,`parked-drag:${parkedDraggedRow.path}`,{isParked:!0,style:{left:"0",opacity:"0",pointerEvents:"none",position:"absolute",right:"0",top:`${parkedDraggedRowOffset}px`}}):null]})]})]}),contextMenuEnabled?u$1("div",{ref:contextMenuAnchorRef,"data-type":"context-menu-anchor","data-visible":contextMenuAnchorVisible?"true":"false",style:contextMenuAnchorStyle,children:[u$1("button",{ref:contextMenuTriggerRef,type:"button","data-type":CONTEXT_MENU_TRIGGER_TYPE,"aria-label":"Options","aria-haspopup":"menu","aria-expanded":contextMenuState!=null?"true":"false","data-visible":triggerButtonVisible?"true":"false",onMouseDown:event=>{event.preventDefault()},onClick:event=>{if(event.preventDefault(),event.stopPropagation(),contextMenuState!=null){closeContextMenu();return}openMenuFromTrigger()},tabIndex:-1,style:contextMenuTriggerStyle,children:u$1(Icon,{...resolveIcon("file-tree-icon-ellipsis")})}),contextMenuState!=null?u$1("slot",{name:CONTEXT_MENU_SLOT_NAME}):null]}):null,contextMenuState!=null?u$1("div",{"data-type":"context-menu-wash","aria-hidden":"true",onMouseDownCapture:event=>{event.preventDefault(),closeContextMenu()},onTouchStartCapture:event=>{event.preventDefault(),event.stopPropagation(),closeContextMenu()},onTouchMoveCapture:event=>{event.preventDefault(),event.stopPropagation()},onWheelCapture:event=>{event.preventDefault(),event.stopPropagation()}}):null]})}const fileTreeRenderer={hydrateRoot:(element,props)=>{G(_$1(FileTreeView,props),element)},renderRoot:(element,props)=>{F$1(_$1(FileTreeView,props),element)},unmountRoot:element=>{F$1(null,element)}};function renderFileTreeRoot(element,props){fileTreeRenderer.renderRoot(element,props)}function hydrateFileTreeRoot(element,props){fileTreeRenderer.hydrateRoot(element,props)}function unmountFileTreeRoot(element){fileTreeRenderer.unmountRoot(element)}var FileTreeManagedSlotHost=class{#contentBySlot=new Map;#host=null;clearAll(){for(const content of this.#contentBySlot.values())content.remove();this.#contentBySlot.clear()}clearSlotContent(slotName){const currentContent=this.#getCurrentContent(slotName);currentContent!=null&&(currentContent.remove(),this.#contentBySlot.delete(slotName))}setHost(host){if(this.#host=host,host!=null){this.#adoptExistingManagedContent(host);for(const[slotName,content]of this.#contentBySlot)this.#attachContent(slotName,content)}}setSlotContent(slotName,content){const currentContent=this.#getCurrentContent(slotName);if(currentContent===content){content!=null&&(this.#contentBySlot.set(slotName,content),this.#attachContent(slotName,content));return}if(currentContent?.remove(),content==null){this.#contentBySlot.delete(slotName);return}this.#contentBySlot.set(slotName,content),this.#attachContent(slotName,content)}setSlotHtml(slotName,html){const normalizedHtml=html?.trim()??"";if(normalizedHtml.length===0){this.setSlotContent(slotName,null);return}const currentContent=this.#getCurrentContent(slotName);if(currentContent!=null&&currentContent.innerHTML===normalizedHtml){this.#contentBySlot.set(slotName,currentContent),this.#attachContent(slotName,currentContent);return}const nextContent=document.createElement("div");nextContent.innerHTML=normalizedHtml,this.setSlotContent(slotName,nextContent)}#getCurrentContent(slotName){const trackedContent=this.#contentBySlot.get(slotName)??null;if(trackedContent!=null)return trackedContent;const host=this.#host;if(host==null)return null;for(const element of Array.from(host.children))if(element instanceof HTMLElement&&element.dataset.fileTreeManagedSlot===slotName)return element;return null}#attachContent(slotName,content){content.slot=slotName,content.dataset.fileTreeManagedSlot=slotName,this.#host!=null&&content.parentNode!==this.#host&&this.#host.appendChild(content)}#adoptExistingManagedContent(host){for(const element of Array.from(host.children)){if(!(element instanceof HTMLElement))continue;const slotName=element.dataset.fileTreeManagedSlot;slotName==null||this.#contentBySlot.has(slotName)||this.#contentBySlot.set(slotName,element)}}};let clientInstanceId=0;function createClientId(explicitId){return explicitId!=null&&explicitId.length>0?explicitId:(clientInstanceId+=1,`pst_ft_${clientInstanceId}`)}function resolveInitialViewportHeight({initialVisibleRowCount,itemHeight}){return initialVisibleRowCount==null?420:Math.max(0,initialVisibleRowCount)*(itemHeight??FILE_TREE_DEFAULT_ITEM_HEIGHT)}function parseSpriteSheet(spriteSheet){if(typeof document>"u")return;const wrapper=document.createElement("div");wrapper.innerHTML=spriteSheet;const svg=wrapper.querySelector("svg");return svg instanceof SVGElement?svg:void 0}function isBuiltInSpriteSheet(spriteSheet){return spriteSheet.querySelector("#file-tree-icon-chevron")instanceof SVGElement&&spriteSheet.querySelector("#file-tree-icon-file")instanceof SVGElement&&spriteSheet.querySelector("#file-tree-icon-dot")instanceof SVGElement&&spriteSheet.querySelector("#file-tree-icon-lock")instanceof SVGElement}function getTopLevelSpriteSheets(shadowRoot){return Array.from(shadowRoot.children).filter(element=>element instanceof SVGElement)}var FileTree$2=class{static LoadedCustomComponent=!0;#composition;#controller;#id;#onSelectionChange;#renderRowDecoration;#renamingEnabled;#searchBlurBehavior;#searchEnabled;#searchFakeFocus;#slotHost=new FileTreeManagedSlotHost;#density;#viewOptions;#fileTreeContainer;#gitStatusState;#icons;#unsafeCSS;#unsafeCSSStyle;#appliedUnsafeCSS;#selectionVersion;#selectionSubscription=null;#wrapper;#wroteHostItemHeight=!1;#wroteHostDensityFactor=!1;constructor(options){const{composition,density,fileTreeSearchMode,gitStatus,id,initialSearchQuery,icons,itemHeight,onSearchChange,onSelectionChange,overscan,renderRowDecoration:renderRowDecoration2,renaming,search,searchBlurBehavior,searchFakeFocus,stickyFolders,unsafeCSS,initialVisibleRowCount,...controllerOptions}=options;this.#composition=composition,this.#id=createClientId(id),this.#gitStatusState=resolveFileTreeGitStatusState(gitStatus),this.#icons=icons,this.#unsafeCSS=unsafeCSS,this.#onSelectionChange=onSelectionChange,this.#renderRowDecoration=renderRowDecoration2,this.#renamingEnabled=renaming!=null&&renaming!==!1,this.#searchBlurBehavior=searchBlurBehavior,this.#searchEnabled=search===!0,this.#searchFakeFocus=searchFakeFocus===!0,this.#density=resolveFileTreeDensity(density,itemHeight),this.#viewOptions={itemHeight:this.#density.itemHeight,overscan,stickyFolders,initialVisibleRowCount},this.#controller=new FileTreeController({...controllerOptions,fileTreeSearchMode,initialSearchQuery,onSearchChange,renaming}),this.#selectionVersion=this.#controller.getSelectionVersion(),this.#selectionSubscription=this.#onSelectionChange==null?null:this.subscribe(()=>{this.#emitSelectionChange()})}unmount(){this.#wrapper!=null&&(unmountFileTreeRoot(this.#wrapper),delete this.#wrapper.dataset.fileTreeVirtualizedWrapper,this.#wrapper=void 0),this.#slotHost.clearAll(),this.#slotHost.setHost(null),this.#fileTreeContainer!=null&&(delete this.#fileTreeContainer.dataset.fileTreeVirtualized,this.#removeOwnedDensityHostStyle(this.#fileTreeContainer),this.#fileTreeContainer=void 0)}cleanUp(){this.unmount(),this.#selectionSubscription?.(),this.#selectionSubscription=null,this.#controller.destroy()}getFileTreeContainer(){return this.#fileTreeContainer}getItem(path){return this.#controller.getItem(path)}getFocusedItem(){return this.#controller.getFocusedItem()}getFocusedPath(){return this.#controller.getFocusedPath()}getFocusedIndex(){return this.#controller.getFocusedIndex()}getVisibleCount(){return this.#controller.getVisibleCount()}getVisibleRows(start,end){return this.#controller.getVisibleRows(start,end)}getSelectedPaths(){return this.#controller.getSelectedPaths()}getComposition(){return this.#composition}getItemHeight(){return this.#density.itemHeight}getDensityFactor(){return this.#density.factor}subscribe(listener){let hasSeenInitialSnapshot=!1;return this.#controller.subscribe(()=>{if(!hasSeenInitialSnapshot){hasSeenInitialSnapshot=!0;return}listener()})}focusPath(path){this.#controller.focusPath(path)}focusFirstItem(){this.#controller.focusFirstItem()}focusLastItem(){this.#controller.focusLastItem()}focusNextItem(){this.#controller.focusNextItem()}focusPreviousItem(){this.#controller.focusPreviousItem()}focusParentItem(){this.#controller.focusParentItem()}scrollToPath(path,options){this.#controller.scrollToPath(path,options)}focusNearestPath(path){return this.#controller.focusNearestPath(path)}add(path){this.#controller.add(path)}batch(operations){this.#controller.batch(operations)}applyGitStatusPatch(patch){const nextGitStatusState=applyFileTreeGitStatusPatch(this.#gitStatusState,patch);if(nextGitStatusState===this.#gitStatusState)return;this.#gitStatusState=nextGitStatusState;const mountedTree=this.#getMountedTreeElements();mountedTree!=null&&renderFileTreeRoot(mountedTree.wrapper,this.#getViewProps())}move(fromPath,toPath,options){this.#controller.move(fromPath,toPath,options)}onMutation(type,handler){return this.#controller.onMutation(type,handler)}setSearch(value){this.#controller.setSearch(value)}openSearch(initialValue){this.#controller.openSearch(initialValue)}closeSearch(){this.#controller.closeSearch()}isSearchOpen(){return this.#controller.isSearchOpen()}getSearchValue(){return this.#controller.getSearchValue()}getSearchMatchingPaths(){return this.#controller.getSearchMatchingPaths()}focusNextSearchMatch(){this.#controller.focusNextSearchMatch()}focusPreviousSearchMatch(){this.#controller.focusPreviousSearchMatch()}startRenaming(path,options){return this.#controller.startRenaming(path,options)}remove(path,options){this.#controller.remove(path,options)}resetPaths(pathsOrOptions,options){Array.isArray(pathsOrOptions)?this.#controller.resetPaths(pathsOrOptions,options):this.#controller.resetPaths(pathsOrOptions)}setComposition(composition){this.#composition=composition;const mountedTree=this.#getMountedTreeElements();mountedTree!=null&&(this.#syncHeaderSlotContent(),renderFileTreeRoot(mountedTree.wrapper,this.#getViewProps()))}setGitStatus(gitStatus){const nextGitStatusState=resolveFileTreeGitStatusState(gitStatus,this.#gitStatusState);if(nextGitStatusState===this.#gitStatusState)return;this.#gitStatusState=nextGitStatusState;const mountedTree=this.#getMountedTreeElements();mountedTree!=null&&renderFileTreeRoot(mountedTree.wrapper,this.#getViewProps())}setIcons(icons){this.#icons=icons;const mountedTree=this.#getMountedTreeElements();mountedTree!=null&&(this.#syncIconSurface(mountedTree.host,mountedTree.wrapper),renderFileTreeRoot(mountedTree.wrapper,this.#getViewProps()))}hydrate({fileTreeContainer}){const host=this.#prepareHost(fileTreeContainer),wrapper=this.#getOrCreateWrapper(host);this.#syncHeaderSlotContent(),hydrateFileTreeRoot(wrapper,this.#getViewProps())}render({containerWrapper,fileTreeContainer}){const host=this.#prepareHost(fileTreeContainer??this.#fileTreeContainer,containerWrapper),wrapper=this.#getOrCreateWrapper(host);this.#syncHeaderSlotContent(),renderFileTreeRoot(wrapper,this.#getViewProps())}#getInitialViewOptions(){return{initialViewportHeight:resolveInitialViewportHeight({initialVisibleRowCount:this.#viewOptions.initialVisibleRowCount,itemHeight:this.#viewOptions.itemHeight}),itemHeight:this.#viewOptions.itemHeight,overscan:this.#viewOptions.overscan,stickyFolders:this.#viewOptions.stickyFolders}}#getViewProps(){return{composition:this.#composition,controller:this.#controller,gitStatusByPath:this.#gitStatusState?.statusByPath,ignoredGitDirectories:this.#gitStatusState?.ignoredDirectoryPaths,directoriesWithGitChanges:this.#gitStatusState?.directoriesWithChanges,icons:this.#icons,instanceId:this.#id,renamingEnabled:this.#renamingEnabled,renderRowDecoration:this.#renderRowDecoration,searchBlurBehavior:this.#searchBlurBehavior,searchEnabled:this.#searchEnabled,searchFakeFocus:this.#searchFakeFocus,slotHost:this.#slotHost,...this.#getInitialViewOptions()}}#getMountedTreeElements(){const host=this.#fileTreeContainer,wrapper=this.#wrapper;return host==null||wrapper==null?null:{host,wrapper}}#syncIconSurface(host,wrapper){const shadowRoot=host.shadowRoot;shadowRoot!=null&&(this.#syncBuiltInSpriteSheet(shadowRoot),this.#syncCustomSpriteSheet(shadowRoot)),this.#syncIconModeAttrs(wrapper)}#emitSelectionChange(){const onSelectionChange=this.#onSelectionChange;if(onSelectionChange==null)return;const nextSelectionVersion=this.#controller.getSelectionVersion();nextSelectionVersion!==this.#selectionVersion&&(this.#selectionVersion=nextSelectionVersion,onSelectionChange(this.#controller.getSelectedPaths()))}#syncHeaderSlotContent(){const renderHeader=this.#composition?.header?.render;if(renderHeader!=null){this.#slotHost.setSlotContent(HEADER_SLOT_NAME,renderHeader());return}this.#slotHost.setSlotHtml(HEADER_SLOT_NAME,this.#composition?.header?.html??null)}#syncBuiltInSpriteSheet(shadowRoot){const currentBuiltInSprite=getTopLevelSpriteSheets(shadowRoot).find(sprite=>isBuiltInSpriteSheet(sprite)),nextBuiltInSprite=parseSpriteSheet(getBuiltInSpriteSheet(normalizeFileTreeIcons(this.#icons).set));nextBuiltInSprite!=null&&(currentBuiltInSprite!=null&&currentBuiltInSprite.outerHTML===nextBuiltInSprite.outerHTML||(currentBuiltInSprite!=null?currentBuiltInSprite.replaceWith(nextBuiltInSprite):shadowRoot.prepend(nextBuiltInSprite)))}#syncCustomSpriteSheet(shadowRoot){const topLevelSprites=getTopLevelSpriteSheets(shadowRoot),builtInSprite=topLevelSprites.find(sprite=>isBuiltInSpriteSheet(sprite)),currentCustomSprites=topLevelSprites.filter(sprite=>sprite!==builtInSprite),customSpriteSheet=normalizeFileTreeIcons(this.#icons).spriteSheet?.trim()??"";if(customSpriteSheet.length===0){for(const currentCustomSprite of currentCustomSprites)currentCustomSprite.remove();return}const customSprite=parseSpriteSheet(customSpriteSheet);if(customSprite==null){for(const currentCustomSprite of currentCustomSprites)currentCustomSprite.remove();return}if(!(currentCustomSprites.length===1&&currentCustomSprites[0].outerHTML===customSprite.outerHTML)){for(const currentCustomSprite of currentCustomSprites)currentCustomSprite.remove();shadowRoot.appendChild(customSprite)}}#syncIconModeAttrs(wrapper){const normalizedIcons=normalizeFileTreeIcons(this.#icons);normalizedIcons.colored&&isColoredBuiltInIconSet(normalizedIcons.set)?wrapper.dataset.fileTreeColoredIcons="true":delete wrapper.dataset.fileTreeColoredIcons}#syncUnsafeCSS(shadowRoot){const existingUnsafeStyle=shadowRoot.querySelector(`style[${FILE_TREE_UNSAFE_CSS_ATTRIBUTE}]`);if(this.#unsafeCSSStyle==null&&existingUnsafeStyle instanceof HTMLStyleElement&&(this.#unsafeCSSStyle=existingUnsafeStyle),this.#unsafeCSS==null||this.#unsafeCSS===""){this.#unsafeCSSStyle?.remove(),this.#unsafeCSSStyle=void 0,this.#appliedUnsafeCSS=void 0;return}this.#unsafeCSSStyle?.parentNode===shadowRoot&&this.#appliedUnsafeCSS===this.#unsafeCSS||(this.#unsafeCSSStyle??=document.createElement("style"),this.#unsafeCSSStyle.setAttribute(FILE_TREE_UNSAFE_CSS_ATTRIBUTE,""),this.#unsafeCSSStyle.parentNode!==shadowRoot&&shadowRoot.appendChild(this.#unsafeCSSStyle),this.#unsafeCSSStyle.textContent=wrapUnsafeCSS(this.#unsafeCSS),this.#appliedUnsafeCSS=this.#unsafeCSS)}#getOrCreateWrapper(host){if(this.#wrapper!=null)return this.#wrapper;const shadowRoot=host.shadowRoot;if(shadowRoot==null)throw new Error("FileTree requires a shadow root");const wrapperCandidates=Array.from(shadowRoot.children).filter(element=>element instanceof HTMLDivElement&&typeof element.dataset.fileTreeId=="string"&&element.dataset.fileTreeId.length>0),existingWrapper=wrapperCandidates.find(element=>element.dataset.fileTreeId===this.#id)??wrapperCandidates[0];return existingWrapper!=null&&(this.#id=existingWrapper.dataset.fileTreeId??this.#id),this.#wrapper=existingWrapper??document.createElement("div"),this.#wrapper.dataset.fileTreeId=this.#id,this.#wrapper.dataset.fileTreeVirtualizedWrapper="true",this.#syncIconSurface(host,this.#wrapper),this.#wrapper.parentNode!==shadowRoot&&shadowRoot.appendChild(this.#wrapper),this.#wrapper}#prepareHost(fileTreeContainer,parentNode){const host=fileTreeContainer??this.#fileTreeContainer??document.createElement("file-tree-container");parentNode!=null&&host.parentNode!==parentNode&&parentNode.appendChild(host);const shadowRoot=host.shadowRoot??host.attachShadow({mode:"open"});return prepareFileTreeShadowRoot(host,shadowRoot),this.#syncUnsafeCSS(shadowRoot),host.dataset.fileTreeVirtualized="true",host.style.display="flex",this.#applyDensityHostStyle(host),this.#slotHost.setHost(host),this.#fileTreeContainer=host,host}#applyDensityHostStyle(host){host.style.getPropertyValue("--trees-item-height")===""&&(host.style.setProperty("--trees-item-height",`${String(this.#density.itemHeight)}px`),this.#wroteHostItemHeight=!0),host.style.getPropertyValue("--trees-density-override")===""&&(host.style.setProperty("--trees-density-override",String(this.#density.factor)),this.#wroteHostDensityFactor=!0)}#removeOwnedDensityHostStyle(host){this.#wroteHostItemHeight&&(host.style.removeProperty("--trees-item-height"),this.#wroteHostItemHeight=!1),this.#wroteHostDensityFactor&&(host.style.removeProperty("--trees-density-override"),this.#wroteHostDensityFactor=!1)}};function FileTabPill({path,label,title,active,dirty=!1,readOnly=!1,lifted=!1,glyph,onPick,onClose,onMove,onContextMenu,className,style}){const labels=useLabels(),name=label??path.split("/").pop()??path;return jsxRuntimeExports.jsx(TabPill,{size:"sm",label:name,selected:active,lifted,title:title??(dirty?labels.fileUnsavedTitle(path):readOnly?labels.fileReadOnly(path):path),onSelect:onPick,keyShortcuts:onMove?"Alt+Shift+ArrowLeft Alt+Shift+ArrowRight":void 0,onKeyDown:e2=>{!onMove||!e2.altKey||!e2.shiftKey||e2.key!=="ArrowLeft"&&e2.key!=="ArrowRight"||(e2.preventDefault(),onMove(e2.key==="ArrowLeft"?-1:1))},onAuxClick:e2=>{e2.button===1&&onClose()},onContextMenu:e2=>{onContextMenu&&(e2.preventDefault(),onContextMenu({x:e2.clientX,y:e2.clientY}))},leading:glyph??jsxRuntimeExports.jsx(FileIcon,{path}),marker:dirty&&jsxRuntimeExports.jsx("span",{"aria-label":labels.fileUnsaved,className:"absolute right-2.5 top-1/2 -translate-y-1/2 w-2 h-2 rounded-full bg-[var(--zg-accent)] pointer-events-none group-hover:opacity-0"}),closeLabel:labels.closeTab(name),onClose,closeAlways:active&&!dirty,className,style})}const useClientLayoutEffect=typeof window>"u"?reactExports.useEffect:reactExports.useLayoutEffect;function renderFileTreeChildren(header,renderContextMenu,activeContextMenu){const headerChild=header!=null?jsxRuntimeExports.jsx("div",{slot:HEADER_SLOT_NAME,children:header}):null,contextMenuChild=renderContextMenu!=null&&activeContextMenu!=null?jsxRuntimeExports.jsx("div",{slot:CONTEXT_MENU_SLOT_NAME,children:renderContextMenu(activeContextMenu.item,activeContextMenu.context)}):null;return headerChild==null&&contextMenuChild==null?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[headerChild,contextMenuChild]})}function renderPreloadedShadowDom(children,preloadedData){return typeof window>"u"&&preloadedData!=null?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("template",{shadowrootmode:"open",dangerouslySetInnerHTML:{__html:preloadedData.shadowHtml}}),children]}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children})}function hasExistingPreloadedContent(host){const shadowRoot=host.shadowRoot;return shadowRoot?.querySelector("[data-file-tree-id]")instanceof HTMLElement||shadowRoot?.querySelector("[data-file-tree-id]")instanceof SVGElement?!0:host.querySelector('template[shadowrootmode="open"]')instanceof HTMLTemplateElement}function resolveComposition(baselineComposition,header,hasContextMenu,onClose,onOpen){const nextComposition={...baselineComposition??{}};if(header!=null&&delete nextComposition.header,hasContextMenu){const baselineContextMenu=baselineComposition?.contextMenu,baselineOnClose=baselineContextMenu?.onClose,baselineOnOpen=baselineContextMenu?.onOpen;nextComposition.contextMenu={...baselineContextMenu??{},enabled:!0,onClose:()=>{baselineOnClose?.(),onClose()},onOpen:(item,context)=>{onOpen(item,context),baselineOnOpen?.(item,context)}},delete nextComposition.contextMenu.render}return nextComposition.header!=null||nextComposition.contextMenu!=null?nextComposition:void 0}function FileTree$1({header,id,model,preloadedData,renderContextMenu,...hostProps}){const[activeContextMenu,setActiveContextMenu]=reactExports.useState(null),[hostElement,setHostElement]=reactExports.useState(null),baselineCompositionRef=reactExports.useRef(model.getComposition()),baselineModelRef=reactExports.useRef(model);baselineModelRef.current!==model&&(baselineModelRef.current=model,baselineCompositionRef.current=model.getComposition());const hasContextMenu=renderContextMenu!=null,handleContextMenuClose=reactExports.useCallback(()=>{setActiveContextMenu(null)},[]),handleContextMenuOpen=reactExports.useCallback((item,context)=>{setActiveContextMenu({context,item})},[]),baselineComposition=baselineCompositionRef.current,composition=reactExports.useMemo(()=>resolveComposition(baselineComposition,header,hasContextMenu,handleContextMenuClose,handleContextMenuOpen),[baselineComposition,handleContextMenuClose,handleContextMenuOpen,hasContextMenu,header]),handleHostRef=reactExports.useCallback(node=>{setHostElement(node)},[]);reactExports.useEffect(()=>{hasContextMenu||setActiveContextMenu(null)},[hasContextMenu]),useClientLayoutEffect(()=>{model.setComposition(composition)},[composition,model]),useClientLayoutEffect(()=>{if(hostElement!=null)return preloadedData!=null&&hasExistingPreloadedContent(hostElement)?model.hydrate({fileTreeContainer:hostElement}):model.render({fileTreeContainer:hostElement}),()=>{model.unmount(),model.setComposition(baselineComposition)}},[baselineComposition,hostElement,model,preloadedData]);const children=renderPreloadedShadowDom(renderFileTreeChildren(header,renderContextMenu,activeContextMenu),preloadedData),resolvedHostId=id??preloadedData?.id,mergedStyle={"--trees-item-height":`${String(model.getItemHeight())}px`,"--trees-density-override":model.getDensityFactor(),...hostProps.style};return jsxRuntimeExports.jsx(FILE_TREE_TAG_NAME,{...hostProps,id:resolvedHostId,ref:handleHostRef,style:mergedStyle,suppressHydrationWarning:preloadedData!=null,children})}function useFileTree(options){const[model]=reactExports.useState(()=>new FileTree$2(options)),cleanUpRef=reactExports.useRef({timeout:null,model});return reactExports.useEffect(()=>{const{current}=cleanUpRef;return current.timeout!=null&&(clearTimeout(current.timeout),current.timeout=null),()=>{current.timeout=setTimeout(()=>current.model.cleanUp(),1)}},[]),{model}}const TREE_PATH_MIME="application/x-zidane-tree-path";function FileTree2({controlRef,entries,gitStatus,selectedPath,onSelect,onOpen,onContextMenu,className,style,openPaths,label,editing,onExpandFolder}){const labels=useLabels(),paths=reactExports.useMemo(()=>entries.map(e2=>e2.path),[entries]),editingRef=reactExports.useRef(editing);editingRef.current=editing;const pathsRef=reactExports.useRef(paths);pathsRef.current=paths;const creating=reactExports.useRef(null),copyDrag=reactExports.useRef(!1),[externalDrag,setExternalDrag]=reactExports.useState(!1),revealNext=reactExports.useRef(null),[editable]=reactExports.useState(()=>editing!==void 0),decorated=reactExports.useMemo(()=>[...gitStatus,...entries.filter(e2=>e2.ignored).map(e2=>({path:e2.path.replace(/\/$/,""),status:"ignored"}))],[entries,gitStatus]),[expanded]=reactExports.useState(()=>ancestorDirs(openPaths??[])),{model}=useFileTree({paths,initialExpansion:"closed",initialExpandedPaths:expanded,density:"compact",icons:{set:"complete",colored:!0},gitStatus:decorated,unsafeCSS:TREES_UNSAFE_CSS,onSelectionChange:selected=>onSelect(selected[0]??null),...editable?{renaming:{onRename:({sourcePath,destinationPath,isFolder})=>{const kind=isFolder?"folder":"file",from=bare(sourcePath),to=bare(destinationPath),pending=creating.current;if(pending&&bare(pending.path)===from){creating.current=null,editingRef.current?.onCreate(to,pending.kind);return}editingRef.current?.onRename(from,to,kind)},onError:message=>{const pending=creating.current;pending&&(creating.current=null,model.remove(pending.path,pending.kind==="folder"?{recursive:!0}:void 0)),editingRef.current?.onError?.(message)}},dragAndDrop:{onDropComplete:({draggedPaths,target})=>{const toDir=target.kind==="root"||!target.directoryPath?"":bare(target.directoryPath),moved=draggedPaths.map(bare),copy=copyDrag.current;copyDrag.current=!1,copy&&model.resetPaths(pathsRef.current),editingRef.current?.onMove(moved,toDir,copy)}}}:{}}),lazyDirs=reactExports.useMemo(()=>entries.filter(e2=>(e2.ignored||e2.deferred)&&e2.kind==="dir"&&e2.path.endsWith("/")).map(e2=>e2.path),[entries]),lazyRef=reactExports.useRef({dirs:lazyDirs,onExpandFolder});lazyRef.current={dirs:lazyDirs,onExpandFolder},reactExports.useEffect(()=>{const open=new Set;return model.subscribe(()=>{const{dirs,onExpandFolder:report}=lazyRef.current;if(report)for(const path of dirs){const item=model.getItem(path);item!==null&&"isExpanded"in item&&item.isExpanded()?open.has(path)||(open.add(path),report(bare(path))):open.delete(path)}})},[model]),reactExports.useEffect(()=>{if(editable)return model.onMutation("remove",event=>{creating.current&&"path"in event&&event.path===creating.current.path&&(creating.current=null)})},[model,editable]),reactExports.useEffect(()=>{if(editable)return model.subscribe(()=>{const pending=creating.current;pending&&requestAnimationFrame(()=>{creating.current!==pending||!model.getItem(pending.path)||model.getFileTreeContainer()?.shadowRoot?.querySelector('input[aria-label^="Rename"]')||(creating.current=null,editingRef.current?.onCreate(bare(pending.path),pending.kind))})})},[model,editable]);const revealPath=reactExports.useCallback(path=>{const item=model.getItem(path)??model.getItem(`${path}/`);if(!item)return!1;"expand"in item&&item.expand();for(const selected of model.getSelectedPaths())selected!==item.getPath()&&model.getItem(selected)?.deselect();return item.select(),model.scrollToPath(item.getPath(),{focus:!0}),!0},[model]);reactExports.useEffect(()=>{if(controlRef)return controlRef.current={revealSoon:path=>{revealNext.current=revealPath(path)?null:path},startCreate:(dir,kind,name)=>{if(!editable||creating.current)return!1;const base=dir?`${bare(dir)}/`:"";let leaf=name;for(let n2=2;model.getItem(`${base}${leaf}`)||model.getItem(`${base}${leaf}/`);n2++)leaf=`${name} ${n2}`;const path=`${base}${leaf}${kind==="folder"?"/":""}`;return base&&model.getItem(base)?.expand?.(),model.add(path),creating.current={path,kind},model.startRenaming(path,{removeIfCanceled:!0})?!0:(creating.current=null,model.remove(path,kind==="folder"?{recursive:!0}:void 0),!1)},startRename:path=>{if(!editable)return!1;const item=model.getItem(path)??model.getItem(`${path}/`);return item?model.startRenaming(item.getPath()):!1},resync:()=>model.resetPaths(pathsRef.current),setSearch:value=>model.setSearch(value&&value.length>0?value:null),reveal:revealPath},()=>{controlRef.current=null}},[controlRef,model,editable,revealPath]);const initial=reactExports.useRef(!0);reactExports.useEffect(()=>{if(initial.current){initial.current=!1;return}const pending=creating.current?.path;model.resetPaths(pending&&!paths.includes(pending)?[...paths,pending]:paths);const next=revealNext.current;revealNext.current=null,next&&revealPath(next)},[model,paths,revealPath]),reactExports.useEffect(()=>{model.setGitStatus(decorated)},[model,decorated]);const rowOf=e2=>e2.nativeEvent.composedPath().find(el=>el instanceof Element&&el.hasAttribute?.("data-item-path")),rowPath=e2=>rowOf(e2)?.getAttribute("data-item-path")??null,onClickCapture=e2=>{if(e2.shiftKey||e2.button!==0)return;const path=rowPath(e2);if(!path)return;!path.endsWith("/")&&entries.some(en=>en.path===path&&en.kind==="file")&&onOpen(path,{metaKey:e2.metaKey,ctrlKey:e2.ctrlKey})},onKeyDown=e2=>{e2.key==="Enter"&&selectedPath&&!selectedPath.endsWith("/")&&onOpen(selectedPath,{metaKey:e2.metaKey,ctrlKey:e2.ctrlKey})},dropDir=e2=>{const row=e2.nativeEvent.composedPath().find(el=>el instanceof Element&&el.hasAttribute?.("data-item-path")),path=row?.getAttribute("data-item-path")??"";if(!path)return"";if(row?.getAttribute("data-item-type")==="folder")return bare(path);const at=path.lastIndexOf("/");return at<0?"":path.slice(0,at)},fromOutside=e2=>editable&&!!editingRef.current?.onDropFiles&&Array.from(e2.dataTransfer?.types??[]).includes("Files");return jsxRuntimeExports.jsx(FileTree$1,{model,className,style:style?{...TREES_HOST_STYLE,...style}:TREES_HOST_STYLE,"aria-label":label??labels.fileTree,"data-zg-file-drop":externalDrag?"true":void 0,onDragStart:e2=>{const path=e2.dataTransfer.getData("text/plain");path&&!path.endsWith("/")&&e2.dataTransfer.setData(TREE_PATH_MIME,path),e2.dataTransfer.effectAllowed="copyMove"},onDragOverCapture:editable?e2=>{copyDrag.current=e2.altKey}:void 0,onDropCapture:editable?e2=>{copyDrag.current=e2.altKey}:void 0,onDragOver:e2=>{fromOutside(e2)&&(e2.preventDefault(),e2.dataTransfer.dropEffect="copy",externalDrag||setExternalDrag(!0))},onDragLeave:e2=>{externalDrag&&!(e2.relatedTarget instanceof Node&&e2.currentTarget.contains(e2.relatedTarget))&&setExternalDrag(!1)},onDrop:e2=>{fromOutside(e2)&&(e2.preventDefault(),setExternalDrag(!1),editingRef.current?.onDropFiles?.(dropDir(e2),e2.dataTransfer))},onClickCapture,onContextMenu:e2=>{const row=rowOf(e2),path=row?.getAttribute("data-item-path");if(!onContextMenu)return;if((!row||!path)&&editable){e2.preventDefault(),onContextMenu({path:"",kind:"folder"},{x:e2.clientX,y:e2.clientY});return}if(!row||!path)return;e2.preventDefault();const kind=row.getAttribute("data-item-type")==="folder"?"folder":"file";onContextMenu({path:path.replace(/\/$/,""),kind},{x:e2.clientX,y:e2.clientY})},onKeyDown})}function bare(path){return path.replace(/\/$/,"")}function ancestorDirs(paths){const dirs=new Set;for(const path of paths){const parts=path.split("/").filter(Boolean);for(let i2=1;i2<parts.length;i2++)dirs.add(`${parts.slice(0,i2).join("/")}/`)}return[...dirs]}const MAX_SHOWN=100,ROW_PX=22,VISIBLE_ROWS=10,RESOLVE_DELAY_MS=120,BUSY_RETRY_MS$1=1500,BUSY_RETRIES$1=40,SETTLE_MS=400,WORD=/[\p{L}\p{N}_$]/u,KIND_ICON={method:"i-ph-function text-[var(--zg-accent)]",function:"i-ph-function text-[var(--zg-accent)]",constructor:"i-ph-function text-[var(--zg-accent)]",field:"i-ph-tag-simple text-zg-info",property:"i-ph-tag-simple text-zg-info",variable:"i-ph-cube-transparent text-zg-info",value:"i-ph-cube-transparent text-zg-info",class:"i-ph-cube text-zg-warn",struct:"i-ph-cube text-zg-warn",interface:"i-ph-plugs text-zg-warn",enum:"i-ph-list-bullets text-zg-warn","enum-member":"i-ph-list-dashes text-zg-warn","type-parameter":"i-ph-text-t text-zg-warn",module:"i-ph-package text-[var(--zg-text-muted)]",constant:"i-ph-lock-simple text-zg-info",keyword:"i-ph-key text-[var(--zg-text-muted)]",snippet:"i-ph-brackets-curly text-[var(--zg-text-muted)]",file:"i-ph-file text-[var(--zg-text-muted)]",folder:"i-ph-folder text-[var(--zg-text-muted)]"},DEFAULT_ICON="i-ph-circle text-[var(--zg-text-muted)]";function matchWord(text,typed){if(!typed)return{rank:0,positions:[]};if(text.startsWith(typed))return{rank:3,positions:range(typed.length)};const lower=text.toLowerCase(),want=typed.toLowerCase();if(lower.startsWith(want))return{rank:2,positions:range(typed.length)};const positions=[];let boundaryHits=0,from=0;for(let k2=0;k2<want.length;k2++){let found=-1;for(let i2=from;i2<lower.length;i2++)if(lower[i2]===want[k2]&&isBoundary(text,i2)){found=i2,boundaryHits++;break}if(found===-1&&(k2===0||(found=lower.indexOf(want[k2],from),found===-1)))return null;positions.push(found),from=found+1}return{rank:boundaryHits===want.length?1:0,positions}}function isBoundary(text,i2){if(i2===0)return!0;const prev=text[i2-1],c2=text[i2];return!WORD.test(prev)||prev==="_"||prev==="$"?!0:c2!==c2.toLowerCase()&&prev===prev.toLowerCase()}function range(n2){return Array.from({length:n2},(_2,i2)=>i2)}function rankCompletions(items,typed){const out=[];return items.forEach((item,index)=>{const m2=matchWord(item.filterText??item.label,typed);m2&&out.push({item,index,rank:m2.rank,matches:item.filterText?[]:m2.positions})}),out.sort((a2,b2)=>{if(a2.rank!==b2.rank)return b2.rank-a2.rank;const sa=a2.item.sortText??a2.item.label,sb=b2.item.sortText??b2.item.label;return sa<sb?-1:sa>sb?1:a2.index-b2.index}),out.slice(0,MAX_SHOWN).map(({item,index,matches})=>({item,index,matches}))}function lineOf(text,line){let start=0;for(let n2=0;n2<line;n2++){const nl=text.indexOf(`
1100
1100
  `,start);if(nl===-1)return"";start=nl+1}const end=text.indexOf(`
1101
1101
  `,start);return text.slice(start,end===-1?text.length:end).replace(/\r$/,"")}function advance(from,inserted){const lines=inserted.split(`
1102
1102
  `);return lines.length===1?{line:from.line,character:from.character+inserted.length}:{line:from.line+lines.length-1,character:lines[lines.length-1].length}}function before(a2,b2){return a2.line<b2.line||a2.line===b2.line&&a2.character<=b2.character}function useCompletion(source,handle){const[menu,setMenu]=reactExports.useState(null),[detail,setDetail]=reactExports.useState(null),session=reactExports.useRef(null),seq=reactExports.useRef(0),text=reactExports.useRef(null),frame=reactExports.useRef(0),timers=reactExports.useRef(new Set),dismissed=reactExports.useRef(null),menuRef=reactExports.useRef(null),sourceRef=reactExports.useRef(source);reactExports.useLayoutEffect(()=>{menuRef.current=menu,sourceRef.current=source});const resolved=reactExports.useRef(new Map),later=(ms,fn)=>{const id=setTimeout(()=>{timers.current.delete(id),fn()},ms);timers.current.add(id)},move=reactExports.useCallback(next=>{menuRef.current=next,setMenu(next)},[]),close=reactExports.useCallback(()=>{cancelAnimationFrame(frame.current);for(const id of timers.current)clearTimeout(id);timers.current.clear(),session.current=null,seq.current++,menuRef.current&&move(null)},[move]),editorOf=()=>handle.current?.editor()??null,caretOf=editor=>{try{const sel=editor.getViewState().selections?.[0];return!sel||sel.start.line!==sel.end.line||sel.start.character!==sel.end.character?null:{line:sel.end.line,character:sel.end.character}}catch{return null}},caretRect=()=>{const rect=handle.current?.host()?.querySelector("diffs-container")?.shadowRoot?.querySelector("[data-caret]")?.getBoundingClientRect();return rect&&rect.height>0?rect:null},refresh=(explicit,trigger)=>{const editor=editorOf(),src=sourceRef.current,doc=text.current;if(!editor||!src||doc===null)return close();const caret=caretOf(editor);if(!caret)return close();const lineText=lineOf(doc,caret.line);let start=caret.character;for(;start>0&&WORD.test(lineText[start-1]);)start--;const typed=lineText.slice(start,caret.character),s2=session.current,sameWord=s2!==null&&s2.line===caret.line&&s2.start===start;if(!explicit&&!trigger){const quiet=dismissed.current;if(quiet&&quiet.line===caret.line&&quiet.start===start||!sameWord&&typed.length===0)return close()}if(dismissed.current=null,sameWord&&s2.answer&&!s2.answer.incomplete&&!explicit&&!trigger)return show(s2,typed);sameWord&&s2.answer&&!explicit&&!trigger&&show(s2,typed),ask(doc,caret,start,trigger)};function ask(doc,caret,start,trigger){const src=sourceRef.current;if(!src)return;const mine=++seq.current,prev=session.current,s2=prev&&prev.line===caret.line&&prev.start===start?prev:{line:caret.line,start,answer:null,busyTries:0};session.current=s2,src.complete(doc,caret.line,caret.character,trigger).catch(()=>({id:0,items:[],incomplete:!1})).then(answer=>{if(seq.current!==mine||session.current!==s2)return;s2.answer=answer;const editor=editorOf(),now=editor?caretOf(editor):null;if(!now||now.line!==s2.line||now.character<s2.start)return close();const typed=lineOf(text.current??doc,now.line).slice(s2.start,now.character);show(s2,typed),answer.items.length===0&&answer.busy&&s2.busyTries++<BUSY_RETRIES$1&&later(BUSY_RETRY_MS$1,()=>{session.current===s2&&refresh(!0)})})}function show(s2,typed){const answer=s2.answer;if(!answer)return;const items=rankCompletions(answer.items,typed);if(items.length===0&&!answer.busy){menuRef.current&&move(null);return}cancelAnimationFrame(frame.current),frame.current=requestAnimationFrame(()=>{if(session.current!==s2)return;const rect=caretRect();if(!rect)return close();const keep=menuRef.current?.items[menuRef.current.selected];let selected=keep?items.findIndex(r2=>r2.index===keep.index):-1;selected<0&&(selected=Math.max(0,typed?0:items.findIndex(r2=>r2.item.preselect)));const next={answerId:answer.id,items,selected,rect};answer.busy&&items.length===0&&(next.busy=answer.busy),menuRef.current=next,setMenu(next)})}const accept=pick=>{const editor=editorOf(),s2=session.current,answer=s2?.answer;if(close(),!editor||!s2||!answer)return;const caret=caretOf(editor);if(!caret||caret.line!==s2.line)return;const{item}=pick,start=item.range&&item.range.start.line===caret.line&&item.range.start.character<=caret.character?item.range.start:{line:caret.line,character:s2.start},from=advance(start,item.insertText.slice(0,item.cursor?.start??item.insertText.length)),to=item.cursor?advance(start,item.insertText.slice(0,item.cursor.end)):from,place=()=>editor.setSelections([{start:from,end:to,direction:"forward"}]);try{editor.applyEdits([{range:{start,end:caret},newText:item.insertText}]),place()}catch{return}if(item.cursor&&(from.line!==to.line||from.character!==to.character)){let stop=function(){document.removeEventListener("selectionchange",restore),clearTimeout(timer)};const settled=editor.getText(),same=(a2,b2)=>a2.line===b2.line&&a2.character===b2.character,restore=()=>{try{if(editorOf()!==editor||editor.getText()!==settled)return stop();const sel=editor.getViewState().selections?.[0];sel&&same(sel.start,sel.end)&&(same(sel.start,from)||same(sel.start,to))&&place()}catch{stop()}};let timer;document.addEventListener("selectionchange",restore),timer=setTimeout(stop,SETTLE_MS),requestAnimationFrame(restore)}const src=sourceRef.current;if(!src?.resolve)return;const key2=`${answer.id}:${pick.index}`,known=resolved.current.get(key2);(known!==void 0?Promise.resolve(known):src.resolve(answer.id,pick.index).catch(()=>null)).then(d2=>{const edits=d2?.additionalEdits?.filter(e2=>before(e2.range.end,start))??[];if(!(edits.length===0||editorOf()!==editor))try{editor.applyEdits(edits)}catch{}})},selectedItem=menu?menu.items[menu.selected]:void 0,answerId=menu?.answerId;reactExports.useEffect(()=>{const src=sourceRef.current;if(!selectedItem||!src?.resolve||answerId===void 0)return;const key2=`${answerId}:${selectedItem.index}`;if(resolved.current.has(key2)){const d2=resolved.current.get(key2);d2&&setDetail({key:key2,detail:d2});return}const id=setTimeout(()=>{src.resolve(answerId,selectedItem.index).catch(()=>null).then(d2=>{resolved.current.size>200&&resolved.current.clear(),resolved.current.set(key2,d2),d2&&setDetail({key:key2,detail:d2})})},RESOLVE_DELAY_MS);return()=>clearTimeout(id)},[selectedItem,answerId]);const open=menu!==null;reactExports.useEffect(()=>{const host=handle.current?.host();if(!host)return;const onKey=e2=>{if(e2.key===" "&&e2.ctrlKey&&!e2.metaKey&&!e2.altKey){if(!editorOf()||!sourceRef.current)return;e2.preventDefault(),e2.stopPropagation(),text.current=editorOf()?.getText()??text.current,refresh(!0);return}const m2=menuRef.current;if(!m2)return;const take=()=>{e2.preventDefault(),e2.stopPropagation()},n2=m2.items.length;switch(e2.key){case"ArrowDown":case"ArrowUp":if(n2===0||e2.altKey||e2.metaKey||e2.shiftKey)return close();take(),move({...m2,selected:(m2.selected+(e2.key==="ArrowDown"?1:n2-1))%n2});return;case"PageDown":case"PageUp":if(n2===0)return;take(),move({...m2,selected:Math.max(0,Math.min(n2-1,m2.selected+(e2.key==="PageDown"?VISIBLE_ROWS:-VISIBLE_ROWS)))});return;case"Enter":case"Tab":if(n2===0||e2.altKey||e2.metaKey||e2.ctrlKey||e2.shiftKey)return close();take(),accept(m2.items[m2.selected]);return;case"Escape":{take();const s2=session.current;s2&&(dismissed.current={line:s2.line,start:s2.start}),close();return}case"ArrowLeft":case"ArrowRight":case"Home":case"End":close()}},onPointer=()=>close(),onFocusOut=e2=>{const next=e2.relatedTarget;(!next||!host.contains(next))&&close()},onScroll=()=>{menuRef.current&&close()};return host.addEventListener("keydown",onKey,!0),host.addEventListener("pointerdown",onPointer,!0),host.addEventListener("focusout",onFocusOut),host.addEventListener("scroll",onScroll,!0),()=>{host.removeEventListener("keydown",onKey,!0),host.removeEventListener("pointerdown",onPointer,!0),host.removeEventListener("focusout",onFocusOut),host.removeEventListener("scroll",onScroll,!0)}},[open,source]),reactExports.useEffect(()=>{source||close()},[source,close]),reactExports.useEffect(()=>()=>close(),[close]);const onChange=reactExports.useCallback((next,changes)=>{if(text.current=next,!sourceRef.current)return;const last=changes[changes.length-1];if(!last||changes.length>1)return close();const inserted=last.text,deleted=last.range.start.line!==last.range.end.line||last.range.start.character!==last.range.end.character;let trigger;if(inserted.length===1&&!WORD.test(inserted)){if(/\s/.test(inserted))return close();trigger=inserted}else{if(inserted.length>1||inserted.length===0&&!deleted)return close();if(inserted.length===0&&!session.current)return}cancelAnimationFrame(frame.current),frame.current=requestAnimationFrame(()=>refresh(!1,trigger))},[close]),shown=menu,detailFor=shown&&selectedItem&&detail?.key===`${answerId}:${selectedItem.index}`?detail.detail:null;return{onChange,close,node:shown?jsxRuntimeExports.jsx(CompletionMenu,{menu:shown,detail:detailFor,onPick:i2=>accept(shown.items[i2]),onHover:i2=>move({...shown,selected:i2})}):null,open}}function CompletionMenu({menu,detail,onPick,onHover}){const labels=useLabels(),ref=reactExports.useRef(null),list=reactExports.useRef(null),[pos,setPos]=reactExports.useState(null);reactExports.useLayoutEffect(()=>{const el=ref.current;if(!el)return;const{width,height}=el.getBoundingClientRect(),margin=8,left=Math.max(margin,Math.min(menu.rect.left,window.innerWidth-width-margin)),below=menu.rect.bottom+2;below+height<=window.innerHeight-margin?setPos({left,top:below}):setPos({left,bottom:window.innerHeight-menu.rect.top+2})},[menu.rect,menu.items.length,detail]),reactExports.useLayoutEffect(()=>{list.current?.children[menu.selected]?.scrollIntoView({block:"nearest"})},[menu.selected]);const selected=menu.items[menu.selected],doc=detail?.documentation??(detail?.detail&&detail.detail!==selected?.item.detail?detail.detail:void 0);return reactDomExports.createPortal(jsxRuntimeExports.jsxs("div",{ref,"data-testid":"code-completion",className:"zg-float fixed z-30 w-[28rem] max-w-[calc(100vw-16px)] text-zg-label leading-zg-ui overflow-hidden flex flex-col",style:pos??{left:menu.rect.left,top:menu.rect.bottom+2,visibility:"hidden"},onMouseDown:e2=>e2.preventDefault(),children:[menu.busy&&menu.items.length===0?jsxRuntimeExports.jsxs("div",{role:"status",className:"flex items-center gap-1.5 px-2 py-1 text-[var(--zg-text-muted)]",children:[jsxRuntimeExports.jsx("span",{className:"i-ph-circle-notch animate-spin shrink-0","aria-hidden":!0}),jsxRuntimeExports.jsx("span",{className:"min-w-0 truncate",children:menu.busy})]}):jsxRuntimeExports.jsx("ul",{ref:list,role:"listbox","aria-label":labels.completionSuggestions,className:"m-0 p-0.5 list-none overflow-auto",style:{maxHeight:ROW_PX*VISIBLE_ROWS+4},children:menu.items.map((r2,i2)=>jsxRuntimeExports.jsxs("li",{role:"option","aria-selected":i2===menu.selected,onMouseMove:()=>i2!==menu.selected&&onHover(i2),onClick:()=>onPick(i2),className:`flex items-center gap-2 px-1.5 rounded-zg-xs cursor-pointer ${i2===menu.selected?"bg-[var(--zg-row-active)]":""}`,style:{height:ROW_PX},children:[jsxRuntimeExports.jsx("span",{className:`${KIND_ICON[r2.item.kind??""]??DEFAULT_ICON} shrink-0 text-zg-label`,"aria-hidden":!0}),jsxRuntimeExports.jsx("span",{className:"min-w-0 truncate font-mono",children:jsxRuntimeExports.jsx(Highlighted,{text:r2.item.label,at:r2.matches})}),r2.item.detail&&jsxRuntimeExports.jsx("span",{className:"ml-auto pl-2 min-w-0 truncate text-zg-meta text-[var(--zg-text-muted)]",children:r2.item.detail})]},`${r2.index}`))}),doc&&jsxRuntimeExports.jsx("div",{className:"border-t border-[var(--zg-hairline)] px-2 py-1 max-h-28 overflow-auto whitespace-pre-wrap break-words text-zg-meta text-[var(--zg-text-muted)]",children:doc})]}),document.body)}function Highlighted({text,at}){if(at.length===0)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:text});const hits=new Set(at),parts=[];for(let i2=0;i2<text.length;i2++){const hit=hits.has(i2),last=parts[parts.length-1];last&&last.hit===hit?last.s+=text[i2]:parts.push({s:text[i2],hit})}return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:parts.map((p2,i2)=>p2.hit?jsxRuntimeExports.jsx("span",{className:"text-[var(--zg-accent)] font-semibold",children:p2.s},i2):jsxRuntimeExports.jsx("span",{children:p2.s},i2))})}const PREFETCH_MS=120,SHOW_MIN_MS=220,CACHE_MAX=300,CACHE_TTL_MS=1e4,BUSY_RETRY_MS=1500,BUSY_RETRIES=80,SETTLE_RETRIES=3,NO_ACTIONS=[];function useHoverCard(fetch,actions=NO_ACTIONS,docVersion=null,notesAt){const[card,setCard]=reactExports.useState(null),seq=reactExports.useRef(0),timers=reactExports.useRef(new Set),cache=reactExports.useRef(new Map),cacheVersion=reactExports.useRef(docVersion);reactExports.useLayoutEffect(()=>{cacheVersion.current!==docVersion&&(cacheVersion.current=docVersion,cache.current.clear())},[docVersion]);const clear=()=>{for(const id of timers.current)clearTimeout(id);timers.current.clear(),seq.current++,setCard(null)},later=(ms,fn)=>{const id=setTimeout(()=>{timers.current.delete(id),fn()},ms);timers.current.add(id)},onEnter=(t2,_e)=>{clear();const mine=++seq.current,rect=wordRect(t2),column=t2.column,notes=notesAt?.(t2.lineNumber,column)??[];if(!fetch&&notes.length===0)return;const key2=`${t2.lineNumber}:${column}`,started=performance.now(),show=(text,busy)=>{if(mine!==seq.current||!text&&!busy&&notes.length===0)return;const wait=Math.max(0,SHOW_MIN_MS-(performance.now()-started));later(wait,()=>{mine===seq.current&&setCard({text,...busy?{busy}:{},notes,rect,line:t2.lineNumber,column})})};if(!fetch){show(null);return}const hit=cache.current.get(key2);if(hit&&performance.now()-hit.at<CACHE_TTL_MS){show(hit.text);return}notes.length>0&&show(null);const version=cacheVersion.current,ask=(tries,settle)=>{fetch(t2.lineNumber,column).catch(()=>({text:null})).then(({text,busy})=>{if(mine===seq.current){if(text&&cacheVersion.current===version&&(cache.current.size>=CACHE_MAX&&cache.current.clear(),cache.current.set(key2,{text,at:performance.now()})),text||busy){show(text,text?void 0:busy),!text&&tries<BUSY_RETRIES&&later(BUSY_RETRY_MS,()=>ask(tries+1,SETTLE_RETRIES));return}if(settle>0){later(BUSY_RETRY_MS,()=>ask(tries+1,settle-1));return}notes.length>0?show(null):setCard(null)}})};later(PREFETCH_MS,()=>ask(0,0))};reactExports.useEffect(()=>()=>clear(),[]);const[lastCard,setLastCard]=reactExports.useState(null);card&&card!==lastCard&&setLastCard(card);const{mounted}=usePresence(card!==null,{exitMs:readMenuExitMs}),shown=mounted?card??lastCard:null;return{onEnter,onLeave:clear,node:shown?jsxRuntimeExports.jsx(HoverCardView,{card:shown,open:card!==null,actions,onAction:clear}):null}}function wordRect(t2){const node=t2.element.firstChild;if(node&&node.nodeType===Node.TEXT_NODE&&(node.textContent?.length??0)>=t2.word.end){const range2=document.createRange();range2.setStart(node,t2.word.start),range2.setEnd(node,t2.word.end);const rect=range2.getBoundingClientRect();if(rect.width>0)return rect}return t2.element.getBoundingClientRect()}function HoverCardView({card,open,actions,onAction}){const ref=reactExports.useRef(null),[pos,setPos]=reactExports.useState(null);reactExports.useLayoutEffect(()=>{const el=ref.current;if(!el)return;const{width,height}=el.getBoundingClientRect(),margin=8,left=Math.max(margin,Math.min(card.rect.left,window.innerWidth-width-margin)),below=card.rect.bottom+4;below+height<=window.innerHeight-margin?setPos({left,top:below}):setPos({left,bottom:window.innerHeight-card.rect.top+4})},[card]);const sections=reactExports.useMemo(()=>card.text?renderHover(card.text):[],[card.text]);return reactDomExports.createPortal(jsxRuntimeExports.jsxs("div",{role:"tooltip",ref,"data-state":open?"open":"closed","data-side":pos?.bottom!==void 0?"top":"bottom",className:`zg-float zg-menu-motion zg-hover-card fixed z-30 max-w-[36rem] max-h-64 overflow-auto text-zg-label leading-zg-ui ${pos?.bottom!==void 0?"origin-bottom-left":"origin-top-left"}`,style:pos??{left:card.rect.left,top:card.rect.bottom+4,visibility:"hidden"},children:[card.notes.length>0&&jsxRuntimeExports.jsx("ul",{className:"zg-hover-section m-0 list-none flex flex-col gap-0.5",children:card.notes.map((d2,i2)=>jsxRuntimeExports.jsxs("li",{className:"flex items-start gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:`${DIAGNOSTIC_GLYPH[d2.severity].icon} ${DIAGNOSTIC_GLYPH[d2.severity].tone} shrink-0 mt-[3px] text-zg-label`,"aria-hidden":!0}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 whitespace-pre-wrap break-words",children:[d2.message,jsxRuntimeExports.jsx("span",{className:"zg-meta ml-1.5",children:d2.code?`${d2.source}(${d2.code})`:d2.source})]})]},i2))}),card.busy&&!card.text&&jsxRuntimeExports.jsxs("div",{role:"status",className:"zg-hover-section flex items-center gap-1.5 text-[var(--zg-text-muted)]",children:[jsxRuntimeExports.jsx("span",{className:"i-ph-circle-notch animate-spin text-zg-label shrink-0","aria-hidden":!0}),jsxRuntimeExports.jsx("span",{className:"min-w-0 truncate",children:card.busy})]}),sections.map((section,i2)=>jsxRuntimeExports.jsx("div",{className:"zg-hover-section",children:section},i2)),actions.length>0&&jsxRuntimeExports.jsx("div",{className:actions.length>1?"zg-hover-section flex flex-wrap gap-x-3":"zg-hover-section",children:actions.map(action=>jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>{onAction(),action.run(card.line,card.column)},className:"bg-transparent border-0 p-0 cursor-pointer text-zg-meta leading-4 text-[var(--zg-text-muted)] hover:text-[var(--zg-accent)]",children:action.label},action.label))})]}),document.body)}const tokenCache=new Map,TOKEN_CACHE_MAX=200;function hoverLanguage(fence){return fence.trim().toLowerCase()||null}async function highlightHover(highlighter,code,lang,theme){const key2=`${theme}\0${lang}\0${code}`,hit=tokenCache.get(key2);if(hit)return hit;const html=await highlighter.highlight(code,lang,theme);if(html===null)throw new Error("highlight failed");const out=tokensFromHtml(html);return tokenCache.size>=TOKEN_CACHE_MAX&&tokenCache.clear(),tokenCache.set(key2,out),out}function tokensFromHtml(html){const tpl=document.createElement("template");tpl.innerHTML=html;const lines=[[]];for(const node of tpl.content.querySelector("code")?.childNodes??[]){const color=node instanceof HTMLElement?node.style.color:"";(node.textContent??"").split(`
1103
1103
  `).forEach((content,i2)=>{i2>0&&lines.push([]),content&&lines[lines.length-1].push(color?{content,color}:{content})})}return lines}function HoverCode({code,lang,className,style}){const{highlighter,theme}=useCodeHighlight(),language=hoverLanguage(lang),key2=language?`${theme}\0${language}\0${code}`:null,[highlighted,setHighlighted]=reactExports.useState(null),tokens=key2?highlighted?.key===key2?highlighted.tokens:tokenCache.get(key2)??null:null;return reactExports.useEffect(()=>{if(!language||!key2)return;let live=!0;return highlightHover(highlighter,code,language,theme).then(t2=>{live&&setHighlighted({key:key2,tokens:t2})}).catch(()=>{}),()=>{live=!1}},[highlighter,code,language,theme,key2]),jsxRuntimeExports.jsx("pre",{className:["zg-hover-code",className].filter(Boolean).join(" "),style,children:tokens?tokens.map((line,i2)=>jsxRuntimeExports.jsx("span",{className:"block",children:line.map((t2,j2)=>t2.color?jsxRuntimeExports.jsx("span",{style:{color:t2.color},children:t2.content},j2):t2.content)},i2)):code})}function renderHover(markdown){const out=[],lines=markdown.split(`
1104
1104
  `);let i2=0,key2=0;for(;i2<lines.length;){const fence=/^```(\S*)/.exec(lines[i2]);if(fence){const code=[];for(i2++;i2<lines.length&&!lines[i2].startsWith("```");)code.push(lines[i2++]);i2++,out.push(jsxRuntimeExports.jsx(HoverCode,{code:code.join(`
1105
- `),lang:fence[1]},key2++));continue}const para=[];for(;i2<lines.length&&!lines[i2].startsWith("```")&&lines[i2].trim()!=="";)para.push(lines[i2++]);para.length?out.push(jsxRuntimeExports.jsx("p",{className:"m-0",children:inline(para.join(" "))},key2++)):i2++}return out}const INLINE=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|_[^_]+_)/g;function inline(text){return text.split(INLINE).map((part,idx)=>part.startsWith("`")?jsxRuntimeExports.jsx("code",{children:part.slice(1,-1)},idx):part.startsWith("**")?jsxRuntimeExports.jsx("strong",{children:part.slice(2,-2)},idx):(part.startsWith("*")||part.startsWith("_"))&&part.length>2?jsxRuntimeExports.jsx("em",{children:part.slice(1,-1)},idx):part)}function DiagnosticAnnotation({items,onAddToChat,className,style}){const labels=useLabels();return jsxRuntimeExports.jsx("ul",{className:["m-0 p-0 list-none flex flex-col gap-1 px-3 py-1.5 border-s-2 border-[var(--zg-border-strong)] bg-[var(--zg-tray)] font-sans",className].filter(Boolean).join(" "),style,children:items.map((d2,i2)=>{const g2=DIAGNOSTIC_GLYPH[d2.severity];return jsxRuntimeExports.jsxs("li",{className:"group flex items-start gap-2 text-zg-meta leading-4",children:[jsxRuntimeExports.jsx("span",{className:`${g2.icon} ${g2.tone} text-zg-label shrink-0 mt-px`,"aria-hidden":!0}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 text-[var(--zg-text)] whitespace-pre-wrap break-words",children:[d2.message,jsxRuntimeExports.jsx("span",{className:"zg-meta ml-1.5",children:d2.code?`${d2.source}(${d2.code})`:d2.source})]}),onAddToChat&&jsxRuntimeExports.jsx(Tooltip,{label:labels.addToChat,portal:!0,children:jsxRuntimeExports.jsx(IconButton,{size:"xs",icon:"i-ph-chat-teardrop-text",label:labels.addDiagnosticToChat(d2.message),title:"",onClick:()=>onAddToChat(d2),className:"opacity-0 group-hover:opacity-100 focus-visible:opacity-100"})})]},i2)})})}function useDefinition(scope,enabled,resolve,navigate){const[modifier,setModifier]=reactExports.useState(!1),[linked,setLinked]=reactExports.useState(!1),shown=reactExports.useRef(!1),hovered=reactExports.useRef(null),lookup=reactExports.useRef(null);reactExports.useEffect(()=>{if(!enabled)return;const down=e2=>(e2.key==="Meta"||e2.key==="Control")&&setModifier(!0),up=e2=>(e2.key==="Meta"||e2.key==="Control")&&setModifier(!1),blur=()=>setModifier(!1);return window.addEventListener("keydown",down),window.addEventListener("keyup",up),window.addEventListener("blur",blur),()=>{window.removeEventListener("keydown",down),window.removeEventListener("keyup",up),window.removeEventListener("blur",blur)}},[enabled]);const show=reactExports.useCallback(on=>{shown.current!==on&&(shown.current=on,setLinked(on))},[]),unlink=reactExports.useCallback(()=>{hovered.current?.link(!1),lookup.current=null,show(!1)},[show]),ask=reactExports.useCallback(t2=>{const answer=resolve(t2.lineNumber,t2.column).catch(()=>[]),mine={line:t2.lineNumber,column:t2.column,span:null,answer};lookup.current=mine,answer.then(targets=>{if(lookup.current!==mine||hovered.current!==t2||targets.length===0)return;const span=originColumns(targets[0].origin,t2);mine.span=span??{column:t2.lineCharStart+t2.word.start+1,endColumn:t2.lineCharStart+t2.word.end+1},t2.link(!0,span??void 0),show(!0)})},[resolve,show]);reactExports.useEffect(()=>{!enabled||!modifier?unlink():hovered.current&&ask(hovered.current)},[enabled,modifier,ask,unlink]);const onEnter=reactExports.useCallback(t2=>{unlink(),hovered.current=t2,enabled&&modifier&&ask(t2)},[enabled,modifier,ask,unlink]),onLeave=reactExports.useCallback(()=>{unlink(),hovered.current=null},[unlink]),asked=reactExports.useRef(0);reactExports.useEffect(()=>()=>{asked.current++,lookup.current=null},[scope]);const goTo=reactExports.useCallback(async(line,column)=>{if(!enabled)return!1;const mine=++asked.current,held=lookup.current,targets=await(held!==null&&held.line===line&&(held.column===column||held.span!==null&&column>=held.span.column&&column<held.span.endColumn)?held.answer:resolve(line,column).catch(()=>[]));return mine!==asked.current||targets.length===0?!1:(navigate(targets[0]),!0)},[enabled,resolve,navigate]),onClick=reactExports.useCallback((t2,e2)=>{!enabled||!(e2.metaKey||e2.ctrlKey)||(e2.preventDefault(),goTo(t2.lineNumber,t2.column))},[enabled,goTo]);return{enabled,linking:enabled&&modifier&&linked,onEnter,onLeave,onClick,goTo}}function originColumns(origin,t2){return!origin||origin.line!==t2.lineNumber||origin.endLine!==origin.line||t2.column<origin.column||t2.column>=origin.endColumn?null:{column:origin.column,endColumn:origin.endColumn}}const REVEAL_MAX_FRAMES=90;function useRevealLine(editor,reveal,select,caret){reactExports.useEffect(()=>{if(!reveal)return;select(reveal.line);let tries=0,id=0,caretPlaced=!caret;const tick=()=>{const host=editor.current?.host(),scroller=host?.querySelector(".zg-code-scroller"),root=host?.querySelector("diffs-container")?.shadowRoot,lines=root?.querySelectorAll("[data-line]");if(!scroller||!root||!lines||lines.length===0){tries++<REVEAL_MAX_FRAMES&&(id=requestAnimationFrame(tick));return}const scrollerTop=scroller.getBoundingClientRect().top,centre=top=>{const want=Math.max(0,Math.min(top-scroller.clientHeight/2,scroller.scrollHeight-scroller.clientHeight)),settled=Math.abs(scroller.scrollTop-want)<1;return scroller.scrollTop=want,settled},exact=root.querySelector(`[data-line="${reveal.line}"]`);if(exact){const settled=centre(exact.getBoundingClientRect().top-scrollerTop+scroller.scrollTop);caretPlaced||(caretPlaced=!0,editor.current?.placeCaret({lineNumber:reveal.line,character:Math.max(0,reveal.column-1)})),!settled&&tries++<REVEAL_MAX_FRAMES&&(id=requestAnimationFrame(tick));return}const probe=lines[0],probeLine=Number.parseInt(probe.getAttribute("data-line")??"",10),lineHeight=probe.getBoundingClientRect().height;if(Number.isFinite(probeLine)&&lineHeight>0){const probeTop=probe.getBoundingClientRect().top-scrollerTop+scroller.scrollTop;centre(probeTop+(reveal.line-probeLine)*lineHeight)}tries++<REVEAL_MAX_FRAMES&&(id=requestAnimationFrame(tick))};return id=requestAnimationFrame(tick),()=>cancelAnimationFrame(id)},[reveal?.line,reveal?.column,reveal?.nonce])}const MAX_CHANGES=1e3,buffers=new Map,key=(cwd,path)=>`${cwd}\0${path}`;function recordEdits(cwd,path,changes){const k2=key(cwd,path),buf=buffers.get(k2)??{changes:[],complete:!0};buf.complete&&buf.changes.push(...changes),buf.changes.length>MAX_CHANGES&&(buf.changes=[],buf.complete=!1),buffers.set(k2,buf)}function resetEdits(cwd,path){buffers.set(key(cwd,path),{changes:[],complete:!1})}function takeEdits(cwd,path){const k2=key(cwd,path),buf=buffers.get(k2);if(buffers.set(k2,{changes:[],complete:!0}),!(!buf||!buf.complete))return buf.changes}function forgetEdits(cwd,path){buffers.delete(key(cwd,path))}const CHANGE_DEBOUNCE_MS=300,docs=new Map,docKey=(cwd,path)=>`${cwd}\0${path}`;function setItems(doc,items){doc.items=items;for(const l2 of doc.listeners)l2()}function attachLspDoc(lsp,cwd,path,text){const key2=docKey(cwd,path),existing=docs.get(key2);if(existing)return existing.views++,text!==existing.synced&&updateLspDoc(existing,text),existing;const doc={lsp,cwd,path,items:null,views:1,synced:text,timer:null,listeners:new Set,off:()=>{}};return docs.set(key2,doc),resetEdits(cwd,path),takeEdits(cwd,path),lsp.open(cwd,path,text).then(known=>docs.get(key2)===doc&&doc.items===null&&setItems(doc,known)).catch(()=>{}),doc.off=lsp.onDiagnostics((atCwd,atPath,diagnostics)=>{atCwd===cwd&&atPath===path&&setItems(doc,diagnostics)}),doc}function updateLspDoc(doc,text){text!==doc.synced&&(doc.synced=text,doc.timer&&clearTimeout(doc.timer),doc.timer=setTimeout(()=>{doc.timer=null,docs.get(docKey(doc.cwd,doc.path))===doc&&doc.lsp.open(doc.cwd,doc.path,doc.synced,takeEdits(doc.cwd,doc.path)).catch(()=>{})},CHANGE_DEBOUNCE_MS))}function syncLspDocNow(cwd,path,text){const doc=docs.get(docKey(cwd,path));return doc?(doc.timer&&clearTimeout(doc.timer),doc.timer=null,doc.synced=text,{changes:takeEdits(cwd,path)}):null}function detachLspDoc(doc){if(--doc.views>0)return;doc.timer&&clearTimeout(doc.timer),doc.timer=null,doc.off();const key2=docKey(doc.cwd,doc.path);docs.get(key2)===doc&&(docs.delete(key2),forgetEdits(doc.cwd,doc.path)),doc.lsp.close(doc.cwd,doc.path).catch(()=>{})}const noSubscribe=()=>()=>{};function useLsp(cwd,path,text){const ed=useEditorPrefs(),lsp=useFilesHost().lsp,enabled=ed.diagnostics==="lsp"&&lsp!==void 0&&cwd!==null&&path!==null&&!path.startsWith("/")&&text!==null,[doc,setDoc]=reactExports.useState(null),opening=reactExports.useRef(text);opening.current=text,reactExports.useEffect(()=>{if(!enabled||!lsp||!cwd||!path)return;const d2=attachLspDoc(lsp,cwd,path,opening.current??"");return setDoc(d2),()=>{setDoc(cur=>cur===d2?null:cur),detachLspDoc(d2)}},[enabled,lsp,cwd,path]),reactExports.useEffect(()=>{doc&&text!==null&&updateLspDoc(doc,text)},[doc,text]);const subscribe2=reactExports.useCallback(fn=>doc?(doc.listeners.add(fn),()=>doc.listeners.delete(fn)):noSubscribe(),[doc]),read=()=>doc?.items??null,items=reactExports.useSyncExternalStore(subscribe2,read,read),live=doc&&doc.cwd===cwd&&doc.path===path;return enabled&&live?items:null}function useLspConfigSync(){const ed=useEditorPrefs(),lsp=useFilesHost().lsp;reactExports.useEffect(()=>{lsp?.configure({idleMs:ed.lspIdleMin*6e4,overrides:{...ed.lspOverrides}}).catch(()=>{})},[lsp,ed.lspIdleMin,ed.lspOverrides])}const NO_DIAGNOSTICS=[],CodeViewer=reactExports.memo(({cwd,path,readOnly=!1,file,drafts,editKey,diagnostics=NO_DIAGNOSTICS,liveDiagnostics=NO_DIAGNOSTICS,onNavigate,reveal,visible=!0,findAsk=0,onDraft,onAdopt})=>{const ed=useEditorPrefs(),host=useFilesHost(),{write,read,lsp:server,system}=host,labels=useFilesLabels(),completionChange=reactExports.useRef(()=>{}),[initialDraft]=reactExports.useState(()=>drafts.get(path)??null),document2=useCodeDocument({doc:file,initialDraft,initialBase:drafts.baseOf(path),save:reactExports.useCallback(async(text,base2,force)=>{if(!write)throw new Error("write refused: read-only");const expected=force?(await read?.(cwd,path))?.mtimeMs:base2.mtimeMs,result=await write(cwd,path,text,expected??base2.mtimeMs);if(result.ok)return{ok:!0,doc:{...base2,contents:text,size:utf8Bytes(text),mtimeMs:result.mtimeMs}};if(result.reason==="changed")return{ok:!1,reason:"changed"};throw new Error(`write refused: ${result.reason}`)},[write,read,cwd,path]),reload:reactExports.useCallback(async()=>read?read(cwd,path):null,[read,cwd,path]),onChange:reactExports.useCallback((text,changes)=>{recordEdits(cwd,path,changes),completionChange.current(text,changes)},[cwd,path]),onDraft:reactExports.useCallback((text,base2)=>onDraft(path,text,base2),[onDraft,path]),onAdopt:reactExports.useCallback((next,reset)=>{reset&&resetEdits(cwd,path),onAdopt(path,next,reset)},[cwd,path,onAdopt])}),{contents,dirty,base}=document2,editorHandle=reactExports.useRef(null),lspOn=ed.diagnostics==="lsp"&&server!==void 0,resolveDefinition=reactExports.useCallback(async(line,column)=>server?server.definition(cwd,path,line,column):[],[server,cwd,path]),navigate=reactExports.useCallback(t2=>onNavigate?.(t2),[onNavigate]),definition=useDefinition(`${cwd}\0${path}`,lspOn&&onNavigate!==void 0,resolveDefinition,navigate),findings=reactExports.useMemo(()=>[...dirty?[]:diagnostics,...liveDiagnostics],[diagnostics,liveDiagnostics,dirty]),hover=useHoverCard(lspOn&&ed.lspHover&&server?(line,column)=>server.hover(cwd,path,line,column):null,reactExports.useMemo(()=>definition.enabled?[{label:labels.filesGoToDefinition,run:definition.goTo}]:[],[definition.enabled,definition.goTo,labels]),contents,(line,column)=>diagnosticsAt(findings,line,column)),completionSource=reactExports.useMemo(()=>lspOn&&ed.lspCompletion&&server?{complete:(text,line,character,trigger)=>{const sync=syncLspDocNow(cwd,path,text);return sync?server.completion(cwd,path,text,sync.changes,line+1,character+1,trigger):Promise.resolve({id:0,items:[],incomplete:!1})},resolve:(id,index)=>server.resolveCompletion(cwd,path,id,index)}:null,[lspOn,ed.lspCompletion,server,cwd,path]),completion=useCompletion(completionSource,editorHandle);completionChange.current=completion.onChange;const onTokenEnter=(t2,e2)=>{definition.onEnter(t2),!(completion.open||e2.metaKey||e2.ctrlKey)&&hover.onEnter(t2)},onTokenClick=(t2,e2)=>{hover.onLeave(),definition.onClick(t2,e2)};reactExports.useEffect(()=>{visible||hover.onLeave()},[visible]);const onTokenLeave=()=>{hover.onLeave(),definition.onLeave()};reactExports.useEffect(()=>{if(!lspOn)return;const onKey=e2=>{(e2.key==="Meta"||e2.key==="Control")&&hover.onLeave()};return window.addEventListener("keydown",onKey),()=>window.removeEventListener("keydown",onKey)},[lspOn]);const extraItems=reactExports.useMemo(()=>fileActionItems({cwd,path,kind:"file"},{labels,system,only:["copy-path","editor","reveal"],shortcuts:!1}),[cwd,path,labels,system]),chat=useFilesChat(),review=useCodeReview({filePath:path,kind:"file",excerptOf:range2=>excerptFromContents(contents,range2),extraItems,chat});useRevealLine(editorHandle,reveal,line=>review.onSelectionEnd({start:line,end:line}),ed.editing);const annotations=reactExports.useMemo(()=>{const out=[],byLine=diagnosticsByLine([...dirty?[]:diagnostics,...liveDiagnostics]);for(const[lineNumber,items]of byLine)out.push({lineNumber,metadata:{kind:"diagnostics",items}});return review.draft&&out.push({lineNumber:Math.max(review.draft.start,review.draft.end),metadata:{kind:"draft",range:review.draft}}),out},[diagnostics,liveDiagnostics,dirty,review.draft]),addDiagnosticToChat=d2=>{if(!chat)return;const range2={start:d2.line,end:d2.endLine??d2.line},body=serializeDiagnostic({filePath:path,rangeLabel:rangeLabel(range2),excerpt:excerptFromContents(base.contents,range2),language:languageFor(path),severity:d2.severity,source:d2.source,...d2.code?{code:d2.code}:{},diagnosticMessage:d2.message});chat.attach(attachmentName("diagnostic",path,rangeLabel(range2)),body)},renderAnnotation=a2=>a2.metadata?.kind==="diagnostics"?jsxRuntimeExports.jsx(DiagnosticAnnotation,{items:a2.metadata.items,onAddToChat:addDiagnosticToChat}):review.draftNode,markers=reactExports.useMemo(()=>diagnosticMarkers(findings),[findings]);return jsxRuntimeExports.jsxs(CodeEditor,{ref:editorHandle,path,doc:document2,sessionKey:editKey,readOnly:readOnly||!write,visible,findAsk,markers,selectedLines:review.selected,onSelectionEnd:review.onSelectionEnd,onGutterAction:review.canComment?review.openDraft:void 0,onContextMenu:review.onContextMenu,onTokenEnter,onTokenLeave,onTokenClick,annotations,renderAnnotation,hostAttributes:{"data-zg-linking":definition.linking?"true":void 0},children:[review.menuNode,hover.node,completion.node]})});CodeViewer.displayName="CodeViewer";function utf8Bytes(text){return new TextEncoder().encode(text).length}function useDiffPrimer(){const pool=useWorkerPool();return reactExports.useCallback(diff=>{const work=diff&&pool?.primeDiffHighlightCache(diff);return work?new Promise(resolve=>{const timer=setTimeout(resolve,REVEAL_FALLBACK_MS);work.catch(()=>{}).then(()=>{clearTimeout(timer),resolve()})}):Promise.resolve()},[pool])}const RELOAD_DEBOUNCE_MS=300;function DiffFileViewer({cwd,path,file,onUnavailable,findAsk=0,visible=!0,onReady}){const diffOf=useFilesHost().workingTreeDiff,labels=useFilesLabels(),prime=useDiffPrimer(),contents=file.contents,[fileDiff,setFileDiff]=reactExports.useState(null),loaded=reactExports.useRef(!1);reactExports.useEffect(()=>{let live=!0;const load=()=>(diffOf?diffOf(cwd,{path,context:1/0}):Promise.reject(new Error("no working-tree diff"))).then(patch=>{if(!live)return;const next=parseFilePatch(patch,`${cwd}:${path}:`);return prime(next).then(()=>{live&&(loaded.current=!0,setFileDiff(next))})}).catch(()=>live&&setFileDiff(void 0)),timer=loaded.current?window.setTimeout(()=>{load()},RELOAD_DEBOUNCE_MS):null;return timer===null&&load(),()=>{live=!1,timer!==null&&window.clearTimeout(timer)}},[diffOf,prime,cwd,path,contents]),reactExports.useEffect(()=>{fileDiff===void 0?onUnavailable():fileDiff&&onReady?.(path)},[fileDiff,onUnavailable,onReady,path]);const scroller=reactExports.useRef(null),reducedMotion=useAppearanceReducedMotion(),rows=reactExports.useMemo(()=>fileDiff?diffLines(fileDiff):[],[fileDiff]),find=useFind({parts:()=>[{part:"",lines:rows}],version:rows,surfaces:()=>{const root=scroller.current?.querySelector("diffs-container")?.shadowRoot;return root?[{part:"",root}]:[]},scroller:()=>scroller.current,fallback:(m2,root)=>estimateRowTop(root,rows.findIndex(r2=>r2.side===m2.side&&r2.line===m2.line)),smooth:!reducedMotion}),seenAsk=reactExports.useRef(findAsk),show=find.show;return reactExports.useEffect(()=>{findAsk!==seenAsk.current&&(seenAsk.current=findAsk,visible&&show())},[findAsk,show,visible]),fileDiff===null?jsxRuntimeExports.jsx(PanelLoading,{}):fileDiff===void 0?null:jsxRuntimeExports.jsxs("div",{className:"relative flex-1 min-h-0 flex flex-col",children:[jsxRuntimeExports.jsx("div",{ref:el=>{scroller.current=el?.firstElementChild??null},className:"contents",children:jsxRuntimeExports.jsx(DiffScroller,{className:"flex-1 min-h-0 overflow-auto",children:jsxRuntimeExports.jsx(ReviewableDiff,{fileDiff,diffStyle:"unified",wrap:!1,hideHeader:!0})})}),jsxRuntimeExports.jsx(FindBar,{find,label:labels.filesFindInDiff})]})}function estimateRowTop(scroller,row){const probe=scroller.querySelector("diffs-container")?.shadowRoot?.querySelector("[data-line-index]:not([data-column-number])"),probeRow=Number(probe?.getAttribute("data-line-index")?.split(",")[0]),rect=probe?.getBoundingClientRect();return row<0||!rect||!Number.isFinite(probeRow)||rect.height<=0?void 0:{top:rect.top-scroller.getBoundingClientRect().top+scroller.scrollTop+(row-probeRow)*rect.height}}EditStateManager.setCapacity(20);function editSessionKey(cwd,path,generation){return`${cwd}:${path}:${generation}`}function forgetEditSession(key2){setTimeout(()=>EditStateManager.clear("file",key2),0)}class DraftStore{drafts=new Map;listeners=new Map;get(path){return this.drafts.get(path)?.text}baseOf(path){return this.drafts.get(path)?.base}has(path){return this.drafts.has(path)}set(path,contents,base){const prev=this.drafts.get(path);if(contents===null){if(!prev)return;this.drafts.delete(path)}else{if(prev?.text===contents){base&&(prev.base=base);return}this.drafts.set(path,{text:contents,base:base??prev?.base})}for(const fn of this.listeners.get(path)??[])fn()}get idle(){return this.drafts.size===0&&this.listeners.size===0}subscribe(path,fn){let set=this.listeners.get(path);return set||this.listeners.set(path,set=new Set),set.add(fn),()=>{set.delete(fn),set.size===0&&this.listeners.get(path)===set&&this.listeners.delete(path)}}}function useDraft(store,path){const subscribe2=reactExports.useCallback(fn=>path?store.subscribe(path,fn):()=>{},[store,path]),read=()=>path?store.get(path)??null:null;return reactExports.useSyncExternalStore(subscribe2,read,read)}function useIsDirty(store,path){const subscribe2=reactExports.useCallback(fn=>path?store.subscribe(path,fn):()=>{},[store,path]),read=()=>path?store.has(path):!1;return reactExports.useSyncExternalStore(subscribe2,read,read)}class FolderBuffers{constructor(root){this.root=root}root;drafts=new DraftStore;generations=new Map;slots=new Map;claim(path){let taken=this.slots.get(path);taken||this.slots.set(path,taken=new Set);let slot=0;for(;taken.has(slot);)slot++;return taken.add(slot),{slot,generation:this.generations.get(path)??0}}release(path,held){const taken=this.slots.get(path);taken?.delete(held.slot),taken?.size===0&&this.slots.delete(path),held.slot!==0&&forgetEditSession(this.key(path,held))}get idle(){return this.drafts.idle&&this.slots.size===0}forgetSessions(){for(const[path,generation]of this.generations)for(let g2=0;g2<=generation;g2++)forgetEditSession(editSessionKey(this.root,path,g2))}holders(path){return this.slots.get(path)?.size??0}key(path,held){const base=editSessionKey(this.root,path,held.generation);return held.slot===0?base:`${base}#${held.slot}`}reset(path,held){forgetEditSession(this.key(path,held));const generation=(this.generations.get(path)??0)+1;return this.generations.set(path,generation),{slot:held.slot,generation}}}const folders=new Map,MAX_FOLDERS=32;function folderBuffers(root){let buffers2=folders.get(root);if(buffers2)return folders.delete(root),folders.set(root,buffers2),buffers2;folders.set(root,buffers2=new FolderBuffers(root));for(const[oldRoot,old]of folders){if(folders.size<=MAX_FOLDERS)break;old===buffers2||!old.idle||(folders.delete(oldRoot),old.forgetSessions())}return buffers2}const BY_EXTENSION={md:"markdown",markdown:"markdown",mdx:"markdown",html:"html",htm:"html"};function previewKindOfPath(path){const name=path.slice(path.lastIndexOf("/")+1).toLowerCase(),dot=name.lastIndexOf(".");return dot>0?BY_EXTENSION[name.slice(dot+1)]??null:null}function resolveWorkspaceLink(from,url){if(url===""||url.startsWith("#")||url.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(url))return null;const bare2=url.replace(/[?#].*$/,"");if(bare2==="")return null;let decoded;try{decoded=decodeURIComponent(bare2)}catch{decoded=bare2}const parts=[...decoded.startsWith("/")?[]:from.split("/").slice(0,-1)];for(const part of decoded.split("/"))if(!(part===""||part==="."))if(part===".."){if(parts.length===0)return null;parts.pop()}else parts.push(part);return parts.length>0?parts.join("/"):null}function githubRepoOfOrigin(origin){const match=/^(?:[a-z+]+:\/\/)?(?:[^@/]+@)?github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?\/?$/i.exec(origin.trim());return match?`${match[1]}/${match[2]}`.toLowerCase():null}function githubFileInRepo(url,repo){let parsed;try{parsed=new URL(url)}catch{return null}if(parsed.protocol!=="https:"&&parsed.protocol!=="http:")return null;const parts=parsed.pathname.split("/").filter(Boolean),host=parsed.hostname.toLowerCase();let rest;if(host==="github.com"||host==="www.github.com"){if(parts[2]!=="blob"&&parts[2]!=="raw")return null;rest=[parts[0]??"",parts[1]??"",...parts.slice(4)]}else if(host==="raw.githubusercontent.com")rest=[parts[0]??"",parts[1]??"",...parts.slice(3)];else return null;if(`${rest[0]}/${rest[1]}`.toLowerCase()!==repo)return null;const path=rest.slice(2);if(path.length===0)return null;try{return path.map(decodeURIComponent).join("/")}catch{return null}}const PREVIEW_FRAME_SANDBOX="allow-scripts",FilePreview=reactExports.memo(({kind,...props})=>kind==="markdown"?jsxRuntimeExports.jsx(MarkdownPreview,{...props}):jsxRuntimeExports.jsx(HtmlPreview,{path:props.path,text:props.text}));FilePreview.displayName="FilePreview";async function copyText(text){try{await navigator.clipboard.writeText(text)}catch(err){console.error("[zidane-ui] clipboard write failed",err)}}function selectionIn(root){const selection=root.ownerDocument.getSelection();if(!selection||selection.isCollapsed||!selection.anchorNode||!root.contains(selection.anchorNode))return null;const text=selection.toString();return text.trim()?text:null}function MarkdownPreview({cwd,path,text,version,onOpenFile,onRevealFolder}){const host=useFilesHost(),labels=useFilesLabels(),kitLabels=useLabels(),chat=useFilesChat(),links=useLinkRouter(),lightbox=useLightbox(),rootRef=reactExports.useRef(null),[menu,setMenu]=reactExports.useState(null),mediaUrl=host.mediaUrl,repo=useGithubRepo(cwd),inFolder2=reactExports.useCallback(url=>resolveWorkspaceLink(path,url)??(repo?githubFileInRepo(url,repo):null),[path,repo]),urlTransform=reactExports.useCallback((url,key2)=>{if(key2==="src"&&mediaUrl){const target=inFolder2(url);if(target&&mediaTypeOfPath(target)?.kind==="image")return mediaUrl({kind:"file",cwd,path:target,version})}return safeUrl(url)},[cwd,version,mediaUrl,inFolder2]),onClickCapture=e2=>{const anchor=e2.target.closest?.("a[href]"),href=anchor?.getAttribute("href");if(!anchor||href==null)return;const target=href.startsWith("#")?null:inFolder2(href);!href.startsWith("#")&&target===null||(e2.preventDefault(),e2.stopPropagation(),target!==null&&(href.replace(/[?#].*$/,"").endsWith("/")?onRevealFolder?.(target):onOpenFile?.(target)))},onClick=e2=>{const image=e2.target instanceof HTMLImageElement?e2.target:null;if(!image||image.closest("a")||!rootRef.current)return;const images=Array.from(rootRef.current.querySelectorAll("img")).filter(img=>!img.closest("a"));lightbox.open(images.map((img,i2)=>({key:`${i2}:${img.currentSrc||img.src}`,name:img.alt||path,src:img.currentSrc||img.src})),images.indexOf(image),image)},onContextMenu=e2=>{const root=rootRef.current;if(!root)return;const element=e2.target,image=element instanceof HTMLImageElement?element:null,link=element.closest?.("a[href]")?.getAttribute("href")??null,selection=selectionIn(root);!image&&!link&&!selection||(e2.preventDefault(),setMenu({target:{selection,image,link},at:{x:e2.clientX,y:e2.clientY}}))},items=[];if(menu){const{selection,image,link}=menu.target;if(selection){const what=labels.filesSelection,attach=()=>chat?.attach(attachmentName("snippet",path,null),serializeCodeSnippet({filePath:path,rangeLabel:null,excerpt:selection,language:"markdown"}));items.push(chat?{id:"chat",label:labels.filesAddWhatToChat(what),shortcut:"a",group:"text",onSelect:attach}:{...noChatItem("chat",labels.filesAddWhatToChat(what),labels),group:"text"},{id:"copy",label:labels.filesCopyWhat(what),shortcut:"c",group:"text",onSelect:()=>{copyText(selection)}})}if(image){const src=image.currentSrc||image.src,copy=run=>()=>{run(src).catch(()=>{})};items.push({id:"copy-image",label:kitLabels.copyImage,group:"image",onSelect:copy(copyImage)},{id:"copy-base64",label:kitLabels.copyImageBase64,group:"image",onSelect:copy(copyImageBase64)},{id:"copy-data-url",label:kitLabels.copyImageDataUrl,group:"image",onSelect:copy(copyImageDataUrl)})}if(link&&!link.startsWith("#")){const target=inFolder2(link);items.push({id:"open-link",label:labels.filesOpenLink,group:"link",onSelect:()=>{target===null?links.open(link,{source:"other"}):link.replace(/[?#].*$/,"").endsWith("/")?onRevealFolder?.(target):onOpenFile?.(target)}},{id:"copy-link",label:labels.filesCopyLink,group:"link",onSelect:()=>{copyText(link)}})}}return jsxRuntimeExports.jsxs("div",{ref:rootRef,className:"zg-file-preview flex-1 min-h-0 overflow-auto px-6 py-4 select-text","data-testid":"file-preview",role:"presentation",onClickCapture,onClick,onContextMenu,children:[jsxRuntimeExports.jsx(Markdown,{document:!0,urlTransform,children:text}),jsxRuntimeExports.jsx(RowActionsMenu,{open:menu!==null,position:menu?.at??null,onClose:()=>setMenu(null),items}),lightbox.element]})}function useGithubRepo(cwd){const originUrl=useGitHost()?.originUrl,[read,setRead]=reactExports.useState(null);return reactExports.useEffect(()=>{if(!originUrl)return;let cancelled=!1;return originUrl(cwd).then(origin=>{cancelled||setRead({cwd,repo:origin?githubRepoOfOrigin(origin):null})}).catch(()=>{cancelled||setRead({cwd,repo:null})}),()=>{cancelled=!0}},[cwd,originUrl]),read?.cwd===cwd?read.repo:null}function safeUrl(url){const colon=url.indexOf(":"),cut=Math.min(...["/","?","#"].map(c2=>url.includes(c2)?url.indexOf(c2):1/0));return colon===-1||colon>cut||/^(?:https?|mailto|tel)$/i.test(url.slice(0,colon))?url:""}function HtmlPreview({path,text}){const labels=useFilesLabels(),frameRef=reactExports.useRef(null);return reactExports.useEffect(()=>{const frame=frameRef.current;if(!frame)return;const url=URL.createObjectURL(new Blob([text],{type:"text/html"}));return frame.src=url,()=>URL.revokeObjectURL(url)},[text]),jsxRuntimeExports.jsx("div",{className:"flex-1 min-h-0 flex","data-testid":"file-preview",children:jsxRuntimeExports.jsx("iframe",{ref:frameRef,className:"zg-file-preview-frame flex-1 min-w-0 min-h-0",sandbox:PREVIEW_FRAME_SANDBOX,title:labels.filesRenderedTitle(path.slice(path.lastIndexOf("/")+1))})})}function DiagnosticsChip({state,items,label,onClick,className,style}){const counts=countBySeverity(items),clean=state==="checked"&&counts.errors+counts.warnings+counts.other===0;return jsxRuntimeExports.jsx(Tooltip,{label,portal:!0,className,style,children:jsxRuntimeExports.jsx("button",{type:"button",onClick,"aria-label":label,className:"zg-segment-item zg-press-soft zg-meta inline-flex items-center gap-1.5 h-5 px-1.5 rounded-full border-0 bg-transparent cursor-pointer shrink-0 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-[var(--zg-ring)]",children:state==="running"?jsxRuntimeExports.jsx("span",{className:"i-ph-circle-notch animate-spin text-zg-label","aria-hidden":!0}):clean?jsxRuntimeExports.jsx("span",{className:"i-ph-check-circle-fill text-zg-label text-zg-success","aria-hidden":!0}):state!=="checked"?jsxRuntimeExports.jsx("span",{className:`${state==="failed"?"i-ph-warning-circle text-zg-warn":"i-ph-circle-dashed"} text-zg-label`,"aria-hidden":!0}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[counts.errors>0&&jsxRuntimeExports.jsxs("span",{className:"inline-flex items-center gap-0.5 text-zg-danger",children:[jsxRuntimeExports.jsx("span",{className:"i-ph-x-circle-fill text-zg-label","aria-hidden":!0}),counts.errors]}),counts.warnings>0&&jsxRuntimeExports.jsxs("span",{className:"inline-flex items-center gap-0.5 text-zg-warn",children:[jsxRuntimeExports.jsx("span",{className:"i-ph-warning text-zg-label","aria-hidden":!0}),counts.warnings]}),counts.other>0&&jsxRuntimeExports.jsxs("span",{className:"inline-flex items-center gap-0.5 text-zg-info",children:[jsxRuntimeExports.jsx("span",{className:"i-ph-info text-zg-label","aria-hidden":!0}),counts.other]})]})})})}function FilesDiagnosticsChip({diagnostics,live}){const labels=useFilesLabels(),{items,failed,running:toolsRunning,rerun}=diagnostics,running=toolsRunning&&live===null,servers=live?[...new Set(live.map(d2=>d2.source))]:[],ran=[...diagnostics.ran,...live!==null&&servers.length===0?[labels.filesLanguageServer]:servers],failedIds=failed.map(f2=>f2.id),label=running?labels.filesChecking:failed.length>0&&ran.length===0?labels.filesCheckFailed(failedIds):ran.length===0?labels.filesNoTool:labels.filesCheckedBy(ran,failedIds),state=running?"running":ran.length>0?"checked":failed.length?"failed":"idle";return jsxRuntimeExports.jsx(DiagnosticsChip,{state,items:[...items??[],...live??[]],label,onClick:rerun})}function sameEntries(a2,b2){if(a2===b2)return!0;if(!a2||!b2||a2.length!==b2.length)return!1;for(let i2=0;i2<a2.length;i2++){const x2=a2[i2],y2=b2[i2];if(x2.path!==y2.path||x2.kind!==y2.kind||!!x2.ignored!=!!y2.ignored)return!1}return!0}function sameStatus(a2,b2){if(a2===b2)return!0;if(a2.length!==b2.length)return!1;for(let i2=0;i2<a2.length;i2++)if(a2[i2].path!==b2[i2].path||a2[i2].status!==b2[i2].status)return!1;return!0}function sameSet(a2,b2){if(a2===b2)return!0;if(a2.size!==b2.size)return!1;for(const x2 of a2)if(!b2.has(x2))return!1;return!0}function statusDelta(prev,next){const before2=new Map(prev.map(e2=>[e2.path,e2.status])),out=new Set;for(const e2 of next)before2.get(e2.path)!==e2.status&&out.add(e2.path),before2.delete(e2.path);for(const p2 of before2.keys())out.add(p2);return out}function editedPath(ev){const edit=ev.kind==="tool"?ev.edit:void 0;return edit&&(edit.outcomes?edit.hunks.some((_2,i2)=>edit.outcomes?.[i2]?.kind!=="denied"&&edit.outcomes?.[i2]?.kind!=="failed"):edit.hunks.length>0)?edit.path:null}function editedPaths(events){const out=new Set;for(const ev of events){const p2=editedPath(ev);p2!==null&&out.add(p2)}return out}function sameFile(a2,b2){return a2===b2?!0:a2===null||a2==="missing"||b2==="missing"?!1:a2.mtimeMs===b2.mtimeMs&&a2.size===b2.size&&a2.contents===b2.contents&&a2.truncated===b2.truncated}function lineCount(text){let n2=1;for(let i2=text.indexOf(`
1105
+ `),lang:fence[1]},key2++));continue}const para=[];for(;i2<lines.length&&!lines[i2].startsWith("```")&&lines[i2].trim()!=="";)para.push(lines[i2++]);para.length?out.push(jsxRuntimeExports.jsx("p",{className:"m-0",children:inline(para.join(" "))},key2++)):i2++}return out}const INLINE=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|_[^_]+_)/g;function inline(text){return text.split(INLINE).map((part,idx)=>part.startsWith("`")?jsxRuntimeExports.jsx("code",{children:part.slice(1,-1)},idx):part.startsWith("**")?jsxRuntimeExports.jsx("strong",{children:part.slice(2,-2)},idx):(part.startsWith("*")||part.startsWith("_"))&&part.length>2?jsxRuntimeExports.jsx("em",{children:part.slice(1,-1)},idx):part)}function DiagnosticAnnotation({items,onAddToChat,className,style}){const labels=useLabels();return jsxRuntimeExports.jsx("ul",{className:["m-0 p-0 list-none flex flex-col gap-1 px-3 py-1.5 border-s-2 border-[var(--zg-border-strong)] bg-[var(--zg-tray)] font-sans",className].filter(Boolean).join(" "),style,children:items.map((d2,i2)=>{const g2=DIAGNOSTIC_GLYPH[d2.severity];return jsxRuntimeExports.jsxs("li",{className:"group flex items-start gap-2 text-zg-meta leading-4",children:[jsxRuntimeExports.jsx("span",{className:`${g2.icon} ${g2.tone} text-zg-label shrink-0 mt-px`,"aria-hidden":!0}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 text-[var(--zg-text)] whitespace-pre-wrap break-words",children:[d2.message,jsxRuntimeExports.jsx("span",{className:"zg-meta ml-1.5",children:d2.code?`${d2.source}(${d2.code})`:d2.source})]}),onAddToChat&&jsxRuntimeExports.jsx(Tooltip,{label:labels.addToChat,portal:!0,children:jsxRuntimeExports.jsx(IconButton,{size:"xs",icon:"i-ph-chat-teardrop-text",label:labels.addDiagnosticToChat(d2.message),title:"",onClick:()=>onAddToChat(d2),className:"opacity-0 group-hover:opacity-100 focus-visible:opacity-100"})})]},i2)})})}function useDefinition(scope,enabled,resolve,navigate){const[modifier,setModifier]=reactExports.useState(!1),[linked,setLinked]=reactExports.useState(!1),shown=reactExports.useRef(!1),hovered=reactExports.useRef(null),lookup=reactExports.useRef(null);reactExports.useEffect(()=>{if(!enabled)return;const down=e2=>(e2.key==="Meta"||e2.key==="Control")&&setModifier(!0),up=e2=>(e2.key==="Meta"||e2.key==="Control")&&setModifier(!1),blur=()=>setModifier(!1);return window.addEventListener("keydown",down),window.addEventListener("keyup",up),window.addEventListener("blur",blur),()=>{window.removeEventListener("keydown",down),window.removeEventListener("keyup",up),window.removeEventListener("blur",blur)}},[enabled]);const show=reactExports.useCallback(on=>{shown.current!==on&&(shown.current=on,setLinked(on))},[]),unlink=reactExports.useCallback(()=>{hovered.current?.link(!1),lookup.current=null,show(!1)},[show]),ask=reactExports.useCallback(t2=>{const answer=resolve(t2.lineNumber,t2.column).catch(()=>[]),mine={line:t2.lineNumber,column:t2.column,span:null,answer};lookup.current=mine,answer.then(targets=>{if(lookup.current!==mine||hovered.current!==t2||targets.length===0)return;const span=originColumns(targets[0].origin,t2);mine.span=span??{column:t2.lineCharStart+t2.word.start+1,endColumn:t2.lineCharStart+t2.word.end+1},t2.link(!0,span??void 0),show(!0)})},[resolve,show]);reactExports.useEffect(()=>{!enabled||!modifier?unlink():hovered.current&&ask(hovered.current)},[enabled,modifier,ask,unlink]);const onEnter=reactExports.useCallback(t2=>{unlink(),hovered.current=t2,enabled&&modifier&&ask(t2)},[enabled,modifier,ask,unlink]),onLeave=reactExports.useCallback(()=>{unlink(),hovered.current=null},[unlink]),asked=reactExports.useRef(0);reactExports.useEffect(()=>()=>{asked.current++,lookup.current=null},[scope]);const goTo=reactExports.useCallback(async(line,column)=>{if(!enabled)return!1;const mine=++asked.current,held=lookup.current,targets=await(held!==null&&held.line===line&&(held.column===column||held.span!==null&&column>=held.span.column&&column<held.span.endColumn)?held.answer:resolve(line,column).catch(()=>[]));return mine!==asked.current||targets.length===0?!1:(navigate(targets[0]),!0)},[enabled,resolve,navigate]),onClick=reactExports.useCallback((t2,e2)=>{!enabled||!(e2.metaKey||e2.ctrlKey)||(e2.preventDefault(),goTo(t2.lineNumber,t2.column))},[enabled,goTo]);return{enabled,linking:enabled&&modifier&&linked,onEnter,onLeave,onClick,goTo}}function originColumns(origin,t2){return!origin||origin.line!==t2.lineNumber||origin.endLine!==origin.line||t2.column<origin.column||t2.column>=origin.endColumn?null:{column:origin.column,endColumn:origin.endColumn}}const REVEAL_MAX_FRAMES=90;function useRevealLine(editor,reveal,select,caret){reactExports.useEffect(()=>{if(!reveal)return;select(reveal.line);let tries=0,id=0,caretPlaced=!caret;const tick=()=>{const host=editor.current?.host(),scroller=host?.querySelector(".zg-code-scroller"),root=host?.querySelector("diffs-container")?.shadowRoot,lines=root?.querySelectorAll("[data-line]");if(!scroller||!root||!lines||lines.length===0){tries++<REVEAL_MAX_FRAMES&&(id=requestAnimationFrame(tick));return}const scrollerTop=scroller.getBoundingClientRect().top,centre=top=>{const want=Math.max(0,Math.min(top-scroller.clientHeight/2,scroller.scrollHeight-scroller.clientHeight)),settled=Math.abs(scroller.scrollTop-want)<1;return scroller.scrollTop=want,settled},exact=root.querySelector(`[data-line="${reveal.line}"]`);if(exact){const settled=centre(exact.getBoundingClientRect().top-scrollerTop+scroller.scrollTop);caretPlaced||(caretPlaced=!0,editor.current?.placeCaret({lineNumber:reveal.line,character:Math.max(0,reveal.column-1)})),!settled&&tries++<REVEAL_MAX_FRAMES&&(id=requestAnimationFrame(tick));return}const probe=lines[0],probeLine=Number.parseInt(probe.getAttribute("data-line")??"",10),lineHeight=probe.getBoundingClientRect().height;if(Number.isFinite(probeLine)&&lineHeight>0){const probeTop=probe.getBoundingClientRect().top-scrollerTop+scroller.scrollTop;centre(probeTop+(reveal.line-probeLine)*lineHeight)}tries++<REVEAL_MAX_FRAMES&&(id=requestAnimationFrame(tick))};return id=requestAnimationFrame(tick),()=>cancelAnimationFrame(id)},[reveal?.line,reveal?.column,reveal?.nonce])}const MAX_CHANGES=1e3,buffers=new Map,key=(cwd,path)=>`${cwd}\0${path}`;function recordEdits(cwd,path,changes){const k2=key(cwd,path),buf=buffers.get(k2)??{changes:[],complete:!0};buf.complete&&buf.changes.push(...changes),buf.changes.length>MAX_CHANGES&&(buf.changes=[],buf.complete=!1),buffers.set(k2,buf)}function resetEdits(cwd,path){buffers.set(key(cwd,path),{changes:[],complete:!1})}function takeEdits(cwd,path){const k2=key(cwd,path),buf=buffers.get(k2);if(buffers.set(k2,{changes:[],complete:!0}),!(!buf||!buf.complete))return buf.changes}function forgetEdits(cwd,path){buffers.delete(key(cwd,path))}const CHANGE_DEBOUNCE_MS=300,docs=new Map,docKey=(cwd,path)=>`${cwd}\0${path}`;function setItems(doc,items){doc.items=items;for(const l2 of doc.listeners)l2()}function attachLspDoc(lsp,cwd,path,text){const key2=docKey(cwd,path),existing=docs.get(key2);if(existing)return existing.views++,text!==existing.synced&&updateLspDoc(existing,text),existing;const doc={lsp,cwd,path,items:null,views:1,synced:text,timer:null,listeners:new Set,off:()=>{}};return docs.set(key2,doc),resetEdits(cwd,path),takeEdits(cwd,path),lsp.open(cwd,path,text).then(known=>docs.get(key2)===doc&&doc.items===null&&setItems(doc,known)).catch(()=>{}),doc.off=lsp.onDiagnostics((atCwd,atPath,diagnostics)=>{atCwd===cwd&&atPath===path&&setItems(doc,diagnostics)}),doc}function updateLspDoc(doc,text){text!==doc.synced&&(doc.synced=text,doc.timer&&clearTimeout(doc.timer),doc.timer=setTimeout(()=>{doc.timer=null,docs.get(docKey(doc.cwd,doc.path))===doc&&doc.lsp.open(doc.cwd,doc.path,doc.synced,takeEdits(doc.cwd,doc.path)).catch(()=>{})},CHANGE_DEBOUNCE_MS))}function syncLspDocNow(cwd,path,text){const doc=docs.get(docKey(cwd,path));return doc?(doc.timer&&clearTimeout(doc.timer),doc.timer=null,doc.synced=text,{changes:takeEdits(cwd,path)}):null}function detachLspDoc(doc){if(--doc.views>0)return;doc.timer&&clearTimeout(doc.timer),doc.timer=null,doc.off();const key2=docKey(doc.cwd,doc.path);docs.get(key2)===doc&&(docs.delete(key2),forgetEdits(doc.cwd,doc.path)),doc.lsp.close(doc.cwd,doc.path).catch(()=>{})}const noSubscribe=()=>()=>{};function useLsp(cwd,path,text){const ed=useEditorPrefs(),lsp=useFilesHost().lsp,enabled=ed.diagnostics==="lsp"&&lsp!==void 0&&cwd!==null&&path!==null&&!path.startsWith("/")&&text!==null,[doc,setDoc]=reactExports.useState(null),opening=reactExports.useRef(text);opening.current=text,reactExports.useEffect(()=>{if(!enabled||!lsp||!cwd||!path)return;const d2=attachLspDoc(lsp,cwd,path,opening.current??"");return setDoc(d2),()=>{setDoc(cur=>cur===d2?null:cur),detachLspDoc(d2)}},[enabled,lsp,cwd,path]),reactExports.useEffect(()=>{doc&&text!==null&&updateLspDoc(doc,text)},[doc,text]);const subscribe2=reactExports.useCallback(fn=>doc?(doc.listeners.add(fn),()=>doc.listeners.delete(fn)):noSubscribe(),[doc]),read=()=>doc?.items??null,items=reactExports.useSyncExternalStore(subscribe2,read,read),live=doc&&doc.cwd===cwd&&doc.path===path;return enabled&&live?items:null}function useLspConfigSync(){const ed=useEditorPrefs(),lsp=useFilesHost().lsp;reactExports.useEffect(()=>{lsp?.configure({idleMs:ed.lspIdleMin*6e4,overrides:{...ed.lspOverrides}}).catch(()=>{})},[lsp,ed.lspIdleMin,ed.lspOverrides])}const NO_DIAGNOSTICS=[],CodeViewer=reactExports.memo(({cwd,path,readOnly=!1,file,drafts,editKey,diagnostics=NO_DIAGNOSTICS,liveDiagnostics=NO_DIAGNOSTICS,onNavigate,reveal,visible=!0,findAsk=0,onDraft,onAdopt})=>{const ed=useEditorPrefs(),host=useFilesHost(),{write,read,lsp:server,system}=host,labels=useFilesLabels(),completionChange=reactExports.useRef(()=>{}),[initialDraft]=reactExports.useState(()=>drafts.get(path)??null),document2=useCodeDocument({doc:file,initialDraft,initialBase:drafts.baseOf(path),save:reactExports.useCallback(async(text,base2,force)=>{if(!write)throw new Error("write refused: read-only");const expected=force?(await read?.(cwd,path))?.mtimeMs:base2.mtimeMs,result=await write(cwd,path,text,expected??base2.mtimeMs);if(result.ok)return{ok:!0,doc:{...base2,contents:text,size:utf8Bytes(text),mtimeMs:result.mtimeMs}};if(result.reason==="changed")return{ok:!1,reason:"changed"};throw new Error(`write refused: ${result.reason}`)},[write,read,cwd,path]),reload:reactExports.useCallback(async()=>read?read(cwd,path):null,[read,cwd,path]),onChange:reactExports.useCallback((text,changes)=>{recordEdits(cwd,path,changes),completionChange.current(text,changes)},[cwd,path]),onDraft:reactExports.useCallback((text,base2)=>onDraft(path,text,base2),[onDraft,path]),onAdopt:reactExports.useCallback((next,reset)=>{reset&&resetEdits(cwd,path),onAdopt(path,next,reset)},[cwd,path,onAdopt])}),{contents,dirty,base}=document2,editorHandle=reactExports.useRef(null),lspOn=ed.diagnostics==="lsp"&&server!==void 0,resolveDefinition=reactExports.useCallback(async(line,column)=>server?server.definition(cwd,path,line,column):[],[server,cwd,path]),navigate=reactExports.useCallback(t2=>onNavigate?.(t2),[onNavigate]),definition=useDefinition(`${cwd}\0${path}`,lspOn&&onNavigate!==void 0,resolveDefinition,navigate),findings=reactExports.useMemo(()=>[...dirty?[]:diagnostics,...liveDiagnostics],[diagnostics,liveDiagnostics,dirty]),hover=useHoverCard(lspOn&&ed.lspHover&&server?(line,column)=>server.hover(cwd,path,line,column):null,reactExports.useMemo(()=>definition.enabled?[{label:labels.filesGoToDefinition,run:definition.goTo}]:[],[definition.enabled,definition.goTo,labels]),contents,(line,column)=>diagnosticsAt(findings,line,column)),completionSource=reactExports.useMemo(()=>lspOn&&ed.lspCompletion&&server?{complete:(text,line,character,trigger)=>{const sync=syncLspDocNow(cwd,path,text);return sync?server.completion(cwd,path,text,sync.changes,line+1,character+1,trigger):Promise.resolve({id:0,items:[],incomplete:!1})},resolve:(id,index)=>server.resolveCompletion(cwd,path,id,index)}:null,[lspOn,ed.lspCompletion,server,cwd,path]),completion=useCompletion(completionSource,editorHandle);completionChange.current=completion.onChange;const onTokenEnter=(t2,e2)=>{definition.onEnter(t2),!(completion.open||e2.metaKey||e2.ctrlKey)&&hover.onEnter(t2)},onTokenClick=(t2,e2)=>{hover.onLeave(),definition.onClick(t2,e2)};reactExports.useEffect(()=>{visible||hover.onLeave()},[visible]);const onTokenLeave=()=>{hover.onLeave(),definition.onLeave()};reactExports.useEffect(()=>{if(!lspOn)return;const onKey=e2=>{(e2.key==="Meta"||e2.key==="Control")&&hover.onLeave()};return window.addEventListener("keydown",onKey),()=>window.removeEventListener("keydown",onKey)},[lspOn]);const extraItems=reactExports.useMemo(()=>fileActionItems({cwd,path,kind:"file"},{labels,system,only:["copy-path","editor","reveal"],shortcuts:!1}),[cwd,path,labels,system]),chat=useFilesChat(),review=useCodeReview({filePath:path,kind:"file",excerptOf:range2=>excerptFromContents(contents,range2),extraItems,chat});useRevealLine(editorHandle,reveal,line=>review.onSelectionEnd({start:line,end:line}),ed.editing);const annotations=reactExports.useMemo(()=>{const out=[],byLine=diagnosticsByLine([...dirty?[]:diagnostics,...liveDiagnostics]);for(const[lineNumber,items]of byLine)out.push({lineNumber,metadata:{kind:"diagnostics",items}});return review.draft&&out.push({lineNumber:Math.max(review.draft.start,review.draft.end),metadata:{kind:"draft",range:review.draft}}),out},[diagnostics,liveDiagnostics,dirty,review.draft]),addDiagnosticToChat=d2=>{if(!chat)return;const range2={start:d2.line,end:d2.endLine??d2.line},body=serializeDiagnostic({filePath:path,rangeLabel:rangeLabel(range2),excerpt:excerptFromContents(base.contents,range2),language:languageFor(path),severity:d2.severity,source:d2.source,...d2.code?{code:d2.code}:{},diagnosticMessage:d2.message});chat.attach(attachmentName("diagnostic",path,rangeLabel(range2)),body)},renderAnnotation=a2=>a2.metadata?.kind==="diagnostics"?jsxRuntimeExports.jsx(DiagnosticAnnotation,{items:a2.metadata.items,onAddToChat:addDiagnosticToChat}):review.draftNode,markers=reactExports.useMemo(()=>diagnosticMarkers(findings),[findings]);return jsxRuntimeExports.jsxs(CodeEditor,{ref:editorHandle,path,doc:document2,sessionKey:editKey,readOnly:readOnly||!write,visible,findAsk,markers,selectedLines:review.selected,onSelectionEnd:review.onSelectionEnd,onGutterAction:review.canComment?review.openDraft:void 0,onContextMenu:review.onContextMenu,onTokenEnter,onTokenLeave,onTokenClick,annotations,renderAnnotation,hostAttributes:{"data-zg-linking":definition.linking?"true":void 0},children:[review.menuNode,hover.node,completion.node]})});CodeViewer.displayName="CodeViewer";function utf8Bytes(text){return new TextEncoder().encode(text).length}function useDiffPrimer(){const pool=useWorkerPool();return reactExports.useCallback(diff=>{const work=diff&&pool?.primeDiffHighlightCache(diff);return work?new Promise(resolve=>{const timer=setTimeout(resolve,REVEAL_FALLBACK_MS);work.catch(()=>{}).then(()=>{clearTimeout(timer),resolve()})}):Promise.resolve()},[pool])}const RELOAD_DEBOUNCE_MS=300;function DiffFileViewer({cwd,path,file,onUnavailable,findAsk=0,visible=!0,onReady}){const diffOf=useFilesHost().workingTreeDiff,labels=useFilesLabels(),prime=useDiffPrimer(),contents=file.contents,[fileDiff,setFileDiff]=reactExports.useState(null),loaded=reactExports.useRef(!1);reactExports.useEffect(()=>{let live=!0;const load=()=>(diffOf?diffOf(cwd,{path,context:1/0}):Promise.reject(new Error("no working-tree diff"))).then(patch=>{if(!live)return;const next=parseFilePatch(patch,`${cwd}:${path}:`);return prime(next).then(()=>{live&&(loaded.current=!0,setFileDiff(next))})}).catch(()=>live&&setFileDiff(void 0)),timer=loaded.current?window.setTimeout(()=>{load()},RELOAD_DEBOUNCE_MS):null;return timer===null&&load(),()=>{live=!1,timer!==null&&window.clearTimeout(timer)}},[diffOf,prime,cwd,path,contents]),reactExports.useEffect(()=>{fileDiff===void 0?onUnavailable():fileDiff&&onReady?.(path)},[fileDiff,onUnavailable,onReady,path]);const scroller=reactExports.useRef(null),reducedMotion=useAppearanceReducedMotion(),rows=reactExports.useMemo(()=>fileDiff?diffLines(fileDiff):[],[fileDiff]),find=useFind({parts:()=>[{part:"",lines:rows}],version:rows,surfaces:()=>{const root=scroller.current?.querySelector("diffs-container")?.shadowRoot;return root?[{part:"",root}]:[]},scroller:()=>scroller.current,fallback:(m2,root)=>estimateRowTop(root,rows.findIndex(r2=>r2.side===m2.side&&r2.line===m2.line)),smooth:!reducedMotion}),seenAsk=reactExports.useRef(findAsk),show=find.show;return reactExports.useEffect(()=>{findAsk!==seenAsk.current&&(seenAsk.current=findAsk,visible&&show())},[findAsk,show,visible]),fileDiff===null?jsxRuntimeExports.jsx(PanelLoading,{}):fileDiff===void 0?null:jsxRuntimeExports.jsxs("div",{className:"relative flex-1 min-h-0 flex flex-col",children:[jsxRuntimeExports.jsx("div",{ref:el=>{scroller.current=el?.firstElementChild??null},className:"contents",children:jsxRuntimeExports.jsx(DiffScroller,{className:"flex-1 min-h-0 overflow-auto",children:jsxRuntimeExports.jsx(ReviewableDiff,{fileDiff,diffStyle:"unified",wrap:!1,hideHeader:!0})})}),jsxRuntimeExports.jsx(FindBar,{find,label:labels.filesFindInDiff})]})}function estimateRowTop(scroller,row){const probe=scroller.querySelector("diffs-container")?.shadowRoot?.querySelector("[data-line-index]:not([data-column-number])"),probeRow=Number(probe?.getAttribute("data-line-index")?.split(",")[0]),rect=probe?.getBoundingClientRect();return row<0||!rect||!Number.isFinite(probeRow)||rect.height<=0?void 0:{top:rect.top-scroller.getBoundingClientRect().top+scroller.scrollTop+(row-probeRow)*rect.height}}EditStateManager.setCapacity(20);function editSessionKey(cwd,path,generation){return`${cwd}:${path}:${generation}`}function forgetEditSession(key2){setTimeout(()=>EditStateManager.clear("file",key2),0)}class DraftStore{drafts=new Map;listeners=new Map;get(path){return this.drafts.get(path)?.text}baseOf(path){return this.drafts.get(path)?.base}has(path){return this.drafts.has(path)}set(path,contents,base){const prev=this.drafts.get(path);if(contents===null){if(!prev)return;this.drafts.delete(path)}else{if(prev?.text===contents){base&&(prev.base=base);return}this.drafts.set(path,{text:contents,base:base??prev?.base})}for(const fn of this.listeners.get(path)??[])fn()}get idle(){return this.drafts.size===0&&this.listeners.size===0}subscribe(path,fn){let set=this.listeners.get(path);return set||this.listeners.set(path,set=new Set),set.add(fn),()=>{set.delete(fn),set.size===0&&this.listeners.get(path)===set&&this.listeners.delete(path)}}}function useDraft(store,path){const subscribe2=reactExports.useCallback(fn=>path?store.subscribe(path,fn):()=>{},[store,path]),read=()=>path?store.get(path)??null:null;return reactExports.useSyncExternalStore(subscribe2,read,read)}function useIsDirty(store,path){const subscribe2=reactExports.useCallback(fn=>path?store.subscribe(path,fn):()=>{},[store,path]),read=()=>path?store.has(path):!1;return reactExports.useSyncExternalStore(subscribe2,read,read)}class FolderBuffers{constructor(root){this.root=root}root;drafts=new DraftStore;generations=new Map;slots=new Map;claim(path){let taken=this.slots.get(path);taken||this.slots.set(path,taken=new Set);let slot=0;for(;taken.has(slot);)slot++;return taken.add(slot),{slot,generation:this.generations.get(path)??0}}release(path,held){const taken=this.slots.get(path);taken?.delete(held.slot),taken?.size===0&&this.slots.delete(path),held.slot!==0&&forgetEditSession(this.key(path,held))}get idle(){return this.drafts.idle&&this.slots.size===0}forgetSessions(){for(const[path,generation]of this.generations)for(let g2=0;g2<=generation;g2++)forgetEditSession(editSessionKey(this.root,path,g2))}holders(path){return this.slots.get(path)?.size??0}key(path,held){const base=editSessionKey(this.root,path,held.generation);return held.slot===0?base:`${base}#${held.slot}`}reset(path,held){forgetEditSession(this.key(path,held));const generation=(this.generations.get(path)??0)+1;return this.generations.set(path,generation),{slot:held.slot,generation}}}const folders=new Map,MAX_FOLDERS=32;function folderBuffers(root){let buffers2=folders.get(root);if(buffers2)return folders.delete(root),folders.set(root,buffers2),buffers2;folders.set(root,buffers2=new FolderBuffers(root));for(const[oldRoot,old]of folders){if(folders.size<=MAX_FOLDERS)break;old===buffers2||!old.idle||(folders.delete(oldRoot),old.forgetSessions())}return buffers2}const BY_EXTENSION={md:"markdown",markdown:"markdown",mdx:"markdown",html:"html",htm:"html"};function previewKindOfPath(path){const name=path.slice(path.lastIndexOf("/")+1).toLowerCase(),dot=name.lastIndexOf(".");return dot>0?BY_EXTENSION[name.slice(dot+1)]??null:null}function resolveWorkspaceLink(from,url){if(url===""||url.startsWith("#")||url.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(url))return null;const bare2=url.replace(/[?#].*$/,"");if(bare2==="")return null;let decoded;try{decoded=decodeURIComponent(bare2)}catch{decoded=bare2}const parts=[...decoded.startsWith("/")?[]:from.split("/").slice(0,-1)];for(const part of decoded.split("/"))if(!(part===""||part==="."))if(part===".."){if(parts.length===0)return null;parts.pop()}else parts.push(part);return parts.length>0?parts.join("/"):null}function githubRepoOfOrigin(origin){const match=/^(?:[a-z+]+:\/\/)?(?:[^@/]+@)?github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?\/?$/i.exec(origin.trim());return match?`${match[1]}/${match[2]}`.toLowerCase():null}function githubFileInRepo(url,repo){let parsed;try{parsed=new URL(url)}catch{return null}if(parsed.protocol!=="https:"&&parsed.protocol!=="http:")return null;const parts=parsed.pathname.split("/").filter(Boolean),host=parsed.hostname.toLowerCase();let rest;if(host==="github.com"||host==="www.github.com"){if(parts[2]!=="blob"&&parts[2]!=="raw")return null;rest=[parts[0]??"",parts[1]??"",...parts.slice(4)]}else if(host==="raw.githubusercontent.com")rest=[parts[0]??"",parts[1]??"",...parts.slice(3)];else return null;if(`${rest[0]}/${rest[1]}`.toLowerCase()!==repo)return null;const path=rest.slice(2);if(path.length===0)return null;try{return path.map(decodeURIComponent).join("/")}catch{return null}}const PREVIEW_FRAME_SANDBOX="allow-scripts",FilePreview=reactExports.memo(({kind,...props})=>kind==="markdown"?jsxRuntimeExports.jsx(MarkdownPreview,{...props}):jsxRuntimeExports.jsx(HtmlPreview,{path:props.path,text:props.text}));FilePreview.displayName="FilePreview";async function copyText(text){try{await navigator.clipboard.writeText(text)}catch(err){console.error("[zidane-ui] clipboard write failed",err)}}function selectionIn(root){const selection=root.ownerDocument.getSelection();if(!selection||selection.isCollapsed||!selection.anchorNode||!root.contains(selection.anchorNode))return null;const text=selection.toString();return text.trim()?text:null}function MarkdownPreview({cwd,path,text,version,onOpenFile,onRevealFolder}){const host=useFilesHost(),labels=useFilesLabels(),kitLabels=useLabels(),chat=useFilesChat(),links=useLinkRouter(),lightbox=useLightbox(),rootRef=reactExports.useRef(null),[menu,setMenu]=reactExports.useState(null),mediaUrl=host.mediaUrl,repo=useGithubRepo(cwd),inFolder2=reactExports.useCallback(url=>resolveWorkspaceLink(path,url)??(repo?githubFileInRepo(url,repo):null),[path,repo]),urlTransform=reactExports.useCallback((url,key2)=>{if(key2==="src"&&mediaUrl){const target=inFolder2(url);if(target&&mediaTypeOfPath(target)?.kind==="image")return mediaUrl({kind:"file",cwd,path:target,version})}return safeUrl(url)},[cwd,version,mediaUrl,inFolder2]),onClickCapture=e2=>{const anchor=e2.target.closest?.("a[href]"),href=anchor?.getAttribute("href");if(!anchor||href==null)return;const target=href.startsWith("#")?null:inFolder2(href);!href.startsWith("#")&&target===null||(e2.preventDefault(),e2.stopPropagation(),target!==null&&(href.replace(/[?#].*$/,"").endsWith("/")?onRevealFolder?.(target):onOpenFile?.(target)))},onClick=e2=>{const image=e2.target instanceof HTMLImageElement?e2.target:null;if(!image||image.closest("a")||!rootRef.current)return;const images=Array.from(rootRef.current.querySelectorAll("img")).filter(img=>!img.closest("a"));lightbox.open(images.map((img,i2)=>({key:`${i2}:${img.currentSrc||img.src}`,name:img.alt||path,src:img.currentSrc||img.src})),images.indexOf(image),image)},onContextMenu=e2=>{const root=rootRef.current;if(!root)return;const element=e2.target,image=element instanceof HTMLImageElement?element:null,link=element.closest?.("a[href]")?.getAttribute("href")??null,selection=selectionIn(root);!image&&!link&&!selection||(e2.preventDefault(),setMenu({target:{selection,image,link},at:{x:e2.clientX,y:e2.clientY}}))},items=[];if(menu){const{selection,image,link}=menu.target;if(selection){const what=labels.filesSelection,attach=()=>chat?.attach(attachmentName("snippet",path,null),serializeCodeSnippet({filePath:path,rangeLabel:null,excerpt:selection,language:"markdown"}));items.push(chat?{id:"chat",label:labels.filesAddWhatToChat(what),shortcut:"a",group:"text",onSelect:attach}:{...noChatItem("chat",labels.filesAddWhatToChat(what),labels),group:"text"},{id:"copy",label:labels.filesCopyWhat(what),shortcut:"c",group:"text",onSelect:()=>{copyText(selection)}})}if(image){const src=image.currentSrc||image.src,copy=run=>()=>{run(src).catch(()=>{})};items.push({id:"copy-image",label:kitLabels.copyImage,group:"image",onSelect:copy(copyImage)},{id:"copy-base64",label:kitLabels.copyImageBase64,group:"image",onSelect:copy(copyImageBase64)},{id:"copy-data-url",label:kitLabels.copyImageDataUrl,group:"image",onSelect:copy(copyImageDataUrl)})}if(link&&!link.startsWith("#")){const target=inFolder2(link);items.push({id:"open-link",label:labels.filesOpenLink,group:"link",onSelect:()=>{target===null?links.open(link,{source:"other"}):link.replace(/[?#].*$/,"").endsWith("/")?onRevealFolder?.(target):onOpenFile?.(target)}},{id:"copy-link",label:labels.filesCopyLink,group:"link",onSelect:()=>{copyText(link)}})}}return jsxRuntimeExports.jsxs("div",{ref:rootRef,className:"zg-file-preview flex-1 min-h-0 overflow-auto px-6 py-4 select-text","data-testid":"file-preview",role:"presentation",onClickCapture,onClick,onContextMenu,children:[jsxRuntimeExports.jsx(Markdown,{document:!0,urlTransform,children:text}),jsxRuntimeExports.jsx(RowActionsMenu,{open:menu!==null,position:menu?.at??null,onClose:()=>setMenu(null),items}),lightbox.element]})}function useGithubRepo(cwd){const originUrl=useGitHost()?.originUrl,[read,setRead]=reactExports.useState(null);return reactExports.useEffect(()=>{if(!originUrl)return;let cancelled=!1;return originUrl(cwd).then(origin=>{cancelled||setRead({cwd,repo:origin?githubRepoOfOrigin(origin):null})}).catch(()=>{cancelled||setRead({cwd,repo:null})}),()=>{cancelled=!0}},[cwd,originUrl]),read?.cwd===cwd?read.repo:null}function safeUrl(url){const colon=url.indexOf(":"),cut=Math.min(...["/","?","#"].map(c2=>url.includes(c2)?url.indexOf(c2):1/0));return colon===-1||colon>cut||/^(?:https?|mailto|tel)$/i.test(url.slice(0,colon))?url:""}function HtmlPreview({path,text}){const labels=useFilesLabels(),frameRef=reactExports.useRef(null);return reactExports.useEffect(()=>{const frame=frameRef.current;if(!frame)return;const url=URL.createObjectURL(new Blob([text],{type:"text/html"}));return frame.src=url,()=>URL.revokeObjectURL(url)},[text]),jsxRuntimeExports.jsx("div",{className:"flex-1 min-h-0 flex","data-testid":"file-preview",children:jsxRuntimeExports.jsx("iframe",{ref:frameRef,className:"zg-file-preview-frame flex-1 min-w-0 min-h-0",sandbox:PREVIEW_FRAME_SANDBOX,title:labels.filesRenderedTitle(path.slice(path.lastIndexOf("/")+1))})})}function DiagnosticsChip({state,items,label,onClick,className,style}){const counts=countBySeverity(items),clean=state==="checked"&&counts.errors+counts.warnings+counts.other===0;return jsxRuntimeExports.jsx(Tooltip,{label,portal:!0,className,style,children:jsxRuntimeExports.jsx("button",{type:"button",onClick,"aria-label":label,className:"zg-segment-item zg-press-soft zg-meta inline-flex items-center gap-1.5 h-5 px-1.5 rounded-full border-0 bg-transparent cursor-pointer shrink-0 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-[var(--zg-ring)]",children:state==="running"?jsxRuntimeExports.jsx("span",{className:"i-ph-circle-notch animate-spin text-zg-label","aria-hidden":!0}):clean?jsxRuntimeExports.jsx("span",{className:"i-ph-check-circle-fill text-zg-label text-zg-success","aria-hidden":!0}):state!=="checked"?jsxRuntimeExports.jsx("span",{className:`${state==="failed"?"i-ph-warning-circle text-zg-warn":"i-ph-circle-dashed"} text-zg-label`,"aria-hidden":!0}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[counts.errors>0&&jsxRuntimeExports.jsxs("span",{className:"inline-flex items-center gap-0.5 text-zg-danger",children:[jsxRuntimeExports.jsx("span",{className:"i-ph-x-circle-fill text-zg-label","aria-hidden":!0}),counts.errors]}),counts.warnings>0&&jsxRuntimeExports.jsxs("span",{className:"inline-flex items-center gap-0.5 text-zg-warn",children:[jsxRuntimeExports.jsx("span",{className:"i-ph-warning text-zg-label","aria-hidden":!0}),counts.warnings]}),counts.other>0&&jsxRuntimeExports.jsxs("span",{className:"inline-flex items-center gap-0.5 text-zg-info",children:[jsxRuntimeExports.jsx("span",{className:"i-ph-info text-zg-label","aria-hidden":!0}),counts.other]})]})})})}function FilesDiagnosticsChip({diagnostics,live}){const labels=useFilesLabels(),{items,failed,running:toolsRunning,rerun}=diagnostics,running=toolsRunning&&live===null,servers=live?[...new Set(live.map(d2=>d2.source))]:[],ran=[...diagnostics.ran,...live!==null&&servers.length===0?[labels.filesLanguageServer]:servers],failedIds=failed.map(f2=>f2.id),label=running?labels.filesChecking:failed.length>0&&ran.length===0?labels.filesCheckFailed(failedIds):ran.length===0?labels.filesNoTool:labels.filesCheckedBy(ran,failedIds),state=running?"running":ran.length>0?"checked":failed.length?"failed":"idle";return jsxRuntimeExports.jsx(DiagnosticsChip,{state,items:[...items??[],...live??[]],label,onClick:rerun})}function sameEntries(a2,b2){if(a2===b2)return!0;if(!a2||!b2||a2.length!==b2.length)return!1;for(let i2=0;i2<a2.length;i2++){const x2=a2[i2],y2=b2[i2];if(x2.path!==y2.path||x2.kind!==y2.kind||!!x2.ignored!=!!y2.ignored||!!x2.deferred!=!!y2.deferred)return!1}return!0}function sameStatus(a2,b2){if(a2===b2)return!0;if(a2.length!==b2.length)return!1;for(let i2=0;i2<a2.length;i2++)if(a2[i2].path!==b2[i2].path||a2[i2].status!==b2[i2].status)return!1;return!0}function statusDelta(prev,next){const before2=new Map(prev.map(e2=>[e2.path,e2.status])),out=new Set;for(const e2 of next)before2.get(e2.path)!==e2.status&&out.add(e2.path),before2.delete(e2.path);for(const p2 of before2.keys())out.add(p2);return out}function editedPath(ev){const edit=ev.kind==="tool"?ev.edit:void 0;return edit&&(edit.outcomes?edit.hunks.some((_2,i2)=>edit.outcomes?.[i2]?.kind!=="denied"&&edit.outcomes?.[i2]?.kind!=="failed"):edit.hunks.length>0)?edit.path:null}function editedPaths(events){const out=new Set;for(const ev of events){const p2=editedPath(ev);p2!==null&&out.add(p2)}return out}function sameFile(a2,b2){return a2===b2?!0:a2===null||a2==="missing"||b2==="missing"?!1:a2.mtimeMs===b2.mtimeMs&&a2.size===b2.size&&a2.contents===b2.contents&&a2.truncated===b2.truncated}function lineCount(text){let n2=1;for(let i2=text.indexOf(`
1106
1106
  `);i2!==-1;i2=text.indexOf(`
1107
- `,i2+1))n2++;return n2}function useDiagnostics(cwd,path,mtimeMs,savedAt){const ed=useEditorPrefs(),run=useFilesHost().diagnostics,[tick,setTick]=reactExports.useState(0),paths=reactExports.useMemo(()=>path===null?[]:[path],[path]),open=ed.diagnosticsRun==="open",{enabled,result,pending}=useDiagnosticsRun(cwd,paths,{version:String(open?mtimeMs:savedAt),settle:open,lsp:ed.diagnostics==="lsp",rerun:tick});return{items:result?.diagnostics??null,ran:result?.ran??[],failed:result?.failed??[],running:pending,enabled,rerun:()=>{cwd&&run?run.invalidate(cwd).catch(()=>{}).then(()=>setTick(t2=>t2+1)):setTick(t2=>t2+1)}}}const EMPTY_DIAGNOSTICS=[],DIFF_DEFAULT_MAX_LINES=1500,DIFF_DEFAULT_MAX_BYTES=200*1024;function diffFits(file){return file===null||file.size<=DIFF_DEFAULT_MAX_BYTES&&lineCount(file.contents)<=DIFF_DEFAULT_MAX_LINES}function opensAsDiff({changed,isNew,fits}){return changed&&!isNew&&fits}function newFilePaths(status){return new Set(status.filter(s2=>s2.status==="untracked"||s2.status==="added").map(s2=>s2.path))}const OpenFileTab=reactExports.memo(({path,active,drafts,glyph,tab,onPick,onClose,onContextMenu})=>{const dirty=useIsDirty(drafts,path);return jsxRuntimeExports.jsx(FileTabPill,{path,active,dirty,glyph:glyph(path),lifted:tab.lifted,onPick:tab.pick(()=>onPick(path)),onMove:tab.onMove,onClose:()=>onClose(path),onContextMenu:at=>onContextMenu({path,kind:"file"},at)})});OpenFileTab.displayName="OpenFileTab";const EditorColumn=reactExports.memo(({cwd,files,treeSide,treeOpen,hasChanges,isNewFile,onRevealInTree,onContextMenu,revealAt=null,findAsk=0,renderTabGlyph=renderFileIcon,readOnly=!1,onDropFiles,filePaths,onSelectInTree})=>{const host=useFilesHost(),labels=useFilesLabels(),system=host.system,onRight=treeSide==="right",active=files.active,{show,setActivePath,close,setDraft,adoptFile,replace,reorder}=files,[diffOverride,setDiffOverride]=reactExports.useState({}),[reveal,setReveal]=reactExports.useState(null),navigate=reactExports.useCallback(t2=>{show(t2.path),setDiffOverride(o2=>o2[t2.path]===!1?o2:{...o2,[t2.path]:!1}),setReveal(r2=>({path:t2.path,line:t2.line,column:t2.column,nonce:(r2?.nonce??0)+1}))},[show]),revealedNonceRef=reactExports.useRef(0);reactExports.useEffect(()=>{!revealAt||revealAt.nonce===revealedNonceRef.current||(revealedNonceRef.current=revealAt.nonce,navigate(revealAt))},[revealAt,navigate]);const changed=active&&host.workingTreeDiff&&!(active.file&&active.file!=="missing"&&active.file.media)?hasChanges(active.path):!1,dirty=useIsDirty(files.drafts,active?.path??null);active&&dirty&&diffOverride[active.path]!==!1&&setDiffOverride(o2=>({...o2,[active.path]:!1}));const adoptSaved=reactExports.useCallback((path,file,reset)=>{reset||setDiffOverride(o2=>o2[path]===!1?o2:{...o2,[path]:!1}),adoptFile(path,file,reset)},[adoptFile]),activeFile=active&&active.file!==null&&active.file!=="missing"?active.file:null,isNew=active!==null&&isNewFile(active.path),smallEnough=reactExports.useMemo(()=>diffFits(activeFile),[activeFile]),diffMode=active&&!dirty?diffOverride[active.path]??opensAsDiff({changed,isNew,fits:smallEnough}):!1,activeDraft=useDraft(files.drafts,active?.path??null),[rendered,setRendered]=reactExports.useState({}),[diffsShown,setDiffsShown]=reactExports.useState(()=>new Set),[diffsReady,setDiffsReady]=reactExports.useState(()=>new Set),activeText=activeFile!==null&&!activeFile.binary&&!activeFile.truncated,diffActive=diffMode&&activeText&&active!==null,previewKind=active&&activeText?previewKindOfPath(active.path):null,previewing=previewKind!==null&&!diffMode&&active!==null&&rendered[active.path]===!0;reactExports.useEffect(()=>{diffActive&&active&&setDiffsShown(s2=>s2.has(active.path)?s2:new Set(s2).add(active.path))},[diffActive,active]);const markDiffReady=reactExports.useCallback(path=>setDiffsReady(s2=>s2.has(path)?s2:new Set(s2).add(path)),[]),pending=active!==null&&(active.file===null||diffActive&&!diffsReady.has(active.path)),current=active&&activeText&&!pending?{path:active.path,diff:diffMode}:null,shownRef=reactExports.useRef(null);current&&(shownRef.current=current);const isText=f2=>f2.file!==null&&f2.file!=="missing"&&!f2.file.binary&&!f2.file.truncated,heldOpen=files.open.some(f2=>f2.path===shownRef.current?.path&&isText(f2)),shown=current??(pending&&heldOpen?shownRef.current:null),mediaNow=active&&activeFile?.media?{path:active.path,file:activeFile}:null,[heldMedia,setHeldMedia]=reactExports.useState(mediaNow);mediaNow&&(heldMedia?.path!==mediaNow.path||heldMedia.file!==mediaNow.file)&&setHeldMedia(mediaNow);const media=mediaNow??(pending&&active&&mediaTypeOfPath(active.path)?heldMedia:null),mediaViewerRef=reactExports.useRef(null),activePathNow=active?.path??null,siblings=reactExports.useMemo(()=>filePaths&&activePathNow?mediaSiblings(filePaths,activePathNow):null,[filePaths,activePathNow]),browse=reactExports.useMemo(()=>{if(!siblings||siblings.paths.length<2||!activePathNow)return;const{paths,index}=siblings;return{index,count:paths.length,onStep:delta=>{const next=paths[(index+delta+paths.length)%paths.length];replace(activePathNow,next),onSelectInTree?.(next)}}},[siblings,activePathNow,replace,onSelectInTree]),mountedDiffs=files.open.filter(isText).filter(f2=>diffsShown.has(f2.path)||diffActive&&f2.path===active?.path),diagnostics=useDiagnostics(cwd,activeFile&&active?active.path:null,activeFile?.mtimeMs??null,active?files.savedAt.get(active.path)??0:0),lspItems=useLsp(cwd,activeFile&&active&&!activeFile.binary&&!activeFile.truncated?active.path:null,activeFile&&active?activeDraft??activeFile.contents:null),openPaths=reactExports.useMemo(()=>files.open.map(f2=>f2.path),[files.open]),[dropping,setDropping]=reactExports.useState(!1),takes=e2=>{const types=Array.from(e2.dataTransfer?.types??[]);return types.includes(TREE_PATH_MIME)||onDropFiles!==void 0&&types.includes("Files")},onDragOver=e2=>{takes(e2)&&(e2.preventDefault(),e2.dataTransfer.dropEffect="copy",dropping||setDropping(!0))},onDragLeave=e2=>{dropping&&!(e2.relatedTarget instanceof Node&&e2.currentTarget.contains(e2.relatedTarget))&&setDropping(!1)},onDrop=e2=>{if(!takes(e2))return;e2.preventDefault(),e2.stopPropagation(),setDropping(!1);const path=e2.dataTransfer.getData(TREE_PATH_MIME);path?show(path):onDropFiles?.(e2.dataTransfer)};return jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0 min-h-0 flex flex-col","data-zg-file-drop":dropping?"true":void 0,onDragOverCapture:onDragOver,onDragLeave,onDropCapture:onDrop,children:[jsxRuntimeExports.jsx("div",{className:`shrink-0 flex items-center h-9 min-w-0 ${treeOpen?"px-2":onRight?"pl-2 pr-9":"pl-9 pr-2"}`,children:openPaths.length>0&&jsxRuntimeExports.jsx(ReorderTabs,{ids:openPaths,activeId:files.activePath,onReorder:reorder,label:labels.filesOpenFiles,renderTab:(path,tab)=>jsxRuntimeExports.jsx(OpenFileTab,{path,active:path===files.activePath,drafts:files.drafts,glyph:renderTabGlyph,tab,onPick:setActivePath,onClose:close,onContextMenu})})}),active?jsxRuntimeExports.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[jsxRuntimeExports.jsxs("div",{className:"shrink-0 flex items-center gap-2 h-8 pl-3 pr-2",children:[jsxRuntimeExports.jsx(Breadcrumb,{path:active.path,onFolder:onRevealInTree,onFile:()=>onRevealInTree(active.path)}),jsxRuntimeExports.jsxs("div",{className:"zg-segment shrink-0",children:[diagnostics.enabled&&jsxRuntimeExports.jsx(FilesDiagnosticsChip,{diagnostics,live:lspItems}),changed&&!dirty&&jsxRuntimeExports.jsx(IconToggle,{size:"xs",active:diffMode,onClick:()=>{setDiffOverride(o2=>({...o2,[active.path]:!diffMode})),diffMode||setRendered(r2=>({...r2,[active.path]:!1}))},icon:"i-ph-git-diff",label:diffMode?labels.filesPlainView:smallEnough?labels.filesShowChanges:labels.filesShowChangesLarge}),previewKind&&jsxRuntimeExports.jsx(IconToggle,{size:"xs",active:previewing,onClick:()=>{setRendered(r2=>({...r2,[active.path]:!previewing})),!previewing&&diffMode&&setDiffOverride(o2=>({...o2,[active.path]:!1}))},icon:"i-ph-eye",label:previewing?labels.filesShowCode:labels.filesShowRendered}),system?.isLocal(cwd)&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(IconToggle,{size:"xs",active:!1,onClick:()=>{system.openPath(absolutePath({cwd,path:active.path})).catch(()=>!1)},icon:"i-ph-arrow-square-out",label:labels.filesOpenEditor}),jsxRuntimeExports.jsx(IconToggle,{size:"xs",active:!1,onClick:()=>{system.revealPath(absolutePath({cwd,path:active.path})).catch(()=>!1)},icon:"i-ph-folder-open",label:labels.filesRevealFinder})]})]})]}),jsxRuntimeExports.jsxs("div",{className:"relative flex-1 min-h-0 flex flex-col overflow-auto",children:[media&&host.mediaUrl?jsxRuntimeExports.jsx("div",{className:`flex-1 min-h-0 flex ${media.file.media.kind==="pdf"?"":"items-center justify-center p-4"}`,"data-testid":"file-media",children:jsxRuntimeExports.jsx(MediaFrame,{name:media.path.slice(media.path.lastIndexOf("/")+1),viewerRef:mediaViewerRef,...browse?{browse}:{},children:jsxRuntimeExports.jsx(MediaView,{kind:media.file.media.kind,src:host.mediaUrl({kind:"file",cwd,path:media.path,version:media.file.mtimeMs}),name:media.path.slice(media.path.lastIndexOf("/")+1),viewerRef:mediaViewerRef},`${media.path}:${media.file.mtimeMs}`)})}):pending?shown===null&&jsxRuntimeExports.jsx(PanelLoading,{}):active.file==="missing"?jsxRuntimeExports.jsx(PanelEmpty,{icon:"i-ph-file-x",title:labels.filesNotFound}):active.file?.binary||active.file?.media?jsxRuntimeExports.jsx(PanelEmpty,{icon:"i-ph-file",title:labels.filesBinary}):active.file?.truncated?jsxRuntimeExports.jsx(PanelEmpty,{icon:"i-ph-file",title:labels.filesTooLarge(Math.round(active.file.size/1024))}):null,mountedDiffs.map(f2=>{const visible=shown?.path===f2.path&&shown.diff;return jsxRuntimeExports.jsx("div",{hidden:!visible&&!diffsReady.has(f2.path),inert:!visible,"aria-hidden":!visible||void 0,className:visible?"flex-1 min-h-0 flex flex-col":"absolute inset-0 invisible flex flex-col",children:jsxRuntimeExports.jsx(DiffFileViewer,{cwd,path:f2.path,file:f2.file,visible,onReady:markDiffReady,onUnavailable:()=>setDiffOverride(o2=>({...o2,[f2.path]:!1})),findAsk})},`diff:${f2.path}`)}),previewing&&activeFile&&jsxRuntimeExports.jsx(FilePreview,{cwd,path:active.path,kind:previewKind,text:activeDraft??activeFile.contents,version:activeFile.mtimeMs,onOpenFile:show,onRevealFolder:onRevealInTree}),files.open.map(f2=>{if(!isText(f2))return null;const isActive=shown?.path===f2.path&&!shown.diff&&!(previewing&&f2.path===active.path),isCurrent=isActive&&current!==null;return jsxRuntimeExports.jsx("div",{hidden:!isActive,className:"flex-1 min-h-0 flex flex-col",children:jsxRuntimeExports.jsx(CodeViewer,{cwd,path:f2.path,readOnly,file:f2.file,drafts:files.drafts,editKey:files.editKey(f2.path),diagnostics:isCurrent?diagnostics.items??EMPTY_DIAGNOSTICS:EMPTY_DIAGNOSTICS,liveDiagnostics:isCurrent?lspItems??EMPTY_DIAGNOSTICS:EMPTY_DIAGNOSTICS,onNavigate:navigate,reveal:isCurrent&&reveal&&reveal.path===f2.path?reveal:null,visible:isActive,findAsk,onDraft:setDraft,onAdopt:adoptSaved})},f2.path)})]})]}):jsxRuntimeExports.jsx(PanelEmpty,{icon:"i-ph-file-text",title:labels.filesPickFile,hint:labels.filesPickFileHint})]})});EditorColumn.displayName="EditorColumn";function renderFileIcon(path){return jsxRuntimeExports.jsx(FileIcon,{path})}const TREE_WIDTH={default:220,min:160,max:480},SEARCH_DEBOUNCE_MS=100,MemoFileTree=reactExports.memo(FileTree2),TreeColumn=reactExports.memo(p2=>{const onRight=p2.side==="right",presence=usePresence(p2.open,{enter:!0,exitMs:readPanelMs,key:p2.scopeKey}),settled=usePanelSettled(presence.state),labels=useFilesLabels(),colRef=reactExports.useRef(null),drag=useResizeDrag({value:p2.width,min:TREE_WIDTH.min,max:TREE_WIDTH.max,defaultValue:TREE_WIDTH.default,edge:onRight?"start":"end",target:{ref:colRef,cssVar:"--zg-files-tree-w"},onCommit:w2=>p2.layout.update({filesTreeWidth:w2})}),[query,setQuery]=reactExports.useState(""),{controlRef,entries}=p2;reactExports.useEffect(()=>{const t2=window.setTimeout(()=>controlRef.current?.setSearch(query),SEARCH_DEBOUNCE_MS);return()=>window.clearTimeout(t2)},[controlRef,query]);const queryRef=reactExports.useRef(query);return queryRef.current=query,reactExports.useEffect(()=>{controlRef.current?.setSearch(queryRef.current)},[controlRef,entries]),presence.mounted?jsxRuntimeExports.jsxs("div",{ref:colRef,className:"zg-files-tree relative shrink-0 min-h-0","data-collapsed":presence.state!=="open","data-settled":settled||void 0,"data-side":p2.side,style:{"--zg-files-tree-w":`${p2.width}px`},children:[jsxRuntimeExports.jsxs("div",{className:`zg-files-tree-sheet absolute inset-y-0 ${onRight?"left-0":"right-0"} flex flex-col min-h-0`,children:[p2.search&&jsxRuntimeExports.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:p2.search}),jsxRuntimeExports.jsx("div",{hidden:!!p2.search,className:`shrink-0 flex items-center h-9 ${onRight?"pl-2 pr-9":"pl-9 pr-2"}`,children:jsxRuntimeExports.jsxs("div",{className:"zg-well flex-1 min-w-0 flex items-center gap-1.5 h-7 px-2",children:[jsxRuntimeExports.jsx("span",{className:"i-ph-magnifying-glass text-zg-label text-[var(--zg-text-muted)] shrink-0","aria-hidden":!0}),jsxRuntimeExports.jsx("input",{type:"text",value:query,onChange:e2=>setQuery(e2.target.value),onKeyDown:e2=>{e2.key==="Escape"&&(e2.preventDefault(),setQuery(""),e2.currentTarget.blur())},placeholder:labels.filesSearchFiles,"aria-label":labels.filesSearchFiles,spellCheck:!1,className:"flex-1 min-w-0 bg-transparent border-0 outline-none p-0 text-xs text-[var(--zg-text)] placeholder:text-[var(--zg-text-muted)]"}),query.length>0&&jsxRuntimeExports.jsx(IconButton,{size:"xs",icon:"i-ph-x",label:labels.filesClearSearch,onClick:()=>setQuery(""),className:"!rounded-full -mr-1"})]})}),jsxRuntimeExports.jsxs("div",{hidden:!!p2.search,className:"shrink-0 flex items-center gap-1 h-8 pl-3 pr-2",children:[jsxRuntimeExports.jsx("span",{className:"zg-meta truncate flex-1",title:p2.cwd,children:p2.cwd.split("/").pop()}),p2.onNewEntry&&jsxRuntimeExports.jsxs("div",{className:"zg-segment shrink-0",children:[jsxRuntimeExports.jsx(IconToggle,{active:!1,onClick:()=>p2.onNewEntry?.("file"),icon:"i-ph-file-plus",label:labels.filesNewFile}),jsxRuntimeExports.jsx(IconToggle,{active:!1,onClick:()=>p2.onNewEntry?.("folder"),icon:"i-ph-folder-plus",label:labels.filesNewFolder})]}),jsxRuntimeExports.jsxs("div",{className:"zg-segment shrink-0",children:[jsxRuntimeExports.jsx(IconToggle,{active:p2.changedOnly,onClick:p2.onToggleChanged,icon:"i-ph-git-commit",label:p2.changedOnly?labels.filesAllFiles:labels.filesChangedOnly,badge:p2.changedCount>0?String(p2.changedCount):void 0}),jsxRuntimeExports.jsx(IconToggle,{active:p2.showIgnored,onClick:p2.onToggleIgnored,icon:p2.showIgnored?"i-ph-eye":"i-ph-eye-slash",label:p2.showIgnored?labels.filesHideIgnored:labels.filesShowIgnored}),jsxRuntimeExports.jsx(IconToggle,{active:!1,onClick:p2.onRefresh,icon:"i-ph-arrows-clockwise",label:labels.filesRefresh})]})]}),p2.truncated&&!p2.search&&jsxRuntimeExports.jsx("p",{className:"zg-meta shrink-0 mx-3 mb-1 truncate",title:labels.filesTruncated(p2.truncated.shown,p2.truncated.total,!!p2.truncated.atLeast),children:labels.filesTruncated(p2.truncated.shown,p2.truncated.total,!!p2.truncated.atLeast)}),p2.notice&&!p2.search&&jsxRuntimeExports.jsx(Notice,{tone:"error",compact:!0,className:"shrink-0 mx-2 mb-1",action:jsxRuntimeExports.jsx(IconButton,{size:"xs",icon:"i-ph-x",label:labels.filesDismiss,onClick:()=>p2.onDismissNotice?.(),className:"ml-auto"}),children:p2.notice}),p2.entries===null?!p2.search&&jsxRuntimeExports.jsx(PanelLoading,{}):p2.entries.length===0&&!(p2.editing&&!p2.changedOnly)?!p2.search&&jsxRuntimeExports.jsx(PanelEmpty,{icon:"i-ph-tree-structure",title:p2.changedOnly?labels.filesNoChanged:labels.filesEmptyFolder}):jsxRuntimeExports.jsx("div",{className:p2.search?"hidden":"contents",onKeyDown:p2.onTreeKeyDown,children:jsxRuntimeExports.jsx(MemoFileTree,{controlRef:p2.controlRef,entries:p2.entries,gitStatus:p2.gitStatus,selectedPath:p2.selectedPath,onSelect:p2.onSelect,onOpen:p2.onOpen,onContextMenu:p2.onContextMenu,openPaths:p2.openPaths,...p2.onExpandFolder?{onExpandFolder:p2.onExpandFolder}:{},...p2.editing?{editing:p2.editing}:{},className:"flex-1 min-h-0"})})]}),jsxRuntimeExports.jsx("div",{...drag.handleProps,"data-active":drag.active,className:`zg-resize-handle ${onRight?"-left-1":"-right-1"}`})]}):null});TreeColumn.displayName="TreeColumn";function typing(e2){const origin=e2.nativeEvent.composedPath()[0];return origin instanceof HTMLElement&&(origin.isContentEditable||/^(?:INPUT|TEXTAREA|SELECT)$/.test(origin.tagName))}function useEntryActions(input){const{cwd,entries,tree,files,refresh,selected,labels}=input,confirm=useOptionalConfirm(),[notice,setNotice]=reactExports.useState(null),[clipboard,setClipboard]=reactExports.useState(null),latest=reactExports.useRef({cwd,entries,files,refresh,selected,labels,confirm,clipboard});latest.current={cwd,entries,files,refresh,selected,labels,confirm,clipboard};const run=reactExports.useCallback(async actions=>{const{cwd:at,entries:host,refresh:reread,labels:words}=latest.current;if(!at||!host)return[];const done=[];for(const action of actions){let result;try{result=await action(at,host)}catch(error){result={ok:!1,reason:"denied",message:error instanceof Error?error.message:String(error)}}if(!result.ok){setNotice(entryRefusalText(result.reason,words)),tree.current?.resync();break}done.push(result)}return done.length===actions.length&&setNotice(null),await reread(),done},[tree]),enabled=!!entries&&!!cwd,create=reactExports.useCallback(async(path,kind)=>{const[made]=await run([(at,host)=>host.create(at,path,kind==="folder"?"dir":"file")]);made&&kind==="file"&&latest.current.files.show(made.path)},[run]),moveTo=reactExports.useCallback(async(paths,toDir,copy)=>{const picked=topLevelPaths(paths).filter(p2=>copy||parentOf(p2)!==toDir),done=await run(picked.map(from=>copy?(at,host)=>host.copy(at,from,toDir):(at,host)=>host.move(at,from,inFolder(toDir,nameOf(from)))));return copy||done.forEach((result,i2)=>latest.current.files.moved(picked[i2],result.path)),done},[run]),editing=reactExports.useMemo(()=>enabled?{onRename:(from,to)=>{run([(at,host)=>host.move(at,from,to)]).then(([moved])=>{moved&&latest.current.files.moved(from,moved.path)})},onCreate:(path,kind)=>{create(path,kind)},onMove:(paths,toDir,copy)=>{moveTo(paths,toDir,copy)},onDropFiles:(toDir,data)=>{const items=droppedItems(data),{cwd:at,entries:host}=latest.current;!at||!host||items.length===0||host.importFiles(at,toDir,items).then(async result=>{setNotice(result.ok?null:entryRefusalText(result.reason,latest.current.labels)),await latest.current.refresh(),result.paths[0]&&tree.current?.revealSoon(result.paths[0])})},onError:()=>setNotice(latest.current.labels.filesEntryExists)}:void 0,[enabled,run,create,moveTo,tree]),remove=reactExports.useCallback(async paths=>{const{cwd:at,entries:host,confirm:ask,labels:words}=latest.current;if(!at||!host||!ask||paths.length===0)return;const trash=host.removal(at)==="trash";if(!await ask({title:words.filesDeleteTitle(nameOf(paths[0]),paths.length),message:trash?words.filesDeleteToTrash:words.filesDeletePermanent,confirmLabel:trash?words.filesMoveToTrash:words.filesDeleteConfirm,destructive:!0}))return;const picked=topLevelPaths(paths),done=await run(picked.map(path=>(c2,h2)=>h2.remove(c2,path)));for(const result of done)latest.current.files.removed(result.path)},[run]),paste=reactExports.useCallback(async dir=>{const clip=latest.current.clipboard;if(!clip||clip.cwd!==latest.current.cwd)return;const done=await moveTo(clip.paths,dir,clip.mode==="copy");clip.mode==="cut"&&done.length>0&&setClipboard(null),done[0]&&tree.current?.revealSoon(done[0].path)},[moveTo,tree]),canPaste=clipboard!==null&&clipboard.cwd===cwd,menu=reactExports.useMemo(()=>enabled?{create:(dir,kind)=>{tree.current?.startCreate(dir,kind,kind==="folder"?labels.filesNewFolder:labels.filesNewFile)},rename:path=>{tree.current?.startRename(path)},duplicate:path=>{run([(at,host)=>host.copy(at,path,parentOf(path))]).then(([copy])=>{copy&&tree.current?.revealSoon(copy.path)})},clip:(path,mode)=>setClipboard({mode,cwd:latest.current.cwd??"",paths:[path]}),...canPaste?{paste:dir=>{paste(dir)}}:{},...confirm?{remove:path=>{remove([path])}}:{}}:void 0,[enabled,canPaste,confirm,labels,run,paste,remove,tree]),selectedDir=()=>{const at=latest.current.selected;return at?at.endsWith("/")?at.slice(0,-1):parentOf(at):""},newEntry=reactExports.useMemo(()=>enabled?kind=>{tree.current?.startCreate(selectedDir(),kind,kind==="folder"?labels.filesNewFolder:labels.filesNewFile)}:void 0,[enabled,labels,tree]),dropOnEditor=reactExports.useMemo(()=>enabled?data=>{const items=droppedItems(data),{cwd:at,entries:host}=latest.current;!at||!host||items.length===0||host.importFiles(at,"",items).then(async result=>{setNotice(result.ok?null:entryRefusalText(result.reason,latest.current.labels)),await latest.current.refresh();const first=result.paths[0];first&&(items.length===1&&!items[0].entry?.isDirectory?latest.current.files.show(first):tree.current?.revealSoon(first))})}:void 0,[enabled,tree]),onTreeKeyDown=reactExports.useCallback(e2=>{const at=latest.current.selected;if(!enabled||typing(e2)||e2.altKey)return;const mod=e2.metaKey||e2.ctrlKey,path=at?at.replace(/\/$/,""):null,key2=e2.key.toLowerCase();if(mod&&(key2==="c"||key2==="x")&&path)setClipboard({mode:key2==="x"?"cut":"copy",cwd:latest.current.cwd??"",paths:[path]});else if(mod&&key2==="v"&&latest.current.clipboard)paste(selectedDir());else if((mod&&e2.key==="Backspace"||e2.key==="Delete")&&path&&latest.current.confirm)remove([path]);else return;e2.preventDefault(),e2.stopPropagation()},[enabled,paste,remove]),dismissNotice=reactExports.useCallback(()=>setNotice(null),[]);return{editing,menu,newEntry,dropOnEditor,onTreeKeyDown,notice,dismissNotice}}const NO_FOLDER=folderBuffers("");function useOpenFiles(scope,layout,layoutStore,prefs,source){const read=useFilesHost().read,cwd=filesRootOf(scope)||null,[open,setOpen]=reactExports.useState(()=>layout.filesOpen.map(path=>({path,file:null}))),[activePath,setActivePath]=reactExports.useState(layout.filesActive),buffers2=cwd?folderBuffers(cwd):NO_FOLDER,drafts=buffers2.drafts,retired=reactExports.useRef(new Set),setDraft=reactExports.useCallback((path,contents,base)=>{contents!==null&&retired.current.has(path)||drafts.set(path,contents,base)},[drafts]);reactExports.useEffect(()=>{for(const f2 of open)retired.current.delete(f2.path)},[open]);const holding=reactExports.useRef({buffers:buffers2,slots:new Map});holding.current.buffers!==buffers2&&(holding.current={buffers:buffers2,slots:new Map});const slots=holding.current.slots,editKey=reactExports.useCallback(path=>{let held=slots.get(path);return held||slots.set(path,held=buffers2.claim(path)),buffers2.key(path,held)},[buffers2,slots]);reactExports.useEffect(()=>{const h2=holding.current;return()=>{for(const[p2,s2]of h2.slots)h2.buffers.release(p2,s2);h2.slots.clear()}},[buffers2]);const resetEditSession=reactExports.useCallback(path=>{const held=slots.get(path);held&&slots.set(path,buffers2.reset(path,held))},[buffers2,slots]),[savedAt,setSavedAt]=reactExports.useState(new Map),reads=reactExports.useRef(new Map),adoptFile=reactExports.useCallback((path,file,resetEditor=!1)=>{const inFlight=reads.current.get(path);inFlight!==void 0&&reads.current.set(path,inFlight+1),resetEditor?resetEditSession(path):setSavedAt(m2=>new Map(m2).set(path,Date.now())),setOpen(current=>current.map(f2=>f2.path===path&&f2.file!==file?{path,file}:f2)),setDraft(path,null)},[setDraft,resetEditSession]),layoutRef=reactExports.useRef(layoutStore);layoutRef.current=layoutStore,reactExports.useEffect(()=>{layoutRef.current.update({filesOpen:open.map(f2=>f2.path),filesActive:activePath,...prefs})},[open,activePath,prefs]);const stale=reactExports.useRef(new Set),openRef=reactExports.useRef(open);openRef.current=open;const activeRef=reactExports.useRef(activePath);activeRef.current=activePath;const reload=reactExports.useCallback(async path=>{if(!cwd)return;stale.current.delete(path);const mine=(reads.current.get(path)??0)+1;reads.current.set(path,mine);const file=(read?await read(cwd,path).catch(()=>null):null)??"missing";reads.current.get(path)===mine&&(reads.current.delete(path),setOpen(current=>{const idx=current.findIndex(f2=>f2.path===path);if(idx===-1||sameFile(current[idx].file,file))return current;const next=current.slice();return next[idx]={path,file},next}))},[read,cwd]),reloadAll=reactExports.useCallback(()=>{for(const f2 of openRef.current)reload(f2.path)},[reload]),{visible}=source,visibleRef=reactExports.useRef(visible);visibleRef.current=visible,reactExports.useEffect(()=>{visible&&activePath&&stale.current.has(activePath)&&reload(activePath)},[visible,activePath,reload]),reactExports.useEffect(()=>{for(const f2 of openRef.current)f2.file===null&&reload(f2.path)},[cwd,reload]);const seenEdits=reactExports.useRef(new WeakSet),editsRef=reactExports.useRef(source.edits);editsRef.current=source.edits;const{onToolResult}=source;reactExports.useEffect(()=>onToolResult(()=>{const touched=new Set;for(const ev of editsRef.current){if(seenEdits.current.has(ev))continue;seenEdits.current.add(ev);const p2=editedPath(ev);p2!==null&&touched.add(p2)}for(const f2 of openRef.current)visibleRef.current&&(f2.path===activeRef.current||touched.has(f2.path))?reload(f2.path):stale.current.add(f2.path)}),[onToolResult,reload]),reactExports.useEffect(()=>{for(const ev of editsRef.current)seenEdits.current.add(ev)},[]);const lastStatus=reactExports.useRef(source.status);reactExports.useEffect(()=>{const prev=lastStatus.current;if(lastStatus.current=source.status,prev===source.status)return;const moved2=statusDelta(prev,source.status);if(moved2.size!==0)for(const f2 of openRef.current)moved2.has(f2.path)&&f2.path!==activeRef.current&&reload(f2.path)},[source.status,reload]);const show=reactExports.useCallback(path=>{setOpen(current=>current.some(f2=>f2.path===path)?current:[...current,{path,file:null}]),setActivePath(path),reload(path)},[reload]),close=reactExports.useCallback(path=>{const held=slots.get(path);slots.delete(path);const shared=buffers2.holders(path)>(held?1:0);held&&buffers2.release(path,held),shared||(held&&buffers2.reset(path,held),setDraft(path,null),setTimeout(()=>{buffers2.holders(path)===0&&setDraft(path,null)},0)),stale.current.delete(path),setOpen(current=>{const idx=current.findIndex(f2=>f2.path===path),next=current.filter(f2=>f2.path!==path);return setActivePath(active2=>active2===path?next[Math.max(0,Math.min(idx,next.length-1))]?.path??null:active2),next})},[setDraft,buffers2,slots]),reorder=reactExports.useCallback(paths=>{setOpen(current=>{const byPath=new Map(current.map(f2=>[f2.path,f2])),next=[...paths.flatMap(p2=>{const f2=byPath.get(p2);return f2?(byPath.delete(p2),[f2]):[]}),...byPath.values()];return next.every((f2,i2)=>f2===current[i2])?current:next})},[]),moved=reactExports.useCallback((from,to)=>{if(from===to)return;const renames=openRef.current.flatMap(f2=>{const next=movedPath(f2.path,from,to);return next===null||next===f2.path?[]:[{old:f2.path,next}]});if(renames.length===0)return;for(const{old,next}of renames){const text=drafts.get(old),base=drafts.baseOf(old);text!==void 0&&drafts.set(next,text,base?{...base,path:next}:void 0);const held=slots.get(old);slots.delete(old),held&&buffers2.release(old,held),drafts.set(old,null),retired.current.add(old),stale.current.delete(old)}const map=new Map(renames.map(r2=>[r2.old,r2.next]));setOpen(current=>current.map(f2=>map.has(f2.path)?{path:map.get(f2.path),file:null}:f2)),setActivePath(current=>current&&map.has(current)?map.get(current):current);for(const{next}of renames)reload(next)},[drafts,buffers2,slots,reload]),replace=reactExports.useCallback((from,to)=>{if(from===to)return;if(drafts.has(from)){show(to);return}const held=slots.get(from);slots.delete(from),held&&buffers2.release(from,held),stale.current.delete(from),setOpen(current=>{if(current.some(f2=>f2.path===to))return current.filter(f2=>f2.path!==from);const at=current.findIndex(f2=>f2.path===from);return at===-1?[...current,{path:to,file:null}]:current.map((f2,i2)=>i2===at?{path:to,file:null}:f2)}),setActivePath(to),reload(to)},[drafts,show,slots,buffers2,reload]),removed=reactExports.useCallback(path=>{for(const f2 of openRef.current)isUnder(f2.path,path)&&(drafts.has(f2.path)?setOpen(current=>current.map(o2=>o2.path===f2.path?{path:o2.path,file:"missing"}:o2)):close(f2.path))},[drafts,close]),active=reactExports.useMemo(()=>open.find(f2=>f2.path===activePath)??null,[open,activePath]);return reactExports.useMemo(()=>({open,drafts,setDraft,editKey,adoptFile,savedAt,activePath,active,setActivePath,show,replace,close,reorder,reloadAll,moved,removed}),[open,drafts,setDraft,editKey,adoptFile,savedAt,activePath,active,setActivePath,show,replace,close,reorder,reloadAll,moved,removed])}const TOOL_RESULT_DEBOUNCE_MS=400,NO_FOLDERS=new Map;function useWorkspace(scope,showIgnored,visible,useEdits){const host=useFilesHost(),[listed,setListed]=reactExports.useState(null),[truncated,setTruncated]=reactExports.useState(null),[opened,setOpened]=reactExports.useState(NO_FOLDERS),openedRef=reactExports.useRef(opened);openedRef.current=opened;const[status,setStatus]=reactExports.useState([]),cwd=filesRootOf(scope)||null,edits=useEdits(scope.session??null),onFolderChange=useFolderChanges(scope),reads=reactExports.useRef(0),refresh=reactExports.useCallback(async()=>{if(!cwd)return;const mine=++reads.current,folders2=[...openedRef.current.keys()];let listing,git,inFolders;try{[listing,git,inFolders]=await Promise.all([host.list?host.list(cwd,{showIgnored}):{entries:[]},host.gitStatus?host.gitStatus(cwd):[],Promise.all(folders2.map(async dir=>host.list?(await host.list(cwd,{showIgnored,dir})).entries:[]))])}catch{mine===reads.current&&setListed(prev=>prev??[]);return}if(mine!==reads.current)return;const list=listing.entries;setListed(prev=>sameEntries(prev,list)?prev:list),setTruncated(prev=>sameTruncation(prev,listing.truncated)?prev:listing.truncated??null),setStatus(prev=>sameStatus(prev,git)?prev:git),folders2.length>0&&setOpened(prev=>{let changed=!1;const next=new Map(prev);return folders2.forEach((dir,i2)=>{const fresh=inFolders[i2];sameEntries(prev.get(dir)??null,fresh)||(changed=!0,next.set(dir,fresh))}),changed?next:prev})},[host,cwd,showIgnored]),generation=reactExports.useRef(0);reactExports.useEffect(()=>{generation.current++,setListed(null),setTruncated(null),setOpened(NO_FOLDERS),openedRef.current=NO_FOLDERS,refresh()},[refresh]);const openFolder=reactExports.useCallback(dir=>{const list=host.list;if(!cwd||!list||openedRef.current.has(dir))return;const mine=generation.current;list(cwd,{showIgnored,dir}).then(({entries:inside})=>{mine===generation.current&&setOpened(prev=>prev.has(dir)?prev:new Map(prev).set(dir,inside))},()=>{})},[host,cwd,showIgnored]),entries=reactExports.useMemo(()=>withOpenedFolders(listed,opened),[listed,opened]),onToolResult=reactExports.useCallback(handler=>{let timer=null;const off=onFolderChange(()=>{timer&&clearTimeout(timer),timer=setTimeout(()=>{timer=null,handler()},TOOL_RESULT_DEBOUNCE_MS)});return()=>{timer&&clearTimeout(timer),off()}},[onFolderChange]),cwdRef=reactExports.useRef(cwd);cwdRef.current=cwd;const visibleRef=reactExports.useRef(visible);visibleRef.current=visible;const staleListing=reactExports.useRef(!1);reactExports.useEffect(()=>onToolResult(()=>{visibleRef.current?refresh():staleListing.current=!0,cwdRef.current&&host.diagnostics?.invalidate(cwdRef.current).catch(()=>{})}),[host,onToolResult,refresh]),reactExports.useEffect(()=>{!visible||!staleListing.current||(staleListing.current=!1,refresh())},[visible,refresh]);const lastChanged=reactExports.useRef(new Set),changedPaths=reactExports.useMemo(()=>{const set=editedPaths(edits);for(const g2 of status)set.add(g2.path);return sameSet(set,lastChanged.current)?lastChanged.current:(lastChanged.current=set,set)},[edits,status]);return reactExports.useMemo(()=>({entries,status,changedPaths,edits,refresh,onToolResult,truncated,openFolder}),[entries,status,changedPaths,edits,refresh,onToolResult,truncated,openFolder])}function sameTruncation(a2,b2){return!a2||!b2?!a2&&!b2:a2.shown===b2.shown&&a2.total===b2.total&&a2.atLeast===b2.atLeast}function withOpenedFolders(listed,opened){if(!listed||opened.size===0)return listed;const all=[...listed,...[...opened.values()].flat()],seen=new Set;return all.filter(e2=>seen.has(e2.path)?!1:(seen.add(e2.path),!(e2.kind==="dir"&&(opened.get(e2.path.replace(/\/$/,""))?.length??0)>0)))}function filterChanged(entries,changed){return entries.filter(e2=>{const p2=e2.path.replace(/\/$/,"");if(e2.kind==="file")return changed.has(p2);for(const c2 of changed)if(c2.startsWith(`${p2}/`))return!0;return!1})}function FilesTab({scope,layout:layoutStore,chat=null,useEdits=useNoEdits,useKeyScope=useNoKeyScope,revealRequest=null,onRevealTaken,takeRevealPosition,onOpenExternal,renderTabGlyph,readOnly=!1,fileActions=!0,className,style}){const host=useFilesHost(),labels=useFilesLabels(),cwd=filesRootOf(scope)||null,key2=filesScopeKey(scope),[ownLayout]=reactExports.useState(createMemoryFilesLayout),layoutOf=layoutStore??ownLayout,visible=usePanelVisible(),{filesTreeSide}=useAppearanceState(),layout=useReadable(layoutOf),[showIgnored,setShowIgnored]=reactExports.useState(layout.filesShowIgnored),[treeOpen,setTreeOpen]=reactExports.useState(layout.filesTreeOpen),[changedOnly,setChangedOnly]=reactExports.useState(layout.filesChangedOnly),prefs=reactExports.useMemo(()=>({filesShowIgnored:showIgnored,filesTreeOpen:treeOpen,filesChangedOnly:changedOnly}),[showIgnored,treeOpen,changedOnly]),[selected,setSelected]=reactExports.useState(layout.filesActive),treeControl=reactExports.useRef(null);useLspConfigSync();const workspace=useWorkspace(scope,showIgnored,visible,useEdits),files=useOpenFiles(scope,layout,layoutOf,prefs,{onToolResult:workspace.onToolResult,edits:workspace.edits,status:workspace.status,visible}),openPaths=reactExports.useMemo(()=>files.open.map(f2=>f2.path),[files.open]),rootRef=reactExports.useRef(null),[findAsk,setFindAsk]=reactExports.useState(0),[searchOpen,setSearchOpen]=reactExports.useState(!1),[searchAsk,setSearchAsk]=reactExports.useState(0);useKeyScope(rootRef,{step:direction=>{const paths=files.open.map(f2=>f2.path),next=steppedIndex(files.activePath?paths.indexOf(files.activePath):-1,paths.length,direction);return next<0?!1:(files.setActivePath(paths[next]),!0)},close:()=>files.activePath?(files.close(files.activePath),!0):!1,find:mode=>mode==="files"?(setSearchOpen(!0),setSearchAsk(n2=>n2+1),setTreeOpen(!0),!0):files.activePath?(setFindAsk(n2=>n2+1),!0):!1});const actions=useEntryActions({cwd,entries:readOnly||!fileActions?void 0:host.entries,tree:treeControl,files,refresh:workspace.refresh,selected,labels}),[menu,setMenu]=reactExports.useState(null),openTreeMenu=reactExports.useCallback((target,at)=>{cwd&&setMenu({target:{cwd,...target},at,tree:!0})},[cwd]),openMenu=reactExports.useCallback((target,at)=>{cwd&&setMenu({target:{cwd,...target},at,tree:!1})},[cwd]),showFile=files.show,show=reactExports.useCallback(path=>{showFile(path),setSelected(path)},[showFile]),activate=reactExports.useCallback(async(path,event)=>{cwd&&((event.metaKey||event.ctrlKey)&&onOpenExternal&&await onOpenExternal(`${cwd}/${path}`)||show(path))},[cwd,show,onOpenExternal]),toggleTree=reactExports.useCallback(()=>setTreeOpen(v2=>!v2),[]),toggleChanged=reactExports.useCallback(()=>setChangedOnly(v2=>!v2),[]),toggleIgnored=reactExports.useCallback(()=>setShowIgnored(v2=>!v2),[]),{refresh:refreshWorkspace}=workspace,{reloadAll}=files,onRefresh=reactExports.useCallback(()=>{cwd&&(host.diagnostics?.invalidate(cwd).catch(()=>{}),refreshWorkspace(),reloadAll())},[host,cwd,refreshWorkspace,reloadAll]),revealInTree=reactExports.useCallback(path=>{setTreeOpen(!0),treeControl.current?.reveal(path)},[]),selectInTree=reactExports.useCallback(path=>{setSelected(path),treeControl.current?.reveal(path)},[]),[revealAt,setRevealAt]=reactExports.useState(null),[folderAsk,setFolderAsk]=reactExports.useState(null);reactExports.useEffect(()=>{const req=revealRequest;if(!req||!cwd)return;onRevealTaken?.();const at=takeRevealPosition?.(req)??null,rel=relativeTo(req,cwd)??(req.startsWith("/")&&!req.endsWith("/")?req:null);if(rel!==null){if(req.endsWith("/")){setTreeOpen(!0),setSearchOpen(!1),setFolderAsk({abs:req,rel:rel.replace(/\/$/,"")});return}rel&&(show(rel),at&&setRevealAt(r2=>({path:rel,...at,nonce:(r2?.nonce??0)+1})))}},[revealRequest,cwd,show]),reactExports.useEffect(()=>{!folderAsk||!workspace.entries||!treeControl.current||(setFolderAsk(null),folderAsk.rel&&!treeControl.current.reveal(folderAsk.rel)&&host.system&&host.system.revealPath(folderAsk.abs).catch(()=>!1))},[host,folderAsk,workspace.entries,treeOpen]);const statusPaths=reactExports.useMemo(()=>new Set(workspace.status.map(s2=>s2.path)),[workspace.status]),hasChanges=reactExports.useCallback(path=>statusPaths.has(path),[statusPaths]),newPaths=reactExports.useMemo(()=>newFilePaths(workspace.status),[workspace.status]),isNewFile=reactExports.useCallback(path=>newPaths.has(path),[newPaths]),entries=reactExports.useMemo(()=>workspace.entries&&changedOnly?filterChanged(workspace.entries,workspace.changedPaths):workspace.entries,[workspace.entries,workspace.changedPaths,changedOnly]),filePaths=reactExports.useMemo(()=>(workspace.entries??[]).filter(e2=>e2.kind==="file"&&!e2.ignored).map(e2=>e2.path),[workspace.entries]),searchNames=reactExports.useCallback((query,opts)=>nameMatches(filePaths,query,opts),[filePaths]),searchContents=reactExports.useCallback((query,opts)=>cwd&&host.search?host.search(cwd,query,{...opts,searchId:`files:${key2}`}):Promise.resolve({matches:[],capped:!1,engine:"none"}),[host,cwd,key2]),openSearchLine=reactExports.useCallback(m2=>{show(m2.path),setRevealAt(r2=>({path:m2.path,line:m2.line,column:(m2.ranges[0]?.start??0)+1,nonce:(r2?.nonce??0)+1}))},[show]),closeSearch=reactExports.useCallback(()=>setSearchOpen(!1),[]);return cwd?jsxRuntimeExports.jsx(FilesChatContext.Provider,{value:chat,children:jsxRuntimeExports.jsxs("div",{ref:rootRef,className:`relative flex-1 min-h-0 flex ${filesTreeSide==="right"?"flex-row-reverse":"flex-row"}${className?` ${className}`:""}`,style,children:[jsxRuntimeExports.jsx("div",{className:`absolute top-0 h-9 flex items-center z-10 ${filesTreeSide==="right"?"right-1.5":"left-1.5"}`,children:jsxRuntimeExports.jsx(IconToggle,{active:!1,onClick:toggleTree,icon:`${treeOpen?"i-ph-sidebar-simple-fill":"i-ph-sidebar-simple"}${filesTreeSide==="right"?" -scale-x-100":""}`,label:treeOpen?labels.filesHideTree:labels.filesShowTree})}),jsxRuntimeExports.jsx(TreeColumn,{layout:layoutOf,cwd,scopeKey:key2,side:filesTreeSide,open:treeOpen,width:layout.filesTreeWidth??TREE_WIDTH.default,controlRef:treeControl,entries,truncated:workspace.truncated,onExpandFolder:workspace.openFolder,gitStatus:workspace.status,selectedPath:selected,onSelect:setSelected,onOpen:activate,onContextMenu:openTreeMenu,...actions.editing?{editing:actions.editing}:{},...actions.newEntry?{onNewEntry:actions.newEntry}:{},onTreeKeyDown:actions.onTreeKeyDown,notice:actions.notice,onDismissNotice:actions.dismissNotice,changedOnly,changedCount:workspace.changedPaths.size,onToggleChanged:toggleChanged,showIgnored,onToggleIgnored:toggleIgnored,onRefresh,openPaths,search:searchOpen?jsxRuntimeExports.jsx(SearchPanel,{label:labels.filesSearchInFiles,asked:searchAsk,names:searchNames,search:searchContents,onOpenFile:show,onOpenLine:openSearchLine,onClose:closeSearch,inset:filesTreeSide==="right"?"right":"left"}):void 0}),jsxRuntimeExports.jsx(EditorColumn,{cwd,files,treeSide:filesTreeSide,treeOpen,hasChanges,isNewFile,onRevealInTree:revealInTree,onContextMenu:openMenu,revealAt,findAsk,readOnly,filePaths,onSelectInTree:selectInTree,...actions.dropOnEditor?{onDropFiles:actions.dropOnEditor}:{},...renderTabGlyph?{renderTabGlyph}:{}}),jsxRuntimeExports.jsx(RowActionsMenu,{open:menu!==null,position:menu?.at??null,onClose:()=>setMenu(null),items:menu?fileActionItems(menu.target,{chat,labels,system:host.system,...menu.tree&&actions.menu?{entries:actions.menu}:{}}):[]})]})}):jsxRuntimeExports.jsx(PanelEmpty,{icon:"i-ph-folder-dashed",title:scope.session?labels.filesSessionNoFolder:labels.filesNoFolder,className})}function relativeTo(abs,root){const base=root.replace(/\/+$/,"");return abs===base||abs===`${base}/`?"":abs.startsWith(`${base}/`)?abs.slice(base.length+1):null}export{FilesTab};
1107
+ `,i2+1))n2++;return n2}function useDiagnostics(cwd,path,mtimeMs,savedAt){const ed=useEditorPrefs(),run=useFilesHost().diagnostics,[tick,setTick]=reactExports.useState(0),paths=reactExports.useMemo(()=>path===null?[]:[path],[path]),open=ed.diagnosticsRun==="open",{enabled,result,pending}=useDiagnosticsRun(cwd,paths,{version:String(open?mtimeMs:savedAt),settle:open,lsp:ed.diagnostics==="lsp",rerun:tick});return{items:result?.diagnostics??null,ran:result?.ran??[],failed:result?.failed??[],running:pending,enabled,rerun:()=>{cwd&&run?run.invalidate(cwd).catch(()=>{}).then(()=>setTick(t2=>t2+1)):setTick(t2=>t2+1)}}}const EMPTY_DIAGNOSTICS=[],DIFF_DEFAULT_MAX_LINES=1500,DIFF_DEFAULT_MAX_BYTES=200*1024;function diffFits(file){return file===null||file.size<=DIFF_DEFAULT_MAX_BYTES&&lineCount(file.contents)<=DIFF_DEFAULT_MAX_LINES}function opensAsDiff({changed,isNew,fits}){return changed&&!isNew&&fits}function newFilePaths(status){return new Set(status.filter(s2=>s2.status==="untracked"||s2.status==="added").map(s2=>s2.path))}const OpenFileTab=reactExports.memo(({path,active,drafts,glyph,tab,onPick,onClose,onContextMenu})=>{const dirty=useIsDirty(drafts,path);return jsxRuntimeExports.jsx(FileTabPill,{path,active,dirty,glyph:glyph(path),lifted:tab.lifted,onPick:tab.pick(()=>onPick(path)),onMove:tab.onMove,onClose:()=>onClose(path),onContextMenu:at=>onContextMenu({path,kind:"file"},at)})});OpenFileTab.displayName="OpenFileTab";const EditorColumn=reactExports.memo(({cwd,files,treeSide,treeOpen,hasChanges,isNewFile,onRevealInTree,onContextMenu,revealAt=null,findAsk=0,renderTabGlyph=renderFileIcon,readOnly=!1,onDropFiles,filePaths,onSelectInTree})=>{const host=useFilesHost(),labels=useFilesLabels(),system=host.system,onRight=treeSide==="right",active=files.active,{show,setActivePath,close,setDraft,adoptFile,replace,reorder}=files,[diffOverride,setDiffOverride]=reactExports.useState({}),[reveal,setReveal]=reactExports.useState(null),navigate=reactExports.useCallback(t2=>{show(t2.path),setDiffOverride(o2=>o2[t2.path]===!1?o2:{...o2,[t2.path]:!1}),setReveal(r2=>({path:t2.path,line:t2.line,column:t2.column,nonce:(r2?.nonce??0)+1}))},[show]),revealedNonceRef=reactExports.useRef(0);reactExports.useEffect(()=>{!revealAt||revealAt.nonce===revealedNonceRef.current||(revealedNonceRef.current=revealAt.nonce,navigate(revealAt))},[revealAt,navigate]);const changed=active&&host.workingTreeDiff&&!(active.file&&active.file!=="missing"&&active.file.media)?hasChanges(active.path):!1,dirty=useIsDirty(files.drafts,active?.path??null);active&&dirty&&diffOverride[active.path]!==!1&&setDiffOverride(o2=>({...o2,[active.path]:!1}));const adoptSaved=reactExports.useCallback((path,file,reset)=>{reset||setDiffOverride(o2=>o2[path]===!1?o2:{...o2,[path]:!1}),adoptFile(path,file,reset)},[adoptFile]),activeFile=active&&active.file!==null&&active.file!=="missing"?active.file:null,isNew=active!==null&&isNewFile(active.path),smallEnough=reactExports.useMemo(()=>diffFits(activeFile),[activeFile]),diffMode=active&&!dirty?diffOverride[active.path]??opensAsDiff({changed,isNew,fits:smallEnough}):!1,activeDraft=useDraft(files.drafts,active?.path??null),[rendered,setRendered]=reactExports.useState({}),[diffsShown,setDiffsShown]=reactExports.useState(()=>new Set),[diffsReady,setDiffsReady]=reactExports.useState(()=>new Set),activeText=activeFile!==null&&!activeFile.binary&&!activeFile.truncated,diffActive=diffMode&&activeText&&active!==null,previewKind=active&&activeText?previewKindOfPath(active.path):null,previewing=previewKind!==null&&!diffMode&&active!==null&&rendered[active.path]===!0;reactExports.useEffect(()=>{diffActive&&active&&setDiffsShown(s2=>s2.has(active.path)?s2:new Set(s2).add(active.path))},[diffActive,active]);const markDiffReady=reactExports.useCallback(path=>setDiffsReady(s2=>s2.has(path)?s2:new Set(s2).add(path)),[]),pending=active!==null&&(active.file===null||diffActive&&!diffsReady.has(active.path)),current=active&&activeText&&!pending?{path:active.path,diff:diffMode}:null,shownRef=reactExports.useRef(null);current&&(shownRef.current=current);const isText=f2=>f2.file!==null&&f2.file!=="missing"&&!f2.file.binary&&!f2.file.truncated,heldOpen=files.open.some(f2=>f2.path===shownRef.current?.path&&isText(f2)),shown=current??(pending&&heldOpen?shownRef.current:null),mediaNow=active&&activeFile?.media?{path:active.path,file:activeFile}:null,[heldMedia,setHeldMedia]=reactExports.useState(mediaNow);mediaNow&&(heldMedia?.path!==mediaNow.path||heldMedia.file!==mediaNow.file)&&setHeldMedia(mediaNow);const media=mediaNow??(pending&&active&&mediaTypeOfPath(active.path)?heldMedia:null),mediaViewerRef=reactExports.useRef(null),activePathNow=active?.path??null,siblings=reactExports.useMemo(()=>filePaths&&activePathNow?mediaSiblings(filePaths,activePathNow):null,[filePaths,activePathNow]),browse=reactExports.useMemo(()=>{if(!siblings||siblings.paths.length<2||!activePathNow)return;const{paths,index}=siblings;return{index,count:paths.length,onStep:delta=>{const next=paths[(index+delta+paths.length)%paths.length];replace(activePathNow,next),onSelectInTree?.(next)}}},[siblings,activePathNow,replace,onSelectInTree]),mountedDiffs=files.open.filter(isText).filter(f2=>diffsShown.has(f2.path)||diffActive&&f2.path===active?.path),diagnostics=useDiagnostics(cwd,activeFile&&active?active.path:null,activeFile?.mtimeMs??null,active?files.savedAt.get(active.path)??0:0),lspItems=useLsp(cwd,activeFile&&active&&!activeFile.binary&&!activeFile.truncated?active.path:null,activeFile&&active?activeDraft??activeFile.contents:null),openPaths=reactExports.useMemo(()=>files.open.map(f2=>f2.path),[files.open]),[dropping,setDropping]=reactExports.useState(!1),takes=e2=>{const types=Array.from(e2.dataTransfer?.types??[]);return types.includes(TREE_PATH_MIME)||onDropFiles!==void 0&&types.includes("Files")},onDragOver=e2=>{takes(e2)&&(e2.preventDefault(),e2.dataTransfer.dropEffect="copy",dropping||setDropping(!0))},onDragLeave=e2=>{dropping&&!(e2.relatedTarget instanceof Node&&e2.currentTarget.contains(e2.relatedTarget))&&setDropping(!1)},onDrop=e2=>{if(!takes(e2))return;e2.preventDefault(),e2.stopPropagation(),setDropping(!1);const path=e2.dataTransfer.getData(TREE_PATH_MIME);path?show(path):onDropFiles?.(e2.dataTransfer)};return jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0 min-h-0 flex flex-col","data-zg-file-drop":dropping?"true":void 0,onDragOverCapture:onDragOver,onDragLeave,onDropCapture:onDrop,children:[jsxRuntimeExports.jsx("div",{className:`shrink-0 flex items-center h-9 min-w-0 ${treeOpen?"px-2":onRight?"pl-2 pr-9":"pl-9 pr-2"}`,children:openPaths.length>0&&jsxRuntimeExports.jsx(ReorderTabs,{ids:openPaths,activeId:files.activePath,onReorder:reorder,label:labels.filesOpenFiles,renderTab:(path,tab)=>jsxRuntimeExports.jsx(OpenFileTab,{path,active:path===files.activePath,drafts:files.drafts,glyph:renderTabGlyph,tab,onPick:setActivePath,onClose:close,onContextMenu})})}),active?jsxRuntimeExports.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[jsxRuntimeExports.jsxs("div",{className:"shrink-0 flex items-center gap-2 h-8 pl-3 pr-2",children:[jsxRuntimeExports.jsx(Breadcrumb,{path:active.path,onFolder:onRevealInTree,onFile:()=>onRevealInTree(active.path)}),jsxRuntimeExports.jsxs("div",{className:"zg-segment shrink-0",children:[diagnostics.enabled&&jsxRuntimeExports.jsx(FilesDiagnosticsChip,{diagnostics,live:lspItems}),changed&&!dirty&&jsxRuntimeExports.jsx(IconToggle,{size:"xs",active:diffMode,onClick:()=>{setDiffOverride(o2=>({...o2,[active.path]:!diffMode})),diffMode||setRendered(r2=>({...r2,[active.path]:!1}))},icon:"i-ph-git-diff",label:diffMode?labels.filesPlainView:smallEnough?labels.filesShowChanges:labels.filesShowChangesLarge}),previewKind&&jsxRuntimeExports.jsx(IconToggle,{size:"xs",active:previewing,onClick:()=>{setRendered(r2=>({...r2,[active.path]:!previewing})),!previewing&&diffMode&&setDiffOverride(o2=>({...o2,[active.path]:!1}))},icon:"i-ph-eye",label:previewing?labels.filesShowCode:labels.filesShowRendered}),system?.isLocal(cwd)&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(IconToggle,{size:"xs",active:!1,onClick:()=>{system.openPath(absolutePath({cwd,path:active.path})).catch(()=>!1)},icon:"i-ph-arrow-square-out",label:labels.filesOpenEditor}),jsxRuntimeExports.jsx(IconToggle,{size:"xs",active:!1,onClick:()=>{system.revealPath(absolutePath({cwd,path:active.path})).catch(()=>!1)},icon:"i-ph-folder-open",label:labels.filesRevealFinder})]})]})]}),jsxRuntimeExports.jsxs("div",{className:"relative flex-1 min-h-0 flex flex-col overflow-auto",children:[media&&host.mediaUrl?jsxRuntimeExports.jsx("div",{className:`flex-1 min-h-0 flex ${media.file.media.kind==="pdf"?"":"items-center justify-center p-4"}`,"data-testid":"file-media",children:jsxRuntimeExports.jsx(MediaFrame,{name:media.path.slice(media.path.lastIndexOf("/")+1),viewerRef:mediaViewerRef,...browse?{browse}:{},children:jsxRuntimeExports.jsx(MediaView,{kind:media.file.media.kind,src:host.mediaUrl({kind:"file",cwd,path:media.path,version:media.file.mtimeMs}),name:media.path.slice(media.path.lastIndexOf("/")+1),viewerRef:mediaViewerRef},`${media.path}:${media.file.mtimeMs}`)})}):pending?shown===null&&jsxRuntimeExports.jsx(PanelLoading,{}):active.file==="missing"?jsxRuntimeExports.jsx(PanelEmpty,{icon:"i-ph-file-x",title:labels.filesNotFound}):active.file?.binary||active.file?.media?jsxRuntimeExports.jsx(PanelEmpty,{icon:"i-ph-file",title:labels.filesBinary}):active.file?.truncated?jsxRuntimeExports.jsx(PanelEmpty,{icon:"i-ph-file",title:labels.filesTooLarge(Math.round(active.file.size/1024))}):null,mountedDiffs.map(f2=>{const visible=shown?.path===f2.path&&shown.diff;return jsxRuntimeExports.jsx("div",{hidden:!visible&&!diffsReady.has(f2.path),inert:!visible,"aria-hidden":!visible||void 0,className:visible?"flex-1 min-h-0 flex flex-col":"absolute inset-0 invisible flex flex-col",children:jsxRuntimeExports.jsx(DiffFileViewer,{cwd,path:f2.path,file:f2.file,visible,onReady:markDiffReady,onUnavailable:()=>setDiffOverride(o2=>({...o2,[f2.path]:!1})),findAsk})},`diff:${f2.path}`)}),previewing&&activeFile&&jsxRuntimeExports.jsx(FilePreview,{cwd,path:active.path,kind:previewKind,text:activeDraft??activeFile.contents,version:activeFile.mtimeMs,onOpenFile:show,onRevealFolder:onRevealInTree}),files.open.map(f2=>{if(!isText(f2))return null;const isActive=shown?.path===f2.path&&!shown.diff&&!(previewing&&f2.path===active.path),isCurrent=isActive&&current!==null;return jsxRuntimeExports.jsx("div",{hidden:!isActive,className:"flex-1 min-h-0 flex flex-col",children:jsxRuntimeExports.jsx(CodeViewer,{cwd,path:f2.path,readOnly,file:f2.file,drafts:files.drafts,editKey:files.editKey(f2.path),diagnostics:isCurrent?diagnostics.items??EMPTY_DIAGNOSTICS:EMPTY_DIAGNOSTICS,liveDiagnostics:isCurrent?lspItems??EMPTY_DIAGNOSTICS:EMPTY_DIAGNOSTICS,onNavigate:navigate,reveal:isCurrent&&reveal&&reveal.path===f2.path?reveal:null,visible:isActive,findAsk,onDraft:setDraft,onAdopt:adoptSaved})},f2.path)})]})]}):jsxRuntimeExports.jsx(PanelEmpty,{icon:"i-ph-file-text",title:labels.filesPickFile,hint:labels.filesPickFileHint})]})});EditorColumn.displayName="EditorColumn";function renderFileIcon(path){return jsxRuntimeExports.jsx(FileIcon,{path})}const TREE_WIDTH={default:220,min:160,max:480},SEARCH_DEBOUNCE_MS=100,MemoFileTree=reactExports.memo(FileTree2),TreeColumn=reactExports.memo(p2=>{const onRight=p2.side==="right",presence=usePresence(p2.open,{enter:!0,exitMs:readPanelMs,key:p2.scopeKey}),settled=usePanelSettled(presence.state),labels=useFilesLabels(),colRef=reactExports.useRef(null),drag=useResizeDrag({value:p2.width,min:TREE_WIDTH.min,max:TREE_WIDTH.max,defaultValue:TREE_WIDTH.default,edge:onRight?"start":"end",target:{ref:colRef,cssVar:"--zg-files-tree-w"},onCommit:w2=>p2.layout.update({filesTreeWidth:w2})}),[query,setQuery]=reactExports.useState(""),{controlRef,entries}=p2;reactExports.useEffect(()=>{const t2=window.setTimeout(()=>controlRef.current?.setSearch(query),SEARCH_DEBOUNCE_MS);return()=>window.clearTimeout(t2)},[controlRef,query]);const queryRef=reactExports.useRef(query);return queryRef.current=query,reactExports.useEffect(()=>{controlRef.current?.setSearch(queryRef.current)},[controlRef,entries]),presence.mounted?jsxRuntimeExports.jsxs("div",{ref:colRef,className:"zg-files-tree relative shrink-0 min-h-0","data-collapsed":presence.state!=="open","data-settled":settled||void 0,"data-side":p2.side,style:{"--zg-files-tree-w":`${p2.width}px`},children:[jsxRuntimeExports.jsxs("div",{className:`zg-files-tree-sheet absolute inset-y-0 ${onRight?"left-0":"right-0"} flex flex-col min-h-0`,children:[p2.search&&jsxRuntimeExports.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:p2.search}),jsxRuntimeExports.jsx("div",{hidden:!!p2.search,className:`shrink-0 flex items-center h-9 ${onRight?"pl-2 pr-9":"pl-9 pr-2"}`,children:jsxRuntimeExports.jsxs("div",{className:"zg-well flex-1 min-w-0 flex items-center gap-1.5 h-7 px-2",children:[jsxRuntimeExports.jsx("span",{className:"i-ph-magnifying-glass text-zg-label text-[var(--zg-text-muted)] shrink-0","aria-hidden":!0}),jsxRuntimeExports.jsx("input",{type:"text",value:query,onChange:e2=>setQuery(e2.target.value),onKeyDown:e2=>{e2.key==="Escape"&&(e2.preventDefault(),setQuery(""),e2.currentTarget.blur())},placeholder:labels.filesSearchFiles,"aria-label":labels.filesSearchFiles,spellCheck:!1,className:"flex-1 min-w-0 bg-transparent border-0 outline-none p-0 text-xs text-[var(--zg-text)] placeholder:text-[var(--zg-text-muted)]"}),query.length>0&&jsxRuntimeExports.jsx(IconButton,{size:"xs",icon:"i-ph-x",label:labels.filesClearSearch,onClick:()=>setQuery(""),className:"!rounded-full -mr-1"})]})}),jsxRuntimeExports.jsxs("div",{hidden:!!p2.search,className:"shrink-0 flex items-center gap-1 h-8 pl-3 pr-2",children:[jsxRuntimeExports.jsx("span",{className:"zg-meta truncate flex-1",title:p2.cwd,children:p2.cwd.split("/").pop()}),p2.onNewEntry&&jsxRuntimeExports.jsxs("div",{className:"zg-segment shrink-0",children:[jsxRuntimeExports.jsx(IconToggle,{active:!1,onClick:()=>p2.onNewEntry?.("file"),icon:"i-ph-file-plus",label:labels.filesNewFile}),jsxRuntimeExports.jsx(IconToggle,{active:!1,onClick:()=>p2.onNewEntry?.("folder"),icon:"i-ph-folder-plus",label:labels.filesNewFolder})]}),jsxRuntimeExports.jsxs("div",{className:"zg-segment shrink-0",children:[jsxRuntimeExports.jsx(IconToggle,{active:p2.changedOnly,onClick:p2.onToggleChanged,icon:"i-ph-git-commit",label:p2.changedOnly?labels.filesAllFiles:labels.filesChangedOnly,badge:p2.changedCount>0?String(p2.changedCount):void 0}),jsxRuntimeExports.jsx(IconToggle,{active:p2.showIgnored,onClick:p2.onToggleIgnored,icon:p2.showIgnored?"i-ph-eye":"i-ph-eye-slash",label:p2.showIgnored?labels.filesHideIgnored:labels.filesShowIgnored}),jsxRuntimeExports.jsx(IconToggle,{active:!1,onClick:p2.onRefresh,icon:"i-ph-arrows-clockwise",label:labels.filesRefresh})]})]}),p2.notice&&!p2.search&&jsxRuntimeExports.jsx(Notice,{tone:"error",compact:!0,className:"shrink-0 mx-2 mb-1",action:jsxRuntimeExports.jsx(IconButton,{size:"xs",icon:"i-ph-x",label:labels.filesDismiss,onClick:()=>p2.onDismissNotice?.(),className:"ml-auto"}),children:p2.notice}),p2.entries===null?!p2.search&&jsxRuntimeExports.jsx(PanelLoading,{}):p2.entries.length===0&&!(p2.editing&&!p2.changedOnly)?!p2.search&&jsxRuntimeExports.jsx(PanelEmpty,{icon:"i-ph-tree-structure",title:p2.changedOnly?labels.filesNoChanged:labels.filesEmptyFolder}):jsxRuntimeExports.jsx("div",{className:p2.search?"hidden":"contents",onKeyDown:p2.onTreeKeyDown,children:jsxRuntimeExports.jsx(MemoFileTree,{controlRef:p2.controlRef,entries:p2.entries,gitStatus:p2.gitStatus,selectedPath:p2.selectedPath,onSelect:p2.onSelect,onOpen:p2.onOpen,onContextMenu:p2.onContextMenu,openPaths:p2.openPaths,...p2.onExpandFolder?{onExpandFolder:p2.onExpandFolder}:{},...p2.editing?{editing:p2.editing}:{},className:"flex-1 min-h-0"})})]}),jsxRuntimeExports.jsx("div",{...drag.handleProps,"data-active":drag.active,className:`zg-resize-handle ${onRight?"-left-1":"-right-1"}`})]}):null});TreeColumn.displayName="TreeColumn";function typing(e2){const origin=e2.nativeEvent.composedPath()[0];return origin instanceof HTMLElement&&(origin.isContentEditable||/^(?:INPUT|TEXTAREA|SELECT)$/.test(origin.tagName))}function useEntryActions(input){const{cwd,entries,tree,files,refresh,selected,labels}=input,confirm=useOptionalConfirm(),[notice,setNotice]=reactExports.useState(null),[clipboard,setClipboard]=reactExports.useState(null),latest=reactExports.useRef({cwd,entries,files,refresh,selected,labels,confirm,clipboard});latest.current={cwd,entries,files,refresh,selected,labels,confirm,clipboard};const run=reactExports.useCallback(async actions=>{const{cwd:at,entries:host,refresh:reread,labels:words}=latest.current;if(!at||!host)return[];const done=[];for(const action of actions){let result;try{result=await action(at,host)}catch(error){result={ok:!1,reason:"denied",message:error instanceof Error?error.message:String(error)}}if(!result.ok){setNotice(entryRefusalText(result.reason,words)),tree.current?.resync();break}done.push(result)}return done.length===actions.length&&setNotice(null),await reread(),done},[tree]),enabled=!!entries&&!!cwd,create=reactExports.useCallback(async(path,kind)=>{const[made]=await run([(at,host)=>host.create(at,path,kind==="folder"?"dir":"file")]);made&&kind==="file"&&latest.current.files.show(made.path)},[run]),moveTo=reactExports.useCallback(async(paths,toDir,copy)=>{const picked=topLevelPaths(paths).filter(p2=>copy||parentOf(p2)!==toDir),done=await run(picked.map(from=>copy?(at,host)=>host.copy(at,from,toDir):(at,host)=>host.move(at,from,inFolder(toDir,nameOf(from)))));return copy||done.forEach((result,i2)=>latest.current.files.moved(picked[i2],result.path)),done},[run]),editing=reactExports.useMemo(()=>enabled?{onRename:(from,to)=>{run([(at,host)=>host.move(at,from,to)]).then(([moved])=>{moved&&latest.current.files.moved(from,moved.path)})},onCreate:(path,kind)=>{create(path,kind)},onMove:(paths,toDir,copy)=>{moveTo(paths,toDir,copy)},onDropFiles:(toDir,data)=>{const items=droppedItems(data),{cwd:at,entries:host}=latest.current;!at||!host||items.length===0||host.importFiles(at,toDir,items).then(async result=>{setNotice(result.ok?null:entryRefusalText(result.reason,latest.current.labels)),await latest.current.refresh(),result.paths[0]&&tree.current?.revealSoon(result.paths[0])})},onError:()=>setNotice(latest.current.labels.filesEntryExists)}:void 0,[enabled,run,create,moveTo,tree]),remove=reactExports.useCallback(async paths=>{const{cwd:at,entries:host,confirm:ask,labels:words}=latest.current;if(!at||!host||!ask||paths.length===0)return;const trash=host.removal(at)==="trash";if(!await ask({title:words.filesDeleteTitle(nameOf(paths[0]),paths.length),message:trash?words.filesDeleteToTrash:words.filesDeletePermanent,confirmLabel:trash?words.filesMoveToTrash:words.filesDeleteConfirm,destructive:!0}))return;const picked=topLevelPaths(paths),done=await run(picked.map(path=>(c2,h2)=>h2.remove(c2,path)));for(const result of done)latest.current.files.removed(result.path)},[run]),paste=reactExports.useCallback(async dir=>{const clip=latest.current.clipboard;if(!clip||clip.cwd!==latest.current.cwd)return;const done=await moveTo(clip.paths,dir,clip.mode==="copy");clip.mode==="cut"&&done.length>0&&setClipboard(null),done[0]&&tree.current?.revealSoon(done[0].path)},[moveTo,tree]),canPaste=clipboard!==null&&clipboard.cwd===cwd,menu=reactExports.useMemo(()=>enabled?{create:(dir,kind)=>{tree.current?.startCreate(dir,kind,kind==="folder"?labels.filesNewFolder:labels.filesNewFile)},rename:path=>{tree.current?.startRename(path)},duplicate:path=>{run([(at,host)=>host.copy(at,path,parentOf(path))]).then(([copy])=>{copy&&tree.current?.revealSoon(copy.path)})},clip:(path,mode)=>setClipboard({mode,cwd:latest.current.cwd??"",paths:[path]}),...canPaste?{paste:dir=>{paste(dir)}}:{},...confirm?{remove:path=>{remove([path])}}:{}}:void 0,[enabled,canPaste,confirm,labels,run,paste,remove,tree]),selectedDir=()=>{const at=latest.current.selected;return at?at.endsWith("/")?at.slice(0,-1):parentOf(at):""},newEntry=reactExports.useMemo(()=>enabled?kind=>{tree.current?.startCreate(selectedDir(),kind,kind==="folder"?labels.filesNewFolder:labels.filesNewFile)}:void 0,[enabled,labels,tree]),dropOnEditor=reactExports.useMemo(()=>enabled?data=>{const items=droppedItems(data),{cwd:at,entries:host}=latest.current;!at||!host||items.length===0||host.importFiles(at,"",items).then(async result=>{setNotice(result.ok?null:entryRefusalText(result.reason,latest.current.labels)),await latest.current.refresh();const first=result.paths[0];first&&(items.length===1&&!items[0].entry?.isDirectory?latest.current.files.show(first):tree.current?.revealSoon(first))})}:void 0,[enabled,tree]),onTreeKeyDown=reactExports.useCallback(e2=>{const at=latest.current.selected;if(!enabled||typing(e2)||e2.altKey)return;const mod=e2.metaKey||e2.ctrlKey,path=at?at.replace(/\/$/,""):null,key2=e2.key.toLowerCase();if(mod&&(key2==="c"||key2==="x")&&path)setClipboard({mode:key2==="x"?"cut":"copy",cwd:latest.current.cwd??"",paths:[path]});else if(mod&&key2==="v"&&latest.current.clipboard)paste(selectedDir());else if((mod&&e2.key==="Backspace"||e2.key==="Delete")&&path&&latest.current.confirm)remove([path]);else return;e2.preventDefault(),e2.stopPropagation()},[enabled,paste,remove]),dismissNotice=reactExports.useCallback(()=>setNotice(null),[]);return{editing,menu,newEntry,dropOnEditor,onTreeKeyDown,notice,dismissNotice}}const NO_FOLDER=folderBuffers("");function useOpenFiles(scope,layout,layoutStore,prefs,source){const read=useFilesHost().read,cwd=filesRootOf(scope)||null,[open,setOpen]=reactExports.useState(()=>layout.filesOpen.map(path=>({path,file:null}))),[activePath,setActivePath]=reactExports.useState(layout.filesActive),buffers2=cwd?folderBuffers(cwd):NO_FOLDER,drafts=buffers2.drafts,retired=reactExports.useRef(new Set),setDraft=reactExports.useCallback((path,contents,base)=>{contents!==null&&retired.current.has(path)||drafts.set(path,contents,base)},[drafts]);reactExports.useEffect(()=>{for(const f2 of open)retired.current.delete(f2.path)},[open]);const[holding,setHolding]=reactExports.useState(()=>({buffers:buffers2,slots:new Map}));holding.buffers!==buffers2&&setHolding({buffers:buffers2,slots:new Map});const slots=holding.slots,editKey=reactExports.useCallback(path=>{let held=slots.get(path);return held||slots.set(path,held=buffers2.claim(path)),buffers2.key(path,held)},[buffers2,slots]);reactExports.useEffect(()=>()=>{for(const[p2,s2]of holding.slots)holding.buffers.release(p2,s2);holding.slots.clear()},[holding]);const resetEditSession=reactExports.useCallback(path=>{const held=slots.get(path);held&&slots.set(path,buffers2.reset(path,held))},[buffers2,slots]),[savedAt,setSavedAt]=reactExports.useState(new Map),reads=reactExports.useRef(new Map),adoptFile=reactExports.useCallback((path,file,resetEditor=!1)=>{const inFlight=reads.current.get(path);inFlight!==void 0&&reads.current.set(path,inFlight+1),resetEditor?resetEditSession(path):setSavedAt(m2=>new Map(m2).set(path,Date.now())),setOpen(current=>current.map(f2=>f2.path===path&&f2.file!==file?{path,file}:f2)),setDraft(path,null)},[setDraft,resetEditSession]),layoutRef=reactExports.useRef(layoutStore);layoutRef.current=layoutStore,reactExports.useEffect(()=>{layoutRef.current.update({filesOpen:open.map(f2=>f2.path),filesActive:activePath,...prefs})},[open,activePath,prefs]);const stale=reactExports.useRef(new Set),openRef=reactExports.useRef(open);openRef.current=open;const activeRef=reactExports.useRef(activePath);activeRef.current=activePath;const reload=reactExports.useCallback(async path=>{if(!cwd)return;stale.current.delete(path);const mine=(reads.current.get(path)??0)+1;reads.current.set(path,mine);const file=(read?await read(cwd,path).catch(()=>null):null)??"missing";reads.current.get(path)===mine&&(reads.current.delete(path),setOpen(current=>{const idx=current.findIndex(f2=>f2.path===path);if(idx===-1||sameFile(current[idx].file,file))return current;const next=current.slice();return next[idx]={path,file},next}))},[read,cwd]),reloadAll=reactExports.useCallback(()=>{for(const f2 of openRef.current)reload(f2.path)},[reload]),{visible}=source,visibleRef=reactExports.useRef(visible);visibleRef.current=visible,reactExports.useEffect(()=>{visible&&activePath&&stale.current.has(activePath)&&reload(activePath)},[visible,activePath,reload]),reactExports.useEffect(()=>{for(const f2 of openRef.current)f2.file===null&&reload(f2.path)},[cwd,reload]);const seenEdits=reactExports.useRef(new WeakSet),editsRef=reactExports.useRef(source.edits);editsRef.current=source.edits;const{onToolResult}=source;reactExports.useEffect(()=>onToolResult(()=>{const touched=new Set;for(const ev of editsRef.current){if(seenEdits.current.has(ev))continue;seenEdits.current.add(ev);const p2=editedPath(ev);p2!==null&&touched.add(p2)}for(const f2 of openRef.current)visibleRef.current&&(f2.path===activeRef.current||touched.has(f2.path))?reload(f2.path):stale.current.add(f2.path)}),[onToolResult,reload]),reactExports.useEffect(()=>{for(const ev of editsRef.current)seenEdits.current.add(ev)},[]);const lastStatus=reactExports.useRef(source.status);reactExports.useEffect(()=>{const prev=lastStatus.current;if(lastStatus.current=source.status,prev===source.status)return;const moved2=statusDelta(prev,source.status);if(moved2.size!==0)for(const f2 of openRef.current)moved2.has(f2.path)&&f2.path!==activeRef.current&&reload(f2.path)},[source.status,reload]);const show=reactExports.useCallback(path=>{setOpen(current=>current.some(f2=>f2.path===path)?current:[...current,{path,file:null}]),setActivePath(path),reload(path)},[reload]),close=reactExports.useCallback(path=>{const held=slots.get(path);slots.delete(path);const shared=buffers2.holders(path)>(held?1:0);held&&buffers2.release(path,held),shared||(held&&buffers2.reset(path,held),setDraft(path,null),setTimeout(()=>{buffers2.holders(path)===0&&setDraft(path,null)},0)),stale.current.delete(path),setOpen(current=>{const idx=current.findIndex(f2=>f2.path===path),next=current.filter(f2=>f2.path!==path);return setActivePath(active2=>active2===path?next[Math.max(0,Math.min(idx,next.length-1))]?.path??null:active2),next})},[setDraft,buffers2,slots]),reorder=reactExports.useCallback(paths=>{setOpen(current=>{const byPath=new Map(current.map(f2=>[f2.path,f2])),next=[...paths.flatMap(p2=>{const f2=byPath.get(p2);return f2?(byPath.delete(p2),[f2]):[]}),...byPath.values()];return next.every((f2,i2)=>f2===current[i2])?current:next})},[]),moved=reactExports.useCallback((from,to)=>{if(from===to)return;const renames=openRef.current.flatMap(f2=>{const next=movedPath(f2.path,from,to);return next===null||next===f2.path?[]:[{old:f2.path,next}]});if(renames.length===0)return;for(const{old,next}of renames){const text=drafts.get(old),base=drafts.baseOf(old);text!==void 0&&drafts.set(next,text,base?{...base,path:next}:void 0);const held=slots.get(old);slots.delete(old),held&&buffers2.release(old,held),drafts.set(old,null),retired.current.add(old),stale.current.delete(old)}const map=new Map(renames.map(r2=>[r2.old,r2.next]));setOpen(current=>current.map(f2=>map.has(f2.path)?{path:map.get(f2.path),file:null}:f2)),setActivePath(current=>current&&map.has(current)?map.get(current):current);for(const{next}of renames)reload(next)},[drafts,buffers2,slots,reload]),replace=reactExports.useCallback((from,to)=>{if(from===to)return;if(drafts.has(from)){show(to);return}const held=slots.get(from);slots.delete(from),held&&buffers2.release(from,held),stale.current.delete(from),setOpen(current=>{if(current.some(f2=>f2.path===to))return current.filter(f2=>f2.path!==from);const at=current.findIndex(f2=>f2.path===from);return at===-1?[...current,{path:to,file:null}]:current.map((f2,i2)=>i2===at?{path:to,file:null}:f2)}),setActivePath(to),reload(to)},[drafts,show,slots,buffers2,reload]),removed=reactExports.useCallback(path=>{for(const f2 of openRef.current)isUnder(f2.path,path)&&(drafts.has(f2.path)?setOpen(current=>current.map(o2=>o2.path===f2.path?{path:o2.path,file:"missing"}:o2)):close(f2.path))},[drafts,close]),active=reactExports.useMemo(()=>open.find(f2=>f2.path===activePath)??null,[open,activePath]);return reactExports.useMemo(()=>({open,drafts,setDraft,editKey,adoptFile,savedAt,activePath,active,setActivePath,show,replace,close,reorder,reloadAll,moved,removed}),[open,drafts,setDraft,editKey,adoptFile,savedAt,activePath,active,setActivePath,show,replace,close,reorder,reloadAll,moved,removed])}const TOOL_RESULT_DEBOUNCE_MS=400,NO_FOLDERS=new Map;function useWorkspace(scope,showIgnored,visible,useEdits){const host=useFilesHost(),[listed,setListed]=reactExports.useState(null),[opened,setOpened]=reactExports.useState(NO_FOLDERS),openedRef=reactExports.useRef(opened);openedRef.current=opened;const[status,setStatus]=reactExports.useState([]),cwd=filesRootOf(scope)||null,edits=useEdits(scope.session??null),onFolderChange=useFolderChanges(scope),reads=reactExports.useRef(0),refresh=reactExports.useCallback(async()=>{if(!cwd)return;const mine=++reads.current,folders2=[...openedRef.current.keys()];let listing,git,inFolders;try{[listing,git,inFolders]=await Promise.all([host.list?host.list(cwd,{showIgnored}):{entries:[]},host.gitStatus?host.gitStatus(cwd):[],Promise.all(folders2.map(async dir=>host.list?(await host.list(cwd,{showIgnored,dir})).entries:[]))])}catch{mine===reads.current&&setListed(prev=>prev??[]);return}if(mine!==reads.current)return;const list=listing.entries;setListed(prev=>sameEntries(prev,list)?prev:list),setStatus(prev=>sameStatus(prev,git)?prev:git),folders2.length>0&&setOpened(prev=>{let changed=!1;const next=new Map(prev);return folders2.forEach((dir,i2)=>{const fresh=inFolders[i2];sameEntries(prev.get(dir)??null,fresh)||(changed=!0,next.set(dir,fresh))}),changed?next:prev})},[host,cwd,showIgnored]),generation=reactExports.useRef(0);reactExports.useEffect(()=>{generation.current++,setListed(null),setOpened(NO_FOLDERS),openedRef.current=NO_FOLDERS,refresh()},[refresh]);const openFolder=reactExports.useCallback(dir=>{const list=host.list;if(!cwd||!list||openedRef.current.has(dir))return;const mine=generation.current;list(cwd,{showIgnored,dir}).then(({entries:inside})=>{mine===generation.current&&setOpened(prev=>prev.has(dir)?prev:new Map(prev).set(dir,inside))},()=>{})},[host,cwd,showIgnored]),entries=reactExports.useMemo(()=>withOpenedFolders(listed,opened),[listed,opened]),onToolResult=reactExports.useCallback(handler=>{let timer=null;const off=onFolderChange(()=>{timer&&clearTimeout(timer),timer=setTimeout(()=>{timer=null,handler()},TOOL_RESULT_DEBOUNCE_MS)});return()=>{timer&&clearTimeout(timer),off()}},[onFolderChange]),cwdRef=reactExports.useRef(cwd);cwdRef.current=cwd;const visibleRef=reactExports.useRef(visible);visibleRef.current=visible;const staleListing=reactExports.useRef(!1);reactExports.useEffect(()=>onToolResult(()=>{visibleRef.current?refresh():staleListing.current=!0,cwdRef.current&&host.diagnostics?.invalidate(cwdRef.current).catch(()=>{})}),[host,onToolResult,refresh]),reactExports.useEffect(()=>{!visible||!staleListing.current||(staleListing.current=!1,refresh())},[visible,refresh]);const changedKey=reactExports.useMemo(()=>{const set=editedPaths(edits);for(const g2 of status)set.add(g2.path);return[...set].sort().join("\0")},[edits,status]),changedPaths=reactExports.useMemo(()=>new Set(changedKey?changedKey.split("\0"):[]),[changedKey]);return reactExports.useMemo(()=>({entries,status,changedPaths,edits,refresh,onToolResult,openFolder}),[entries,status,changedPaths,edits,refresh,onToolResult,openFolder])}function withOpenedFolders(listed,opened){if(!listed||opened.size===0)return listed;const all=[...listed,...[...opened.values()].flat()],seen=new Set;return all.filter(e2=>seen.has(e2.path)?!1:(seen.add(e2.path),!(e2.kind==="dir"&&(opened.get(e2.path.replace(/\/$/,""))?.length??0)>0)))}function filterChanged(entries,changed){return entries.filter(e2=>{const p2=e2.path.replace(/\/$/,"");if(e2.kind==="file")return changed.has(p2);for(const c2 of changed)if(c2.startsWith(`${p2}/`))return!0;return!1})}function FilesTab({scope,layout:layoutStore,chat=null,useEdits=useNoEdits,useKeyScope=useNoKeyScope,revealRequest=null,onRevealTaken,takeRevealPosition,onOpenExternal,renderTabGlyph,readOnly=!1,fileActions=!0,className,style}){const host=useFilesHost(),labels=useFilesLabels(),cwd=filesRootOf(scope)||null,key2=filesScopeKey(scope),[ownLayout]=reactExports.useState(createMemoryFilesLayout),layoutOf=layoutStore??ownLayout,visible=usePanelVisible(),{filesTreeSide}=useAppearanceState(),layout=useReadable(layoutOf),[showIgnored,setShowIgnored]=reactExports.useState(layout.filesShowIgnored),[treeOpen,setTreeOpen]=reactExports.useState(layout.filesTreeOpen),[changedOnly,setChangedOnly]=reactExports.useState(layout.filesChangedOnly),prefs=reactExports.useMemo(()=>({filesShowIgnored:showIgnored,filesTreeOpen:treeOpen,filesChangedOnly:changedOnly}),[showIgnored,treeOpen,changedOnly]),[selected,setSelected]=reactExports.useState(layout.filesActive),treeControl=reactExports.useRef(null);useLspConfigSync();const workspace=useWorkspace(scope,showIgnored,visible,useEdits),files=useOpenFiles(scope,layout,layoutOf,prefs,{onToolResult:workspace.onToolResult,edits:workspace.edits,status:workspace.status,visible}),openPaths=reactExports.useMemo(()=>files.open.map(f2=>f2.path),[files.open]),rootRef=reactExports.useRef(null),[findAsk,setFindAsk]=reactExports.useState(0),[searchOpen,setSearchOpen]=reactExports.useState(!1),[searchAsk,setSearchAsk]=reactExports.useState(0);useKeyScope(rootRef,{step:direction=>{const paths=files.open.map(f2=>f2.path),next=steppedIndex(files.activePath?paths.indexOf(files.activePath):-1,paths.length,direction);return next<0?!1:(files.setActivePath(paths[next]),!0)},close:()=>files.activePath?(files.close(files.activePath),!0):!1,find:mode=>mode==="files"?(setSearchOpen(!0),setSearchAsk(n2=>n2+1),setTreeOpen(!0),!0):files.activePath?(setFindAsk(n2=>n2+1),!0):!1});const actions=useEntryActions({cwd,entries:readOnly||!fileActions?void 0:host.entries,tree:treeControl,files,refresh:workspace.refresh,selected,labels}),[menu,setMenu]=reactExports.useState(null),openTreeMenu=reactExports.useCallback((target,at)=>{cwd&&setMenu({target:{cwd,...target},at,tree:!0})},[cwd]),openMenu=reactExports.useCallback((target,at)=>{cwd&&setMenu({target:{cwd,...target},at,tree:!1})},[cwd]),showFile=files.show,show=reactExports.useCallback(path=>{showFile(path),setSelected(path)},[showFile]),activate=reactExports.useCallback(async(path,event)=>{cwd&&((event.metaKey||event.ctrlKey)&&onOpenExternal&&await onOpenExternal(`${cwd}/${path}`)||show(path))},[cwd,show,onOpenExternal]),toggleTree=reactExports.useCallback(()=>setTreeOpen(v2=>!v2),[]),toggleChanged=reactExports.useCallback(()=>setChangedOnly(v2=>!v2),[]),toggleIgnored=reactExports.useCallback(()=>setShowIgnored(v2=>!v2),[]),{refresh:refreshWorkspace}=workspace,{reloadAll}=files,onRefresh=reactExports.useCallback(()=>{cwd&&(host.diagnostics?.invalidate(cwd).catch(()=>{}),refreshWorkspace(),reloadAll())},[host,cwd,refreshWorkspace,reloadAll]),revealInTree=reactExports.useCallback(path=>{setTreeOpen(!0),treeControl.current?.reveal(path)},[]),selectInTree=reactExports.useCallback(path=>{setSelected(path),treeControl.current?.reveal(path)},[]),[revealAt,setRevealAt]=reactExports.useState(null),[folderAsk,setFolderAsk]=reactExports.useState(null);reactExports.useEffect(()=>{const req=revealRequest;if(!req||!cwd)return;onRevealTaken?.();const at=takeRevealPosition?.(req)??null,rel=relativeTo(req,cwd)??(req.startsWith("/")&&!req.endsWith("/")?req:null);if(rel!==null){if(req.endsWith("/")){setTreeOpen(!0),setSearchOpen(!1),setFolderAsk({abs:req,rel:rel.replace(/\/$/,"")});return}rel&&(show(rel),at&&setRevealAt(r2=>({path:rel,...at,nonce:(r2?.nonce??0)+1})))}},[revealRequest,cwd,show]),reactExports.useEffect(()=>{!folderAsk||!workspace.entries||!treeControl.current||(setFolderAsk(null),folderAsk.rel&&!treeControl.current.reveal(folderAsk.rel)&&host.system&&host.system.revealPath(folderAsk.abs).catch(()=>!1))},[host,folderAsk,workspace.entries,treeOpen]);const statusPaths=reactExports.useMemo(()=>new Set(workspace.status.map(s2=>s2.path)),[workspace.status]),hasChanges=reactExports.useCallback(path=>statusPaths.has(path),[statusPaths]),newPaths=reactExports.useMemo(()=>newFilePaths(workspace.status),[workspace.status]),isNewFile=reactExports.useCallback(path=>newPaths.has(path),[newPaths]),entries=reactExports.useMemo(()=>workspace.entries&&changedOnly?filterChanged(workspace.entries,workspace.changedPaths):workspace.entries,[workspace.entries,workspace.changedPaths,changedOnly]),filePaths=reactExports.useMemo(()=>(workspace.entries??[]).filter(e2=>e2.kind==="file"&&!e2.ignored).map(e2=>e2.path),[workspace.entries]),searchNames=reactExports.useCallback((query,opts)=>nameMatches(filePaths,query,opts),[filePaths]),searchContents=reactExports.useCallback((query,opts)=>cwd&&host.search?host.search(cwd,query,{...opts,searchId:`files:${key2}`}):Promise.resolve({matches:[],capped:!1,engine:"none"}),[host,cwd,key2]),openSearchLine=reactExports.useCallback(m2=>{show(m2.path),setRevealAt(r2=>({path:m2.path,line:m2.line,column:(m2.ranges[0]?.start??0)+1,nonce:(r2?.nonce??0)+1}))},[show]),closeSearch=reactExports.useCallback(()=>setSearchOpen(!1),[]);return cwd?jsxRuntimeExports.jsx(FilesChatContext.Provider,{value:chat,children:jsxRuntimeExports.jsxs("div",{ref:rootRef,className:`relative flex-1 min-h-0 flex ${filesTreeSide==="right"?"flex-row-reverse":"flex-row"}${className?` ${className}`:""}`,style,children:[jsxRuntimeExports.jsx("div",{className:`absolute top-0 h-9 flex items-center z-10 ${filesTreeSide==="right"?"right-1.5":"left-1.5"}`,children:jsxRuntimeExports.jsx(IconToggle,{active:!1,onClick:toggleTree,icon:`${treeOpen?"i-ph-sidebar-simple-fill":"i-ph-sidebar-simple"}${filesTreeSide==="right"?" -scale-x-100":""}`,label:treeOpen?labels.filesHideTree:labels.filesShowTree})}),jsxRuntimeExports.jsx(TreeColumn,{layout:layoutOf,cwd,scopeKey:key2,side:filesTreeSide,open:treeOpen,width:layout.filesTreeWidth??TREE_WIDTH.default,controlRef:treeControl,entries,onExpandFolder:workspace.openFolder,gitStatus:workspace.status,selectedPath:selected,onSelect:setSelected,onOpen:activate,onContextMenu:openTreeMenu,...actions.editing?{editing:actions.editing}:{},...actions.newEntry?{onNewEntry:actions.newEntry}:{},onTreeKeyDown:actions.onTreeKeyDown,notice:actions.notice,onDismissNotice:actions.dismissNotice,changedOnly,changedCount:workspace.changedPaths.size,onToggleChanged:toggleChanged,showIgnored,onToggleIgnored:toggleIgnored,onRefresh,openPaths,search:searchOpen?jsxRuntimeExports.jsx(SearchPanel,{label:labels.filesSearchInFiles,asked:searchAsk,names:searchNames,search:searchContents,onOpenFile:show,onOpenLine:openSearchLine,onClose:closeSearch,inset:filesTreeSide==="right"?"right":"left"}):void 0}),jsxRuntimeExports.jsx(EditorColumn,{cwd,files,treeSide:filesTreeSide,treeOpen,hasChanges,isNewFile,onRevealInTree:revealInTree,onContextMenu:openMenu,revealAt,findAsk,readOnly,filePaths,onSelectInTree:selectInTree,...actions.dropOnEditor?{onDropFiles:actions.dropOnEditor}:{},...renderTabGlyph?{renderTabGlyph}:{}}),jsxRuntimeExports.jsx(RowActionsMenu,{open:menu!==null,position:menu?.at??null,onClose:()=>setMenu(null),items:menu?fileActionItems(menu.target,{chat,labels,system:host.system,...menu.tree&&actions.menu?{entries:actions.menu}:{}}):[]})]})}):jsxRuntimeExports.jsx(PanelEmpty,{icon:"i-ph-folder-dashed",title:scope.session?labels.filesSessionNoFolder:labels.filesNoFolder,className})}function relativeTo(abs,root){const base=root.replace(/\/+$/,"");return abs===base||abs===`${base}/`?"":abs.startsWith(`${base}/`)?abs.slice(base.length+1):null}export{FilesTab};