diffstalker 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,71 +1,71 @@
1
1
  #!/usr/bin/env node
2
- import n8 from"neo-blessed";import Y$ from"neo-blessed";var i$=0.05;function e8($,J,K,X=1){let Q=X+4,q=$-Q,Z=Math.floor(q*K),V=q-Z;return{width:J,height:$,headerHeight:X,topPaneHeight:Z,bottomPaneHeight:V,footerRow:$-1}}function $5($,J,K,X){let Q=J+1,q=Q+K,Z=q+1,V=Z+X,Y=$-1;return{stagingPaneStart:Q,fileListEnd:q,diffPaneStart:Z,diffPaneEnd:V,footerRow:Y}}class t${screen;headerBox;topSeparator;topPane;middleSeparator;bottomPane;bottomSeparator;footerBox;_dimensions;_splitRatio;constructor($,J=0.4){this.screen=$,this._splitRatio=J,this._dimensions=this.calculateDimensions(),this.headerBox=this.createHeaderBox(),this.topSeparator=this.createSeparator(this._dimensions.headerHeight),this.topPane=this.createTopPane(),this.middleSeparator=this.createSeparator(this._dimensions.headerHeight+1+this._dimensions.topPaneHeight),this.bottomPane=this.createBottomPane(),this.bottomSeparator=this.createSeparator(this._dimensions.headerHeight+2+this._dimensions.topPaneHeight+this._dimensions.bottomPaneHeight),this.footerBox=this.createFooterBox(),$.on("resize",()=>this.onResize())}get dimensions(){return this._dimensions}get splitRatio(){return this._splitRatio}setSplitRatio($){this._splitRatio=Math.min(0.85,Math.max(0.15,$)),this.updateLayout()}adjustSplitRatio($){this.setSplitRatio(this._splitRatio+$)}calculateDimensions(){let $=this.screen.height||24,J=this.screen.width||80;return e8($,J,this._splitRatio)}createHeaderBox(){return Y$.box({parent:this.screen,top:0,left:0,width:"100%",height:this._dimensions.headerHeight,tags:!0})}createSeparator($){let J=this.screen.width||80;return Y$.box({parent:this.screen,top:$,left:0,width:"100%",height:1,content:"─".repeat(J),style:{fg:"gray"}})}createTopPane(){return Y$.box({parent:this.screen,top:this._dimensions.headerHeight+1,left:0,width:"100%",height:this._dimensions.topPaneHeight,tags:!0,scrollable:!0,alwaysScroll:!0,wrap:!1,scrollbar:{ch:" ",track:{bg:"gray"},style:{inverse:!0}}})}createBottomPane(){return Y$.box({parent:this.screen,top:this._dimensions.headerHeight+2+this._dimensions.topPaneHeight,left:0,width:"100%",height:this._dimensions.bottomPaneHeight,tags:!0,scrollable:!0,alwaysScroll:!0,wrap:!1,scrollbar:{ch:" ",track:{bg:"gray"},style:{inverse:!0}}})}createFooterBox(){return Y$.box({parent:this.screen,top:this._dimensions.footerRow,left:0,width:"100%",height:1,tags:!0})}onResize(){this._dimensions=this.calculateDimensions(),this.updateLayout()}updateLayout(){this._dimensions=this.calculateDimensions();let $=this.screen.width||80;this.headerBox.height=this._dimensions.headerHeight,this.headerBox.width=$,this.topSeparator.top=this._dimensions.headerHeight,this.topSeparator.width=$,this.topSeparator.setContent("─".repeat($)),this.topPane.top=this._dimensions.headerHeight+1,this.topPane.height=this._dimensions.topPaneHeight,this.topPane.width=$,this.middleSeparator.top=this._dimensions.headerHeight+1+this._dimensions.topPaneHeight,this.middleSeparator.width=$,this.middleSeparator.setContent("─".repeat($)),this.bottomPane.top=this._dimensions.headerHeight+2+this._dimensions.topPaneHeight,this.bottomPane.height=this._dimensions.bottomPaneHeight,this.bottomPane.width=$,this.bottomSeparator.top=this._dimensions.headerHeight+2+this._dimensions.topPaneHeight+this._dimensions.bottomPaneHeight,this.bottomSeparator.width=$,this.bottomSeparator.setContent("─".repeat($)),this.footerBox.top=this._dimensions.footerRow,this.footerBox.width=$}getPaneBoundaries(){return $5(this._dimensions.height,this._dimensions.headerHeight,this._dimensions.topPaneHeight,this._dimensions.bottomPaneHeight)}screenYToTopPaneRow($){let J=this._dimensions.headerHeight+1,K=J+this._dimensions.topPaneHeight;if($<J||$>=K)return-1;return $-J}screenYToBottomPaneRow($){let J=this._dimensions.headerHeight+2+this._dimensions.topPaneHeight,K=J+this._dimensions.bottomPaneHeight;if($<J||$>=K)return-1;return $-J}get topPaneTop(){return this._dimensions.headerHeight+1}get bottomPaneTop(){return this._dimensions.headerHeight+2+this._dimensions.topPaneHeight}}function s0($,J,K){$.key(["q"],()=>{if(K.hasActiveModal()){J.closeActiveModal();return}J.exit()}),$.key(["C-c"],()=>{J.exit()}),$.key(["j","down"],()=>{if(K.hasActiveModal())return;J.navigateDown()}),$.key(["k","up"],()=>{if(K.hasActiveModal())return;J.navigateUp()});let X=[["1","diff"],["2","commit"],["3","history"],["4","compare"],["5","explorer"]];for(let[Q,q]of X)$.key([Q],()=>{if(K.hasActiveModal())return;K.uiState.setTab(q)});$.key(["tab"],()=>{if(K.hasActiveModal()||K.isCommitInputFocused())return;K.uiState.advanceFocus()}),$.key(["S-tab"],()=>{if(K.hasActiveModal()||K.isCommitInputFocused())return;K.uiState.retreatFocus()}),$.key(["s"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="diff"&&K.getCurrentPane()==="diff")J.toggleCurrentHunk();else J.stageSelected()}),$.key(["S-u"],()=>{if(K.hasActiveModal())return;J.unstageSelected()}),$.key(["S-a"],()=>{if(K.hasActiveModal())return;J.stageAll()}),$.key(["S-z"],()=>{if(K.hasActiveModal())return;J.unstageAll()}),$.key(["enter","space"],()=>{if(K.hasActiveModal())return;let Q=K.getFocusedZone();if(Q==="commitMessage"&&!K.isCommitInputFocused()){J.focusCommitInput();return}if(Q==="commitAmend"){K.commitFlowState.toggleAmend(),J.render();return}if(K.getBottomTab()==="explorer"&&K.getCurrentPane()==="explorer")J.enterExplorerDirectory();else J.toggleSelected()}),$.key(["backspace"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="explorer"&&K.getCurrentPane()==="explorer")J.goExplorerUp()}),$.key(["g"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="explorer")K.getExplorerManager()?.toggleShowOnlyChanges()}),$.key(["/"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="explorer")J.openFileFinder()}),$.key(["C-p"],()=>{if(K.hasActiveModal())return;J.openFileFinder()}),$.key(["c"],()=>{if(K.hasActiveModal())return;K.uiState.setTab("commit")}),$.key(["i"],()=>{if(K.getBottomTab()==="commit"&&!K.isCommitInputFocused())J.focusCommitInput()}),$.key(["a"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="commit"&&!K.isCommitInputFocused())K.commitFlowState.toggleAmend(),J.render();else K.uiState.toggleAutoTab()}),$.key(["C-a"],()=>{if(K.getBottomTab()==="commit")K.commitFlowState.toggleAmend(),J.render()}),$.key(["escape"],()=>{if(K.hasActiveModal()){J.closeActiveModal();return}if(K.getBottomTab()==="commit")if(K.isCommitInputFocused())J.unfocusCommitInput();else K.uiState.setTab("diff")}),$.key(["r"],()=>{if(K.getActiveModalType()==="repoPicker"){J.closeActiveModal();return}if(K.hasActiveModal())return;J.openRepoPicker()}),$.key(["w"],()=>{if(K.hasActiveModal())return;K.uiState.toggleWrapMode()}),$.key(["m"],()=>{if(K.hasActiveModal())return;J.toggleMouseMode()}),$.key(["S-t"],()=>{if(K.hasActiveModal())return;K.uiState.toggleAutoTab()}),$.key(["-","_","["],()=>{K.uiState.adjustSplitRatio(-i$),K.layout.setSplitRatio(K.uiState.state.splitRatio),J.render()}),$.key(["=","+","]"],()=>{K.uiState.adjustSplitRatio(i$),K.layout.setSplitRatio(K.uiState.state.splitRatio),J.render()}),$.key(["t"],()=>{if(K.getActiveModalType()==="theme"){J.closeActiveModal();return}if(K.hasActiveModal())return;J.openThemePicker()}),$.key(["?"],()=>{if(K.getActiveModalType()==="hotkeys"){J.closeActiveModal();return}if(K.hasActiveModal())return;J.openHotkeysModal()}),$.key(["f"],()=>{if(K.hasActiveModal())return;J.toggleFollow()}),$.key(["b"],()=>{if(K.getActiveModalType()==="baseBranch"){J.closeActiveModal();return}if(K.hasActiveModal())return;if(K.getBottomTab()==="compare")J.openBaseBranchPicker()}),$.key(["u"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="compare"){K.uiState.toggleIncludeUncommitted();let Q=K.uiState.state.includeUncommitted;K.getGitManager()?.compare.refreshCompareDiff(Q)}}),$.key(["h"],()=>{if(K.hasActiveModal())return;let Q=K.getBottomTab();if(Q==="diff"||Q==="commit")K.uiState.toggleFlatViewMode()}),$.key(["d"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="diff"){let Q=K.resolveFileAtIndex(K.getSelectedIndex());if(Q&&!Q.staged&&Q.status!=="untracked")J.openDiscardConfirm(Q)}}),$.key(["n"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="diff"&&K.getCurrentPane()==="diff")J.navigateNextHunk()}),$.key(["S-n"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="diff"&&K.getCurrentPane()==="diff")J.navigatePrevHunk()}),$.key(["p"],()=>{if(K.hasActiveModal()||K.isCommitInputFocused())return;if(K.getBottomTab()==="history")J.openCherryPickConfirm()}),$.key(["v"],()=>{if(K.hasActiveModal()||K.isCommitInputFocused())return;if(K.getBottomTab()==="history")J.openRevertConfirm()})}function z$($){let J=$.filter((Q)=>!Q.staged&&Q.status!=="untracked"),K=$.filter((Q)=>!Q.staged&&Q.status==="untracked"),X=$.filter((Q)=>Q.staged);return{modified:J,untracked:K,staged:X,ordered:[...J,...K,...X]}}function a($,J){let{modified:K,untracked:X}=z$($),Q=K.length,q=X.length;if(J<Q)return{category:"modified",categoryIndex:J};if(J<Q+q)return{category:"untracked",categoryIndex:J-Q};return{category:"staged",categoryIndex:J-Q-q}}function a0($,J,K){let{modified:X,untracked:Q,staged:q,ordered:Z}=z$($);if(Z.length===0)return 0;let Y={modified:X,untracked:Q,staged:q}[J];if(Y.length===0)return Z.length-1;let z=Math.min(K,Y.length-1);return{modified:0,untracked:X.length,staged:X.length+Q.length}[J]+z}function U$($,J){let{ordered:K}=z$($);return K[J]??null}function e$($,J){if($.length<=J)return $;let X=Math.max(J,20);if($.length<=X)return $;let Q=$.split("/");if(Q.length===1){let j=Math.floor((X-1)/2);return $.slice(0,j)+"…"+$.slice(-(X-j-1))}let q=Q[Q.length-1],Z=Q[0],V="/…/";if(Z.length+V.length+q.length>X){let j=X-2;if(q.length>j){let B=Math.floor((j-1)/2);return"…/"+q.slice(0,B)+"…"+q.slice(-(j-B-1))}return"…/"+q}let z=Z,U=1;while(U<Q.length-1){let j=Q[U],B=z+"/"+j;if(B.length+V.length+q.length<=X)z=B,U++;else break}if(U===Q.length-1)return $;return z+V+q}function _$($){switch($){case"modified":return"M";case"added":return"A";case"deleted":return"D";case"untracked":return"?";case"renamed":return"R";case"copied":return"C";default:return" "}}function D$($){switch($){case"modified":return"yellow";case"added":return"green";case"deleted":return"red";case"untracked":return"gray";case"renamed":return"blue";case"copied":return"cyan";default:return"white"}}function v$($,J){if($===void 0&&J===void 0)return"";let K=[];if($!==void 0&&$>0)K.push(`{green-fg}+${$}{/green-fg}`);if(J!==void 0&&J>0)K.push(`{red-fg}-${J}{/red-fg}`);return K.length>0?" "+K.join(" "):""}function W$($,J){if($&&J)return"{cyan-fg}{bold}▸ {/bold}{/cyan-fg}";else if($)return"{gray-fg}▸ {/gray-fg}";return" "}function H$($,J,K,X){let Q=e$($,X);if(J&&K)return`{cyan-fg}{inverse}${Q}{/inverse}{/cyan-fg}`;else if(J)return`{cyan-fg}${Q}{/cyan-fg}`;return Q}function T$($){if(!$)return"";return` {gray-fg}← ${e$($,30)}{/gray-fg}`}function A$($){let{modified:J,untracked:K,staged:X}=z$($),Q=[],q=0;if(J.length>0)Q.push({type:"header",content:"Modified:",headerColor:"yellow"}),J.forEach((Z)=>{Q.push({type:"file",file:Z,fileIndex:q++})});if(K.length>0){if(J.length>0)Q.push({type:"spacer"});Q.push({type:"header",content:"Untracked:",headerColor:"gray"}),K.forEach((Z)=>{Q.push({type:"file",file:Z,fileIndex:q++})})}if(X.length>0){if(J.length>0||K.length>0)Q.push({type:"spacer"});Q.push({type:"header",content:"Staged:",headerColor:"green"}),X.forEach((Z)=>{Q.push({type:"file",file:Z,fileIndex:q++})})}return Q}function J5($,J){if(!J)return"";let K=J.staged.get($.path)??0,X=J.unstaged.get($.path)??0,Q=K+X;if(Q===0)return"";let q=$.staged?K:X;if(q===Q)return` {cyan-fg}@${Q}{/cyan-fg}`;return` {cyan-fg}@${q}/${Q}{/cyan-fg}`}function K5($,J,K,X,Q,q){let Z=J===K,V=_$($.status),Y=D$($.status),z=$.staged?"[-]":"[+]",U=$.staged?"red":"green",j=v$($.insertions,$.deletions),B=J5($,q),G=j.replace(/\{[^}]+\}/g,"").length,M=B.replace(/\{[^}]+\}/g,"").length,H=Q-G-M,D=W$(Z,X);return D+=`{${U}-fg}${z}{/${U}-fg} `,D+=`{${Y}-fg}${V}{/${Y}-fg} `,D+=H$($.path,Z,X,H),D+=T$($.originalPath),D+=j,D+=B,D}function n0($,J,K,X,Q=0,q,Z){if($.length===0)return"{gray-fg} No changes{/gray-fg}";let V=A$($),Y=X-12,z=q?V.slice(Q,Q+q):V.slice(Q),U=[],j=!1;for(let B of z)switch(B.type){case"header":{let G=`{bold}{${B.headerColor}-fg}${B.content}{/${B.headerColor}-fg}{/bold}`;if(!j)j=!0,G+=" {gray-fg}(h:flat){/gray-fg}";U.push(G);break}case"spacer":U.push("");break;case"file":if(B.file&&B.fileIndex!==void 0)U.push(K5(B.file,B.fileIndex,J,K,Y,Z??null));break}return U.join(`
3
- `)}function i0($){return A$($).length}function t0($,J){let X=A$(J)[$];if(X?.type==="file"&&X.fileIndex!==void 0)return X.fileIndex;return null}function e0($,J){let K=A$(J);for(let X=0;X<K.length;X++)if(K[X].type==="file"&&K[X].fileIndex===$)return X;return 0}function X5($){switch($){case"unstaged":return{text:"[+]",color:"green"};case"staged":return{text:"[-]",color:"red"};case"partial":return{text:"[~]",color:"yellow"}}}function Q5($){if($.totalHunks===0)return"";return` {cyan-fg}@${$.stagedHunks}/${$.totalHunks}{/cyan-fg}`}function q5($,J,K,X,Q){let q=J===K,Z=_$($.status),V=D$($.status),Y=X5($.stagingState),z=v$($.insertions,$.deletions),U=Q5($),j=z.replace(/\{[^}]+\}/g,"").length,B=U.replace(/\{[^}]+\}/g,"").length,G=Q-j-B,M=W$(q,X);return M+=`{${Y.color}-fg}${Y.text}{/${Y.color}-fg} `,M+=`{${V}-fg}${Z}{/${V}-fg} `,M+=H$($.path,q,X,G),M+=T$($.originalPath),M+=z,M+=U,M}function $1($,J,K,X,Q=0,q){if($.length===0)return"{gray-fg} No changes{/gray-fg}";let Z=X-12,V=[];V.push("{bold}{gray-fg}All files (h):{/gray-fg}{/bold}");for(let z=0;z<$.length;z++)V.push(q5($[z],z,J,K,Z));return(q?V.slice(Q,Q+q):V.slice(Q)).join(`
4
- `)}function J1($){if($.length===0)return 0;return $.length+1}function k$($){let K=new Date().getTime()-$.getTime(),X=Math.floor(K/3600000),Q=Math.floor(K/86400000);if(X<1)return`${Math.floor(K/60000)}m ago`;else if(X<48)return`${X}h ago`;else if(Q<=14)return`${Q}d ago`;else return $.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function K1($){return $.toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Z5($,J){if($.length<=J)return $;if(J<=3)return $.slice(0,J);return $.slice(0,J-3)+"..."}function N$($,J,K,X=20){let Q=J||"",q=Math.max(0,K-X-1),Z=Q;if(Z.length>q&&q>3)Z=Z.slice(0,q-3)+"...";else if(Z.length>q)Z="";let V=Z?Z.length+1:0,Y=Math.max(X,K-V);return{displayMessage:Z5($,Y),displayRefs:Z}}function X1($,J,K,X,Q=0,q){if($.length===0)return"{gray-fg}No commits yet{/gray-fg}";let Z=q?$.slice(Q,Q+q):$.slice(Q),V=[];for(let Y=0;Y<Z.length;Y++){let z=Z[Y],B=Q+Y===J&&K,G=k$(z.date),M=11+G.length+2+2,H=Math.max(10,X-M),{displayMessage:D,displayRefs:T}=N$(z.message,z.refs,H),W="";if(B)W+="{cyan-fg}{bold}▸ {/bold}{/cyan-fg}";else W+=" ";if(W+=`{yellow-fg}${z.shortHash}{/yellow-fg} `,B)W+=`{cyan-fg}{inverse}${$0(D)}{/inverse}{/cyan-fg}`;else W+=$0(D);if(W+=` {gray-fg}(${G}){/gray-fg}`,T)W+=` {green-fg}${$0(T)}{/green-fg}`;V.push(W)}return V.join(`
5
- `)}function $0($){return $.replace(/\{/g,"{{").replace(/\}/g,"}}")}function Q1($,J){return $[J]??null}function q1($){let J={name:"",fullPath:"",isDirectory:!0,children:[],depth:0};for(let K=0;K<$.length;K++){let Q=$[K].path.split("/"),q=J;for(let Z=0;Z<Q.length;Z++){let V=Q[Z],Y=Z===Q.length-1,z=Q.slice(0,Z+1).join("/"),U=q.children.find((j)=>j.name===V&&j.isDirectory===!Y);if(!U)U={name:V,fullPath:z,isDirectory:!Y,children:[],depth:q.depth+1,fileIndex:Y?K:void 0},q.children.push(U);q=U}}return Z1(J),Y1(J),J}function Z1($){for(let J of $.children)Z1(J);for(let J=0;J<$.children.length;J++){let K=$.children[J];while(K.isDirectory&&K.children.length===1&&K.children[0].isDirectory){let X=K.children[0];K.name=`${K.name}/${X.name}`,K.fullPath=X.fullPath,K.children=X.children,V1(K,K.depth)}}}function V1($,J){$.depth=J;for(let K of $.children)V1(K,J+1)}function Y1($){$.children.sort((J,K)=>{if(J.isDirectory&&!K.isDirectory)return-1;if(!J.isDirectory&&K.isDirectory)return 1;return J.name.localeCompare(K.name)});for(let J of $.children)Y1(J)}function z1($){let J=[];function K(X,Q){for(let q=0;q<X.children.length;q++){let Z=X.children[q],V=q===X.children.length-1;if(J.push({type:Z.isDirectory?"directory":"file",name:Z.name,fullPath:Z.fullPath,depth:Z.depth-1,fileIndex:Z.fileIndex,isLast:V,parentIsLast:[...Q]}),Z.isDirectory)K(Z,[...Q,V])}}return K($,[]),J}function J0($){let J="";for(let K=0;K<$.depth;K++)if($.parentIsLast[K])J+=" ";else J+="│ ";if($.depth>=0)if($.isLast)J+="└ ";else J+="├ ";return J}var v="\x1B[0m",u="\x1B[1m",w="\x1B[7m",B$="\x1B[31m",x="\x1B[32m",b="\x1B[33m",n="\x1B[34m",J$="\x1B[35m",R="\x1B[36m",F="\x1B[90m",U1="\x1B[39m",K0=/\x1b\[[0-9;]*m/g;function X0($){let J=parseInt($.slice(1,3),16),K=parseInt($.slice(3,5),16),X=parseInt($.slice(5,7),16);return`\x1B[48;2;${J};${K};${X}m`}function B1($){let J=parseInt($.slice(1,3),16),K=parseInt($.slice(3,5),16),X=parseInt($.slice(5,7),16);return`\x1B[38;2;${J};${K};${X}m`}function G$($,J,K=!0,X=!0){let Q=[];if($.length>0){if(Q.push({type:"section-header",sectionType:"commits"}),K)$.forEach((q,Z)=>{Q.push({type:"commit",commitIndex:Z,commit:q})})}if(J.length>0){if($.length>0)Q.push({type:"spacer"});if(Q.push({type:"section-header",sectionType:"files"}),X){let q=q1(J),Z=z1(q);for(let V of Z)if(V.type==="directory")Q.push({type:"directory",treeRow:V});else{let Y=J[V.fileIndex];Q.push({type:"file",fileIndex:V.fileIndex,file:Y,treeRow:V})}}}return Q}function V5($,J,K,X){let Q=J&&K,q=k$($.date),Z=13+q.length+2,V=Math.max(10,X-Z),{displayMessage:Y,displayRefs:z}=N$($.message,$.refs,V),U=` ${b}${$.shortHash}${v} `;if(Q)U+=`${R}${w}${Y}${v}`;else U+=Y;if(U+=` ${F}(${q})${v}`,z)U+=` ${x}${z}${v}`;return`{escape}${U}{/escape}`}function Y5($,J){let K=J0($),X="▸ ",Q=J-K.length-2-2,q=$.name;if(q.length>Q)q=q.slice(0,Q-1)+"…";return`{escape}${`${F}${K}${v}${n}${"▸ "}${q}${v}`}{/escape}`}function z5($,J,K,X,Q){let q=K&&X,Z=$.isUncommitted??!1,V=J0(J),Y={added:x,modified:b,deleted:B$,renamed:n},z={added:"+",modified:"●",deleted:"−",renamed:"→"},U=Z?J$:Y[$.status],j=z[$.status],B=`(+${$.additions} -${$.deletions})`,G=Z?" [uncommitted]":"",M=V.length+2+B.length+G.length+2,H=Math.max(5,Q-M),D=J.name;if(D.length>H)D=D.slice(0,H-1)+"…";let T=`${F}${V}${v}`;if(T+=`${U}${j}${v} `,q)T+=`${R}${w}${D}${v}`;else if(Z)T+=`${J$}${D}${v}`;else T+=D;if(T+=` ${F}(${x}+${$.additions}${v} ${B$}-${$.deletions}${F})${v}`,Z)T+=` ${J$}[uncommitted]${v}`;return`{escape}${T}{/escape}`}function U5($,J){if(!J)return!1;if($.type==="commit"&&$.commitIndex!==void 0)return J.type==="commit"&&J.index===$.commitIndex;if($.type==="file"&&$.fileIndex!==void 0)return J.type==="file"&&J.index===$.fileIndex;return!1}function B5($,J){return`{escape}${R}${u}▼ ${$}${v} ${F}(${J})${v}{/escape}`}function G5($,J,K,X,Q,q){if($.type==="section-header"){let V=$.sectionType==="commits";return B5(V?"Commits":"Files",V?X.length:Q.length)}if($.type==="spacer")return"";if($.type==="directory"&&$.treeRow)return Y5($.treeRow,q);let Z=U5($,J);if($.type==="commit"&&$.commit&&$.commitIndex!==void 0)return V5($.commit,Z,K,q);if($.type==="file"&&$.file&&$.fileIndex!==void 0&&$.treeRow)return z5($.file,$.treeRow,Z,K,q);return null}function G1($,J,K,X,Q,q=0,Z){if($.length===0&&J.length===0)return"{gray-fg}No changes compared to base branch{/gray-fg}";let V=G$($,J);return(Z?V.slice(q,q+Z):V.slice(q)).map((U)=>G5(U,K,X,$,J,Q)).filter((U)=>U!==null).join(`
6
- `)}function j1($,J,K=!0,X=!0){return G$($,J,K,X).length}function Q0($,J,K,X=!0,Q=!0){let Z=G$(J,K,X,Q)[$];if(!Z)return null;if(Z.type==="commit"&&Z.commitIndex!==void 0)return{type:"commit",index:Z.commitIndex};if(Z.type==="file"&&Z.fileIndex!==void 0)return{type:"file",index:Z.fileIndex};return null}function E$($,J,K,X=!0,Q=!0){let q=G$(J,K,X,Q);for(let Z=0;Z<q.length;Z++){let V=q[Z];if($.type==="commit"&&V.type==="commit"&&V.commitIndex===$.index)return Z;if($.type==="file"&&V.type==="file"&&V.fileIndex===$.index)return Z}return 0}function q0($,J,K,X){let Q=G$(J,K),q=0;if($)q=E$($,J,K);let Z=X==="down"?1:-1,V=q+Z;while(V>=0&&V<Q.length){let Y=Q0(V,J,K);if(Y)return Y;V+=Z}return $}function j5($){let J="";for(let K=0;K<$.depth;K++)if($.parentIsLast[K])J+=" ";else J+="│ ";if($.depth>0||$.parentIsLast.length===0)if($.isLast)J+="└ ";else J+="├ ";return J}function M5($){if(!$)return"";switch($){case"modified":return"M";case"added":return"A";case"deleted":return"D";case"untracked":return"?";case"renamed":return"R";case"copied":return"C";default:return""}}function O5($){if(!$)return v;switch($){case"modified":return b;case"added":return x;case"deleted":return B$;case"untracked":return F;case"renamed":return n;case"copied":return J$;default:return v}}function _5($,J,K,X){let Q=J&&K,q=$.node,Z=j5($),V="";if(q.isDirectory)V=q.expanded?"▾ ":"▸ ";let Y=M5(q.gitStatus),z=O5(q.gitStatus),U=Y?`${z}${Y}${v} `:"",j=q.isDirectory&&q.hasChangedChildren?`${b}●${v} `:"",B=Z.length+V.length+(Y?2:0)+(q.hasChangedChildren&&q.isDirectory?2:0),G=Math.max(5,X-B-2),M=q.isDirectory?`${q.name}/`:q.name;if(M.length>G)M=M.slice(0,G-1)+"…";let H=`${F}${Z}${v}`;if(q.isDirectory)if(H+=`${n}${V}${v}`,H+=j,Q)H+=`${R}${u}${w}${M}${v}`;else H+=`${n}${M}${v}`;else if(H+=U,Q)H+=`${R}${u}${w}${M}${v}`;else if(q.gitStatus)H+=`${z}${M}${v}`;else H+=M;return H}function M1($,J,K,X,Q=0,q,Z=!1,V=null){if(V)return`{red-fg}Error: ${D5(V)}{/red-fg}`;if(Z)return"{gray-fg}Loading...{/gray-fg}";if($.length===0)return"{gray-fg}(empty directory){/gray-fg}";let Y=q?$.slice(Q,Q+q):$.slice(Q),z=[];for(let U=0;U<Y.length;U++){let j=Q+U,B=_5(Y[U],j===J,K,X);z.push(`{escape}${B}{/escape}`)}return z.join(`
7
- `)}function D5($){return $.replace(/\{/g,"{{").replace(/\}/g,"}}")}function O1($){return $.length}var v5={name:"dark",displayName:"Dark",colors:{addBg:"#022800",delBg:"#3D0100",addHighlight:"#044700",delHighlight:"#5C0200",text:"white",addLineNum:"#368F35",delLineNum:"#A14040",contextLineNum:"gray",addSymbol:"greenBright",delSymbol:"redBright"}},W5={name:"light",displayName:"Light",colors:{addBg:"#69db7c",delBg:"#ffa8b4",addHighlight:"#2f9d44",delHighlight:"#d1454b",text:"black",addLineNum:"#2f9d44",delLineNum:"#d1454b",contextLineNum:"#6c757d",addSymbol:"green",delSymbol:"red"}},H5={name:"dark-colorblind",displayName:"Dark (colorblind)",colors:{addBg:"#004466",delBg:"#660000",addHighlight:"#0077b3",delHighlight:"#b30000",text:"white",addLineNum:"#0077b3",delLineNum:"#b30000",contextLineNum:"gray",addSymbol:"cyanBright",delSymbol:"redBright"}},T5={name:"light-colorblind",displayName:"Light (colorblind)",colors:{addBg:"#99ccff",delBg:"#ffcccc",addHighlight:"#3366cc",delHighlight:"#993333",text:"black",addLineNum:"#3366cc",delLineNum:"#993333",contextLineNum:"#6c757d",addSymbol:"blue",delSymbol:"red"}},A5={name:"dark-ansi",displayName:"Dark (ANSI)",colors:{addBg:"green",delBg:"red",addHighlight:"greenBright",delHighlight:"redBright",text:"white",addLineNum:"greenBright",delLineNum:"redBright",contextLineNum:"gray",addSymbol:"greenBright",delSymbol:"redBright"}},k5={name:"light-ansi",displayName:"Light (ANSI)",colors:{addBg:"green",delBg:"red",addHighlight:"greenBright",delHighlight:"redBright",text:"black",addLineNum:"green",delLineNum:"red",contextLineNum:"gray",addSymbol:"green",delSymbol:"red"}},L$={dark:v5,light:W5,"dark-colorblind":H5,"light-colorblind":T5,"dark-ansi":A5,"light-ansi":k5},i=["dark","light","dark-colorblind","light-colorblind","dark-ansi","light-ansi"];function F$($){return L$[$]??L$.dark}function N5($){return!($.startsWith("index ")||$.startsWith("--- ")||$.startsWith("+++ ")||$.startsWith("similarity index"))}function Z0($){if($.type!=="header")return!0;return N5($.content)}function R$($,J,K=!0){if(J<=0)return[{text:$,isContinuation:!1}];if($.length<=J)return[{text:$,isContinuation:!1}];let X=[],Q=$,q=!0;while(Q.length>0){if(Q.length<=J){X.push({text:Q,isContinuation:!q});break}X.push({text:Q.slice(0,J),isContinuation:!q}),Q=Q.slice(J),q=!1}if(K)E5($,J,X);return X}function E5($,J,K){let X=K.map((Q)=>Q.text).join("");if(X!==$)throw Error(`[LineBreaking] Content was lost during breaking!
2
+ import n8 from"neo-blessed";import Y$ from"neo-blessed";var i$=0.05;function e8($,J,K,X=1){let Q=X+4,q=$-Q,Z=Math.floor(q*K),V=q-Z;return{width:J,height:$,headerHeight:X,topPaneHeight:Z,bottomPaneHeight:V,footerRow:$-1}}function $5($,J,K,X){let Q=J+1,q=Q+K,Z=q+1,V=Z+X,Y=$-1;return{stagingPaneStart:Q,fileListEnd:q,diffPaneStart:Z,diffPaneEnd:V,footerRow:Y}}class t${screen;headerBox;topSeparator;topPane;middleSeparator;bottomPane;bottomSeparator;footerBox;_dimensions;_splitRatio;constructor($,J=0.4){this.screen=$,this._splitRatio=J,this._dimensions=this.calculateDimensions(),this.headerBox=this.createHeaderBox(),this.topSeparator=this.createSeparator(this._dimensions.headerHeight),this.topPane=this.createTopPane(),this.middleSeparator=this.createSeparator(this._dimensions.headerHeight+1+this._dimensions.topPaneHeight),this.bottomPane=this.createBottomPane(),this.bottomSeparator=this.createSeparator(this._dimensions.headerHeight+2+this._dimensions.topPaneHeight+this._dimensions.bottomPaneHeight),this.footerBox=this.createFooterBox(),$.on("resize",()=>this.onResize())}get dimensions(){return this._dimensions}get splitRatio(){return this._splitRatio}setSplitRatio($){this._splitRatio=Math.min(0.85,Math.max(0.15,$)),this.updateLayout()}adjustSplitRatio($){this.setSplitRatio(this._splitRatio+$)}calculateDimensions(){let $=this.screen.height||24,J=this.screen.width||80;return e8($,J,this._splitRatio)}createHeaderBox(){return Y$.box({parent:this.screen,top:0,left:0,width:"100%",height:this._dimensions.headerHeight,tags:!0})}createSeparator($){let J=this.screen.width||80;return Y$.box({parent:this.screen,top:$,left:0,width:"100%",height:1,content:"─".repeat(J),style:{fg:"gray"}})}createTopPane(){return Y$.box({parent:this.screen,top:this._dimensions.headerHeight+1,left:0,width:"100%",height:this._dimensions.topPaneHeight,tags:!0,scrollable:!0,alwaysScroll:!0,wrap:!1,scrollbar:{ch:" ",track:{bg:"gray"},style:{inverse:!0}}})}createBottomPane(){return Y$.box({parent:this.screen,top:this._dimensions.headerHeight+2+this._dimensions.topPaneHeight,left:0,width:"100%",height:this._dimensions.bottomPaneHeight,tags:!0,scrollable:!0,alwaysScroll:!0,wrap:!1,scrollbar:{ch:" ",track:{bg:"gray"},style:{inverse:!0}}})}createFooterBox(){return Y$.box({parent:this.screen,top:this._dimensions.footerRow,left:0,width:"100%",height:1,tags:!0})}onResize(){this._dimensions=this.calculateDimensions(),this.updateLayout()}updateLayout(){this._dimensions=this.calculateDimensions();let $=this.screen.width||80;this.headerBox.height=this._dimensions.headerHeight,this.headerBox.width=$,this.topSeparator.top=this._dimensions.headerHeight,this.topSeparator.width=$,this.topSeparator.setContent("─".repeat($)),this.topPane.top=this._dimensions.headerHeight+1,this.topPane.height=this._dimensions.topPaneHeight,this.topPane.width=$,this.middleSeparator.top=this._dimensions.headerHeight+1+this._dimensions.topPaneHeight,this.middleSeparator.width=$,this.middleSeparator.setContent("─".repeat($)),this.bottomPane.top=this._dimensions.headerHeight+2+this._dimensions.topPaneHeight,this.bottomPane.height=this._dimensions.bottomPaneHeight,this.bottomPane.width=$,this.bottomSeparator.top=this._dimensions.headerHeight+2+this._dimensions.topPaneHeight+this._dimensions.bottomPaneHeight,this.bottomSeparator.width=$,this.bottomSeparator.setContent("─".repeat($)),this.footerBox.top=this._dimensions.footerRow,this.footerBox.width=$}getPaneBoundaries(){return $5(this._dimensions.height,this._dimensions.headerHeight,this._dimensions.topPaneHeight,this._dimensions.bottomPaneHeight)}screenYToTopPaneRow($){let J=this._dimensions.headerHeight+1,K=J+this._dimensions.topPaneHeight;if($<J||$>=K)return-1;return $-J}screenYToBottomPaneRow($){let J=this._dimensions.headerHeight+2+this._dimensions.topPaneHeight,K=J+this._dimensions.bottomPaneHeight;if($<J||$>=K)return-1;return $-J}get topPaneTop(){return this._dimensions.headerHeight+1}get bottomPaneTop(){return this._dimensions.headerHeight+2+this._dimensions.topPaneHeight}}function s0($,J,K){$.key(["q"],()=>{if(K.hasActiveModal()){J.closeActiveModal();return}J.exit()}),$.key(["C-c"],()=>{J.exit()}),$.key(["j","down"],()=>{if(K.hasActiveModal())return;J.navigateDown()}),$.key(["k","up"],()=>{if(K.hasActiveModal())return;J.navigateUp()});let X=[["1","diff"],["2","commit"],["3","history"],["4","compare"],["5","explorer"]];for(let[Q,q]of X)$.key([Q],()=>{if(K.hasActiveModal())return;K.uiState.setTab(q)});$.key(["tab"],()=>{if(K.hasActiveModal()||K.isCommitInputFocused())return;K.uiState.advanceFocus()}),$.key(["S-tab"],()=>{if(K.hasActiveModal()||K.isCommitInputFocused())return;K.uiState.retreatFocus()}),$.key(["s"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="diff"&&K.getCurrentPane()==="diff")J.toggleCurrentHunk();else J.stageSelected()}),$.key(["S-u"],()=>{if(K.hasActiveModal())return;J.unstageSelected()}),$.key(["S-a"],()=>{if(K.hasActiveModal())return;J.stageAll()}),$.key(["S-z"],()=>{if(K.hasActiveModal())return;J.unstageAll()}),$.key(["enter","space"],()=>{if(K.hasActiveModal())return;let Q=K.getFocusedZone();if(Q==="commitMessage"&&!K.isCommitInputFocused()){J.focusCommitInput();return}if(Q==="commitAmend"){K.commitFlowState.toggleAmend(),J.render();return}if(K.getBottomTab()==="explorer"&&K.getCurrentPane()==="explorer")J.enterExplorerDirectory();else J.toggleSelected()}),$.key(["backspace"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="explorer"&&K.getCurrentPane()==="explorer")J.goExplorerUp()}),$.key(["g"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="explorer")K.getExplorerManager()?.toggleShowOnlyChanges()}),$.key(["/"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="explorer")J.openFileFinder()}),$.key(["C-p"],()=>{if(K.hasActiveModal())return;J.openFileFinder()}),$.key(["c"],()=>{if(K.hasActiveModal())return;K.uiState.setTab("commit")}),$.key(["i"],()=>{if(K.getBottomTab()==="commit"&&!K.isCommitInputFocused())J.focusCommitInput()}),$.key(["a"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="commit"&&!K.isCommitInputFocused())K.commitFlowState.toggleAmend(),J.render();else K.uiState.toggleAutoTab()}),$.key(["C-a"],()=>{if(K.getBottomTab()==="commit")K.commitFlowState.toggleAmend(),J.render()}),$.key(["escape"],()=>{if(K.hasActiveModal()){J.closeActiveModal();return}if(K.getBottomTab()==="commit")if(K.isCommitInputFocused())J.unfocusCommitInput();else K.uiState.setTab("diff")}),$.key(["r"],()=>{if(K.getActiveModalType()==="repoPicker"){J.closeActiveModal();return}if(K.hasActiveModal())return;J.openRepoPicker()}),$.key(["w"],()=>{if(K.hasActiveModal())return;K.uiState.toggleWrapMode()}),$.key(["m"],()=>{if(K.hasActiveModal())return;J.toggleMouseMode()}),$.key(["S-t"],()=>{if(K.hasActiveModal())return;K.uiState.toggleAutoTab()}),$.key(["-","_","["],()=>{K.uiState.adjustSplitRatio(-i$),K.layout.setSplitRatio(K.uiState.state.splitRatio),J.render()}),$.key(["=","+","]"],()=>{K.uiState.adjustSplitRatio(i$),K.layout.setSplitRatio(K.uiState.state.splitRatio),J.render()}),$.key(["t"],()=>{if(K.getActiveModalType()==="theme"){J.closeActiveModal();return}if(K.hasActiveModal())return;J.openThemePicker()}),$.key(["?"],()=>{if(K.getActiveModalType()==="hotkeys"){J.closeActiveModal();return}if(K.hasActiveModal())return;J.openHotkeysModal()}),$.key(["f"],()=>{if(K.hasActiveModal())return;J.toggleFollow()}),$.key(["b"],()=>{if(K.getActiveModalType()==="baseBranch"){J.closeActiveModal();return}if(K.hasActiveModal())return;if(K.getBottomTab()==="compare")J.openBaseBranchPicker()}),$.key(["u"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="compare"){K.uiState.toggleIncludeUncommitted();let Q=K.uiState.state.includeUncommitted;K.getGitManager()?.compare.refreshCompareDiff(Q)}}),$.key(["h"],()=>{if(K.hasActiveModal())return;let Q=K.getBottomTab();if(Q==="diff"||Q==="commit")K.uiState.toggleFlatViewMode()}),$.key(["d"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="diff"){let Q=K.resolveFileAtIndex(K.getSelectedIndex());if(Q&&!Q.staged&&Q.status!=="untracked")J.openDiscardConfirm(Q)}}),$.key(["n"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="diff"&&K.getCurrentPane()==="diff")J.navigateNextHunk()}),$.key(["S-n"],()=>{if(K.hasActiveModal())return;if(K.getBottomTab()==="diff"&&K.getCurrentPane()==="diff")J.navigatePrevHunk()}),$.key(["p"],()=>{if(K.hasActiveModal()||K.isCommitInputFocused())return;if(K.getBottomTab()==="history")J.openCherryPickConfirm()}),$.key(["v"],()=>{if(K.hasActiveModal()||K.isCommitInputFocused())return;if(K.getBottomTab()==="history")J.openRevertConfirm()})}function z$($){let J=$.filter((Q)=>!Q.staged&&Q.status!=="untracked"),K=$.filter((Q)=>!Q.staged&&Q.status==="untracked"),X=$.filter((Q)=>Q.staged);return{modified:J,untracked:K,staged:X,ordered:[...J,...K,...X]}}function n($,J){let{modified:K,untracked:X}=z$($),Q=K.length,q=X.length;if(J<Q)return{category:"modified",categoryIndex:J};if(J<Q+q)return{category:"untracked",categoryIndex:J-Q};return{category:"staged",categoryIndex:J-Q-q}}function a0($,J,K){let{modified:X,untracked:Q,staged:q,ordered:Z}=z$($);if(Z.length===0)return 0;let Y={modified:X,untracked:Q,staged:q}[J];if(Y.length===0)return Z.length-1;let z=Math.min(K,Y.length-1);return{modified:0,untracked:X.length,staged:X.length+Q.length}[J]+z}function U$($,J){let{ordered:K}=z$($);return K[J]??null}function e$($,J){if($.length<=J)return $;let X=Math.max(J,20);if($.length<=X)return $;let Q=$.split("/");if(Q.length===1){let j=Math.floor((X-1)/2);return $.slice(0,j)+"…"+$.slice(-(X-j-1))}let q=Q[Q.length-1],Z=Q[0],V="/…/";if(Z.length+V.length+q.length>X){let j=X-2;if(q.length>j){let B=Math.floor((j-1)/2);return"…/"+q.slice(0,B)+"…"+q.slice(-(j-B-1))}return"…/"+q}let z=Z,U=1;while(U<Q.length-1){let j=Q[U],B=z+"/"+j;if(B.length+V.length+q.length<=X)z=B,U++;else break}if(U===Q.length-1)return $;return z+V+q}function _$($){switch($){case"modified":return"M";case"added":return"A";case"deleted":return"D";case"untracked":return"?";case"renamed":return"R";case"copied":return"C";default:return" "}}function D$($){switch($){case"modified":return"yellow";case"added":return"green";case"deleted":return"red";case"untracked":return"gray";case"renamed":return"blue";case"copied":return"cyan";default:return"white"}}function W$($,J){if($===void 0&&J===void 0)return"";let K=[];if($!==void 0&&$>0)K.push(`{green-fg}+${$}{/green-fg}`);if(J!==void 0&&J>0)K.push(`{red-fg}-${J}{/red-fg}`);return K.length>0?" "+K.join(" "):""}function v$($,J){if($&&J)return"{cyan-fg}{bold}▸ {/bold}{/cyan-fg}";else if($)return"{gray-fg}▸ {/gray-fg}";return" "}function H$($,J,K,X){let Q=e$($,X);if(J&&K)return`{cyan-fg}{inverse}${Q}{/inverse}{/cyan-fg}`;else if(J)return`{cyan-fg}${Q}{/cyan-fg}`;return Q}function T$($){if(!$)return"";return` {gray-fg}← ${e$($,30)}{/gray-fg}`}function A$($){let{modified:J,untracked:K,staged:X}=z$($),Q=[],q=0;if(J.length>0)Q.push({type:"header",content:"Modified:",headerColor:"yellow"}),J.forEach((Z)=>{Q.push({type:"file",file:Z,fileIndex:q++})});if(K.length>0){if(J.length>0)Q.push({type:"spacer"});Q.push({type:"header",content:"Untracked:",headerColor:"gray"}),K.forEach((Z)=>{Q.push({type:"file",file:Z,fileIndex:q++})})}if(X.length>0){if(J.length>0||K.length>0)Q.push({type:"spacer"});Q.push({type:"header",content:"Staged:",headerColor:"green"}),X.forEach((Z)=>{Q.push({type:"file",file:Z,fileIndex:q++})})}return Q}function J5($,J){if(!J)return"";let K=J.staged.get($.path)??0,X=J.unstaged.get($.path)??0,Q=K+X;if(Q===0)return"";let q=$.staged?K:X;if(q===Q)return` {cyan-fg}@${Q}{/cyan-fg}`;return` {cyan-fg}@${q}/${Q}{/cyan-fg}`}function K5($,J,K,X,Q,q){let Z=J===K,V=_$($.status),Y=D$($.status),z=$.staged?"[-]":"[+]",U=$.staged?"red":"green",j=W$($.insertions,$.deletions),B=J5($,q),G=j.replace(/\{[^}]+\}/g,"").length,M=B.replace(/\{[^}]+\}/g,"").length,v=Q-G-M,D=v$(Z,X);return D+=`{${U}-fg}${z}{/${U}-fg} `,D+=`{${Y}-fg}${V}{/${Y}-fg} `,D+=H$($.path,Z,X,v),D+=T$($.originalPath),D+=j,D+=B,D}function n0($,J,K,X,Q=0,q,Z){if($.length===0)return"{gray-fg} No changes{/gray-fg}";let V=A$($),Y=X-12,z=q?V.slice(Q,Q+q):V.slice(Q),U=[],j=!1;for(let B of z)switch(B.type){case"header":{let G=`{bold}{${B.headerColor}-fg}${B.content}{/${B.headerColor}-fg}{/bold}`;if(!j)j=!0,G+=" {gray-fg}(h:flat){/gray-fg}";U.push(G);break}case"spacer":U.push("");break;case"file":if(B.file&&B.fileIndex!==void 0)U.push(K5(B.file,B.fileIndex,J,K,Y,Z??null));break}return U.join(`
3
+ `)}function i0($){return A$($).length}function t0($,J){let X=A$(J)[$];if(X?.type==="file"&&X.fileIndex!==void 0)return X.fileIndex;return null}function e0($,J){let K=A$(J);for(let X=0;X<K.length;X++)if(K[X].type==="file"&&K[X].fileIndex===$)return X;return 0}function X5($){switch($){case"unstaged":return{text:"[+]",color:"green"};case"staged":return{text:"[-]",color:"red"};case"partial":return{text:"[~]",color:"yellow"}}}function Q5($){if($.totalHunks===0)return"";return` {cyan-fg}@${$.stagedHunks}/${$.totalHunks}{/cyan-fg}`}function q5($,J,K,X,Q){let q=J===K,Z=_$($.status),V=D$($.status),Y=X5($.stagingState),z=W$($.insertions,$.deletions),U=Q5($),j=z.replace(/\{[^}]+\}/g,"").length,B=U.replace(/\{[^}]+\}/g,"").length,G=Q-j-B,M=v$(q,X);return M+=`{${Y.color}-fg}${Y.text}{/${Y.color}-fg} `,M+=`{${V}-fg}${Z}{/${V}-fg} `,M+=H$($.path,q,X,G),M+=T$($.originalPath),M+=z,M+=U,M}function $1($,J,K,X,Q=0,q){if($.length===0)return"{gray-fg} No changes{/gray-fg}";let Z=X-12,V=[];V.push("{bold}{gray-fg}All files (h):{/gray-fg}{/bold}");for(let z=0;z<$.length;z++)V.push(q5($[z],z,J,K,Z));return(q?V.slice(Q,Q+q):V.slice(Q)).join(`
4
+ `)}function J1($){if($.length===0)return 0;return $.length+1}function k$($){let K=new Date().getTime()-$.getTime(),X=Math.floor(K/3600000),Q=Math.floor(K/86400000);if(X<1)return`${Math.floor(K/60000)}m ago`;else if(X<48)return`${X}h ago`;else if(Q<=14)return`${Q}d ago`;else return $.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function K1($){return $.toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Z5($,J){if($.length<=J)return $;if(J<=3)return $.slice(0,J);return $.slice(0,J-3)+"..."}function N$($,J,K,X=20){let Q=J||"",q=Math.max(0,K-X-1),Z=Q;if(Z.length>q&&q>3)Z=Z.slice(0,q-3)+"...";else if(Z.length>q)Z="";let V=Z?Z.length+1:0,Y=Math.max(X,K-V);return{displayMessage:Z5($,Y),displayRefs:Z}}function X1($,J,K,X,Q=0,q){if($.length===0)return"{gray-fg}No commits yet{/gray-fg}";let Z=q?$.slice(Q,Q+q):$.slice(Q),V=[];for(let Y=0;Y<Z.length;Y++){let z=Z[Y],B=Q+Y===J&&K,G=k$(z.date),M=11+G.length+2+2,v=Math.max(10,X-M),{displayMessage:D,displayRefs:T}=N$(z.message,z.refs,v),H="";if(B)H+="{cyan-fg}{bold}▸ {/bold}{/cyan-fg}";else H+=" ";if(H+=`{yellow-fg}${z.shortHash}{/yellow-fg} `,B)H+=`{cyan-fg}{inverse}${$0(D)}{/inverse}{/cyan-fg}`;else H+=$0(D);if(H+=` {gray-fg}(${G}){/gray-fg}`,T)H+=` {green-fg}${$0(T)}{/green-fg}`;V.push(H)}return V.join(`
5
+ `)}function $0($){return $.replace(/\{/g,"{{").replace(/\}/g,"}}")}function Q1($,J){return $[J]??null}function q1($){let J={name:"",fullPath:"",isDirectory:!0,children:[],depth:0};for(let K=0;K<$.length;K++){let Q=$[K].path.split("/"),q=J;for(let Z=0;Z<Q.length;Z++){let V=Q[Z],Y=Z===Q.length-1,z=Q.slice(0,Z+1).join("/"),U=q.children.find((j)=>j.name===V&&j.isDirectory===!Y);if(!U)U={name:V,fullPath:z,isDirectory:!Y,children:[],depth:q.depth+1,fileIndex:Y?K:void 0},q.children.push(U);q=U}}return Z1(J),Y1(J),J}function Z1($){for(let J of $.children)Z1(J);for(let J=0;J<$.children.length;J++){let K=$.children[J];while(K.isDirectory&&K.children.length===1&&K.children[0].isDirectory){let X=K.children[0];K.name=`${K.name}/${X.name}`,K.fullPath=X.fullPath,K.children=X.children,V1(K,K.depth)}}}function V1($,J){$.depth=J;for(let K of $.children)V1(K,J+1)}function Y1($){$.children.sort((J,K)=>{if(J.isDirectory&&!K.isDirectory)return-1;if(!J.isDirectory&&K.isDirectory)return 1;return J.name.localeCompare(K.name)});for(let J of $.children)Y1(J)}function z1($){let J=[];function K(X,Q){for(let q=0;q<X.children.length;q++){let Z=X.children[q],V=q===X.children.length-1;if(J.push({type:Z.isDirectory?"directory":"file",name:Z.name,fullPath:Z.fullPath,depth:Z.depth-1,fileIndex:Z.fileIndex,isLast:V,parentIsLast:[...Q]}),Z.isDirectory)K(Z,[...Q,V])}}return K($,[]),J}function J0($){let J="";for(let K=0;K<$.depth;K++)if($.parentIsLast[K])J+=" ";else J+="│ ";if($.depth>=0)if($.isLast)J+="└ ";else J+="├ ";return J}var W="\x1B[0m",u="\x1B[1m",w="\x1B[7m",B$="\x1B[31m",x="\x1B[32m",b="\x1B[33m",i="\x1B[34m",K$="\x1B[35m",R="\x1B[36m",F="\x1B[90m",U1="\x1B[39m",K0=/\x1b\[[0-9;]*m/g;function X0($){let J=parseInt($.slice(1,3),16),K=parseInt($.slice(3,5),16),X=parseInt($.slice(5,7),16);return`\x1B[48;2;${J};${K};${X}m`}function B1($){let J=parseInt($.slice(1,3),16),K=parseInt($.slice(3,5),16),X=parseInt($.slice(5,7),16);return`\x1B[38;2;${J};${K};${X}m`}function G$($,J,K=!0,X=!0){let Q=[];if($.length>0){if(Q.push({type:"section-header",sectionType:"commits"}),K)$.forEach((q,Z)=>{Q.push({type:"commit",commitIndex:Z,commit:q})})}if(J.length>0){if($.length>0)Q.push({type:"spacer"});if(Q.push({type:"section-header",sectionType:"files"}),X){let q=q1(J),Z=z1(q);for(let V of Z)if(V.type==="directory")Q.push({type:"directory",treeRow:V});else{let Y=J[V.fileIndex];Q.push({type:"file",fileIndex:V.fileIndex,file:Y,treeRow:V})}}}return Q}function V5($,J,K,X){let Q=J&&K,q=k$($.date),Z=13+q.length+2,V=Math.max(10,X-Z),{displayMessage:Y,displayRefs:z}=N$($.message,$.refs,V),U=` ${b}${$.shortHash}${W} `;if(Q)U+=`${R}${w}${Y}${W}`;else U+=Y;if(U+=` ${F}(${q})${W}`,z)U+=` ${x}${z}${W}`;return`{escape}${U}{/escape}`}function Y5($,J){let K=J0($),X="▸ ",Q=J-K.length-2-2,q=$.name;if(q.length>Q)q=q.slice(0,Q-1)+"…";return`{escape}${`${F}${K}${W}${i}${"▸ "}${q}${W}`}{/escape}`}function z5($,J,K,X,Q){let q=K&&X,Z=$.isUncommitted??!1,V=J0(J),Y={added:x,modified:b,deleted:B$,renamed:i},z={added:"+",modified:"●",deleted:"−",renamed:"→"},U=Z?K$:Y[$.status],j=z[$.status],B=`(+${$.additions} -${$.deletions})`,G=Z?" [uncommitted]":"",M=V.length+2+B.length+G.length+2,v=Math.max(5,Q-M),D=J.name;if(D.length>v)D=D.slice(0,v-1)+"…";let T=`${F}${V}${W}`;if(T+=`${U}${j}${W} `,q)T+=`${R}${w}${D}${W}`;else if(Z)T+=`${K$}${D}${W}`;else T+=D;if(T+=` ${F}(${x}+${$.additions}${W} ${B$}-${$.deletions}${F})${W}`,Z)T+=` ${K$}[uncommitted]${W}`;return`{escape}${T}{/escape}`}function U5($,J){if(!J)return!1;if($.type==="commit"&&$.commitIndex!==void 0)return J.type==="commit"&&J.index===$.commitIndex;if($.type==="file"&&$.fileIndex!==void 0)return J.type==="file"&&J.index===$.fileIndex;return!1}function B5($,J){return`{escape}${R}${u}▼ ${$}${W} ${F}(${J})${W}{/escape}`}function G5($,J,K,X,Q,q){if($.type==="section-header"){let V=$.sectionType==="commits";return B5(V?"Commits":"Files",V?X.length:Q.length)}if($.type==="spacer")return"";if($.type==="directory"&&$.treeRow)return Y5($.treeRow,q);let Z=U5($,J);if($.type==="commit"&&$.commit&&$.commitIndex!==void 0)return V5($.commit,Z,K,q);if($.type==="file"&&$.file&&$.fileIndex!==void 0&&$.treeRow)return z5($.file,$.treeRow,Z,K,q);return null}function G1($,J,K,X,Q,q=0,Z){if($.length===0&&J.length===0)return"{gray-fg}No changes compared to base branch{/gray-fg}";let V=G$($,J);return(Z?V.slice(q,q+Z):V.slice(q)).map((U)=>G5(U,K,X,$,J,Q)).filter((U)=>U!==null).join(`
6
+ `)}function j1($,J,K=!0,X=!0){return G$($,J,K,X).length}function Q0($,J,K,X=!0,Q=!0){let Z=G$(J,K,X,Q)[$];if(!Z)return null;if(Z.type==="commit"&&Z.commitIndex!==void 0)return{type:"commit",index:Z.commitIndex};if(Z.type==="file"&&Z.fileIndex!==void 0)return{type:"file",index:Z.fileIndex};return null}function E$($,J,K,X=!0,Q=!0){let q=G$(J,K,X,Q);for(let Z=0;Z<q.length;Z++){let V=q[Z];if($.type==="commit"&&V.type==="commit"&&V.commitIndex===$.index)return Z;if($.type==="file"&&V.type==="file"&&V.fileIndex===$.index)return Z}return 0}function q0($,J,K,X){let Q=G$(J,K),q=0;if($)q=E$($,J,K);let Z=X==="down"?1:-1,V=q+Z;while(V>=0&&V<Q.length){let Y=Q0(V,J,K);if(Y)return Y;V+=Z}return $}function j5($){let J="";for(let K=0;K<$.depth;K++)if($.parentIsLast[K])J+=" ";else J+="│ ";if($.depth>0||$.parentIsLast.length===0)if($.isLast)J+="└ ";else J+="├ ";return J}function M5($){if(!$)return"";switch($){case"modified":return"M";case"added":return"A";case"deleted":return"D";case"untracked":return"?";case"renamed":return"R";case"copied":return"C";default:return""}}function O5($){if(!$)return W;switch($){case"modified":return b;case"added":return x;case"deleted":return B$;case"untracked":return F;case"renamed":return i;case"copied":return K$;default:return W}}function _5($,J,K,X){let Q=J&&K,q=$.node,Z=j5($),V="";if(q.isDirectory)V=q.expanded?"▾ ":"▸ ";let Y=M5(q.gitStatus),z=O5(q.gitStatus),U=Y?`${z}${Y}${W} `:"",j=q.isDirectory&&q.hasChangedChildren?`${b}●${W} `:"",B=Z.length+V.length+(Y?2:0)+(q.hasChangedChildren&&q.isDirectory?2:0),G=Math.max(5,X-B-2),M=q.isDirectory?`${q.name}/`:q.name;if(M.length>G)M=M.slice(0,G-1)+"…";let v=`${F}${Z}${W}`;if(q.isDirectory)if(v+=`${i}${V}${W}`,v+=j,Q)v+=`${R}${u}${w}${M}${W}`;else v+=`${i}${M}${W}`;else if(v+=U,Q)v+=`${R}${u}${w}${M}${W}`;else if(q.gitStatus)v+=`${z}${M}${W}`;else v+=M;return v}function M1($,J,K,X,Q=0,q,Z=!1,V=null){if(V)return`{red-fg}Error: ${D5(V)}{/red-fg}`;if(Z)return"{gray-fg}Loading...{/gray-fg}";if($.length===0)return"{gray-fg}(empty directory){/gray-fg}";let Y=q?$.slice(Q,Q+q):$.slice(Q),z=[];for(let U=0;U<Y.length;U++){let j=Q+U,B=_5(Y[U],j===J,K,X);z.push(`{escape}${B}{/escape}`)}return z.join(`
7
+ `)}function D5($){return $.replace(/\{/g,"{{").replace(/\}/g,"}}")}function O1($){return $.length}var W5={name:"dark",displayName:"Dark",colors:{addBg:"#022800",delBg:"#3D0100",addHighlight:"#044700",delHighlight:"#5C0200",text:"white",addLineNum:"#368F35",delLineNum:"#A14040",contextLineNum:"gray",addSymbol:"greenBright",delSymbol:"redBright"}},v5={name:"light",displayName:"Light",colors:{addBg:"#69db7c",delBg:"#ffa8b4",addHighlight:"#2f9d44",delHighlight:"#d1454b",text:"black",addLineNum:"#2f9d44",delLineNum:"#d1454b",contextLineNum:"#6c757d",addSymbol:"green",delSymbol:"red"}},H5={name:"dark-colorblind",displayName:"Dark (colorblind)",colors:{addBg:"#004466",delBg:"#660000",addHighlight:"#0077b3",delHighlight:"#b30000",text:"white",addLineNum:"#0077b3",delLineNum:"#b30000",contextLineNum:"gray",addSymbol:"cyanBright",delSymbol:"redBright"}},T5={name:"light-colorblind",displayName:"Light (colorblind)",colors:{addBg:"#99ccff",delBg:"#ffcccc",addHighlight:"#3366cc",delHighlight:"#993333",text:"black",addLineNum:"#3366cc",delLineNum:"#993333",contextLineNum:"#6c757d",addSymbol:"blue",delSymbol:"red"}},A5={name:"dark-ansi",displayName:"Dark (ANSI)",colors:{addBg:"green",delBg:"red",addHighlight:"greenBright",delHighlight:"redBright",text:"white",addLineNum:"greenBright",delLineNum:"redBright",contextLineNum:"gray",addSymbol:"greenBright",delSymbol:"redBright"}},k5={name:"light-ansi",displayName:"Light (ANSI)",colors:{addBg:"green",delBg:"red",addHighlight:"greenBright",delHighlight:"redBright",text:"black",addLineNum:"green",delLineNum:"red",contextLineNum:"gray",addSymbol:"green",delSymbol:"red"}},L$={dark:W5,light:v5,"dark-colorblind":H5,"light-colorblind":T5,"dark-ansi":A5,"light-ansi":k5},t=["dark","light","dark-colorblind","light-colorblind","dark-ansi","light-ansi"];function F$($){return L$[$]??L$.dark}function N5($){return!($.startsWith("index ")||$.startsWith("--- ")||$.startsWith("+++ ")||$.startsWith("similarity index"))}function Z0($){if($.type!=="header")return!0;return N5($.content)}function R$($,J,K=!0){if(J<=0)return[{text:$,isContinuation:!1}];if($.length<=J)return[{text:$,isContinuation:!1}];let X=[],Q=$,q=!0;while(Q.length>0){if(Q.length<=J){X.push({text:Q,isContinuation:!q});break}X.push({text:Q.slice(0,J),isContinuation:!q}),Q=Q.slice(J),q=!1}if(K)E5($,J,X);return X}function E5($,J,K){let X=K.map((Q)=>Q.text).join("");if(X!==$)throw Error(`[LineBreaking] Content was lost during breaking!
8
8
  Original (${$.length} chars): "${$.slice(0,50)}${$.length>50?"...":""}"
9
9
  Joined (${X.length} chars): "${X.slice(0,50)}${X.length>50?"...":""}"`);for(let Q=0;Q<K.length;Q++){let q=K[Q];if(q.text.length>J&&J>=1)throw Error(`[LineBreaking] Segment ${Q} exceeds maxWidth!
10
10
  Segment length: ${q.text.length}, maxWidth: ${J}
11
- Segment: "${q.text.slice(0,50)}${q.text.length>50?"...":""}"`)}if(K.length>0&&K[0].isContinuation)throw Error("[LineBreaking] First segment incorrectly marked as continuation!");for(let Q=1;Q<K.length;Q++)if(!K[Q].isContinuation)throw Error(`[LineBreaking] Segment ${Q} should be marked as continuation but isn't!`)}function I$($,J){if(J<=0)return 1;if($.length<=J)return 1;return Math.ceil($.length/J)}import K$ from"fast-diff";function _1($,J){if(!$||!J)return!1;let K=K$($,J),X=0,Q=0;for(let[Z,V]of K)if(Q+=V.length,Z===K$.EQUAL)X+=V.length;if(Q===0)return!1;return X/Q>=0.5}function D1($,J){let K=K$($,J),X=[],Q=[];for(let[q,Z]of K)if(q===K$.EQUAL)X.push({text:Z,type:"same"}),Q.push({text:Z,type:"same"});else if(q===K$.DELETE)X.push({text:Z,type:"changed"});else if(q===K$.INSERT)Q.push({text:Z,type:"changed"});return{oldSegments:X,newSegments:Q}}import{createEmphasize as L5}from"emphasize";import{common as F5}from"lowlight";var Y0=L5(F5),R5={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",html:"xml",htm:"xml",xml:"xml",svg:"xml",css:"css",scss:"scss",sass:"scss",less:"less",json:"json",yaml:"yaml",yml:"yaml",toml:"ini",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ps1:"powershell",bat:"dos",cmd:"dos",c:"c",h:"c",cpp:"cpp",hpp:"cpp",cc:"cpp",cxx:"cpp",rs:"rust",go:"go",zig:"zig",java:"java",kt:"kotlin",kts:"kotlin",scala:"scala",groovy:"groovy",gradle:"groovy",py:"python",rb:"ruby",pl:"perl",lua:"lua",php:"php",r:"r",hs:"haskell",ml:"ocaml",fs:"fsharp",fsx:"fsharp",ex:"elixir",exs:"elixir",erl:"erlang",clj:"clojure",cljs:"clojure",cs:"csharp",vb:"vbnet",md:"markdown",markdown:"markdown",rst:"plaintext",txt:"plaintext",Makefile:"makefile",Dockerfile:"dockerfile",cmake:"cmake",ini:"ini",conf:"ini",cfg:"ini",sql:"sql",vim:"vim",diff:"diff",patch:"diff"},v1={Makefile:"makefile",makefile:"makefile",GNUmakefile:"makefile",Dockerfile:"dockerfile",dockerfile:"dockerfile",Jenkinsfile:"groovy",Vagrantfile:"ruby",Gemfile:"ruby",Rakefile:"ruby",".gitignore":"plaintext",".gitattributes":"plaintext",".editorconfig":"ini",".prettierrc":"json",".eslintrc":"json","tsconfig.json":"json","package.json":"json","package-lock.json":"json","bun.lockb":"plaintext","yarn.lock":"yaml","pnpm-lock.yaml":"yaml","Cargo.toml":"ini","Cargo.lock":"ini","go.mod":"go","go.sum":"plaintext"},V0=null;function W1(){if(!V0)V0=new Set(Y0.listLanguages());return V0}function y$($){if(!$)return null;let J=$.split("/").pop()??"";if(v1[J]){let Q=v1[J];return W1().has(Q)?Q:null}let K=J.includes(".")?J.split(".").pop()?.toLowerCase():null;if(!K)return null;let X=R5[K];if(!X)return null;return W1().has(X)?X:null}function H1($,J){if(!$||!J)return $;try{return Y0.highlight(J,$).value}catch{return $}}function T1($,J){if(!J||$.length===0)return $;try{let K=$.join(`
11
+ Segment: "${q.text.slice(0,50)}${q.text.length>50?"...":""}"`)}if(K.length>0&&K[0].isContinuation)throw Error("[LineBreaking] First segment incorrectly marked as continuation!");for(let Q=1;Q<K.length;Q++)if(!K[Q].isContinuation)throw Error(`[LineBreaking] Segment ${Q} should be marked as continuation but isn't!`)}function I$($,J){if(J<=0)return 1;if($.length<=J)return 1;return Math.ceil($.length/J)}import X$ from"fast-diff";function _1($,J){if(!$||!J)return!1;let K=X$($,J),X=0,Q=0;for(let[Z,V]of K)if(Q+=V.length,Z===X$.EQUAL)X+=V.length;if(Q===0)return!1;return X/Q>=0.5}function D1($,J){let K=X$($,J),X=[],Q=[];for(let[q,Z]of K)if(q===X$.EQUAL)X.push({text:Z,type:"same"}),Q.push({text:Z,type:"same"});else if(q===X$.DELETE)X.push({text:Z,type:"changed"});else if(q===X$.INSERT)Q.push({text:Z,type:"changed"});return{oldSegments:X,newSegments:Q}}import{createEmphasize as L5}from"emphasize";import{common as F5}from"lowlight";var Y0=L5(F5),R5={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",html:"xml",htm:"xml",xml:"xml",svg:"xml",css:"css",scss:"scss",sass:"scss",less:"less",json:"json",yaml:"yaml",yml:"yaml",toml:"ini",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ps1:"powershell",bat:"dos",cmd:"dos",c:"c",h:"c",cpp:"cpp",hpp:"cpp",cc:"cpp",cxx:"cpp",rs:"rust",go:"go",zig:"zig",java:"java",kt:"kotlin",kts:"kotlin",scala:"scala",groovy:"groovy",gradle:"groovy",py:"python",rb:"ruby",pl:"perl",lua:"lua",php:"php",r:"r",hs:"haskell",ml:"ocaml",fs:"fsharp",fsx:"fsharp",ex:"elixir",exs:"elixir",erl:"erlang",clj:"clojure",cljs:"clojure",cs:"csharp",vb:"vbnet",md:"markdown",markdown:"markdown",rst:"plaintext",txt:"plaintext",Makefile:"makefile",Dockerfile:"dockerfile",cmake:"cmake",ini:"ini",conf:"ini",cfg:"ini",sql:"sql",vim:"vim",diff:"diff",patch:"diff"},W1={Makefile:"makefile",makefile:"makefile",GNUmakefile:"makefile",Dockerfile:"dockerfile",dockerfile:"dockerfile",Jenkinsfile:"groovy",Vagrantfile:"ruby",Gemfile:"ruby",Rakefile:"ruby",".gitignore":"plaintext",".gitattributes":"plaintext",".editorconfig":"ini",".prettierrc":"json",".eslintrc":"json","tsconfig.json":"json","package.json":"json","package-lock.json":"json","bun.lockb":"plaintext","yarn.lock":"yaml","pnpm-lock.yaml":"yaml","Cargo.toml":"ini","Cargo.lock":"ini","go.mod":"go","go.sum":"plaintext"},V0=null;function v1(){if(!V0)V0=new Set(Y0.listLanguages());return V0}function y$($){if(!$)return null;let J=$.split("/").pop()??"";if(W1[J]){let Q=W1[J];return v1().has(Q)?Q:null}let K=J.includes(".")?J.split(".").pop()?.toLowerCase():null;if(!K)return null;let X=R5[K];if(!X)return null;return v1().has(X)?X:null}function H1($,J){if(!$||!J)return $;try{return Y0.highlight(J,$).value}catch{return $}}function T1($,J){if(!J||$.length===0)return $;try{let K=$.join(`
12
12
  `);return Y0.highlight(J,K).value.replace(/\x1b\[0m/g,U1).split(`
13
13
  `)}catch{return $}}function A1($){if($.type==="addition"||$.type==="deletion")return $.content.slice(1);if($.type==="context"&&$.content.startsWith(" "))return $.content.slice(1);return $.content}function m($){return A1($).replace(/[\x00-\x08\x0a-\x1f\x7f]/g,"").replace(/\t/g," ")}function k1($){switch($.type){case"header":return{type:"diff-header",content:$.content};case"hunk":return{type:"diff-hunk",content:$.content};case"addition":return{type:"diff-add",lineNum:$.newLineNum,content:m($)};case"deletion":return{type:"diff-del",lineNum:$.oldLineNum,content:m($)};case"context":return{type:"diff-context",lineNum:$.oldLineNum??$.newLineNum,content:m($)}}}function I5($){let J=$.match(/^diff --git a\/.+ b\/(.+)$/);return J?J[1]:null}function y5($){return $.type==="diff-add"||$.type==="diff-del"||$.type==="diff-context"}function C5($,J){let K=new Map,X=new Map,Q=Math.min($.length,J.length);for(let q=0;q<Q;q++){let Z=m($[q]),V=m(J[q]);if(_1(Z,V)){let{oldSegments:Y,newSegments:z}=D1(Z,V);K.set(q,Y),X.set(q,z)}}return{delSegmentsMap:K,addSegmentsMap:X}}function P5($){let J=[],K=[],X=null,Q=0;while(Q<$.length){let q=$[Q];if(q.type==="header"){let U=I5(q.content);if(U){if(X)K.push(X),J.push({type:"spacer"});X={language:y$(U),startRowIndex:J.length,oldContent:[],oldRowIndices:[],newContent:[],newRowIndices:[]}}J.push(k1(q)),Q++;continue}if(q.type==="hunk"){J.push(k1(q)),Q++;continue}if(q.type==="context"){let U=m(q),j=J.length;if(J.push({type:"diff-context",lineNum:q.oldLineNum??q.newLineNum,content:U}),X&&X.language)X.oldContent.push(U),X.oldRowIndices.push(j),X.newContent.push(U),X.newRowIndices.push(j);Q++;continue}let Z=[];while(Q<$.length&&$[Q].type==="deletion")Z.push($[Q]),Q++;let V=[];while(Q<$.length&&$[Q].type==="addition")V.push($[Q]),Q++;let{delSegmentsMap:Y,addSegmentsMap:z}=C5(Z,V);for(let U=0;U<Z.length;U++){let j=Z[U],B=m(j),G=Y.get(U),M=J.length;if(J.push({type:"diff-del",lineNum:j.oldLineNum,content:B,...G&&{wordDiffSegments:G}}),X&&X.language&&!G)X.oldContent.push(B),X.oldRowIndices.push(M)}for(let U=0;U<V.length;U++){let j=V[U],B=m(j),G=z.get(U),M=J.length;if(J.push({type:"diff-add",lineNum:j.newLineNum,content:B,...G&&{wordDiffSegments:G}}),X&&X.language&&!G)X.newContent.push(B),X.newRowIndices.push(M)}}if(X)K.push(X);return{rows:J,fileSections:K}}function N1($,J,K,X,Q){if(J.length===0)return;let q=T1(J,X);for(let Z=0;Z<K.length;Z++){let V=K[Z],Y=$[V],z=q[Z];if(z&&y5(Y)&&Q.has(Y.type)&&z!==Y.content)Y.highlighted=z}}var b5=new Set(["diff-del","diff-context"]),S5=new Set(["diff-add","diff-context"]);function w5($,J){for(let K of J){if(!K.language)continue;N1($,K.oldContent,K.oldRowIndices,K.language,b5),N1($,K.newContent,K.newRowIndices,K.language,S5)}}function C$($){if(!$)return[];let J=$.lines.filter(Z0),{rows:K,fileSections:X}=P5(J);return w5(K,X),K}function L1($,J){let K=[];if($){K.push({type:"commit-header",content:`commit ${$.hash}`}),K.push({type:"commit-header",content:`Author: ${$.author}`}),K.push({type:"commit-header",content:`Date: ${K1($.date)}`}),K.push({type:"spacer"});for(let X of $.message.split(`
14
- `))K.push({type:"commit-message",content:` ${X}`});K.push({type:"spacer"})}return K.push(...C$(J)),K}function P$($){let J=0;for(let K of $)if("lineNum"in K&&K.lineNum!==void 0)J=Math.max(J,K.lineNum);return Math.max(3,String(J).length)}function b$($,J,K){if(!K)return $;let Q=Math.max(10,J),q=[];for(let Z of $)if(Z.type==="diff-add"||Z.type==="diff-del"||Z.type==="diff-context"){let V=Z.content;if(!V||V.length<=Q){q.push(Z);continue}let Y=R$(V,Q);for(let z=0;z<Y.length;z++){let U=Y[z];q.push({...Z,content:U.text,lineNum:U.isContinuation?void 0:Z.lineNum,isContinuation:U.isContinuation})}}else q.push(Z);return q}function z0($){let J=[],K=-1;for(let X=0;X<$.length;X++){let Q=$[X].type;if(Q==="diff-hunk"){if(K!==-1)J.push({startRow:K,endRow:X});K=X}else if(Q==="diff-header"||Q==="spacer"){if(K!==-1)J.push({startRow:K,endRow:X}),K=-1}}if(K!==-1)J.push({startRow:K,endRow:$.length});return J}function x5($,J){let K=$.match(/@@ -(\d+)(?:,\d+)? \+(\d+)/);if(!K)return 0;return J==="staged"?parseInt(K[2],10):parseInt(K[1],10)}function E1($,J){if(!$||$.lines.length===0)return{fileHeaders:[],hunks:[]};let K=[],X=[],Q=null,q=0;for(let Z of $.lines)if(Z.type==="header"){if(Q)X.push(Q),Q=null;K.push(Z)}else if(Z.type==="hunk"){if(Q)X.push(Q);Q={headerLine:Z,bodyLines:[],sortKey:x5(Z.content,J),source:J,hunkIndex:q++}}else if(Q)Q.bodyLines.push(Z);if(Q)X.push(Q);return{fileHeaders:K,hunks:X}}function F1($,J){let K=E1($,"unstaged"),X=E1(J,"staged"),Q=[...K.hunks,...X.hunks];Q.sort((z,U)=>z.sortKey-U.sortKey);let Z=[...K.fileHeaders.length>0?K.fileHeaders:X.fileHeaders],V=[];for(let z of Q)Z.push(z.headerLine,...z.bodyLines),V.push({source:z.source,hunkIndex:z.hunkIndex});return{rows:C$({raw:"",lines:Z}),hunkMapping:V}}function S$($,J,K="…"){if(J<=0)return K;if(!$.includes("\x1B")&&$.length<=J)return $;if(!$.includes("\x1B")){if($.length<=J)return $;return $.slice(0,J-K.length)+K}let X=[],Q=0;K0.lastIndex=0;let q;while((q=K0.exec($))!==null){if(q.index>Q)X.push({type:"text",content:$.slice(Q,q.index)});X.push({type:"ansi",content:q[0]}),Q=q.index+q[0].length}if(Q<$.length)X.push({type:"text",content:$.slice(Q)});let Z="",V=0,Y=J-K.length,z=!1,U=!1;for(let j of X)if(j.type==="ansi")Z+=j.content,z=!0;else{let B=Y-V;if(B<=0){U=!0;break}if(j.content.length<=B)Z+=j.content,V+=j.content.length;else{Z+=j.content.slice(0,B),U=!0;break}}if(U){if(z)Z+=v;Z+=K}return Z}function f($,J){if(J<=0||$.length<=J)return $;if(J<=1)return"…";return $.slice(0,J-1)+"…"}function I1($,J){if($===void 0)return" ".repeat(J);return String($).padStart(J," ")}function p5($){return $.replace(/\{/g,"{{").replace(/\}/g,"}}")}function g5($,J){if($.startsWith("diff --git")){let K=$.match(/diff --git a\/.+ b\/(.+)$/);if(K){let X=J-6,Q=f(K[1],X);return`{escape}${u}${R}── ${Q} ──${v}{/escape}`}}return`{escape}${F}${f($,J)}${v}{/escape}`}function u5($,J){let K=$.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/);if(K){let X=parseInt(K[1],10),Q=K[2]?parseInt(K[2],10):1,q=parseInt(K[3],10),Z=K[4]?parseInt(K[4],10):1,V=K[5].trim(),Y=X+Q-1,z=q+Z-1,U=Q===1?`${X}`:`${X}-${Y}`,j=Z===1?`${q}`:`${q}-${z}`,B=`Lines ${U} → ${j}`,G=J-B.length-1,M=V&&G>3?" "+f(V,G):"";return`{escape}${R}${B}${F}${M}${v}{/escape}`}return`{escape}${R}${f($,J)}${v}{/escape}`}function y1($,J,K){let X=K?$:f($,J);return{display:X,visibleLength:X.length}}function U0($,J,K,X,Q,q){let Z=" ".repeat(Math.max(0,X-$.length-K));return`{escape}${Q}${q}${$}${J}${Z}${v}{/escape}`}function m5($,J,K,X,Q,q){let{display:Z}=y1(J,K,Q),V=`${$}${Z}`.padEnd(X," "),Y=q==="add"?"green":"red";return`{${Y}-bg}{white-fg}${p5(V)}{/white-fg}{/${Y}-bg}`}function f5($,J,K){let X="";for(let Q of $)X+=Q.type==="changed"?`${J}${Q.text}${K}`:Q.text;return X}function R1($,J,K,X,Q,q,Z){let V=Z==="add"?"+":"-",Y=$.isContinuation?"»":V,U=`${I1($.lineNum,J)} ${Y} `,j=$.content||"";if(Q.name.includes("ansi"))return m5(U,j,K,X,q,Z);let{colors:B}=Q,G=X0(Z==="add"?B.addBg:B.delBg),M=B1("#ffffff"),{display:H,visibleLength:D}=y1(j,K,q),T=!$.isContinuation&&(q||j.length<=K);if($.wordDiffSegments&&T){let W=X0(Z==="add"?B.addHighlight:B.delHighlight),E=f5($.wordDiffSegments,W,G);return U0(U,E,j.length,X,G,M)}if($.highlighted&&T)return U0(U,$.highlighted,j.length,X,G,M);return U0(U,H,D,X,G,M)}function B0($,J,K,X,Q,q){switch($.type){case"diff-header":return g5($.content,X);case"diff-hunk":return u5($.content,X);case"diff-add":return R1($,J,K,X,Q,q,"add");case"diff-del":return R1($,J,K,X,Q,q,"del");case"diff-context":{let Z=$.isContinuation,V=Z?"»":" ",z=`${I1($.lineNum,J)} ${V} `,U=$.content||"",j=`${F}${z}${v}`;if($.highlighted&&!Z){let G=q?$.highlighted:S$($.highlighted,K);return`{escape}${j}${G}${v}{/escape}`}let B=q?U:f(U,K);return`{escape}${j}${B}${v}{/escape}`}case"commit-header":return`{escape}${b}${f($.content,X)}${v}{/escape}`;case"commit-message":return`{escape}${f($.content,X)}${v}{/escape}`;case"spacer":return""}}function G0($,J,K=0,X,Q="dark",q=!1,Z,V){let Y=Z!==void 0&&Z>=0,z=C$($);if(z.length===0)return{content:"{gray-fg}No diff to display{/gray-fg}",totalRows:0,hunkCount:0,hunkBoundaries:[]};let U=F$(Q),j=P$(z),B=Y?1:0,G=J-j-5-B,M=J-2,H=b$(z,G,q),D=H.length,T=z0(H),W=T.length,E=Math.min(Z??0,W-1),O=Y&&W>0?T[E]:null,_=K;return{content:(X?H.slice(_,_+X):H.slice(_)).map((k,L)=>{let o=_+L,S=B0(k,j,G,M,U,q);if(!Y)return S;let s=O&&o>=O.startRow&&o<O.endRow,V$=s?`{escape}${V?x:R}▌${v}{/escape}`:" ";if(s&&k.type==="diff-hunk")return V$+S.replace("{escape}",`{escape}${w}`);return V$+S}).join(`
15
- `),totalRows:D,hunkCount:W,hunkBoundaries:T}}function C1($,J,K,X=0,Q,q="dark",Z=!1){let V=L1($,J);if(V.length===0)return{content:"{gray-fg}No commit selected{/gray-fg}",totalRows:0,hunkCount:0,hunkBoundaries:[]};let Y=F$(q),z=P$(V),U=K-z-5,j=K-2,B=b$(V,U,Z),G=B.length;return{content:(Q?B.slice(X,X+Q):B.slice(X)).map((D)=>B0(D,z,U,j,Y,Z)).join(`
16
- `),totalRows:G,hunkCount:0,hunkBoundaries:[]}}function P1($,J,K,X=0,Q,q="dark",Z=!1,V){let{rows:Y,hunkMapping:z}=F1($,J);if(Y.length===0)return{content:"{gray-fg}No diff to display{/gray-fg}",totalRows:0,hunkCount:0,hunkBoundaries:[],hunkMapping:[]};let U=V!==void 0&&V>=0,j=F$(q),B=P$(Y),G=U?1:0,M=K-B-5-G,H=K-2,D=b$(Y,M,Z),T=D.length,W=z0(D),E=W.length,O=Math.min(V??0,E-1),_=new Map;if(U)for(let L=0;L<W.length;L++){let o=W[L];for(let S=o.startRow;S<o.endRow;S++)_.set(S,L)}let A=X;return{content:(Q?D.slice(A,A+Q):D.slice(A)).map((L,o)=>{let S=A+o,s=B0(L,B,M,H,j,Z);if(!U)return s;let O$=_.get(S);if(O$===void 0)return" "+s;let V$=O$===O,t8=z[O$]?.source==="staged"?x:R,o0=`{escape}${V$?u:""}${t8}▌${v}{/escape}`;if(V$&&L.type==="diff-hunk")return o0+s.replace("{escape}",`{escape}${w}`);return o0+s}).join(`
17
- `),totalRows:T,hunkCount:E,hunkBoundaries:W,hunkMapping:z}}function b1($){let{state:J,stagedCount:K,width:X,focusedZone:Q}=$,q=[],Z="{bold}Commit Message{/bold}";if(J.amend)Z+=" {yellow-fg}(amending){/yellow-fg}";q.push(Z),q.push("");let Y=J.inputFocused||Q==="commitMessage"?"cyan":"gray",z=Math.max(20,X-6);q.push(`{${Y}-fg}┌${"─".repeat(z+2)}┐{/${Y}-fg}`);let U=J.message||(J.inputFocused?"":"Press i or Enter to edit..."),j=J.message?"":"{gray-fg}",B=J.message?"":"{/gray-fg}",G=U.length>z?U.slice(0,z-1)+"…":U.padEnd(z);q.push(`{${Y}-fg}│{/${Y}-fg} ${j}${G}${B} {${Y}-fg}│{/${Y}-fg}`),q.push(`{${Y}-fg}└${"─".repeat(z+2)}┘{/${Y}-fg}`),q.push("");let M=Q==="commitAmend",H=J.amend?"[x]":"[ ]",D="gray";if(M)D="cyan";else if(J.amend)D="green";let T=M?"{cyan-fg}▸ {/cyan-fg}":" ";if(q.push(`${T}{${D}-fg}${H}{/${D}-fg} Amend {gray-fg}(a){/gray-fg}`),J.error)q.push(""),q.push(`{red-fg}${J.error}{/red-fg}`);if(J.isCommitting)q.push(""),q.push("{yellow-fg}Committing...{/yellow-fg}");q.push("");let W;if(J.inputFocused)W="Enter: commit | Ctrl+a: amend | Esc: unfocus";else if(Q==="commitMessage")W="Tab: next | Space: edit | a: amend";else if(Q==="commitAmend")W="Tab: next | Space: toggle | Esc: back";else W="i/Enter: edit | a: amend | Esc: back";return q.push(`{gray-fg}Staged: ${K} file(s) | ${W}{/gray-fg}`),q}function S1($){return b1($).length}function w1($,J,K,X=0,Q,q){let Z=b1({state:$,stagedCount:J,width:K,focusedZone:q});if(Q&&Z.length>Q)return Z.slice(X,X+Q).join(`
14
+ `))K.push({type:"commit-message",content:` ${X}`});K.push({type:"spacer"})}return K.push(...C$(J)),K}function P$($){let J=0;for(let K of $)if("lineNum"in K&&K.lineNum!==void 0)J=Math.max(J,K.lineNum);return Math.max(3,String(J).length)}function b$($,J,K){if(!K)return $;let Q=Math.max(10,J),q=[];for(let Z of $)if(Z.type==="diff-add"||Z.type==="diff-del"||Z.type==="diff-context"){let V=Z.content;if(!V||V.length<=Q){q.push(Z);continue}let Y=R$(V,Q);for(let z=0;z<Y.length;z++){let U=Y[z];q.push({...Z,content:U.text,lineNum:U.isContinuation?void 0:Z.lineNum,isContinuation:U.isContinuation})}}else q.push(Z);return q}function z0($){let J=[],K=-1;for(let X=0;X<$.length;X++){let Q=$[X].type;if(Q==="diff-hunk"){if(K!==-1)J.push({startRow:K,endRow:X});K=X}else if(Q==="diff-header"||Q==="spacer"){if(K!==-1)J.push({startRow:K,endRow:X}),K=-1}}if(K!==-1)J.push({startRow:K,endRow:$.length});return J}function x5($,J){let K=$.match(/@@ -(\d+)(?:,\d+)? \+(\d+)/);if(!K)return 0;return J==="staged"?parseInt(K[2],10):parseInt(K[1],10)}function E1($,J){if(!$||$.lines.length===0)return{fileHeaders:[],hunks:[]};let K=[],X=[],Q=null,q=0;for(let Z of $.lines)if(Z.type==="header"){if(Q)X.push(Q),Q=null;K.push(Z)}else if(Z.type==="hunk"){if(Q)X.push(Q);Q={headerLine:Z,bodyLines:[],sortKey:x5(Z.content,J),source:J,hunkIndex:q++}}else if(Q)Q.bodyLines.push(Z);if(Q)X.push(Q);return{fileHeaders:K,hunks:X}}function F1($,J){let K=E1($,"unstaged"),X=E1(J,"staged"),Q=[...K.hunks,...X.hunks];Q.sort((z,U)=>z.sortKey-U.sortKey);let Z=[...K.fileHeaders.length>0?K.fileHeaders:X.fileHeaders],V=[];for(let z of Q)Z.push(z.headerLine,...z.bodyLines),V.push({source:z.source,hunkIndex:z.hunkIndex});return{rows:C$({raw:"",lines:Z}),hunkMapping:V}}function S$($,J,K="…"){if(J<=0)return K;if(!$.includes("\x1B")&&$.length<=J)return $;if(!$.includes("\x1B")){if($.length<=J)return $;return $.slice(0,J-K.length)+K}let X=[],Q=0;K0.lastIndex=0;let q;while((q=K0.exec($))!==null){if(q.index>Q)X.push({type:"text",content:$.slice(Q,q.index)});X.push({type:"ansi",content:q[0]}),Q=q.index+q[0].length}if(Q<$.length)X.push({type:"text",content:$.slice(Q)});let Z="",V=0,Y=J-K.length,z=!1,U=!1;for(let j of X)if(j.type==="ansi")Z+=j.content,z=!0;else{let B=Y-V;if(B<=0){U=!0;break}if(j.content.length<=B)Z+=j.content,V+=j.content.length;else{Z+=j.content.slice(0,B),U=!0;break}}if(U){if(z)Z+=W;Z+=K}return Z}function f($,J){if(J<=0||$.length<=J)return $;if(J<=1)return"…";return $.slice(0,J-1)+"…"}function I1($,J){if($===void 0)return" ".repeat(J);return String($).padStart(J," ")}function p5($){return $.replace(/\{/g,"{{").replace(/\}/g,"}}")}function g5($,J){if($.startsWith("diff --git")){let K=$.match(/diff --git a\/.+ b\/(.+)$/);if(K){let X=J-6,Q=f(K[1],X);return`{escape}${u}${R}── ${Q} ──${W}{/escape}`}}return`{escape}${F}${f($,J)}${W}{/escape}`}function u5($,J){let K=$.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/);if(K){let X=parseInt(K[1],10),Q=K[2]?parseInt(K[2],10):1,q=parseInt(K[3],10),Z=K[4]?parseInt(K[4],10):1,V=K[5].trim(),Y=X+Q-1,z=q+Z-1,U=Q===1?`${X}`:`${X}-${Y}`,j=Z===1?`${q}`:`${q}-${z}`,B=`Lines ${U} → ${j}`,G=J-B.length-1,M=V&&G>3?" "+f(V,G):"";return`{escape}${R}${B}${F}${M}${W}{/escape}`}return`{escape}${R}${f($,J)}${W}{/escape}`}function y1($,J,K){let X=K?$:f($,J);return{display:X,visibleLength:X.length}}function U0($,J,K,X,Q,q){let Z=" ".repeat(Math.max(0,X-$.length-K));return`{escape}${Q}${q}${$}${J}${Z}${W}{/escape}`}function m5($,J,K,X,Q,q){let{display:Z}=y1(J,K,Q),V=`${$}${Z}`.padEnd(X," "),Y=q==="add"?"green":"red";return`{${Y}-bg}{white-fg}${p5(V)}{/white-fg}{/${Y}-bg}`}function f5($,J,K){let X="";for(let Q of $)X+=Q.type==="changed"?`${J}${Q.text}${K}`:Q.text;return X}function R1($,J,K,X,Q,q,Z){let V=Z==="add"?"+":"-",Y=$.isContinuation?"»":V,U=`${I1($.lineNum,J)} ${Y} `,j=$.content||"";if(Q.name.includes("ansi"))return m5(U,j,K,X,q,Z);let{colors:B}=Q,G=X0(Z==="add"?B.addBg:B.delBg),M=B1("#ffffff"),{display:v,visibleLength:D}=y1(j,K,q),T=!$.isContinuation&&(q||j.length<=K);if($.wordDiffSegments&&T){let H=X0(Z==="add"?B.addHighlight:B.delHighlight),E=f5($.wordDiffSegments,H,G);return U0(U,E,j.length,X,G,M)}if($.highlighted&&T)return U0(U,$.highlighted,j.length,X,G,M);return U0(U,v,D,X,G,M)}function B0($,J,K,X,Q,q){switch($.type){case"diff-header":return g5($.content,X);case"diff-hunk":return u5($.content,X);case"diff-add":return R1($,J,K,X,Q,q,"add");case"diff-del":return R1($,J,K,X,Q,q,"del");case"diff-context":{let Z=$.isContinuation,V=Z?"»":" ",z=`${I1($.lineNum,J)} ${V} `,U=$.content||"",j=`${F}${z}${W}`;if($.highlighted&&!Z){let G=q?$.highlighted:S$($.highlighted,K);return`{escape}${j}${G}${W}{/escape}`}let B=q?U:f(U,K);return`{escape}${j}${B}${W}{/escape}`}case"commit-header":return`{escape}${b}${f($.content,X)}${W}{/escape}`;case"commit-message":return`{escape}${f($.content,X)}${W}{/escape}`;case"spacer":return""}}function G0($,J,K=0,X,Q="dark",q=!1,Z,V){let Y=Z!==void 0&&Z>=0,z=C$($);if(z.length===0)return{content:"{gray-fg}No diff to display{/gray-fg}",totalRows:0,hunkCount:0,hunkBoundaries:[]};let U=F$(Q),j=P$(z),B=Y?1:0,G=J-j-5-B,M=J-2,v=b$(z,G,q),D=v.length,T=z0(v),H=T.length,E=Math.min(Z??0,H-1),O=Y&&H>0?T[E]:null,_=K;return{content:(X?v.slice(_,_+X):v.slice(_)).map((k,L)=>{let s=_+L,S=B0(k,j,G,M,U,q);if(!Y)return S;let a=O&&s>=O.startRow&&s<O.endRow,V$=a?`{escape}${V?x:R}▌${W}{/escape}`:" ";if(a&&k.type==="diff-hunk")return V$+S.replace("{escape}",`{escape}${w}`);return V$+S}).join(`
15
+ `),totalRows:D,hunkCount:H,hunkBoundaries:T}}function C1($,J,K,X=0,Q,q="dark",Z=!1){let V=L1($,J);if(V.length===0)return{content:"{gray-fg}No commit selected{/gray-fg}",totalRows:0,hunkCount:0,hunkBoundaries:[]};let Y=F$(q),z=P$(V),U=K-z-5,j=K-2,B=b$(V,U,Z),G=B.length;return{content:(Q?B.slice(X,X+Q):B.slice(X)).map((D)=>B0(D,z,U,j,Y,Z)).join(`
16
+ `),totalRows:G,hunkCount:0,hunkBoundaries:[]}}function P1($,J,K,X=0,Q,q="dark",Z=!1,V){let{rows:Y,hunkMapping:z}=F1($,J);if(Y.length===0)return{content:"{gray-fg}No diff to display{/gray-fg}",totalRows:0,hunkCount:0,hunkBoundaries:[],hunkMapping:[]};let U=V!==void 0&&V>=0,j=F$(q),B=P$(Y),G=U?1:0,M=K-B-5-G,v=K-2,D=b$(Y,M,Z),T=D.length,H=z0(D),E=H.length,O=Math.min(V??0,E-1),_=new Map;if(U)for(let L=0;L<H.length;L++){let s=H[L];for(let S=s.startRow;S<s.endRow;S++)_.set(S,L)}let A=X;return{content:(Q?D.slice(A,A+Q):D.slice(A)).map((L,s)=>{let S=A+s,a=B0(L,B,M,v,j,Z);if(!U)return a;let O$=_.get(S);if(O$===void 0)return" "+a;let V$=O$===O,t8=z[O$]?.source==="staged"?x:R,o0=`{escape}${V$?u:""}${t8}▌${W}{/escape}`;if(V$&&L.type==="diff-hunk")return o0+a.replace("{escape}",`{escape}${w}`);return o0+a}).join(`
17
+ `),totalRows:T,hunkCount:E,hunkBoundaries:H,hunkMapping:z}}function b1($){let{state:J,stagedCount:K,width:X,focusedZone:Q}=$,q=[],Z="{bold}Commit Message{/bold}";if(J.amend)Z+=" {yellow-fg}(amending){/yellow-fg}";q.push(Z),q.push("");let Y=J.inputFocused||Q==="commitMessage"?"cyan":"gray",z=Math.max(20,X-6);q.push(`{${Y}-fg}┌${"─".repeat(z+2)}┐{/${Y}-fg}`);let U=J.message||(J.inputFocused?"":"Press i or Enter to edit..."),j=J.message?"":"{gray-fg}",B=J.message?"":"{/gray-fg}",G=U.length>z?U.slice(0,z-1)+"…":U.padEnd(z);q.push(`{${Y}-fg}│{/${Y}-fg} ${j}${G}${B} {${Y}-fg}│{/${Y}-fg}`),q.push(`{${Y}-fg}└${"─".repeat(z+2)}┘{/${Y}-fg}`),q.push("");let M=Q==="commitAmend",v=J.amend?"[x]":"[ ]",D="gray";if(M)D="cyan";else if(J.amend)D="green";let T=M?"{cyan-fg}▸ {/cyan-fg}":" ";if(q.push(`${T}{${D}-fg}${v}{/${D}-fg} Amend {gray-fg}(a){/gray-fg}`),J.error)q.push(""),q.push(`{red-fg}${J.error}{/red-fg}`);if(J.isCommitting)q.push(""),q.push("{yellow-fg}Committing...{/yellow-fg}");q.push("");let H;if(J.inputFocused)H="Enter: commit | Ctrl+a: amend | Esc: unfocus";else if(Q==="commitMessage")H="Tab: next | Space: edit | a: amend";else if(Q==="commitAmend")H="Tab: next | Space: toggle | Esc: back";else H="i/Enter: edit | a: amend | Esc: back";return q.push(`{gray-fg}Staged: ${K} file(s) | ${H}{/gray-fg}`),q}function S1($){return b1($).length}function w1($,J,K,X=0,Q,q){let Z=b1({state:$,stagedCount:J,width:K,focusedZone:q});if(Q&&Z.length>Q)return Z.slice(X,X+Q).join(`
18
18
  `);return Z.join(`
19
19
  `)}function j0($,J,K){if(!$)return[];let X=$.split(`
20
- `),Q=[],q=J?y$(J):null;for(let Z=0;Z<X.length;Z++){let V=X[Z],Y=q?H1(V,q):void 0;Q.push({type:"code",lineNum:Z+1,content:V,highlighted:Y})}if(K)Q.push({type:"truncation",content:"(file truncated)"});return Q}function x1($,J,K){if(!K)return $;let Q=Math.max(10,J),q=[];for(let Z of $)if(Z.type==="code"){let V=Z.content;if(!V||V.length<=Q){q.push(Z);continue}let Y=R$(V,Q);for(let z=0;z<Y.length;z++){let U=Y[z];q.push({type:"code",lineNum:U.isContinuation?0:Z.lineNum,content:U.text,highlighted:void 0,isContinuation:U.isContinuation})}}else q.push(Z);return q}function p1($,J,K){if(!K)return $.length;let Q=Math.max(10,J),q=0;for(let Z of $)if(Z.type==="code"){let V=Z.content;if(!V||V.length<=Q)q+=1;else q+=I$(V,Q)}else q+=1;return q}function M0($){let J=0;for(let K of $)if(K.type==="code"&&K.lineNum>J)J=K.lineNum;return Math.max(3,String(J).length)}function g1($,J,K,X=0,Q,q=!1,Z=!1){if(!$)return"{gray-fg}Select a file to view its contents{/gray-fg}";if(!J)return"{gray-fg}Loading...{/gray-fg}";let V=j0(J,$,q);if(V.length===0)return"{gray-fg}(empty file){/gray-fg}";let Y=M0(V),z=K-Y-2,U=x1(V,z,Z),j=Q?U.slice(X,X+Q):U.slice(X),B=[];for(let G of j){if(G.type==="truncation"){B.push(`{escape}${b}${G.content}${v}{/escape}`);continue}let M=G.isContinuation??!1,H;if(M)H=">>".padStart(Y," ");else H=String(G.lineNum).padStart(Y," ");let D=G.content,T=!Z&&D.length>z,W=G.highlighted&&!M,E;if(W&&G.highlighted)E=T?S$(G.highlighted,z):G.highlighted;else{let A=D;if(T)A=A.slice(0,Math.max(0,z-1))+"...";E=A}let _=`{escape}${M?R:F}${H}${v} ${E||" "}{/escape}`;B.push(_)}return B.join(`
21
- `)}function u1($,J,K,X,Q){if(!$)return 0;let q=j0($,J,K),Z=M0(q),V=X-Z-2;return p1(q,V,Q)}function m1($,J,K,X,Q,q,Z,V,Y,z){if($.bottomTab==="history")return X1(K,$.historySelectedIndex,$.currentPane==="history",Z,$.historyScrollOffset,V);if($.bottomTab==="compare"){let U=X?.commits??[],j=X?.files??[];return G1(U,j,Q,$.currentPane==="compare",Z,$.compareScrollOffset,V)}if($.bottomTab==="explorer"){let U=q?.displayRows??[];return M1(U,$.explorerSelectedIndex,$.currentPane==="explorer",Z,$.explorerScrollOffset,V,q?.isLoading??!1,q?.error??null)}if($.flatViewMode&&z)return $1(z,$.selectedIndex,$.currentPane==="files",Z,$.fileListScrollOffset,V);return n0(J,$.selectedIndex,$.currentPane==="files",Z,$.fileListScrollOffset,V,Y)}function f1($,J,K,X,Q,q,Z,V,Y,z,U,j,B,G){if($.bottomTab==="commit"){let E=S1({state:q,stagedCount:Z,width:Y,focusedZone:G});return{content:w1(q,Z,Y,$.diffScrollOffset,z,G),totalRows:E,hunkCount:0,hunkBoundaries:[]}}if($.bottomTab==="history"){let W=K?.selectedCommit??null,E=K?.commitDiff??null,{content:O,totalRows:_}=C1(W,E,Y,$.diffScrollOffset,z,V,$.wrapMode);return{content:O,totalRows:_,hunkCount:0,hunkBoundaries:[]}}if($.bottomTab==="compare"){let W=X?.diff??null;if(W){let{content:E,totalRows:O}=G0(W,Y,$.diffScrollOffset,z,V,$.wrapMode);return{content:E,totalRows:O,hunkCount:0,hunkBoundaries:[]}}return{content:"{gray-fg}Select a commit or file to view diff{/gray-fg}",totalRows:0,hunkCount:0,hunkBoundaries:[]}}if($.bottomTab==="explorer")return{content:g1(Q?.path??null,Q?.content??null,Y,$.explorerFileScrollOffset,z,Q?.truncated??!1,$.wrapMode),totalRows:0,hunkCount:0,hunkBoundaries:[]};if($.flatViewMode&&B){let W=P1(B.unstaged,B.staged,Y,$.diffScrollOffset,z,V,$.wrapMode,U);return{content:W.content,totalRows:W.totalRows,hunkCount:W.hunkCount,hunkBoundaries:W.hunkBoundaries,hunkMapping:W.hunkMapping}}let{content:M,totalRows:H,hunkCount:D,hunkBoundaries:T}=G0(J,Y,$.diffScrollOffset,z,V,$.wrapMode,U,j);return{content:M,totalRows:H,hunkCount:D,hunkBoundaries:T}}import{EventEmitter as h5}from"node:events";class O0{items;index;constructor($,J=0){this.items=$,this.index=Math.min(J,Math.max(0,$.length-1))}current(){return this.items[this.index]}next(){return this.index=(this.index+1)%this.items.length,this.items[this.index]}prev(){return this.index=(this.index-1+this.items.length)%this.items.length,this.items[this.index]}setCurrent($){let J=this.items.indexOf($);if(J===-1)return!1;return this.index=J,!0}setItems($,J){if(this.items=$,J!==void 0){let K=$.indexOf(J);this.index=K!==-1?K:0}else this.index=Math.min(this.index,Math.max(0,$.length-1))}}var w$={fileList:"files",diffView:"diff",commitMessage:"commit",commitAmend:"commit",historyList:"history",historyDiff:"diff",compareList:"compare",compareDiff:"diff",explorerTree:"explorer",explorerContent:"diff"},X$={diff:["fileList","diffView"],commit:["fileList","commitMessage","commitAmend"],history:["historyList","historyDiff"],compare:["compareList","compareDiff"],explorer:["explorerTree","explorerContent"]},h1={diff:"fileList",commit:"commitMessage",history:"historyList",compare:"compareList",explorer:"explorerTree"},c5={focusedZone:"fileList",currentPane:"files",bottomTab:"diff",selectedIndex:0,fileListScrollOffset:0,diffScrollOffset:0,historyScrollOffset:0,compareScrollOffset:0,explorerScrollOffset:0,explorerFileScrollOffset:0,historySelectedIndex:0,compareSelectedIndex:0,includeUncommitted:!1,explorerSelectedIndex:0,selectedHunkIndex:0,wrapMode:!1,autoTabEnabled:!1,mouseEnabled:!0,hideHiddenFiles:!0,hideGitignored:!0,flatViewMode:!1,splitRatio:0.4,commitInputFocused:!1};class _0 extends h5{_state;focusRing;constructor($={}){super();this._state={...c5,...$};let J=this._state.bottomTab,K=X$[J];if(this.focusRing=new O0(K),this._state.focusedZone)this.focusRing.setCurrent(this._state.focusedZone);this._state.currentPane=w$[this._state.focusedZone]}get state(){return this._state}update($){this._state={...this._state,...$},this._state.currentPane=w$[this._state.focusedZone],this.emit("change",this._state)}setPane($){let K=X$[this._state.bottomTab].find((X)=>w$[X]===$);if(K)this.setFocusedZone(K)}setFocusedZone($){if(this._state.focusedZone!==$){this.focusRing.setCurrent($);let J=this._state.currentPane;if(this.update({focusedZone:$}),this._state.currentPane!==J)this.emit("pane-change",this._state.currentPane)}}setTab($){if(this._state.bottomTab!==$){let J=h1[$];this.focusRing.setItems(X$[$],J),this.update({bottomTab:$,focusedZone:J}),this.emit("tab-change",$)}}setSelectedIndex($){if(this._state.selectedIndex!==$)this.update({selectedIndex:$}),this.emit("selection-change",$)}setFileListScrollOffset($){this.update({fileListScrollOffset:Math.max(0,$)}),this.emit("scroll-change",{type:"fileList",offset:$})}setDiffScrollOffset($){this.update({diffScrollOffset:Math.max(0,$)}),this.emit("scroll-change",{type:"diff",offset:$})}setHistoryScrollOffset($){this.update({historyScrollOffset:Math.max(0,$)}),this.emit("scroll-change",{type:"history",offset:$})}setCompareScrollOffset($){this.update({compareScrollOffset:Math.max(0,$)}),this.emit("scroll-change",{type:"compare",offset:$})}setExplorerScrollOffset($){this.update({explorerScrollOffset:Math.max(0,$)}),this.emit("scroll-change",{type:"explorer",offset:$})}setExplorerFileScrollOffset($){this.update({explorerFileScrollOffset:Math.max(0,$)}),this.emit("scroll-change",{type:"explorerFile",offset:$})}setHistorySelectedIndex($){this.update({historySelectedIndex:Math.max(0,$)})}setCompareSelectedIndex($){this.update({compareSelectedIndex:Math.max(0,$)})}toggleIncludeUncommitted(){this.update({includeUncommitted:!this._state.includeUncommitted})}setExplorerSelectedIndex($){this.update({explorerSelectedIndex:Math.max(0,$)})}setSelectedHunkIndex($){this.update({selectedHunkIndex:Math.max(0,$)})}clampSelectedHunkIndex($){if($<=0)this._state.selectedHunkIndex=0;else if(this._state.selectedHunkIndex>=$)this._state.selectedHunkIndex=$-1}toggleWrapMode(){this.update({wrapMode:!this._state.wrapMode,diffScrollOffset:0})}toggleAutoTab(){this.update({autoTabEnabled:!this._state.autoTabEnabled})}toggleMouse(){this.update({mouseEnabled:!this._state.mouseEnabled})}toggleHideHiddenFiles(){this.update({hideHiddenFiles:!this._state.hideHiddenFiles})}toggleHideGitignored(){this.update({hideGitignored:!this._state.hideGitignored})}toggleFlatViewMode(){this.update({flatViewMode:!this._state.flatViewMode,fileListScrollOffset:0})}adjustSplitRatio($){let J=Math.min(0.85,Math.max(0.15,this._state.splitRatio+$));this.update({splitRatio:J})}setSplitRatio($){this.update({splitRatio:Math.min(0.85,Math.max(0.15,$))})}setCommitInputFocused($){this.update({commitInputFocused:$})}advanceFocus(){let $=this.focusRing.next(),J=this._state.currentPane;if(this.update({focusedZone:$}),this._state.currentPane!==J)this.emit("pane-change",this._state.currentPane)}retreatFocus(){let $=this.focusRing.prev(),J=this._state.currentPane;if(this.update({focusedZone:$}),this._state.currentPane!==J)this.emit("pane-change",this._state.currentPane)}togglePane(){this.advanceFocus()}resetForNewRepo(){let $=h1[this._state.bottomTab];this.focusRing.setItems(X$[this._state.bottomTab],$),this._state={...this._state,focusedZone:$,currentPane:w$[$],selectedIndex:0,fileListScrollOffset:0,diffScrollOffset:0,historySelectedIndex:0,historyScrollOffset:0,compareSelectedIndex:0,compareScrollOffset:0,explorerSelectedIndex:0,explorerScrollOffset:0,explorerFileScrollOffset:0,selectedHunkIndex:0},this.emit("change",this._state)}}var x$=3;function l1($,J,K){$.topPane.on("wheeldown",()=>{c1(x$,$,K)}),$.topPane.on("wheelup",()=>{c1(-x$,$,K)}),$.bottomPane.on("wheeldown",()=>{d1(x$,$,K)}),$.bottomPane.on("wheelup",()=>{d1(-x$,$,K)}),$.topPane.on("click",(X)=>{let Q=$.screenYToTopPaneRow(X.y);if(Q>=0)r5(Q,X.x,J,K)}),$.bottomPane.on("click",(X)=>{let Q=$.screenYToBottomPaneRow(X.y);if(Q>=0)if(K.uiState.state.bottomTab==="commit")l5(Q,J,K);else{let q=X$[K.uiState.state.bottomTab],Z=q[q.length-1];K.uiState.setFocusedZone(Z),J.selectHunkAtRow(Q)}}),$.footerBox.on("click",(X)=>{o5(X.x,J,K)})}function d5($,J,K,X){let Q=X.uiState.state,q;if(Q.flatViewMode){let V=$+Q.fileListScrollOffset-1,Y=X.getCachedFlatFiles();q=V>=0&&V<Y.length?V:null}else q=t0($+Q.fileListScrollOffset,X.getStatusFiles());if(q===null||q<0)return;if(J!==void 0&&J>=2&&J<=4)K.toggleFileByIndex(q);else X.uiState.setSelectedIndex(q),K.selectFileByIndex(q)}function l5($,J,K){let X=$+K.uiState.state.diffScrollOffset;if(X===6)K.uiState.setFocusedZone("commitAmend");else if(X>=2&&X<=4)K.uiState.setFocusedZone("commitMessage"),J.focusCommitInput();else K.uiState.setFocusedZone("commitMessage")}function r5($,J,K,X){let Q=X.uiState.state;if(Q.bottomTab==="history"){let q=Q.historyScrollOffset+$;X.uiState.setHistorySelectedIndex(q),K.selectHistoryCommitByIndex(q)}else if(Q.bottomTab==="compare"){let q=X.getCompareCommits(),Z=X.getCompareFiles(),V=Q0(Q.compareScrollOffset+$,q,Z);if(V)K.selectCompareItem(V)}else if(Q.bottomTab==="explorer"){let q=Q.explorerScrollOffset+$,Z=X.getExplorerManager(),V=Z?.state.selectedIndex===q,Y=Z?.state.displayRows[q];if(V&&Y?.node.isDirectory)K.enterExplorerDirectory();else Z?.selectIndex(q),X.uiState.setExplorerSelectedIndex(q)}else d5($,J,K,X)}function o5($,J,K){let X=K.getScreenWidth(),Q=[{tab:"explorer",width:11},{tab:"compare",width:10},{tab:"history",width:10},{tab:"commit",width:9},{tab:"diff",width:7}],q=X;for(let{tab:Z,width:V}of Q){let Y=q-V-1;if($>=Y&&$<q){K.uiState.setTab(Z);return}q=Y}if($>=2&&$<=9)J.toggleMouseMode();else if($>=11&&$<=16)K.uiState.toggleAutoTab();else if($>=18&&$<=23)K.uiState.toggleWrapMode();else if($>=25&&$<=32)J.toggleFollow();else if($>=34&&$<=43&&K.uiState.state.bottomTab==="explorer")K.getExplorerManager()?.toggleShowOnlyChanges();else if($===0)J.openHotkeysModal()}function c1($,J,K){let X=K.uiState.state,Q=J.dimensions.topPaneHeight;if(X.bottomTab==="history"){let q=K.getHistoryCommitCount(),Z=Math.max(0,q-Q),V=Math.min(Z,Math.max(0,X.historyScrollOffset+$));K.uiState.setHistoryScrollOffset(V)}else if(X.bottomTab==="compare"){let q=j1(K.getCompareCommits(),K.getCompareFiles()),Z=Math.max(0,q-Q),V=Math.min(Z,Math.max(0,X.compareScrollOffset+$));K.uiState.setCompareScrollOffset(V)}else if(X.bottomTab==="explorer"){let q=O1(K.getExplorerManager()?.state.displayRows??[]),Z=Math.max(0,q-Q),V=Math.min(Z,Math.max(0,X.explorerScrollOffset+$));K.uiState.setExplorerScrollOffset(V)}else{let q=X.flatViewMode?J1(K.getCachedFlatFiles()):i0(K.getStatusFiles()),Z=Math.max(0,q-Q),V=Math.min(Z,Math.max(0,X.fileListScrollOffset+$));K.uiState.setFileListScrollOffset(V)}}function d1($,J,K){let X=K.uiState.state,Q=J.dimensions.bottomPaneHeight,q=K.getScreenWidth();if(X.bottomTab==="explorer"){let Z=K.getExplorerManager()?.state.selectedFile,V=u1(Z?.content??null,Z?.path??null,Z?.truncated??!1,q,X.wrapMode),Y=Math.max(0,V-Q),z=Math.min(Y,Math.max(0,X.explorerFileScrollOffset+$));K.uiState.setExplorerFileScrollOffset(z)}else{let Z=Math.max(0,K.getBottomPaneTotalRows()-Q),V=Math.min(Z,Math.max(0,X.diffScrollOffset+$));K.uiState.setDiffScrollOffset(V)}}class D0{ctx;compareSelection=null;constructor($){this.ctx=$}scrollActiveDiffPane($){let J=this.ctx.uiState.state;if(J.bottomTab==="explorer"){let K=Math.max(0,J.explorerFileScrollOffset+$);this.ctx.uiState.setExplorerFileScrollOffset(K)}else{let K=Math.max(0,J.diffScrollOffset+$);this.ctx.uiState.setDiffScrollOffset(K)}}navigateFileList($){let J=this.ctx.uiState.state,K=this.ctx.getGitManager()?.workingTree.state.status?.files??[],X=this.ctx.getFileListMaxIndex();if(X<0)return;let Q=$===-1?Math.max(0,J.selectedIndex-1):Math.min(X,J.selectedIndex+1);this.ctx.uiState.setSelectedIndex(Q),this.selectFileByIndex(Q);let q=J.flatViewMode?Q+1:e0(Q,K);this.scrollToKeepRowVisible(q,$,J.fileListScrollOffset)}scrollToKeepRowVisible($,J,K){if(J===-1&&$<K)this.ctx.uiState.setFileListScrollOffset($);else if(J===1){let X=K+this.ctx.getTopPaneHeight()-1;if($>=X)this.ctx.uiState.setFileListScrollOffset(K+($-X+1))}}navigateActiveList($){let J=this.ctx.uiState.state.bottomTab;if(J==="history")if($===-1)this.navigateHistoryUp();else this.navigateHistoryDown();else if(J==="compare")if($===-1)this.navigateCompareUp();else this.navigateCompareDown();else if(J==="explorer")if($===-1)this.navigateExplorerUp();else this.navigateExplorerDown();else this.navigateFileList($)}navigateUp(){if(this.ctx.uiState.state.currentPane!=="diff")this.navigateActiveList(-1);else this.scrollActiveDiffPane(-3)}navigateDown(){if(this.ctx.uiState.state.currentPane!=="diff")this.navigateActiveList(1);else this.scrollActiveDiffPane(3)}navigateHistoryUp(){let $=this.ctx.uiState.state,J=Math.max(0,$.historySelectedIndex-1);if(J!==$.historySelectedIndex){if(this.ctx.uiState.setHistorySelectedIndex(J),J<$.historyScrollOffset)this.ctx.uiState.setHistoryScrollOffset(J);this.selectHistoryCommitByIndex(J)}}navigateHistoryDown(){let $=this.ctx.uiState.state,J=this.ctx.getGitManager()?.history.historyState.commits??[],K=Math.min(J.length-1,$.historySelectedIndex+1);if(K!==$.historySelectedIndex){this.ctx.uiState.setHistorySelectedIndex(K);let X=$.historyScrollOffset+this.ctx.getTopPaneHeight()-1;if(K>=X)this.ctx.uiState.setHistoryScrollOffset($.historyScrollOffset+1);this.selectHistoryCommitByIndex(K)}}selectHistoryCommitByIndex($){let J=this.ctx.getGitManager(),K=J?.history.historyState.commits??[],X=Q1(K,$);if(X)this.ctx.uiState.setDiffScrollOffset(0),J?.history.selectHistoryCommit(X).catch((Q)=>{this.ctx.onError(`Failed to load commit diff: ${Q instanceof Error?Q.message:String(Q)}`)})}navigateCompareUp(){let $=this.ctx.getGitManager()?.compare.compareState,J=$?.compareDiff?.commits??[],K=$?.compareDiff?.files??[];if(J.length===0&&K.length===0)return;let X=q0(this.compareSelection,J,K,"up");if(X&&(X.type!==this.compareSelection?.type||X.index!==this.compareSelection?.index)){this.selectCompareItem(X);let Q=this.ctx.uiState.state,q=E$(X,J,K);if(q<Q.compareScrollOffset)this.ctx.uiState.setCompareScrollOffset(q)}}navigateCompareDown(){let $=this.ctx.getGitManager()?.compare.compareState,J=$?.compareDiff?.commits??[],K=$?.compareDiff?.files??[];if(J.length===0&&K.length===0)return;if(!this.compareSelection){if(J.length>0)this.selectCompareItem({type:"commit",index:0});else if(K.length>0)this.selectCompareItem({type:"file",index:0});return}let X=q0(this.compareSelection,J,K,"down");if(X&&(X.type!==this.compareSelection?.type||X.index!==this.compareSelection?.index)){this.selectCompareItem(X);let Q=this.ctx.uiState.state,q=E$(X,J,K),Z=Q.compareScrollOffset+this.ctx.getTopPaneHeight()-1;if(q>=Z)this.ctx.uiState.setCompareScrollOffset(Q.compareScrollOffset+(q-Z+1))}}selectCompareItem($){this.compareSelection=$,this.ctx.uiState.setDiffScrollOffset(0);let J=this.ctx.getGitManager();if($.type==="commit")J?.compare.selectCompareCommit($.index).catch((K)=>{this.ctx.onError(`Failed to load commit diff: ${K instanceof Error?K.message:String(K)}`)});else J?.compare.selectCompareFile($.index)}navigateExplorerUp(){let $=this.ctx.uiState.state,J=this.ctx.getExplorerManager();if((J?.state.displayRows??[]).length===0)return;let X=J?.navigateUp($.explorerScrollOffset);if(X!==null&&X!==void 0)this.ctx.uiState.setExplorerScrollOffset(X);this.ctx.uiState.setExplorerSelectedIndex(J?.state.selectedIndex??0)}navigateExplorerDown(){let $=this.ctx.uiState.state,J=this.ctx.getExplorerManager();if((J?.state.displayRows??[]).length===0)return;let X=this.ctx.getTopPaneHeight(),Q=J?.navigateDown($.explorerScrollOffset,X);if(Q!==null&&Q!==void 0)this.ctx.uiState.setExplorerScrollOffset(Q);this.ctx.uiState.setExplorerSelectedIndex(J?.state.selectedIndex??0)}async enterExplorerDirectory(){let $=this.ctx.getExplorerManager();await $?.enterDirectory(),this.ctx.uiState.setExplorerFileScrollOffset(0),this.ctx.uiState.setExplorerSelectedIndex($?.state.selectedIndex??0)}async goExplorerUp(){let $=this.ctx.getExplorerManager();await $?.goUp(),this.ctx.uiState.setExplorerFileScrollOffset(0),this.ctx.uiState.setExplorerSelectedIndex($?.state.selectedIndex??0)}selectFileByIndex($){let J=this.ctx.resolveFileAtIndex($);if(J)this.ctx.uiState.setDiffScrollOffset(0),this.ctx.uiState.setSelectedHunkIndex(0),this.ctx.getGitManager()?.workingTree.selectFile(J)}navigateToFile($){let J=this.ctx.getRepoPath();if(!$||!J)return;let K=J.endsWith("/")?J:J+"/";if(!$.startsWith(K))return;let X=$.slice(K.length);if(!X)return;let q=(this.ctx.getGitManager()?.workingTree.state.status?.files??[]).findIndex((Z)=>Z.path===X);if(q>=0)this.ctx.uiState.setSelectedIndex(q),this.selectFileByIndex(q)}navigateNextHunk(){let $=this.ctx.uiState.state.selectedHunkIndex,J=this.ctx.getHunkCount();if(J>0&&$<J-1)this.ctx.uiState.setSelectedHunkIndex($+1),this.scrollHunkIntoView($+1)}navigatePrevHunk(){let $=this.ctx.uiState.state.selectedHunkIndex;if($>0)this.ctx.uiState.setSelectedHunkIndex($-1),this.scrollHunkIntoView($-1)}scrollHunkIntoView($){let J=this.ctx.getHunkBoundaries()[$];if(!J)return;let K=this.ctx.uiState.state.diffScrollOffset,X=this.ctx.getBottomPaneHeight();if(J.startRow<K||J.startRow>=K+X)this.ctx.uiState.setDiffScrollOffset(J.startRow)}selectHunkAtRow($){if(this.ctx.uiState.state.bottomTab!=="diff")return;let J=this.ctx.getHunkBoundaries();if(J.length===0)return;this.ctx.uiState.setPane("diff");let K=this.ctx.uiState.state.diffScrollOffset+$;for(let X=0;X<J.length;X++){let Q=J[X];if(K>=Q.startRow&&K<Q.endRow){this.ctx.uiState.setSelectedHunkIndex(X);return}}}}function p$($,J){let K=new Map;for(let Q of $){let q=K.get(Q.path)??{staged:null,unstaged:null};if(Q.staged)q.staged=Q;else q.unstaged=Q;K.set(Q.path,q)}let X=[];for(let[Q,{staged:q,unstaged:Z}]of K){let V=J?.staged.get(Q)??0,Y=J?.unstaged.get(Q)??0,z=V+Y,U;if(q&&Z)U="partial";else if(q)U="staged";else U="unstaged";let j=Z??q,B,G;if(q?.insertions!==void 0||Z?.insertions!==void 0)B=(q?.insertions??0)+(Z?.insertions??0);if(q?.deletions!==void 0||Z?.deletions!==void 0)G=(q?.deletions??0)+(Z?.deletions??0);X.push({path:Q,status:j.status,stagingState:U,stagedHunks:V,totalHunks:z,insertions:B,deletions:G,originalPath:j.originalPath,stagedEntry:q,unstagedEntry:Z})}return X.sort((Q,q)=>Q.path.localeCompare(q.path)),X}function p($,J){return $[J]??null}function r1($,J){return $.findIndex((K)=>K.path===J)}import{execSync as s5}from"node:child_process";import{simpleGit as j$}from"simple-git";function a5($){let J=$.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(J)return{oldStart:parseInt(J[1],10),newStart:parseInt(J[2],10)};return null}function g$($){let J=$.split(`
22
- `);if(J.length>1&&J[J.length-1]==="")J.pop();let K=[],X=0,Q=0;for(let q of J)if(q.startsWith("diff --git")||q.startsWith("index ")||q.startsWith("---")||q.startsWith("+++")||q.startsWith("new file")||q.startsWith("deleted file")||q.startsWith("Binary files")||q.startsWith("similarity index")||q.startsWith("rename from")||q.startsWith("rename to"))K.push({type:"header",content:q});else if(q.startsWith("@@")){let Z=a5(q);if(Z)X=Z.oldStart,Q=Z.newStart;K.push({type:"hunk",content:q})}else if(q.startsWith("+"))K.push({type:"addition",content:q,newLineNum:Q++});else if(q.startsWith("-"))K.push({type:"deletion",content:q,oldLineNum:X++});else K.push({type:"context",content:q,oldLineNum:X++,newLineNum:Q++});return K}function v0($,J){if(!$)return null;let K=$.split(`
20
+ `),Q=[],q=J?y$(J):null;for(let Z=0;Z<X.length;Z++){let V=X[Z],Y=q?H1(V,q):void 0;Q.push({type:"code",lineNum:Z+1,content:V,highlighted:Y})}if(K)Q.push({type:"truncation",content:"(file truncated)"});return Q}function x1($,J,K){if(!K)return $;let Q=Math.max(10,J),q=[];for(let Z of $)if(Z.type==="code"){let V=Z.content;if(!V||V.length<=Q){q.push(Z);continue}let Y=R$(V,Q);for(let z=0;z<Y.length;z++){let U=Y[z];q.push({type:"code",lineNum:U.isContinuation?0:Z.lineNum,content:U.text,highlighted:void 0,isContinuation:U.isContinuation})}}else q.push(Z);return q}function p1($,J,K){if(!K)return $.length;let Q=Math.max(10,J),q=0;for(let Z of $)if(Z.type==="code"){let V=Z.content;if(!V||V.length<=Q)q+=1;else q+=I$(V,Q)}else q+=1;return q}function M0($){let J=0;for(let K of $)if(K.type==="code"&&K.lineNum>J)J=K.lineNum;return Math.max(3,String(J).length)}function g1($,J,K,X=0,Q,q=!1,Z=!1){if(!$)return"{gray-fg}Select a file to view its contents{/gray-fg}";if(!J)return"{gray-fg}Loading...{/gray-fg}";let V=j0(J,$,q);if(V.length===0)return"{gray-fg}(empty file){/gray-fg}";let Y=M0(V),z=K-Y-2,U=x1(V,z,Z),j=Q?U.slice(X,X+Q):U.slice(X),B=[];for(let G of j){if(G.type==="truncation"){B.push(`{escape}${b}${G.content}${W}{/escape}`);continue}let M=G.isContinuation??!1,v;if(M)v=">>".padStart(Y," ");else v=String(G.lineNum).padStart(Y," ");let D=G.content,T=!Z&&D.length>z,H=G.highlighted&&!M,E;if(H&&G.highlighted)E=T?S$(G.highlighted,z):G.highlighted;else{let A=D;if(T)A=A.slice(0,Math.max(0,z-1))+"...";E=A}let _=`{escape}${M?R:F}${v}${W} ${E||" "}{/escape}`;B.push(_)}return B.join(`
21
+ `)}function u1($,J,K,X,Q){if(!$)return 0;let q=j0($,J,K),Z=M0(q),V=X-Z-2;return p1(q,V,Q)}function m1($,J,K,X,Q,q,Z,V,Y,z){if($.bottomTab==="history")return X1(K,$.historySelectedIndex,$.currentPane==="history",Z,$.historyScrollOffset,V);if($.bottomTab==="compare"){let U=X?.commits??[],j=X?.files??[];return G1(U,j,Q,$.currentPane==="compare",Z,$.compareScrollOffset,V)}if($.bottomTab==="explorer"){let U=q?.displayRows??[];return M1(U,$.explorerSelectedIndex,$.currentPane==="explorer",Z,$.explorerScrollOffset,V,q?.isLoading??!1,q?.error??null)}if($.flatViewMode&&z)return $1(z,$.selectedIndex,$.currentPane==="files",Z,$.fileListScrollOffset,V);return n0(J,$.selectedIndex,$.currentPane==="files",Z,$.fileListScrollOffset,V,Y)}function f1($,J,K,X,Q,q,Z,V,Y,z,U,j,B,G){if($.bottomTab==="commit"){let E=S1({state:q,stagedCount:Z,width:Y,focusedZone:G});return{content:w1(q,Z,Y,$.diffScrollOffset,z,G),totalRows:E,hunkCount:0,hunkBoundaries:[]}}if($.bottomTab==="history"){let H=K?.selectedCommit??null,E=K?.commitDiff??null,{content:O,totalRows:_}=C1(H,E,Y,$.diffScrollOffset,z,V,$.wrapMode);return{content:O,totalRows:_,hunkCount:0,hunkBoundaries:[]}}if($.bottomTab==="compare"){let H=X?.diff??null;if(H){let{content:E,totalRows:O}=G0(H,Y,$.diffScrollOffset,z,V,$.wrapMode);return{content:E,totalRows:O,hunkCount:0,hunkBoundaries:[]}}return{content:"{gray-fg}Select a commit or file to view diff{/gray-fg}",totalRows:0,hunkCount:0,hunkBoundaries:[]}}if($.bottomTab==="explorer")return{content:g1(Q?.path??null,Q?.content??null,Y,$.explorerFileScrollOffset,z,Q?.truncated??!1,$.wrapMode),totalRows:0,hunkCount:0,hunkBoundaries:[]};if($.flatViewMode&&B){let H=P1(B.unstaged,B.staged,Y,$.diffScrollOffset,z,V,$.wrapMode,U);return{content:H.content,totalRows:H.totalRows,hunkCount:H.hunkCount,hunkBoundaries:H.hunkBoundaries,hunkMapping:H.hunkMapping}}let{content:M,totalRows:v,hunkCount:D,hunkBoundaries:T}=G0(J,Y,$.diffScrollOffset,z,V,$.wrapMode,U,j);return{content:M,totalRows:v,hunkCount:D,hunkBoundaries:T}}import{EventEmitter as h5}from"node:events";class O0{items;index;constructor($,J=0){this.items=$,this.index=Math.min(J,Math.max(0,$.length-1))}current(){return this.items[this.index]}next(){return this.index=(this.index+1)%this.items.length,this.items[this.index]}prev(){return this.index=(this.index-1+this.items.length)%this.items.length,this.items[this.index]}setCurrent($){let J=this.items.indexOf($);if(J===-1)return!1;return this.index=J,!0}setItems($,J){if(this.items=$,J!==void 0){let K=$.indexOf(J);this.index=K!==-1?K:0}else this.index=Math.min(this.index,Math.max(0,$.length-1))}}var w$={fileList:"files",diffView:"diff",commitMessage:"commit",commitAmend:"commit",historyList:"history",historyDiff:"diff",compareList:"compare",compareDiff:"diff",explorerTree:"explorer",explorerContent:"diff"},Q$={diff:["fileList","diffView"],commit:["fileList","commitMessage","commitAmend"],history:["historyList","historyDiff"],compare:["compareList","compareDiff"],explorer:["explorerTree","explorerContent"]},h1={diff:"fileList",commit:"commitMessage",history:"historyList",compare:"compareList",explorer:"explorerTree"},c5={focusedZone:"fileList",currentPane:"files",bottomTab:"diff",selectedIndex:0,fileListScrollOffset:0,diffScrollOffset:0,historyScrollOffset:0,compareScrollOffset:0,explorerScrollOffset:0,explorerFileScrollOffset:0,historySelectedIndex:0,compareSelectedIndex:0,includeUncommitted:!1,explorerSelectedIndex:0,selectedHunkIndex:0,wrapMode:!1,autoTabEnabled:!1,mouseEnabled:!0,hideHiddenFiles:!0,hideGitignored:!0,flatViewMode:!1,splitRatio:0.4,commitInputFocused:!1};class _0 extends h5{_state;focusRing;constructor($={}){super();this._state={...c5,...$};let J=this._state.bottomTab,K=Q$[J];if(this.focusRing=new O0(K),this._state.focusedZone)this.focusRing.setCurrent(this._state.focusedZone);this._state.currentPane=w$[this._state.focusedZone]}get state(){return this._state}update($){this._state={...this._state,...$},this._state.currentPane=w$[this._state.focusedZone],this.emit("change",this._state)}setPane($){let K=Q$[this._state.bottomTab].find((X)=>w$[X]===$);if(K)this.setFocusedZone(K)}setFocusedZone($){if(this._state.focusedZone!==$){this.focusRing.setCurrent($);let J=this._state.currentPane;if(this.update({focusedZone:$}),this._state.currentPane!==J)this.emit("pane-change",this._state.currentPane)}}setTab($){if(this._state.bottomTab!==$){let J=h1[$];this.focusRing.setItems(Q$[$],J),this.update({bottomTab:$,focusedZone:J}),this.emit("tab-change",$)}}setSelectedIndex($){if(this._state.selectedIndex!==$)this.update({selectedIndex:$}),this.emit("selection-change",$)}setFileListScrollOffset($){this.update({fileListScrollOffset:Math.max(0,$)}),this.emit("scroll-change",{type:"fileList",offset:$})}setDiffScrollOffset($){this.update({diffScrollOffset:Math.max(0,$)}),this.emit("scroll-change",{type:"diff",offset:$})}setHistoryScrollOffset($){this.update({historyScrollOffset:Math.max(0,$)}),this.emit("scroll-change",{type:"history",offset:$})}setCompareScrollOffset($){this.update({compareScrollOffset:Math.max(0,$)}),this.emit("scroll-change",{type:"compare",offset:$})}setExplorerScrollOffset($){this.update({explorerScrollOffset:Math.max(0,$)}),this.emit("scroll-change",{type:"explorer",offset:$})}setExplorerFileScrollOffset($){this.update({explorerFileScrollOffset:Math.max(0,$)}),this.emit("scroll-change",{type:"explorerFile",offset:$})}setHistorySelectedIndex($){this.update({historySelectedIndex:Math.max(0,$)})}setCompareSelectedIndex($){this.update({compareSelectedIndex:Math.max(0,$)})}toggleIncludeUncommitted(){this.update({includeUncommitted:!this._state.includeUncommitted})}setExplorerSelectedIndex($){this.update({explorerSelectedIndex:Math.max(0,$)})}setSelectedHunkIndex($){this.update({selectedHunkIndex:Math.max(0,$)})}clampSelectedHunkIndex($){if($<=0)this._state.selectedHunkIndex=0;else if(this._state.selectedHunkIndex>=$)this._state.selectedHunkIndex=$-1}toggleWrapMode(){this.update({wrapMode:!this._state.wrapMode,diffScrollOffset:0})}toggleAutoTab(){this.update({autoTabEnabled:!this._state.autoTabEnabled})}toggleMouse(){this.update({mouseEnabled:!this._state.mouseEnabled})}toggleHideHiddenFiles(){this.update({hideHiddenFiles:!this._state.hideHiddenFiles})}toggleHideGitignored(){this.update({hideGitignored:!this._state.hideGitignored})}toggleFlatViewMode(){this.update({flatViewMode:!this._state.flatViewMode,fileListScrollOffset:0})}adjustSplitRatio($){let J=Math.min(0.85,Math.max(0.15,this._state.splitRatio+$));this.update({splitRatio:J})}setSplitRatio($){this.update({splitRatio:Math.min(0.85,Math.max(0.15,$))})}setCommitInputFocused($){this.update({commitInputFocused:$})}advanceFocus(){let $=this.focusRing.next(),J=this._state.currentPane;if(this.update({focusedZone:$}),this._state.currentPane!==J)this.emit("pane-change",this._state.currentPane)}retreatFocus(){let $=this.focusRing.prev(),J=this._state.currentPane;if(this.update({focusedZone:$}),this._state.currentPane!==J)this.emit("pane-change",this._state.currentPane)}togglePane(){this.advanceFocus()}resetForNewRepo(){let $=h1[this._state.bottomTab];this.focusRing.setItems(Q$[this._state.bottomTab],$),this._state={...this._state,focusedZone:$,currentPane:w$[$],selectedIndex:0,fileListScrollOffset:0,diffScrollOffset:0,historySelectedIndex:0,historyScrollOffset:0,compareSelectedIndex:0,compareScrollOffset:0,explorerSelectedIndex:0,explorerScrollOffset:0,explorerFileScrollOffset:0,selectedHunkIndex:0},this.emit("change",this._state)}}var x$=3;function l1($,J,K){$.topPane.on("wheeldown",()=>{c1(x$,$,K)}),$.topPane.on("wheelup",()=>{c1(-x$,$,K)}),$.bottomPane.on("wheeldown",()=>{d1(x$,$,K)}),$.bottomPane.on("wheelup",()=>{d1(-x$,$,K)}),$.topPane.on("click",(X)=>{let Q=$.screenYToTopPaneRow(X.y);if(Q>=0)r5(Q,X.x,J,K)}),$.bottomPane.on("click",(X)=>{let Q=$.screenYToBottomPaneRow(X.y);if(Q>=0)if(K.uiState.state.bottomTab==="commit")l5(Q,J,K);else{let q=Q$[K.uiState.state.bottomTab],Z=q[q.length-1];K.uiState.setFocusedZone(Z),J.selectHunkAtRow(Q)}}),$.footerBox.on("click",(X)=>{o5(X.x,J,K)})}function d5($,J,K,X){let Q=X.uiState.state,q;if(Q.flatViewMode){let V=$+Q.fileListScrollOffset-1,Y=X.getCachedFlatFiles();q=V>=0&&V<Y.length?V:null}else q=t0($+Q.fileListScrollOffset,X.getStatusFiles());if(q===null||q<0)return;if(J!==void 0&&J>=2&&J<=4)K.toggleFileByIndex(q);else X.uiState.setSelectedIndex(q),K.selectFileByIndex(q)}function l5($,J,K){let X=$+K.uiState.state.diffScrollOffset;if(X===6)K.uiState.setFocusedZone("commitAmend");else if(X>=2&&X<=4)K.uiState.setFocusedZone("commitMessage"),J.focusCommitInput();else K.uiState.setFocusedZone("commitMessage")}function r5($,J,K,X){let Q=X.uiState.state;if(Q.bottomTab==="history"){let q=Q.historyScrollOffset+$;X.uiState.setHistorySelectedIndex(q),K.selectHistoryCommitByIndex(q)}else if(Q.bottomTab==="compare"){let q=X.getCompareCommits(),Z=X.getCompareFiles(),V=Q0(Q.compareScrollOffset+$,q,Z);if(V)K.selectCompareItem(V)}else if(Q.bottomTab==="explorer"){let q=Q.explorerScrollOffset+$,Z=X.getExplorerManager(),V=Z?.state.selectedIndex===q,Y=Z?.state.displayRows[q];if(V&&Y?.node.isDirectory)K.enterExplorerDirectory();else Z?.selectIndex(q),X.uiState.setExplorerSelectedIndex(q)}else d5($,J,K,X)}function o5($,J,K){let X=K.getScreenWidth(),Q=[{tab:"explorer",width:11},{tab:"compare",width:10},{tab:"history",width:10},{tab:"commit",width:9},{tab:"diff",width:7}],q=X;for(let{tab:Z,width:V}of Q){let Y=q-V-1;if($>=Y&&$<q){K.uiState.setTab(Z);return}q=Y}if($>=2&&$<=9)J.toggleMouseMode();else if($>=11&&$<=16)K.uiState.toggleAutoTab();else if($>=18&&$<=23)K.uiState.toggleWrapMode();else if($>=25&&$<=32)J.toggleFollow();else if($>=34&&$<=43&&K.uiState.state.bottomTab==="explorer")K.getExplorerManager()?.toggleShowOnlyChanges();else if($===0)J.openHotkeysModal()}function c1($,J,K){let X=K.uiState.state,Q=J.dimensions.topPaneHeight;if(X.bottomTab==="history"){let q=K.getHistoryCommitCount(),Z=Math.max(0,q-Q),V=Math.min(Z,Math.max(0,X.historyScrollOffset+$));K.uiState.setHistoryScrollOffset(V)}else if(X.bottomTab==="compare"){let q=j1(K.getCompareCommits(),K.getCompareFiles()),Z=Math.max(0,q-Q),V=Math.min(Z,Math.max(0,X.compareScrollOffset+$));K.uiState.setCompareScrollOffset(V)}else if(X.bottomTab==="explorer"){let q=O1(K.getExplorerManager()?.state.displayRows??[]),Z=Math.max(0,q-Q),V=Math.min(Z,Math.max(0,X.explorerScrollOffset+$));K.uiState.setExplorerScrollOffset(V)}else{let q=X.flatViewMode?J1(K.getCachedFlatFiles()):i0(K.getStatusFiles()),Z=Math.max(0,q-Q),V=Math.min(Z,Math.max(0,X.fileListScrollOffset+$));K.uiState.setFileListScrollOffset(V)}}function d1($,J,K){let X=K.uiState.state,Q=J.dimensions.bottomPaneHeight,q=K.getScreenWidth();if(X.bottomTab==="explorer"){let Z=K.getExplorerManager()?.state.selectedFile,V=u1(Z?.content??null,Z?.path??null,Z?.truncated??!1,q,X.wrapMode),Y=Math.max(0,V-Q),z=Math.min(Y,Math.max(0,X.explorerFileScrollOffset+$));K.uiState.setExplorerFileScrollOffset(z)}else{let Z=Math.max(0,K.getBottomPaneTotalRows()-Q),V=Math.min(Z,Math.max(0,X.diffScrollOffset+$));K.uiState.setDiffScrollOffset(V)}}class D0{ctx;compareSelection=null;constructor($){this.ctx=$}scrollActiveDiffPane($){let J=this.ctx.uiState.state;if(J.bottomTab==="explorer"){let K=Math.max(0,J.explorerFileScrollOffset+$);this.ctx.uiState.setExplorerFileScrollOffset(K)}else{let K=Math.max(0,J.diffScrollOffset+$);this.ctx.uiState.setDiffScrollOffset(K)}}navigateFileList($){let J=this.ctx.uiState.state,K=this.ctx.getGitManager()?.workingTree.state.status?.files??[],X=this.ctx.getFileListMaxIndex();if(X<0)return;let Q=$===-1?Math.max(0,J.selectedIndex-1):Math.min(X,J.selectedIndex+1);this.ctx.uiState.setSelectedIndex(Q),this.selectFileByIndex(Q);let q=J.flatViewMode?Q+1:e0(Q,K);this.scrollToKeepRowVisible(q,$,J.fileListScrollOffset)}scrollToKeepRowVisible($,J,K){if(J===-1&&$<K)this.ctx.uiState.setFileListScrollOffset($);else if(J===1){let X=K+this.ctx.getTopPaneHeight()-1;if($>=X)this.ctx.uiState.setFileListScrollOffset(K+($-X+1))}}navigateActiveList($){let J=this.ctx.uiState.state.bottomTab;if(J==="history")if($===-1)this.navigateHistoryUp();else this.navigateHistoryDown();else if(J==="compare")if($===-1)this.navigateCompareUp();else this.navigateCompareDown();else if(J==="explorer")if($===-1)this.navigateExplorerUp();else this.navigateExplorerDown();else this.navigateFileList($)}navigateUp(){if(this.ctx.uiState.state.currentPane!=="diff")this.navigateActiveList(-1);else this.scrollActiveDiffPane(-3)}navigateDown(){if(this.ctx.uiState.state.currentPane!=="diff")this.navigateActiveList(1);else this.scrollActiveDiffPane(3)}navigateHistoryUp(){let $=this.ctx.uiState.state,J=Math.max(0,$.historySelectedIndex-1);if(J!==$.historySelectedIndex){if(this.ctx.uiState.setHistorySelectedIndex(J),J<$.historyScrollOffset)this.ctx.uiState.setHistoryScrollOffset(J);this.selectHistoryCommitByIndex(J)}}navigateHistoryDown(){let $=this.ctx.uiState.state,J=this.ctx.getGitManager()?.history.historyState.commits??[],K=Math.min(J.length-1,$.historySelectedIndex+1);if(K!==$.historySelectedIndex){this.ctx.uiState.setHistorySelectedIndex(K);let X=$.historyScrollOffset+this.ctx.getTopPaneHeight()-1;if(K>=X)this.ctx.uiState.setHistoryScrollOffset($.historyScrollOffset+1);this.selectHistoryCommitByIndex(K)}}selectHistoryCommitByIndex($){let J=this.ctx.getGitManager(),K=J?.history.historyState.commits??[],X=Q1(K,$);if(X)this.ctx.uiState.setDiffScrollOffset(0),J?.history.selectHistoryCommit(X).catch((Q)=>{this.ctx.onError(`Failed to load commit diff: ${Q instanceof Error?Q.message:String(Q)}`)})}navigateCompareUp(){let $=this.ctx.getGitManager()?.compare.compareState,J=$?.compareDiff?.commits??[],K=$?.compareDiff?.files??[];if(J.length===0&&K.length===0)return;let X=q0(this.compareSelection,J,K,"up");if(X&&(X.type!==this.compareSelection?.type||X.index!==this.compareSelection?.index)){this.selectCompareItem(X);let Q=this.ctx.uiState.state,q=E$(X,J,K);if(q<Q.compareScrollOffset)this.ctx.uiState.setCompareScrollOffset(q)}}navigateCompareDown(){let $=this.ctx.getGitManager()?.compare.compareState,J=$?.compareDiff?.commits??[],K=$?.compareDiff?.files??[];if(J.length===0&&K.length===0)return;if(!this.compareSelection){if(J.length>0)this.selectCompareItem({type:"commit",index:0});else if(K.length>0)this.selectCompareItem({type:"file",index:0});return}let X=q0(this.compareSelection,J,K,"down");if(X&&(X.type!==this.compareSelection?.type||X.index!==this.compareSelection?.index)){this.selectCompareItem(X);let Q=this.ctx.uiState.state,q=E$(X,J,K),Z=Q.compareScrollOffset+this.ctx.getTopPaneHeight()-1;if(q>=Z)this.ctx.uiState.setCompareScrollOffset(Q.compareScrollOffset+(q-Z+1))}}selectCompareItem($){this.compareSelection=$,this.ctx.uiState.setDiffScrollOffset(0);let J=this.ctx.getGitManager();if($.type==="commit")J?.compare.selectCompareCommit($.index).catch((K)=>{this.ctx.onError(`Failed to load commit diff: ${K instanceof Error?K.message:String(K)}`)});else J?.compare.selectCompareFile($.index)}navigateExplorerUp(){let $=this.ctx.uiState.state,J=this.ctx.getExplorerManager();if((J?.state.displayRows??[]).length===0)return;let X=J?.navigateUp($.explorerScrollOffset);if(X!==null&&X!==void 0)this.ctx.uiState.setExplorerScrollOffset(X);this.ctx.uiState.setExplorerSelectedIndex(J?.state.selectedIndex??0)}navigateExplorerDown(){let $=this.ctx.uiState.state,J=this.ctx.getExplorerManager();if((J?.state.displayRows??[]).length===0)return;let X=this.ctx.getTopPaneHeight(),Q=J?.navigateDown($.explorerScrollOffset,X);if(Q!==null&&Q!==void 0)this.ctx.uiState.setExplorerScrollOffset(Q);this.ctx.uiState.setExplorerSelectedIndex(J?.state.selectedIndex??0)}async enterExplorerDirectory(){let $=this.ctx.getExplorerManager();await $?.enterDirectory(),this.ctx.uiState.setExplorerFileScrollOffset(0),this.ctx.uiState.setExplorerSelectedIndex($?.state.selectedIndex??0)}async goExplorerUp(){let $=this.ctx.getExplorerManager();await $?.goUp(),this.ctx.uiState.setExplorerFileScrollOffset(0),this.ctx.uiState.setExplorerSelectedIndex($?.state.selectedIndex??0)}selectFileByIndex($){let J=this.ctx.resolveFileAtIndex($);if(J)this.ctx.uiState.setDiffScrollOffset(0),this.ctx.uiState.setSelectedHunkIndex(0),this.ctx.getGitManager()?.workingTree.selectFile(J)}navigateToFile($){let J=this.ctx.getRepoPath();if(!$||!J)return;let K=J.endsWith("/")?J:J+"/";if(!$.startsWith(K))return;let X=$.slice(K.length);if(!X)return;let q=(this.ctx.getGitManager()?.workingTree.state.status?.files??[]).findIndex((Z)=>Z.path===X);if(q>=0)this.ctx.uiState.setSelectedIndex(q),this.selectFileByIndex(q)}navigateNextHunk(){let $=this.ctx.uiState.state.selectedHunkIndex,J=this.ctx.getHunkCount();if(J>0&&$<J-1)this.ctx.uiState.setSelectedHunkIndex($+1),this.scrollHunkIntoView($+1)}navigatePrevHunk(){let $=this.ctx.uiState.state.selectedHunkIndex;if($>0)this.ctx.uiState.setSelectedHunkIndex($-1),this.scrollHunkIntoView($-1)}scrollHunkIntoView($){let J=this.ctx.getHunkBoundaries()[$];if(!J)return;let K=this.ctx.uiState.state.diffScrollOffset,X=this.ctx.getBottomPaneHeight();if(J.startRow<K||J.startRow>=K+X)this.ctx.uiState.setDiffScrollOffset(J.startRow)}selectHunkAtRow($){if(this.ctx.uiState.state.bottomTab!=="diff")return;let J=this.ctx.getHunkBoundaries();if(J.length===0)return;this.ctx.uiState.setPane("diff");let K=this.ctx.uiState.state.diffScrollOffset+$;for(let X=0;X<J.length;X++){let Q=J[X];if(K>=Q.startRow&&K<Q.endRow){this.ctx.uiState.setSelectedHunkIndex(X);return}}}}function p$($,J){let K=new Map;for(let Q of $){let q=K.get(Q.path)??{staged:null,unstaged:null};if(Q.staged)q.staged=Q;else q.unstaged=Q;K.set(Q.path,q)}let X=[];for(let[Q,{staged:q,unstaged:Z}]of K){let V=J?.staged.get(Q)??0,Y=J?.unstaged.get(Q)??0,z=V+Y,U;if(q&&Z)U="partial";else if(q)U="staged";else U="unstaged";let j=Z??q,B,G;if(q?.insertions!==void 0||Z?.insertions!==void 0)B=(q?.insertions??0)+(Z?.insertions??0);if(q?.deletions!==void 0||Z?.deletions!==void 0)G=(q?.deletions??0)+(Z?.deletions??0);X.push({path:Q,status:j.status,stagingState:U,stagedHunks:V,totalHunks:z,insertions:B,deletions:G,originalPath:j.originalPath,stagedEntry:q,unstagedEntry:Z})}return X.sort((Q,q)=>Q.path.localeCompare(q.path)),X}function p($,J){return $[J]??null}function r1($,J){return $.findIndex((K)=>K.path===J)}import{execSync as s5}from"node:child_process";import{simpleGit as j$}from"simple-git";function a5($){let J=$.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(J)return{oldStart:parseInt(J[1],10),newStart:parseInt(J[2],10)};return null}function g$($){let J=$.split(`
22
+ `);if(J.length>1&&J[J.length-1]==="")J.pop();let K=[],X=0,Q=0;for(let q of J)if(q.startsWith("diff --git")||q.startsWith("index ")||q.startsWith("---")||q.startsWith("+++")||q.startsWith("new file")||q.startsWith("deleted file")||q.startsWith("Binary files")||q.startsWith("similarity index")||q.startsWith("rename from")||q.startsWith("rename to"))K.push({type:"header",content:q});else if(q.startsWith("@@")){let Z=a5(q);if(Z)X=Z.oldStart,Q=Z.newStart;K.push({type:"hunk",content:q})}else if(q.startsWith("+"))K.push({type:"addition",content:q,newLineNum:Q++});else if(q.startsWith("-"))K.push({type:"deletion",content:q,oldLineNum:X++});else K.push({type:"context",content:q,oldLineNum:X++,newLineNum:Q++});return K}function W0($,J){if(!$)return null;let K=$.split(`
23
23
  `),X=[],Q=-1;for(let z=0;z<K.length;z++){if(K[z].startsWith("@@")){Q=z;break}X.push(K[z])}if(Q===-1)return null;let q=-1,Z=-1;for(let z=Q;z<K.length;z++)if(K[z].startsWith("@@")){if(q++,q===J){Z=z;break}}if(Z===-1)return null;let V=[K[Z]];for(let z=Z+1;z<K.length;z++){if(K[z].startsWith("@@")||K[z].startsWith("diff --git"))break;V.push(K[z])}while(V.length>1&&V[V.length-1]==="")V.pop();return[...X,...V].join(`
24
24
  `)+`
25
- `}function W0($){let J=new Map;if(!$)return J;let K=null;for(let X of $.split(`
25
+ `}function v0($){let J=new Map;if(!$)return J;let K=null;for(let X of $.split(`
26
26
  `))if(X.startsWith("diff --git")){let Q=X.match(/^diff --git a\/.+ b\/(.+)$/);if(Q){if(K=Q[1],!J.has(K))J.set(K,0)}}else if(X.startsWith("@@")&&K)J.set(K,(J.get(K)??0)+1);return J}async function h($,J,K=!1){let X=j$($);try{let Q=[];if(K)Q.push("--cached");if(J)Q.push("--",J);let q=await X.diff(Q),Z=g$(q);return{raw:q,lines:Z}}catch{return{raw:"",lines:[]}}}async function H0($,J){try{let K=s5(`cat "${J}"`,{cwd:$,encoding:"utf-8"}),X=[{type:"header",content:`diff --git a/${J} b/${J}`},{type:"header",content:"new file mode 100644"},{type:"header",content:"--- /dev/null"},{type:"header",content:`+++ b/${J}`}],Q=K.split(`
27
27
  `);X.push({type:"hunk",content:`@@ -0,0 +1,${Q.length} @@`});let q=1;for(let V of Q)X.push({type:"addition",content:"+"+V,newLineNum:q++});return{raw:X.map((V)=>V.content).join(`
28
28
  `),lines:X}}catch{return{raw:"",lines:[]}}}async function o1($){return h($,void 0,!0)}async function T0($){let J=j$($),K=new Set,X=[];try{let Q=await J.raw(["log","--oneline","--decorate=short","--all","-n","200"]),q=/\(([^)]+)\)/g;for(let Z of Q.split(`
29
29
  `)){let V=q.exec(Z);if(V){let Y=V[1].split(",").map((z)=>z.trim());for(let z of Y){if(z.startsWith("HEAD")||z.startsWith("tag:")||!z.includes("/"))continue;let U=z.replace(/^.*-> /,"");if(U.includes("/")&&!K.has(U))K.add(U),X.push(U)}}q.lastIndex=0}if(X.length>0)X.sort((Z,V)=>{let Y=Z.split("/").slice(1).join("/"),z=V.split("/").slice(1).join("/"),U=Y==="main"||Y==="master",j=z==="main"||z==="master";if(U&&!j)return-1;if(!U&&j)return 1;if(U&&j){let B=Z.startsWith("origin/"),G=V.startsWith("origin/");if(B&&!G)return 1;if(!B&&G)return-1}return 0})}catch{}return[...new Set(X)]}async function s1($){return(await T0($))[0]??null}async function A0($,J){let K=j$($),Q=(await K.raw(["merge-base",J,"HEAD"])).trim(),q=await K.raw(["diff","--numstat",`${Q}...HEAD`]),Z=await K.raw(["diff","--name-status",`${Q}...HEAD`]),V=await K.raw(["diff",`${Q}...HEAD`]),Y=q.trim().split(`
30
30
  `).filter((O)=>O),z=new Map;for(let O of Y){let _=O.split("\t");if(_.length>=3){let A=_[0]==="-"?0:parseInt(_[0],10),y=_[1]==="-"?0:parseInt(_[1],10),k=_.slice(2).join("\t");z.set(k,{additions:A,deletions:y})}}let U=Z.trim().split(`
31
- `).filter((O)=>O),j=new Map;for(let O of U){let _=O.split("\t");if(_.length>=2){let A=_[0][0],y=_[_.length-1],k;switch(A){case"A":k="added";break;case"D":k="deleted";break;case"R":k="renamed";break;default:k="modified"}j.set(y,k)}}let B=[],G=V.split(/(?=^diff --git )/m).filter((O)=>O.trim());for(let O of G){let _=O.match(/^diff --git a\/.+ b\/(.+)$/m);if(!_)continue;let A=_[1],y=g$(O),k=z.get(A)||{additions:0,deletions:0},L=j.get(A)||"modified";B.push({path:A,status:L,additions:k.additions,deletions:k.deletions,diff:{raw:O,lines:y}})}let M=0,H=0;for(let O of B)M+=O.additions,H+=O.deletions;let T=(await K.status()).files.length,E=(await K.log({from:Q,to:"HEAD"})).all.map((O)=>({hash:O.hash,shortHash:O.hash.slice(0,7),message:O.message.split(`
32
- `)[0],author:O.author_name,date:new Date(O.date),refs:O.refs||""}));return B.sort((O,_)=>O.path.localeCompare(_.path)),{baseBranch:J,stats:{filesChanged:B.length,additions:M,deletions:H},files:B,commits:E,uncommittedCount:T}}async function u$($,J){let K=j$($);try{let X=await K.raw(["show",J,"--format="]),Q=g$(X);return{raw:X,lines:Q}}catch{return{raw:"",lines:[]}}}async function a1($,J){let K=j$($),X=await A0($,J),Q=await K.diff(["--cached","--numstat"]),q=await K.diff(["--numstat"]),Z=await K.diff(["--cached"]),V=await K.diff([]),Y=new Map;for(let O of Q.trim().split(`
31
+ `).filter((O)=>O),j=new Map;for(let O of U){let _=O.split("\t");if(_.length>=2){let A=_[0][0],y=_[_.length-1],k;switch(A){case"A":k="added";break;case"D":k="deleted";break;case"R":k="renamed";break;default:k="modified"}j.set(y,k)}}let B=[],G=V.split(/(?=^diff --git )/m).filter((O)=>O.trim());for(let O of G){let _=O.match(/^diff --git a\/.+ b\/(.+)$/m);if(!_)continue;let A=_[1],y=g$(O),k=z.get(A)||{additions:0,deletions:0},L=j.get(A)||"modified";B.push({path:A,status:L,additions:k.additions,deletions:k.deletions,diff:{raw:O,lines:y}})}let M=0,v=0;for(let O of B)M+=O.additions,v+=O.deletions;let T=(await K.status()).files.length,E=(await K.log({from:Q,to:"HEAD"})).all.map((O)=>({hash:O.hash,shortHash:O.hash.slice(0,7),message:O.message.split(`
32
+ `)[0],author:O.author_name,date:new Date(O.date),refs:O.refs||""}));return B.sort((O,_)=>O.path.localeCompare(_.path)),{baseBranch:J,stats:{filesChanged:B.length,additions:M,deletions:v},files:B,commits:E,uncommittedCount:T}}async function u$($,J){let K=j$($);try{let X=await K.raw(["show",J,"--format="]),Q=g$(X);return{raw:X,lines:Q}}catch{return{raw:"",lines:[]}}}async function a1($,J){let K=j$($),X=await A0($,J),Q=await K.diff(["--cached","--numstat"]),q=await K.diff(["--numstat"]),Z=await K.diff(["--cached"]),V=await K.diff([]),Y=new Map;for(let O of Q.trim().split(`
33
33
  `).filter((_)=>_)){let _=O.split("\t");if(_.length>=3){let A=_[0]==="-"?0:parseInt(_[0],10),y=_[1]==="-"?0:parseInt(_[1],10),k=_.slice(2).join("\t");Y.set(k,{additions:A,deletions:y,staged:!0,unstaged:!1})}}for(let O of q.trim().split(`
34
- `).filter((_)=>_)){let _=O.split("\t");if(_.length>=3){let A=_[0]==="-"?0:parseInt(_[0],10),y=_[1]==="-"?0:parseInt(_[1],10),k=_.slice(2).join("\t"),L=Y.get(k);if(L)L.additions+=A,L.deletions+=y,L.unstaged=!0;else Y.set(k,{additions:A,deletions:y,staged:!1,unstaged:!0})}}let z=await K.status(),U=new Map;for(let O of z.files)if(O.index==="A"||O.working_dir==="?")U.set(O.path,"added");else if(O.index==="D"||O.working_dir==="D")U.set(O.path,"deleted");else if(O.index==="R")U.set(O.path,"renamed");else U.set(O.path,"modified");let j=[],G=(Z+V).split(/(?=^diff --git )/m).filter((O)=>O.trim()),M=new Set;for(let O of G){let _=O.match(/^diff --git a\/.+ b\/(.+)$/m);if(!_)continue;let A=_[1];if(M.has(A))continue;M.add(A);let y=g$(O),k=Y.get(A)||{additions:0,deletions:0},L=U.get(A)||"modified";j.push({path:A,status:L,additions:k.additions,deletions:k.deletions,diff:{raw:O,lines:y},isUncommitted:!0})}let H=new Set(X.files.map((O)=>O.path)),D=[];for(let O of X.files){let _=j.find((A)=>A.path===O.path);if(_)D.push(O),D.push(_);else D.push(O)}for(let O of j)if(!H.has(O.path))D.push(O);let T=0,W=0,E=new Set;for(let O of D)E.add(O.path),T+=O.additions,W+=O.deletions;return D.sort((O,_)=>O.path.localeCompare(_.path)),{baseBranch:X.baseBranch,stats:{filesChanged:E.size,additions:T,deletions:W},files:D,commits:X.commits,uncommittedCount:X.uncommittedCount}}class k0{ctx;pendingSelectionAnchor=null;pendingFlatSelectionPath=null;pendingHunkIndex=null;constructor($){this.ctx=$}consumePendingSelectionAnchor(){let $=this.pendingSelectionAnchor;return this.pendingSelectionAnchor=null,$}consumePendingFlatSelectionPath(){let $=this.pendingFlatSelectionPath;return this.pendingFlatSelectionPath=null,$}consumePendingHunkIndex(){let $=this.pendingHunkIndex;return this.pendingHunkIndex=null,$}async stageSelected(){let J=this.ctx.getGitManager()?.workingTree,K=J?.state.status?.files??[],X=this.ctx.uiState.state.selectedIndex;if(this.ctx.uiState.state.flatViewMode){let Q=p(this.ctx.getCachedFlatFiles(),X);if(!Q)return;let q=Q.unstagedEntry;if(q)this.pendingFlatSelectionPath=Q.path,await J?.stage(q)}else{let Q=this.ctx.resolveFileAtIndex(X);if(Q&&!Q.staged)this.pendingSelectionAnchor=a(K,X),await J?.stage(Q)}}async unstageSelected(){let J=this.ctx.getGitManager()?.workingTree,K=J?.state.status?.files??[],X=this.ctx.uiState.state.selectedIndex;if(this.ctx.uiState.state.flatViewMode){let Q=p(this.ctx.getCachedFlatFiles(),X);if(!Q)return;let q=Q.stagedEntry;if(q)this.pendingFlatSelectionPath=Q.path,await J?.unstage(q)}else{let Q=this.ctx.resolveFileAtIndex(X);if(Q?.staged)this.pendingSelectionAnchor=a(K,X),await J?.unstage(Q)}}async toggleSelected(){let $=this.ctx.uiState.state.selectedIndex;if(this.ctx.uiState.state.flatViewMode){let J=p(this.ctx.getCachedFlatFiles(),$);if(J)await this.toggleFlatEntry(J)}else{let K=this.ctx.getGitManager()?.workingTree,X=K?.state.status?.files??[],Q=this.ctx.resolveFileAtIndex($);if(Q)if(this.pendingSelectionAnchor=a(X,$),Q.staged)await K?.unstage(Q);else await K?.stage(Q)}}async stageAll(){await this.ctx.getGitManager()?.workingTree.stageAll()}async unstageAll(){await this.ctx.getGitManager()?.workingTree.unstageAll()}async toggleFlatEntry($){let J=this.ctx.getGitManager()?.workingTree;if(this.pendingFlatSelectionPath=$.path,$.stagingState==="staged"){if($.stagedEntry)await J?.unstage($.stagedEntry)}else if($.unstagedEntry)await J?.stage($.unstagedEntry)}async toggleFileByIndex($){if(this.ctx.uiState.state.flatViewMode){let J=p(this.ctx.getCachedFlatFiles(),$);if(J)await this.toggleFlatEntry(J)}else{let K=this.ctx.getGitManager()?.workingTree,X=K?.state.status?.files??[],Q=this.ctx.resolveFileAtIndex($);if(Q)if(this.pendingSelectionAnchor=a(X,this.ctx.uiState.state.selectedIndex),Q.staged)await K?.unstage(Q);else await K?.stage(Q)}}async toggleCurrentHunk(){let $=this.ctx.getGitManager()?.workingTree.state.selectedFile;if(!$)return;if($.status==="untracked"){let J=this.ctx.getGitManager()?.workingTree,K=J?.state.status?.files??[];this.pendingSelectionAnchor=a(K,this.ctx.uiState.state.selectedIndex),this.pendingHunkIndex=this.ctx.uiState.state.selectedHunkIndex,await J?.stage($);return}if(this.ctx.uiState.state.flatViewMode)await this.toggleCurrentHunkFlat();else await this.toggleCurrentHunkCategorized($)}async toggleCurrentHunkFlat(){let $=this.ctx.getCombinedHunkMapping()[this.ctx.uiState.state.selectedHunkIndex];if(!$)return;let J=this.ctx.getGitManager()?.workingTree,K=J?.state.combinedFileDiffs;if(!K)return;let X=$.source==="unstaged"?K.unstaged.raw:K.staged.raw,Q=v0(X,$.hunkIndex);if(!Q)return;if(this.pendingHunkIndex=this.ctx.uiState.state.selectedHunkIndex,$.source==="staged")await J?.unstageHunk(Q);else await J?.stageHunk(Q)}async toggleCurrentHunkCategorized($){let J=this.ctx.getGitManager()?.workingTree,K=J?.state.diff?.raw;if(!K)return;let X=v0(K,this.ctx.uiState.state.selectedHunkIndex);if(!X)return;let Q=J?.state.status?.files??[];if(this.pendingSelectionAnchor=a(Q,this.ctx.uiState.state.selectedIndex),$.staged)await J?.unstageHunk(X);else await J?.stageHunk(X)}}import n5 from"neo-blessed";class N0{box;screen;selectedIndex;currentTheme;onSelect;onCancel;constructor($,J,K,X){if(this.screen=$,this.currentTheme=J,this.onSelect=K,this.onCancel=X,this.selectedIndex=i.indexOf(J),this.selectedIndex<0)this.selectedIndex=0;let Q=50,q=i.length+12;this.box=n5.box({parent:$,top:"center",left:"center",width:Q,height:q,border:{type:"line"},style:{border:{fg:"cyan"}},tags:!0,keys:!0}),this.setupKeyHandlers(),this.render()}setupKeyHandlers(){this.box.key(["escape"],()=>{this.destroy(),this.onCancel()}),this.box.key(["enter","space"],()=>{let $=i[this.selectedIndex];this.destroy(),this.onSelect($)}),this.box.key(["up","k"],()=>{this.selectedIndex=Math.max(0,this.selectedIndex-1),this.render()}),this.box.key(["down","j"],()=>{this.selectedIndex=Math.min(i.length-1,this.selectedIndex+1),this.render()})}render(){let $=[];$.push("{bold}{cyan-fg} Select Theme{/cyan-fg}{/bold}"),$.push("");for(let J=0;J<i.length;J++){let K=i[J],X=L$[K],Q=J===this.selectedIndex,q=K===this.currentTheme,Z=Q?"{cyan-fg}{bold}> ":" ";if(Z+=X.displayName,Q)Z+="{/bold}{/cyan-fg}";if(q)Z+=" {gray-fg}(current){/gray-fg}";$.push(Z)}$.push(""),$.push("{gray-fg}Preview:{/gray-fg}"),$.push(" {green-fg}+ added line{/green-fg}"),$.push(" {red-fg}- deleted line{/red-fg}"),$.push(""),$.push("{gray-fg}j/k: navigate | Enter: select | Esc: cancel{/gray-fg}"),this.box.setContent($.join(`
35
- `)),this.screen.render()}destroy(){this.box.destroy()}focus(){this.box.focus()}}import i5 from"neo-blessed";var c=[{title:"Navigation",entries:[{key:"j/k",description:"Move up/down"},{key:"Tab",description:"Next focus zone"},{key:"Shift+Tab",description:"Previous focus zone"}]},{title:"Staging",entries:[{key:"s",description:"Stage file"},{key:"U",description:"Unstage file"},{key:"A",description:"Stage all"},{key:"Z",description:"Unstage all"},{key:"Space",description:"Toggle stage"}]},{title:"Actions",entries:[{key:"c",description:"Commit panel"},{key:"r",description:"Repo picker"},{key:"q",description:"Quit"}]},{title:"Resize",entries:[{key:"-",description:"Shrink top pane"},{key:"+",description:"Grow top pane"}]},{title:"Tabs",entries:[{key:"1",description:"Diff view"},{key:"2",description:"Commit panel"},{key:"3",description:"History view"},{key:"4",description:"Compare view"},{key:"5",description:"Explorer view"}]},{title:"Toggles",entries:[{key:"h",description:"Flat file view"},{key:"m",description:"Mouse mode"},{key:"w",description:"Wrap mode"},{key:"f",description:"Follow mode"},{key:"t",description:"Theme picker"},{key:"?",description:"This help"}]},{title:"Explorer",entries:[{key:"Enter",description:"Enter directory"},{key:"Backspace",description:"Go up"},{key:"/",description:"Find file"},{key:"Ctrl+P",description:"Find file (any tab)"},{key:"g",description:"Show changes only"}]},{title:"Commit Panel",entries:[{key:"i/Enter",description:"Edit message"},{key:"a",description:"Toggle amend"},{key:"Ctrl+a",description:"Toggle amend (typing)"}]},{title:"History",entries:[{key:"p",description:"Cherry-pick commit"},{key:"v",description:"Revert commit"}]},{title:"Compare",entries:[{key:"b",description:"Base branch picker"},{key:"u",description:"Toggle uncommitted"}]},{title:"Diff (pane focus)",entries:[{key:"n",description:"Next hunk"},{key:"N",description:"Previous hunk"},{key:"s",description:"Toggle hunk staged/unstaged"},{key:"d",description:"Discard changes"}]}];class E0{box;screen;onClose;screenClickHandler=null;constructor($,J){this.screen=$,this.onClose=J;let{width:K,height:X}=$,Q=K>=90,q=Q?Math.min(80,K-4):Math.min(42,K-4),Z=Math.min(this.calculateHeight(Q),X-4);this.box=i5.box({parent:$,top:"center",left:"center",width:q,height:Z,border:{type:"line"},style:{border:{fg:"cyan"}},tags:!0,keys:!0,scrollable:!0,alwaysScroll:!0}),this.setupKeyHandlers(),this.render(Q,q)}calculateHeight($){if($){let J=Math.ceil(c.length/2),K=c.slice(0,J),X=c.slice(J),Q=K.reduce((Z,V)=>Z+V.entries.length+2,0),q=X.reduce((Z,V)=>Z+V.entries.length+2,0);return Math.max(Q,q)+5}else return c.reduce((J,K)=>J+K.entries.length+2,0)+5}setupKeyHandlers(){this.box.key(["escape","enter"],()=>{this.destroy(),this.onClose()}),this.screenClickHandler=()=>{this.destroy(),this.onClose()},this.screen.on("click",this.screenClickHandler)}visibleWidth($){return $.replace(/\{[^}]+\}/g,"").length}padToVisible($,J){let K=this.visibleWidth($),X=Math.max(0,J-K);return $+" ".repeat(X)}render($,J){let K=[];if(K.push("{bold}{cyan-fg} Keyboard Shortcuts{/cyan-fg}{/bold}"),K.push(""),$){let X=Math.ceil(c.length/2),Q=c.slice(0,X),q=c.slice(X),Z=Math.floor((J-6)/2),V=this.renderGroups(Q,Z),Y=this.renderGroups(q,Z),z=Math.max(V.length,Y.length);for(let U=0;U<z;U++){let j=this.padToVisible(V[U]||"",Z),B=Y[U]||"";K.push(j+" "+B)}}else for(let X of c){K.push(`{bold}{gray-fg}${X.title}{/gray-fg}{/bold}`);for(let Q of X.entries)K.push(` {cyan-fg}${Q.key.padEnd(10)}{/cyan-fg} ${Q.description}`);K.push("")}K.push(""),K.push("{gray-fg}Press Esc, Enter, ?, or click to close{/gray-fg}"),this.box.setContent(K.join(`
36
- `)),this.screen.render()}renderGroups($,J){let K=[];for(let X of $){K.push(`{bold}{gray-fg}${X.title}{/gray-fg}{/bold}`);for(let Q of X.entries)K.push(` {cyan-fg}${Q.key.padEnd(10)}{/cyan-fg} ${Q.description}`);K.push("")}return K}destroy(){if(this.screenClickHandler)this.screen.removeListener("click",this.screenClickHandler),this.screenClickHandler=null;this.box.destroy()}focus(){this.box.focus()}}import t5 from"neo-blessed";class L0{box;screen;branches;selectedIndex;currentBranch;onSelect;onCancel;constructor($,J,K,X,Q){if(this.screen=$,this.branches=J,this.currentBranch=K,this.onSelect=X,this.onCancel=Q,this.selectedIndex=K?J.indexOf(K):0,this.selectedIndex<0)this.selectedIndex=0;let q=50,V=Math.min(J.length,15)+6;this.box=t5.box({parent:$,top:"center",left:"center",width:q,height:V,border:{type:"line"},style:{border:{fg:"cyan"}},tags:!0,keys:!0,scrollable:!0,alwaysScroll:!0}),this.setupKeyHandlers(),this.render()}setupKeyHandlers(){this.box.key(["escape"],()=>{this.destroy(),this.onCancel()}),this.box.key(["enter","space"],()=>{let $=this.branches[this.selectedIndex];if($)this.destroy(),this.onSelect($)}),this.box.key(["up","k"],()=>{this.selectedIndex=Math.max(0,this.selectedIndex-1),this.render()}),this.box.key(["down","j"],()=>{this.selectedIndex=Math.min(this.branches.length-1,this.selectedIndex+1),this.render()})}render(){let $=[];if($.push("{bold}{cyan-fg} Select Base Branch{/cyan-fg}{/bold}"),$.push(""),this.branches.length===0)$.push("{gray-fg}No branches found{/gray-fg}");else for(let J=0;J<this.branches.length;J++){let K=this.branches[J],X=J===this.selectedIndex,Q=K===this.currentBranch,q=X?"{cyan-fg}{bold}> ":" ";if(q+=K,X)q+="{/bold}{/cyan-fg}";if(Q)q+=" {gray-fg}(current){/gray-fg}";$.push(q)}$.push(""),$.push("{gray-fg}j/k: navigate | Enter: select | Esc: cancel{/gray-fg}"),this.box.setContent($.join(`
37
- `)),this.screen.render()}destroy(){this.box.destroy()}focus(){this.box.focus()}}import e5 from"neo-blessed";class F0{box;screen;filePath;onConfirm;onCancel;constructor($,J,K,X){this.screen=$,this.filePath=J,this.onConfirm=K,this.onCancel=X;let Q=Math.min(60,Math.max(40,J.length+20)),q=7;this.box=e5.box({parent:$,top:"center",left:"center",width:Q,height:q,border:{type:"line"},style:{border:{fg:"yellow"}},tags:!0,keys:!0}),this.setupKeyHandlers(),this.render()}setupKeyHandlers(){this.box.key(["y","Y"],()=>{this.destroy(),this.onConfirm()}),this.box.key(["n","N","escape"],()=>{this.destroy(),this.onCancel()})}render(){let $=[];$.push("{bold}{yellow-fg} Discard Changes?{/yellow-fg}{/bold}"),$.push("");let J=this.box.width-6,K=this.filePath.length>J?"..."+this.filePath.slice(-(J-3)):this.filePath;$.push(`{white-fg}${K}{/white-fg}`),$.push(""),$.push("{gray-fg}Press {/gray-fg}{green-fg}y{/green-fg}{gray-fg} to confirm, {/gray-fg}{red-fg}n{/red-fg}{gray-fg} or Esc to cancel{/gray-fg}"),this.box.setContent($.join(`
38
- `)),this.screen.render()}destroy(){this.box.destroy()}focus(){this.box.focus()}}import n1 from"neo-blessed";import{Fzf as $9}from"fzf";var m$=15,J9=15;function K9($,J,K){let X="";for(let Q=0;Q<$.length;Q++)if(J.has(Q+K))X+=`{yellow-fg}${$[Q]}{/yellow-fg}`;else X+=$[Q];return X}class R0{box;textbox;screen;allPaths;results=[];selectedIndex=0;query="";onSelect;onCancel;debounceTimer=null;fzf;constructor($,J,K,X){this.screen=$,this.allPaths=J,this.onSelect=K,this.onCancel=X,this.fzf=new $9(J,{limit:m$,casing:"smart-case"});let Q=Math.min(80,$.width-10),q=m$+6;this.box=n1.box({parent:$,top:"center",left:"center",width:Q,height:q,border:{type:"line"},style:{border:{fg:"cyan"}},tags:!0,keys:!1}),this.textbox=n1.textarea({parent:this.box,top:1,left:1,width:Q-4,height:1,inputOnFocus:!0,style:{fg:"white",bg:"default"}}),this.setupKeyHandlers(),this.updateResults(),this.renderContent()}setupKeyHandlers(){this.textbox.key(["escape"],()=>{this.destroy(),this.onCancel()}),this.textbox.key(["enter"],()=>{if(this.results.length>0){let $=this.results[this.selectedIndex];this.destroy(),this.onSelect($.path)}}),this.textbox.key(["C-j","down"],()=>{this.selectedIndex=Math.min(this.results.length-1,this.selectedIndex+1),this.renderContent()}),this.textbox.key(["C-k","up"],()=>{this.selectedIndex=Math.max(0,this.selectedIndex-1),this.renderContent()}),this.textbox.key(["tab"],()=>{this.selectedIndex=(this.selectedIndex+1)%Math.max(1,this.results.length),this.renderContent()}),this.textbox.key(["S-tab"],()=>{this.selectedIndex=(this.selectedIndex-1+this.results.length)%Math.max(1,this.results.length),this.renderContent()}),this.textbox.on("keypress",()=>{if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{let $=this.textbox.getValue()||"";if($!==this.query)this.query=$,this.selectedIndex=0,this.updateResults(),this.renderContent()},J9)})}updateResults(){if(!this.query){this.results=this.allPaths.slice(0,m$).map((J)=>({path:J,positions:new Set,score:0}));return}let $=this.fzf.find(this.query);this.results=$.map((J)=>({path:J.item,score:J.score,positions:J.positions}))}renderContent(){let $=[],J=this.box.width-4;if($.push("{bold}{cyan-fg}Find File{/cyan-fg}{/bold}"),$.push(""),$.push(""),this.results.length===0&&this.query)$.push("{gray-fg}No matches{/gray-fg}");else for(let K=0;K<this.results.length;K++){let X=this.results[K],Q=K===this.selectedIndex,q=X.path,Z=J-4,V=q,Y=0;if(V.length>Z)Y=V.length-(Z-1),V="…"+V.slice(Y),Y=Y-1;let z=K9(V,X.positions,Y);if(Q)$.push(`{cyan-fg}{bold}> ${z}{/bold}{/cyan-fg}`);else $.push(` ${z}`)}while($.length<m$+3)$.push("");$.push("{gray-fg}Enter: select | Esc: cancel | Ctrl+j/k or ↑↓: navigate{/gray-fg}"),this.box.setContent($.join(`
39
- `)),this.screen.render()}destroy(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.textbox.destroy(),this.box.destroy()}focus(){this.textbox.focus()}}import X9 from"neo-blessed";class f${box;screen;onConfirm;onCancel;constructor($,J,K,X,Q){this.screen=$,this.onConfirm=X,this.onCancel=Q;let q=Math.min(60,$.width-6),Z=8;this.box=X9.box({parent:$,top:"center",left:"center",width:q,height:Z,border:{type:"line"},style:{border:{fg:"yellow"}},tags:!0,keys:!0}),this.setupKeyHandlers(),this.renderContent(J,K,q)}setupKeyHandlers(){this.box.key(["y","Y"],()=>{this.destroy(),this.onConfirm()}),this.box.key(["n","N","escape"],()=>{this.destroy(),this.onCancel()})}renderContent($,J,K){let X=[],Q=K-6;X.push(`{bold}{yellow-fg} ${$} commit?{/yellow-fg}{/bold}`),X.push("");let q=J.message.length>Q?J.message.slice(0,Q-3)+"…":J.message;X.push(`{yellow-fg}${J.shortHash}{/yellow-fg} ${q}`),X.push(""),X.push("{gray-fg}Press {/gray-fg}{green-fg}y{/green-fg}{gray-fg} to confirm, {/gray-fg}{red-fg}n{/red-fg}{gray-fg} or Esc to cancel{/gray-fg}"),this.box.setContent(X.join(`
40
- `)),this.screen.render()}destroy(){this.box.destroy()}focus(){this.box.focus()}}import V9 from"neo-blessed";import*as I from"node:fs";import*as Q$ from"node:path";import*as h$ from"node:os";var Q9={targetFile:Q$.join(h$.homedir(),".cache","diffstalker","target"),watcherEnabled:!1,debug:!1,theme:"dark"},d=Q$.join(h$.homedir(),".config","diffstalker","config.json"),q9=["dark","light","dark-colorblind","light-colorblind","dark-ansi","light-ansi"];function Z9($){return typeof $==="string"&&q9.includes($)}function i1(){let $={...Q9};if(process.env.DIFFSTALKER_PAGER)$.pager=process.env.DIFFSTALKER_PAGER;if(I.existsSync(d))try{let J=JSON.parse(I.readFileSync(d,"utf-8"));if(J.pager)$.pager=J.pager;if(J.targetFile)$.targetFile=J.targetFile;if(Z9(J.theme))$.theme=J.theme;if(typeof J.splitRatio==="number"&&J.splitRatio>=0.15&&J.splitRatio<=0.85)$.splitRatio=J.splitRatio;if(typeof J.autoTabEnabled==="boolean")$.autoTabEnabled=J.autoTabEnabled;if(typeof J.wrapMode==="boolean")$.wrapMode=J.wrapMode;if(typeof J.mouseEnabled==="boolean")$.mouseEnabled=J.mouseEnabled;if(Array.isArray(J.recentRepos)&&J.recentRepos.every((K)=>typeof K==="string"))$.recentRepos=J.recentRepos;if(typeof J.maxRecentRepos==="number"&&J.maxRecentRepos>=1&&J.maxRecentRepos<=50)$.maxRecentRepos=J.maxRecentRepos}catch{}return $}function M$($){let J=Q$.dirname(d);if(!I.existsSync(J))I.mkdirSync(J,{recursive:!0});let K={};if(I.existsSync(d))try{K=JSON.parse(I.readFileSync(d,"utf-8"))}catch{}Object.assign(K,$),I.writeFileSync(d,JSON.stringify(K,null,2)+`
41
- `)}function t1($){let J=Q$.dirname($);if(!I.existsSync(J))I.mkdirSync(J,{recursive:!0})}function c$($){let J=h$.homedir();if($.startsWith(J))return"~"+$.slice(J.length);return $}function I0($){return $.length>1&&$.endsWith("/")?$.slice(0,-1):$}function e1($,J=10){let K=I0($),X=[];if(I.existsSync(d))try{let q=JSON.parse(I.readFileSync(d,"utf-8"));if(Array.isArray(q.recentRepos))X=q.recentRepos}catch{}let Q=X.filter((q)=>I0(q)!==K);M$({recentRepos:[K,...Q.map(I0)].slice(0,J)})}class y0{box;screen;repos;selectedIndex;currentRepo;onSelect;onCancel;constructor($,J,K,X,Q){if(this.screen=$,this.repos=J,this.currentRepo=K,this.onSelect=X,this.onCancel=Q,this.selectedIndex=J.indexOf(K),this.selectedIndex<0)this.selectedIndex=0;let q=$.width,Z=Math.min(70,q-4),Y=Math.min(J.length,15)+6;this.box=V9.box({parent:$,top:"center",left:"center",width:Z,height:Y,border:{type:"line"},style:{border:{fg:"cyan"}},tags:!0,keys:!0,scrollable:!0,alwaysScroll:!0}),this.setupKeyHandlers(),this.render()}setupKeyHandlers(){this.box.key(["escape"],()=>{this.destroy(),this.onCancel()}),this.box.key(["enter","space"],()=>{let $=this.repos[this.selectedIndex];if($)this.destroy(),this.onSelect($)}),this.box.key(["up","k"],()=>{this.selectedIndex=Math.max(0,this.selectedIndex-1),this.render()}),this.box.key(["down","j"],()=>{this.selectedIndex=Math.min(this.repos.length-1,this.selectedIndex+1),this.render()})}render(){let $=[];if($.push("{bold}{cyan-fg} Recent Repositories{/cyan-fg}{/bold}"),$.push(""),this.repos.length===0)$.push("{gray-fg}No recent repositories{/gray-fg}");else for(let J=0;J<this.repos.length;J++){let K=this.repos[J],X=J===this.selectedIndex,Q=K===this.currentRepo,q=X?"{cyan-fg}{bold}> ":" ";if(q+=c$(K),X)q+="{/bold}{/cyan-fg}";if(Q)q+=" {gray-fg}(current){/gray-fg}";$.push(q)}$.push(""),$.push("{gray-fg}j/k: navigate | Enter: select | Esc: cancel{/gray-fg}"),this.box.setContent($.join(`
42
- `)),this.screen.render()}destroy(){this.box.destroy()}focus(){this.box.focus()}}var Y9=!1;function $8($){Y9=$}function q$($){process.stderr.write(`[diffstalker warn] ${$}
43
- `)}function z9($){if($ instanceof Error)return $.message;if($)return String($);return""}function J8($,J){let K=J?`: ${z9(J)}`:"";process.stderr.write(`[diffstalker error] ${$}${K}
44
- `)}class P0{ctx;activeModal=null;activeModalType=null;constructor($){this.ctx=$}hasActiveModal(){return this.activeModal!==null}getActiveModalType(){return this.activeModalType}closeActiveModal(){if(this.activeModal)this.activeModal.destroy(),this.activeModal=null,this.activeModalType=null,this.ctx.render()}clearModal(){this.activeModal=null,this.activeModalType=null}openThemePicker(){this.activeModalType="theme",this.activeModal=new N0(this.ctx.screen,this.ctx.getCurrentTheme(),($)=>{this.ctx.setCurrentTheme($),M$({theme:$}),this.clearModal(),this.ctx.render()},()=>{this.clearModal()}),this.activeModal.focus()}openHotkeysModal(){this.activeModalType="hotkeys",this.activeModal=new E0(this.ctx.screen,()=>{this.clearModal()}),this.activeModal.focus()}openBaseBranchPicker(){let $=this.ctx.getGitManager();if(!$)return;this.activeModalType="baseBranch",$.compare.getCandidateBaseBranches().then((J)=>{let K=$.compare.compareState.compareBaseBranch??null,X=new L0(this.ctx.screen,J,K,(Q)=>{this.clearModal();let q=this.ctx.uiState.state.includeUncommitted;$.compare.setCompareBaseBranch(Q,q)},()=>{this.clearModal()});this.activeModal=X,X.focus()}).catch((J)=>{this.clearModal(),J8("Failed to load base branches",J)})}openDiscardConfirm($){this.activeModalType="discard",this.activeModal=new F0(this.ctx.screen,$.path,async()=>{this.clearModal(),await this.ctx.getGitManager()?.workingTree.discard($)},()=>{this.clearModal()}),this.activeModal.focus()}async openFileFinder(){let $=this.ctx.getExplorerManager(),J=$?.getCachedFilePaths()??[];if(J.length===0)await $?.loadFilePaths(),J=$?.getCachedFilePaths()??[];if(J.length===0)return;this.activeModalType="fileFinder",this.activeModal=new R0(this.ctx.screen,J,async(K)=>{if(this.clearModal(),this.ctx.uiState.state.bottomTab!=="explorer")this.ctx.uiState.setTab("explorer");if(await $?.navigateToPath(K)){let Q=$?.state.selectedIndex??0;this.ctx.uiState.setExplorerSelectedIndex(Q),this.ctx.uiState.setExplorerFileScrollOffset(0);let q=this.ctx.getTopPaneHeight();if(Q>=q)this.ctx.uiState.setExplorerScrollOffset(Q-Math.floor(q/2));else this.ctx.uiState.setExplorerScrollOffset(0)}this.ctx.render()},()=>{this.clearModal(),this.ctx.render()}),this.activeModal.focus()}openCherryPickConfirm(){let $=this.ctx.getGitManager()?.history.historyState.selectedCommit;if(!$)return;this.activeModalType="commitAction",this.activeModal=new f$(this.ctx.screen,"Cherry-pick",$,()=>{this.clearModal(),this.ctx.getGitManager()?.remote.cherryPick($.hash)},()=>{this.clearModal()}),this.activeModal.focus()}openRevertConfirm(){let $=this.ctx.getGitManager()?.history.historyState.selectedCommit;if(!$)return;this.activeModalType="commitAction",this.activeModal=new f$(this.ctx.screen,"Revert",$,()=>{this.clearModal(),this.ctx.getGitManager()?.remote.revertCommit($.hash)},()=>{this.clearModal()}),this.activeModal.focus()}openRepoPicker(){let $=this.ctx.getRecentRepos(),J=this.ctx.getRepoPath();this.activeModalType="repoPicker",this.activeModal=new y0(this.ctx.screen,$,J,(K)=>{this.clearModal(),this.ctx.onRepoSwitch(K)},()=>{this.clearModal(),this.ctx.render()}),this.activeModal.focus()}}import*as t from"node:fs";import*as d$ from"node:path";import{watch as U9}from"chokidar";import{EventEmitter as B9}from"node:events";import*as K8 from"node:path";import*as b0 from"node:os";function X8($){if($.startsWith("~/"))return K8.join(b0.homedir(),$.slice(2));if($==="~")return b0.homedir();return $}function S0($){let J=$.split(`
45
- `);for(let K=J.length-1;K>=0;K--){let X=J[K].trim();if(X)return X}return""}class w0 extends B9{targetFile;debug;watcher=null;debounceTimer=null;lastReadPath=null;_state={path:null,lastUpdate:null,rawContent:null,sourceFile:null};constructor($,J=!1){super();this.targetFile=$,this.debug=J,this._state.sourceFile=$}get state(){return this._state}updateState($){this._state={...this._state,...$},this.emit("path-change",this._state)}processContent($){if(!$)return null;let J=X8($);return d$.isAbsolute(J)?J:d$.resolve(J)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let $=t.readFileSync(this.targetFile,"utf-8"),J=S0($);if(J&&J!==this.lastReadPath){let K=this.processContent(J),X=new Date;if(this.debug&&K)process.stderr.write(`[diffstalker ${X.toISOString()}] Path change detected
34
+ `).filter((_)=>_)){let _=O.split("\t");if(_.length>=3){let A=_[0]==="-"?0:parseInt(_[0],10),y=_[1]==="-"?0:parseInt(_[1],10),k=_.slice(2).join("\t"),L=Y.get(k);if(L)L.additions+=A,L.deletions+=y,L.unstaged=!0;else Y.set(k,{additions:A,deletions:y,staged:!1,unstaged:!0})}}let z=await K.status(),U=new Map;for(let O of z.files)if(O.index==="A"||O.working_dir==="?")U.set(O.path,"added");else if(O.index==="D"||O.working_dir==="D")U.set(O.path,"deleted");else if(O.index==="R")U.set(O.path,"renamed");else U.set(O.path,"modified");let j=[],G=(Z+V).split(/(?=^diff --git )/m).filter((O)=>O.trim()),M=new Set;for(let O of G){let _=O.match(/^diff --git a\/.+ b\/(.+)$/m);if(!_)continue;let A=_[1];if(M.has(A))continue;M.add(A);let y=g$(O),k=Y.get(A)||{additions:0,deletions:0},L=U.get(A)||"modified";j.push({path:A,status:L,additions:k.additions,deletions:k.deletions,diff:{raw:O,lines:y},isUncommitted:!0})}let v=new Set(X.files.map((O)=>O.path)),D=[];for(let O of X.files){let _=j.find((A)=>A.path===O.path);if(_)D.push(O),D.push(_);else D.push(O)}for(let O of j)if(!v.has(O.path))D.push(O);let T=0,H=0,E=new Set;for(let O of D)E.add(O.path),T+=O.additions,H+=O.deletions;return D.sort((O,_)=>O.path.localeCompare(_.path)),{baseBranch:X.baseBranch,stats:{filesChanged:E.size,additions:T,deletions:H},files:D,commits:X.commits,uncommittedCount:X.uncommittedCount}}class k0{ctx;pendingSelectionAnchor=null;pendingFlatSelectionPath=null;pendingHunkIndex=null;constructor($){this.ctx=$}consumePendingSelectionAnchor(){let $=this.pendingSelectionAnchor;return this.pendingSelectionAnchor=null,$}consumePendingFlatSelectionPath(){let $=this.pendingFlatSelectionPath;return this.pendingFlatSelectionPath=null,$}consumePendingHunkIndex(){let $=this.pendingHunkIndex;return this.pendingHunkIndex=null,$}async stageSelected(){let J=this.ctx.getGitManager()?.workingTree,K=J?.state.status?.files??[],X=this.ctx.uiState.state.selectedIndex;if(this.ctx.uiState.state.flatViewMode){let Q=p(this.ctx.getCachedFlatFiles(),X);if(!Q)return;let q=Q.unstagedEntry;if(q)this.pendingFlatSelectionPath=Q.path,await J?.stage(q)}else{let Q=this.ctx.resolveFileAtIndex(X);if(Q&&!Q.staged)this.pendingSelectionAnchor=n(K,X),await J?.stage(Q)}}async unstageSelected(){let J=this.ctx.getGitManager()?.workingTree,K=J?.state.status?.files??[],X=this.ctx.uiState.state.selectedIndex;if(this.ctx.uiState.state.flatViewMode){let Q=p(this.ctx.getCachedFlatFiles(),X);if(!Q)return;let q=Q.stagedEntry;if(q)this.pendingFlatSelectionPath=Q.path,await J?.unstage(q)}else{let Q=this.ctx.resolveFileAtIndex(X);if(Q?.staged)this.pendingSelectionAnchor=n(K,X),await J?.unstage(Q)}}async toggleSelected(){let $=this.ctx.uiState.state.selectedIndex;if(this.ctx.uiState.state.flatViewMode){let J=p(this.ctx.getCachedFlatFiles(),$);if(J)await this.toggleFlatEntry(J)}else{let K=this.ctx.getGitManager()?.workingTree,X=K?.state.status?.files??[],Q=this.ctx.resolveFileAtIndex($);if(Q)if(this.pendingSelectionAnchor=n(X,$),Q.staged)await K?.unstage(Q);else await K?.stage(Q)}}async stageAll(){await this.ctx.getGitManager()?.workingTree.stageAll()}async unstageAll(){await this.ctx.getGitManager()?.workingTree.unstageAll()}async toggleFlatEntry($){let J=this.ctx.getGitManager()?.workingTree;if(this.pendingFlatSelectionPath=$.path,$.stagingState==="staged"){if($.stagedEntry)await J?.unstage($.stagedEntry)}else if($.unstagedEntry)await J?.stage($.unstagedEntry)}async toggleFileByIndex($){if(this.ctx.uiState.state.flatViewMode){let J=p(this.ctx.getCachedFlatFiles(),$);if(J)await this.toggleFlatEntry(J)}else{let K=this.ctx.getGitManager()?.workingTree,X=K?.state.status?.files??[],Q=this.ctx.resolveFileAtIndex($);if(Q)if(this.pendingSelectionAnchor=n(X,this.ctx.uiState.state.selectedIndex),Q.staged)await K?.unstage(Q);else await K?.stage(Q)}}async toggleCurrentHunk(){let $=this.ctx.getGitManager()?.workingTree.state.selectedFile;if(!$)return;if($.status==="untracked"){let J=this.ctx.getGitManager()?.workingTree,K=J?.state.status?.files??[];this.pendingSelectionAnchor=n(K,this.ctx.uiState.state.selectedIndex),this.pendingHunkIndex=this.ctx.uiState.state.selectedHunkIndex,await J?.stage($);return}if(this.ctx.uiState.state.flatViewMode)await this.toggleCurrentHunkFlat();else await this.toggleCurrentHunkCategorized($)}async toggleCurrentHunkFlat(){let $=this.ctx.getCombinedHunkMapping()[this.ctx.uiState.state.selectedHunkIndex];if(!$)return;let J=this.ctx.getGitManager()?.workingTree,K=J?.state.combinedFileDiffs;if(!K)return;let X=$.source==="unstaged"?K.unstaged.raw:K.staged.raw,Q=W0(X,$.hunkIndex);if(!Q)return;if(this.pendingHunkIndex=this.ctx.uiState.state.selectedHunkIndex,$.source==="staged")await J?.unstageHunk(Q);else await J?.stageHunk(Q)}async toggleCurrentHunkCategorized($){let J=this.ctx.getGitManager()?.workingTree,K=J?.state.diff?.raw;if(!K)return;let X=W0(K,this.ctx.uiState.state.selectedHunkIndex);if(!X)return;let Q=J?.state.status?.files??[];if(this.pendingSelectionAnchor=n(Q,this.ctx.uiState.state.selectedIndex),$.staged)await J?.unstageHunk(X);else await J?.stageHunk(X)}}import n5 from"neo-blessed";class N0{box;screen;selectedIndex;currentTheme;onSelect;onCancel;constructor($,J,K,X){if(this.screen=$,this.currentTheme=J,this.onSelect=K,this.onCancel=X,this.selectedIndex=t.indexOf(J),this.selectedIndex<0)this.selectedIndex=0;let Q=50,q=t.length+12;this.box=n5.box({parent:$,top:"center",left:"center",width:Q,height:q,border:{type:"line"},style:{border:{fg:"cyan"}},tags:!0,keys:!0}),this.setupKeyHandlers(),this.render()}setupKeyHandlers(){this.box.key(["escape"],()=>{this.destroy(),this.onCancel()}),this.box.key(["enter","space"],()=>{let $=t[this.selectedIndex];this.destroy(),this.onSelect($)}),this.box.key(["up","k"],()=>{this.selectedIndex=Math.max(0,this.selectedIndex-1),this.render()}),this.box.key(["down","j"],()=>{this.selectedIndex=Math.min(t.length-1,this.selectedIndex+1),this.render()})}render(){let $=[];$.push("{bold}{cyan-fg} Select Theme{/cyan-fg}{/bold}"),$.push("");for(let J=0;J<t.length;J++){let K=t[J],X=L$[K],Q=J===this.selectedIndex,q=K===this.currentTheme,Z=Q?"{cyan-fg}{bold}> ":" ";if(Z+=X.displayName,Q)Z+="{/bold}{/cyan-fg}";if(q)Z+=" {gray-fg}(current){/gray-fg}";$.push(Z)}$.push(""),$.push("{gray-fg}Preview:{/gray-fg}"),$.push(" {green-fg}+ added line{/green-fg}"),$.push(" {red-fg}- deleted line{/red-fg}"),$.push(""),$.push("{gray-fg}j/k: navigate | Enter: select | Esc: cancel{/gray-fg}"),this.box.setContent($.join(`
35
+ `)),this.screen.render()}destroy(){this.box.destroy()}focus(){this.box.focus()}}import{createRequire as i5}from"node:module";import t5 from"neo-blessed";var e5=i5(import.meta.url),{version:$9}=e5("../../../package.json"),c=[{title:"Navigation",entries:[{key:"j/k",description:"Move up/down"},{key:"Tab",description:"Next focus zone"},{key:"Shift+Tab",description:"Previous focus zone"}]},{title:"Staging",entries:[{key:"s",description:"Stage file"},{key:"U",description:"Unstage file"},{key:"A",description:"Stage all"},{key:"Z",description:"Unstage all"},{key:"Space",description:"Toggle stage"}]},{title:"Actions",entries:[{key:"c",description:"Commit panel"},{key:"r",description:"Repo picker"},{key:"q",description:"Quit"}]},{title:"Resize",entries:[{key:"-",description:"Shrink top pane"},{key:"+",description:"Grow top pane"}]},{title:"Tabs",entries:[{key:"1",description:"Diff view"},{key:"2",description:"Commit panel"},{key:"3",description:"History view"},{key:"4",description:"Compare view"},{key:"5",description:"Explorer view"}]},{title:"Toggles",entries:[{key:"h",description:"Flat file view"},{key:"m",description:"Mouse mode"},{key:"w",description:"Wrap mode"},{key:"f",description:"Follow mode"},{key:"t",description:"Theme picker"},{key:"?",description:"This help"}]},{title:"Explorer",entries:[{key:"Enter",description:"Enter directory"},{key:"Backspace",description:"Go up"},{key:"/",description:"Find file"},{key:"Ctrl+P",description:"Find file (any tab)"},{key:"g",description:"Show changes only"}]},{title:"Commit Panel",entries:[{key:"i/Enter",description:"Edit message"},{key:"a",description:"Toggle amend"},{key:"Ctrl+a",description:"Toggle amend (typing)"}]},{title:"History",entries:[{key:"p",description:"Cherry-pick commit"},{key:"v",description:"Revert commit"}]},{title:"Compare",entries:[{key:"b",description:"Base branch picker"},{key:"u",description:"Toggle uncommitted"}]},{title:"Diff (pane focus)",entries:[{key:"n",description:"Next hunk"},{key:"N",description:"Previous hunk"},{key:"s",description:"Toggle hunk staged/unstaged"},{key:"d",description:"Discard changes"}]}];class E0{box;screen;onClose;screenClickHandler=null;constructor($,J){this.screen=$,this.onClose=J;let{width:K,height:X}=$,Q=K>=90,q=Q?Math.min(80,K-4):Math.min(42,K-4),Z=Math.min(this.calculateHeight(Q),X-4);this.box=t5.box({parent:$,top:"center",left:"center",width:q,height:Z,border:{type:"line"},style:{border:{fg:"cyan"}},tags:!0,keys:!0,scrollable:!0,alwaysScroll:!0}),this.setupKeyHandlers(),this.render(Q,q)}calculateHeight($){if($){let J=Math.ceil(c.length/2),K=c.slice(0,J),X=c.slice(J),Q=K.reduce((Z,V)=>Z+V.entries.length+2,0),q=X.reduce((Z,V)=>Z+V.entries.length+2,0);return Math.max(Q,q)+5}else return c.reduce((J,K)=>J+K.entries.length+2,0)+5}setupKeyHandlers(){this.box.key(["escape","enter"],()=>{this.destroy(),this.onClose()}),this.screenClickHandler=()=>{this.destroy(),this.onClose()},this.screen.on("click",this.screenClickHandler)}visibleWidth($){return $.replace(/\{[^}]+\}/g,"").length}padToVisible($,J){let K=this.visibleWidth($),X=Math.max(0,J-K);return $+" ".repeat(X)}render($,J){let K=[];if(K.push("{bold}{cyan-fg} Keyboard Shortcuts{/cyan-fg}{/bold}"),K.push(""),$){let V=Math.ceil(c.length/2),Y=c.slice(0,V),z=c.slice(V),U=Math.floor((J-6)/2),j=this.renderGroups(Y,U),B=this.renderGroups(z,U),G=Math.max(j.length,B.length);for(let M=0;M<G;M++){let v=this.padToVisible(j[M]||"",U),D=B[M]||"";K.push(v+" "+D)}}else for(let V of c){K.push(`{bold}{gray-fg}${V.title}{/gray-fg}{/bold}`);for(let Y of V.entries)K.push(` {cyan-fg}${Y.key.padEnd(10)}{/cyan-fg} ${Y.description}`);K.push("")}K.push("");let X="Press Esc, Enter, ?, or click to close",Q=`v${$9}`,q=J-4,Z=Math.max(1,q-X.length-Q.length);K.push(`{gray-fg}${X}${" ".repeat(Z)}${Q}{/gray-fg}`),this.box.setContent(K.join(`
36
+ `)),this.screen.render()}renderGroups($,J){let K=[];for(let X of $){K.push(`{bold}{gray-fg}${X.title}{/gray-fg}{/bold}`);for(let Q of X.entries)K.push(` {cyan-fg}${Q.key.padEnd(10)}{/cyan-fg} ${Q.description}`);K.push("")}return K}destroy(){if(this.screenClickHandler)this.screen.removeListener("click",this.screenClickHandler),this.screenClickHandler=null;this.box.destroy()}focus(){this.box.focus()}}import J9 from"neo-blessed";class L0{box;screen;branches;selectedIndex;currentBranch;onSelect;onCancel;constructor($,J,K,X,Q){if(this.screen=$,this.branches=J,this.currentBranch=K,this.onSelect=X,this.onCancel=Q,this.selectedIndex=K?J.indexOf(K):0,this.selectedIndex<0)this.selectedIndex=0;let q=50,V=Math.min(J.length,15)+6;this.box=J9.box({parent:$,top:"center",left:"center",width:q,height:V,border:{type:"line"},style:{border:{fg:"cyan"}},tags:!0,keys:!0,scrollable:!0,alwaysScroll:!0}),this.setupKeyHandlers(),this.render()}setupKeyHandlers(){this.box.key(["escape"],()=>{this.destroy(),this.onCancel()}),this.box.key(["enter","space"],()=>{let $=this.branches[this.selectedIndex];if($)this.destroy(),this.onSelect($)}),this.box.key(["up","k"],()=>{this.selectedIndex=Math.max(0,this.selectedIndex-1),this.render()}),this.box.key(["down","j"],()=>{this.selectedIndex=Math.min(this.branches.length-1,this.selectedIndex+1),this.render()})}render(){let $=[];if($.push("{bold}{cyan-fg} Select Base Branch{/cyan-fg}{/bold}"),$.push(""),this.branches.length===0)$.push("{gray-fg}No branches found{/gray-fg}");else for(let J=0;J<this.branches.length;J++){let K=this.branches[J],X=J===this.selectedIndex,Q=K===this.currentBranch,q=X?"{cyan-fg}{bold}> ":" ";if(q+=K,X)q+="{/bold}{/cyan-fg}";if(Q)q+=" {gray-fg}(current){/gray-fg}";$.push(q)}$.push(""),$.push("{gray-fg}j/k: navigate | Enter: select | Esc: cancel{/gray-fg}"),this.box.setContent($.join(`
37
+ `)),this.screen.render()}destroy(){this.box.destroy()}focus(){this.box.focus()}}import K9 from"neo-blessed";class F0{box;screen;filePath;onConfirm;onCancel;constructor($,J,K,X){this.screen=$,this.filePath=J,this.onConfirm=K,this.onCancel=X;let Q=Math.min(60,Math.max(40,J.length+20)),q=7;this.box=K9.box({parent:$,top:"center",left:"center",width:Q,height:q,border:{type:"line"},style:{border:{fg:"yellow"}},tags:!0,keys:!0}),this.setupKeyHandlers(),this.render()}setupKeyHandlers(){this.box.key(["y","Y"],()=>{this.destroy(),this.onConfirm()}),this.box.key(["n","N","escape"],()=>{this.destroy(),this.onCancel()})}render(){let $=[];$.push("{bold}{yellow-fg} Discard Changes?{/yellow-fg}{/bold}"),$.push("");let J=this.box.width-6,K=this.filePath.length>J?"..."+this.filePath.slice(-(J-3)):this.filePath;$.push(`{white-fg}${K}{/white-fg}`),$.push(""),$.push("{gray-fg}Press {/gray-fg}{green-fg}y{/green-fg}{gray-fg} to confirm, {/gray-fg}{red-fg}n{/red-fg}{gray-fg} or Esc to cancel{/gray-fg}"),this.box.setContent($.join(`
38
+ `)),this.screen.render()}destroy(){this.box.destroy()}focus(){this.box.focus()}}import n1 from"neo-blessed";import{Fzf as X9}from"fzf";var m$=15,Q9=15;function q9($,J,K){let X="";for(let Q=0;Q<$.length;Q++)if(J.has(Q+K))X+=`{yellow-fg}${$[Q]}{/yellow-fg}`;else X+=$[Q];return X}class R0{box;textbox;screen;allPaths;results=[];selectedIndex=0;query="";onSelect;onCancel;debounceTimer=null;fzf;constructor($,J,K,X){this.screen=$,this.allPaths=J,this.onSelect=K,this.onCancel=X,this.fzf=new X9(J,{limit:m$,casing:"smart-case"});let Q=Math.min(80,$.width-10),q=m$+6;this.box=n1.box({parent:$,top:"center",left:"center",width:Q,height:q,border:{type:"line"},style:{border:{fg:"cyan"}},tags:!0,keys:!1}),this.textbox=n1.textarea({parent:this.box,top:1,left:1,width:Q-4,height:1,inputOnFocus:!0,style:{fg:"white",bg:"default"}}),this.setupKeyHandlers(),this.updateResults(),this.renderContent()}setupKeyHandlers(){this.textbox.key(["escape"],()=>{this.destroy(),this.onCancel()}),this.textbox.key(["enter"],()=>{if(this.results.length>0){let $=this.results[this.selectedIndex];this.destroy(),this.onSelect($.path)}}),this.textbox.key(["C-j","down"],()=>{this.selectedIndex=Math.min(this.results.length-1,this.selectedIndex+1),this.renderContent()}),this.textbox.key(["C-k","up"],()=>{this.selectedIndex=Math.max(0,this.selectedIndex-1),this.renderContent()}),this.textbox.key(["tab"],()=>{this.selectedIndex=(this.selectedIndex+1)%Math.max(1,this.results.length),this.renderContent()}),this.textbox.key(["S-tab"],()=>{this.selectedIndex=(this.selectedIndex-1+this.results.length)%Math.max(1,this.results.length),this.renderContent()}),this.textbox.on("keypress",()=>{if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{let $=this.textbox.getValue()||"";if($!==this.query)this.query=$,this.selectedIndex=0,this.updateResults(),this.renderContent()},Q9)})}updateResults(){if(!this.query){this.results=this.allPaths.slice(0,m$).map((J)=>({path:J,positions:new Set,score:0}));return}let $=this.fzf.find(this.query);this.results=$.map((J)=>({path:J.item,score:J.score,positions:J.positions}))}renderContent(){let $=[],J=this.box.width-4;if($.push("{bold}{cyan-fg}Find File{/cyan-fg}{/bold}"),$.push(""),$.push(""),this.results.length===0&&this.query)$.push("{gray-fg}No matches{/gray-fg}");else for(let K=0;K<this.results.length;K++){let X=this.results[K],Q=K===this.selectedIndex,q=X.path,Z=J-4,V=q,Y=0;if(V.length>Z)Y=V.length-(Z-1),V="…"+V.slice(Y),Y=Y-1;let z=q9(V,X.positions,Y);if(Q)$.push(`{cyan-fg}{bold}> ${z}{/bold}{/cyan-fg}`);else $.push(` ${z}`)}while($.length<m$+3)$.push("");$.push("{gray-fg}Enter: select | Esc: cancel | Ctrl+j/k or ↑↓: navigate{/gray-fg}"),this.box.setContent($.join(`
39
+ `)),this.screen.render()}destroy(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.textbox.destroy(),this.box.destroy()}focus(){this.textbox.focus()}}import Z9 from"neo-blessed";class f${box;screen;onConfirm;onCancel;constructor($,J,K,X,Q){this.screen=$,this.onConfirm=X,this.onCancel=Q;let q=Math.min(60,$.width-6),Z=8;this.box=Z9.box({parent:$,top:"center",left:"center",width:q,height:Z,border:{type:"line"},style:{border:{fg:"yellow"}},tags:!0,keys:!0}),this.setupKeyHandlers(),this.renderContent(J,K,q)}setupKeyHandlers(){this.box.key(["y","Y"],()=>{this.destroy(),this.onConfirm()}),this.box.key(["n","N","escape"],()=>{this.destroy(),this.onCancel()})}renderContent($,J,K){let X=[],Q=K-6;X.push(`{bold}{yellow-fg} ${$} commit?{/yellow-fg}{/bold}`),X.push("");let q=J.message.length>Q?J.message.slice(0,Q-3)+"…":J.message;X.push(`{yellow-fg}${J.shortHash}{/yellow-fg} ${q}`),X.push(""),X.push("{gray-fg}Press {/gray-fg}{green-fg}y{/green-fg}{gray-fg} to confirm, {/gray-fg}{red-fg}n{/red-fg}{gray-fg} or Esc to cancel{/gray-fg}"),this.box.setContent(X.join(`
40
+ `)),this.screen.render()}destroy(){this.box.destroy()}focus(){this.box.focus()}}import U9 from"neo-blessed";import*as I from"node:fs";import*as q$ from"node:path";import*as h$ from"node:os";var V9={targetFile:q$.join(h$.homedir(),".cache","diffstalker","target"),watcherEnabled:!1,debug:!1,theme:"dark"},d=q$.join(h$.homedir(),".config","diffstalker","config.json"),Y9=["dark","light","dark-colorblind","light-colorblind","dark-ansi","light-ansi"];function z9($){return typeof $==="string"&&Y9.includes($)}function i1(){let $={...V9};if(process.env.DIFFSTALKER_PAGER)$.pager=process.env.DIFFSTALKER_PAGER;if(I.existsSync(d))try{let J=JSON.parse(I.readFileSync(d,"utf-8"));if(J.pager)$.pager=J.pager;if(J.targetFile)$.targetFile=J.targetFile;if(z9(J.theme))$.theme=J.theme;if(typeof J.splitRatio==="number"&&J.splitRatio>=0.15&&J.splitRatio<=0.85)$.splitRatio=J.splitRatio;if(typeof J.autoTabEnabled==="boolean")$.autoTabEnabled=J.autoTabEnabled;if(typeof J.wrapMode==="boolean")$.wrapMode=J.wrapMode;if(typeof J.mouseEnabled==="boolean")$.mouseEnabled=J.mouseEnabled;if(Array.isArray(J.recentRepos)&&J.recentRepos.every((K)=>typeof K==="string"))$.recentRepos=J.recentRepos;if(typeof J.maxRecentRepos==="number"&&J.maxRecentRepos>=1&&J.maxRecentRepos<=50)$.maxRecentRepos=J.maxRecentRepos}catch{}return $}function M$($){let J=q$.dirname(d);if(!I.existsSync(J))I.mkdirSync(J,{recursive:!0});let K={};if(I.existsSync(d))try{K=JSON.parse(I.readFileSync(d,"utf-8"))}catch{}Object.assign(K,$),I.writeFileSync(d,JSON.stringify(K,null,2)+`
41
+ `)}function t1($){let J=q$.dirname($);if(!I.existsSync(J))I.mkdirSync(J,{recursive:!0})}function c$($){let J=h$.homedir();if($.startsWith(J))return"~"+$.slice(J.length);return $}function I0($){return $.length>1&&$.endsWith("/")?$.slice(0,-1):$}function e1($,J=10){let K=I0($),X=[];if(I.existsSync(d))try{let q=JSON.parse(I.readFileSync(d,"utf-8"));if(Array.isArray(q.recentRepos))X=q.recentRepos}catch{}let Q=X.filter((q)=>I0(q)!==K);M$({recentRepos:[K,...Q.map(I0)].slice(0,J)})}class y0{box;screen;repos;selectedIndex;currentRepo;onSelect;onCancel;constructor($,J,K,X,Q){if(this.screen=$,this.repos=J,this.currentRepo=K,this.onSelect=X,this.onCancel=Q,this.selectedIndex=J.indexOf(K),this.selectedIndex<0)this.selectedIndex=0;let q=$.width,Z=Math.min(70,q-4),Y=Math.min(J.length,15)+6;this.box=U9.box({parent:$,top:"center",left:"center",width:Z,height:Y,border:{type:"line"},style:{border:{fg:"cyan"}},tags:!0,keys:!0,scrollable:!0,alwaysScroll:!0}),this.setupKeyHandlers(),this.render()}setupKeyHandlers(){this.box.key(["escape"],()=>{this.destroy(),this.onCancel()}),this.box.key(["enter","space"],()=>{let $=this.repos[this.selectedIndex];if($)this.destroy(),this.onSelect($)}),this.box.key(["up","k"],()=>{this.selectedIndex=Math.max(0,this.selectedIndex-1),this.render()}),this.box.key(["down","j"],()=>{this.selectedIndex=Math.min(this.repos.length-1,this.selectedIndex+1),this.render()})}render(){let $=[];if($.push("{bold}{cyan-fg} Recent Repositories{/cyan-fg}{/bold}"),$.push(""),this.repos.length===0)$.push("{gray-fg}No recent repositories{/gray-fg}");else for(let J=0;J<this.repos.length;J++){let K=this.repos[J],X=J===this.selectedIndex,Q=K===this.currentRepo,q=X?"{cyan-fg}{bold}> ":" ";if(q+=c$(K),X)q+="{/bold}{/cyan-fg}";if(Q)q+=" {gray-fg}(current){/gray-fg}";$.push(q)}$.push(""),$.push("{gray-fg}j/k: navigate | Enter: select | Esc: cancel{/gray-fg}"),this.box.setContent($.join(`
42
+ `)),this.screen.render()}destroy(){this.box.destroy()}focus(){this.box.focus()}}var B9=!1;function $8($){B9=$}function Z$($){process.stderr.write(`[diffstalker warn] ${$}
43
+ `)}function G9($){if($ instanceof Error)return $.message;if($)return String($);return""}function J8($,J){let K=J?`: ${G9(J)}`:"";process.stderr.write(`[diffstalker error] ${$}${K}
44
+ `)}class P0{ctx;activeModal=null;activeModalType=null;constructor($){this.ctx=$}hasActiveModal(){return this.activeModal!==null}getActiveModalType(){return this.activeModalType}closeActiveModal(){if(this.activeModal)this.activeModal.destroy(),this.activeModal=null,this.activeModalType=null,this.ctx.render()}clearModal(){this.activeModal=null,this.activeModalType=null}openThemePicker(){this.activeModalType="theme",this.activeModal=new N0(this.ctx.screen,this.ctx.getCurrentTheme(),($)=>{this.ctx.setCurrentTheme($),M$({theme:$}),this.clearModal(),this.ctx.render()},()=>{this.clearModal()}),this.activeModal.focus()}openHotkeysModal(){this.activeModalType="hotkeys",this.activeModal=new E0(this.ctx.screen,()=>{this.clearModal()}),this.activeModal.focus()}openBaseBranchPicker(){let $=this.ctx.getGitManager();if(!$)return;this.activeModalType="baseBranch",$.compare.getCandidateBaseBranches().then((J)=>{let K=$.compare.compareState.compareBaseBranch??null,X=new L0(this.ctx.screen,J,K,(Q)=>{this.clearModal();let q=this.ctx.uiState.state.includeUncommitted;$.compare.setCompareBaseBranch(Q,q)},()=>{this.clearModal()});this.activeModal=X,X.focus()}).catch((J)=>{this.clearModal(),J8("Failed to load base branches",J)})}openDiscardConfirm($){this.activeModalType="discard",this.activeModal=new F0(this.ctx.screen,$.path,async()=>{this.clearModal(),await this.ctx.getGitManager()?.workingTree.discard($)},()=>{this.clearModal()}),this.activeModal.focus()}async openFileFinder(){let $=this.ctx.getExplorerManager(),J=$?.getCachedFilePaths()??[];if(J.length===0)await $?.loadFilePaths(),J=$?.getCachedFilePaths()??[];if(J.length===0)return;this.activeModalType="fileFinder",this.activeModal=new R0(this.ctx.screen,J,async(K)=>{if(this.clearModal(),this.ctx.uiState.state.bottomTab!=="explorer")this.ctx.uiState.setTab("explorer");if(await $?.navigateToPath(K)){let Q=$?.state.selectedIndex??0;this.ctx.uiState.setExplorerSelectedIndex(Q),this.ctx.uiState.setExplorerFileScrollOffset(0);let q=this.ctx.getTopPaneHeight();if(Q>=q)this.ctx.uiState.setExplorerScrollOffset(Q-Math.floor(q/2));else this.ctx.uiState.setExplorerScrollOffset(0)}this.ctx.render()},()=>{this.clearModal(),this.ctx.render()}),this.activeModal.focus()}openCherryPickConfirm(){let $=this.ctx.getGitManager()?.history.historyState.selectedCommit;if(!$)return;this.activeModalType="commitAction",this.activeModal=new f$(this.ctx.screen,"Cherry-pick",$,()=>{this.clearModal(),this.ctx.getGitManager()?.remote.cherryPick($.hash)},()=>{this.clearModal()}),this.activeModal.focus()}openRevertConfirm(){let $=this.ctx.getGitManager()?.history.historyState.selectedCommit;if(!$)return;this.activeModalType="commitAction",this.activeModal=new f$(this.ctx.screen,"Revert",$,()=>{this.clearModal(),this.ctx.getGitManager()?.remote.revertCommit($.hash)},()=>{this.clearModal()}),this.activeModal.focus()}openRepoPicker(){let $=this.ctx.getRecentRepos(),J=this.ctx.getRepoPath();this.activeModalType="repoPicker",this.activeModal=new y0(this.ctx.screen,$,J,(K)=>{this.clearModal(),this.ctx.onRepoSwitch(K)},()=>{this.clearModal(),this.ctx.render()}),this.activeModal.focus()}}import*as e from"node:fs";import*as d$ from"node:path";import{watch as j9}from"chokidar";import{EventEmitter as M9}from"node:events";import*as K8 from"node:path";import*as b0 from"node:os";function X8($){if($.startsWith("~/"))return K8.join(b0.homedir(),$.slice(2));if($==="~")return b0.homedir();return $}function S0($){let J=$.split(`
45
+ `);for(let K=J.length-1;K>=0;K--){let X=J[K].trim();if(X)return X}return""}class w0 extends M9{targetFile;debug;watcher=null;debounceTimer=null;lastReadPath=null;_state={path:null,lastUpdate:null,rawContent:null,sourceFile:null};constructor($,J=!1){super();this.targetFile=$,this.debug=J,this._state.sourceFile=$}get state(){return this._state}updateState($){this._state={...this._state,...$},this.emit("path-change",this._state)}processContent($){if(!$)return null;let J=X8($);return d$.isAbsolute(J)?J:d$.resolve(J)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let $=e.readFileSync(this.targetFile,"utf-8"),J=S0($);if(J&&J!==this.lastReadPath){let K=this.processContent(J),X=new Date;if(this.debug&&K)process.stderr.write(`[diffstalker ${X.toISOString()}] Path change detected
46
46
  `),process.stderr.write(` Source file: ${this.targetFile}
47
47
  `),process.stderr.write(` Raw content: "${J}"
48
48
  `),process.stderr.write(` Previous: "${this.lastReadPath??"(none)"}"
49
49
  `),process.stderr.write(` Resolved: "${K}"
50
- `);this.lastReadPath=K,this.updateState({path:K,lastUpdate:X,rawContent:J})}}catch{}}start(){if(t1(this.targetFile),!t.existsSync(this.targetFile))t.writeFileSync(this.targetFile,"");try{let $=t.readFileSync(this.targetFile,"utf-8"),J=S0($);if(J){let K=this.processContent(J),X=new Date;if(this.debug&&K)process.stderr.write(`[diffstalker ${X.toISOString()}] Initial path read
50
+ `);this.lastReadPath=K,this.updateState({path:K,lastUpdate:X,rawContent:J})}}catch{}}start(){if(t1(this.targetFile),!e.existsSync(this.targetFile))e.writeFileSync(this.targetFile,"");try{let $=e.readFileSync(this.targetFile,"utf-8"),J=S0($);if(J){let K=this.processContent(J),X=new Date;if(this.debug&&K)process.stderr.write(`[diffstalker ${X.toISOString()}] Initial path read
51
51
  `),process.stderr.write(` Source file: ${this.targetFile}
52
52
  `),process.stderr.write(` Raw content: "${J}"
53
53
  `),process.stderr.write(` Resolved: "${K}"
54
- `);this.lastReadPath=K,this._state={path:K,lastUpdate:X,rawContent:J,sourceFile:this.targetFile}}}catch{}this.watcher=U9(this.targetFile,{persistent:!0,ignoreInitial:!0}),this.watcher.on("change",()=>this.readTargetDebounced()),this.watcher.on("add",()=>this.readTargetDebounced())}stop(){if(this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.watcher)this.watcher.close(),this.watcher=null}}class l${targetFile;getCurrentRepoPath;callbacks;watcher=null;_watcherState={enabled:!1};constructor($,J,K){this.targetFile=$,this.getCurrentRepoPath=J,this.callbacks=K}get watcherState(){return this._watcherState}get isEnabled(){return this.watcher!==null}start(){this.watcher=new w0(this.targetFile),this.watcher.on("path-change",(J)=>{if(J.path&&J.path!==this.getCurrentRepoPath())this._watcherState={enabled:!0,sourceFile:J.sourceFile??this.targetFile,rawContent:J.rawContent??void 0,lastUpdate:J.lastUpdate??void 0},this.callbacks.onRepoChange(J.path,this._watcherState);if(J.rawContent)this.callbacks.onFileNavigate(J.rawContent)}),this._watcherState={enabled:!0,sourceFile:this.targetFile},this.watcher.start();let $=this.watcher.state;if($.path&&$.path!==this.getCurrentRepoPath())this._watcherState={enabled:!0,sourceFile:$.sourceFile??this.targetFile,rawContent:$.rawContent??void 0,lastUpdate:$.lastUpdate??void 0},this.callbacks.onRepoChange($.path,this._watcherState);else if($.rawContent)this._watcherState.rawContent=$.rawContent,this.callbacks.onFileNavigate($.rawContent)}toggle(){if(this.watcher)this.stop();else this.start()}stop(){if(this.watcher)this.watcher.stop(),this.watcher=null,this._watcherState={enabled:!1}}}function G9($){let J=`{bold}{green-fg}${$.current}{/green-fg}{/bold}`;if($.tracking)J+=` {gray-fg}→{/gray-fg} {blue-fg}${$.tracking}{/blue-fg}`;if($.ahead>0)J+=` {green-fg}↑${$.ahead}{/green-fg}`;if($.behind>0)J+=` {red-fg}↓${$.behind}{/red-fg}`;return J}function j9($){let J=$.current.length;if($.tracking)J+=3+$.tracking.length;if($.ahead>0)J+=3+String($.ahead).length;if($.behind>0)J+=3+String($.behind).length;return J}function Q8($,J,K,X,Q,q){if(!$)return"{gray-fg}Waiting for target path...{/gray-fg}";let Z=c$($),V=X==="Not a git repository",Y=`{bold}{cyan-fg}${Z}{/cyan-fg}{/bold}`;if(K)Y+=" {yellow-fg}⟳{/yellow-fg}";if(V)Y+=" {yellow-fg}(not a git repository){/yellow-fg}";else if(X)Y+=` {red-fg}(${X}){/red-fg}`;let z="",U=0;if(q){if(q.inProgress&&q.operation){let G={push:"pushing...",fetch:"fetching...",pull:"rebasing...",stash:"stashing...",stashPop:"popping stash...",branchSwitch:"switching branch...",branchCreate:"creating branch...",softReset:"resetting...",cherryPick:"cherry-picking...",revert:"reverting..."}[q.operation]??"";z=` {yellow-fg}${G}{/yellow-fg}`,U=1+G.length}else if(q.error){let B=q.error.length>40?q.error.slice(0,40)+"…":q.error;z=` {red-fg}${B}{/red-fg}`,U=1+B.length}else if(q.lastResult)z=` {green-fg}${q.lastResult}{/green-fg}`,U=1+q.lastResult.length}let j=J?G9(J):"";if(j){let B=Z.length;if(K)B+=2;if(V)B+=24;else if(X)B+=X.length+3;B+=U;let G=J?j9(J):0,M=Math.max(1,Q-B-G-2);return Y+z+" ".repeat(M)+j}return Y+z}function q8($){return $.replace(/\{[^}]+\}/g,"").length}function r$($,J){return J?`{blue-fg}[${$}]{/blue-fg}`:`{gray-fg}[${$}]{/gray-fg}`}function M9($,J,K,X,Q,q){let Z=[];if(Z.push($?"{yellow-fg}[scroll]{/yellow-fg}":"{yellow-fg}m:[select]{/yellow-fg}"),Z.push(r$("auto",J)),Z.push(r$("wrap",K)),Z.push(r$("follow",X)),q==="explorer")Z.push(r$("changes",Q));return Z.join(" ")}function Z8($,J,K,X,Q,q,Z,V){let Y="{gray-fg}?{/gray-fg} ";if(Y+=M9(J,K,X,Q,q,$),$==="diff"&&V==="diff")Y+=" {gray-fg}n/N:hunk s:toggle{/gray-fg}";Y+=" {gray-fg}Tab:next{/gray-fg}";let U=[{key:"1",label:"Diff",tab:"diff"},{key:"2",label:"Commit",tab:"commit"},{key:"3",label:"History",tab:"history"},{key:"4",label:"Compare",tab:"compare"},{key:"5",label:"Explorer",tab:"explorer"}].map(({key:M,label:H,tab:D})=>{if($===D)return`{bold}{cyan-fg}[${M}]${H}{/cyan-fg}{/bold}`;return`[${M}]${H}`}).join(" "),j=q8(Y),B=q8(U),G=Math.max(1,Z-j-B);return Y+" ".repeat(G)+U}import*as Z$ from"node:fs";import*as P from"node:path";import{EventEmitter as D9}from"node:events";import{simpleGit as O9}from"simple-git";async function o$($,J){if(J.length===0)return new Set;let K=O9($),X=new Set,Q=100;for(let q=0;q<J.length;q+=Q){let Z=J.slice(q,q+Q);try{let Y=(await K.raw(["check-ignore",...Z])).trim().split(`
54
+ `);this.lastReadPath=K,this._state={path:K,lastUpdate:X,rawContent:J,sourceFile:this.targetFile}}}catch{}this.watcher=j9(this.targetFile,{persistent:!0,ignoreInitial:!0}),this.watcher.on("change",()=>this.readTargetDebounced()),this.watcher.on("add",()=>this.readTargetDebounced())}stop(){if(this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.watcher)this.watcher.close(),this.watcher=null}}class l${targetFile;getCurrentRepoPath;callbacks;watcher=null;_watcherState={enabled:!1};constructor($,J,K){this.targetFile=$,this.getCurrentRepoPath=J,this.callbacks=K}get watcherState(){return this._watcherState}get isEnabled(){return this.watcher!==null}start(){this.watcher=new w0(this.targetFile),this.watcher.on("path-change",(J)=>{if(J.path&&J.path!==this.getCurrentRepoPath())this._watcherState={enabled:!0,sourceFile:J.sourceFile??this.targetFile,rawContent:J.rawContent??void 0,lastUpdate:J.lastUpdate??void 0},this.callbacks.onRepoChange(J.path,this._watcherState);if(J.rawContent)this.callbacks.onFileNavigate(J.rawContent)}),this._watcherState={enabled:!0,sourceFile:this.targetFile},this.watcher.start();let $=this.watcher.state;if($.path&&$.path!==this.getCurrentRepoPath())this._watcherState={enabled:!0,sourceFile:$.sourceFile??this.targetFile,rawContent:$.rawContent??void 0,lastUpdate:$.lastUpdate??void 0},this.callbacks.onRepoChange($.path,this._watcherState);else if($.rawContent)this._watcherState.rawContent=$.rawContent,this.callbacks.onFileNavigate($.rawContent)}toggle(){if(this.watcher)this.stop();else this.start()}stop(){if(this.watcher)this.watcher.stop(),this.watcher=null,this._watcherState={enabled:!1}}}function O9($){let J=`{bold}{green-fg}${$.current}{/green-fg}{/bold}`;if($.tracking)J+=` {gray-fg}→{/gray-fg} {blue-fg}${$.tracking}{/blue-fg}`;if($.ahead>0)J+=` {green-fg}↑${$.ahead}{/green-fg}`;if($.behind>0)J+=` {red-fg}↓${$.behind}{/red-fg}`;return J}function _9($){let J=$.current.length;if($.tracking)J+=3+$.tracking.length;if($.ahead>0)J+=3+String($.ahead).length;if($.behind>0)J+=3+String($.behind).length;return J}function Q8($,J,K,X,Q,q){if(!$)return"{gray-fg}Waiting for target path...{/gray-fg}";let Z=c$($),V=X==="Not a git repository",Y=`{bold}{cyan-fg}${Z}{/cyan-fg}{/bold}`;if(K)Y+=" {yellow-fg}⟳{/yellow-fg}";if(V)Y+=" {yellow-fg}(not a git repository){/yellow-fg}";else if(X)Y+=` {red-fg}(${X}){/red-fg}`;let z="",U=0;if(q){if(q.inProgress&&q.operation){let G={push:"pushing...",fetch:"fetching...",pull:"rebasing...",stash:"stashing...",stashPop:"popping stash...",branchSwitch:"switching branch...",branchCreate:"creating branch...",softReset:"resetting...",cherryPick:"cherry-picking...",revert:"reverting..."}[q.operation]??"";z=` {yellow-fg}${G}{/yellow-fg}`,U=1+G.length}else if(q.error){let B=q.error.length>40?q.error.slice(0,40)+"…":q.error;z=` {red-fg}${B}{/red-fg}`,U=1+B.length}else if(q.lastResult)z=` {green-fg}${q.lastResult}{/green-fg}`,U=1+q.lastResult.length}let j=J?O9(J):"";if(j){let B=Z.length;if(K)B+=2;if(V)B+=24;else if(X)B+=X.length+3;B+=U;let G=J?_9(J):0,M=Math.max(1,Q-B-G-2);return Y+z+" ".repeat(M)+j}return Y+z}function q8($){return $.replace(/\{[^}]+\}/g,"").length}function r$($,J){return J?`{blue-fg}[${$}]{/blue-fg}`:`{gray-fg}[${$}]{/gray-fg}`}function D9($,J,K,X,Q,q){let Z=[];if(Z.push($?"{yellow-fg}[scroll]{/yellow-fg}":"{yellow-fg}m:[select]{/yellow-fg}"),Z.push(r$("auto",J)),Z.push(r$("wrap",K)),Z.push(r$("follow",X)),q==="explorer")Z.push(r$("changes",Q));return Z.join(" ")}function Z8($,J,K,X,Q,q,Z,V){let Y="{gray-fg}?{/gray-fg} ";if(Y+=D9(J,K,X,Q,q,$),$==="diff"&&V==="diff")Y+=" {gray-fg}n/N:hunk s:toggle{/gray-fg}";Y+=" {gray-fg}Tab:next{/gray-fg}";let U=[{key:"1",label:"Diff",tab:"diff"},{key:"2",label:"Commit",tab:"commit"},{key:"3",label:"History",tab:"history"},{key:"4",label:"Compare",tab:"compare"},{key:"5",label:"Explorer",tab:"explorer"}].map(({key:M,label:v,tab:D})=>{if($===D)return`{bold}{cyan-fg}[${M}]${v}{/cyan-fg}{/bold}`;return`[${M}]${v}`}).join(" "),j=q8(Y),B=q8(U),G=Math.max(1,Z-j-B);return Y+" ".repeat(G)+U}import*as l from"node:fs";import*as C from"node:path";import{EventEmitter as H9}from"node:events";import{simpleGit as W9}from"simple-git";async function o$($,J){if(J.length===0)return new Set;let K=W9($),X=new Set,Q=100;for(let q=0;q<J.length;q+=Q){let Z=J.slice(q,q+Q);try{let Y=(await K.raw(["check-ignore",...Z])).trim().split(`
55
55
  `).filter((z)=>z.length>0);for(let z of Y)X.add(z)}catch{}}return X}import{simpleGit as N}from"simple-git";import{execFileSync as z8}from"node:child_process";import*as U8 from"node:fs";import*as B8 from"node:path";function V8($){let J=new Map;for(let K of $.trim().split(`
56
- `)){if(!K)continue;let X=K.split("\t");if(X.length>=3){let Q=X[0]==="-"?0:parseInt(X[0],10),q=X[1]==="-"?0:parseInt(X[1],10),Z=X.slice(2).join("\t");J.set(Z,{insertions:Q,deletions:q})}}return J}async function _9($,J){try{let K=B8.join($,J);return(await U8.promises.readFile(K,"utf-8")).split(`
57
- `).filter((Q)=>Q.length>0).length}catch{return 0}}function Y8($){switch($){case"M":return"modified";case"A":return"added";case"D":return"deleted";case"?":return"untracked";case"R":return"renamed";case"C":return"copied";default:return"modified"}}async function x0($){let J=N($);try{if(!await J.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let X=await J.status(),Q=[],q=new Set,Z=X.files.filter((G)=>G.working_dir==="?").map((G)=>G.path),V=await o$($,Z);for(let G of X.files){if(G.index==="!"||G.working_dir==="!"||V.has(G.path))continue;let M=`${G.path}-${G.index!==" "&&G.index!=="?"}`;if(q.has(M))continue;if(q.add(M),G.index&&G.index!==" "&&G.index!=="?")Q.push({path:G.path,status:Y8(G.index),staged:!0});if(G.working_dir&&G.working_dir!==" ")Q.push({path:G.path,status:G.working_dir==="?"?"untracked":Y8(G.working_dir),staged:!1})}let[Y,z]=await Promise.all([J.diff(["--cached","--numstat"]).catch(()=>""),J.diff(["--numstat"]).catch(()=>"")]),U=V8(Y),j=V8(z);for(let G of Q){let M=G.staged?U.get(G.path):j.get(G.path);if(M)G.insertions=M.insertions,G.deletions=M.deletions}let B=Q.filter((G)=>G.status==="untracked");if(B.length>0){let G=await Promise.all(B.map((M)=>_9($,M.path)));for(let M=0;M<B.length;M++)B[M].insertions=G[M],B[M].deletions=0}return{files:Q,branch:{current:X.current||"HEAD",tracking:X.tracking||void 0,ahead:X.ahead,behind:X.behind},isRepo:!0}}catch{return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1}}}async function G8($,J){await N($).add(J)}async function j8($,J){await N($).reset(["HEAD","--",J])}async function M8($){await N($).add("-A")}async function O8($){await N($).reset(["HEAD"])}async function _8($,J){await N($).checkout(["--",J])}async function D8($,J,K=!1){await N($).commit(J,void 0,K?{"--amend":null}:void 0)}async function v8($){let J=N($);try{return(await J.log({n:1})).latest?.message||""}catch{return""}}function W8($,J){z8("git",["apply","--cached","--unidiff-zero"],{cwd:$,input:J,encoding:"utf-8"})}function H8($,J){z8("git",["apply","--cached","--reverse","--unidiff-zero"],{cwd:$,input:J,encoding:"utf-8"})}async function T8($){let X=(await N($).push()).pushed;if(X.length===0)return"Everything up-to-date";return X.map((Q)=>`${Q.local} → ${Q.remote}`).join(", ")}async function A8($){return await N($).fetch(),"Fetch complete"}async function k8($){let K=await N($).pull(["--rebase"]);if(K.summary.changes===0&&K.summary.insertions===0&&K.summary.deletions===0)return"Already up-to-date";return`${K.summary.changes} file(s) changed`}async function N8($,J=50){let K=N($);try{return(await K.log({n:J})).all.map((Q)=>({hash:Q.hash,shortHash:Q.hash.slice(0,7),message:Q.message.split(`
58
- `)[0],author:Q.author_name,date:new Date(Q.date),refs:Q.refs||""}))}catch{return[]}}async function E8($){let J=N($);try{return(await J.stashList()).all.map((X,Q)=>({index:Q,message:X.message}))}catch{return[]}}async function L8($,J){let K=N($),X=["push"];if(J)X.push("-m",J);return await K.stash(X),"Stashed"}async function F8($,J=0){return await N($).stash(["pop",`stash@{${J}}`]),"Stash popped"}async function R8($){let K=await N($).branchLocal();return K.all.map((X)=>({name:X,current:X===K.current,tracking:K.branches[X]?.label||void 0}))}async function I8($,J){return await N($).checkout(J),`Switched to ${J}`}async function y8($,J){return await N($).checkoutLocalBranch(J),`Created ${J}`}async function C8($,J=1){return await N($).reset(["--soft",`HEAD~${J}`]),"Reset done"}async function P8($,J){return await N($).raw(["cherry-pick",J]),"Cherry-picked"}async function b8($,J){return await N($).revert(J),"Reverted"}async function S8($){return(await N($).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((X)=>X.length>0)}var v9=1048576,W9=102400;function H9($){let J=Math.min($.length,8192);for(let K=0;K<J;K++)if($[K]===0)return!0;return!1}class p0 extends D9{repoPath;options;expandedPaths=new Set;gitStatusMap={files:new Map,directories:new Set};_cachedFilePaths=null;_state={currentPath:"",tree:null,displayRows:[],selectedIndex:0,selectedFile:null,isLoading:!1,error:null};constructor($,J){super();this.repoPath=$,this.options={hideHidden:J.hideHidden??!0,hideGitignored:J.hideGitignored??!0,showOnlyChanges:J.showOnlyChanges??!1},this.expandedPaths.add("")}get state(){return this._state}updateState($){this._state={...this._state,...$},this.emit("state-change",this._state)}async setOptions($){this.options={...this.options,...$},await this.loadTree()}setGitStatus($){if(this.gitStatusMap=$,this.loadFilePaths(),this._state.tree)this.applyGitStatusToTree(this._state.tree),this.refreshDisplayRows()}async toggleShowOnlyChanges(){this.options.showOnlyChanges=!this.options.showOnlyChanges,this.refreshDisplayRows()}get showOnlyChanges(){return this.options.showOnlyChanges}async loadTree(){this.updateState({isLoading:!0,error:null});try{let $=await this.buildTreeNode("",0);if($){$.expanded=!0,this.applyGitStatusToTree($);let J=this.flattenTree($);this.updateState({tree:$,displayRows:J,selectedIndex:0,selectedFile:null,isLoading:!1})}else this.updateState({tree:null,displayRows:[],isLoading:!1,error:"Failed to load directory"})}catch($){this.updateState({error:$ instanceof Error?$.message:"Failed to read directory",tree:null,displayRows:[],isLoading:!1})}}async buildTreeNode($,J){try{let K=P.join(this.repoPath,$);if(!(await Z$.promises.stat(K)).isDirectory())return{name:P.basename($)||this.getRepoName(),path:$,isDirectory:!1,expanded:!1,children:[],childrenLoaded:!0};let Q=this.expandedPaths.has($),q={name:P.basename($)||this.getRepoName(),path:$,isDirectory:!0,expanded:Q,children:[],childrenLoaded:!1};if($===""||Q)await this.loadChildrenForNode(q);return q}catch(K){return q$(`Failed to build tree node for ${$}: ${K instanceof Error?K.message:K}`),null}}async loadChildrenForNode($){if($.childrenLoaded)return;try{let J=P.join(this.repoPath,$.path),K=await Z$.promises.readdir(J,{withFileTypes:!0}),X=K.map((Z)=>$.path?P.join($.path,Z.name):Z.name),Q=this.options.hideGitignored?await o$(this.repoPath,X):new Set,q=[];for(let Z of K){if(this.options.hideHidden&&Z.name.startsWith("."))continue;let V=$.path?P.join($.path,Z.name):Z.name;if(this.options.hideGitignored&&Q.has(V))continue;let Y=Z.isDirectory(),z=this.expandedPaths.has(V),U={name:Z.name,path:V,isDirectory:Y,expanded:z,children:[],childrenLoaded:!Y};if(Y&&z)await this.loadChildrenForNode(U);q.push(U)}q.sort((Z,V)=>{if(Z.isDirectory&&!V.isDirectory)return-1;if(!Z.isDirectory&&V.isDirectory)return 1;return Z.name.localeCompare(V.name)}),this.collapseNode($,q),$.childrenLoaded=!0}catch(J){q$(`Failed to read directory ${$.name}: ${J instanceof Error?J.message:J}`),$.childrenLoaded=!0,$.children=[]}}collapseNode($,J){for(let K of J)if(K.isDirectory&&K.childrenLoaded)while(K.children.length===1&&K.children[0].isDirectory&&K.children[0].childrenLoaded){let X=K.children[0];K.name=`${K.name}/${X.name}`,K.path=X.path,K.children=X.children,K.expanded=this.expandedPaths.has(K.path)}$.children=J}applyGitStatusToTree($){if(!$.isDirectory){let J=this.gitStatusMap.files.get($.path);if(J)$.gitStatus=J.status;else $.gitStatus=void 0}else{$.hasChangedChildren=this.gitStatusMap.directories.has($.path);for(let J of $.children)this.applyGitStatusToTree(J)}}shouldIncludeNode($){if(!this.options.showOnlyChanges)return!0;if($.isDirectory)return!!$.hasChangedChildren;return!!$.gitStatus}flattenTree($){let J=[],K=(X,Q,q)=>{for(let Z=0;Z<X.children.length;Z++){let V=X.children[Z],Y=Z===X.children.length-1;if(!this.shouldIncludeNode(V))continue;if(J.push({node:V,depth:Q,isLast:Y,parentIsLast:[...q]}),V.isDirectory&&V.expanded)K(V,Q+1,[...q,Y])}};return K($,0,[]),J}refreshDisplayRows(){if(!this._state.tree)return;let $=this._state.displayRows[this._state.selectedIndex]?.node.path??null,J=this.flattenTree(this._state.tree),K=0;if($!==null){let X=J.findIndex((Q)=>Q.node.path===$);if(X>=0)K=X}K=Math.min(K,Math.max(0,J.length-1)),this.updateState({displayRows:J,selectedIndex:K})}getRepoName(){return P.basename(this.repoPath)||"repo"}async loadDirectory($){this._state.currentPath=$,await this.loadTree()}async loadFile($){try{let J=P.join(this.repoPath,$),K=await Z$.promises.stat(J);if(K.size>v9){this.updateState({selectedFile:{path:$,content:`File too large to display (${(K.size/1024/1024).toFixed(2)} MB).
59
- Maximum size: 1 MB`,truncated:!0}});return}let X=await Z$.promises.readFile(J);if(H9(X)){this.updateState({selectedFile:{path:$,content:"Binary file - cannot display"}});return}let Q=X.toString("utf-8"),q=!1;if(K.size>W9)Q=`Warning: Large file (${(K.size/1024).toFixed(1)} KB)
56
+ `)){if(!K)continue;let X=K.split("\t");if(X.length>=3){let Q=X[0]==="-"?0:parseInt(X[0],10),q=X[1]==="-"?0:parseInt(X[1],10),Z=X.slice(2).join("\t");J.set(Z,{insertions:Q,deletions:q})}}return J}async function v9($,J){try{let K=B8.join($,J);return(await U8.promises.readFile(K,"utf-8")).split(`
57
+ `).filter((Q)=>Q.length>0).length}catch{return 0}}function Y8($){switch($){case"M":return"modified";case"A":return"added";case"D":return"deleted";case"?":return"untracked";case"R":return"renamed";case"C":return"copied";default:return"modified"}}async function x0($){let J=N($);try{if(!await J.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let X=await J.status(),Q=[],q=new Set,Z=X.files.filter((G)=>G.working_dir==="?").map((G)=>G.path),V=await o$($,Z);for(let G of X.files){if(G.index==="!"||G.working_dir==="!"||V.has(G.path))continue;let M=`${G.path}-${G.index!==" "&&G.index!=="?"}`;if(q.has(M))continue;if(q.add(M),G.index&&G.index!==" "&&G.index!=="?")Q.push({path:G.path,status:Y8(G.index),staged:!0});if(G.working_dir&&G.working_dir!==" ")Q.push({path:G.path,status:G.working_dir==="?"?"untracked":Y8(G.working_dir),staged:!1})}let[Y,z]=await Promise.all([J.diff(["--cached","--numstat"]).catch(()=>""),J.diff(["--numstat"]).catch(()=>"")]),U=V8(Y),j=V8(z);for(let G of Q){let M=G.staged?U.get(G.path):j.get(G.path);if(M)G.insertions=M.insertions,G.deletions=M.deletions}let B=Q.filter((G)=>G.status==="untracked");if(B.length>0){let G=await Promise.all(B.map((M)=>v9($,M.path)));for(let M=0;M<B.length;M++)B[M].insertions=G[M],B[M].deletions=0}return{files:Q,branch:{current:X.current||"HEAD",tracking:X.tracking||void 0,ahead:X.ahead,behind:X.behind},isRepo:!0}}catch{return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1}}}async function G8($,J){await N($).add(J)}async function j8($,J){await N($).reset(["HEAD","--",J])}async function M8($){await N($).add("-A")}async function O8($){await N($).reset(["HEAD"])}async function _8($,J){await N($).checkout(["--",J])}async function D8($,J,K=!1){await N($).commit(J,void 0,K?{"--amend":null}:void 0)}async function W8($){let J=N($);try{return(await J.log({n:1})).latest?.message||""}catch{return""}}function v8($,J){z8("git",["apply","--cached","--unidiff-zero"],{cwd:$,input:J,encoding:"utf-8"})}function H8($,J){z8("git",["apply","--cached","--reverse","--unidiff-zero"],{cwd:$,input:J,encoding:"utf-8"})}async function T8($){let X=(await N($).push()).pushed;if(X.length===0)return"Everything up-to-date";return X.map((Q)=>`${Q.local} → ${Q.remote}`).join(", ")}async function A8($){return await N($).fetch(),"Fetch complete"}async function k8($){let K=await N($).pull(["--rebase"]);if(K.summary.changes===0&&K.summary.insertions===0&&K.summary.deletions===0)return"Already up-to-date";return`${K.summary.changes} file(s) changed`}async function N8($,J=50){let K=N($);try{return(await K.log({n:J})).all.map((Q)=>({hash:Q.hash,shortHash:Q.hash.slice(0,7),message:Q.message.split(`
58
+ `)[0],author:Q.author_name,date:new Date(Q.date),refs:Q.refs||""}))}catch{return[]}}async function E8($){let J=N($);try{return(await J.stashList()).all.map((X,Q)=>({index:Q,message:X.message}))}catch{return[]}}async function L8($,J){let K=N($),X=["push"];if(J)X.push("-m",J);return await K.stash(X),"Stashed"}async function F8($,J=0){return await N($).stash(["pop",`stash@{${J}}`]),"Stash popped"}async function R8($){let K=await N($).branchLocal();return K.all.map((X)=>({name:X,current:X===K.current,tracking:K.branches[X]?.label||void 0}))}async function I8($,J){return await N($).checkout(J),`Switched to ${J}`}async function y8($,J){return await N($).checkoutLocalBranch(J),`Created ${J}`}async function C8($,J=1){return await N($).reset(["--soft",`HEAD~${J}`]),"Reset done"}async function P8($,J){return await N($).raw(["cherry-pick",J]),"Cherry-picked"}async function b8($,J){return await N($).revert(J),"Reverted"}async function S8($){return(await N($).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((X)=>X.length>0)}var T9=1048576,A9=102400;function k9($){let J=Math.min($.length,8192);for(let K=0;K<J;K++)if($[K]===0)return!0;return!1}class p0 extends H9{repoPath;options;expandedPaths=new Set;gitStatusMap={files:new Map,directories:new Set};_cachedFilePaths=null;_isGitRepo;_state={currentPath:"",tree:null,displayRows:[],selectedIndex:0,selectedFile:null,isLoading:!1,error:null};constructor($,J){super();this.repoPath=$,this._isGitRepo=l.existsSync(C.join($,".git")),this.options={hideHidden:J.hideHidden??!0,hideGitignored:J.hideGitignored??!0,showOnlyChanges:J.showOnlyChanges??!1},this.expandedPaths.add("")}get state(){return this._state}updateState($){this._state={...this._state,...$},this.emit("state-change",this._state)}async setOptions($){this.options={...this.options,...$},await this.loadTree()}setGitStatus($){if(this.gitStatusMap=$,this.loadFilePaths(),this._state.tree)this.applyGitStatusToTree(this._state.tree),this.refreshDisplayRows()}async toggleShowOnlyChanges(){this.options.showOnlyChanges=!this.options.showOnlyChanges,this.refreshDisplayRows()}get showOnlyChanges(){return this.options.showOnlyChanges}async loadTree(){this.updateState({isLoading:!0,error:null});try{let $=await this.buildTreeNode("",0);if($){$.expanded=!0,this.applyGitStatusToTree($);let J=this.flattenTree($);this.updateState({tree:$,displayRows:J,selectedIndex:0,selectedFile:null,isLoading:!1})}else this.updateState({tree:null,displayRows:[],isLoading:!1,error:"Failed to load directory"})}catch($){this.updateState({error:$ instanceof Error?$.message:"Failed to read directory",tree:null,displayRows:[],isLoading:!1})}}async buildTreeNode($,J){try{let K=C.join(this.repoPath,$);if(!(await l.promises.stat(K)).isDirectory())return{name:C.basename($)||this.getRepoName(),path:$,isDirectory:!1,expanded:!1,children:[],childrenLoaded:!0};let Q=this.expandedPaths.has($),q={name:C.basename($)||this.getRepoName(),path:$,isDirectory:!0,expanded:Q,children:[],childrenLoaded:!1};if($===""||Q)await this.loadChildrenForNode(q);return q}catch(K){return Z$(`Failed to build tree node for ${$}: ${K instanceof Error?K.message:K}`),null}}async loadChildrenForNode($){if($.childrenLoaded)return;try{let J=C.join(this.repoPath,$.path),K=await l.promises.readdir(J,{withFileTypes:!0}),X=K.map((Z)=>$.path?C.join($.path,Z.name):Z.name),Q=this.options.hideGitignored&&this._isGitRepo?await o$(this.repoPath,X):new Set,q=[];for(let Z of K){if(this.options.hideHidden&&Z.name.startsWith("."))continue;let V=$.path?C.join($.path,Z.name):Z.name;if(this.options.hideGitignored&&Q.has(V))continue;let Y=Z.isDirectory(),z=this.expandedPaths.has(V),U={name:Z.name,path:V,isDirectory:Y,expanded:z,children:[],childrenLoaded:!Y};if(Y&&z)await this.loadChildrenForNode(U);q.push(U)}q.sort((Z,V)=>{if(Z.isDirectory&&!V.isDirectory)return-1;if(!Z.isDirectory&&V.isDirectory)return 1;return Z.name.localeCompare(V.name)}),this.collapseNode($,q),$.childrenLoaded=!0}catch(J){Z$(`Failed to read directory ${$.name}: ${J instanceof Error?J.message:J}`),$.childrenLoaded=!0,$.children=[]}}collapseNode($,J){for(let K of J)if(K.isDirectory&&K.childrenLoaded)while(K.children.length===1&&K.children[0].isDirectory&&K.children[0].childrenLoaded){let X=K.children[0];K.name=`${K.name}/${X.name}`,K.path=X.path,K.children=X.children,K.expanded=this.expandedPaths.has(K.path)}$.children=J}applyGitStatusToTree($){if(!$.isDirectory){let J=this.gitStatusMap.files.get($.path);if(J)$.gitStatus=J.status;else $.gitStatus=void 0}else{$.hasChangedChildren=this.gitStatusMap.directories.has($.path);for(let J of $.children)this.applyGitStatusToTree(J)}}shouldIncludeNode($){if(!this.options.showOnlyChanges)return!0;if($.isDirectory)return!!$.hasChangedChildren;return!!$.gitStatus}flattenTree($){let J=[],K=(X,Q,q)=>{for(let Z=0;Z<X.children.length;Z++){let V=X.children[Z],Y=Z===X.children.length-1;if(!this.shouldIncludeNode(V))continue;if(J.push({node:V,depth:Q,isLast:Y,parentIsLast:[...q]}),V.isDirectory&&V.expanded)K(V,Q+1,[...q,Y])}};return K($,0,[]),J}refreshDisplayRows(){if(!this._state.tree)return;let $=this._state.displayRows[this._state.selectedIndex]?.node.path??null,J=this.flattenTree(this._state.tree),K=0;if($!==null){let X=J.findIndex((Q)=>Q.node.path===$);if(X>=0)K=X}K=Math.min(K,Math.max(0,J.length-1)),this.updateState({displayRows:J,selectedIndex:K})}getRepoName(){return C.basename(this.repoPath)||"repo"}async loadDirectory($){this._state.currentPath=$,await this.loadTree()}async loadFile($){try{let J=C.join(this.repoPath,$),K=await l.promises.stat(J);if(K.size>T9){this.updateState({selectedFile:{path:$,content:`File too large to display (${(K.size/1024/1024).toFixed(2)} MB).
59
+ Maximum size: 1 MB`,truncated:!0}});return}let X=await l.promises.readFile(J);if(k9(X)){this.updateState({selectedFile:{path:$,content:"Binary file - cannot display"}});return}let Q=X.toString("utf-8"),q=!1;if(K.size>A9)Q=`Warning: Large file (${(K.size/1024).toFixed(1)} KB)
60
60
 
61
61
  `+Q;let Z=5000,V=Q.split(`
62
62
  `);if(V.length>Z)Q=V.slice(0,Z).join(`
63
63
  `)+`
64
64
 
65
- ... (truncated, ${V.length-Z} more lines)`,q=!0;this.updateState({selectedFile:{path:$,content:Q,truncated:q}})}catch(J){this.updateState({selectedFile:{path:$,content:J instanceof Error?`Error: ${J.message}`:"Failed to read file"}})}}async selectIndex($){let J=this._state.displayRows;if($<0||$>=J.length)return;let K=J[$];if(this.updateState({selectedIndex:$}),K&&!K.node.isDirectory)await this.loadFile(K.node.path);else this.updateState({selectedFile:null})}navigateUp($){let J=Math.max(0,this._state.selectedIndex-1);if(J===this._state.selectedIndex)return null;if(this.selectIndex(J),J<$)return J;return null}navigateDown($,J){let K=Math.min(this._state.displayRows.length-1,this._state.selectedIndex+1);if(K===this._state.selectedIndex)return null;this.selectIndex(K);let Q=this._state.displayRows.length>J?J-2:J,q=$+Q;if(K>=q)return $+1;return null}async toggleExpand(){let $=this._state.displayRows,J=this._state.selectedIndex;if(J<0||J>=$.length)return;let K=$[J];if(!K.node.isDirectory)return;let X=K.node;if(X.expanded)this.expandedPaths.delete(X.path),X.expanded=!1;else if(this.expandedPaths.add(X.path),X.expanded=!0,!X.childrenLoaded)await this.loadChildrenForNode(X),this.applyGitStatusToTree(X);this.refreshDisplayRows()}async enterDirectory(){let $=this._state.displayRows,J=this._state.selectedIndex;if(J<0||J>=$.length)return;if($[J].node.isDirectory)await this.toggleExpand()}async goUp(){let $=this._state.displayRows,J=this._state.selectedIndex;if(J<0||J>=$.length)return;let X=$[J].node.path,Q=P.dirname(X);if(Q==="."||Q==="")return;let q=X.split("/");for(let Z=q.length-1;Z>0;Z--){let V=q.slice(0,Z).join("/");if(this.expandedPaths.has(V)){this.expandedPaths.delete(V);let Y=this.findNodeByPath(V);if(Y)Y.expanded=!1;this.refreshDisplayRows();let U=this._state.displayRows.findIndex((j)=>j.node.path===V);if(U>=0)this.updateState({selectedIndex:U,selectedFile:null});return}}}findNodeByPath($){if(!this._state.tree)return null;let J=(K)=>{if(K.path===$)return K;for(let X of K.children){let Q=J(X);if(Q)return Q}return null};return J(this._state.tree)}async loadFilePaths(){try{this._cachedFilePaths=await S8(this.repoPath)}catch($){q$(`Failed to load file paths: ${$ instanceof Error?$.message:$}`),this._cachedFilePaths=[]}}getCachedFilePaths(){return this._cachedFilePaths??[]}async navigateToPath($){if(!this._state.tree)return!1;let J=$.split("/"),K="";for(let Q=0;Q<J.length-1;Q++)K=K?`${K}/${J[Q]}`:J[Q],this.expandedPaths.add(K);await this.loadTree();let X=this._state.displayRows.findIndex((Q)=>Q.node.path===$);if(X>=0)return await this.selectIndex(X),!0;return!1}dispose(){this.removeAllListeners()}}import{EventEmitter as T9}from"node:events";function w8($,J,K){if(!$.trim())return{valid:!1,error:"Commit message cannot be empty"};if(J===0&&!K)return{valid:!1,error:"No changes staged for commit"};return{valid:!0,error:null}}function x8($){return $.trim()}var p8={message:"",amend:!1,isCommitting:!1,error:null,inputFocused:!1};class g0 extends T9{_state={...p8};getHeadMessage;onCommit;onSuccess;stagedCount=0;constructor($){super();this.getHeadMessage=$.getHeadMessage,this.onCommit=$.onCommit,this.onSuccess=$.onSuccess}get state(){return this._state}update($){this._state={...this._state,...$},this.emit("change",this._state)}setStagedCount($){this.stagedCount=$}setMessage($){this.update({message:$,error:null})}setInputFocused($){this.update({inputFocused:$}),this.emit("focus-change",$)}async toggleAmend(){let $=!this._state.amend;if(this.update({amend:$}),$&&!this._state.message)try{let J=await this.getHeadMessage();if(J)this.update({message:J})}catch{}}async submit(){let $=w8(this._state.message,this.stagedCount,this._state.amend);if(!$.valid){this.update({error:$.error});return}this.update({isCommitting:!0,error:null});try{await this.onCommit(x8(this._state.message),this._state.amend),this.update({message:"",amend:!1,isCommitting:!1,inputFocused:!1}),this.onSuccess()}catch(J){this.update({isCommitting:!1,error:J instanceof Error?J.message:"Commit failed"})}}reset(){this._state={...p8},this.emit("change",this._state)}}class g8{queue=[];isProcessing=!1;pendingMutations=0;refreshScheduled=!1;enqueue($){return new Promise((J,K)=>{this.queue.push({execute:$,resolve:J,reject:K}),this.processNext()})}enqueueMutation($){return this.pendingMutations++,this.enqueue($).finally(()=>{this.pendingMutations--})}hasPendingMutations(){return this.pendingMutations>0}scheduleRefresh($){if(this.pendingMutations>0)return;if(this.refreshScheduled)return;this.refreshScheduled=!0,this.enqueue(async()=>{this.refreshScheduled=!1,await $()}).catch(()=>{this.refreshScheduled=!1})}isBusy(){return this.isProcessing||this.queue.length>0}async processNext(){if(this.isProcessing||this.queue.length===0)return;this.isProcessing=!0;let $=this.queue.shift();try{let J=await $.execute();$.resolve(J)}catch(J){$.reject(J instanceof Error?J:Error(String(J)))}finally{this.isProcessing=!1,this.processNext()}}}var u0=new Map;function u8($){let J=u0.get($);if(!J)J=new g8,u0.set($,J);return J}function m8($){u0.delete($)}import*as C from"node:path";import*as l from"node:fs";import{execFileSync as A9}from"node:child_process";import{watch as f8}from"chokidar";import{EventEmitter as k9}from"node:events";import h8 from"ignore";class m0 extends k9{repoPath;queue;onRefresh;gitWatcher=null;workingDirWatcher=null;ignorers=new Map;diffDebounceTimer=null;_state={status:null,diff:null,combinedFileDiffs:null,selectedFile:null,isLoading:!1,error:null,hunkCounts:null,stashList:[]};constructor($,J,K){super();this.repoPath=$,this.queue=J,this.onRefresh=K??null}get state(){return this._state}updateState($){this._state={...this._state,...$},this.emit("state-change",this._state)}loadGitignores(){let $=new Map,J=h8();J.add(".git");let K=C.join(this.repoPath,".gitignore");if(l.existsSync(K))J.add(l.readFileSync(K,"utf-8"));let X=C.join(this.repoPath,".git","info","exclude");if(l.existsSync(X))J.add(l.readFileSync(X,"utf-8"));$.set("",J);try{let Q=A9("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8"});for(let q of Q.split("\x00")){if(!q||q===".gitignore")continue;if(!q.endsWith(".gitignore"))continue;let Z=C.dirname(q),V=C.join(this.repoPath,q);try{let Y=l.readFileSync(V,"utf-8"),z=h8();z.add(Y),$.set(Z,z)}catch(Y){q$(`Failed to read ${V}: ${Y instanceof Error?Y.message:Y}`)}}}catch{}return $}startWatching(){let $=C.join(this.repoPath,".git");if(!l.existsSync($))return;let J=C.join($,"index"),K=C.join($,"HEAD"),X=C.join($,"refs"),Q=C.join(this.repoPath,".gitignore");this.gitWatcher=f8([J,K,X,Q],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=f8(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(Z)=>{let V=C.relative(this.repoPath,Z);if(!V)return!1;let Y=V.split("/");for(let z=0;z<Y.length;z++){let U=z===0?"":Y.slice(0,z).join("/"),j=this.ignorers.get(U);if(j){let B=z===0?V:Y.slice(z).join("/");if(j.ignores(B))return!0}}return!1},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let q=()=>this.scheduleRefresh();this.gitWatcher.on("change",(Z)=>{if(Z===Q)this.ignorers=this.loadGitignores();q()}),this.gitWatcher.on("add",q),this.gitWatcher.on("unlink",q),this.gitWatcher.on("error",(Z)=>{let V=Z instanceof Error?Z.message:String(Z);this.emit("error",`Git watcher error: ${V}`)}),this.workingDirWatcher.on("change",q),this.workingDirWatcher.on("add",q),this.workingDirWatcher.on("unlink",q),this.workingDirWatcher.on("error",(Z)=>{let V=Z instanceof Error?Z.message:String(Z);this.emit("error",`Working dir watcher error: ${V}`)})}dispose(){if(this.diffDebounceTimer)clearTimeout(this.diffDebounceTimer);this.gitWatcher?.close(),this.workingDirWatcher?.close()}scheduleRefresh(){this.queue.scheduleRefresh(async()=>{if(await this.doRefresh(),this.onRefresh)await this.onRefresh()})}scheduleStatusRefresh(){this.queue.scheduleRefresh(async()=>{let $=await x0(this.repoPath);if(!$.isRepo){this.updateState({status:$,diff:null,isLoading:!1,error:"Not a git repository"});return}this.updateState({status:$,isLoading:!1})})}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.updateState({isLoading:!0,error:null});try{let $=await x0(this.repoPath);if(!$.isRepo){this.updateState({status:$,diff:null,isLoading:!1,error:"Not a git repository"});return}let[J,K]=await Promise.all([h(this.repoPath,void 0,!1),h(this.repoPath,void 0,!0)]),X={unstaged:W0(J.raw),staged:W0(K.raw)},{displayDiff:Q,combinedFileDiffs:q}=await this.resolveFileDiffs($,J);this.updateState({status:$,diff:Q,combinedFileDiffs:q,hunkCounts:X,isLoading:!1})}catch($){this.updateState({isLoading:!1,error:$ instanceof Error?$.message:"Unknown error"})}}async resolveFileDiffs($,J){let K=this._state.selectedFile;if(!K)return{displayDiff:J,combinedFileDiffs:null};let X=$.files.find((V)=>V.path===K.path&&V.staged===K.staged)??$.files.find((V)=>V.path===K.path);if(!X)return this.updateState({selectedFile:null}),{displayDiff:J,combinedFileDiffs:null};if(X.status==="untracked"){let V=await H0(this.repoPath,X.path);return{displayDiff:V,combinedFileDiffs:{unstaged:V,staged:{raw:"",lines:[]}}}}let[Q,q]=await Promise.all([h(this.repoPath,X.path,!1),h(this.repoPath,X.path,!0)]);return{displayDiff:X.staged?q:Q,combinedFileDiffs:{unstaged:Q,staged:q}}}selectFile($){if(this.updateState({selectedFile:$}),!this._state.status?.isRepo)return;if(this.diffDebounceTimer)clearTimeout(this.diffDebounceTimer),this.diffDebounceTimer=setTimeout(()=>{this.diffDebounceTimer=null,this.fetchDiffForSelection()},20);else this.fetchDiffForSelection(),this.diffDebounceTimer=setTimeout(()=>{this.diffDebounceTimer=null},20)}fetchDiffForSelection(){let $=this._state.selectedFile;this.queue.enqueue(async()=>{if($!==this._state.selectedFile)return;await this.doFetchDiffForFile($)}).catch((J)=>{this.updateState({error:`Failed to load diff: ${J instanceof Error?J.message:String(J)}`})})}async doFetchDiffForFile($){if(!$){let X=await o1(this.repoPath);if(this._state.selectedFile===null)this.updateState({diff:X,combinedFileDiffs:null});return}if($.status==="untracked"){let X=await H0(this.repoPath,$.path);if($===this._state.selectedFile)this.updateState({diff:X,combinedFileDiffs:{unstaged:X,staged:{raw:"",lines:[]}}});return}let[J,K]=await Promise.all([h(this.repoPath,$.path,!1),h(this.repoPath,$.path,!0)]);if($===this._state.selectedFile){let X=$.staged?K:J;this.updateState({diff:X,combinedFileDiffs:{unstaged:J,staged:K}})}}async stage($){try{await this.queue.enqueueMutation(()=>G8(this.repoPath,$.path)),this.scheduleStatusRefresh()}catch(J){await this.refresh(),this.updateState({error:`Failed to stage ${$.path}: ${J instanceof Error?J.message:String(J)}`})}}async unstage($){try{await this.queue.enqueueMutation(()=>j8(this.repoPath,$.path)),this.scheduleStatusRefresh()}catch(J){await this.refresh(),this.updateState({error:`Failed to unstage ${$.path}: ${J instanceof Error?J.message:String(J)}`})}}async stageHunk($){try{await this.queue.enqueueMutation(async()=>W8(this.repoPath,$)),this.scheduleRefresh()}catch(J){await this.refresh(),this.updateState({error:`Failed to stage hunk: ${J instanceof Error?J.message:String(J)}`})}}async unstageHunk($){try{await this.queue.enqueueMutation(async()=>H8(this.repoPath,$)),this.scheduleRefresh()}catch(J){await this.refresh(),this.updateState({error:`Failed to unstage hunk: ${J instanceof Error?J.message:String(J)}`})}}async discard($){if($.staged||$.status==="untracked")return;try{await this.queue.enqueueMutation(()=>_8(this.repoPath,$.path)),await this.refresh()}catch(J){this.updateState({error:`Failed to discard ${$.path}: ${J instanceof Error?J.message:String(J)}`})}}async stageAll(){try{await this.queue.enqueueMutation(()=>M8(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to stage all: ${$ instanceof Error?$.message:String($)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>O8(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to unstage all: ${$ instanceof Error?$.message:String($)}`})}}async commit($,J=!1){try{await this.queue.enqueue(()=>D8(this.repoPath,$,J)),await this.refresh()}catch(K){this.updateState({error:`Failed to commit: ${K instanceof Error?K.message:String(K)}`})}}async loadStashList(){try{let $=await this.queue.enqueue(()=>E8(this.repoPath));this.updateState({stashList:$})}catch{}}}import{EventEmitter as N9}from"node:events";class f0 extends N9{repoPath;queue;_historyState={commits:[],selectedCommit:null,commitDiff:null,isLoading:!1};constructor($,J){super();this.repoPath=$,this.queue=J}get historyState(){return this._historyState}updateHistoryState($){this._historyState={...this._historyState,...$},this.emit("history-state-change",this._historyState)}async refreshIfLoaded($=100){if(this._historyState.commits.length>0)await this.doLoadHistory($)}async loadHistory($=100){this.updateHistoryState({isLoading:!0});try{await this.queue.enqueue(()=>this.doLoadHistory($))}catch(J){throw this.updateHistoryState({isLoading:!1}),J}}async doLoadHistory($=100){let J=await N8(this.repoPath,$);this.updateHistoryState({commits:J,selectedCommit:null,commitDiff:null,isLoading:!1})}async selectHistoryCommit($){if(this.updateHistoryState({selectedCommit:$,commitDiff:null}),!$)return;await this.queue.enqueue(async()=>{let J=await u$(this.repoPath,$.hash);this.updateHistoryState({commitDiff:J})})}async getHeadCommitMessage(){return this.queue.enqueue(()=>v8(this.repoPath))}}import{EventEmitter as F9}from"node:events";import*as g from"node:fs";import*as e from"node:path";import*as c8 from"node:os";var s$=e.join(c8.homedir(),".cache","diffstalker","base-branches.json");function E9(){let $=e.dirname(s$);if(!g.existsSync($))g.mkdirSync($,{recursive:!0})}function d8(){try{if(g.existsSync(s$))return JSON.parse(g.readFileSync(s$,"utf-8"))}catch{}return{}}function L9($){E9(),g.writeFileSync(s$,JSON.stringify($,null,2)+`
66
- `)}function l8($){let J=d8(),K=e.resolve($);return J[K]}function r8($,J){let K=d8(),X=e.resolve($);K[X]=J,L9(K)}class h0 extends F9{repoPath;queue;_compareState={compareDiff:null,compareBaseBranch:null,compareLoading:!1,compareError:null};_compareSelectionState={type:null,index:0,diff:null};constructor($,J){super();this.repoPath=$,this.queue=J}get compareState(){return this._compareState}get compareSelectionState(){return this._compareSelectionState}updateCompareState($){this._compareState={...this._compareState,...$},this.emit("compare-state-change",this._compareState)}updateCompareSelectionState($){this._compareSelectionState={...this._compareSelectionState,...$},this.emit("compare-selection-change",this._compareSelectionState)}async refreshIfLoaded(){if(this._compareState.compareBaseBranch)await this.doRefreshCompareDiff(!1)}resetBaseBranch(){this.updateCompareState({compareBaseBranch:null})}async refreshCompareDiff($=!1){this.updateCompareState({compareLoading:!0,compareError:null});try{await this.queue.enqueue(()=>this.doRefreshCompareDiff($))}catch(J){this.updateCompareState({compareLoading:!1,compareError:`Failed to load compare diff: ${J instanceof Error?J.message:String(J)}`})}}async doRefreshCompareDiff($){let J=this._compareState.compareBaseBranch;if(!J)J=l8(this.repoPath)??await s1(this.repoPath),this.updateCompareState({compareBaseBranch:J});if(J){let K=$?await a1(this.repoPath,J):await A0(this.repoPath,J);this.updateCompareState({compareDiff:K,compareLoading:!1})}else this.updateCompareState({compareDiff:null,compareLoading:!1,compareError:"No base branch found"})}async getCandidateBaseBranches(){return T0(this.repoPath)}async setCompareBaseBranch($,J=!1){this.updateCompareState({compareBaseBranch:$}),r8(this.repoPath,$),await this.refreshCompareDiff(J)}async selectCompareCommit($){let J=this._compareState.compareDiff;if(!J||$<0||$>=J.commits.length){this.updateCompareSelectionState({type:null,index:0,diff:null});return}let K=J.commits[$];this.updateCompareSelectionState({type:"commit",index:$,diff:null}),await this.queue.enqueue(async()=>{let X=await u$(this.repoPath,K.hash);this.updateCompareSelectionState({diff:X})})}selectCompareFile($){let J=this._compareState.compareDiff;if(!J||$<0||$>=J.files.length){this.updateCompareSelectionState({type:null,index:0,diff:null});return}let K=J.files[$];this.updateCompareSelectionState({type:"file",index:$,diff:K.diff})}}import{EventEmitter as R9}from"node:events";class c0 extends R9{repoPath;queue;callbacks;_remoteState={operation:null,inProgress:!1,error:null,lastResult:null};constructor($,J,K){super();this.repoPath=$,this.queue=J,this.callbacks=K}get remoteState(){return this._remoteState}updateRemoteState($){this._remoteState={...this._remoteState,...$},this.emit("remote-state-change",this._remoteState)}async runRemoteOperation($,J){this.updateRemoteState({operation:$,inProgress:!0,error:null,lastResult:null});try{let K=await this.queue.enqueue(J);this.updateRemoteState({inProgress:!1,lastResult:K}),this.callbacks.scheduleRefresh()}catch(K){let X=K instanceof Error?K.message:String(K);this.updateRemoteState({inProgress:!1,error:X})}}clearRemoteState(){this.updateRemoteState({operation:null,error:null,lastResult:null})}async push(){if(this._remoteState.inProgress)return;await this.runRemoteOperation("push",()=>T8(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return;await this.runRemoteOperation("fetch",()=>A8(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return;await this.runRemoteOperation("pull",()=>k8(this.repoPath))}async stash($){if(this._remoteState.inProgress)return;await this.runRemoteOperation("stash",()=>L8(this.repoPath,$)),await this.callbacks.loadStashList()}async stashPop($=0){if(this._remoteState.inProgress)return;await this.runRemoteOperation("stashPop",()=>F8(this.repoPath,$)),await this.callbacks.loadStashList()}async getLocalBranches(){return this.queue.enqueue(()=>R8(this.repoPath))}async switchBranch($){if(this._remoteState.inProgress)return;await this.runRemoteOperation("branchSwitch",()=>I8(this.repoPath,$)),this.callbacks.resetCompareBaseBranch()}async createBranch($){if(this._remoteState.inProgress)return;await this.runRemoteOperation("branchCreate",()=>y8(this.repoPath,$)),this.callbacks.resetCompareBaseBranch()}async softReset($=1){if(this._remoteState.inProgress)return;await this.runRemoteOperation("softReset",()=>C8(this.repoPath,$))}async cherryPick($){if(this._remoteState.inProgress)return;await this.runRemoteOperation("cherryPick",()=>P8(this.repoPath,$))}async revertCommit($){if(this._remoteState.inProgress)return;await this.runRemoteOperation("revert",()=>b8(this.repoPath,$))}}class o8{workingTree;history;compare;remote;repoPath;constructor($){this.repoPath=$;let J=u8($);this.history=new f0($,J),this.compare=new h0($,J),this.workingTree=new m0($,J,async()=>{await this.history.refreshIfLoaded(),await this.compare.refreshIfLoaded()}),this.remote=new c0($,J,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList(),resetCompareBaseBranch:()=>this.compare.resetBaseBranch()})}dispose(){this.workingTree.dispose(),m8(this.repoPath)}}var a$=new Map;function s8($){let J=a$.get($);if(!J)J=new o8($),a$.set($,J);return J}function d0($){let J=a$.get($);if(J)J.dispose(),a$.delete($)}function n$($,J,K,X){if(J){let Q=p(K,$);return Q?.unstagedEntry??Q?.stagedEntry??null}return U$(X,$)}function a8($,J,K){if($)return J.length-1;return K.length-1}class l0{screen;layout;uiState;gitManager=null;followMode=null;explorerManager=null;config;commandServer;navigation;staging;modals;repoPath;currentTheme;recentRepos;commitFlowState;commitTextarea=null;remoteClearTimer=null;bottomPaneTotalRows=0;bottomPaneHunkCount=0;bottomPaneHunkBoundaries=[];prevFileCount=0;cachedFlatFiles=[];combinedHunkMapping=[];constructor($){this.config=$.config,this.commandServer=$.commandServer??null,this.repoPath=$.initialPath??process.cwd(),this.currentTheme=$.config.theme,this.recentRepos=$.config.recentRepos??[],this.uiState=new _0({splitRatio:$.config.splitRatio??0.4,autoTabEnabled:$.config.autoTabEnabled??!1,wrapMode:$.config.wrapMode??!1,mouseEnabled:$.config.mouseEnabled??!0}),this.screen=n8.screen({smartCSR:!0,fullUnicode:!0,title:"diffstalker",mouse:!0,terminal:"xterm-256color"});let J=this.screen;if(J.tput)J.tput.colors=256;if(J.program?.tput)J.program.tput.colors=256;if(this.layout=new t$(this.screen,this.uiState.state.splitRatio),this.screen.on("resize",()=>{setImmediate(()=>this.render())}),this.commitFlowState=new g0({getHeadMessage:()=>this.gitManager?.history.getHeadCommitMessage()??Promise.resolve(""),onCommit:async(K,X)=>{await this.gitManager?.workingTree.commit(K,X)},onSuccess:()=>{this.uiState.setTab("diff"),this.render()}}),this.commitTextarea=n8.textarea({parent:this.layout.bottomPane,top:3,left:1,width:"100%-4",height:1,inputOnFocus:!0,hidden:!0,style:{fg:"white",bg:"default"}}),this.commitTextarea.on("submit",()=>{this.commitFlowState.submit()}),this.commitTextarea.on("keypress",()=>{setImmediate(()=>{let K=this.commitTextarea?.getValue()??"";this.commitFlowState.setMessage(K)})}),this.navigation=new D0({uiState:this.uiState,getGitManager:()=>this.gitManager,getExplorerManager:()=>this.explorerManager,getTopPaneHeight:()=>this.layout.dimensions.topPaneHeight,getBottomPaneHeight:()=>this.layout.dimensions.bottomPaneHeight,getCachedFlatFiles:()=>this.cachedFlatFiles,getHunkCount:()=>this.bottomPaneHunkCount,getHunkBoundaries:()=>this.bottomPaneHunkBoundaries,getRepoPath:()=>this.repoPath,onError:(K)=>this.showError(K),resolveFileAtIndex:(K)=>n$(K,this.uiState.state.flatViewMode,this.cachedFlatFiles,this.gitManager?.workingTree.state.status?.files??[]),getFileListMaxIndex:()=>a8(this.uiState.state.flatViewMode,this.cachedFlatFiles,this.gitManager?.workingTree.state.status?.files??[])}),this.modals=new P0({screen:this.screen,uiState:this.uiState,getGitManager:()=>this.gitManager,getExplorerManager:()=>this.explorerManager,getTopPaneHeight:()=>this.layout.dimensions.topPaneHeight,getCurrentTheme:()=>this.currentTheme,setCurrentTheme:(K)=>{this.currentTheme=K},getRepoPath:()=>this.repoPath,getRecentRepos:()=>this.recentRepos,onRepoSwitch:(K)=>this.switchToRepo(K),render:()=>this.render()}),this.staging=new k0({uiState:this.uiState,getGitManager:()=>this.gitManager,getCachedFlatFiles:()=>this.cachedFlatFiles,getCombinedHunkMapping:()=>this.combinedHunkMapping,resolveFileAtIndex:(K)=>n$(K,this.uiState.state.flatViewMode,this.cachedFlatFiles,this.gitManager?.workingTree.state.status?.files??[])}),!this.uiState.state.mouseEnabled)this.screen.program.disableMouse();if(this.setupKeyboardHandlers(),this.setupMouseEventHandlers(),this.setupStateListeners(),this.config.watcherEnabled)this.followMode=new l$(this.config.targetFile,()=>this.repoPath,{onRepoChange:(K,X)=>this.handleFollowRepoChange(K,X),onFileNavigate:(K)=>this.handleFollowFileNavigate(K)}),this.followMode.start();if(this.commandServer)this.setupCommandHandler();this.initGitManager(),this.render()}showError($){if(!this.gitManager)return;let J=this.gitManager.workingTree;J.emit("state-change",{...J.state,error:$})}setupKeyboardHandlers(){s0(this.screen,{exit:()=>this.exit(),navigateDown:()=>this.navigation.navigateDown(),navigateUp:()=>this.navigation.navigateUp(),stageSelected:()=>this.staging.stageSelected(),unstageSelected:()=>this.staging.unstageSelected(),stageAll:()=>this.staging.stageAll(),unstageAll:()=>this.staging.unstageAll(),toggleSelected:()=>this.staging.toggleSelected(),enterExplorerDirectory:()=>this.navigation.enterExplorerDirectory(),goExplorerUp:()=>this.navigation.goExplorerUp(),openFileFinder:()=>this.modals.openFileFinder(),focusCommitInput:()=>this.focusCommitInput(),unfocusCommitInput:()=>this.unfocusCommitInput(),openRepoPicker:()=>this.modals.openRepoPicker(),openThemePicker:()=>this.modals.openThemePicker(),openHotkeysModal:()=>this.modals.openHotkeysModal(),openBaseBranchPicker:()=>this.modals.openBaseBranchPicker(),closeActiveModal:()=>this.modals.closeActiveModal(),toggleMouseMode:()=>this.toggleMouseMode(),toggleFollow:()=>this.toggleFollow(),openDiscardConfirm:($)=>this.modals.openDiscardConfirm($),render:()=>this.render(),toggleCurrentHunk:()=>this.staging.toggleCurrentHunk(),navigateNextHunk:()=>this.navigation.navigateNextHunk(),navigatePrevHunk:()=>this.navigation.navigatePrevHunk(),openCherryPickConfirm:()=>this.modals.openCherryPickConfirm(),openRevertConfirm:()=>this.modals.openRevertConfirm()},{hasActiveModal:()=>this.modals.hasActiveModal(),getActiveModalType:()=>this.modals.getActiveModalType(),getBottomTab:()=>this.uiState.state.bottomTab,getCurrentPane:()=>this.uiState.state.currentPane,getFocusedZone:()=>this.uiState.state.focusedZone,isCommitInputFocused:()=>this.commitFlowState.state.inputFocused,getStatusFiles:()=>this.gitManager?.workingTree.state.status?.files??[],getSelectedIndex:()=>this.uiState.state.selectedIndex,uiState:this.uiState,getExplorerManager:()=>this.explorerManager,commitFlowState:this.commitFlowState,getGitManager:()=>this.gitManager,layout:this.layout,resolveFileAtIndex:($)=>n$($,this.uiState.state.flatViewMode,this.cachedFlatFiles,this.gitManager?.workingTree.state.status?.files??[])})}setupMouseEventHandlers(){l1(this.layout,{selectHistoryCommitByIndex:($)=>this.navigation.selectHistoryCommitByIndex($),selectCompareItem:($)=>this.navigation.selectCompareItem($),selectFileByIndex:($)=>this.navigation.selectFileByIndex($),toggleFileByIndex:($)=>this.staging.toggleFileByIndex($),enterExplorerDirectory:()=>this.navigation.enterExplorerDirectory(),toggleMouseMode:()=>this.toggleMouseMode(),toggleFollow:()=>this.toggleFollow(),selectHunkAtRow:($)=>this.navigation.selectHunkAtRow($),focusCommitInput:()=>this.focusCommitInput(),openHotkeysModal:()=>this.modals.openHotkeysModal(),render:()=>this.render()},{uiState:this.uiState,getExplorerManager:()=>this.explorerManager,getStatusFiles:()=>this.gitManager?.workingTree.state.status?.files??[],getHistoryCommitCount:()=>this.gitManager?.history.historyState.commits.length??0,getCompareCommits:()=>this.gitManager?.compare.compareState?.compareDiff?.commits??[],getCompareFiles:()=>this.gitManager?.compare.compareState?.compareDiff?.files??[],getBottomPaneTotalRows:()=>this.bottomPaneTotalRows,getScreenWidth:()=>this.screen.width||80,getCachedFlatFiles:()=>this.cachedFlatFiles})}setupStateListeners(){let $=this.uiState.state.autoTabEnabled;this.uiState.on("change",(K)=>{if(K.autoTabEnabled&&!$)this.applyAutoTab();$=K.autoTabEnabled}),this.uiState.on("change",()=>{this.render()}),this.uiState.on("tab-change",(K)=>{if(K!=="diff")this.uiState.setSelectedHunkIndex(0);if(K==="history")this.loadHistory();else if(K==="compare")this.gitManager?.compare.refreshCompareDiff(this.uiState.state.includeUncommitted);else if(K==="explorer"){if(!this.explorerManager?.state.displayRows.length)this.explorerManager?.loadDirectory("")}});let J=null;this.uiState.on("change",(K)=>{if(J)clearTimeout(J);J=setTimeout(()=>{let X={};if(K.splitRatio!==this.config.splitRatio)X.splitRatio=K.splitRatio;if(K.autoTabEnabled!==this.config.autoTabEnabled)X.autoTabEnabled=K.autoTabEnabled;if(K.wrapMode!==this.config.wrapMode)X.wrapMode=K.wrapMode;if(K.mouseEnabled!==this.config.mouseEnabled)X.mouseEnabled=K.mouseEnabled;if(Object.keys(X).length>0)M$(X)},500)})}handleFollowRepoChange($,J){let K=this.repoPath;this.repoPath=$,this.initGitManager(K),this.resetRepoSpecificState(),this.loadCurrentTabData(),this.render()}handleFollowFileNavigate($){this.navigation.navigateToFile($),this.render()}recordCurrentRepo(){let $=this.config.maxRecentRepos??10,J=this.repoPath.replace(/\/$/,"");this.recentRepos=[J,...this.recentRepos.map((K)=>K.replace(/\/$/,"")).filter((K)=>K!==J)].slice(0,$),e1(this.repoPath,$)}switchToRepo($){if($===this.repoPath)return;if(this.followMode?.isEnabled)this.followMode.stop();let J=this.repoPath;this.repoPath=$,this.initGitManager(J),this.resetRepoSpecificState(),this.loadCurrentTabData(),this.render()}initGitManager($){if(this.gitManager)this.gitManager.workingTree.removeAllListeners(),this.gitManager.history.removeAllListeners(),this.gitManager.compare.removeAllListeners(),this.gitManager.remote.removeAllListeners(),d0($??this.repoPath);this.gitManager=s8(this.repoPath),this.gitManager.workingTree.on("state-change",()=>{if(!this.gitManager?.workingTree.state.isLoading)this.reconcileSelectionAfterStateChange(),this.applyAutoTab();this.updateExplorerGitStatus(),this.render()}),this.gitManager.history.on("history-state-change",(J)=>{if(J.commits.length>0&&!J.selectedCommit){let K=this.uiState.state;if(K.bottomTab==="history")this.navigation.selectHistoryCommitByIndex(K.historySelectedIndex)}this.render()}),this.gitManager.compare.on("compare-state-change",()=>{this.render()}),this.gitManager.compare.on("compare-selection-change",()=>{this.render()}),this.gitManager.remote.on("remote-state-change",(J)=>{if(this.remoteClearTimer)clearTimeout(this.remoteClearTimer);if(J.lastResult&&!J.inProgress)this.remoteClearTimer=setTimeout(()=>{this.gitManager?.remote.clearRemoteState()},3000);else if(J.error)this.remoteClearTimer=setTimeout(()=>{this.gitManager?.remote.clearRemoteState()},5000);this.render()}),this.gitManager.workingTree.startWatching(),this.gitManager.workingTree.refresh(),this.initExplorerManager(),this.recordCurrentRepo()}loadHistory($=100){this.gitManager?.history.loadHistory($).catch((J)=>{this.showError(`Failed to load history: ${J instanceof Error?J.message:String(J)}`)})}reconcileSelectionAfterStateChange(){let $=this.gitManager?.workingTree.state.status?.files??[],J=this.staging.consumePendingFlatSelectionPath();if(this.uiState.state.flatViewMode&&J){let Q=p$($,this.gitManager?.workingTree.state.hunkCounts??null),q=r1(Q,J);if(q>=0)this.uiState.setSelectedIndex(q),this.navigation.selectFileByIndex(q);else if(Q.length>0){let Z=Math.min(this.uiState.state.selectedIndex,Q.length-1);this.uiState.setSelectedIndex(Z),this.navigation.selectFileByIndex(Z)}return}let K=this.staging.consumePendingSelectionAnchor();if(K){let Q=a0($,K.category,K.categoryIndex);this.uiState.setSelectedIndex(Q),this.navigation.selectFileByIndex(Q);return}let X=this.gitManager?.workingTree.state.selectedFile??null;if(this.uiState.state.flatViewMode){let Q=p$($,this.gitManager?.workingTree.state.hunkCounts??null),q=Q.length-1,Z=this.uiState.state.selectedIndex;if(q>=0&&Z>q)Z=q,this.uiState.setSelectedIndex(Z);let V=p(Q,Z),Y=V?.unstagedEntry??V?.stagedEntry??null;if(Y&&(Y.path!==X?.path||Y.staged!==X?.staged))this.navigation.selectFileByIndex(Z)}else if($.length>0){let Q=$.length-1,q=this.uiState.state.selectedIndex;if(q>Q)q=Q,this.uiState.setSelectedIndex(q);let Z=U$($,q);if(Z&&(Z.path!==X?.path||Z.staged!==X?.staged))this.navigation.selectFileByIndex(q)}}initExplorerManager(){if(this.explorerManager)this.explorerManager.dispose();let $={hideHidden:!0,hideGitignored:!0,showOnlyChanges:!1};this.explorerManager=new p0(this.repoPath,$),this.explorerManager.on("state-change",()=>{this.render()}),this.explorerManager.loadDirectory(""),this.explorerManager.loadFilePaths(),this.updateExplorerGitStatus()}updateExplorerGitStatus(){if(!this.explorerManager||!this.gitManager)return;let $=this.gitManager.workingTree.state.status?.files??[],J={files:new Map,directories:new Set};for(let K of $){J.files.set(K.path,{status:K.status,staged:K.staged});let X=K.path.split("/"),Q="";for(let q=0;q<X.length-1;q++)Q=Q?`${Q}/${X[q]}`:X[q],J.directories.add(Q);J.directories.add("")}this.explorerManager.setGitStatus(J)}resetRepoSpecificState(){this.navigation.compareSelection=null,this.uiState.resetForNewRepo()}loadCurrentTabData(){let $=this.uiState.state.bottomTab;if($==="history")this.loadHistory();else if($==="compare")this.gitManager?.compare.refreshCompareDiff(this.uiState.state.includeUncommitted)}setupCommandHandler(){if(!this.commandServer)return;let $={navigateUp:()=>this.navigation.navigateUp(),navigateDown:()=>this.navigation.navigateDown(),switchTab:(J)=>this.uiState.setTab(J),togglePane:()=>this.uiState.togglePane(),stage:async()=>this.staging.stageSelected(),unstage:async()=>this.staging.unstageSelected(),stageAll:async()=>this.staging.stageAll(),unstageAll:async()=>this.staging.unstageAll(),commit:async(J)=>this.commit(J),refresh:async()=>this.refresh(),getState:()=>this.getAppState(),quit:()=>this.exit()};this.commandServer.setHandler($),this.commandServer.notifyReady()}getAppState(){let $=this.uiState.state,J=this.gitManager?.workingTree.state,K=this.gitManager?.history.historyState,X=J?.status?.files??[],Q=K?.commits??[];return{currentTab:$.bottomTab,currentPane:$.currentPane,selectedIndex:$.selectedIndex,totalFiles:X.length,stagedCount:X.filter((q)=>q.staged).length,files:X.map((q)=>({path:q.path,status:q.status,staged:q.staged})),historySelectedIndex:$.historySelectedIndex,historyCommitCount:Q.length,compareSelectedIndex:$.compareSelectedIndex,compareTotalItems:0,includeUncommitted:$.includeUncommitted,explorerPath:this.repoPath,explorerSelectedIndex:$.explorerSelectedIndex,explorerItemCount:0,wrapMode:$.wrapMode,mouseEnabled:$.mouseEnabled,autoTabEnabled:$.autoTabEnabled}}async commit($){await this.gitManager?.workingTree.commit($)}async refresh(){await this.gitManager?.workingTree.refresh()}toggleMouseMode(){let $=!this.uiState.state.mouseEnabled;this.uiState.toggleMouse();let J=this.screen.program;if($)J.enableMouse();else J.disableMouse()}applyAutoTab(){let J=(this.gitManager?.workingTree.state.status?.files??[]).length,K=this.prevFileCount;if(this.prevFileCount=J,!this.uiState.state.autoTabEnabled)return;let X=this.uiState.state.bottomTab;if(K>0&&J===0&&(X==="diff"||X==="commit"))this.uiState.setHistorySelectedIndex(0),this.uiState.setHistoryScrollOffset(0),this.uiState.setTab("history");else if(K===0&&J>0&&X==="history")this.uiState.setTab("diff")}toggleFollow(){if(!this.followMode)this.followMode=new l$(this.config.targetFile,()=>this.repoPath,{onRepoChange:($,J)=>this.handleFollowRepoChange($,J),onFileNavigate:($)=>this.handleFollowFileNavigate($)});this.followMode.toggle(),this.render()}focusCommitInput(){if(this.commitTextarea)this.commitTextarea.show(),this.commitTextarea.focus(),this.commitTextarea.setValue(this.commitFlowState.state.message),this.commitFlowState.setInputFocused(!0),this.render()}unfocusCommitInput(){if(this.commitTextarea){let $=this.commitTextarea.getValue()??"";this.commitFlowState.setMessage($),this.commitTextarea.hide(),this.commitFlowState.setInputFocused(!1),this.screen.focusPush(this.layout.bottomPane),this.render()}}render(){this.updateHeader(),this.updateTopPane(),this.updateBottomPane();let $=this.staging.consumePendingHunkIndex();if($!==null&&this.bottomPaneHunkCount>0){let J=Math.min($,this.bottomPaneHunkCount-1);this.uiState.setSelectedHunkIndex(J),this.updateBottomPane()}this.updateSeparators(),this.updateFooter(),this.screen.render()}updateSeparators(){let $=this.uiState.state.focusedZone,J=$==="fileList"||$==="historyList"||$==="compareList"||$==="explorerTree";this.layout.middleSeparator.style.fg=J?"cyan":"gray"}updateHeader(){let $=this.gitManager?.workingTree.state,J=this.screen.width||80,K=Q8(this.repoPath,$?.status?.branch??null,$?.isLoading??!1,$?.error??null,J,this.gitManager?.remote.remoteState??null);this.layout.headerBox.setContent(K)}updateTopPane(){let $=this.uiState.state,J=this.screen.width||80,K=this.gitManager?.workingTree.state.status?.files??[];if($.flatViewMode)this.cachedFlatFiles=p$(K,this.gitManager?.workingTree.state.hunkCounts??null);let X=m1($,K,this.gitManager?.history.historyState?.commits??[],this.gitManager?.compare.compareState?.compareDiff??null,this.navigation.compareSelection,this.explorerManager?.state,J,this.layout.dimensions.topPaneHeight,this.gitManager?.workingTree.state.hunkCounts,$.flatViewMode?this.cachedFlatFiles:void 0);this.layout.topPane.setContent(X)}updateBottomPane(){let $=this.uiState.state,J=this.screen.width||80,X=(this.gitManager?.workingTree.state.status?.files??[]).filter((B)=>B.staged).length;this.commitFlowState.setStagedCount(X);let Q=$.bottomTab==="diff"&&$.currentPane==="diff",q=Q?$.selectedHunkIndex:void 0,Z=Q?this.gitManager?.workingTree.state.selectedFile?.staged:void 0,{content:V,totalRows:Y,hunkCount:z,hunkBoundaries:U,hunkMapping:j}=f1($,this.gitManager?.workingTree.state.diff??null,this.gitManager?.history.historyState,this.gitManager?.compare.compareSelectionState,this.explorerManager?.state?.selectedFile??null,this.commitFlowState.state,X,this.currentTheme,J,this.layout.dimensions.bottomPaneHeight,q,Z,$.flatViewMode?this.gitManager?.workingTree.state.combinedFileDiffs:void 0,$.focusedZone);if(this.bottomPaneTotalRows=Y,this.bottomPaneHunkCount=z,this.bottomPaneHunkBoundaries=U,this.combinedHunkMapping=j??[],this.uiState.clampSelectedHunkIndex(z),this.layout.bottomPane.setContent(V),this.commitTextarea)if($.bottomTab==="commit"&&this.commitFlowState.state.inputFocused)this.commitTextarea.show();else this.commitTextarea.hide()}updateFooter(){let $=this.uiState.state,J=this.screen.width||80,K=Z8($.bottomTab,$.mouseEnabled,$.autoTabEnabled,$.wrapMode,this.followMode?.isEnabled??!1,this.explorerManager?.showOnlyChanges??!1,J,$.currentPane);this.layout.footerBox.setContent(K)}exit(){if(this.gitManager)d0(this.repoPath);if(this.explorerManager)this.explorerManager.dispose();if(this.followMode)this.followMode.stop();if(this.commandServer)this.commandServer.stop();if(this.remoteClearTimer)clearTimeout(this.remoteClearTimer);this.screen.destroy()}start(){return new Promise(($)=>{this.screen.on("destroy",()=>{$()})})}}import*as i8 from"net";import*as r from"fs";import{EventEmitter as I9}from"events";class r0 extends I9{server=null;socketPath;handler=null;ready=!1;constructor($){super();this.socketPath=$}setHandler($){this.handler=$}notifyReady(){this.ready=!0,this.emit("ready")}isReady(){return this.ready&&this.handler!==null}async start(){if(r.existsSync(this.socketPath))r.unlinkSync(this.socketPath);return new Promise(($,J)=>{this.server=i8.createServer((K)=>{this.handleConnection(K)}),this.server.on("error",(K)=>{J(K)}),this.server.listen(this.socketPath,()=>{r.chmodSync(this.socketPath,384),$()})})}stop(){if(this.server)this.server.close(),this.server=null;if(r.existsSync(this.socketPath))r.unlinkSync(this.socketPath)}handleConnection($){let J="";$.on("data",async(K)=>{J+=K.toString();let X=J.split(`
65
+ ... (truncated, ${V.length-Z} more lines)`,q=!0;this.updateState({selectedFile:{path:$,content:Q,truncated:q}})}catch(J){this.updateState({selectedFile:{path:$,content:J instanceof Error?`Error: ${J.message}`:"Failed to read file"}})}}async selectIndex($){let J=this._state.displayRows;if($<0||$>=J.length)return;let K=J[$];if(this.updateState({selectedIndex:$}),K&&!K.node.isDirectory)await this.loadFile(K.node.path);else this.updateState({selectedFile:null})}navigateUp($){let J=Math.max(0,this._state.selectedIndex-1);if(J===this._state.selectedIndex)return null;if(this.selectIndex(J),J<$)return J;return null}navigateDown($,J){let K=Math.min(this._state.displayRows.length-1,this._state.selectedIndex+1);if(K===this._state.selectedIndex)return null;this.selectIndex(K);let Q=this._state.displayRows.length>J?J-2:J,q=$+Q;if(K>=q)return $+1;return null}async toggleExpand(){let $=this._state.displayRows,J=this._state.selectedIndex;if(J<0||J>=$.length)return;let K=$[J];if(!K.node.isDirectory)return;let X=K.node;if(X.expanded)this.expandedPaths.delete(X.path),X.expanded=!1;else if(this.expandedPaths.add(X.path),X.expanded=!0,!X.childrenLoaded)await this.loadChildrenForNode(X),this.applyGitStatusToTree(X);this.refreshDisplayRows()}async enterDirectory(){let $=this._state.displayRows,J=this._state.selectedIndex;if(J<0||J>=$.length)return;if($[J].node.isDirectory)await this.toggleExpand()}async goUp(){let $=this._state.displayRows,J=this._state.selectedIndex;if(J<0||J>=$.length)return;let X=$[J].node.path,Q=C.dirname(X);if(Q==="."||Q==="")return;let q=X.split("/");for(let Z=q.length-1;Z>0;Z--){let V=q.slice(0,Z).join("/");if(this.expandedPaths.has(V)){this.expandedPaths.delete(V);let Y=this.findNodeByPath(V);if(Y)Y.expanded=!1;this.refreshDisplayRows();let U=this._state.displayRows.findIndex((j)=>j.node.path===V);if(U>=0)this.updateState({selectedIndex:U,selectedFile:null});return}}}findNodeByPath($){if(!this._state.tree)return null;let J=(K)=>{if(K.path===$)return K;for(let X of K.children){let Q=J(X);if(Q)return Q}return null};return J(this._state.tree)}async loadFilePaths(){if(!this._isGitRepo){this._cachedFilePaths=[];return}try{this._cachedFilePaths=await S8(this.repoPath)}catch($){Z$(`Failed to load file paths: ${$ instanceof Error?$.message:$}`),this._cachedFilePaths=[]}}getCachedFilePaths(){return this._cachedFilePaths??[]}async navigateToPath($){if(!this._state.tree)return!1;let J=$.split("/"),K="";for(let Q=0;Q<J.length-1;Q++)K=K?`${K}/${J[Q]}`:J[Q],this.expandedPaths.add(K);await this.loadTree();let X=this._state.displayRows.findIndex((Q)=>Q.node.path===$);if(X>=0)return await this.selectIndex(X),!0;return!1}dispose(){this.removeAllListeners()}}import{EventEmitter as N9}from"node:events";function w8($,J,K){if(!$.trim())return{valid:!1,error:"Commit message cannot be empty"};if(J===0&&!K)return{valid:!1,error:"No changes staged for commit"};return{valid:!0,error:null}}function x8($){return $.trim()}var p8={message:"",amend:!1,isCommitting:!1,error:null,inputFocused:!1};class g0 extends N9{_state={...p8};getHeadMessage;onCommit;onSuccess;stagedCount=0;constructor($){super();this.getHeadMessage=$.getHeadMessage,this.onCommit=$.onCommit,this.onSuccess=$.onSuccess}get state(){return this._state}update($){this._state={...this._state,...$},this.emit("change",this._state)}setStagedCount($){this.stagedCount=$}setMessage($){this.update({message:$,error:null})}setInputFocused($){this.update({inputFocused:$}),this.emit("focus-change",$)}async toggleAmend(){let $=!this._state.amend;if(this.update({amend:$}),$&&!this._state.message)try{let J=await this.getHeadMessage();if(J)this.update({message:J})}catch{}}async submit(){let $=w8(this._state.message,this.stagedCount,this._state.amend);if(!$.valid){this.update({error:$.error});return}this.update({isCommitting:!0,error:null});try{await this.onCommit(x8(this._state.message),this._state.amend),this.update({message:"",amend:!1,isCommitting:!1,inputFocused:!1}),this.onSuccess()}catch(J){this.update({isCommitting:!1,error:J instanceof Error?J.message:"Commit failed"})}}reset(){this._state={...p8},this.emit("change",this._state)}}class g8{queue=[];isProcessing=!1;pendingMutations=0;refreshScheduled=!1;enqueue($){return new Promise((J,K)=>{this.queue.push({execute:$,resolve:J,reject:K}),this.processNext()})}enqueueMutation($){return this.pendingMutations++,this.enqueue($).finally(()=>{this.pendingMutations--})}hasPendingMutations(){return this.pendingMutations>0}scheduleRefresh($){if(this.pendingMutations>0)return;if(this.refreshScheduled)return;this.refreshScheduled=!0,this.enqueue(async()=>{this.refreshScheduled=!1,await $()}).catch(()=>{this.refreshScheduled=!1})}isBusy(){return this.isProcessing||this.queue.length>0}async processNext(){if(this.isProcessing||this.queue.length===0)return;this.isProcessing=!0;let $=this.queue.shift();try{let J=await $.execute();$.resolve(J)}catch(J){$.reject(J instanceof Error?J:Error(String(J)))}finally{this.isProcessing=!1,this.processNext()}}}var u0=new Map;function u8($){let J=u0.get($);if(!J)J=new g8,u0.set($,J);return J}function m8($){u0.delete($)}import*as P from"node:path";import*as r from"node:fs";import{execFileSync as E9}from"node:child_process";import{watch as f8}from"chokidar";import{EventEmitter as L9}from"node:events";import h8 from"ignore";class m0 extends L9{repoPath;queue;onRefresh;gitWatcher=null;workingDirWatcher=null;ignorers=new Map;diffDebounceTimer=null;_state={status:null,diff:null,combinedFileDiffs:null,selectedFile:null,isLoading:!1,error:null,hunkCounts:null,stashList:[]};constructor($,J,K){super();this.repoPath=$,this.queue=J,this.onRefresh=K??null}get state(){return this._state}updateState($){this._state={...this._state,...$},this.emit("state-change",this._state)}loadGitignores(){let $=new Map,J=h8();J.add(".git");let K=P.join(this.repoPath,".gitignore");if(r.existsSync(K))J.add(r.readFileSync(K,"utf-8"));let X=P.join(this.repoPath,".git","info","exclude");if(r.existsSync(X))J.add(r.readFileSync(X,"utf-8"));$.set("",J);try{let Q=E9("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8"});for(let q of Q.split("\x00")){if(!q||q===".gitignore")continue;if(!q.endsWith(".gitignore"))continue;let Z=P.dirname(q),V=P.join(this.repoPath,q);try{let Y=r.readFileSync(V,"utf-8"),z=h8();z.add(Y),$.set(Z,z)}catch(Y){Z$(`Failed to read ${V}: ${Y instanceof Error?Y.message:Y}`)}}}catch{}return $}startWatching(){let $=P.join(this.repoPath,".git");if(!r.existsSync($))return;let J=P.join($,"index"),K=P.join($,"HEAD"),X=P.join($,"refs"),Q=P.join(this.repoPath,".gitignore");this.gitWatcher=f8([J,K,X,Q],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=f8(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(Z)=>{let V=P.relative(this.repoPath,Z);if(!V)return!1;let Y=V.split("/");for(let z=0;z<Y.length;z++){let U=z===0?"":Y.slice(0,z).join("/"),j=this.ignorers.get(U);if(j){let B=z===0?V:Y.slice(z).join("/");if(j.ignores(B))return!0}}return!1},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let q=()=>this.scheduleRefresh();this.gitWatcher.on("change",(Z)=>{if(Z===Q)this.ignorers=this.loadGitignores();q()}),this.gitWatcher.on("add",q),this.gitWatcher.on("unlink",q),this.gitWatcher.on("error",(Z)=>{let V=Z instanceof Error?Z.message:String(Z);this.emit("error",`Git watcher error: ${V}`)}),this.workingDirWatcher.on("change",q),this.workingDirWatcher.on("add",q),this.workingDirWatcher.on("unlink",q),this.workingDirWatcher.on("error",(Z)=>{let V=Z instanceof Error?Z.message:String(Z);this.emit("error",`Working dir watcher error: ${V}`)})}dispose(){if(this.diffDebounceTimer)clearTimeout(this.diffDebounceTimer);this.gitWatcher?.close(),this.workingDirWatcher?.close()}scheduleRefresh(){this.queue.scheduleRefresh(async()=>{if(await this.doRefresh(),this.onRefresh)await this.onRefresh()})}scheduleStatusRefresh(){this.queue.scheduleRefresh(async()=>{let $=await x0(this.repoPath);if(!$.isRepo){this.updateState({status:$,diff:null,isLoading:!1,error:"Not a git repository"});return}this.updateState({status:$,isLoading:!1})})}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.updateState({isLoading:!0,error:null});try{let $=await x0(this.repoPath);if(!$.isRepo){this.updateState({status:$,diff:null,isLoading:!1,error:"Not a git repository"});return}let[J,K]=await Promise.all([h(this.repoPath,void 0,!1),h(this.repoPath,void 0,!0)]),X={unstaged:v0(J.raw),staged:v0(K.raw)},{displayDiff:Q,combinedFileDiffs:q}=await this.resolveFileDiffs($,J);this.updateState({status:$,diff:Q,combinedFileDiffs:q,hunkCounts:X,isLoading:!1})}catch($){this.updateState({isLoading:!1,error:$ instanceof Error?$.message:"Unknown error"})}}async resolveFileDiffs($,J){let K=this._state.selectedFile;if(!K)return{displayDiff:J,combinedFileDiffs:null};let X=$.files.find((V)=>V.path===K.path&&V.staged===K.staged)??$.files.find((V)=>V.path===K.path);if(!X)return this.updateState({selectedFile:null}),{displayDiff:J,combinedFileDiffs:null};if(X.status==="untracked"){let V=await H0(this.repoPath,X.path);return{displayDiff:V,combinedFileDiffs:{unstaged:V,staged:{raw:"",lines:[]}}}}let[Q,q]=await Promise.all([h(this.repoPath,X.path,!1),h(this.repoPath,X.path,!0)]);return{displayDiff:X.staged?q:Q,combinedFileDiffs:{unstaged:Q,staged:q}}}selectFile($){if(this.updateState({selectedFile:$}),!this._state.status?.isRepo)return;if(this.diffDebounceTimer)clearTimeout(this.diffDebounceTimer),this.diffDebounceTimer=setTimeout(()=>{this.diffDebounceTimer=null,this.fetchDiffForSelection()},20);else this.fetchDiffForSelection(),this.diffDebounceTimer=setTimeout(()=>{this.diffDebounceTimer=null},20)}fetchDiffForSelection(){let $=this._state.selectedFile;this.queue.enqueue(async()=>{if($!==this._state.selectedFile)return;await this.doFetchDiffForFile($)}).catch((J)=>{this.updateState({error:`Failed to load diff: ${J instanceof Error?J.message:String(J)}`})})}async doFetchDiffForFile($){if(!$){let X=await o1(this.repoPath);if(this._state.selectedFile===null)this.updateState({diff:X,combinedFileDiffs:null});return}if($.status==="untracked"){let X=await H0(this.repoPath,$.path);if($===this._state.selectedFile)this.updateState({diff:X,combinedFileDiffs:{unstaged:X,staged:{raw:"",lines:[]}}});return}let[J,K]=await Promise.all([h(this.repoPath,$.path,!1),h(this.repoPath,$.path,!0)]);if($===this._state.selectedFile){let X=$.staged?K:J;this.updateState({diff:X,combinedFileDiffs:{unstaged:J,staged:K}})}}async stage($){try{await this.queue.enqueueMutation(()=>G8(this.repoPath,$.path)),this.scheduleStatusRefresh()}catch(J){await this.refresh(),this.updateState({error:`Failed to stage ${$.path}: ${J instanceof Error?J.message:String(J)}`})}}async unstage($){try{await this.queue.enqueueMutation(()=>j8(this.repoPath,$.path)),this.scheduleStatusRefresh()}catch(J){await this.refresh(),this.updateState({error:`Failed to unstage ${$.path}: ${J instanceof Error?J.message:String(J)}`})}}async stageHunk($){try{await this.queue.enqueueMutation(async()=>v8(this.repoPath,$)),this.scheduleRefresh()}catch(J){await this.refresh(),this.updateState({error:`Failed to stage hunk: ${J instanceof Error?J.message:String(J)}`})}}async unstageHunk($){try{await this.queue.enqueueMutation(async()=>H8(this.repoPath,$)),this.scheduleRefresh()}catch(J){await this.refresh(),this.updateState({error:`Failed to unstage hunk: ${J instanceof Error?J.message:String(J)}`})}}async discard($){if($.staged||$.status==="untracked")return;try{await this.queue.enqueueMutation(()=>_8(this.repoPath,$.path)),await this.refresh()}catch(J){this.updateState({error:`Failed to discard ${$.path}: ${J instanceof Error?J.message:String(J)}`})}}async stageAll(){try{await this.queue.enqueueMutation(()=>M8(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to stage all: ${$ instanceof Error?$.message:String($)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>O8(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to unstage all: ${$ instanceof Error?$.message:String($)}`})}}async commit($,J=!1){try{await this.queue.enqueue(()=>D8(this.repoPath,$,J)),await this.refresh()}catch(K){this.updateState({error:`Failed to commit: ${K instanceof Error?K.message:String(K)}`})}}async loadStashList(){try{let $=await this.queue.enqueue(()=>E8(this.repoPath));this.updateState({stashList:$})}catch{}}}import{EventEmitter as F9}from"node:events";class f0 extends F9{repoPath;queue;_historyState={commits:[],selectedCommit:null,commitDiff:null,isLoading:!1};constructor($,J){super();this.repoPath=$,this.queue=J}get historyState(){return this._historyState}updateHistoryState($){this._historyState={...this._historyState,...$},this.emit("history-state-change",this._historyState)}async refreshIfLoaded($=100){if(this._historyState.commits.length>0)await this.doLoadHistory($)}async loadHistory($=100){this.updateHistoryState({isLoading:!0});try{await this.queue.enqueue(()=>this.doLoadHistory($))}catch(J){throw this.updateHistoryState({isLoading:!1}),J}}async doLoadHistory($=100){let J=await N8(this.repoPath,$);this.updateHistoryState({commits:J,selectedCommit:null,commitDiff:null,isLoading:!1})}async selectHistoryCommit($){if(this.updateHistoryState({selectedCommit:$,commitDiff:null}),!$)return;await this.queue.enqueue(async()=>{let J=await u$(this.repoPath,$.hash);this.updateHistoryState({commitDiff:J})})}async getHeadCommitMessage(){return this.queue.enqueue(()=>W8(this.repoPath))}}import{EventEmitter as y9}from"node:events";import*as g from"node:fs";import*as $$ from"node:path";import*as c8 from"node:os";var s$=$$.join(c8.homedir(),".cache","diffstalker","base-branches.json");function R9(){let $=$$.dirname(s$);if(!g.existsSync($))g.mkdirSync($,{recursive:!0})}function d8(){try{if(g.existsSync(s$))return JSON.parse(g.readFileSync(s$,"utf-8"))}catch{}return{}}function I9($){R9(),g.writeFileSync(s$,JSON.stringify($,null,2)+`
66
+ `)}function l8($){let J=d8(),K=$$.resolve($);return J[K]}function r8($,J){let K=d8(),X=$$.resolve($);K[X]=J,I9(K)}class h0 extends y9{repoPath;queue;_compareState={compareDiff:null,compareBaseBranch:null,compareLoading:!1,compareError:null};_compareSelectionState={type:null,index:0,diff:null};constructor($,J){super();this.repoPath=$,this.queue=J}get compareState(){return this._compareState}get compareSelectionState(){return this._compareSelectionState}updateCompareState($){this._compareState={...this._compareState,...$},this.emit("compare-state-change",this._compareState)}updateCompareSelectionState($){this._compareSelectionState={...this._compareSelectionState,...$},this.emit("compare-selection-change",this._compareSelectionState)}async refreshIfLoaded(){if(this._compareState.compareBaseBranch)await this.doRefreshCompareDiff(!1)}resetBaseBranch(){this.updateCompareState({compareBaseBranch:null})}async refreshCompareDiff($=!1){this.updateCompareState({compareLoading:!0,compareError:null});try{await this.queue.enqueue(()=>this.doRefreshCompareDiff($))}catch(J){this.updateCompareState({compareLoading:!1,compareError:`Failed to load compare diff: ${J instanceof Error?J.message:String(J)}`})}}async doRefreshCompareDiff($){let J=this._compareState.compareBaseBranch;if(!J)J=l8(this.repoPath)??await s1(this.repoPath),this.updateCompareState({compareBaseBranch:J});if(J){let K=$?await a1(this.repoPath,J):await A0(this.repoPath,J);this.updateCompareState({compareDiff:K,compareLoading:!1})}else this.updateCompareState({compareDiff:null,compareLoading:!1,compareError:"No base branch found"})}async getCandidateBaseBranches(){return T0(this.repoPath)}async setCompareBaseBranch($,J=!1){this.updateCompareState({compareBaseBranch:$}),r8(this.repoPath,$),await this.refreshCompareDiff(J)}async selectCompareCommit($){let J=this._compareState.compareDiff;if(!J||$<0||$>=J.commits.length){this.updateCompareSelectionState({type:null,index:0,diff:null});return}let K=J.commits[$];this.updateCompareSelectionState({type:"commit",index:$,diff:null}),await this.queue.enqueue(async()=>{let X=await u$(this.repoPath,K.hash);this.updateCompareSelectionState({diff:X})})}selectCompareFile($){let J=this._compareState.compareDiff;if(!J||$<0||$>=J.files.length){this.updateCompareSelectionState({type:null,index:0,diff:null});return}let K=J.files[$];this.updateCompareSelectionState({type:"file",index:$,diff:K.diff})}}import{EventEmitter as C9}from"node:events";class c0 extends C9{repoPath;queue;callbacks;_remoteState={operation:null,inProgress:!1,error:null,lastResult:null};constructor($,J,K){super();this.repoPath=$,this.queue=J,this.callbacks=K}get remoteState(){return this._remoteState}updateRemoteState($){this._remoteState={...this._remoteState,...$},this.emit("remote-state-change",this._remoteState)}async runRemoteOperation($,J){this.updateRemoteState({operation:$,inProgress:!0,error:null,lastResult:null});try{let K=await this.queue.enqueue(J);this.updateRemoteState({inProgress:!1,lastResult:K}),this.callbacks.scheduleRefresh()}catch(K){let X=K instanceof Error?K.message:String(K);this.updateRemoteState({inProgress:!1,error:X})}}clearRemoteState(){this.updateRemoteState({operation:null,error:null,lastResult:null})}async push(){if(this._remoteState.inProgress)return;await this.runRemoteOperation("push",()=>T8(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return;await this.runRemoteOperation("fetch",()=>A8(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return;await this.runRemoteOperation("pull",()=>k8(this.repoPath))}async stash($){if(this._remoteState.inProgress)return;await this.runRemoteOperation("stash",()=>L8(this.repoPath,$)),await this.callbacks.loadStashList()}async stashPop($=0){if(this._remoteState.inProgress)return;await this.runRemoteOperation("stashPop",()=>F8(this.repoPath,$)),await this.callbacks.loadStashList()}async getLocalBranches(){return this.queue.enqueue(()=>R8(this.repoPath))}async switchBranch($){if(this._remoteState.inProgress)return;await this.runRemoteOperation("branchSwitch",()=>I8(this.repoPath,$)),this.callbacks.resetCompareBaseBranch()}async createBranch($){if(this._remoteState.inProgress)return;await this.runRemoteOperation("branchCreate",()=>y8(this.repoPath,$)),this.callbacks.resetCompareBaseBranch()}async softReset($=1){if(this._remoteState.inProgress)return;await this.runRemoteOperation("softReset",()=>C8(this.repoPath,$))}async cherryPick($){if(this._remoteState.inProgress)return;await this.runRemoteOperation("cherryPick",()=>P8(this.repoPath,$))}async revertCommit($){if(this._remoteState.inProgress)return;await this.runRemoteOperation("revert",()=>b8(this.repoPath,$))}}class o8{workingTree;history;compare;remote;repoPath;constructor($){this.repoPath=$;let J=u8($);this.history=new f0($,J),this.compare=new h0($,J),this.workingTree=new m0($,J,async()=>{await this.history.refreshIfLoaded(),await this.compare.refreshIfLoaded()}),this.remote=new c0($,J,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList(),resetCompareBaseBranch:()=>this.compare.resetBaseBranch()})}dispose(){this.workingTree.dispose(),m8(this.repoPath)}}var a$=new Map;function s8($){let J=a$.get($);if(!J)J=new o8($),a$.set($,J);return J}function d0($){let J=a$.get($);if(J)J.dispose(),a$.delete($)}function n$($,J,K,X){if(J){let Q=p(K,$);return Q?.unstagedEntry??Q?.stagedEntry??null}return U$(X,$)}function a8($,J,K){if($)return J.length-1;return K.length-1}class l0{screen;layout;uiState;gitManager=null;followMode=null;explorerManager=null;config;commandServer;navigation;staging;modals;repoPath;currentTheme;recentRepos;commitFlowState;commitTextarea=null;remoteClearTimer=null;bottomPaneTotalRows=0;bottomPaneHunkCount=0;bottomPaneHunkBoundaries=[];prevFileCount=0;cachedFlatFiles=[];combinedHunkMapping=[];constructor($){this.config=$.config,this.commandServer=$.commandServer??null,this.repoPath=$.initialPath??process.cwd(),this.currentTheme=$.config.theme,this.recentRepos=$.config.recentRepos??[],this.uiState=new _0({splitRatio:$.config.splitRatio??0.4,autoTabEnabled:$.config.autoTabEnabled??!1,wrapMode:$.config.wrapMode??!1,mouseEnabled:$.config.mouseEnabled??!0}),this.screen=n8.screen({smartCSR:!0,fullUnicode:!0,title:"diffstalker",mouse:!0,terminal:"xterm-256color"});let J=this.screen;if(J.tput)J.tput.colors=256;if(J.program?.tput)J.program.tput.colors=256;if(this.layout=new t$(this.screen,this.uiState.state.splitRatio),this.screen.on("resize",()=>{setImmediate(()=>this.render())}),this.commitFlowState=new g0({getHeadMessage:()=>this.gitManager?.history.getHeadCommitMessage()??Promise.resolve(""),onCommit:async(K,X)=>{await this.gitManager?.workingTree.commit(K,X)},onSuccess:()=>{this.uiState.setTab("diff"),this.render()}}),this.commitTextarea=n8.textarea({parent:this.layout.bottomPane,top:3,left:1,width:"100%-4",height:1,inputOnFocus:!0,hidden:!0,style:{fg:"white",bg:"default"}}),this.commitTextarea.on("submit",()=>{this.commitFlowState.submit()}),this.commitTextarea.on("keypress",()=>{setImmediate(()=>{let K=this.commitTextarea?.getValue()??"";this.commitFlowState.setMessage(K)})}),this.navigation=new D0({uiState:this.uiState,getGitManager:()=>this.gitManager,getExplorerManager:()=>this.explorerManager,getTopPaneHeight:()=>this.layout.dimensions.topPaneHeight,getBottomPaneHeight:()=>this.layout.dimensions.bottomPaneHeight,getCachedFlatFiles:()=>this.cachedFlatFiles,getHunkCount:()=>this.bottomPaneHunkCount,getHunkBoundaries:()=>this.bottomPaneHunkBoundaries,getRepoPath:()=>this.repoPath,onError:(K)=>this.showError(K),resolveFileAtIndex:(K)=>n$(K,this.uiState.state.flatViewMode,this.cachedFlatFiles,this.gitManager?.workingTree.state.status?.files??[]),getFileListMaxIndex:()=>a8(this.uiState.state.flatViewMode,this.cachedFlatFiles,this.gitManager?.workingTree.state.status?.files??[])}),this.modals=new P0({screen:this.screen,uiState:this.uiState,getGitManager:()=>this.gitManager,getExplorerManager:()=>this.explorerManager,getTopPaneHeight:()=>this.layout.dimensions.topPaneHeight,getCurrentTheme:()=>this.currentTheme,setCurrentTheme:(K)=>{this.currentTheme=K},getRepoPath:()=>this.repoPath,getRecentRepos:()=>this.recentRepos,onRepoSwitch:(K)=>this.switchToRepo(K),render:()=>this.render()}),this.staging=new k0({uiState:this.uiState,getGitManager:()=>this.gitManager,getCachedFlatFiles:()=>this.cachedFlatFiles,getCombinedHunkMapping:()=>this.combinedHunkMapping,resolveFileAtIndex:(K)=>n$(K,this.uiState.state.flatViewMode,this.cachedFlatFiles,this.gitManager?.workingTree.state.status?.files??[])}),!this.uiState.state.mouseEnabled)this.screen.program.disableMouse();if(this.setupKeyboardHandlers(),this.setupMouseEventHandlers(),this.setupStateListeners(),this.config.watcherEnabled)this.followMode=new l$(this.config.targetFile,()=>this.repoPath,{onRepoChange:(K,X)=>this.handleFollowRepoChange(K,X),onFileNavigate:(K)=>this.handleFollowFileNavigate(K)}),this.followMode.start();if(this.commandServer)this.setupCommandHandler();this.initGitManager(),this.render()}showError($){if(!this.gitManager)return;let J=this.gitManager.workingTree;J.emit("state-change",{...J.state,error:$})}setupKeyboardHandlers(){s0(this.screen,{exit:()=>this.exit(),navigateDown:()=>this.navigation.navigateDown(),navigateUp:()=>this.navigation.navigateUp(),stageSelected:()=>this.staging.stageSelected(),unstageSelected:()=>this.staging.unstageSelected(),stageAll:()=>this.staging.stageAll(),unstageAll:()=>this.staging.unstageAll(),toggleSelected:()=>this.staging.toggleSelected(),enterExplorerDirectory:()=>this.navigation.enterExplorerDirectory(),goExplorerUp:()=>this.navigation.goExplorerUp(),openFileFinder:()=>this.modals.openFileFinder(),focusCommitInput:()=>this.focusCommitInput(),unfocusCommitInput:()=>this.unfocusCommitInput(),openRepoPicker:()=>this.modals.openRepoPicker(),openThemePicker:()=>this.modals.openThemePicker(),openHotkeysModal:()=>this.modals.openHotkeysModal(),openBaseBranchPicker:()=>this.modals.openBaseBranchPicker(),closeActiveModal:()=>this.modals.closeActiveModal(),toggleMouseMode:()=>this.toggleMouseMode(),toggleFollow:()=>this.toggleFollow(),openDiscardConfirm:($)=>this.modals.openDiscardConfirm($),render:()=>this.render(),toggleCurrentHunk:()=>this.staging.toggleCurrentHunk(),navigateNextHunk:()=>this.navigation.navigateNextHunk(),navigatePrevHunk:()=>this.navigation.navigatePrevHunk(),openCherryPickConfirm:()=>this.modals.openCherryPickConfirm(),openRevertConfirm:()=>this.modals.openRevertConfirm()},{hasActiveModal:()=>this.modals.hasActiveModal(),getActiveModalType:()=>this.modals.getActiveModalType(),getBottomTab:()=>this.uiState.state.bottomTab,getCurrentPane:()=>this.uiState.state.currentPane,getFocusedZone:()=>this.uiState.state.focusedZone,isCommitInputFocused:()=>this.commitFlowState.state.inputFocused,getStatusFiles:()=>this.gitManager?.workingTree.state.status?.files??[],getSelectedIndex:()=>this.uiState.state.selectedIndex,uiState:this.uiState,getExplorerManager:()=>this.explorerManager,commitFlowState:this.commitFlowState,getGitManager:()=>this.gitManager,layout:this.layout,resolveFileAtIndex:($)=>n$($,this.uiState.state.flatViewMode,this.cachedFlatFiles,this.gitManager?.workingTree.state.status?.files??[])})}setupMouseEventHandlers(){l1(this.layout,{selectHistoryCommitByIndex:($)=>this.navigation.selectHistoryCommitByIndex($),selectCompareItem:($)=>this.navigation.selectCompareItem($),selectFileByIndex:($)=>this.navigation.selectFileByIndex($),toggleFileByIndex:($)=>this.staging.toggleFileByIndex($),enterExplorerDirectory:()=>this.navigation.enterExplorerDirectory(),toggleMouseMode:()=>this.toggleMouseMode(),toggleFollow:()=>this.toggleFollow(),selectHunkAtRow:($)=>this.navigation.selectHunkAtRow($),focusCommitInput:()=>this.focusCommitInput(),openHotkeysModal:()=>this.modals.openHotkeysModal(),render:()=>this.render()},{uiState:this.uiState,getExplorerManager:()=>this.explorerManager,getStatusFiles:()=>this.gitManager?.workingTree.state.status?.files??[],getHistoryCommitCount:()=>this.gitManager?.history.historyState.commits.length??0,getCompareCommits:()=>this.gitManager?.compare.compareState?.compareDiff?.commits??[],getCompareFiles:()=>this.gitManager?.compare.compareState?.compareDiff?.files??[],getBottomPaneTotalRows:()=>this.bottomPaneTotalRows,getScreenWidth:()=>this.screen.width||80,getCachedFlatFiles:()=>this.cachedFlatFiles})}setupStateListeners(){let $=this.uiState.state.autoTabEnabled;this.uiState.on("change",(K)=>{if(K.autoTabEnabled&&!$)this.applyAutoTab();$=K.autoTabEnabled}),this.uiState.on("change",()=>{this.render()}),this.uiState.on("tab-change",(K)=>{if(K!=="diff")this.uiState.setSelectedHunkIndex(0);if(K==="history")this.loadHistory();else if(K==="compare")this.gitManager?.compare.refreshCompareDiff(this.uiState.state.includeUncommitted);else if(K==="explorer"){if(!this.explorerManager?.state.displayRows.length)this.explorerManager?.loadDirectory("")}});let J=null;this.uiState.on("change",(K)=>{if(J)clearTimeout(J);J=setTimeout(()=>{let X={};if(K.splitRatio!==this.config.splitRatio)X.splitRatio=K.splitRatio;if(K.autoTabEnabled!==this.config.autoTabEnabled)X.autoTabEnabled=K.autoTabEnabled;if(K.wrapMode!==this.config.wrapMode)X.wrapMode=K.wrapMode;if(K.mouseEnabled!==this.config.mouseEnabled)X.mouseEnabled=K.mouseEnabled;if(Object.keys(X).length>0)M$(X)},500)})}handleFollowRepoChange($,J){let K=this.repoPath;this.repoPath=$,this.initGitManager(K),this.resetRepoSpecificState(),this.loadCurrentTabData(),this.render()}handleFollowFileNavigate($){this.navigation.navigateToFile($),this.render()}recordCurrentRepo(){let $=this.config.maxRecentRepos??10,J=this.repoPath.replace(/\/$/,"");this.recentRepos=[J,...this.recentRepos.map((K)=>K.replace(/\/$/,"")).filter((K)=>K!==J)].slice(0,$),e1(this.repoPath,$)}switchToRepo($){if($===this.repoPath)return;if(this.followMode?.isEnabled)this.followMode.stop();let J=this.repoPath;this.repoPath=$,this.initGitManager(J),this.resetRepoSpecificState(),this.loadCurrentTabData(),this.render()}initGitManager($){if(this.gitManager)this.gitManager.workingTree.removeAllListeners(),this.gitManager.history.removeAllListeners(),this.gitManager.compare.removeAllListeners(),this.gitManager.remote.removeAllListeners(),d0($??this.repoPath);this.gitManager=s8(this.repoPath),this.gitManager.workingTree.on("state-change",()=>{if(!this.gitManager?.workingTree.state.isLoading)this.reconcileSelectionAfterStateChange(),this.applyAutoTab();this.updateExplorerGitStatus(),this.render()}),this.gitManager.history.on("history-state-change",(J)=>{if(J.commits.length>0&&!J.selectedCommit){let K=this.uiState.state;if(K.bottomTab==="history")this.navigation.selectHistoryCommitByIndex(K.historySelectedIndex)}this.render()}),this.gitManager.compare.on("compare-state-change",()=>{this.render()}),this.gitManager.compare.on("compare-selection-change",()=>{this.render()}),this.gitManager.remote.on("remote-state-change",(J)=>{if(this.remoteClearTimer)clearTimeout(this.remoteClearTimer);if(J.lastResult&&!J.inProgress)this.remoteClearTimer=setTimeout(()=>{this.gitManager?.remote.clearRemoteState()},3000);else if(J.error)this.remoteClearTimer=setTimeout(()=>{this.gitManager?.remote.clearRemoteState()},5000);this.render()}),this.gitManager.workingTree.startWatching(),this.gitManager.workingTree.refresh(),this.initExplorerManager(),this.recordCurrentRepo()}loadHistory($=100){this.gitManager?.history.loadHistory($).catch((J)=>{this.showError(`Failed to load history: ${J instanceof Error?J.message:String(J)}`)})}reconcileSelectionAfterStateChange(){let $=this.gitManager?.workingTree.state.status?.files??[],J=this.staging.consumePendingFlatSelectionPath();if(this.uiState.state.flatViewMode&&J){let Q=p$($,this.gitManager?.workingTree.state.hunkCounts??null),q=r1(Q,J);if(q>=0)this.uiState.setSelectedIndex(q),this.navigation.selectFileByIndex(q);else if(Q.length>0){let Z=Math.min(this.uiState.state.selectedIndex,Q.length-1);this.uiState.setSelectedIndex(Z),this.navigation.selectFileByIndex(Z)}return}let K=this.staging.consumePendingSelectionAnchor();if(K){let Q=a0($,K.category,K.categoryIndex);this.uiState.setSelectedIndex(Q),this.navigation.selectFileByIndex(Q);return}let X=this.gitManager?.workingTree.state.selectedFile??null;if(this.uiState.state.flatViewMode){let Q=p$($,this.gitManager?.workingTree.state.hunkCounts??null),q=Q.length-1,Z=this.uiState.state.selectedIndex;if(q>=0&&Z>q)Z=q,this.uiState.setSelectedIndex(Z);let V=p(Q,Z),Y=V?.unstagedEntry??V?.stagedEntry??null;if(Y&&(Y.path!==X?.path||Y.staged!==X?.staged))this.navigation.selectFileByIndex(Z)}else if($.length>0){let Q=$.length-1,q=this.uiState.state.selectedIndex;if(q>Q)q=Q,this.uiState.setSelectedIndex(q);let Z=U$($,q);if(Z&&(Z.path!==X?.path||Z.staged!==X?.staged))this.navigation.selectFileByIndex(q)}}initExplorerManager(){if(this.explorerManager)this.explorerManager.dispose();let $={hideHidden:!0,hideGitignored:!0,showOnlyChanges:!1};this.explorerManager=new p0(this.repoPath,$),this.explorerManager.on("state-change",()=>{this.render()}),this.explorerManager.loadDirectory(""),this.explorerManager.loadFilePaths(),this.updateExplorerGitStatus()}updateExplorerGitStatus(){if(!this.explorerManager||!this.gitManager)return;let $=this.gitManager.workingTree.state.status?.files??[],J={files:new Map,directories:new Set};for(let K of $){J.files.set(K.path,{status:K.status,staged:K.staged});let X=K.path.split("/"),Q="";for(let q=0;q<X.length-1;q++)Q=Q?`${Q}/${X[q]}`:X[q],J.directories.add(Q);J.directories.add("")}this.explorerManager.setGitStatus(J)}resetRepoSpecificState(){this.navigation.compareSelection=null,this.uiState.resetForNewRepo()}loadCurrentTabData(){let $=this.uiState.state.bottomTab;if($==="history")this.loadHistory();else if($==="compare")this.gitManager?.compare.refreshCompareDiff(this.uiState.state.includeUncommitted)}setupCommandHandler(){if(!this.commandServer)return;let $={navigateUp:()=>this.navigation.navigateUp(),navigateDown:()=>this.navigation.navigateDown(),switchTab:(J)=>this.uiState.setTab(J),togglePane:()=>this.uiState.togglePane(),stage:async()=>this.staging.stageSelected(),unstage:async()=>this.staging.unstageSelected(),stageAll:async()=>this.staging.stageAll(),unstageAll:async()=>this.staging.unstageAll(),commit:async(J)=>this.commit(J),refresh:async()=>this.refresh(),getState:()=>this.getAppState(),quit:()=>this.exit()};this.commandServer.setHandler($),this.commandServer.notifyReady()}getAppState(){let $=this.uiState.state,J=this.gitManager?.workingTree.state,K=this.gitManager?.history.historyState,X=J?.status?.files??[],Q=K?.commits??[];return{currentTab:$.bottomTab,currentPane:$.currentPane,selectedIndex:$.selectedIndex,totalFiles:X.length,stagedCount:X.filter((q)=>q.staged).length,files:X.map((q)=>({path:q.path,status:q.status,staged:q.staged})),historySelectedIndex:$.historySelectedIndex,historyCommitCount:Q.length,compareSelectedIndex:$.compareSelectedIndex,compareTotalItems:0,includeUncommitted:$.includeUncommitted,explorerPath:this.repoPath,explorerSelectedIndex:$.explorerSelectedIndex,explorerItemCount:0,wrapMode:$.wrapMode,mouseEnabled:$.mouseEnabled,autoTabEnabled:$.autoTabEnabled}}async commit($){await this.gitManager?.workingTree.commit($)}async refresh(){await this.gitManager?.workingTree.refresh()}toggleMouseMode(){let $=!this.uiState.state.mouseEnabled;this.uiState.toggleMouse();let J=this.screen.program;if($)J.enableMouse();else J.disableMouse()}applyAutoTab(){let J=(this.gitManager?.workingTree.state.status?.files??[]).length,K=this.prevFileCount;if(this.prevFileCount=J,!this.uiState.state.autoTabEnabled)return;let X=this.uiState.state.bottomTab;if(K>0&&J===0&&(X==="diff"||X==="commit"))this.uiState.setHistorySelectedIndex(0),this.uiState.setHistoryScrollOffset(0),this.uiState.setTab("history");else if(K===0&&J>0&&X==="history")this.uiState.setTab("diff")}toggleFollow(){if(!this.followMode)this.followMode=new l$(this.config.targetFile,()=>this.repoPath,{onRepoChange:($,J)=>this.handleFollowRepoChange($,J),onFileNavigate:($)=>this.handleFollowFileNavigate($)});this.followMode.toggle(),this.render()}focusCommitInput(){if(this.commitTextarea)this.commitTextarea.show(),this.commitTextarea.focus(),this.commitTextarea.setValue(this.commitFlowState.state.message),this.commitFlowState.setInputFocused(!0),this.render()}unfocusCommitInput(){if(this.commitTextarea){let $=this.commitTextarea.getValue()??"";this.commitFlowState.setMessage($),this.commitTextarea.hide(),this.commitFlowState.setInputFocused(!1),this.screen.focusPush(this.layout.bottomPane),this.render()}}render(){this.updateHeader(),this.updateTopPane(),this.updateBottomPane();let $=this.staging.consumePendingHunkIndex();if($!==null&&this.bottomPaneHunkCount>0){let J=Math.min($,this.bottomPaneHunkCount-1);this.uiState.setSelectedHunkIndex(J),this.updateBottomPane()}this.updateSeparators(),this.updateFooter(),this.screen.render()}updateSeparators(){let $=this.uiState.state.focusedZone,J=$==="fileList"||$==="historyList"||$==="compareList"||$==="explorerTree";this.layout.middleSeparator.style.fg=J?"cyan":"gray"}updateHeader(){let $=this.gitManager?.workingTree.state,J=this.screen.width||80,K=Q8(this.repoPath,$?.status?.branch??null,$?.isLoading??!1,$?.error??null,J,this.gitManager?.remote.remoteState??null);this.layout.headerBox.setContent(K)}updateTopPane(){let $=this.uiState.state,J=this.screen.width||80,K=this.gitManager?.workingTree.state.status?.files??[];if($.flatViewMode)this.cachedFlatFiles=p$(K,this.gitManager?.workingTree.state.hunkCounts??null);let X=m1($,K,this.gitManager?.history.historyState?.commits??[],this.gitManager?.compare.compareState?.compareDiff??null,this.navigation.compareSelection,this.explorerManager?.state,J,this.layout.dimensions.topPaneHeight,this.gitManager?.workingTree.state.hunkCounts,$.flatViewMode?this.cachedFlatFiles:void 0);this.layout.topPane.setContent(X)}updateBottomPane(){let $=this.uiState.state,J=this.screen.width||80,X=(this.gitManager?.workingTree.state.status?.files??[]).filter((B)=>B.staged).length;this.commitFlowState.setStagedCount(X);let Q=$.bottomTab==="diff"&&$.currentPane==="diff",q=Q?$.selectedHunkIndex:void 0,Z=Q?this.gitManager?.workingTree.state.selectedFile?.staged:void 0,{content:V,totalRows:Y,hunkCount:z,hunkBoundaries:U,hunkMapping:j}=f1($,this.gitManager?.workingTree.state.diff??null,this.gitManager?.history.historyState,this.gitManager?.compare.compareSelectionState,this.explorerManager?.state?.selectedFile??null,this.commitFlowState.state,X,this.currentTheme,J,this.layout.dimensions.bottomPaneHeight,q,Z,$.flatViewMode?this.gitManager?.workingTree.state.combinedFileDiffs:void 0,$.focusedZone);if(this.bottomPaneTotalRows=Y,this.bottomPaneHunkCount=z,this.bottomPaneHunkBoundaries=U,this.combinedHunkMapping=j??[],this.uiState.clampSelectedHunkIndex(z),this.layout.bottomPane.setContent(V),this.commitTextarea)if($.bottomTab==="commit"&&this.commitFlowState.state.inputFocused)this.commitTextarea.show();else this.commitTextarea.hide()}updateFooter(){let $=this.uiState.state,J=this.screen.width||80,K=Z8($.bottomTab,$.mouseEnabled,$.autoTabEnabled,$.wrapMode,this.followMode?.isEnabled??!1,this.explorerManager?.showOnlyChanges??!1,J,$.currentPane);this.layout.footerBox.setContent(K)}exit(){if(this.gitManager)d0(this.repoPath);if(this.explorerManager)this.explorerManager.dispose();if(this.followMode)this.followMode.stop();if(this.commandServer)this.commandServer.stop();if(this.remoteClearTimer)clearTimeout(this.remoteClearTimer);this.screen.destroy()}start(){return new Promise(($)=>{this.screen.on("destroy",()=>{$()})})}}import*as i8 from"net";import*as o from"fs";import{EventEmitter as P9}from"events";class r0 extends P9{server=null;socketPath;handler=null;ready=!1;constructor($){super();this.socketPath=$}setHandler($){this.handler=$}notifyReady(){this.ready=!0,this.emit("ready")}isReady(){return this.ready&&this.handler!==null}async start(){if(o.existsSync(this.socketPath))o.unlinkSync(this.socketPath);return new Promise(($,J)=>{this.server=i8.createServer((K)=>{this.handleConnection(K)}),this.server.on("error",(K)=>{J(K)}),this.server.listen(this.socketPath,()=>{o.chmodSync(this.socketPath,384),$()})})}stop(){if(this.server)this.server.close(),this.server=null;if(o.existsSync(this.socketPath))o.unlinkSync(this.socketPath)}handleConnection($){let J="";$.on("data",async(K)=>{J+=K.toString();let X=J.split(`
67
67
  `);J=X.pop()||"";for(let Q of X)if(Q.trim()){let q=await this.processCommand(Q);$.write(JSON.stringify(q)+`
68
- `)}}),$.on("error",(K)=>{this.emit("error",K)})}async processCommand($){try{let J=JSON.parse($);if(J.action==="ping")return{success:!0,ready:this.isReady()};if(!this.handler)return{success:!1,error:"No handler registered"};switch(J.action){case"navigateUp":return this.handler.navigateUp(),{success:!0};case"navigateDown":return this.handler.navigateDown(),{success:!0};case"switchTab":return this.handler.switchTab(J.tab),{success:!0};case"togglePane":return this.handler.togglePane(),{success:!0};case"stage":return await this.handler.stage(),{success:!0};case"unstage":return await this.handler.unstage(),{success:!0};case"stageAll":return await this.handler.stageAll(),{success:!0};case"unstageAll":return await this.handler.unstageAll(),{success:!0};case"commit":return await this.handler.commit(J.message),{success:!0};case"refresh":return await this.handler.refresh(),{success:!0};case"getState":return{success:!0,state:this.handler.getState()};case"quit":return this.handler.quit(),{success:!0};default:return{success:!1,error:`Unknown action: ${J.action}`}}}catch(J){return{success:!1,error:J instanceof Error?J.message:String(J)}}}}function $$(){process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1000l"),process.stdout.write("\x1B[?1003l"),process.stdout.write("\x1B[?25h")}$$();process.on("exit",$$);process.on("SIGINT",()=>{$$(),process.exit(0)});process.on("SIGTERM",()=>{$$(),process.exit(0)});process.on("uncaughtException",($)=>{$$(),console.error("Uncaught exception:",$),process.exit(1)});process.on("unhandledRejection",($)=>{$$(),console.error("Unhandled rejection:",$),process.exit(1)});function y9($){let J={};for(let K=0;K<$.length;K++){let X=$[K];if(X==="--follow"||X==="-f"){if(J.follow=!0,$[K+1]&&!$[K+1].startsWith("-"))J.followFile=$[++K]}else if(X==="--once")J.once=!0;else if(X==="--debug"||X==="-d")J.debug=!0;else if(X==="--socket"||X==="-s")if($[K+1]&&!$[K+1].startsWith("-"))J.socket=$[++K];else console.error("Error: --socket requires a path argument"),process.exit(1);else if(X==="--help"||X==="-h")console.log(`
68
+ `)}}),$.on("error",(K)=>{this.emit("error",K)})}async processCommand($){try{let J=JSON.parse($);if(J.action==="ping")return{success:!0,ready:this.isReady()};if(!this.handler)return{success:!1,error:"No handler registered"};switch(J.action){case"navigateUp":return this.handler.navigateUp(),{success:!0};case"navigateDown":return this.handler.navigateDown(),{success:!0};case"switchTab":return this.handler.switchTab(J.tab),{success:!0};case"togglePane":return this.handler.togglePane(),{success:!0};case"stage":return await this.handler.stage(),{success:!0};case"unstage":return await this.handler.unstage(),{success:!0};case"stageAll":return await this.handler.stageAll(),{success:!0};case"unstageAll":return await this.handler.unstageAll(),{success:!0};case"commit":return await this.handler.commit(J.message),{success:!0};case"refresh":return await this.handler.refresh(),{success:!0};case"getState":return{success:!0,state:this.handler.getState()};case"quit":return this.handler.quit(),{success:!0};default:return{success:!1,error:`Unknown action: ${J.action}`}}}catch(J){return{success:!1,error:J instanceof Error?J.message:String(J)}}}}function J$(){process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1000l"),process.stdout.write("\x1B[?1003l"),process.stdout.write("\x1B[?25h")}J$();process.on("exit",J$);process.on("SIGINT",()=>{J$(),process.exit(0)});process.on("SIGTERM",()=>{J$(),process.exit(0)});process.on("uncaughtException",($)=>{J$(),console.error("Uncaught exception:",$),process.exit(1)});process.on("unhandledRejection",($)=>{J$(),console.error("Unhandled rejection:",$),process.exit(1)});function b9($){let J={};for(let K=0;K<$.length;K++){let X=$[K];if(X==="--follow"||X==="-f"){if(J.follow=!0,$[K+1]&&!$[K+1].startsWith("-"))J.followFile=$[++K]}else if(X==="--once")J.once=!0;else if(X==="--debug"||X==="-d")J.debug=!0;else if(X==="--socket"||X==="-s")if($[K+1]&&!$[K+1].startsWith("-"))J.socket=$[++K];else console.error("Error: --socket requires a path argument"),process.exit(1);else if(X==="--help"||X==="-h")console.log(`
69
69
  diffstalker - Terminal git diff/status viewer
70
70
 
71
71
  Usage: diffstalker [options] [path]
@@ -106,4 +106,4 @@ Keyboard:
106
106
  Mouse:
107
107
  Click Select file / focus pane
108
108
  Scroll Navigate files / scroll diff
109
- `),process.exit(0);else if(!X.startsWith("-"))J.initialPath=X}return J}async function C9(){let $=y9(process.argv.slice(2)),J=i1();if($.follow){if(J.watcherEnabled=!0,$.followFile)J.targetFile=$.followFile}if($.debug)J.debug=!0,$8(!0);let K=null;if($.socket){K=new r0($.socket);try{await K.start()}catch(Q){console.error("Failed to start command server:",Q),process.exit(1)}}if(await new l0({config:J,initialPath:$.initialPath,commandServer:K}).start(),K)K.stop();process.exit(0)}C9().catch(($)=>{console.error("Fatal error:",$),$$(),process.exit(1)});
109
+ `),process.exit(0);else if(!X.startsWith("-"))J.initialPath=X}return J}async function S9(){let $=b9(process.argv.slice(2)),J=i1();if($.follow){if(J.watcherEnabled=!0,$.followFile)J.targetFile=$.followFile}if($.debug)J.debug=!0,$8(!0);let K=null;if($.socket){K=new r0($.socket);try{await K.start()}catch(Q){console.error("Failed to start command server:",Q),process.exit(1)}}if(await new l0({config:J,initialPath:$.initialPath,commandServer:K}).start(),K)K.stop();process.exit(0)}S9().catch(($)=>{console.error("Fatal error:",$),J$(),process.exit(1)});