diffstalkerd 0.13.5 → 0.13.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,56 +1,49 @@
1
- var c5=Object.create;var{getPrototypeOf:u5,defineProperty:_6,getOwnPropertyNames:p5}=Object;var f5=Object.prototype.hasOwnProperty;function h5($){return this[$]}var d5,l5,n5=($,Z,K)=>{var V=$!=null&&typeof $==="object";if(V){var Q=Z?d5??=new WeakMap:l5??=new WeakMap,Y=Q.get($);if(Y)return Y}K=$!=null?c5(u5($)):{};let X=Z||!$||!$.__esModule?_6(K,"default",{value:$,enumerable:!0}):K;for(let J of p5($))if(!f5.call(X,J))_6(X,J,{get:h5.bind($,J),enumerable:!0});if(V)Q.set($,X);return X};var o5=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var V4=o5((eK,K4)=>{var b=-1,x=1,k=0;function s$($,Z,K,V,Q){if($===Z){if($)return[[k,$]];return[]}if(K!=null){var Y=Y7($,Z,K);if(Y)return Y}var X=Z6($,Z),J=$.substring(0,X);$=$.substring(X),Z=Z.substring(X),X=BZ($,Z);var W=$.substring($.length-X);$=$.substring(0,$.length-X),Z=Z.substring(0,Z.length-X);var z=r1($,Z);if(J)z.unshift([k,J]);if(W)z.push([k,W]);if(K6(z,Q),V)$7(z);return z}function r1($,Z){var K;if(!$)return[[x,Z]];if(!Z)return[[b,$]];var V=$.length>Z.length?$:Z,Q=$.length>Z.length?Z:$,Y=V.indexOf(Q);if(Y!==-1){if(K=[[x,V.substring(0,Y)],[k,Q],[x,V.substring(Y+Q.length)]],$.length>Z.length)K[0][0]=K[2][0]=b;return K}if(Q.length===1)return[[b,$],[x,Z]];var X=e1($,Z);if(X){var J=X[0],W=X[1],z=X[2],U=X[3],j=X[4],G=s$(J,z),M=s$(W,U);return G.concat([[k,j]],M)}return t1($,Z)}function t1($,Z){var K=$.length,V=Z.length,Q=Math.ceil((K+V)/2),Y=Q,X=2*Q,J=Array(X),W=Array(X);for(var z=0;z<X;z++)J[z]=-1,W[z]=-1;J[Y+1]=0,W[Y+1]=0;var U=K-V,j=U%2!==0,G=0,M=0,C=0,H=0;for(var D=0;D<Q;D++){for(var q=-D+G;q<=D-M;q+=2){var S=Y+q,R;if(q===-D||q!==D&&J[S-1]<J[S+1])R=J[S+1];else R=J[S-1]+1;var v=R-q;while(R<K&&v<V&&$.charAt(R)===Z.charAt(v))R++,v++;if(J[S]=R,R>K)M+=2;else if(v>V)G+=2;else if(j){var N=Y+U-q;if(N>=0&&N<X&&W[N]!==-1){var A=K-W[N];if(R>=A)return o8($,Z,R,v)}}}for(var T=-D+C;T<=D-H;T+=2){var N=Y+T,A;if(T===-D||T!==D&&W[N-1]<W[N+1])A=W[N+1];else A=W[N-1]+1;var F=A-T;while(A<K&&F<V&&$.charAt(K-A-1)===Z.charAt(V-F-1))A++,F++;if(W[N]=A,A>K)H+=2;else if(F>V)C+=2;else if(!j){var S=Y+U-T;if(S>=0&&S<X&&J[S]!==-1){var R=J[S],v=Y+R-S;if(A=K-A,R>=A)return o8($,Z,R,v)}}}}return[[b,$],[x,Z]]}function o8($,Z,K,V){var Q=$.substring(0,K),Y=Z.substring(0,V),X=$.substring(K),J=Z.substring(V),W=s$(Q,Y),z=s$(X,J);return W.concat(z)}function Z6($,Z){if(!$||!Z||$.charAt(0)!==Z.charAt(0))return 0;var K=0,V=Math.min($.length,Z.length),Q=V,Y=0;while(K<Q){if($.substring(Y,Q)==Z.substring(Y,Q))K=Q,Y=K;else V=Q;Q=Math.floor((V-K)/2+K)}if(t8($.charCodeAt(Q-1)))Q--;return Q}function a8($,Z){var K=$.length,V=Z.length;if(K==0||V==0)return 0;if(K>V)$=$.substring(K-V);else if(K<V)Z=Z.substring(0,K);var Q=Math.min(K,V);if($==Z)return Q;var Y=0,X=1;while(!0){var J=$.substring(Q-X),W=Z.indexOf(J);if(W==-1)return Y;if(X+=W,W==0||$.substring(Q-X)==Z.substring(0,X))Y=X,X++}}function BZ($,Z){if(!$||!Z||$.slice(-1)!==Z.slice(-1))return 0;var K=0,V=Math.min($.length,Z.length),Q=V,Y=0;while(K<Q){if($.substring($.length-Q,$.length-Y)==Z.substring(Z.length-Q,Z.length-Y))K=Q,Y=K;else V=Q;Q=Math.floor((V-K)/2+K)}if(e8($.charCodeAt($.length-Q)))Q--;return Q}function e1($,Z){var K=$.length>Z.length?$:Z,V=$.length>Z.length?Z:$;if(K.length<4||V.length*2<K.length)return null;function Q(M,C,H){var D=M.substring(H,H+Math.floor(M.length/4)),q=-1,S="",R,v,N,A;while((q=C.indexOf(D,q+1))!==-1){var T=Z6(M.substring(H),C.substring(q)),F=BZ(M.substring(0,H),C.substring(0,q));if(S.length<F+T)S=C.substring(q-F,q)+C.substring(q,q+T),R=M.substring(0,H-F),v=M.substring(H+T),N=C.substring(0,q-F),A=C.substring(q+T)}if(S.length*2>=M.length)return[R,v,N,A,S];else return null}var Y=Q(K,V,Math.ceil(K.length/4)),X=Q(K,V,Math.ceil(K.length/2)),J;if(!Y&&!X)return null;else if(!X)J=Y;else if(!Y)J=X;else J=Y[4].length>X[4].length?Y:X;var W,z,U,j;if($.length>Z.length)W=J[0],z=J[1],U=J[2],j=J[3];else U=J[0],j=J[1],W=J[2],z=J[3];var G=J[4];return[W,z,U,j,G]}function $7($){var Z=!1,K=[],V=0,Q=null,Y=0,X=0,J=0,W=0,z=0;while(Y<$.length){if($[Y][0]==k)K[V++]=Y,X=W,J=z,W=0,z=0,Q=$[Y][1];else{if($[Y][0]==x)W+=$[Y][1].length;else z+=$[Y][1].length;if(Q&&Q.length<=Math.max(X,J)&&Q.length<=Math.max(W,z))$.splice(K[V-1],0,[b,Q]),$[K[V-1]+1][0]=x,V--,V--,Y=V>0?K[V-1]:-1,X=0,J=0,W=0,z=0,Q=null,Z=!0}Y++}if(Z)K6($);V7($),Y=1;while(Y<$.length){if($[Y-1][0]==b&&$[Y][0]==x){var U=$[Y-1][1],j=$[Y][1],G=a8(U,j),M=a8(j,U);if(G>=M){if(G>=U.length/2||G>=j.length/2)$.splice(Y,0,[k,j.substring(0,G)]),$[Y-1][1]=U.substring(0,U.length-G),$[Y+1][1]=j.substring(G),Y++}else if(M>=U.length/2||M>=j.length/2)$.splice(Y,0,[k,U.substring(0,M)]),$[Y-1][0]=x,$[Y-1][1]=j.substring(0,j.length-M),$[Y+1][0]=b,$[Y+1][1]=U.substring(M),Y++;Y++}Y++}}var i8=/[^a-zA-Z0-9]/,s8=/\s/,r8=/[\r\n]/,Z7=/\n\r?\n$/,K7=/^\r?\n\r?\n/;function V7($){function Z(M,C){if(!M||!C)return 6;var H=M.charAt(M.length-1),D=C.charAt(0),q=H.match(i8),S=D.match(i8),R=q&&H.match(s8),v=S&&D.match(s8),N=R&&H.match(r8),A=v&&D.match(r8),T=N&&M.match(Z7),F=A&&C.match(K7);if(T||F)return 5;else if(N||A)return 4;else if(q&&!R&&v)return 3;else if(R||v)return 2;else if(q||S)return 1;return 0}var K=1;while(K<$.length-1){if($[K-1][0]==k&&$[K+1][0]==k){var V=$[K-1][1],Q=$[K][1],Y=$[K+1][1],X=BZ(V,Q);if(X){var J=Q.substring(Q.length-X);V=V.substring(0,V.length-X),Q=J+Q.substring(0,Q.length-X),Y=J+Y}var W=V,z=Q,U=Y,j=Z(V,Q)+Z(Q,Y);while(Q.charAt(0)===Y.charAt(0)){V+=Q.charAt(0),Q=Q.substring(1)+Y.charAt(0),Y=Y.substring(1);var G=Z(V,Q)+Z(Q,Y);if(G>=j)j=G,W=V,z=Q,U=Y}if($[K-1][1]!=W){if(W)$[K-1][1]=W;else $.splice(K-1,1),K--;if($[K][1]=z,U)$[K+1][1]=U;else $.splice(K+1,1),K--}}K++}}function K6($,Z){$.push([k,""]);var K=0,V=0,Q=0,Y="",X="",J;while(K<$.length){if(K<$.length-1&&!$[K][1]){$.splice(K,1);continue}switch($[K][0]){case x:Q++,X+=$[K][1],K++;break;case b:V++,Y+=$[K][1],K++;break;case k:var W=K-Q-V-1;if(Z){if(W>=0&&Z4($[W][1])){var z=$[W][1].slice(-1);if($[W][1]=$[W][1].slice(0,-1),Y=z+Y,X=z+X,!$[W][1]){$.splice(W,1),K--;var U=W-1;if($[U]&&$[U][0]===x)Q++,X=$[U][1]+X,U--;if($[U]&&$[U][0]===b)V++,Y=$[U][1]+Y,U--;W=U}}if($4($[K][1])){var z=$[K][1].charAt(0);$[K][1]=$[K][1].slice(1),Y+=z,X+=z}}if(K<$.length-1&&!$[K][1]){$.splice(K,1);break}if(Y.length>0||X.length>0){if(Y.length>0&&X.length>0){if(J=Z6(X,Y),J!==0){if(W>=0)$[W][1]+=X.substring(0,J);else $.splice(0,0,[k,X.substring(0,J)]),K++;X=X.substring(J),Y=Y.substring(J)}if(J=BZ(X,Y),J!==0)$[K][1]=X.substring(X.length-J)+$[K][1],X=X.substring(0,X.length-J),Y=Y.substring(0,Y.length-J)}var j=Q+V;if(Y.length===0&&X.length===0)$.splice(K-j,j),K=K-j;else if(Y.length===0)$.splice(K-j,j,[x,X]),K=K-j+1;else if(X.length===0)$.splice(K-j,j,[b,Y]),K=K-j+1;else $.splice(K-j,j,[b,Y],[x,X]),K=K-j+2}if(K!==0&&$[K-1][0]===k)$[K-1][1]+=$[K][1],$.splice(K,1);else K++;Q=0,V=0,Y="",X="";break}}if($[$.length-1][1]==="")$.pop();var G=!1;K=1;while(K<$.length-1){if($[K-1][0]===k&&$[K+1][0]===k){if($[K][1].substring($[K][1].length-$[K-1][1].length)===$[K-1][1])$[K][1]=$[K-1][1]+$[K][1].substring(0,$[K][1].length-$[K-1][1].length),$[K+1][1]=$[K-1][1]+$[K+1][1],$.splice(K-1,1),G=!0;else if($[K][1].substring(0,$[K+1][1].length)==$[K+1][1])$[K-1][1]+=$[K+1][1],$[K][1]=$[K][1].substring($[K+1][1].length)+$[K+1][1],$.splice(K+1,1),G=!0}K++}if(G)K6($,Z)}function t8($){return $>=55296&&$<=56319}function e8($){return $>=56320&&$<=57343}function $4($){return e8($.charCodeAt(0))}function Z4($){return t8($.charCodeAt($.length-1))}function Q7($){var Z=[];for(var K=0;K<$.length;K++)if($[K][1].length>0)Z.push($[K]);return Z}function $6($,Z,K,V){if(Z4($)||$4(V))return null;return Q7([[k,$],[b,Z],[x,K],[k,V]])}function Y7($,Z,K){var V=typeof K==="number"?{index:K,length:0}:K.oldRange,Q=typeof K==="number"?null:K.newRange,Y=$.length,X=Z.length;if(V.length===0&&(Q===null||Q.length===0)){var J=V.index,W=$.slice(0,J),z=$.slice(J),U=Q?Q.index:null;$:{var j=J+X-Y;if(U!==null&&U!==j)break $;if(j<0||j>X)break $;var G=Z.slice(0,j),M=Z.slice(j);if(M!==z)break $;var C=Math.min(J,j),H=W.slice(0,C),D=G.slice(0,C);if(H!==D)break $;var q=W.slice(C),S=G.slice(C);return $6(H,q,S,z)}$:{if(U!==null&&U!==J)break $;var R=J,G=Z.slice(0,R),M=Z.slice(R);if(G!==W)break $;var v=Math.min(Y-R,X-R),N=z.slice(z.length-v),A=M.slice(M.length-v);if(N!==A)break $;var q=z.slice(0,z.length-v),S=M.slice(0,M.length-v);return $6(W,q,S,N)}}if(V.length>0&&Q&&Q.length===0)$:{var H=$.slice(0,V.index),N=$.slice(V.index+V.length),C=H.length,v=N.length;if(X<C+v)break $;var D=Z.slice(0,C),A=Z.slice(X-v);if(H!==D||N!==A)break $;var q=$.slice(C,Y-v),S=Z.slice(C,X-v);return $6(H,q,S,N)}return null}function AZ($,Z,K,V){return s$($,Z,K,V,!0)}AZ.INSERT=x;AZ.DELETE=b;AZ.EQUAL=k;K4.exports=AZ});import*as PZ from"node:fs";import*as h$ from"node:path";import{fileURLToPath as r9}from"node:url";import*as bZ from"node:os";import*as L$ from"node:path";var yZ="diffstalker";function P6(){return L$.join(process.env.XDG_CONFIG_HOME||L$.join(bZ.homedir(),".config"),yZ)}function T$(){return L$.join(process.env.XDG_CACHE_HOME||L$.join(bZ.homedir(),".cache"),yZ)}function x6(){return process.env.XDG_RUNTIME_DIR?L$.join(process.env.XDG_RUNTIME_DIR,yZ):null}import*as QZ from"node:fs";import*as YZ from"node:path";import*as mZ from"node:os";function l($){if($.startsWith("~/"))return YZ.join(mZ.homedir(),$.slice(2));if($==="~")return mZ.homedir();return $}function b6($){let Z=YZ.dirname($);if(!QZ.existsSync(Z))QZ.mkdirSync(Z,{recursive:!0})}function gZ($){let Z=$.split(`
2
- `);for(let K=Z.length-1;K>=0;K--){let V=Z[K].trim();if(V)return V}return""}import*as S5 from"node:http";import*as I$ from"node:fs";import*as R5 from"node:net";function XZ($){process.stderr.write(`[diffstalker warn] ${$}
3
- `)}function a5($){if($ instanceof Error)return $.message;if($)return String($);return""}function JZ($,Z){let K=Z?`: ${a5(Z)}`:"";process.stderr.write(`[diffstalker error] ${$}${K}
4
- `)}function cZ($){let Z={};for(let[K,V]of $)Z[K]=V;return Z}function i5($){if(!$)return null;return{staged:cZ($.staged),unstaged:cZ($.unstaged)}}function Y$($){return{status:$.status,hunkCounts:i5($.hunkCounts),error:$.error,stashList:$.stashList,operationInProgress:$.operationInProgress,mtimes:$.mtimes?cZ($.mtimes):null}}function uZ($){return $}function s5($){return $.entries.length>0?$.entries[0].seq-1:$.nextSeq-1}function m6($,Z){let K=Z>0?$.entries.filter((V)=>V.seq>Z):$.entries;return{epoch:$.epoch,prunedBefore:s5($),entries:uZ(K)}}function d$($){if($ instanceof Date)return $.toISOString();if($ instanceof Map){let Z={};for(let[K,V]of $)Z[String(K)]=d$(V);return Z}if(Array.isArray($))return $.map(d$);if($!==null&&typeof $==="object"){let Z={};for(let[K,V]of Object.entries($))Z[K]=d$(V);return Z}return $}var r5=1048576;class O extends Error{status;constructor($,Z){super(Z);this.status=$,this.name="HttpError"}}function B($,Z,K){let V=JSON.stringify(d$(K));$.writeHead(Z,{"content-type":"application/json"}),$.end(V)}function g6($,Z,K,V){$.writeHead(Z,{...V,"content-length":String(K.byteLength)}),$.end(K)}function t5($,Z){if($.segments.length!==Z.length)return null;let K={};for(let V=0;V<$.segments.length;V++){let Q=$.segments[V];if(Q.startsWith(":"))try{K[Q.slice(1)]=decodeURIComponent(Z[V])}catch{throw new O(400,`Malformed percent-encoding in path: ${Z[V]}`)}else if(Q!==Z[V])return null}return K}async function e5($){if($.method!=="POST"&&$.method!=="PUT"&&$.method!=="PATCH")return;let Z=[],K=0;for await(let Q of $){let Y=Q;if(K+=Y.length,K>r5)throw new O(413,"Request body too large");Z.push(Y)}let V=Buffer.concat(Z).toString("utf-8");if(!V.trim())return;try{return JSON.parse(V)}catch{throw new O(400,"Invalid JSON body")}}class pZ{routes=[];get($,Z){this.add("GET",$,Z)}post($,Z){this.add("POST",$,Z)}put($,Z){this.add("PUT",$,Z)}delete($,Z){this.add("DELETE",$,Z)}add($,Z,K){this.routes.push({method:$,segments:Z.split("/").filter(Boolean),handler:K})}match($,Z){for(let K of this.routes){if(K.method!==$)continue;let V=t5(K,Z);if(V)return{handler:K.handler,params:V}}return null}async handle($,Z,K){try{let V=new URL($.url??"/","http://localhost"),Q=V.pathname.split("/").filter(Boolean),Y=$.method??"GET",X=this.match(Y,Q);if(!X){if(K&&Y==="GET"){await K($,Z,V.pathname);return}throw new O(404,`Unknown route: ${Y} ${V.pathname}`)}let J=await e5($);await X.handler({req:$,res:Z,params:X.params,query:V.searchParams,body:J})}catch(V){if(Z.headersSent){Z.end();return}if(V instanceof O){B(Z,V.status,{error:V.message});return}JZ(`${$.method??"GET"} ${$.url??"/"}`,V),B(Z,500,{error:"Internal server error"})}}}import*as fZ from"node:fs";import*as p from"node:path";var $1=new Set(["health","repos","events","follow"]),Z1={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".json":"application/json",".map":"application/json",".woff2":"font/woff2",".woff":"font/woff",".ttf":"font/ttf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".wasm":"application/wasm",".txt":"text/plain; charset=utf-8",".webmanifest":"application/manifest+json"},c6="no-cache",K1="public, max-age=31536000, immutable";async function u6($,Z,K){let V;try{V=await fZ.promises.readFile(Z)}catch{throw new O(404,`Not found: ${p.basename(Z)}`)}$.writeHead(200,{"content-type":Z1[p.extname(Z)]??"application/octet-stream","cache-control":K,"content-length":V.length}),$.end(V)}function p6($){let Z=p.resolve($);return async(K,V,Q)=>{let Y;try{Y=decodeURIComponent(Q)}catch{throw new O(400,`Malformed percent-encoding in path: ${Q}`)}if(Y.includes("\x00"))throw new O(400,"Invalid path");let X=Y.split("/").filter(Boolean);if(X.length>0&&$1.has(X[0]))throw new O(404,`Unknown route: GET ${Q}`);let J=X.length>0?p.resolve(Z,X.join("/")):Z;if(J!==Z&&!J.startsWith(Z+p.sep))throw new O(403,"Forbidden");if((await fZ.promises.stat(J).catch(()=>null))?.isFile()){await u6(V,J,X[0]==="assets"?K1:c6);return}await u6(V,p.join(Z,"index.html"),c6)}}function V1($){try{let Z=new URL(`http://${$}`).hostname.toLowerCase();return Z.startsWith("[")&&Z.endsWith("]")?Z.slice(1,-1):Z}catch{return null}}function Q1($){try{let Z=new URL($).hostname.toLowerCase();return Z.startsWith("[")&&Z.endsWith("]")?Z.slice(1,-1):Z}catch{return null}}function h6($){let Z=$.split(".");if(Z.length!==4)return!1;if(!Z.every((K)=>/^\d{1,3}$/.test(K)&&Number(K)<=255))return!1;return Z[0]==="127"}function Y1($){return $.length>10&&$.endsWith(".localhost")}function f6($){return $==="localhost"||$==="::1"||Y1($)||h6($)}function X1($){return $==="::1"||h6($)}function d6($){if($===null)return!1;if(typeof $==="string")return!0;return X1($.address)}function l6($){let Z=$.headers.host;if(Z!==void 0){let X=V1(Z);if(X===null||!f6(X))return{status:421,message:"Host not allowed (loopback only)"}}let K=$.method??"GET";if(!(K!=="GET"&&K!=="HEAD"&&K!=="OPTIONS"))return null;let Q=$.headers["sec-fetch-site"];if(Q&&Q!=="same-origin"&&Q!=="none")return{status:403,message:"Cross-site request blocked"};let Y=$.headers.origin;if(Y!==void 0&&Y!==""){let X=Q1(Y);if(X===null||!f6(X))return{status:403,message:"Cross-origin request blocked"}}return null}function n6($){let Z=$.headers["sec-fetch-site"];if(Z&&Z!=="same-origin"&&Z!=="none")return{status:403,message:"Cross-site request blocked"};let K=$.headers["sec-fetch-dest"];if(K&&K!=="image")return{status:403,message:"Request destination must be an image"};return null}var o6={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Referrer-Policy":"no-referrer","Cross-Origin-Resource-Policy":"same-origin","Content-Security-Policy":["default-src 'self'","script-src 'self'","style-src 'self' 'unsafe-inline'","img-src 'self' data:","font-src 'self' data:","connect-src 'self'","object-src 'none'","frame-src 'none'","child-src 'none'","media-src 'none'","worker-src 'none'","form-action 'none'","base-uri 'self'","frame-ancestors 'none'"].join("; ")};import{createHash as v7}from"node:crypto";class a6{queue=[];isProcessing=!1;pendingMutations=0;refreshScheduled=!1;enqueue($){return new Promise((Z,K)=>{this.queue.push({execute:$,resolve:Z,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 Z=await $.execute();$.resolve(Z)}catch(Z){$.reject(Z instanceof Error?Z:Error(String(Z)))}finally{this.isProcessing=!1,this.processNext()}}}var hZ=new Map;function i6($){let Z=hZ.get($);if(!Z)Z=new a6,hZ.set($,Z);return Z}function s6($){hZ.delete($)}import*as E from"node:path";import*as h from"node:fs";import{execFileSync as W7}from"node:child_process";import{watch as Y4}from"chokidar";import{EventEmitter as z7}from"node:events";import X4 from"ignore";import*as r6 from"node:fs";function WZ($,Z){let K=Z;if(!K||K.isSymbolicLink())try{K=r6.statSync($)}catch{return!1}return!K.isFile()&&!K.isDirectory()}import{simpleGit as G1}from"simple-git";import*as n from"node:fs";import*as t6 from"node:os";import*as D$ from"node:path";import{execFileSync as J1}from"node:child_process";var W1=[["*.ada","ada"],["*.adb","ada"],["*.ads","ada"],["*.sh","bash"],["*.bash","bash"],["*.bib","bibtex"],["*.c","cpp"],["*.h","cpp"],["*.cc","cpp"],["*.cpp","cpp"],["*.cxx","cpp"],["*.hpp","cpp"],["*.hh","cpp"],["*.cs","csharp"],["*.css","css"],["*.scss","css"],["*.dts","dts"],["*.ex","elixir"],["*.exs","elixir"],["*.f","fortran"],["*.f90","fortran"],["*.go","golang"],["*.html","html"],["*.htm","html"],["*.java","java"],["*.kt","kotlin"],["*.kts","kotlin"],["*.md","markdown"],["*.m","objc"],["*.pas","pascal"],["*.pl","perl"],["*.pm","perl"],["*.php","php"],["*.py","python"],["*.rb","ruby"],["*.rs","rust"],["*.scm","scheme"],["*.tex","tex"]];function z1(){return`# Generated by diffstalker: turns on git's built-in funcname drivers.
1
+ var Pi=Object.create;var{getPrototypeOf:Mi,defineProperty:or,getOwnPropertyNames:Fi}=Object;var ir=Object.prototype.hasOwnProperty;function Ti(t){return this[t]}var $i,Oi,Ni=(t,e,n)=>{var r=t!=null&&typeof t==="object";if(r){var s=e?$i??=new WeakMap:Oi??=new WeakMap,o=s.get(t);if(o)return o}n=t!=null?Pi(Mi(t)):{};let i=e||!t||!t.__esModule||!ir.call(t,"default")?or(n,"default",{value:t,enumerable:!0}):n;if(t&&typeof t==="object"||typeof t==="function"){for(let a of Fi(t))if(!ir.call(i,a))or(i,a,{get:Ti.bind(t,a),enumerable:!0})}if(r)s.set(t,i);return i};var Ci=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ls=Ci(function(sh,Cs){var H=-1,C=1,M=0;function le(t,e,n,r,s){if(t===e){if(t)return[[M,t]];return[]}if(n!=null){var o=nc(t,e,n);if(o)return o}var i=kn(t,e),a=t.substring(0,i);t=t.substring(i),e=e.substring(i),i=Ae(t,e);var c=t.substring(t.length-i);t=t.substring(0,t.length-i),e=e.substring(0,e.length-i);var l=Ja(t,e);if(a)l.unshift([M,a]);if(c)l.push([M,c]);if(Rn(l,s),r)Va(l);return l}function Ja(t,e){var n;if(!t)return[[C,e]];if(!e)return[[H,t]];var r=t.length>e.length?t:e,s=t.length>e.length?e:t,o=r.indexOf(s);if(o!==-1){if(n=[[C,r.substring(0,o)],[M,s],[C,r.substring(o+s.length)]],t.length>e.length)n[0][0]=n[2][0]=H;return n}if(s.length===1)return[[H,t],[C,e]];var i=Ka(t,e);if(i){var a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],h=le(a,l),g=le(c,u);return h.concat([[M,f]],g)}return Ya(t,e)}function Ya(t,e){var n=t.length,r=e.length,s=Math.ceil((n+r)/2),o=s,i=2*s,a=Array(i),c=Array(i);for(var l=0;l<i;l++)a[l]=-1,c[l]=-1;a[o+1]=0,c[o+1]=0;var u=n-r,f=u%2!==0,h=0,g=0,d=0,p=0;for(var y=0;y<s;y++){for(var v=-y+h;v<=y-g;v+=2){var A=o+v,I;if(v===-y||v!==y&&a[A-1]<a[A+1])I=a[A+1];else I=a[A-1]+1;var D=I-v;while(I<n&&D<r&&t.charAt(I)===e.charAt(D))I++,D++;if(a[A]=I,I>n)g+=2;else if(D>r)h+=2;else if(f){var w=o+u-v;if(w>=0&&w<i&&c[w]!==-1){var x=n-c[w];if(I>=x)return Is(t,e,I,D)}}}for(var _=-y+d;_<=y-p;_+=2){var w=o+_,x;if(_===-y||_!==y&&c[w-1]<c[w+1])x=c[w+1];else x=c[w-1]+1;var b=x-_;while(x<n&&b<r&&t.charAt(n-x-1)===e.charAt(r-b-1))x++,b++;if(c[w]=x,x>n)p+=2;else if(b>r)d+=2;else if(!f){var A=o+u-_;if(A>=0&&A<i&&a[A]!==-1){var I=a[A],D=o+I-A;if(x=n-x,I>=x)return Is(t,e,I,D)}}}}return[[H,t],[C,e]]}function Is(t,e,n,r){var s=t.substring(0,n),o=e.substring(0,r),i=t.substring(n),a=e.substring(r),c=le(s,o),l=le(i,a);return c.concat(l)}function kn(t,e){if(!t||!e||t.charAt(0)!==e.charAt(0))return 0;var n=0,r=Math.min(t.length,e.length),s=r,o=0;while(n<s){if(t.substring(o,s)==e.substring(o,s))n=s,o=n;else r=s;s=Math.floor((r-n)/2+n)}if(Ts(t.charCodeAt(s-1)))s--;return s}function Ds(t,e){var n=t.length,r=e.length;if(n==0||r==0)return 0;if(n>r)t=t.substring(n-r);else if(n<r)e=e.substring(0,n);var s=Math.min(n,r);if(t==e)return s;var o=0,i=1;while(!0){var a=t.substring(s-i),c=e.indexOf(a);if(c==-1)return o;if(i+=c,c==0||t.substring(s-i)==e.substring(0,i))o=i,i++}}function Ae(t,e){if(!t||!e||t.slice(-1)!==e.slice(-1))return 0;var n=0,r=Math.min(t.length,e.length),s=r,o=0;while(n<s){if(t.substring(t.length-s,t.length-o)==e.substring(e.length-s,e.length-o))n=s,o=n;else r=s;s=Math.floor((r-n)/2+n)}if($s(t.charCodeAt(t.length-s)))s--;return s}function Ka(t,e){var n=t.length>e.length?t:e,r=t.length>e.length?e:t;if(n.length<4||r.length*2<n.length)return null;function s(g,d,p){var y=g.substring(p,p+Math.floor(g.length/4)),v=-1,A="",I,D,w,x;while((v=d.indexOf(y,v+1))!==-1){var _=kn(g.substring(p),d.substring(v)),b=Ae(g.substring(0,p),d.substring(0,v));if(A.length<b+_)A=d.substring(v-b,v)+d.substring(v,v+_),I=g.substring(0,p-b),D=g.substring(p+_),w=d.substring(0,v-b),x=d.substring(v+_)}if(A.length*2>=g.length)return[I,D,w,x,A];else return null}var o=s(n,r,Math.ceil(n.length/4)),i=s(n,r,Math.ceil(n.length/2)),a;if(!o&&!i)return null;else if(!i)a=o;else if(!o)a=i;else a=o[4].length>i[4].length?o:i;var c,l,u,f;if(t.length>e.length)c=a[0],l=a[1],u=a[2],f=a[3];else u=a[0],f=a[1],c=a[2],l=a[3];var h=a[4];return[c,l,u,f,h]}function Va(t){var e=!1,n=[],r=0,s=null,o=0,i=0,a=0,c=0,l=0;while(o<t.length){if(t[o][0]==M)n[r++]=o,i=c,a=l,c=0,l=0,s=t[o][1];else{if(t[o][0]==C)c+=t[o][1].length;else l+=t[o][1].length;if(s&&s.length<=Math.max(i,a)&&s.length<=Math.max(c,l))t.splice(n[r-1],0,[H,s]),t[n[r-1]+1][0]=C,r--,r--,o=r>0?n[r-1]:-1,i=0,a=0,c=0,l=0,s=null,e=!0}o++}if(e)Rn(t);tc(t),o=1;while(o<t.length){if(t[o-1][0]==H&&t[o][0]==C){var u=t[o-1][1],f=t[o][1],h=Ds(u,f),g=Ds(f,u);if(h>=g){if(h>=u.length/2||h>=f.length/2)t.splice(o,0,[M,f.substring(0,h)]),t[o-1][1]=u.substring(0,u.length-h),t[o+1][1]=f.substring(h),o++}else if(g>=u.length/2||g>=f.length/2)t.splice(o,0,[M,u.substring(0,g)]),t[o-1][0]=C,t[o-1][1]=f.substring(0,f.length-g),t[o+1][0]=H,t[o+1][1]=u.substring(g),o++;o++}o++}}var Ps=/[^a-zA-Z0-9]/,Ms=/\s/,Fs=/[\r\n]/,Qa=/\n\r?\n$/,Za=/^\r?\n\r?\n/;function tc(t){function e(g,d){if(!g||!d)return 6;var p=g.charAt(g.length-1),y=d.charAt(0),v=p.match(Ps),A=y.match(Ps),I=v&&p.match(Ms),D=A&&y.match(Ms),w=I&&p.match(Fs),x=D&&y.match(Fs),_=w&&g.match(Qa),b=x&&d.match(Za);if(_||b)return 5;else if(w||x)return 4;else if(v&&!I&&D)return 3;else if(I||D)return 2;else if(v||A)return 1;return 0}var n=1;while(n<t.length-1){if(t[n-1][0]==M&&t[n+1][0]==M){var r=t[n-1][1],s=t[n][1],o=t[n+1][1],i=Ae(r,s);if(i){var a=s.substring(s.length-i);r=r.substring(0,r.length-i),s=a+s.substring(0,s.length-i),o=a+o}var c=r,l=s,u=o,f=e(r,s)+e(s,o);while(s.charAt(0)===o.charAt(0)){r+=s.charAt(0),s=s.substring(1)+o.charAt(0),o=o.substring(1);var h=e(r,s)+e(s,o);if(h>=f)f=h,c=r,l=s,u=o}if(t[n-1][1]!=c){if(c)t[n-1][1]=c;else t.splice(n-1,1),n--;if(t[n][1]=l,u)t[n+1][1]=u;else t.splice(n+1,1),n--}}n++}}function Rn(t,e){t.push([M,""]);var n=0,r=0,s=0,o="",i="",a;while(n<t.length){if(n<t.length-1&&!t[n][1]){t.splice(n,1);continue}switch(t[n][0]){case C:s++,i+=t[n][1],n++;break;case H:r++,o+=t[n][1],n++;break;case M:var c=n-s-r-1;if(e){if(c>=0&&Ns(t[c][1])){var l=t[c][1].slice(-1);if(t[c][1]=t[c][1].slice(0,-1),o=l+o,i=l+i,!t[c][1]){t.splice(c,1),n--;var u=c-1;if(t[u]&&t[u][0]===C)s++,i=t[u][1]+i,u--;if(t[u]&&t[u][0]===H)r++,o=t[u][1]+o,u--;c=u}}if(Os(t[n][1])){var l=t[n][1].charAt(0);t[n][1]=t[n][1].slice(1),o+=l,i+=l}}if(n<t.length-1&&!t[n][1]){t.splice(n,1);break}if(o.length>0||i.length>0){if(o.length>0&&i.length>0){if(a=kn(i,o),a!==0){if(c>=0)t[c][1]+=i.substring(0,a);else t.splice(0,0,[M,i.substring(0,a)]),n++;i=i.substring(a),o=o.substring(a)}if(a=Ae(i,o),a!==0)t[n][1]=i.substring(i.length-a)+t[n][1],i=i.substring(0,i.length-a),o=o.substring(0,o.length-a)}var f=s+r;if(o.length===0&&i.length===0)t.splice(n-f,f),n=n-f;else if(o.length===0)t.splice(n-f,f,[C,i]),n=n-f+1;else if(i.length===0)t.splice(n-f,f,[H,o]),n=n-f+1;else t.splice(n-f,f,[H,o],[C,i]),n=n-f+2}if(n!==0&&t[n-1][0]===M)t[n-1][1]+=t[n][1],t.splice(n,1);else n++;s=0,r=0,o="",i="";break}}if(t[t.length-1][1]==="")t.pop();var h=!1;n=1;while(n<t.length-1){if(t[n-1][0]===M&&t[n+1][0]===M){if(t[n][1].substring(t[n][1].length-t[n-1][1].length)===t[n-1][1])t[n][1]=t[n-1][1]+t[n][1].substring(0,t[n][1].length-t[n-1][1].length),t[n+1][1]=t[n-1][1]+t[n+1][1],t.splice(n-1,1),h=!0;else if(t[n][1].substring(0,t[n+1][1].length)==t[n+1][1])t[n-1][1]+=t[n+1][1],t[n][1]=t[n][1].substring(t[n+1][1].length)+t[n+1][1],t.splice(n+1,1),h=!0}n++}if(h)Rn(t,e)}function Ts(t){return t>=55296&&t<=56319}function $s(t){return t>=56320&&t<=57343}function Os(t){return $s(t.charCodeAt(0))}function Ns(t){return Ts(t.charCodeAt(t.length-1))}function ec(t){var e=[];for(var n=0;n<t.length;n++)if(t[n][1].length>0)e.push(t[n]);return e}function vn(t,e,n,r){if(Ns(t)||Os(r))return null;return ec([[M,t],[H,e],[C,n],[M,r]])}function nc(t,e,n){var r=typeof n==="number"?{index:n,length:0}:n.oldRange,s=typeof n==="number"?null:n.newRange,o=t.length,i=e.length;if(r.length===0&&(s===null||s.length===0)){var a=r.index,c=t.slice(0,a),l=t.slice(a),u=s?s.index:null;t:{var f=a+i-o;if(u!==null&&u!==f)break t;if(f<0||f>i)break t;var h=e.slice(0,f),g=e.slice(f);if(g!==l)break t;var d=Math.min(a,f),p=c.slice(0,d),y=h.slice(0,d);if(p!==y)break t;var v=c.slice(d),A=h.slice(d);return vn(p,v,A,l)}t:{if(u!==null&&u!==a)break t;var I=a,h=e.slice(0,I),g=e.slice(I);if(h!==c)break t;var D=Math.min(o-I,i-I),w=l.slice(l.length-D),x=g.slice(g.length-D);if(w!==x)break t;var v=l.slice(0,l.length-D),A=g.slice(0,g.length-D);return vn(c,v,A,w)}}if(r.length>0&&s&&s.length===0)t:{var p=t.slice(0,r.index),w=t.slice(r.index+r.length),d=p.length,D=w.length;if(i<d+D)break t;var y=e.slice(0,d),x=e.slice(i-D);if(p!==y||w!==x)break t;var v=t.slice(d,o-D),A=e.slice(d,i-D);return vn(p,v,A,w)}return null}function Ie(t,e,n,r){return le(t,e,n,r,!0)}Ie.INSERT=C;Ie.DELETE=H;Ie.EQUAL=M;Cs.exports=Ie});import*as Je from"node:fs";import*as Vt from"node:path";import{fileURLToPath as Ju}from"node:url";import*as Ke from"node:os";import*as kt from"node:path";var Ve="diffstalker";function Qe(){return process.env.XDG_CONFIG_HOME||kt.join(Ke.homedir(),".config")}function ar(){return kt.join(Qe(),Ve)}function Rt(){return kt.join(process.env.XDG_CACHE_HOME||kt.join(Ke.homedir(),".cache"),Ve)}function cr(){return process.env.XDG_RUNTIME_DIR?kt.join(process.env.XDG_RUNTIME_DIR,Ve):null}import*as ge from"node:fs";import*as we from"node:path";import*as Ze from"node:os";function J(t){if(t.startsWith("~/"))return we.join(Ze.homedir(),t.slice(2));if(t==="~")return Ze.homedir();return t}function ye(t){let e=we.dirname(t);if(!ge.existsSync(e))ge.mkdirSync(e,{recursive:!0})}function tn(t){let e=t.split(`
2
+ `);for(let n=e.length-1;n>=0;n--){let r=e[n].trim();if(r)return r}return""}var lr=!1;function ur(t){lr=t}function fr(t){let e="";for(let n of t){let r=n.charCodeAt(0);if(r>=32&&r!==127)e+=n;else if(n===`
3
+ `)e+="\\n";else if(n==="\r")e+="\\r";else if(n==="\t")e+="\\t";else e+=`\\x${r.toString(16).padStart(2,"0")}`}return e}var Li=/(\w+:\/\/)[^/\s@]+@/g;function Hi(t){return t.replace(Li,"$1***@")}function Bi(t){if(!t)return"";let e=[];for(let[n,r]of Object.entries(t)){if(r===void 0)continue;let s=fr(String(r));e.push(`${n}=${/\s/.test(s)||s===""?JSON.stringify(s):s}`)}return e.length===0?"":` ${e.join(" ")}`}function Wi(t){if(t instanceof Error)return`${t.name}: ${t.message}`;return String(t)}function en(t,e={stacks:!0}){let n=[],r=t;for(let s=0;s<10&&r!==void 0&&r!==null;s++){let o=s===0?"":"caused by: ",i=e.stacks&&r instanceof Error&&r.stack?r.stack:Wi(r);n.push(o+i),r=r instanceof Error?r.cause:void 0}return n.join(`
4
+ `)}function nn(t,e,n,r){let s=`${new Date().toISOString()} ${t.padEnd(5)} ${fr(e)}${Bi(n)}`,o=r?`
5
+ ${r.replace(/^/gm," ")}`:"";process.stderr.write(Hi(`${s}${o}
6
+ `))}function L(t,e,n){if(!lr)return;nn("debug",t,n,e===void 0?void 0:en(e,{stacks:!1}))}function k(t,e,n){nn("warn",t,n,e===void 0?void 0:en(e,{stacks:!1}))}function F(t,e,n){nn("error",t,n,e===void 0?void 0:en(e))}import*as wi from"node:http";import*as vt from"node:fs";import*as yi from"node:net";function rn(t){let e={};for(let[n,r]of t)e[n]=r;return e}function ji(t){if(!t)return null;return{staged:rn(t.staged),unstaged:rn(t.unstaged)}}function lt(t){return{status:t.status,hunkCounts:ji(t.hunkCounts),error:t.error,stashList:t.stashList,operationInProgress:t.operationInProgress,mtimes:t.mtimes?rn(t.mtimes):null}}function Gi(t){return t.entries.length>0?t.entries[0].seq-1:t.nextSeq-1}function hr(t,e){let n=e>0?t.entries.filter((r)=>r.seq>e):t.entries;return{epoch:t.epoch,prunedBefore:Gi(t),entries:n}}function Qt(t){if(t instanceof Date)return t.toISOString();if(t instanceof Map){let e={};for(let[n,r]of t)e[String(n)]=Qt(r);return e}if(Array.isArray(t))return t.map(Qt);if(t!==null&&typeof t==="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=Qt(r);return e}return t}var Ui=1048576;class m extends Error{status;constructor(t,e,n){super(e,n);this.status=t,this.name="HttpError"}}function S(t,e,n){let r=JSON.stringify(Qt(n));t.writeHead(e,{"content-type":"application/json"}),t.end(r)}function dr(t,e,n,r){t.writeHead(e,{...r,"content-length":String(n.byteLength)}),t.end(n)}function qi(t,e){if(t.segments.length!==e.length)return null;let n={};for(let r=0;r<t.segments.length;r++){let s=t.segments[r];if(s.startsWith(":"))try{n[s.slice(1)]=decodeURIComponent(e[r])}catch{throw new m(400,`Malformed percent-encoding in path: ${e[r]}`)}else if(s!==e[r])return null}return n}async function Xi(t){if(t.method!=="POST"&&t.method!=="PUT"&&t.method!=="PATCH")return;let e=[],n=0;for await(let s of t){let o=s;if(n+=o.length,n>Ui)throw new m(413,"Request body too large");e.push(o)}let r=Buffer.concat(e).toString("utf-8");if(!r.trim())return;try{return JSON.parse(r)}catch{throw new m(400,"Invalid JSON body")}}class sn{routes=[];get(t,e){this.add("GET",t,e)}post(t,e){this.add("POST",t,e)}put(t,e){this.add("PUT",t,e)}delete(t,e){this.add("DELETE",t,e)}add(t,e,n){this.routes.push({method:t,segments:e.split("/").filter(Boolean),handler:n})}match(t,e){for(let n of this.routes){if(n.method!==t)continue;let r=qi(n,e);if(r)return{handler:n.handler,params:r}}return null}async handle(t,e,n){try{let r=new URL(t.url??"/","http://localhost"),s=r.pathname.split("/").filter(Boolean),o=t.method??"GET",i=this.match(o,s);if(!i){if(n&&o==="GET"){await n(t,e,r.pathname);return}throw new m(404,`Unknown route: ${o} ${r.pathname}`)}let a=await Xi(t);await i.handler({req:t,res:e,params:i.params,query:r.searchParams,body:a})}catch(r){let s=`${t.method??"GET"} ${t.url??"/"}`;if(e.headersSent){F(`${s} failed after the response headers were sent`,r),e.end();return}if(r instanceof m){zi(s,r),S(e,r.status,{error:r.message});return}F(`${s} -> 500`,r),S(e,500,{error:"Internal server error"})}}}function zi(t,e){let n=`${t} -> ${e.status} ${e.message}`;if(e.cause!==void 0||e.status>=500)k(n,e.cause);else L(n)}import*as on from"node:fs";import*as X from"node:path";var Ji=new Set(["health","version","repos","resolve","worktrees","events","follow","settings","discovered","browse"]),Yi={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".json":"application/json",".map":"application/json",".woff2":"font/woff2",".woff":"font/woff",".ttf":"font/ttf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".wasm":"application/wasm",".txt":"text/plain; charset=utf-8",".webmanifest":"application/manifest+json"},pr="no-cache",Ki="public, max-age=31536000, immutable";async function mr(t,e,n){let r;try{r=await on.promises.readFile(e)}catch(s){throw new m(404,`Not found: ${X.basename(e)}`,{cause:s})}t.writeHead(200,{"content-type":Yi[X.extname(e)]??"application/octet-stream","cache-control":n,"content-length":r.length}),t.end(r)}function gr(t){let e=X.resolve(t);return async(n,r,s)=>{let o;try{o=decodeURIComponent(s)}catch{throw new m(400,`Malformed percent-encoding in path: ${s}`)}if(o.includes("\x00"))throw new m(400,"Invalid path");let i=o.split("/").filter(Boolean);if(i.length>0&&Ji.has(i[0]))throw new m(404,`Unknown route: GET ${s}`);let a=i.length>0?X.resolve(e,i.join("/")):e;if(a!==e&&!a.startsWith(e+X.sep))throw new m(403,"Forbidden");if((await on.promises.stat(a).catch(()=>null))?.isFile()){await mr(r,a,i[0]==="assets"?Ki:pr);return}await mr(r,X.join(e,"index.html"),pr)}}function Vi(t){try{let e=new URL(`http://${t}`).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function Qi(t){try{let e=new URL(t).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function yr(t){let e=t.split(".");if(e.length!==4)return!1;if(!e.every((n)=>/^\d{1,3}$/.test(n)&&Number(n)<=255))return!1;return e[0]==="127"}function Zi(t){return t.length>10&&t.endsWith(".localhost")}function wr(t){return t==="localhost"||t==="::1"||Zi(t)||yr(t)}function ta(t){return t==="::1"||yr(t)}function br(t){if(t===null)return!1;if(typeof t==="string")return!0;return ta(t.address)}function Sr(t){let e=t.headers.host;if(e!==void 0){let i=Vi(e);if(i===null||!wr(i))return{status:421,message:"Host not allowed (loopback only)"}}let n=t.method??"GET";if(!(n!=="GET"&&n!=="HEAD"&&n!=="OPTIONS"))return null;let s=t.headers["sec-fetch-site"];if(s&&s!=="same-origin"&&s!=="none")return{status:403,message:"Cross-site request blocked"};let o=t.headers.origin;if(o!==void 0&&o!==""){let i=Qi(o);if(i===null||!wr(i))return{status:403,message:"Cross-origin request blocked"}}return null}function Er(t){let e=t.headers["sec-fetch-site"];if(e&&e!=="same-origin"&&e!=="none")return{status:403,message:"Cross-site request blocked"};let n=t.headers["sec-fetch-dest"];if(n&&n!=="image")return{status:403,message:"Request destination must be an image"};return null}var xr={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Referrer-Policy":"no-referrer","Cross-Origin-Resource-Policy":"same-origin","Content-Security-Policy":["default-src 'self'","script-src 'self'","style-src 'self' 'unsafe-inline'","img-src 'self' data:","font-src 'self' data:","connect-src 'self'","object-src 'none'","frame-src 'none'","child-src 'none'","media-src 'none'","worker-src 'none'","form-action 'none'","base-uri 'self'","frame-ancestors 'none'"].join("; ")};import{createHash as Ac}from"node:crypto";class vr{repoPath;queue=[];isProcessing=!1;pendingMutations=0;refreshScheduled=!1;constructor(t){this.repoPath=t}enqueue(t){return new Promise((e,n)=>{this.queue.push({execute:t,resolve:e,reject:n}),this.processNext()})}enqueueMutation(t){return this.pendingMutations++,this.enqueue(t).finally(()=>{this.pendingMutations--})}hasPendingMutations(){return this.pendingMutations>0}scheduleRefresh(t){if(this.pendingMutations>0)return;if(this.refreshScheduled)return;this.refreshScheduled=!0,this.enqueue(async()=>{this.refreshScheduled=!1,await t()}).catch((e)=>{F("Scheduled refresh threw",e,{repo:this.repoPath}),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 t=this.queue.shift();try{let e=await t.execute();t.resolve(e)}catch(e){t.reject(e instanceof Error?e:Error(String(e)))}finally{this.isProcessing=!1,this.processNext()}}}var an=new Map;function kr(t){let e=an.get(t);if(!e)e=new vr(t),an.set(t,e);return e}function Rr(t){an.delete(t)}import*as T from"node:path";import*as G from"node:fs";import{execFileSync as sc}from"node:child_process";import{watch as Bs}from"chokidar";import{EventEmitter as oc}from"node:events";import Ws from"ignore";import{execFile as ia}from"node:child_process";import{promisify as aa}from"node:util";import{simpleGit as ca}from"simple-git";import*as Y from"node:fs";import*as te from"node:path";import{execFileSync as ea}from"node:child_process";var na=[["*.ada","ada"],["*.adb","ada"],["*.ads","ada"],["*.sh","bash"],["*.bash","bash"],["*.bib","bibtex"],["*.c","cpp"],["*.h","cpp"],["*.cc","cpp"],["*.cpp","cpp"],["*.cxx","cpp"],["*.hpp","cpp"],["*.hh","cpp"],["*.cs","csharp"],["*.css","css"],["*.scss","css"],["*.dts","dts"],["*.ex","elixir"],["*.exs","elixir"],["*.f","fortran"],["*.f90","fortran"],["*.go","golang"],["*.html","html"],["*.htm","html"],["*.java","java"],["*.kt","kotlin"],["*.kts","kotlin"],["*.md","markdown"],["*.m","objc"],["*.pas","pascal"],["*.pl","perl"],["*.pm","perl"],["*.php","php"],["*.py","python"],["*.rb","ruby"],["*.rs","rust"],["*.scm","scheme"],["*.tex","tex"]];function ra(){return`# Generated by diffstalker: turns on git's built-in funcname drivers.
5
7
  `+`# Lowest-priority attributes source — a repo's own .gitattributes wins.
6
- `+W1.map(([Z,K])=>`${Z} diff=${K}`).join(`
8
+ `+na.map(([e,n])=>`${e} diff=${n}`).join(`
7
9
  `)+`
8
- `}var l$=null,W$=null;function U1(){if(W$!==null)return W$;try{if(J1("git",["config","--get","core.attributesFile"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:process.env}).trim()!=="")return W$=!0,!0}catch(Z){if(Z.status!==1)return W$=!0,!0}let $=process.env.XDG_CONFIG_HOME||D$.join(t6.homedir(),".config");return W$=n.existsSync(D$.join($,"git","attributes")),W$}function e6(){if(l$!==null)return l$;if(U1())return null;let $=D$.join(T$(),"funcname.gitattributes"),Z=z1();try{let K=null;try{K=n.readFileSync($,"utf8")}catch{K=null}if(K!==Z)n.mkdirSync(D$.dirname($),{recursive:!0}),j1($,Z);return l$=$,l$}catch{return l$=null,W$=!0,null}}function j1($,Z){let K=`${$}.${process.pid}.tmp`;n.writeFileSync(K,Z,"utf8"),n.renameSync(K,$)}function f(){return{...process.env,LC_ALL:"C",LANG:"C"}}var M1={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0},O1=1e4,H1=600000;function L($,Z={}){let K=e6(),V=K===null?[]:[`core.attributesFile=${K}`];return G1({baseDir:$,unsafe:M1,timeout:{block:Z.longRunning===!0?H1:O1},config:V}).env(f())}import{execFileSync as X8}from"node:child_process";import*as o$ from"node:fs";import*as lZ from"node:path";async function F$($,Z){if(Z.length===0)return new Set;let K=L($),V=new Set,Q=100;for(let Y=0;Y<Z.length;Y+=Q){let X=Z.slice(Y,Y+Q);try{let W=(await K.raw(["check-ignore","--",...X])).trim().split(`
9
- `).filter((z)=>z.length>0);for(let z of W)V.add(z)}catch{}}return V}function z$($){if($.length===0)return"";return $.map((Z)=>Z.content).join(`
10
+ `}var Zt=null,ht=null;function sa(){if(ht!==null)return ht;try{if(ea("git",["config","--get","core.attributesFile"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:process.env}).trim()!=="")return ht=!0,!0}catch(t){if(t.status!==1)return k("git config core.attributesFile failed; funcname drivers are off",t),ht=!0,!0}return ht=Y.existsSync(te.join(Qe(),"git","attributes")),ht}function _r(){if(Zt!==null)return Zt;if(sa())return null;let t=te.join(Rt(),"funcname.gitattributes"),e=ra();try{let n=null;try{n=Y.readFileSync(t,"utf8")}catch{n=null}if(n!==e)Y.mkdirSync(te.dirname(t),{recursive:!0}),oa(t,e);return Zt=t,Zt}catch(n){return k("Cannot write the attributes file; funcname drivers are off",n,{file:t}),Zt=null,ht=!0,null}}function oa(t,e){let n=`${t}.${process.pid}.tmp`;Y.writeFileSync(n,e,"utf8"),Y.renameSync(n,t)}var la=aa(ia);function ut(){return{...process.env,LC_ALL:"C",LANG:"C"}}var ee=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"],cn=5000;async function be(t,e,n){let{stdout:r}=await la("git",e,{cwd:t,env:ut(),encoding:"buffer",maxBuffer:n,timeout:cn,windowsHide:!0});return r}var ua={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0},fa=1e4,ha=600000;function E(t,e={}){let n=_r(),r=n===null?[]:[`core.attributesFile=${n}`];return ca({baseDir:t,unsafe:ua,timeout:{block:e.longRunning===!0?ha:fa},config:r}).env(ut())}import{execFileSync as Ea}from"node:child_process";import*as re from"node:fs";import*as fn from"node:path";async function _t(t,e){if(e.length===0)return new Set;let n=E(t),r=100,s=[];for(let a=0;a<e.length;a+=r)s.push(e.slice(a,a+r));let o=await Promise.all(s.map(async(a)=>{try{return await n.raw(["check-ignore","--",...a])}catch(c){if(c instanceof Error?c.message.trim():String(c))k("git check-ignore failed; ignored files may show as untracked",c,{repo:t});return""}})),i=new Set;for(let a of o)for(let c of a.trim().split(`
11
+ `))if(c.length>0)i.add(c);return i}function dt(t){if(t.length===0)return"";return t.map((e)=>e.content).join(`
10
12
  `)+`
11
- `}function zZ($){let Z=0;for(let K of $)Z+=K.content.length+1;return Z}var C1=5000,n$=262144,K8="Large file — diff not shown";function N1($){return String($).replace(/\B(?=(\d{3})+(?!\d))/g,",")}function B1($){let Z=$/1048576;if(Z>=1)return`${Z.toFixed(1)} MB`;return`${Math.round($/1024)} KB`}function dZ($,Z){let K=B1($),V=Z===void 0?K:`${K}, ${N1(Z)} lines`;return`${K8} (${V})`}function $8($){if($.length===0)return 0;let Z=1,K=-1;while((K=$.indexOf(`
12
- `,K+1))!==-1)Z++;return Z}function Z8($,Z,K){let V=$.split(`
13
- `),Q=V.findIndex((X)=>X.startsWith("@@"));return`${[...V.slice(0,Q===-1?4:Q),dZ(Z,K)].join(`
13
+ `}function Se(t){let e=0;for(let n of t)e+=n.content.length+1;return e}var da=5000,ne=262144,Pr="Large file — diff not shown";function pa(t){return String(t).replace(/\B(?=(\d{3})+(?!\d))/g,",")}function ma(t){let e=t/1048576;if(e>=1)return`${e.toFixed(1)} MB`;return`${Math.round(t/1024)} KB`}function ln(t,e){let n=ma(t),r=e===void 0?n:`${n}, ${pa(e)} lines`;return`${Pr} (${r})`}function Ar(t){if(t.length===0)return 0;let e=1,n=-1;while((n=t.indexOf(`
14
+ `,n+1))!==-1)e++;return e}function Ir(t,e,n){let r=t.split(`
15
+ `),s=r.findIndex((i)=>i.startsWith("@@"));return`${[...r.slice(0,s===-1?4:s),ln(e,n)].join(`
14
16
  `)}
15
- `}function s($){if($.length===0)return $;let Z=$.split(/(?=^diff --git )/m),K=!1,V=Z.map((Q)=>{let Y=Q.length;if(Y<=n$){let X=$8(Q);if(X<=C1)return Q;return K=!0,Z8(Q,Y,X)}return K=!0,Z8(Q,Y,$8(Q))});return K?V.join(""):$}function A1($){return $.startsWith("diff --git")||$.startsWith("index ")||$.startsWith("---")||$.startsWith("+++")||$.startsWith("old mode")||$.startsWith("new mode")||$.startsWith("new file")||$.startsWith("deleted file")||$.startsWith("similarity index")||$.startsWith("dissimilarity index")||$.startsWith("rename from")||$.startsWith("rename to")||$.startsWith("copy from")||$.startsWith("copy to")||$.startsWith("Binary files")||$.startsWith(K8)}function I1($){return $.startsWith("\\ ")}function V8($){let Z=$.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(Z)return{oldStart:parseInt(Z[1],10),newStart:parseInt(Z[2],10)};return null}function r($){if($==="")return[];let Z=$.split(`
16
- `);if(Z.length>1&&Z[Z.length-1]==="")Z.pop();let K=[],V=0,Q=0;for(let Y of Z)if(A1(Y))K.push({type:"header",content:Y});else if(I1(Y))K.push({type:"context",content:Y});else if(Y.startsWith("@@")){let X=V8(Y);if(X)V=X.oldStart,Q=X.newStart;K.push({type:"hunk",content:Y})}else if(Y.startsWith("+"))K.push({type:"addition",content:Y,newLineNum:Q++});else if(Y.startsWith("-"))K.push({type:"deletion",content:Y,oldLineNum:V++});else K.push({type:"context",content:Y,oldLineNum:V++,newLineNum:Q++});return K}function UZ($){let Z=new Map;if(!$)return Z;let K=null;for(let V of $.split(`
17
- `))if(V.startsWith("diff --git")){let Q=V.match(/^diff --git a\/.+ b\/(.+)$/);if(Q){if(K=Q[1],!Z.has(K))Z.set(K,0)}}else if(V.startsWith("@@")&&K)Z.set(K,(Z.get(K)??0)+1);return Z}function Q8($){let Z=new Map;for(let K of $.trim().split(`
18
- `)){if(!K)continue;let V=K.split("\t");if(V.length>=3){let Q=V[0]==="-"?0:parseInt(V[0],10),Y=V[1]==="-"?0:parseInt(V[1],10),X=V.slice(2).join("\t");Z.set(X,{insertions:Q,deletions:Y})}}return Z}var L1=n$;async function T1($,Z){try{let K=lZ.join($,Z),V=await o$.promises.stat(K);if(!V.isFile())return null;if(V.size>L1)return null;return(await o$.promises.readFile(K,"utf-8")).split(`
19
- `).filter((Y)=>Y.length>0).length}catch{return null}}var D1=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function F1($,Z){return D1.has(`${$}${Z}`)}function Y8($,Z){return Z?"conflicted":q1($)}function q1($){switch($){case"M":return"modified";case"A":return"added";case"D":return"deleted";case"?":return"untracked";case"R":return"renamed";case"C":return"copied";case"U":return"conflicted";default:return"modified"}}async function nZ($){let Z=L($);if(!await Z.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let V=await Z.status(),Q=[],Y=new Set,X=V.files.filter((M)=>M.working_dir==="?").map((M)=>M.path),J=await F$($,X);for(let M of V.files){if(M.index==="!"||M.working_dir==="!"||J.has(M.path))continue;let C=`${M.path}-${M.index!==" "&&M.index!=="?"}`;if(Y.has(C))continue;Y.add(C);let H=F1(M.index,M.working_dir);if(M.index&&M.index!==" "&&M.index!=="?"){let D=Y8(M.index,H);Q.push({path:M.path,status:D,staged:!0,...M.from&&(D==="renamed"||D==="copied")?{originalPath:M.from}:{}})}if(M.working_dir&&M.working_dir!==" ")Q.push({path:M.path,status:Y8(M.working_dir,H),staged:!1})}let[W,z]=await Promise.all([Z.diff(["--cached","--numstat"]).catch(()=>""),Z.diff(["--numstat"]).catch(()=>"")]),U=Q8(W),j=Q8(z);for(let M of Q){let C=M.staged?U.get(M.path):j.get(M.path);if(C)M.insertions=C.insertions,M.deletions=C.deletions}let G=Q.filter((M)=>M.status==="untracked");if(G.length>0){let M=await Promise.all(G.map((C)=>T1($,C.path)));for(let C=0;C<G.length;C++){let H=M[C];if(H===null)continue;G[C].insertions=H,G[C].deletions=0}}return{files:Q,branch:{current:V.current||"HEAD",tracking:V.tracking||void 0,ahead:V.ahead,behind:V.behind},isRepo:!0}}async function J8($,Z){await L($).add(["--",Z])}async function W8($,Z){await L($).reset(["HEAD","--",Z])}async function z8($){await L($).add("-A")}async function U8($){await L($).reset(["HEAD"])}async function j8($,Z){await L($).checkout(["--",Z])}async function G8($,Z){await L($).clean("f",["--",Z])}async function M8($,Z,K=!1){if(!(await L($,{longRunning:!0}).commit(Z,void 0,K?{"--amend":null}:void 0)).commit)throw Error("Nothing to commit: no staged changes")}async function O8($){let Z=L($);try{return(await Z.log({n:1})).latest?.message||""}catch{return""}}function H8($,Z){X8("git",["apply","--cached","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:f()})}function C8($,Z){X8("git",["apply","--cached","--reverse","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:f()})}async function N8($){let V=(await L($,{longRunning:!0}).push()).pushed;if(V.length===0)return"Everything up-to-date";return V.map((Q)=>`${Q.local} → ${Q.remote}`).join(", ")}async function B8($){return await L($,{longRunning:!0}).fetch(),"Fetch complete"}async function A8($){let K=await L($,{longRunning:!0}).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 I8($,Z=50){let K=L($);try{return(await K.log({n:Z})).all.map((Q)=>({hash:Q.hash,shortHash:Q.hash.slice(0,7),message:Q.message.split(`
20
- `)[0],author:Q.author_name,date:new Date(Q.date),refs:Q.refs||""}))}catch{return[]}}async function L8($,Z){let K=L($);try{let Q=(await K.log(["--no-walk",Z])).all[0];if(!Q)return null;return{hash:Q.hash,shortHash:Q.hash.slice(0,7),message:Q.message.split(`
21
- `)[0],author:Q.author_name,date:new Date(Q.date),refs:Q.refs||""}}catch{return null}}async function jZ($){let Z=L($);try{return(await Z.stashList()).all.map((V,Q)=>({index:Q,message:V.message}))}catch{return[]}}async function T8($,Z){let K=L($),V=["push"];if(Z)V.push("-m",Z);return await K.stash(V),"Stashed"}async function D8($,Z=0){let K=L($);await K.stash(["pop",`stash@{${Z}}`]);let V=(await K.raw(["diff","--name-only","--diff-filter=U"])).trim();if(V)throw Error(`Stash pop hit conflicts in: ${V.split(`
22
- `).join(", ")}`);return"Stash popped"}async function GZ($){let K=await L($).branchLocal();return K.all.map((V)=>({name:V,current:V===K.current,tracking:K.branches[V]?.label||void 0}))}async function F8($,Z){return await L($).raw(["switch","--",Z]),`Switched to ${Z}`}async function q8($,Z){return await L($).raw(["switch","-c",Z]),`Created ${Z}`}async function S8($,Z=1){return await L($).reset(["--soft",`HEAD~${Z}`]),"Reset done"}async function R8($,Z){return await L($,{longRunning:!0}).raw(["cherry-pick","--end-of-options",Z]),"Cherry-picked"}async function v8($,Z){return await L($,{longRunning:!0}).raw(["revert","--no-edit","--end-of-options",Z]),"Reverted"}async function t($){let Z=L($),K;try{K=(await Z.raw(["rev-parse","--absolute-git-dir"])).trim()}catch{return null}let V=(Q)=>o$.existsSync(lZ.join(K,Q));if(V("rebase-merge")||V("rebase-apply"))return"rebase";if(V("CHERRY_PICK_HEAD"))return"cherry-pick";if(V("REVERT_HEAD"))return"revert";if(V("MERGE_HEAD"))return"merge";return null}async function w8($){let Z=await t($);if(!Z)throw Error("No operation in progress to abort");return await L($).raw([Z,"--abort"]),`Aborted ${Z}`}async function k8($){return await L($,{longRunning:!0}).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function E8($){return(await L($).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((V)=>V.length>0)}import*as j$ from"node:fs";import*as S$ from"node:path";import*as e from"node:fs";import*as U$ from"node:path";function oZ(){return U$.join(T$(),"base-branches.json")}function S1(){let $=U$.dirname(oZ());if(!e.existsSync($))e.mkdirSync($,{recursive:!0})}function _8(){try{let $=oZ();if(e.existsSync($))return JSON.parse(e.readFileSync($,"utf-8"))}catch{}return{}}function R1($){S1(),e.writeFileSync(oZ(),JSON.stringify($,null,2)+`
23
- `)}function q$($){let Z=_8(),K=U$.resolve($);return Z[K]}function P8($,Z){let K=_8(),V=U$.resolve($);K[V]=Z,R1(K)}function a$($){let Z=Math.min($.length,8192);for(let K=0;K<Z;K++)if($[K]===0)return!0;return!1}class R$ extends Error{constructor($){super(`No common history with ${$}`);this.name="NoCommonHistoryError"}}var v1={staged:!1,unstaged:!1,untracked:!1};var G$=3,OZ=1e5;async function v$($,Z,K=!1,V={}){let Q=L($);try{let Y=[`-U${V.context??G$}`];if(K)Y.push("--cached");if(Z)Y.push("--",Z);let X=s(await Q.diff(Y));return{lines:r(X)}}catch{return{lines:[]}}}var w1="4b825dc642cb6eb9a060e54bf8d69288fbee4904",x8="(unborn)",k1=/unknown revision|ambiguous argument 'HEAD'|needed a single revision/i;async function HZ($){let Z=L($);try{return(await Z.raw(["rev-parse","HEAD"])).trim()}catch(K){let V=K instanceof Error?K.message:String(K);if(k1.test(V))return x8;throw K}}async function b8($){let Z=L($),V=await HZ($)===x8?w1:"HEAD",Q=s(await Z.raw(["diff",`-U${G$}`,V,"--"]));return{lines:r(Q)}}var E1=n$;function _1($,Z){return{lines:[{type:"header",content:`diff --git a/${$} b/${$}`},{type:"header",content:"new file mode 100644"},{type:"header",content:"--- /dev/null"},{type:"header",content:`+++ b/${$}`},{type:"header",content:dZ(Z)}]}}function P1($){return{lines:[{type:"header",content:`diff --git a/${$} b/${$}`},{type:"header",content:"new file mode 100644"},{type:"header",content:`Binary files /dev/null and b/${$} differ`}]}}function x1($,Z){let K=S$.resolve($),V=S$.resolve(K,Z);if(V!==K&&!V.startsWith(K+S$.sep))return null;let Q,Y;try{Q=j$.realpathSync(V),Y=j$.realpathSync(K)}catch{return null}if(Q!==Y&&!Q.startsWith(Y+S$.sep))return null;let X=j$.statSync(Q);if(!X.isFile())return null;return{path:V,size:X.size}}async function M$($,Z){try{let K=x1($,Z);if(K===null)return{lines:[]};if(K.size>E1)return _1(Z,K.size);let V=j$.readFileSync(K.path);if(a$(V))return P1(Z);let Q=V.toString("utf-8"),Y=[{type:"header",content:`diff --git a/${Z} b/${Z}`},{type:"header",content:"new file mode 100644"},{type:"header",content:"--- /dev/null"},{type:"header",content:`+++ b/${Z}`}],X=Q.endsWith(`
24
- `),J=Q.split(`
25
- `);if(X)J.pop();if(Q.length>0){Y.push({type:"hunk",content:`@@ -0,0 +1,${J.length} @@`});let U=1;for(let j of J)Y.push({type:"addition",content:"+"+j,newLineNum:U++});if(!X)Y.push({type:"context",content:"\"})}let W=z$(Y),z=s(W);if(z!==W)return{lines:r(z)};return{lines:Y}}catch{return{lines:[]}}}async function aZ($){let Z=L($),K=new Set,V=[];try{let Q=await Z.raw(["log","--oneline","--decorate=short","--all","-n","200"]),Y=/\(([^)]+)\)/g;for(let X of Q.split(`
26
- `)){let J=Y.exec(X);if(J){let W=J[1].split(",").map((z)=>z.trim());for(let z of W){if(z.startsWith("HEAD")||z.startsWith("tag:")||!z.includes("/"))continue;let U=z.replace(/^.*-> /,"");if(U.includes("/")&&!K.has(U))K.add(U),V.push(U)}}Y.lastIndex=0}if(V.length>0)V.sort((X,J)=>{let W=X.split("/").slice(1).join("/"),z=J.split("/").slice(1).join("/"),U=W==="main"||W==="master",j=z==="main"||z==="master";if(U&&!j)return-1;if(!U&&j)return 1;if(U&&j){let G=X.startsWith("origin/"),M=J.startsWith("origin/");if(G&&!M)return 1;if(!G&&M)return-1}return 0})}catch{}return[...new Set(V)]}async function i$($){return(await aZ($))[0]??null}async function iZ($){return q$($)??await i$($)}async function $$($,Z){let K=L($);try{return await K.raw(["cat-file","-e","--end-of-options",`${Z}^{commit}`]),!0}catch{return!1}}function y8($,Z,K){let V=$.trim().split(`
27
- `).filter((z)=>z),Q=new Map;for(let z of V){let U=z.split("\t");if(U.length>=3){let j=U[0]==="-"?0:parseInt(U[0],10),G=U[1]==="-"?0:parseInt(U[1],10),M=U.slice(2).join("\t");Q.set(M,{additions:j,deletions:G})}}let Y=Z.trim().split(`
28
- `).filter((z)=>z),X=new Map;for(let z of Y){let U=z.split("\t");if(U.length>=2){let j=U[0][0],G=U[U.length-1],M;switch(j){case"A":M="added";break;case"D":M="deleted";break;case"R":M="renamed";break;default:M="modified"}X.set(G,M)}}let J=[],W=K.split(/(?=^diff --git )/m).filter((z)=>z.trim());for(let z of W){let U=z.match(/^diff --git a\/.+ b\/(.+)$/m);if(!U)continue;let j=U[1],G=r(z),M=Q.get(j)||{additions:0,deletions:0},C=X.get(j)||"modified";J.push({path:j,status:C,additions:M.additions,deletions:M.deletions,diff:{lines:G}})}return J.sort((z,U)=>z.path.localeCompare(U.path)),J}async function b1($,Z){let K=L($),Q=(await K.raw(["merge-base","--end-of-options",Z,"HEAD"])).trim();if(!Q)throw new R$(Z);let Y=await K.raw(["diff","--numstat",`${Q}...HEAD`]),X=await K.raw(["diff","--name-status",`${Q}...HEAD`]),J=s(await K.raw(["diff",`-U${G$}`,`${Q}...HEAD`])),W=y8(Y,X,J),z=0,U=0;for(let H of W)z+=H.additions,U+=H.deletions;let G=(await K.status()).files.length,C=(await K.log({from:Q,to:"HEAD"})).all.map((H)=>({hash:H.hash,shortHash:H.hash.slice(0,7),message:H.message.split(`
29
- `)[0],author:H.author_name,date:new Date(H.date),refs:H.refs||""}));return{baseBranch:Z,stats:{filesChanged:W.length,additions:z,deletions:U},files:W,commits:C,uncommittedCount:G}}async function m8($,Z){let K=L($),Q=(await K.raw(["merge-base","--end-of-options",Z,"HEAD"])).trim();if(!Q)throw new R$(Z);let Y=await K.raw(["rev-list","--count","--end-of-options",`${Q}..HEAD`]);return Number.parseInt(Y.trim(),10)}function MZ($,Z){switch($.kind){case"commit":return["show","--format=",...Z,"--end-of-options",$.hash];case"compare":return["diff",...Z,`${$.base}...HEAD`];case"head":return["diff",...Z,"HEAD"];case"staged":return["diff","--cached",...Z];case"unstaged":return["diff",...Z]}}async function y1($,Z,K){let V=L($),Q=MZ(Z,["--name-status","-M","--diff-filter=R"]),Y;try{Y=await V.raw(Q)}catch{return null}for(let X of Y.trim().split(`
30
- `)){if(!X)continue;let J=X.split("\t");if(J.length>=3&&J[2]===K)return J[1]}return null}async function sZ($,Z,K,V={}){let Q=L($),Y=V.context??G$;try{let X=await y1($,Z,K),J=X===null?[K]:[X,K],W=MZ(Z,["-M",`-U${Y}`]),z=s(await Q.raw([...W,"--",...J]));return{lines:r(z)}}catch{return{lines:[]}}}async function g8($,Z){let K=L($),V=(J)=>K.raw(["show","--format=",...J,"--end-of-options",Z]),Q=await V(["--numstat"]),Y=await V(["--name-status"]),X=s(await V([`-U${G$}`]));return y8(Q,Y,X)}async function c8($,Z){let K=L($);try{let V=s(await K.raw(["show","--format=",`-U${G$}`,"--end-of-options",Z]));return{lines:r(V)}}catch{return{lines:[]}}}function m1($){if($.staged&&$.unstaged)return"both";if($.staged)return"staged";if($.unstaged)return"unstaged";return null}function g1($){switch($){case"both":return{kind:"head"};case"staged":return{kind:"staged"};case"unstaged":return{kind:"unstaged"}}}function c1($,Z,K){let V=$==="staged"?[Z]:$==="unstaged"?[K]:[Z,K];if(V.includes("R"))return"renamed";if(V.includes("D"))return"deleted";if(V.includes("A")||V.includes("?"))return"added";return"modified"}function u1($){let Z=new Map;for(let K of $.trim().split(`
31
- `)){if(!K)continue;let V=K.split("\t");if(V.length<3)continue;let Q=V[0]==="-"?0:parseInt(V[0],10),Y=V[1]==="-"?0:parseInt(V[1],10);Z.set(V.slice(2).join("\t"),{additions:Q,deletions:Y})}return Z}async function p1($,Z,K){let V=L($),Q=g1(Z),Y=u1(await V.raw(MZ(Q,["--numstat"]))),X=s(await V.raw(MZ(Q,[`-U${G$}`]))),J=new Map(K.files.map((z)=>[z.path,z])),W=[];for(let z of X.split(/(?=^diff --git )/m)){if(!z.trim())continue;let U=z.match(/^diff --git a\/.+ b\/(.+)$/m);if(!U)continue;let j=U[1],G=J.get(j);W.push({path:j,status:c1(Z,G?.index??"",G?.working_dir??""),...Y.get(j)??{additions:0,deletions:0},diff:{lines:r(z)},uncommitted:Z})}return W}async function f1($,Z){let K=Z.files.filter((Y)=>Y.working_dir==="?").map((Y)=>Y.path),V=await F$($,K),Q=[];for(let Y of K){if(V.has(Y))continue;let X=await M$($,Y);if(X.lines.length===0)continue;Q.push({path:Y,status:"added",additions:X.lines.filter((J)=>J.type==="addition").length,deletions:0,diff:X,uncommitted:"untracked"})}return Q}async function u8($,Z,K=v1){let V=await b1($,Z),Q=m1(K);if(Q===null&&!K.untracked)return V;let Y=await L($).status(),X=[...Q===null?[]:await p1($,Q,Y),...K.untracked?await f1($,Y):[]],J=new Set(V.files.map((U)=>U.path)),W=[];for(let U of V.files)W.push(U),W.push(...X.filter((j)=>j.path===U.path));W.push(...X.filter((U)=>!J.has(U.path))),W.sort((U,j)=>U.path.localeCompare(j.path));let z=new Set(W.map((U)=>U.path));return{baseBranch:V.baseBranch,stats:{filesChanged:z.size,additions:W.reduce((U,j)=>U+j.additions,0),deletions:W.reduce((U,j)=>U+j.deletions,0)},files:W,commits:V.commits,uncommittedCount:V.uncommittedCount}}import*as p8 from"node:fs";import*as f8 from"node:path";var h1=/^diff --git a\/.+ b\/(.+)$/;function CZ($){let Z=5381;for(let K of $){for(let V=0;V<K.length;V++)Z=(Z<<5)+Z+K.charCodeAt(V)|0;Z=(Z<<5)+Z+10|0}return(Z>>>0).toString(36)}function d1($){let Z=[],K="",V=null,Q=()=>{if(V&&K)Z.push({file:K,key:`${K}\x00${CZ(V.body)}`,headerLine:V.headerLine});V=null};for(let Y of $.lines)if(Y.type==="header"){Q();let X=Y.content.match(h1);if(X)K=X[1]}else if(Y.type==="hunk")Q(),V={headerLine:Y,body:[]};else if(V&&(Y.type==="addition"||Y.type==="deletion"))V.body.push(Y.content);return Q(),Z}class rZ{repoPath;stamps=new Map;constructor($){this.repoPath=$}stamp($){if(!$)return;let Z=new Map;for(let K of d1($)){let V=this.stamps.get(K.key);if(V===void 0){let Q=Z.get(K.file);if(Q===void 0)Q=this.mtimeOf(K.file),Z.set(K.file,Q);V=Q,this.stamps.set(K.key,V)}K.headerLine.editedAt=V}}prune($){for(let Z of this.stamps.keys()){let K=Z.slice(0,Z.indexOf("\x00"));if(!$.has(K))this.stamps.delete(Z)}}mtimeOf($){try{return p8.statSync(f8.join(this.repoPath,$)).mtimeMs}catch{return Date.now()}}}import*as o from"node:fs";import*as P from"node:path";async function l1($){let Z=eZ($);if(!Z)return null;try{let K=L(Z);if((await K.raw(["rev-parse","--is-bare-repository"])).trim()==="true")return null;return(await K.raw(["rev-parse","--show-toplevel"])).trim()||null}catch{return null}}async function NZ($,{mustExist:Z}){let K=l($);if(!P.isAbsolute(K))return{ok:!1,reason:"not-absolute",requested:K};if(Z&&!n1(K))return{ok:!1,reason:"not-a-repo",requested:K};let V=await l1(K);if(V)return{ok:!0,root:V};let Q=s1(await o1(K));return Q?{ok:!0,root:Q.path}:{ok:!1,reason:"not-a-repo",requested:K}}function n1($){try{return o.statSync($).isDirectory()}catch{return!1}}async function o1($){let Z=eZ($);if(!Z)return[];try{let K=L(Z);return n8(await K.raw(["worktree","list","--porcelain"]))}catch{return[]}}async function tZ($){let Z=eZ($);if(!Z)return[];try{let V=await L(Z).raw(["worktree","list","--porcelain"]),Q=n8(V),Y=await i1(Q,Z);return Q.map((X)=>({...X,lastActivity:X.isBare?null:a1(h8(X.path)),aheadOfBase:Y.get(X.path)??null}))}catch{return[]}}function a1($){return Number.isFinite($)?$:null}async function i1($,Z){let K=$.filter((Y)=>!Y.isBare);if(K.length===0)return new Map;let V=await i$(Z).catch(()=>null),Q=await Promise.all(K.map(async(Y)=>{let X=q$(Y.path)??V;if(!X)return null;try{let W=await L(Y.path).raw(["rev-list","--count","--end-of-options",`${X}..HEAD`]);return[Y.path,parseInt(W.trim(),10)]}catch{return null}}));return new Map(Q.filter((Y)=>Y!==null))}function s1($){let Z=null,K=-1/0;for(let V of $){if(V.isBare)continue;let Q=h8(V.path);if(Q>K)K=Q,Z=V}return Z}function h8($){let Z=d8($),K=Z?[P.join(Z,"index"),P.join(Z,"HEAD")]:[$],V=-1/0;for(let Q of K)try{let Y=o.statSync(Q).mtimeMs;if(Y>V)V=Y}catch{}return V}function d8($){let Z=P.join($,".git");try{if(o.statSync(Z).isDirectory())return Z;let K=o.readFileSync(Z,"utf8").match(/^gitdir:\s*(.+)$/m);if(!K)return null;let V=K[1].trim();return P.isAbsolute(V)?V:P.resolve($,V)}catch{return null}}function l8($){let Z=d8($);if(Z===null)return null;let K=Z;try{let V=o.readFileSync(P.join(Z,"commondir"),"utf8").trim();if(V)K=P.isAbsolute(V)?V:P.resolve(Z,V)}catch{}return{gitDir:Z,commonDir:K}}function n8($){let Z=[],K=null;for(let V of $.split(`
32
- `))if(V.startsWith("worktree ")){if(K)Z.push(K);K={path:V.slice(9).trim(),branch:null,head:null,isBare:!1,isMain:Z.length===0}}else if(!K)continue;else if(V.startsWith("HEAD "))K.head=V.slice(5).trim();else if(V.startsWith("branch "))K.branch=V.slice(7).trim().replace(/^refs\/heads\//,"");else if(V==="bare")K.isBare=!0;if(K)Z.push(K);return Z}function eZ($){try{if(o.statSync($).isDirectory())return $;return P.dirname($)}catch{let Z=P.dirname($);return Z!==$&&o.existsSync(Z)?Z:null}}var X7=n5(V4(),1);var J7=/^diff --git a\/.+ b\/(.+)$/;function Q4($){return J7.exec($)?.[1]??null}function IZ($){let Z=new Map,K=null;for(let Q of $.lines){if(Q.type==="header"){let Y=Q4(Q.content);if(Y!==null)K=Z.get(Y)??[],Z.set(Y,K)}K?.push(Q)}let V=new Map;for(let[Q,Y]of Z)V.set(Q,{lines:Y});return V}var LZ="diffstalker-journal: oversize untracked snapshot omitted";var U7=262144;class TZ extends z7{repoPath;queue;hunkTimes;gitWatcher=null;workingDirWatcher=null;ignorers=new Map;_state={status:null,isLoading:!1,error:null,hunkCounts:null,stashList:[],operationInProgress:null,mtimes:null};constructor($,Z){super();this.repoPath=$,this.queue=Z,this.hunkTimes=new rZ($)}get state(){return this._state}updateState($){this._state={...this._state,...$},this.emit("state-change",this._state)}setError($){this.updateState({error:$})}clearError(){if(this._state.error!==null)this.updateState({error:null})}stampDiff($){this.hunkTimes.stamp($)}loadGitignores(){let $=new Map,Z=X4();Z.add(".git");let K=E.join(this.repoPath,".gitignore");if(h.existsSync(K))Z.add(h.readFileSync(K,"utf-8"));let V=E.join(this.repoPath,".git","info","exclude");if(h.existsSync(V))Z.add(h.readFileSync(V,"utf-8"));$.set("",Z);try{let Q=W7("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:f()});for(let Y of Q.split("\x00")){if(!Y||Y===".gitignore")continue;if(!Y.endsWith(".gitignore"))continue;let X=E.dirname(Y),J=E.join(this.repoPath,Y);try{let W=h.readFileSync(J,"utf-8"),z=X4();z.add(W),$.set(X,z)}catch(W){XZ(`Failed to read ${J}: ${W instanceof Error?W.message:W}`)}}}catch{}return $}startWatching(){let $=l8(this.repoPath);if($===null)return;let Z=E.join($.gitDir,"index"),K=E.join($.gitDir,"HEAD"),V=E.join($.commonDir,"refs"),Q=E.join($.commonDir,"packed-refs"),Y=E.join(this.repoPath,".gitignore");this.gitWatcher=Y4([Z,K,V,Q,Y],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=Y4(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(J,W)=>{let z=E.relative(this.repoPath,J);if(!z)return!1;let U=z.split("/");for(let j=0;j<U.length;j++){let G=j===0?"":U.slice(0,j).join("/"),M=this.ignorers.get(G);if(M){let C=j===0?z:U.slice(j).join("/");if(M.ignores(C))return!0}}return WZ(J,W)},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let X=()=>this.scheduleRefresh();this.gitWatcher.on("change",(J)=>{if(J===Y)this.ignorers=this.loadGitignores();X()}),this.gitWatcher.on("add",X),this.gitWatcher.on("unlink",X),this.gitWatcher.on("error",(J)=>{let W=J instanceof Error?J.message:String(J);this.setError(`Git watcher error: ${W}`)}),this.workingDirWatcher.on("change",X),this.workingDirWatcher.on("add",X),this.workingDirWatcher.on("unlink",X),this.workingDirWatcher.on("error",(J)=>{let W=J instanceof Error?J.message:String(J);this.setError(`Working dir watcher error: ${W}`)})}dispose(){this.gitWatcher?.close(),this.workingDirWatcher?.close()}statMtimes($){let Z=new Map;for(let K of $.files){if(Z.has(K.path))continue;try{Z.set(K.path,h.statSync(E.join(this.repoPath,K.path)).mtimeMs)}catch{}}return Z}pendingRefreshKind=null;scheduleRefresh(){this.requestRefresh("full")}scheduleStatusRefresh(){this.requestRefresh("status")}requestRefresh($){if(this.pendingRefreshKind!==null){if($==="full")this.pendingRefreshKind="full";return}if(this.queue.hasPendingMutations())return;this.pendingRefreshKind=$,this.queue.scheduleRefresh(async()=>{let Z=this.pendingRefreshKind??"full";if(this.pendingRefreshKind=null,Z==="full")await this.doRefresh();else await this.doStatusRefresh()})}async doStatusRefresh(){try{let $=await nZ(this.repoPath);if(!$.isRepo){this.updateState({status:$,isLoading:!1,error:"Not a git repository"});return}this.updateState({status:$,mtimes:this.statMtimes($),isLoading:!1})}catch($){this.updateState({isLoading:!1,error:$ instanceof Error?$.message:"Unknown error"})}}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.updateState({isLoading:!0,error:null});let $=Date.now(),Z=await HZ(this.repoPath).catch(()=>null);try{let K=await nZ(this.repoPath);if(!K.isRepo){this.updateState({status:K,isLoading:!1,error:"Not a git repository"});return}let[V,Q,Y,X,J]=await Promise.all([v$(this.repoPath,void 0,!1),v$(this.repoPath,void 0,!0),jZ(this.repoPath),t(this.repoPath),this.gatherJournalInputs(K,Z,$)]),W={unstaged:UZ(z$(V.lines)),staged:UZ(z$(Q.lines))};this.hunkTimes.stamp(V),this.hunkTimes.stamp(Q),this.hunkTimes.prune(new Set(K.files.map((U)=>U.path)));let z=this.statMtimes(K);if(this.updateState({status:K,hunkCounts:W,stashList:Y,operationInProgress:X,mtimes:z,isLoading:!1}),J!==null)this.emit("journal-observation",{status:K,headDiff:J.headDiff,headOid:J.headOid,stashCount:J.stashCount,operationInProgress:J.operationInProgress,mtimes:J.mtimes,at:Date.now()})}catch(K){this.updateState({isLoading:!1,error:K instanceof Error?K.message:"Unknown error"})}}async snapshotJournalGuard($){let[Z,K]=await Promise.all([t(this.repoPath),jZ(this.repoPath)]);return{operation:Z,stashCount:K.length,mtimes:this.statMtimes($)}}static journalGuardMoved($,Z){if($.operation!==Z.operation||$.stashCount!==Z.stashCount)return!0;if($.mtimes.size!==Z.mtimes.size)return!0;for(let[K,V]of $.mtimes)if(Z.mtimes.get(K)!==V)return!0;return!1}sectionWrittenDuringGather($,Z,K){let V=new Set(Z);for(let Q of $.files)if(Q.status==="untracked")V.add(Q.path);for(let Q of V)try{let Y=h.statSync(E.join(this.repoPath,Q));if(Math.floor(Y.mtimeMs)>K)return!0}catch{}return!1}async gatherJournalInputs($,Z,K){if(Z===null)return null;try{let V=await this.snapshotJournalGuard($),Q=await b8(this.repoPath),Y=new Set(IZ(Q).keys()),X=[...Q.lines];await this.appendUntrackedSections($,Y,X);let J=await HZ(this.repoPath);if(Z!==J)return null;let W=await this.snapshotJournalGuard($);if(TZ.journalGuardMoved(V,W))return null;if(this.sectionWrittenDuringGather($,Y,K))return null;return{headDiff:{lines:X},headOid:J,stashCount:W.stashCount,operationInProgress:W.operation,mtimes:W.mtimes}}catch{return null}}async appendUntrackedSections($,Z,K){let V=new Set;for(let Q of $.files){if(Q.status!=="untracked"||V.has(Q.path)||Z.has(Q.path))continue;V.add(Q.path);let Y;try{Y=h.statSync(E.join(this.repoPath,Q.path))}catch{continue}if(!Y.isFile())continue;if(Y.size>U7){this.appendOversizeSection(Q.path,Y,K);continue}let X=await M$(this.repoPath,Q.path);if(X.lines.length===0)continue;K.push(...X.lines)}}appendOversizeSection($,Z,K){let V=[`diff --git a/${$} b/${$}`,"new file mode 100644",`${LZ} size=${Z.size} mtime=${Math.round(Z.mtimeMs)}`];K.push(...V.map((Q)=>({type:"header",content:Q})))}async stage($){try{await this.queue.enqueueMutation(()=>J8(this.repoPath,$.path)),this.scheduleStatusRefresh()}catch(Z){await this.refresh(),this.updateState({error:`Failed to stage ${$.path}: ${Z instanceof Error?Z.message:String(Z)}`})}}async unstage($){try{await this.queue.enqueueMutation(()=>W8(this.repoPath,$.path)),this.scheduleStatusRefresh()}catch(Z){await this.refresh(),this.updateState({error:`Failed to unstage ${$.path}: ${Z instanceof Error?Z.message:String(Z)}`})}}async stageHunk($){try{await this.queue.enqueueMutation(async()=>H8(this.repoPath,$)),this.scheduleRefresh()}catch(Z){await this.refresh(),this.updateState({error:`Failed to stage hunk: ${Z instanceof Error?Z.message:String(Z)}`})}}async unstageHunk($){try{await this.queue.enqueueMutation(async()=>C8(this.repoPath,$)),this.scheduleRefresh()}catch(Z){await this.refresh(),this.updateState({error:`Failed to unstage hunk: ${Z instanceof Error?Z.message:String(Z)}`})}}async discard($){if($.staged)return;let Z=$.status==="untracked"?()=>G8(this.repoPath,$.path):()=>j8(this.repoPath,$.path);try{await this.queue.enqueueMutation(Z),await this.refresh()}catch(K){this.updateState({error:`Failed to discard ${$.path}: ${K instanceof Error?K.message:String(K)}`})}}async stageAll(){try{await this.queue.enqueueMutation(()=>z8(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to stage all: ${$ instanceof Error?$.message:String($)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>U8(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to unstage all: ${$ instanceof Error?$.message:String($)}`})}}async commit($,Z=!1){try{await this.queue.enqueue(()=>M8(this.repoPath,$,Z)),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(()=>jZ(this.repoPath));this.updateState({stashList:$})}catch{}}}import{EventEmitter as j7}from"node:events";class V6 extends j7{repoPath;queue;callbacks;_remoteState={operation:null,inProgress:!1,error:null,lastResult:null};constructor($,Z,K){super();this.repoPath=$,this.queue=Z,this.callbacks=K}get remoteState(){return this._remoteState}updateRemoteState($){this._remoteState={...this._remoteState,...$},this.emit("remote-state-change",this._remoteState)}async runRemoteOperation($,Z){this.updateRemoteState({operation:$,inProgress:!0,error:null,lastResult:null});try{let K=await this.queue.enqueue(Z);this.updateRemoteState({inProgress:!1,lastResult:K}),this.callbacks.scheduleRefresh()}catch(K){let V=K instanceof Error?K.message:String(K);this.updateRemoteState({inProgress:!1,error:V})}return this._remoteState}clearRemoteState(){this.updateRemoteState({operation:null,error:null,lastResult:null})}async push(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("push",()=>N8(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>B8(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>A8(this.repoPath))}async stash($){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stash",()=>T8(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async stashPop($=0){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stashPop",()=>D8(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async getLocalBranches(){return this.queue.enqueue(()=>GZ(this.repoPath))}async switchBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>F8(this.repoPath,$))}async createBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>q8(this.repoPath,$))}async softReset($=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>S8(this.repoPath,$))}async cherryPick($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>R8(this.repoPath,$))}async revertCommit($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>v8(this.repoPath,$))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>w8(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>k8(this.repoPath))}}import{EventEmitter as G7}from"node:events";import{randomBytes as M7}from"node:crypto";var O7=262144,H7=500,C7=16777216,z4=Number.MAX_SAFE_INTEGER,N7=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function B7($){let Z=N7.exec($);if(!Z)return null;return{oldStart:parseInt(Z[1],10),oldCount:Z[2]!==void 0?parseInt(Z[2],10):1}}function A7($,Z){let K=B7(Z);if(!K)return[];let V=K.oldCount===0?K.oldStart+1:K.oldStart,Q=[],Y=null;for(let X of $){let J=X.content[0];if(J==="\\")continue;if(J==="-")Y=I7(Y,V),V++;else if(J==="+")Y=Y??{hasDel:!1,delStart:0,delEnd:0,anchor:V-1};else J4(Q,Y),Y=null,V++}return J4(Q,Y),Q}function I7($,Z){if(!$)return{hasDel:!0,delStart:Z,delEnd:Z,anchor:Z-1};if(!$.hasDel)$.hasDel=!0,$.delStart=Z;return $.delEnd=Z,$}function J4($,Z){if(!Z)return;$.push(Z.hasDel?[2*Z.delStart,2*Z.delEnd]:[2*Z.anchor,2*Z.anchor+2])}function Q6($){if($.length===0)return{start:0,count:0};let Z=1/0,K=-1/0;for(let[Y,X]of $){if(Y<Z)Z=Y;if(X>K)K=X}if(K>=z4)return{start:0,count:0};let V=Math.ceil(Z/2),Q=Math.floor(K/2);return{start:V,count:Q-V+1}}function L7($){let Z=[],K=null,V=[],Q=null;for(let X of $.lines)if(X.type==="hunk")Q={header:X,body:[]},V.push(Q);else if(Q)Q.body.push(X);else if(Z.push(X),X.content.startsWith("rename from "))K=X.content.slice(12);if(V.length===0){let X=Z.some((J)=>J.content.startsWith(LZ));return{hunks:[{runs:[[0,z4]],bodyHash:CZ([z$($.lines)]),ins:0,del:0,span:{start:0,count:0},diff:$,oversize:X}],renamedFrom:K,hunkless:!0}}return{hunks:V.map(({header:X,body:J})=>{let W=A7(J,X.content),z=[],U=0,j=0;for(let M of J){let C=M.content[0];if(C==="\\")continue;if(C==="+")U++,z.push(M.content);else if(C==="-")j++,z.push(M.content)}let G=[...Z,X,...J];return{runs:W,bodyHash:CZ(z),ins:U,del:j,span:Q6(W),diff:{lines:G}}}),renamedFrom:K,hunkless:!1}}function T7($){if($.oversize===!0)return null;return zZ($.diff.lines)>O7?null:$.diff}function D7($,Z,K){if($===0&&Z>0)return"shrunk";let V=$+Z;if(V>K)return"expanded";if(V<K)return"shrunk";return"edited"}function W4($,Z){let K=[];return $.forEach((V,Q)=>{for(let[Y,X]of V.runs)K.push({lo:Y,hi:X,node:Z+Q})}),K.sort((V,Q)=>V.lo-Q.lo),K}function F7($,Z){let K=Array.from({length:$.length+Z.length},(W,z)=>z),V=(W)=>{while(K[W]!==W)K[W]=K[K[W]],W=K[W];return W},Q=(W,z)=>{let U=V(W),j=V(z);if(U!==j)K[U]=j},Y=W4($,0),X=W4(Z,$.length),J=0;for(let W of Y){while(J<X.length&&X[J].hi<W.lo)J++;for(let z=J;z<X.length&&X[z].lo<=W.hi;z++)Q(W.node,X[z].node)}return K.map((W,z)=>V(z))}function q7($,Z){let K=F7($,Z),V=new Map,Q=(Y)=>{let X=V.get(Y);if(!X)X={prevIdx:[],nextIdx:[],minLo:1/0},V.set(Y,X);return X};return $.forEach((Y,X)=>{let J=Q(K[X]);J.prevIdx.push(X);for(let[W]of Y.runs)if(W<J.minLo)J.minLo=W}),Z.forEach((Y,X)=>{let J=Q(K[$.length+X]);J.nextIdx.push(X);for(let[W]of Y.runs)if(W<J.minLo)J.minLo=W}),[...V.values()].sort((Y,X)=>Y.minLo-X.minLo)}function S7($,Z,K){let V=[],Q=Z.map(()=>null),Y=K;for(let X of q7($,Z)){let J=X.prevIdx.map((j)=>$[j]),W=X.nextIdx.map((j)=>Z[j]);if(J.length===1&&W.length===1&&J[0].bodyHash===W[0].bodyHash){let j=W[0];Q[X.nextIdx[0]]={seq:J[0].seq,runs:j.runs,bodyHash:j.bodyHash,ins:j.ins,del:j.del};continue}if(W.length===0){for(let j of J)V.push({seq:Y++,kind:"reverted",span:Q6(j.runs),stats:{insertions:0,deletions:0},diff:null,supersedes:[j.seq],siblings:1});continue}let z=J.map((j)=>j.seq),U=J.reduce((j,G)=>j+G.ins+G.del,0);for(let j of X.nextIdx){let G=Z[j],M={seq:Y++,kind:J.length===0?"created":D7(G.ins,G.del,U),span:G.span,stats:{insertions:G.ins,deletions:G.del},diff:T7(G),supersedes:[...z],siblings:W.length};V.push(M),Q[j]={seq:M.seq,runs:G.runs,bodyHash:G.bodyHash,ins:G.ins,del:G.del}}}return{entries:V,nextLive:Q.filter((X)=>X!==null)}}function R7($,Z){let K=Array($.length).fill(!1),V=Array(Z.length).fill(null);for(let J=0;J<Z.length;J++){let W=$.findIndex((z,U)=>!K[U]&&z.bodyHash===Z[J].bodyHash);if(W!==-1)K[W]=!0,V[J]=$[W].seq}for(let J=0;J<Z.length;J++){if(V[J]!==null)continue;let W=K.findIndex((z)=>!z);if(W!==-1)K[W]=!0,V[J]=$[W].seq}let Q=$[$.length-1].seq,Y=Z.map((J,W)=>{return{seq:V[W]??Q,runs:J.runs,bodyHash:J.bodyHash,ins:J.ins,del:J.del}}),X=$.filter((J,W)=>!K[W]).map((J)=>J.seq);return{carried:Y,retired:X}}function DZ(){return{entries:[],epoch:`${Date.now().toString(36)}-${M7(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class Y6 extends G7{store;constructor($){super();this.store=$}get journalStore(){return this.store}observe($){try{this.doObserve($)}catch(Z){XZ(`Journal observation skipped: ${Z instanceof Error?Z.message:String(Z)}`)}}doObserve($){let Z=[];if(this.store.lastHeadOid===null){if($.operationInProgress===null)this.seed($,Z)}else if(this.handleOperations($,Z));else if($.headOid!==this.store.lastHeadOid)this.rebaseline($,Z);else this.classify($,Z);if(Z.length>0)this.store.entries.push(...Z),this.emit("append",Z),this.pruneStore()}pruneStore(){let $=new Set;for(let Z of this.store.live.values())for(let K of Z)$.add(K.seq);this.pruneBodies($),this.pruneEntries($)}pruneBodies($){let Z=0;for(let K of this.store.entries)if(K.type==="hunk"&&K.diff!==null)Z+=zZ(K.diff.lines);for(let K of this.store.entries){if(Z<=C7)return;if(K.type!=="hunk"||K.diff===null||$.has(K.seq))continue;Z-=zZ(K.diff.lines),K.diff=null}}pruneEntries($){let Z=this.store.entries,K=0;while(Z.length-K>H7&&(Z[K].type==="boundary"||!$.has(Z[K].seq)))K++;if(K>0)Z.splice(0,K)}handleOperations($,Z){let K=this.store.lastOperation;if($.operationInProgress!==null){if(K===null)Z.push(this.boundary("op-start",$.operationInProgress,[],$.at)),this.store.lastOperation=$.operationInProgress;return!0}if(K!==null)Z.push(this.boundary("op-end",K,[],$.at)),this.store.lastOperation=null;return!1}seed($,Z){Z.push(this.boundary("journal-start",$.status.branch.current,[],$.at));let{files:K}=this.parseObservation($),V=[...K.keys()].sort((Q,Y)=>this.tsFor($,Q)-this.tsFor($,Y));for(let Q of V)this.classifyPath(Q,[],K.get(Q).hunks,$,!0,Z);this.store.lastHeadOid=$.headOid,this.store.lastBranch=$.status.branch.current,this.store.lastStashCount=$.stashCount,this.store.lastOperation=null}rebaseline($,Z){let{files:K,deferred:V}=this.parseObservation($),Q=$.status.branch.current===this.store.lastBranch,Y=Q?"commit":"checkout",X=Q?$.headOid.slice(0,7):$.status.branch.current,{resolves:J,newLive:W}=this.carrySurvivors(K,V);Z.push(this.boundary(Y,X,J,$.at)),this.store.live=W;for(let[z,{hunks:U}]of K){if(W.has(z))continue;this.classifyPath(z,[],U,$,!1,Z)}this.store.lastHeadOid=$.headOid,this.store.lastBranch=$.status.branch.current,this.store.lastStashCount=$.stashCount}carrySurvivors($,Z){let K=[],V=new Map;for(let[Q,Y]of this.store.live){if(Z.has(Q)){V.set(Q,Y);continue}let X=$.get(Q);if(!X){K.push(...Y.map((z)=>z.seq));continue}let{carried:J,retired:W}=R7(Y,X.hunks);K.push(...W),V.set(Q,J)}return{resolves:K,newLive:V}}classify($,Z){let{files:K,deferred:V}=this.parseObservation($);this.handleRenames($,K,Z),this.handleDisappearances($,K,V,Z);for(let[Q,{hunks:Y,renamedFrom:X,hunkless:J}]of K){let W=this.store.live.get(Q)??[];if(J&&X!==null&&W.length>0)continue;this.classifyPath(Q,W,Y,$,!1,Z)}this.store.lastBranch=$.status.branch.current,this.store.lastStashCount=$.stashCount}handleRenames($,Z,K){for(let[V,Q]of Z){let Y=Q.renamedFrom;if(Y===null||Y===V)continue;if(!this.store.live.has(Y)||Z.has(Y))continue;let X=(this.store.live.get(V)??[]).map((J)=>J.seq);this.store.live.set(V,this.store.live.get(Y)),this.store.live.delete(Y),K.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor($,V),path:V,status:"renamed",kind:"renamed",span:{start:0,count:0},stats:{insertions:0,deletions:0},diff:null,supersedes:X,siblings:1,seeded:!1})}}handleDisappearances($,Z,K,V){let Q=[...this.store.live.keys()].filter((Y)=>!Z.has(Y)&&!K.has(Y));if(Q.length===0)return;if($.stashCount>this.store.lastStashCount){let Y=Q.flatMap((X)=>this.store.live.get(X).map((J)=>J.seq));V.push(this.boundary("stash","stash",Y,$.at));for(let X of Q)this.store.live.delete(X);return}for(let Y of Q){let X=this.store.live.get(Y);V.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor($,Y),path:Y,status:this.statusOf($,Y),kind:"reverted",span:Q6(X.flatMap((J)=>J.runs)),stats:{insertions:0,deletions:0},diff:null,supersedes:X.map((J)=>J.seq),siblings:1,seeded:!1}),this.store.live.delete(Y)}}classifyPath($,Z,K,V,Q,Y){let{entries:X,nextLive:J}=S7(Z,K,this.store.nextSeq);this.store.nextSeq+=X.length;let W=this.tsFor(V,$),z=this.statusOf(V,$);for(let U of X){let j={type:"hunk",seq:U.seq,ts:W,path:$,status:z,kind:U.kind==="created"&&z==="renamed"?"renamed":U.kind,span:U.span,stats:U.stats,diff:U.diff,supersedes:U.supersedes,siblings:U.siblings,seeded:Q};Y.push(j)}if(J.length>0)this.store.live.set($,J);else this.store.live.delete($)}parseObservation($){let Z=new Map;for(let[V,Q]of IZ($.headDiff))Z.set(V,L7(Q));let K=new Set;for(let V of $.status.files)if(V.status==="untracked"&&!Z.has(V.path))K.add(V.path);return{files:Z,deferred:K}}boundary($,Z,K,V){return{type:"boundary",seq:this.store.nextSeq++,ts:V,kind:$,label:Z,resolves:K}}tsFor($,Z){let K=$.mtimes?.get(Z);return K===void 0?$.at:Math.min(K,$.at)}statusOf($,Z){return $.status.files.find((K)=>K.path===Z)?.status??"modified"}}class X6{workingTree;remote;journal;repoPath;constructor($,Z){this.repoPath=$;let K=i6($);this.workingTree=new TZ($,K),this.remote=new V6($,K,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new Y6(Z??DZ()),this.workingTree.on("journal-observation",(V)=>this.journal.observe(V))}dispose(){this.workingTree.dispose(),s6(this.repoPath)}}function w7($){return v7("sha256").update($).digest("hex").slice(0,12)}var k7=32;class U4{cap;stores=new Map;constructor($=k7){this.cap=$}acquire($){let Z=this.stores.get($);if(Z)this.stores.delete($);else Z=DZ();return this.stores.set($,Z),Z}prune($){if(this.stores.size<=this.cap)return;for(let Z of this.stores.keys()){if(this.stores.size<=this.cap)return;if($(Z))continue;this.stores.delete(Z)}}has($){return this.stores.has($)}get size(){return this.stores.size}}class J6{events;byId=new Map;byPath=new Map;journalStores=new U4;constructor($={}){this.events=$}async openRepo($){let Z=await NZ($,{mustExist:!1});if(!Z.ok)throw Error(Z.reason==="not-absolute"?`Repo path must be absolute: ${Z.requested}`:`Not a git repository: ${Z.requested}`);let K=Z.root,V=this.byPath.get(K);if(V)return V.refCount++,{handle:V,created:!1};let Q=w7(K),Y=new X6(K,this.journalStores.acquire(Q));Y.workingTree.startWatching();let X={id:Q,path:K,manager:Y,refCount:1};return this.byId.set(X.id,X),this.byPath.set(K,X),this.journalStores.prune((J)=>this.byId.has(J)),this.events.onOpened?.(X),{handle:X,created:!0}}getRepo($){return this.byId.get($)}listRepos(){return[...this.byId.values()]}closeRepo($){let Z=this.byId.get($);if(!Z)return!1;if(Z.refCount--,Z.refCount>0)return!1;return this.byId.delete(Z.id),this.byPath.delete(Z.path),Z.manager.dispose(),this.events.onClosed?.(Z.id),!0}disposeAll(){for(let $ of this.byId.values())$.manager.dispose();this.byId.clear(),this.byPath.clear()}}async function FZ($,Z){let K=await $.openRepo(Z);if(K.created)K.handle.manager.workingTree.refresh().catch(()=>{});return K}var G4=25000;function w$($,Z,K){$.write(`event: ${Z}
33
- data: ${K}
17
+ `}function nt(t){if(t.length===0)return t;let e=t.split(/(?=^diff --git )/m),n=!1,r=e.map((s)=>{let o=s.length;if(o<=ne){let i=Ar(s);if(i<=da)return s;return n=!0,Ir(s,o,i)}return n=!0,Ir(s,o,Ar(s))});return n?r.join(""):t}function ga(t){return t.startsWith("diff --git")||t.startsWith("index ")||t.startsWith("---")||t.startsWith("+++")||t.startsWith("old mode")||t.startsWith("new mode")||t.startsWith("new file")||t.startsWith("deleted file")||t.startsWith("similarity index")||t.startsWith("dissimilarity index")||t.startsWith("rename from")||t.startsWith("rename to")||t.startsWith("copy from")||t.startsWith("copy to")||t.startsWith("Binary files")||t.startsWith(Pr)}function wa(t){return t.startsWith("\\ ")}function Mr(t){let e=t.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(e)return{oldStart:parseInt(e[1],10),newStart:parseInt(e[2],10)};return null}function rt(t){if(t==="")return[];let e=t.split(`
18
+ `);if(e.length>1&&e[e.length-1]==="")e.pop();let n=[],r=0,s=0;for(let o of e)if(ga(o))n.push({type:"header",content:o});else if(wa(o))n.push({type:"context",content:o});else if(o.startsWith("@@")){let i=Mr(o);if(i)r=i.oldStart,s=i.newStart;n.push({type:"hunk",content:o})}else if(o.startsWith("+"))n.push({type:"addition",content:o,newLineNum:s++});else if(o.startsWith("-"))n.push({type:"deletion",content:o,oldLineNum:r++});else n.push({type:"context",content:o,oldLineNum:r++,newLineNum:s++});return n}function Ee(t){let e=new Map;if(!t)return e;let n=null;for(let r of t.split(`
19
+ `))if(r.startsWith("diff --git")){let s=pt(r);if(s!==null){if(n=s,!e.has(n))e.set(n,0)}}else if(r.startsWith("@@")&&n)e.set(n,(e.get(n)??0)+1);return e}var Fr=new Map([["a",7],["b",8],["f",12],["n",10],["r",13],["t",9],["v",11],["\\",92],['"',34]]),ya=new Map([...Fr].map(([t,e])=>[e,t]));function Dr(t){return t<32||t===127||t>=128||t===34||t===92}function At(t){let e=new TextEncoder().encode(t);if(!e.some(Dr))return t;let n='"';for(let r of e){let s=ya.get(r);if(s!==void 0)n+=`\\${s}`;else if(Dr(r))n+=`\\${r.toString(8).padStart(3,"0")}`;else n+=String.fromCharCode(r)}return`${n}"`}function ba(t){if(t.length<2||!t.startsWith('"')||!t.endsWith('"'))return t;let e=t.slice(1,-1),n=new TextEncoder,r=[],s=0;while(s<e.length){let o=e.indexOf("\\",s);if(o===-1){r.push(...n.encode(e.slice(s)));break}r.push(...n.encode(e.slice(s,o)));let i=/^[0-7]{1,3}/.exec(e.slice(o+1,o+4));if(i!==null){r.push(parseInt(i[0],8)),s=o+1+i[0].length;continue}let a=Fr.get(e[o+1]??"");if(a!==void 0){r.push(a),s=o+2;continue}r.push(92),s=o+1}return new TextDecoder().decode(Uint8Array.from(r))}function Sa(t){for(let e=t.length-2;e>=0;e--){if(t[e]!=='"')continue;let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r--)n++;if(n%2===0)return e}return-1}function pt(t){if(!t.startsWith("diff --git "))return null;let n=t.slice(11);if(n.endsWith('"')){let s=Sa(n);if(s===-1)return null;let o=ba(n.slice(s));return o.startsWith("b/")?o.slice(2):null}let r=n.lastIndexOf(" b/");return r===-1?null:n.slice(r+3)}function It(t){let e=new Map,n=t.split("\x00");for(let r=0;r<n.length;r++){let s=n[r];if(s==="")continue;let o=s.split("\t");if(o.length<3)continue;let i=o[0]==="-"?0:parseInt(o[0],10),a=o[1]==="-"?0:parseInt(o[1],10),c=o.slice(2).join("\t");if(c==="")c=n[r+2]??"",r+=2;if(c!=="")e.set(c,{additions:i,deletions:a})}return e}function un(t){let e=[],n=t.split("\x00");for(let r=0;r<n.length;r++){let s=n[r];if(s==="")continue;let o=s[0];if(o==="R"||o==="C"){let i=n[r+1],a=n[r+2];if(i!==void 0&&a!==void 0)e.push({code:o,path:a,oldPath:i});r+=2}else{let i=n[r+1];if(i!==void 0)e.push({code:o,path:i});r+=1}}return e}function Dt(t){return t instanceof Error?t.message:String(t)}function $r(t){return/does not have any commits yet|bad default revision/i.test(Dt(t))}var xa=ne;async function va(t,e){try{let n=fn.join(t,e),r=await re.promises.stat(n);if(!r.isFile())return null;if(r.size>xa)return null;return(await re.promises.readFile(n,"utf-8")).split(`
20
+ `).filter((o)=>o.length>0).length}catch{return null}}var ka=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function Ra(t,e){return ka.has(`${t}${e}`)}function Tr(t,e){return e?"conflicted":_a(t)}function _a(t){switch(t){case"M":return"modified";case"A":return"added";case"D":return"deleted";case"?":return"untracked";case"R":return"renamed";case"C":return"copied";case"U":return"conflicted";default:return"modified"}}async function hn(t){let e=E(t);if(!await e.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let r=await e.status(),s=[],o=new Set,i=r.files.filter((d)=>d.working_dir==="?").map((d)=>d.path),a=await _t(t,i);for(let d of r.files){if(d.index==="!"||d.working_dir==="!"||a.has(d.path))continue;let p=`${d.path}-${d.index!==" "&&d.index!=="?"}`;if(o.has(p))continue;o.add(p);let y=Ra(d.index,d.working_dir);if(d.index&&d.index!==" "&&d.index!=="?"){let v=Tr(d.index,y);s.push({path:d.path,status:v,staged:!0,...d.from&&(v==="renamed"||v==="copied")?{originalPath:d.from}:{}})}if(d.working_dir&&d.working_dir!==" ")s.push({path:d.path,status:Tr(d.working_dir,y),staged:!1})}let c=(d)=>e.diff([...d,"--numstat","-z"]).catch((p)=>(k(`git diff ${d.join(" ")} --numstat failed in ${t}: ${Dt(p)}`),"")),[l,u]=await Promise.all([c(["--cached"]),c([])]),f=It(l),h=It(u);for(let d of s){let p=d.staged?f.get(d.path):h.get(d.path);if(p)d.insertions=p.additions,d.deletions=p.deletions}let g=s.filter((d)=>d.status==="untracked");if(g.length>0){let d=await Promise.all(g.map((p)=>va(t,p.path)));for(let p=0;p<g.length;p++){let y=d[p];if(y===null)continue;g[p].insertions=y,g[p].deletions=0}}return{files:s,branch:{current:r.current||"HEAD",tracking:r.tracking||void 0,ahead:r.ahead,behind:r.behind},isRepo:!0}}async function Or(t,e){await E(t).add(["--",e])}async function Nr(t,e){await E(t).reset(["HEAD","--",e])}async function Cr(t){await E(t).add("-A")}async function Lr(t){await E(t).reset(["HEAD"])}async function Hr(t,e){await E(t).checkout(["--",e])}async function Br(t,e){await E(t).clean("f",["--",e])}async function Wr(t,e,n=!1){if(!(await E(t,{longRunning:!0}).commit(e,void 0,n?{"--amend":null}:void 0)).commit)throw Error("Nothing to commit: no staged changes")}async function jr(t){let e=E(t);try{return(await e.log({n:1})).latest?.message||""}catch(n){if(!$r(n))k(`git log for the HEAD message failed in ${t}: ${Dt(n)}`);return""}}function Gr(t,e,n){Ea("git",["apply","--cached",...n?["--reverse"]:[],"--unidiff-zero"],{cwd:t,input:e,encoding:"utf-8",env:ut(),stdio:["pipe","pipe","pipe"]})}function Ur(t,e){Gr(t,e,!1)}function qr(t,e){Gr(t,e,!0)}async function Xr(t){let r=(await E(t,{longRunning:!0}).push()).pushed;if(r.length===0)return"Everything up-to-date";return r.map((s)=>`${s.local} → ${s.remote}`).join(", ")}async function zr(t){return await E(t,{longRunning:!0}).fetch(),"Fetch complete"}async function Jr(t){let n=await E(t,{longRunning:!0}).pull(["--rebase"]);if(n.summary.changes===0&&n.summary.insertions===0&&n.summary.deletions===0)return"Already up-to-date";return`${n.summary.changes} file(s) changed`}async function Yr(t,e=50){let n=E(t);try{return(await n.log({n:e})).all.map((s)=>({hash:s.hash,shortHash:s.hash.slice(0,7),message:s.message.split(`
21
+ `)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}))}catch(r){if(!$r(r))k(`git log failed in ${t}: ${Dt(r)}`);return[]}}async function Kr(t,e){let n=E(t);try{let s=(await n.log(["--no-walk",e])).all[0];if(!s)return null;return{hash:s.hash,shortHash:s.hash.slice(0,7),message:s.message.split(`
22
+ `)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}}catch{return null}}async function dn(t){let e=E(t);try{return(await e.stashList()).all.map((r,s)=>({index:s,message:r.message}))}catch(n){return k(`git stash list failed in ${t}, reporting no stashes: ${Dt(n)}`),[]}}async function Vr(t,e){let n=E(t),r=["push"];if(e)r.push("-m",e);return await n.stash(r),"Stashed"}async function Qr(t,e=0){let n=E(t);await n.stash(["pop",`stash@{${e}}`]);let r=(await n.raw(["diff","--name-only","--diff-filter=U"])).trim();if(r)throw Error(`Stash pop hit conflicts in: ${r.split(`
23
+ `).join(", ")}`);return"Stash popped"}async function Zr(t){let n=await E(t).branchLocal();return n.all.map((r)=>({name:r,current:r===n.current,tracking:n.branches[r]?.label||void 0}))}async function ts(t,e){return await E(t).raw(["switch","--",e]),`Switched to ${e}`}async function es(t,e){return await E(t).raw(["switch","-c",e]),`Created ${e}`}async function ns(t,e=1){return await E(t).reset(["--soft",`HEAD~${e}`]),"Reset done"}async function rs(t,e){return await E(t,{longRunning:!0}).raw(["cherry-pick","--end-of-options",e]),"Cherry-picked"}async function ss(t,e){return await E(t,{longRunning:!0}).raw(["revert","--no-edit","--end-of-options",e]),"Reverted"}async function Pt(t){let e=E(t),n;try{n=(await e.raw(["rev-parse","--absolute-git-dir"])).trim()}catch(s){return k(`git rev-parse --absolute-git-dir failed in ${t}: ${Dt(s)}`),null}let r=(s)=>re.existsSync(fn.join(n,s));if(r("rebase-merge")||r("rebase-apply"))return"rebase";if(r("CHERRY_PICK_HEAD"))return"cherry-pick";if(r("REVERT_HEAD"))return"revert";if(r("MERGE_HEAD"))return"merge";return null}async function os(t){let e=await Pt(t);if(!e)throw Error("No operation in progress to abort");return await E(t).raw([e,"--abort"]),`Aborted ${e}`}async function is(t){return await E(t,{longRunning:!0}).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function as(t){return(await E(t).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((r)=>r.length>0)}import*as mt from"node:fs";import*as Ft from"node:path";import*as xe from"node:fs";import*as se from"node:path";function pn(){return se.join(Rt(),"base-branches.json")}function cs(){let t=pn();try{return JSON.parse(xe.readFileSync(t,"utf-8"))}catch(e){if(e.code!=="ENOENT")k("Ignoring the base-branch cache",e,{file:t});return{}}}function Aa(t){ye(pn()),xe.writeFileSync(pn(),JSON.stringify(t,null,2)+`
24
+ `)}function Mt(t){let e=cs(),n=se.resolve(t);return e[n]}function ls(t,e){let n=cs(),r=se.resolve(t);n[r]=e,Aa(n)}function oe(t){let e=Math.min(t.length,8192);for(let n=0;n<e;n++)if(t[n]===0)return!0;return!1}var us={staged:!1,unstaged:!1,untracked:!1};class ae extends Error{constructor(t){super(`No common history with ${t}`);this.name="NoCommonHistoryError"}}var gt=3,hs=1e5;function mn(t){return t instanceof Error?t.message:String(t)}function ve(t,e,n){k(`${t} failed in ${e}, answering an empty diff: ${mn(n)}`)}async function Tt(t,e,n=!1,r={}){let s=E(t);try{let o=[`-U${r.context??gt}`];if(n)o.push("--cached");if(e)o.push("--",e);let i=nt(await s.diff(o));return{lines:rt(i)}}catch(o){let i=e===void 0?"":` -- ${e}`;return ve(`git diff${n?" --cached":""}${i}`,t,o),{lines:[]}}}var Ia="4b825dc642cb6eb9a060e54bf8d69288fbee4904",ds="(unborn)",Da=/unknown revision|ambiguous argument 'HEAD'|needed a single revision/i;async function ke(t){let e=E(t);try{return(await e.raw(["rev-parse","HEAD"])).trim()}catch(n){let r=n instanceof Error?n.message:String(n);if(Da.test(r))return ds;throw n}}async function ps(t,e){let n=E(t),s=(e??await ke(t))===ds?Ia:"HEAD",o=nt(await n.raw(["diff",`-U${gt}`,s,"--"]));return{lines:rt(o)}}var Pa=ne;function gn(t,e={}){let n=At(`a/${t}`),r=At(`b/${t}`),s=[{type:"header",content:`diff --git ${n} ${r}`},{type:"header",content:"new file mode 100644"}];if(e.binary)s.push({type:"header",content:`Binary files /dev/null and ${r} differ`});else s.push({type:"header",content:"--- /dev/null"}),s.push({type:"header",content:`+++ ${r}`});return s}function Ma(t,e){return{lines:[...gn(t),{type:"header",content:ln(e)}]}}function Fa(t){return{lines:gn(t,{binary:!0})}}function Ta(t,e){let n=Ft.resolve(t),r=Ft.resolve(n,e);if(r!==n&&!r.startsWith(n+Ft.sep))return null;let s,o;try{s=mt.realpathSync(r),o=mt.realpathSync(n)}catch{return null}if(s!==o&&!s.startsWith(o+Ft.sep))return null;let i=mt.statSync(s);if(!i.isFile())return null;return{path:r,size:i.size}}async function wt(t,e){try{let n=Ta(t,e);if(n===null)return{lines:[]};if(n.size>Pa)return Ma(e,n.size);let r=mt.readFileSync(n.path);if(oe(r))return Fa(e);let s=r.toString("utf-8"),o=gn(e),i=s.endsWith(`
25
+ `),a=s.split(`
26
+ `);if(i)a.pop();if(s.length>0){o.push({type:"hunk",content:`@@ -0,0 +1,${a.length} @@`});let u=1;for(let f of a)o.push({type:"addition",content:"+"+f,newLineNum:u++});if(!i)o.push({type:"context",content:"\"})}let c=dt(o),l=nt(c);if(l!==c)return{lines:rt(l)};return{lines:o}}catch(n){return ve(`reading untracked file ${e}`,t,n),{lines:[]}}}var fs="refs/remotes/";async function wn(t){let e=E(t),n=new Set,r=[];try{let s=await e.raw(["log","--oneline","--decorate=full","--all","-n","200"]),o=/\(([^)]+)\)/g;for(let i of s.split(`
27
+ `)){let a=o.exec(i);if(a)for(let c of a[1].split(",")){let l=c.trim().replace(/^.*-> /,"");if(!l.startsWith(fs))continue;let u=l.slice(fs.length);if(u.endsWith("/HEAD")||n.has(u))continue;n.add(u),r.push(u)}o.lastIndex=0}if(r.length>0)r.sort((i,a)=>{let c=i.split("/").slice(1).join("/"),l=a.split("/").slice(1).join("/"),u=c==="main"||c==="master",f=l==="main"||l==="master";if(u&&!f)return-1;if(!u&&f)return 1;if(u&&f){let h=i.startsWith("origin/"),g=a.startsWith("origin/");if(h&&!g)return 1;if(!h&&g)return-1}return 0})}catch(s){k(`git log for base-branch discovery failed in ${t}: ${mn(s)}`)}return r}async function ce(t){return(await wn(t))[0]??null}async function yn(t){return Mt(t)??await ce(t)}async function st(t,e){let n=E(t);try{return await n.raw(["cat-file","-e","--end-of-options",`${e}^{commit}`]),!0}catch{return!1}}function ms(t){let e=t.indexOf(`
28
+ `);return pt(e===-1?t:t.slice(0,e))}function gs(t,e,n){let r=It(t),s=new Map;for(let a of un(e)){let c;switch(a.code){case"A":c="added";break;case"D":c="deleted";break;case"R":c="renamed";break;default:c="modified"}s.set(a.path,c)}let o=[],i=n.split(/(?=^diff --git )/m).filter((a)=>a.trim());for(let a of i){let c=ms(a);if(c===null)continue;let l=rt(a),u=r.get(c)||{additions:0,deletions:0},f=s.get(c)||"modified";o.push({path:c,status:f,additions:u.additions,deletions:u.deletions,diff:{lines:l}})}return o.sort((a,c)=>a.path.localeCompare(c.path)),o}async function $a(t,e,n){let r=E(t);return ws(r,e,r.status(),n)}async function ws(t,e,n,r="HEAD"){let o=(await t.raw(["merge-base","--end-of-options",e,r])).trim();if(!o)throw new ae(e);let[i,a,c,{files:l},u]=await Promise.all([t.raw(["diff","--numstat","-z",`${o}...${r}`]),t.raw(["diff","--name-status","-z",`${o}...${r}`]),t.raw(["diff",`-U${gt}`,`${o}...${r}`]).then(nt),n,t.log({from:o,to:r})]),f=gs(i,a,c),h=0,g=0;for(let y of f)h+=y.additions,g+=y.deletions;let d=l.length,p=u.all.map((y)=>({hash:y.hash,shortHash:y.hash.slice(0,7),message:y.message.split(`
29
+ `)[0],author:y.author_name,date:new Date(y.date),refs:y.refs||""}));return{baseBranch:e,stats:{filesChanged:f.length,additions:h,deletions:g},files:f,commits:p,uncommittedCount:d}}async function ys(t,e,n="HEAD"){let r=E(t),o=(await r.raw(["merge-base","--end-of-options",e,n])).trim();if(!o)throw new ae(e);let i=await r.raw(["rev-list","--count","--end-of-options",`${o}..${n}`]);return Number.parseInt(i.trim(),10)}function ie(t,e){switch(t.kind){case"commit":return["show","--format=",...e,"--end-of-options",t.hash];case"compare":return["diff",...e,`${t.base}...${t.head??"HEAD"}`];case"head":return["diff",...e,"HEAD"];case"staged":return["diff","--cached",...e];case"unstaged":return["diff",...e]}}async function Oa(t,e,n){let r=E(t),s=ie(e,["--name-status","-z","-M","--diff-filter=R"]),o;try{o=await r.raw(s)}catch(i){return k(`rename lookup for ${n} failed in ${t}: ${mn(i)}`),null}return un(o).find((i)=>i.path===n)?.oldPath??null}async function bn(t,e,n,r={}){let s=E(t),o=r.context??gt;try{let i=await Oa(t,e,n),a=i===null?[n]:[i,n],c=ie(e,["-M",`-U${o}`]),l=nt(await s.raw([...c,"--",...a]));return{lines:rt(l)}}catch(i){return ve(`git ${ie(e,[]).join(" ")} -- ${n}`,t,i),{lines:[]}}}async function bs(t,e){let n=E(t),r=(a)=>n.raw(["show","--format=",...a,"--end-of-options",e]),[s,o,i]=await Promise.all([r(["--numstat","-z"]),r(["--name-status","-z"]),r([`-U${gt}`]).then(nt)]);return gs(s,o,i)}async function Ss(t,e){let n=E(t);try{let r=nt(await n.raw(["show","--format=",`-U${gt}`,"--end-of-options",e]));return{lines:rt(r)}}catch(r){return ve(`git show ${e}`,t,r),{lines:[]}}}function Na(t){if(t.staged&&t.unstaged)return"both";if(t.staged)return"staged";if(t.unstaged)return"unstaged";return null}function Ca(t){switch(t){case"both":return{kind:"head"};case"staged":return{kind:"staged"};case"unstaged":return{kind:"unstaged"}}}function La(t,e,n){let r=t==="staged"?[e]:t==="unstaged"?[n]:[e,n];if(r.includes("R"))return"renamed";if(r.includes("D"))return"deleted";if(r.includes("A")||r.includes("?"))return"added";return"modified"}async function Ha(t,e,n){let r=E(t),s=Ca(e),[o,i]=await Promise.all([r.raw(ie(s,["--numstat","-z"])).then(It),r.raw(ie(s,[`-U${gt}`])).then(nt)]),a=new Map(n.files.map((l)=>[l.path,l])),c=[];for(let l of i.split(/(?=^diff --git )/m)){if(!l.trim())continue;let u=ms(l);if(u===null)continue;let f=a.get(u);c.push({path:u,status:La(e,f?.index??"",f?.working_dir??""),...o.get(u)??{additions:0,deletions:0},diff:{lines:rt(l)},uncommitted:e})}return c}async function Ba(t,e){let n=e.files.filter((o)=>o.working_dir==="?").map((o)=>o.path),r=await _t(t,n),s=[];for(let o of n){if(r.has(o))continue;let i=await wt(t,o);if(i.lines.length===0)continue;s.push({path:o,status:"added",additions:i.lines.filter((a)=>a.type==="addition").length,deletions:0,diff:i,uncommitted:"untracked"})}return s}async function Es(t,e,n=us,r){let s=Na(n);if(s===null&&!n.untracked)return $a(t,e,r);if(r!==void 0)throw Error("Uncommitted work can only be compared against HEAD, not a named head");let o=E(t),i=o.status(),[a,c,l]=await Promise.all([ws(o,e,i),s===null?[]:i.then((d)=>Ha(t,s,d)),n.untracked?i.then((d)=>Ba(t,d)):[]]),u=[...c,...l],f=new Map;for(let d of u){let p=f.get(d.path);if(p)p.push(d);else f.set(d.path,[d])}let h=[];for(let d of a.files)h.push(d,...f.get(d.path)??[]),f.delete(d.path);for(let d of f.values())h.push(...d);h.sort((d,p)=>d.path.localeCompare(p.path));let g=new Set(h.map((d)=>d.path));return{baseBranch:a.baseBranch,stats:{filesChanged:g.size,additions:h.reduce((d,p)=>d+p.additions,0),deletions:h.reduce((d,p)=>d+p.deletions,0)},files:h,commits:a.commits,uncommittedCount:a.uncommittedCount}}import*as xs from"node:fs";import*as vs from"node:path";function Re(t){let e=5381;for(let n of t){for(let r=0;r<n.length;r++)e=(e<<5)+e+n.charCodeAt(r)|0;e=(e<<5)+e+10|0}return(e>>>0).toString(36)}function Wa(t){let e=[],n="",r=null,s=()=>{if(r&&n)e.push({file:n,key:`${n}\x00${Re(r.body)}`,headerLine:r.headerLine});r=null};for(let o of t.lines)if(o.type==="header"){if(s(),o.content.startsWith("diff --git"))n=pt(o.content)??""}else if(o.type==="hunk")s(),r={headerLine:o,body:[]};else if(r&&(o.type==="addition"||o.type==="deletion"))r.body.push(o.content);return s(),e}class Sn{repoPath;stamps=new Map;constructor(t){this.repoPath=t}stamp(t){if(!t)return;let e=new Map;for(let n of Wa(t)){let r=this.stamps.get(n.key);if(r===void 0){let s=e.get(n.file);if(s===void 0)s=this.mtimeOf(n.file),e.set(n.file,s);r=s,this.stamps.set(n.key,r)}n.headerLine.editedAt=r}}prune(t){for(let e of this.stamps.keys()){let n=e.slice(0,e.indexOf("\x00"));if(!t.has(n))this.stamps.delete(e)}}mtimeOf(t){try{return xs.statSync(vs.join(this.repoPath,t)).mtimeMs}catch{return Date.now()}}}import*as K from"node:fs";import*as N from"node:path";async function ja(t){let e=xn(t);if(!e)return null;try{let n=E(e);if((await n.raw(["rev-parse","--is-bare-repository"])).trim()==="true")return null;return(await n.raw(["rev-parse","--show-toplevel"])).trim()||null}catch(n){return L("rev-parse failed",n,{dir:e}),null}}async function _e(t,{mustExist:e}){let n=J(t);if(!N.isAbsolute(n))return{ok:!1,reason:"not-absolute",requested:n};if(e&&!Ga(n))return{ok:!1,reason:"not-a-repo",requested:n};let r=await ja(n);if(r)return{ok:!0,root:r};let s=za(await Ua(n));return s?{ok:!0,root:s.path}:{ok:!1,reason:"not-a-repo",requested:n}}function Ga(t){try{return K.statSync(t).isDirectory()}catch{return!1}}async function Ua(t){let e=xn(t);if(!e)return[];try{let n=E(e);return As(await n.raw(["worktree","list","--porcelain"]))}catch(n){return L("worktree list failed",n,{dir:e}),[]}}async function En(t){let e=xn(t);if(!e)return[];try{let r=await E(e).raw(["worktree","list","--porcelain"]),s=As(r),o=await Xa(s,e);return s.map((i)=>({...i,lastActivity:i.isBare?null:qa(ks(i.path)),aheadOfBase:o.get(i.path)??null}))}catch(n){return L("worktree list failed",n,{dir:e}),[]}}function qa(t){return Number.isFinite(t)?t:null}async function Xa(t,e){let n=t.filter((o)=>!o.isBare);if(n.length===0)return new Map;let r=await ce(e).catch(()=>null),s=await Promise.all(n.map(async(o)=>{let i=Mt(o.path)??r;if(!i)return null;try{let c=await E(o.path).raw(["rev-list","--count","--end-of-options",`${i}..HEAD`]);return[o.path,parseInt(c.trim(),10)]}catch{return null}}));return new Map(s.filter((o)=>o!==null))}function za(t){let e=null,n=-1/0;for(let r of t){if(r.isBare)continue;let s=ks(r.path);if(s>n)n=s,e=r}return e}function ks(t){let e=Rs(t),n=e?[N.join(e,"index"),N.join(e,"HEAD")]:[t],r=-1/0;for(let s of n)try{let o=K.statSync(s).mtimeMs;if(o>r)r=o}catch{}return r}function Rs(t){let e=N.join(t,".git");try{if(K.statSync(e).isDirectory())return e;let n=K.readFileSync(e,"utf8").match(/^gitdir:\s*(.+)$/m);if(!n)return null;let r=n[1].trim();return N.isAbsolute(r)?r:N.resolve(t,r)}catch{return null}}function _s(t){let e=Rs(t);if(e===null)return null;let n=e;try{let r=K.readFileSync(N.join(e,"commondir"),"utf8").trim();if(r)n=N.isAbsolute(r)?r:N.resolve(e,r)}catch{}return{gitDir:e,commonDir:n}}function As(t){let e=[],n=null;for(let r of t.split(`
30
+ `))if(r.startsWith("worktree ")){if(n)e.push(n);n={path:r.slice(9).trim(),branch:null,head:null,isBare:!1,isMain:e.length===0}}else if(!n)continue;else if(r.startsWith("HEAD "))n.head=r.slice(5).trim();else if(r.startsWith("branch "))n.branch=r.slice(7).trim().replace(/^refs\/heads\//,"");else if(r==="bare")n.isBare=!0;if(n)e.push(n);return e}function xn(t){try{if(K.statSync(t).isDirectory())return t;return N.dirname(t)}catch{let e=N.dirname(t);return e!==t&&K.existsSync(e)?e:null}}var rc=Ni(Ls(),1);function Hs(t){return pt(t)}function De(t){let e=new Map,n=null;for(let s of t.lines){if(s.type==="header"&&s.content.startsWith("diff --git")){let o=Hs(s.content);if(o!==null)n=e.get(o)??[],e.set(o,n);else n=null}n?.push(s)}let r=new Map;for(let[s,o]of e)r.set(s,{lines:o});return r}var Pe="diffstalker-journal: oversize untracked snapshot omitted";var ic=262144,ac=new Set(["EACCES","EPERM","ENOENT"]);function cc(t){let e=t?.code;return typeof e==="string"&&ac.has(e)}function lc(){return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1}}class Me extends oc{repoPath;queue;hunkTimes;gitWatcher=null;workingDirWatcher=null;ignorers=new Map;_state={status:null,isLoading:!1,error:null,hunkCounts:null,stashList:[],operationInProgress:null,mtimes:null};constructor(t,e){super();this.repoPath=t,this.queue=e,this.hunkTimes=new Sn(t)}get state(){return this._state}get unavailable(){return this._state.status?.isRepo===!1?this.unavailableReason:null}unavailableReason=null;updateState(t){this._state={...this._state,...t},this.emit("state-change",this._state)}setError(t){this.updateState({error:t})}clearError(){if(this._state.error!==null)this.updateState({error:null})}stampDiff(t){this.hunkTimes.stamp(t)}loadGitignores(){let t=new Map,e=Ws();e.add(".git");let n=T.join(this.repoPath,".gitignore");if(G.existsSync(n))e.add(G.readFileSync(n,"utf-8"));let r=T.join(this.repoPath,".git","info","exclude");if(G.existsSync(r))e.add(G.readFileSync(r,"utf-8"));t.set("",e);try{let s=sc("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:ut(),stdio:["ignore","pipe","pipe"]});for(let o of s.split("\x00")){if(!o||o===".gitignore")continue;if(!o.endsWith(".gitignore"))continue;let i=T.dirname(o),a=T.join(this.repoPath,o);try{let c=G.readFileSync(a,"utf-8"),l=Ws();l.add(c),t.set(i,l)}catch(c){k(`Failed to read ${a}`,c,{repo:this.repoPath})}}}catch(s){k("git ls-files failed; nested .gitignore files are not applied",s,{repo:this.repoPath})}return t}startWatching(){let t=_s(this.repoPath);if(t===null)return;let e=T.join(t.gitDir,"index"),n=T.join(t.gitDir,"HEAD"),r=T.join(t.commonDir,"refs"),s=T.join(t.commonDir,"packed-refs"),o=T.join(this.repoPath,".gitignore");this.gitWatcher=Bs([e,n,r,s,o],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=Bs(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(a)=>{let c=T.relative(this.repoPath,a);if(!c)return!1;let l=c.split("/");for(let u=0;u<l.length;u++){let f=u===0?"":l.slice(0,u).join("/"),h=this.ignorers.get(f);if(h){let g=u===0?c:l.slice(u).join("/");if(h.ignores(g))return!0}}return!1},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let i=()=>this.scheduleRefresh();this.gitWatcher.on("change",(a)=>{if(a===o)this.ignorers=this.loadGitignores();i()}),this.gitWatcher.on("add",i),this.gitWatcher.on("unlink",i),this.gitWatcher.on("error",(a)=>{this.logWatchError("Git dir watcher error",a),this.setError(`Git watcher error: ${a instanceof Error?a.message:String(a)}`)}),this.workingDirWatcher.on("change",i),this.workingDirWatcher.on("add",i),this.workingDirWatcher.on("unlink",i),this.workingDirWatcher.on("error",(a)=>{this.logWatchError("Working dir watcher error",a),this.setError(`Working dir watcher error: ${a instanceof Error?a.message:String(a)}`)})}logWatchError(t,e){if(cc(e))L(t,e,{repo:this.repoPath});else k(t,e,{repo:this.repoPath})}dispose(){let t=(e)=>(n)=>k(`Failed to close the ${e} watcher`,n,{repo:this.repoPath});this.gitWatcher?.close().catch(t("git dir")),this.workingDirWatcher?.close().catch(t("working dir"))}statMtimes(t){let e=new Map;for(let n of t.files){if(e.has(n.path))continue;try{e.set(n.path,G.statSync(T.join(this.repoPath,n.path)).mtimeMs)}catch{}}return e}pendingRefreshKind=null;scheduleRefresh(){this.requestRefresh("full")}scheduleStatusRefresh(){this.requestRefresh("status")}requestRefresh(t){if(this.pendingRefreshKind!==null){if(t==="full")this.pendingRefreshKind="full";return}if(this.queue.hasPendingMutations())return;this.pendingRefreshKind=t,this.queue.scheduleRefresh(async()=>{let e=this.pendingRefreshKind??"full";if(this.pendingRefreshKind=null,e==="full")await this.doRefresh();else await this.doStatusRefresh()})}notARepo(t,e){if(this._state.status?.isRepo!==!1)k(`${e} (was open as one)`,void 0,{repo:this.repoPath});this.unavailableReason=e,this.updateState({status:t,isLoading:!1,error:e})}refreshFailed(t,e){if(!G.existsSync(this.repoPath)){this.notARepo(lc(),"Repository directory no longer exists");return}k(t,e,{repo:this.repoPath}),this.updateState({isLoading:!1,error:e instanceof Error?e.message:"Unknown error"})}async doStatusRefresh(){try{let t=await hn(this.repoPath);if(!t.isRepo){this.notARepo(t,"Not a git repository");return}this.updateState({status:t,mtimes:this.statMtimes(t),isLoading:!1})}catch(t){this.refreshFailed("Status refresh failed",t)}}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.updateState({isLoading:!0,error:null});let t=Date.now(),e=await ke(this.repoPath).catch((n)=>(L("HEAD oid unreadable; journal observation skipped",n,{repo:this.repoPath}),null));try{let n=await hn(this.repoPath);if(!n.isRepo){this.notARepo(n,"Not a git repository");return}let r=this.snapshotJournalGuard(n),[s,o,{stashList:i,operation:a},c]=await Promise.all([Tt(this.repoPath,void 0,!1),Tt(this.repoPath,void 0,!0),r,this.gatherJournalInputs(n,e,t,r)]),l={unstaged:Ee(dt(s.lines)),staged:Ee(dt(o.lines))};this.hunkTimes.stamp(s),this.hunkTimes.stamp(o),this.hunkTimes.prune(new Set(n.files.map((f)=>f.path)));let u=this.statMtimes(n);if(this.updateState({status:n,hunkCounts:l,stashList:i,operationInProgress:a,mtimes:u,isLoading:!1}),c!==null)this.emit("journal-observation",{status:n,headDiff:c.headDiff,headOid:c.headOid,stashCount:c.stashCount,operationInProgress:c.operationInProgress,mtimes:c.mtimes,at:Date.now()})}catch(n){this.refreshFailed("Refresh failed",n)}}async snapshotJournalGuard(t){let[e,n]=await Promise.all([Pt(this.repoPath),dn(this.repoPath)]);return{operation:e,stashList:n,mtimes:this.statMtimes(t)}}static journalGuardMoved(t,e){if(t.operation!==e.operation||t.stashList.length!==e.stashList.length)return!0;if(t.mtimes.size!==e.mtimes.size)return!0;for(let[n,r]of t.mtimes)if(e.mtimes.get(n)!==r)return!0;return!1}sectionWrittenDuringGather(t,e,n){let r=new Set(e);for(let s of t.files)if(s.status==="untracked")r.add(s.path);for(let s of r)try{let o=G.statSync(T.join(this.repoPath,s));if(Math.floor(o.mtimeMs)>n)return!0}catch{}return!1}async gatherJournalInputs(t,e,n,r){if(e===null)return null;try{let s=await r,o=await ps(this.repoPath,e),i=new Set(De(o).keys()),a=[...o.lines];await this.appendUntrackedSections(t,i,a);let c=await ke(this.repoPath);if(e!==c)return null;let l=await this.snapshotJournalGuard(t);if(Me.journalGuardMoved(s,l))return null;if(this.sectionWrittenDuringGather(t,i,n))return null;return{headDiff:{lines:a},headOid:c,stashCount:l.stashList.length,operationInProgress:l.operation,mtimes:l.mtimes}}catch(s){return L("Journal observation skipped: git read failed",s,{repo:this.repoPath}),null}}async appendUntrackedSections(t,e,n){let r=new Set;for(let s of t.files){if(s.status!=="untracked"||r.has(s.path)||e.has(s.path))continue;r.add(s.path);let o;try{o=G.statSync(T.join(this.repoPath,s.path))}catch{continue}if(!o.isFile())continue;if(o.size>ic){this.appendOversizeSection(s.path,o,n);continue}let i=await wt(this.repoPath,s.path);if(i.lines.length===0)continue;n.push(...i.lines)}}appendOversizeSection(t,e,n){let r=[`diff --git ${At("a/"+t)} ${At("b/"+t)}`,"new file mode 100644",`${Pe} size=${e.size} mtime=${Math.round(e.mtimeMs)}`];n.push(...r.map((s)=>({type:"header",content:s})))}failed(t,e,n){k(`Failed to ${t}`,e,{repo:this.repoPath,file:n}),this.updateState({error:`Failed to ${t}: ${e instanceof Error?e.message:String(e)}`})}async stage(t){try{await this.queue.enqueueMutation(()=>Or(this.repoPath,t.path)),this.scheduleStatusRefresh()}catch(e){await this.refresh(),this.failed(`stage ${t.path}`,e,t.path)}}async unstage(t){try{await this.queue.enqueueMutation(()=>Nr(this.repoPath,t.path)),this.scheduleStatusRefresh()}catch(e){await this.refresh(),this.failed(`unstage ${t.path}`,e,t.path)}}async stageHunk(t){try{await this.queue.enqueueMutation(async()=>Ur(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.failed("stage hunk",e)}}async unstageHunk(t){try{await this.queue.enqueueMutation(async()=>qr(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.failed("unstage hunk",e)}}async discard(t){if(t.staged)return;let e=t.status==="untracked"?()=>Br(this.repoPath,t.path):()=>Hr(this.repoPath,t.path);try{await this.queue.enqueueMutation(e),await this.refresh()}catch(n){this.failed(`discard ${t.path}`,n,t.path)}}async stageAll(){try{await this.queue.enqueueMutation(()=>Cr(this.repoPath)),await this.refresh()}catch(t){this.failed("stage all",t)}}async unstageAll(){try{await this.queue.enqueueMutation(()=>Lr(this.repoPath)),await this.refresh()}catch(t){this.failed("unstage all",t)}}async commit(t,e=!1){try{await this.queue.enqueue(()=>Wr(this.repoPath,t,e)),await this.refresh()}catch(n){this.failed("commit",n)}}async loadStashList(){try{let t=await this.queue.enqueue(()=>dn(this.repoPath));this.updateState({stashList:t})}catch(t){k("Failed to load the stash list",t,{repo:this.repoPath})}}}import{EventEmitter as uc}from"node:events";class _n extends uc{repoPath;queue;callbacks;_remoteState={operation:null,inProgress:!1,error:null,lastResult:null};constructor(t,e,n){super();this.repoPath=t,this.queue=e,this.callbacks=n}get remoteState(){return this._remoteState}updateRemoteState(t){this._remoteState={...this._remoteState,...t},this.emit("remote-state-change",this._remoteState)}async runRemoteOperation(t,e){this.updateRemoteState({operation:t,inProgress:!0,error:null,lastResult:null});try{let n=await this.queue.enqueue(e);this.updateRemoteState({inProgress:!1,lastResult:n}),this.callbacks.scheduleRefresh()}catch(n){k(`git ${t} failed`,n,{repo:this.repoPath});let r=n instanceof Error?n.message:String(n);this.updateRemoteState({inProgress:!1,error:r})}return this._remoteState}async push(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("push",()=>Xr(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>zr(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>Jr(this.repoPath))}async stash(t){if(this._remoteState.inProgress)return null;let e=await this.runRemoteOperation("stash",()=>Vr(this.repoPath,t));return await this.callbacks.loadStashList(),e}async stashPop(t=0){if(this._remoteState.inProgress)return null;let e=await this.runRemoteOperation("stashPop",()=>Qr(this.repoPath,t));return await this.callbacks.loadStashList(),e}async switchBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>ts(this.repoPath,t))}async createBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>es(this.repoPath,t))}async softReset(t=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>ns(this.repoPath,t))}async cherryPick(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>rs(this.repoPath,t))}async revertCommit(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>ss(this.repoPath,t))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>os(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>is(this.repoPath))}}import{EventEmitter as fc}from"node:events";import{randomBytes as hc}from"node:crypto";var dc=262144,pc=500,mc=16777216,Us=Number.MAX_SAFE_INTEGER,gc=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function wc(t){let e=gc.exec(t);if(!e)return null;return{oldStart:parseInt(e[1],10),oldCount:e[2]!==void 0?parseInt(e[2],10):1}}function yc(t,e){let n=wc(e);if(!n)return[];let r=n.oldCount===0?n.oldStart+1:n.oldStart,s=[],o=null;for(let i of t){let a=i.content[0];if(a==="\\")continue;if(a==="-")o=bc(o,r),r++;else if(a==="+")o=o??{hasDel:!1,delStart:0,delEnd:0,anchor:r-1};else js(s,o),o=null,r++}return js(s,o),s}function bc(t,e){if(!t)return{hasDel:!0,delStart:e,delEnd:e,anchor:e-1};if(!t.hasDel)t.hasDel=!0,t.delStart=e;return t.delEnd=e,t}function js(t,e){if(!e)return;t.push(e.hasDel?[2*e.delStart,2*e.delEnd]:[2*e.anchor,2*e.anchor+2])}function An(t){if(t.length===0)return{start:0,count:0};let e=1/0,n=-1/0;for(let[o,i]of t){if(o<e)e=o;if(i>n)n=i}if(n>=Us)return{start:0,count:0};let r=Math.ceil(e/2),s=Math.floor(n/2);return{start:r,count:s-r+1}}function Sc(t){let e=[],n=null,r=[],s=null;for(let i of t.lines)if(i.type==="hunk")s={header:i,body:[]},r.push(s);else if(s)s.body.push(i);else if(e.push(i),i.content.startsWith("rename from "))n=i.content.slice(12);if(r.length===0){let i=e.some((a)=>a.content.startsWith(Pe));return{hunks:[{runs:[[0,Us]],bodyHash:Re([dt(t.lines)]),ins:0,del:0,span:{start:0,count:0},diff:t,oversize:i}],renamedFrom:n,hunkless:!0}}return{hunks:r.map(({header:i,body:a})=>{let c=yc(a,i.content),l=[],u=0,f=0;for(let g of a){let d=g.content[0];if(d==="\\")continue;if(d==="+")u++,l.push(g.content);else if(d==="-")f++,l.push(g.content)}let h=[...e,i,...a];return{runs:c,bodyHash:Re(l),ins:u,del:f,span:An(c),diff:{lines:h}}}),renamedFrom:n,hunkless:!1}}function Ec(t){if(t.oversize===!0)return null;return Se(t.diff.lines)>dc?null:t.diff}function xc(t,e,n){if(t===0&&e>0)return"shrunk";let r=t+e;if(r>n)return"expanded";if(r<n)return"shrunk";return"edited"}function Gs(t,e){let n=[];return t.forEach((r,s)=>{for(let[o,i]of r.runs)n.push({lo:o,hi:i,node:e+s})}),n.sort((r,s)=>r.lo-s.lo),n}function vc(t,e){let n=Array.from({length:t.length+e.length},(c,l)=>l),r=(c)=>{while(n[c]!==c)n[c]=n[n[c]],c=n[c];return c},s=(c,l)=>{let u=r(c),f=r(l);if(u!==f)n[u]=f},o=Gs(t,0),i=Gs(e,t.length),a=0;for(let c of o){while(a<i.length&&i[a].hi<c.lo)a++;for(let l=a;l<i.length&&i[l].lo<=c.hi;l++)s(c.node,i[l].node)}return n.map((c,l)=>r(l))}function kc(t,e){let n=vc(t,e),r=new Map,s=(o)=>{let i=r.get(o);if(!i)i={prevIdx:[],nextIdx:[],minLo:1/0},r.set(o,i);return i};return t.forEach((o,i)=>{let a=s(n[i]);a.prevIdx.push(i);for(let[c]of o.runs)if(c<a.minLo)a.minLo=c}),e.forEach((o,i)=>{let a=s(n[t.length+i]);a.nextIdx.push(i);for(let[c]of o.runs)if(c<a.minLo)a.minLo=c}),[...r.values()].sort((o,i)=>o.minLo-i.minLo)}function Rc(t,e,n){let r=[],s=e.map(()=>null),o=n;for(let i of kc(t,e)){let a=i.prevIdx.map((f)=>t[f]),c=i.nextIdx.map((f)=>e[f]);if(a.length===1&&c.length===1&&a[0].bodyHash===c[0].bodyHash){let f=c[0];s[i.nextIdx[0]]={seq:a[0].seq,runs:f.runs,bodyHash:f.bodyHash,ins:f.ins,del:f.del};continue}if(c.length===0){for(let f of a)r.push({seq:o++,kind:"reverted",span:An(f.runs),stats:{insertions:0,deletions:0},diff:null,supersedes:[f.seq],siblings:1});continue}let l=a.map((f)=>f.seq),u=a.reduce((f,h)=>f+h.ins+h.del,0);for(let f of i.nextIdx){let h=e[f],g={seq:o++,kind:a.length===0?"created":xc(h.ins,h.del,u),span:h.span,stats:{insertions:h.ins,deletions:h.del},diff:Ec(h),supersedes:[...l],siblings:c.length};r.push(g),s[f]={seq:g.seq,runs:h.runs,bodyHash:h.bodyHash,ins:h.ins,del:h.del}}}return{entries:r,nextLive:s.filter((i)=>i!==null)}}function _c(t,e){let n=Array(t.length).fill(!1),r=Array(e.length).fill(null);for(let a=0;a<e.length;a++){let c=t.findIndex((l,u)=>!n[u]&&l.bodyHash===e[a].bodyHash);if(c!==-1)n[c]=!0,r[a]=t[c].seq}for(let a=0;a<e.length;a++){if(r[a]!==null)continue;let c=n.findIndex((l)=>!l);if(c!==-1)n[c]=!0,r[a]=t[c].seq}let s=t[t.length-1].seq,o=e.map((a,c)=>({seq:r[c]??s,runs:a.runs,bodyHash:a.bodyHash,ins:a.ins,del:a.del})),i=t.filter((a,c)=>!n[c]).map((a)=>a.seq);return{carried:o,retired:i}}function Fe(){return{entries:[],epoch:`${Date.now().toString(36)}-${hc(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class In extends fc{store;constructor(t){super();this.store=t}get journalStore(){return this.store}observe(t){try{this.doObserve(t)}catch(e){F("Journal observation skipped: classifier threw",e)}}doObserve(t){let e=[];if(this.store.lastHeadOid===null){if(t.operationInProgress===null)this.seed(t,e)}else if(this.handleOperations(t,e));else if(t.headOid!==this.store.lastHeadOid)this.rebaseline(t,e);else this.classify(t,e);if(e.length>0)this.store.entries.push(...e),this.emit("append",e),this.pruneStore()}pruneStore(){let t=new Set;for(let e of this.store.live.values())for(let n of e)t.add(n.seq);this.pruneBodies(t),this.pruneEntries(t)}pruneBodies(t){let e=0;for(let n of this.store.entries)if(n.type==="hunk"&&n.diff!==null)e+=Se(n.diff.lines);for(let n of this.store.entries){if(e<=mc)return;if(n.type!=="hunk"||n.diff===null||t.has(n.seq))continue;e-=Se(n.diff.lines),n.diff=null}}pruneEntries(t){let e=this.store.entries,n=0;while(e.length-n>pc&&(e[n].type==="boundary"||!t.has(e[n].seq)))n++;if(n>0)e.splice(0,n)}handleOperations(t,e){let n=this.store.lastOperation;if(t.operationInProgress!==null){if(n===null)e.push(this.boundary("op-start",t.operationInProgress,[],t.at)),this.store.lastOperation=t.operationInProgress;return!0}if(n!==null)e.push(this.boundary("op-end",n,[],t.at)),this.store.lastOperation=null;return!1}seed(t,e){e.push(this.boundary("journal-start",t.status.branch.current,[],t.at));let{files:n}=this.parseObservation(t),r=[...n.keys()].sort((s,o)=>this.tsFor(t,s)-this.tsFor(t,o));for(let s of r)this.classifyPath(s,[],n.get(s).hunks,t,!0,e);this.store.lastHeadOid=t.headOid,this.store.lastBranch=t.status.branch.current,this.store.lastStashCount=t.stashCount,this.store.lastOperation=null}rebaseline(t,e){let{files:n,deferred:r}=this.parseObservation(t),s=t.status.branch.current===this.store.lastBranch,o=s?"commit":"checkout",i=s?t.headOid.slice(0,7):t.status.branch.current,{resolves:a,newLive:c}=this.carrySurvivors(n,r);e.push(this.boundary(o,i,a,t.at)),this.store.live=c;for(let[l,{hunks:u}]of n){if(c.has(l))continue;this.classifyPath(l,[],u,t,!1,e)}this.store.lastHeadOid=t.headOid,this.store.lastBranch=t.status.branch.current,this.store.lastStashCount=t.stashCount}carrySurvivors(t,e){let n=[],r=new Map;for(let[s,o]of this.store.live){if(e.has(s)){r.set(s,o);continue}let i=t.get(s);if(!i){n.push(...o.map((l)=>l.seq));continue}let{carried:a,retired:c}=_c(o,i.hunks);n.push(...c),r.set(s,a)}return{resolves:n,newLive:r}}classify(t,e){let{files:n,deferred:r}=this.parseObservation(t);this.handleRenames(t,n,e),this.handleDisappearances(t,n,r,e);for(let[s,{hunks:o,renamedFrom:i,hunkless:a}]of n){let c=this.store.live.get(s)??[];if(a&&i!==null&&c.length>0)continue;this.classifyPath(s,c,o,t,!1,e)}this.store.lastBranch=t.status.branch.current,this.store.lastStashCount=t.stashCount}handleRenames(t,e,n){for(let[r,s]of e){let o=s.renamedFrom;if(o===null||o===r)continue;if(!this.store.live.has(o)||e.has(o))continue;let i=(this.store.live.get(r)??[]).map((a)=>a.seq);this.store.live.set(r,this.store.live.get(o)),this.store.live.delete(o),n.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor(t,r),path:r,status:"renamed",kind:"renamed",span:{start:0,count:0},stats:{insertions:0,deletions:0},diff:null,supersedes:i,siblings:1,seeded:!1})}}handleDisappearances(t,e,n,r){let s=[...this.store.live.keys()].filter((o)=>!e.has(o)&&!n.has(o));if(s.length===0)return;if(t.stashCount>this.store.lastStashCount){let o=s.flatMap((i)=>this.store.live.get(i).map((a)=>a.seq));r.push(this.boundary("stash","stash",o,t.at));for(let i of s)this.store.live.delete(i);return}for(let o of s){let i=this.store.live.get(o);r.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor(t,o),path:o,status:this.statusOf(t,o),kind:"reverted",span:An(i.flatMap((a)=>a.runs)),stats:{insertions:0,deletions:0},diff:null,supersedes:i.map((a)=>a.seq),siblings:1,seeded:!1}),this.store.live.delete(o)}}classifyPath(t,e,n,r,s,o){let{entries:i,nextLive:a}=Rc(e,n,this.store.nextSeq);this.store.nextSeq+=i.length;let c=this.tsFor(r,t),l=this.statusOf(r,t);for(let u of i){let f={type:"hunk",seq:u.seq,ts:c,path:t,status:l,kind:u.kind==="created"&&l==="renamed"?"renamed":u.kind,span:u.span,stats:u.stats,diff:u.diff,supersedes:u.supersedes,siblings:u.siblings,seeded:s};o.push(f)}if(a.length>0)this.store.live.set(t,a);else this.store.live.delete(t)}parseObservation(t){let e=new Map;for(let[r,s]of De(t.headDiff))e.set(r,Sc(s));let n=new Set;for(let r of t.status.files)if(r.status==="untracked"&&!e.has(r.path))n.add(r.path);return{files:e,deferred:n}}boundary(t,e,n,r){return{type:"boundary",seq:this.store.nextSeq++,ts:r,kind:t,label:e,resolves:n}}tsFor(t,e){let n=t.mtimes?.get(e);return n===void 0?t.at:Math.min(n,t.at)}statusOf(t,e){return t.status.files.find((n)=>n.path===e)?.status??"modified"}}class Dn{workingTree;remote;journal;repoPath;constructor(t,e){this.repoPath=t;let n=kr(t);this.workingTree=new Me(t,n),this.remote=new _n(t,n,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new In(e??Fe()),this.workingTree.on("journal-observation",(r)=>this.journal.observe(r))}dispose(){this.workingTree.dispose(),Rr(this.repoPath)}}function Ic(t){return Ac("sha256").update(t).digest("hex").slice(0,12)}var Dc=32;class qs{cap;stores=new Map;constructor(t=Dc){this.cap=t}acquire(t){let e=this.stores.get(t);if(e)this.stores.delete(t);else e=Fe();return this.stores.set(t,e),e}prune(t){if(this.stores.size<=this.cap)return;for(let e of this.stores.keys()){if(this.stores.size<=this.cap)return;if(t(e))continue;this.stores.delete(e)}}has(t){return this.stores.has(t)}get size(){return this.stores.size}}class Te extends Error{reason;requested;constructor(t,e){super(t==="not-absolute"?`Repo path must be absolute: ${e}`:`Not a git repository: ${e}`);this.reason=t,this.requested=e,this.name="RepoOpenRefused"}}class Pn{events;byId=new Map;byPath=new Map;journalStores=new qs;constructor(t={}){this.events=t}async openRepo(t){let e=await _e(t,{mustExist:!1});if(!e.ok)throw new Te(e.reason,e.requested);let n=e.root,r=this.byPath.get(n);if(r)return r.refCount++,{handle:r,created:!1};let s=Ic(n),o=new Dn(n,this.journalStores.acquire(s));o.workingTree.startWatching();let i={id:s,path:n,manager:o,refCount:1};return this.byId.set(i.id,i),this.byPath.set(n,i),this.journalStores.prune((a)=>this.byId.has(a)),this.events.onOpened?.(i),{handle:i,created:!0}}getRepo(t){return this.byId.get(t)}listRepos(){return[...this.byId.values()]}closeRepo(t){let e=this.byId.get(t);if(!e)return!1;if(e.refCount--,e.refCount>0)return!1;return this.byId.delete(e.id),this.byPath.delete(e.path),e.manager.dispose(),this.events.onClosed?.(e.id),!0}disposeAll(){for(let t of this.byId.values())t.manager.dispose();this.byId.clear(),this.byPath.clear()}}function Mn(t){t.manager.workingTree.refresh().catch((e)=>{F("First refresh threw",e,{repo:t.path})})}async function $e(t,e){let n=await t.openRepo(e);if(n.created)Mn(n.handle);return n}var zs=25000;function $t(t,e,n){t.write(`event: ${e}
31
+ data: ${n}
34
32
 
35
- `)}function M4($){$.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function j4($,Z){w$($,"repo-missing",JSON.stringify({id:Z}))}class W6{channels=new Map;subscribe($,Z,K,V){M4(V),this.join($,Z,K,V,{owned:!0})}attach($,Z,K,V){if(!Z){j4(V,$);return}this.join($,Z,K,V,{owned:!1})}join($,Z,K,V,Q){let Y=this.channels.get($);if(!Y){let J=new Map,W={manager:Z,subscribers:J,listener:(z)=>{let U=JSON.stringify(Y$(z));if(U===W.lastData)return;W.lastData=U;for(let j of J.keys())w$(j,"state-change",U)},journalListener:(z)=>{let U=JSON.stringify({epoch:Z.journal.journalStore.epoch,entries:uZ(z)});for(let j of J.keys())w$(j,"journal-append",U)},keepAlive:setInterval(()=>{for(let[z,{owned:U}]of J)if(U)z.write(`: ping
33
+ `)}function Js(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Xs(t,e){$t(t,"repo-missing",JSON.stringify({id:e}))}class Fn{channels=new Map;subscribe(t,e,n,r){Js(r),this.join(t,e,n,r,{owned:!0})}attach(t,e,n,r){if(!e){Xs(r,t);return}this.join(t,e,n,r,{owned:!1})}join(t,e,n,r,s){let o=this.channels.get(t);if(!o){let a=new Map,c={manager:e,subscribers:a,listener:(l)=>{let u=JSON.stringify(lt(l));if(u===c.lastData)return;c.lastData=u;for(let f of a.keys())$t(f,"state-change",u)},journalListener:(l)=>{let u=JSON.stringify({epoch:e.journal.journalStore.epoch,entries:l});for(let f of a.keys())$t(f,"journal-append",u)},keepAlive:setInterval(()=>{for(let[l,{owned:u}]of a)if(u)l.write(`: ping
36
34
 
37
- `)},G4),lastData:null};Z.workingTree.on("state-change",W.listener),Z.journal.on("append",W.journalListener),W.keepAlive.unref(),Y=W,this.channels.set($,Y)}Y.subscribers.set(V,Q),K.on("close",()=>this.unsubscribe($,V));let X=JSON.stringify(Y$(Z.workingTree.state));w$(V,Q.owned?"snapshot":"repo-snapshot",X)}unsubscribe($,Z){let K=this.channels.get($);if(!K)return;if(K.subscribers.delete(Z),K.subscribers.size===0)this.teardown($,K)}teardown($,Z){Z.manager.workingTree.off("state-change",Z.listener),Z.manager.journal.off("append",Z.journalListener),clearInterval(Z.keepAlive);for(let[K,{owned:V}]of Z.subscribers)if(V)K.end();else j4(K,$);Z.subscribers.clear(),this.channels.delete($)}closeRepo($){let Z=this.channels.get($);if(Z)this.teardown($,Z)}destroy(){for(let[$,Z]of this.channels)this.teardown($,Z)}}class z6{subscribers=new Set;keepAlive=null;subscribe($,Z,K){if(M4(Z),this.subscribers.add(Z),!this.keepAlive)this.keepAlive=setInterval(()=>{for(let V of this.subscribers)V.write(`: ping
35
+ `)},zs),lastData:null};e.workingTree.on("state-change",c.listener),e.journal.on("append",c.journalListener),c.keepAlive.unref(),o=c,this.channels.set(t,o)}o.subscribers.set(r,s),n.on("close",()=>this.unsubscribe(t,r));let i=JSON.stringify(lt(e.workingTree.state));$t(r,s.owned?"snapshot":"repo-snapshot",i)}unsubscribe(t,e){let n=this.channels.get(t);if(!n)return;if(n.subscribers.delete(e),n.subscribers.size===0)this.teardown(t,n)}teardown(t,e){e.manager.workingTree.off("state-change",e.listener),e.manager.journal.off("append",e.journalListener),clearInterval(e.keepAlive);for(let[n,{owned:r}]of e.subscribers)if(r)n.end();else Xs(n,t);e.subscribers.clear(),this.channels.delete(t)}closeRepo(t){let e=this.channels.get(t);if(e)this.teardown(t,e)}destroy(){for(let[t,e]of this.channels)this.teardown(t,e)}}class Tn{subscribers=new Set;keepAlive=null;subscribe(t,e,n){if(Js(e),this.subscribers.add(e),!this.keepAlive)this.keepAlive=setInterval(()=>{for(let r of this.subscribers)r.write(`: ping
38
36
 
39
- `)},G4),this.keepAlive.unref();$.on("close",()=>{if(this.subscribers.delete(Z),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),w$(Z,"snapshot",JSON.stringify(K))}broadcast($,Z){let K=JSON.stringify(Z);for(let V of this.subscribers)w$(V,$,K)}destroy(){if(this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null;for(let $ of this.subscribers)$.end();this.subscribers.clear()}}import*as O$ from"node:fs";import*as qZ from"node:path";import{watch as E7}from"chokidar";import{EventEmitter as _7}from"node:events";class U6 extends _7{targetFile;debug;watcher=null;debounceTimer=null;lastReadPath=null;_state={path:null,lastUpdate:null,rawContent:null,sourceFile:null};constructor($,Z=!1){super();this.targetFile=$,this.debug=Z,this._state.sourceFile=$}get state(){return this._state}updateState($){this._state={...this._state,...$},this.emit("path-change",this._state)}processContent($){if(!$)return null;let Z=l($);return qZ.isAbsolute(Z)?Z:qZ.resolve(Z)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let $=O$.readFileSync(this.targetFile,"utf-8"),Z=gZ($);if(Z&&Z!==this.lastReadPath){let K=this.processContent(Z),V=new Date;if(this.debug&&K)process.stderr.write(`[diffstalker ${V.toISOString()}] Path change detected
40
- `),process.stderr.write(` Source file: ${this.targetFile}
41
- `),process.stderr.write(` Raw content: "${Z}"
42
- `),process.stderr.write(` Previous: "${this.lastReadPath??"(none)"}"
43
- `),process.stderr.write(` Resolved: "${K}"
44
- `);this.lastReadPath=K,this.updateState({path:K,lastUpdate:V,rawContent:Z})}}catch{}}start(){if(b6(this.targetFile),!O$.existsSync(this.targetFile))O$.writeFileSync(this.targetFile,"");try{let $=O$.readFileSync(this.targetFile,"utf-8"),Z=gZ($);if(Z){let K=this.processContent(Z),V=new Date;if(this.debug&&K)process.stderr.write(`[diffstalker ${V.toISOString()}] Initial path read
45
- `),process.stderr.write(` Source file: ${this.targetFile}
46
- `),process.stderr.write(` Raw content: "${Z}"
47
- `),process.stderr.write(` Resolved: "${K}"
48
- `);this.lastReadPath=K,this._state={path:K,lastUpdate:V,rawContent:Z,sourceFile:this.targetFile}}}catch{}this.watcher=E7(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}}var O4={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class j6{registry;hub;targetFile;watcher;followedRepoId=null;followedPath=null;disposed=!1;queue=Promise.resolve();constructor($,Z,K){this.registry=$,this.hub=Z,this.targetFile=K,this.watcher=new U6(K)}get state(){return{targetFile:this.targetFile,enabled:!0,followedRepoId:this.followedRepoId,followedPath:this.followedPath}}start(){if(this.watcher.on("path-change",($)=>this.enqueue($)),this.watcher.start(),this.watcher.state.path)this.enqueue(this.watcher.state)}enqueue($){this.queue=this.queue.then(()=>this.follow($)).catch(()=>{})}async follow($){if(this.disposed||!$.path)return;let Z;try{Z=await this.registry.openRepo($.path)}catch{return}if(this.disposed){this.registry.closeRepo(Z.handle.id);return}if(Z.created)Z.handle.manager.workingTree.refresh().catch(()=>{});if(Z.handle.id===this.followedRepoId)this.registry.closeRepo(Z.handle.id);else{let K=this.followedRepoId;if(this.followedRepoId=Z.handle.id,this.followedPath=Z.handle.path,K)this.registry.closeRepo(K)}this.hub.broadcast("follow-change",{repoId:Z.handle.id,path:$.path,rawContent:$.rawContent})}dispose(){if(this.disposed)return;if(this.disposed=!0,this.watcher.stop(),this.followedRepoId)this.registry.closeRepo(this.followedRepoId),this.followedRepoId=null,this.followedPath=null}}import*as c from"node:fs";import*as k$ from"node:path";function H4(){return{watchRoots:[]}}var G6=16;function P7($){let Z=$.trim();if(!Z)throw Error("Watch directory cannot be empty");let K=l(Z);if(!k$.isAbsolute(K))throw Error(`Watch directory must be absolute: ${$}`);let V=k$.resolve(K),Q;try{Q=c.statSync(V)}catch{throw Error(`No such directory: ${V}`)}if(!Q.isDirectory())throw Error(`Not a directory: ${V}`);return V}function C4($){if($.length>G6)throw Error(`Too many watch directories (max ${G6})`);let Z=new Set,K=[];for(let V of $){let Q=P7(V);if(Z.has(Q))continue;Z.add(Q),K.push(Q)}return K}function x7($){let Z=H4();if(typeof $!=="object"||$===null)return Z;let K=$;if(Array.isArray(K.watchRoots))Z.watchRoots=K.watchRoots.filter((V)=>typeof V==="string").slice(0,G6);return Z}class M6{file;current=H4();constructor($){this.file=$}get settings(){return this.current}get persisted(){return this.file!==null}load(){if(!this.file)return this.current;let $;try{$=c.readFileSync(this.file,"utf-8")}catch{return this.current}try{this.current=x7(JSON.parse($))}catch(Z){JZ(`Ignoring invalid settings file ${this.file}: ${String(Z)}`)}return this.current}save($){if(this.current=$,!this.file)return this.current;c.mkdirSync(k$.dirname(this.file),{recursive:!0});let Z=`${this.file}.${process.pid}.tmp`;try{c.writeFileSync(Z,`${JSON.stringify(this.current,null,2)}
49
- `,{mode:384}),c.renameSync(Z,this.file)}catch(K){throw c.rmSync(Z,{force:!0}),K}return this.current}}import*as I4 from"node:path";import{watch as d7}from"chokidar";import*as a from"node:fs/promises";import*as y from"node:path";var b7=2,y7=500,m7=new Set(["node_modules","vendor","target","dist","build","venv","__pycache__"]);async function N4($){try{return await a.stat(y.join($,".git")),!0}catch{return!1}}async function g7($){let Z=y.join($,".git"),K;try{K=await a.stat(Z)}catch{return null}if(K.isDirectory())return Z;try{let V=await a.readFile(Z,"utf-8"),Q=/^gitdir:\s*(.+)$/m.exec(V);if(!Q)return null;let Y=Q[1].trim(),X=y.isAbsolute(Y)?Y:y.resolve($,Y);return await a.stat(X),X}catch{return null}}async function c7($){let Z;try{Z=(await a.readFile(y.join($,"HEAD"),"utf-8")).trim()}catch{return null}let K=/^ref:\s*refs\/heads\/(.+)$/.exec(Z);if(K)return K[1].trim();if(/^[0-9a-f]{40}$/i.test(Z))return Z.slice(0,7);return null}async function u7($){let K=(await Promise.all(["index","HEAD"].map(async(V)=>{try{return(await a.stat(y.join($,V))).mtimeMs}catch{return null}}))).filter((V)=>V!==null);return K.length===0?null:Math.max(...K)}async function p7($){let Z=await g7($);if(Z===null)return null;let[K,V]=await Promise.all([c7(Z),u7(Z)]);return{path:$,name:y.basename($),branch:K,lastActivity:V}}function f7($){if(!$.isDirectory())return!1;if($.name.startsWith("."))return!1;return!m7.has($.name)}async function B4($){let Z=await O6($);return Promise.all(Z.map(async(K)=>({name:y.basename(K),path:K,isRepo:await N4(K)})))}async function O6($){return(await a.readdir($,{withFileTypes:!0})).filter(f7).map((K)=>y.join($,K.name)).sort()}async function h7($,Z,K){let V=[],Q=[];for(let Y of $){if(V.length>=K)return{repos:V,next:Q,capped:!0};if(await N4(Y)){V.push(Y);continue}if(!Z)continue;try{Q.push(...await O6(Y))}catch{}}return{repos:V,next:Q,capped:!1}}async function A4($,Z={}){let K=Z.depth??b7,V=Z.limit??y7,Q=await O6($),Y=[],X=!1;for(let W=1;W<=K&&Q.length>0&&!X;W++){let z=await h7(Q,W<K,V-Y.length);Y.push(...z.repos),X=z.capped,Q=z.next.sort()}return{repos:(await Promise.all(Y.map(p7))).filter((W)=>W!==null),capped:X}}var l7=300;function n7($,Z){let K=I4.basename($);if(K.startsWith(".")&&K!==".")return!0;if(K==="node_modules")return!0;return WZ($,Z)}class H6{hub;roots=new Map;disposed=!1;constructor($){this.hub=$}get state(){return{roots:[...this.roots.values()].map(($)=>$.state)}}async setRoots($){if(this.disposed)return;for(let[V,Q]of this.roots)if(!$.includes(V))this.teardown(Q),this.roots.delete(V);let Z=[],K=new Map;for(let V of $){let Q=this.roots.get(V);if(Q){K.set(V,Q);continue}K.set(V,{state:{path:V,repos:[],error:null,capped:!1},watcher:null,timer:null}),Z.push(V)}this.roots=K,await Promise.all(Z.map((V)=>this.scan(V)));for(let V of Z)this.startWatching(V);this.broadcast()}async rescan(){return await Promise.all([...this.roots.keys()].map(($)=>this.scan($))),this.broadcast(),this.state}dispose(){this.disposed=!0;for(let $ of this.roots.values())this.teardown($);this.roots.clear()}teardown($){if($.timer)clearTimeout($.timer);$.timer=null,$.watcher?.close(),$.watcher=null}async scan($){let Z=this.roots.get($);if(!Z)return;try{let K=await A4($);Z.state={path:$,repos:K.repos,error:null,capped:K.capped}}catch(K){Z.state={path:$,repos:[],error:K instanceof Error?K.message:String(K),capped:!1}}}startWatching($){let Z=this.roots.get($);if(!Z||Z.watcher)return;let K=d7($,{persistent:!0,ignoreInitial:!0,depth:1,ignored:n7});K.on("error",(V)=>{Z.state={...Z.state,error:V instanceof Error?V.message:String(V)},this.broadcast()}),K.on("addDir",()=>this.scheduleRescan($)),K.on("unlinkDir",()=>this.scheduleRescan($)),Z.watcher=K}scheduleRescan($){let Z=this.roots.get($);if(!Z)return;if(Z.timer)clearTimeout(Z.timer);Z.timer=setTimeout(()=>{Z.timer=null,this.scan($).then(()=>this.broadcast())},l7),Z.timer.unref?.()}broadcast(){if(this.disposed)return;this.hub.broadcast("discovery-change",this.state)}}import*as F4 from"node:fs";import{execFile as o7}from"node:child_process";import*as X$ from"node:fs";import*as Z$ from"node:path";import{fileURLToPath as a7}from"node:url";var L4={method:"unknown",package:null,command:null},r$="diffstalkerd",i7=3000,s7=["paru","yay"],r7=[{method:"bun",pattern:/\/install\/global\/node_modules\/diffstalkerd$/,command:`bun add -g ${r$}`},{method:"pnpm",pattern:/\/pnpm\/global\/\d+\/node_modules\/diffstalkerd$/,command:`pnpm add -g ${r$}`},{method:"yarn",pattern:/\/yarn\/global\/node_modules\/diffstalkerd$/,command:`yarn global add ${r$}`},{method:"npm",pattern:/\/lib\/node_modules\/diffstalkerd$/,command:`npm install -g ${r$}`}];async function t7($,Z){let K=$.split(Z$.sep).join("/").replace(/\/+$/,"");for(let Q of r7){if(!Q.pattern.test(K))continue;let Y=Z.writable($)?"":"sudo ";return{method:Q.method,package:r$,command:`${Y}${Q.command}`}}let V=await Z.pacmanOwner(Z$.join($,"package.json"));if(V!==null){let Q=Z.onPath(s7);return{method:"pacman",package:V,command:Q?`${Q} -S ${V}`:`sudo pacman -Syu ${V}`}}return L4}var e7={onPath($){let Z=(process.env.PATH??"").split(Z$.delimiter).filter(Boolean);for(let K of $)for(let V of Z)try{return X$.accessSync(Z$.join(V,K),X$.constants.X_OK),K}catch{}return null},pacmanOwner($){return new Promise((Z)=>{o7("pacman",["-Qoq","--",$],{timeout:i7},(K,V)=>{if(K)return Z(null);let Q=V.trim().split(`
50
- `)[0]?.trim();Z(Q?Q:null)})})},writable($){try{return X$.accessSync($,X$.constants.W_OK),!0}catch{return!1}}};function $0(){let $=Z$.dirname(a7(new URL("../package.json",import.meta.url)));try{return X$.realpathSync($)}catch{return $}}function T4($=$0(),Z=e7){let K=null;return{info(){return K??=t7($,Z).catch(()=>L4),K}}}var Z0="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",K0=21600000,V0=300000,Q0=5000;function C6(){try{let $=F4.readFileSync(new URL("../package.json",import.meta.url),"utf-8"),Z=JSON.parse($);return typeof Z.version==="string"?Z.version:null}catch{return null}}async function Y0(){let $=await fetch(Z0,{headers:{accept:"application/json"},signal:AbortSignal.timeout(Q0)});if(!$.ok)return null;let Z=await $.json();return typeof Z.latest==="string"?Z.latest:null}function D4($){let Z=/^(\d+)\.(\d+)\.(\d+)/.exec($.trim());if(!Z)return null;return[Number(Z[1]),Number(Z[2]),Number(Z[3])]}function X0($,Z){if($===null||Z===null)return"unknown";let K=D4($),V=D4(Z);if(!K||!V)return"unknown";for(let Q=0;Q<K.length;Q++){if(K[Q]<V[Q])return"outdated";if(K[Q]>V[Q])return"ahead"}return"current"}function q4($=Y0,Z=C6(),K=T4()){let V=null,Q=null;function Y(){if(V&&Date.now()<V.expiresAt)return Promise.resolve(V.value);if(Q)return Q;return Q=$().catch(()=>null).then((X)=>{let J=X===null?V0:K0;return V={value:X,expiresAt:Date.now()+J},Q=null,X}),Q}return{async state(){let[X,J]=await Promise.all([Y(),K.info()]);return{current:Z,latest:X,status:X0(Z,X),install:J}}}}import*as S4 from"node:os";function R4($,Z){$.get("/health",({res:K})=>{B(K,200,{ok:!0,ready:!0,home:S4.homedir(),http:{port:Z.httpPort()},symbols:{extensions:Z.symbols?.extensions??[]}})})}function v4($,Z){$.get("/version",async({res:K})=>{B(K,200,await Z.version.state())})}import*as t$ from"node:fs";import*as _ from"node:path";function I($,Z){let K=$.getRepo(Z);if(!K)throw new O(404,`Unknown repo id: ${Z}`);return K}function u($,Z,K){if(typeof $!=="object"||$===null)throw new O(400,`Expected a JSON body with "${Z}"`);let V=$[Z];if(typeof V!=="string"||!K?.allowEmpty&&V.length===0)throw new O(400,`Missing "${Z}" (string) in body`);return V}function H$($,Z){let K=u($,Z);if(K.startsWith("-"))throw new O(400,`Invalid "${Z}" (must not start with "-"): ${K}`);return K}function k4($,Z){if(typeof $!=="object"||$===null)throw new O(400,`Expected a JSON body with "${Z}"`);let K=$[Z];if(!Array.isArray(K)||K.some((V)=>typeof V!=="string"))throw new O(400,`Missing "${Z}" (array of strings) in body`);return K}function E4($,Z){if(typeof $!=="object"||$===null)return;let K=$[Z];if(K===void 0)return;if(typeof K!=="string"||K.length===0)throw new O(400,`Invalid "${Z}" (expected a non-empty string)`);return K}function A6($,Z,K){if(typeof $!=="object"||$===null)return K.fallback;let V=$[Z];if(V===void 0)return K.fallback;if(typeof V!=="number"||!Number.isInteger(V)||V<K.min)throw new O(400,`Invalid "${Z}" (expected an integer >= ${K.min})`);return V}function _4($,Z){if(typeof $!=="object"||$===null)return!1;let K=$[Z];if(K===void 0)return!1;if(typeof K!=="boolean")throw new O(400,`Invalid "${Z}" (expected a boolean)`);return K}function m($,Z,K){let V=$.get(Z);if(V===null)return K;if(V==="true")return!0;if(V==="false")return!1;throw new O(400,`Invalid "${Z}" (expected true or false): ${V}`)}function P4($,Z,K,V){let Q=$.get(Z);if(Q===null)return K;let Y=Number(Q);if(!Number.isInteger(Y)||Y<1)throw new O(400,`Invalid "${Z}" (expected a positive integer): ${Q}`);if(V!==void 0&&Y>V)throw new O(400,`Invalid "${Z}" (must be <= ${V}): ${Q}`);return Y}async function K$($){if(!$.state.status)await $.refresh();let Z=$.state.status;if(!Z)throw new O(500,"Repository status unavailable");return Z}function w4($,Z,K){let V=$.files.filter((Q)=>Q.path===Z);if(V.length===0)return null;return V.find((Q)=>Q.staged===K)??V[0]}async function E$($,Z,K){let V=await K$($),Q=w4(V,Z,K);if(!Q)await $.refresh(),V=await K$($),Q=w4(V,Z,K);if(!Q)throw new O(404,`File not in status: ${Z}`);return Q}function B6($,Z){return $===Z||$.startsWith(Z+_.sep)}function I6($){return $.replace(/[. ]+$/,"").toLowerCase()===".git"}function C$($,Z){if(Z.length===0)throw new O(400,"Empty path");if(Z.includes("\x00"))throw new O(400,"Path contains a NUL byte");let K=_.resolve($),V=_.relative(K,_.resolve(K,Z));if(V==="")throw new O(400,`Path resolves to the repository root: ${Z}`);if(_.isAbsolute(V)||V===".."||V.startsWith(`..${_.sep}`))throw new O(400,`Path escapes repository root: ${Z}`);if(V.startsWith("-"))throw new O(400,`Path must not start with "-": ${Z}`);if(V.startsWith(":"))throw new O(400,`Path must not start with ":": ${Z}`);if(V.split(_.sep).some(I6))throw new O(400,`Path addresses the git directory: ${Z}`);return V}async function x4($){try{return await t$.promises.realpath($)}catch{return null}}var N6=new WeakMap;async function J0($){let Z=N6.get($);if(!Z)Z=(async()=>{let K=await L($.path).raw(["rev-parse","--absolute-git-dir"]);return await t$.promises.realpath(K.trim())})(),N6.set($,Z),Z.catch(()=>N6.delete($));try{return await Z}catch{throw new O(500,"Cannot resolve the git directory for this repository")}}async function N$($,Z){let K=await t$.promises.realpath(_.resolve($.path)),V=await x4(_.join($.path,Z));if(V===null)return;if(!B6(V,K))throw new O(400,`Path escapes repository root: ${Z}`);if(B6(V,await J0($)))throw new O(400,`Path addresses the git directory: ${Z}`)}async function b4($,Z){let K=await t$.promises.realpath(_.resolve($)),V=[];for(let Q of Z){let Y=await x4(_.join($,Q.path));if(Y===null||B6(Y,K))V.push(Q)}return V}function L6($){return $?.code??null}function W0($){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test($)?409:500}async function V$($,Z,K){$.clearError(),await K();let V=$.state.error;if(V){B(Z,W0(V),{error:V});return}await $.refresh(),B(Z,200,{state:Y$($.state)})}function z0($){return/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged/i.test($)?409:500}async function g($,Z,K){let V=$.manager.remote,Q=()=>new O(409,`A ${V.remoteState.operation??"remote"} operation is already in progress`);if(V.remoteState.inProgress)throw Q();let Y=await K();if(Y===null)throw Q();if(Y.error){B(Z,z0(Y.error),{error:Y.error});return}let X=$.manager.workingTree;await X.refresh(),B(Z,200,{state:Y$(X.state),result:Y.lastResult})}function y4($,Z){let{registry:K}=Z;$.get("/repos",({res:V})=>{let Q=K.listRepos().map((Y)=>({id:Y.id,path:Y.path,branch:Y.manager.workingTree.state.status?.branch.current??null}));B(V,200,Q)}),$.post("/repos",async({body:V,res:Q})=>{let Y=u(V,"path"),X;try{X=await FZ(K,Y)}catch(J){throw new O(400,J instanceof Error?J.message:String(J))}B(Q,X.created?201:200,{id:X.handle.id,path:X.handle.path})}),$.get("/resolve",async({query:V,res:Q})=>{let Y=V.get("path");if(!Y)throw new O(400,'Missing "path" query parameter');let X=await NZ(Y,{mustExist:!0});if(!X.ok&&X.reason==="not-absolute")throw new O(400,`Repo path must be absolute: ${X.requested}`);B(Q,200,{openable:X.ok,root:X.ok?X.root:null})}),$.get("/repos/:id/worktrees",async({params:V,res:Q})=>{let Y=I(K,V.id);B(Q,200,await tZ(Y.path))}),$.get("/worktrees",async({query:V,res:Q})=>{let Y=V.get("path");if(!Y)throw new O(400,'Missing "path" query parameter');B(Q,200,await tZ(Y))}),$.delete("/repos/:id",({params:V,res:Q})=>{I(K,V.id),K.closeRepo(V.id),B(Q,200,{})})}function m4($,Z,K){if(!$.trim())return{valid:!1,error:"Commit message cannot be empty"};if(Z===0&&!K)return{valid:!1,error:"No changes staged for commit"};return{valid:!0,error:null}}function g4($){return $.trim()}async function U0($){let Z=(V)=>V.filter((Q)=>Q.staged).length,K=Z((await K$($)).files);if(K===0)await $.refresh(),K=Z((await K$($)).files);return K}function c4($,Z){let{registry:K,sse:V}=Z;if($.get("/repos/:id/status",async({params:Q,res:Y})=>{let X=I(K,Q.id);await K$(X.manager.workingTree);let J=Y$(X.manager.workingTree.state);J.operationInProgress=await t(X.path),B(Y,200,J)}),$.get("/repos/:id/diff",async({params:Q,query:Y,res:X})=>{let J=I(K,Q.id),W=Y.get("path")??void 0,z=m(Y,"staged",!1),U=m(Y,"whole",!1);if(U&&!W)throw new O(400,"whole=true requires a path (one file at a time)");let j=U?OZ:void 0,G,M=!1;if(W){let H=(await K$(J.manager.workingTree)).files.some((D)=>D.path===W&&D.status==="untracked");if(H&&z)throw new O(400,`staged=true is meaningless for untracked file: ${W} (untracked files have no staged diff)`);M=U&&!H,G=H?await M$(J.path,W):await v$(J.path,W,z,{context:j})}else G=await v$(J.path,void 0,z);if(!M)J.manager.workingTree.stampDiff(G);B(X,200,G)}),$.post("/repos/:id/stage",async({params:Q,body:Y,res:X})=>{let J=I(K,Q.id),W=u(Y,"path"),z=J.manager.workingTree,U=await E$(z,W,!1);await V$(z,X,()=>z.stage(U))}),$.post("/repos/:id/unstage",async({params:Q,body:Y,res:X})=>{let J=I(K,Q.id),W=u(Y,"path"),z=J.manager.workingTree,U=await E$(z,W,!0);await V$(z,X,()=>z.unstage(U))}),$.get("/repos/:id/events",({params:Q,req:Y,res:X})=>{let J=I(K,Q.id);V.subscribe(Q.id,J.manager,Y,X)}),Z.apiMode==="full")j0($,Z)}function j0($,Z){let{registry:K}=Z;$.post("/repos/:id/stage-all",async({params:V,res:Q})=>{let X=I(K,V.id).manager.workingTree;await V$(X,Q,()=>X.stageAll())}),$.post("/repos/:id/unstage-all",async({params:V,res:Q})=>{let X=I(K,V.id).manager.workingTree;await V$(X,Q,()=>X.unstageAll())}),$.post("/repos/:id/discard",async({params:V,body:Q,res:Y})=>{let X=I(K,V.id),J=u(Q,"path"),W=X.manager.workingTree,z=await E$(W,J,!1);if(z.staged)throw new O(409,`Cannot discard a staged file: ${J} (unstage it first)`);await V$(W,Y,()=>W.discard(z))}),$.post("/repos/:id/commit",async({params:V,body:Q,res:Y})=>{let X=I(K,V.id),J=u(Q,"message",{allowEmpty:!0}),W=_4(Q,"amend"),z=X.manager.workingTree,U=await U0(z),j=m4(J,U,W);if(!j.valid)throw new O(400,j.error??"Invalid commit");await V$(z,Y,()=>z.commit(g4(J),W))}),$.post("/repos/:id/stage-hunk",async({params:V,body:Q,res:Y})=>{let X=I(K,V.id),J=u(Q,"patch"),W=X.manager.workingTree;await V$(W,Y,()=>W.stageHunk(J))}),$.post("/repos/:id/unstage-hunk",async({params:V,body:Q,res:Y})=>{let X=I(K,V.id),J=u(Q,"patch"),W=X.manager.workingTree;await V$(W,Y,()=>W.unstageHunk(J))})}async function G0($){let Z=await iZ($);if(Z&&await $$($,Z))return Z;if(q$($)){let K=await i$($);if(K&&await $$($,K))return K}throw new O(422,"No usable base branch")}async function T6($,Z){let K=Z.get("base");if(K===null)return G0($);if(!await $$($,K))throw new O(400,`Unknown base ref: ${K}`);return K}var M0=new Set(["staged","unstaged","both","untracked"]);function O0($){return{staged:m($,"staged",!1),unstaged:m($,"unstaged",!1),untracked:m($,"untracked",!1)}}function u4($){return $?{context:OZ}:{}}function p4($,Z){let{registry:K}=Z;if($.get("/repos/:id/history",async({params:V,query:Q,res:Y})=>{let X=I(K,V.id),J=P4(Q,"count",100,5000);B(Y,200,await I8(X.path,J))}),$.get("/repos/:id/commits/:hash",async({params:V,res:Q})=>{let Y=I(K,V.id),X=V.hash;if(!/^[0-9a-f]{4,40}$/i.test(X))throw new O(400,`Invalid commit hash: ${X}`);let J=await L8(Y.path,X);if(J===null)throw new O(404,`Unknown commit: ${X}`);B(Q,200,J)}),$.get("/repos/:id/commits/:hash/diff",async({params:V,query:Q,res:Y})=>{let X=I(K,V.id),J=V.hash;if(!/^[0-9a-f]{4,40}$/i.test(J))throw new O(400,`Invalid commit hash: ${J}`);if(!await $$(X.path,J))throw new O(404,`Unknown commit: ${J}`);let W=Q.get("path")??void 0,z=m(Q,"whole",!1);if(z&&!W)throw new O(400,"whole=true requires a path (one file at a time)");let U=W?await sZ(X.path,{kind:"commit",hash:J},W,u4(z)):await c8(X.path,J);B(Y,200,U)}),$.get("/repos/:id/commits/:hash/files",async({params:V,res:Q})=>{let Y=I(K,V.id),X=V.hash;if(!/^[0-9a-f]{4,40}$/i.test(X))throw new O(400,`Invalid commit hash: ${X}`);if(!await $$(Y.path,X))throw new O(404,`Unknown commit: ${X}`);B(Q,200,await g8(Y.path,X))}),$.get("/repos/:id/compare/file",async({params:V,query:Q,res:Y})=>{let X=I(K,V.id),J=Q.get("path");if(!J)throw new O(400,"path is required");let W=m(Q,"whole",!1),z=Q.get("side");if(z!==null&&!M0.has(z))throw new O(400,`Unknown side: ${z}`);let U=z;if(U==="untracked"){B(Y,200,await M$(X.path,J));return}let j=U===null?{kind:"compare",base:await T6(X.path,Q)}:{kind:U==="both"?"head":U};B(Y,200,await sZ(X.path,j,J,u4(W)))}),$.get("/repos/:id/head-message",async({params:V,res:Q})=>{let Y=I(K,V.id);B(Q,200,{message:await O8(Y.path)})}),$.get("/repos/:id/branches",async({params:V,res:Q})=>{let Y=I(K,V.id);B(Q,200,await GZ(Y.path))}),$.get("/repos/:id/base-branches",async({params:V,res:Q})=>{let Y=I(K,V.id);B(Q,200,await aZ(Y.path))}),$.get("/repos/:id/compare/base",async({params:V,res:Q})=>{let Y=I(K,V.id);B(Q,200,{base:await iZ(Y.path)})}),Z.apiMode==="full")$.put("/repos/:id/compare/base",async({params:V,body:Q,res:Y})=>{let X=I(K,V.id),J=H$(Q,"branch");if(!await $$(X.path,J))throw new O(400,`Not a valid base ref: ${J}`);P8(X.path,J),B(Y,200,{base:J})});$.get("/repos/:id/compare/count",async({params:V,query:Q,res:Y})=>{let X=I(K,V.id),J=await T6(X.path,Q);try{B(Y,200,{baseBranch:J,commits:await m8(X.path,J)})}catch(W){if(W instanceof R$)throw new O(422,W.message);throw W}}),$.get("/repos/:id/compare",async({params:V,query:Q,res:Y})=>{let X=I(K,V.id),J=O0(Q),W=await T6(X.path,Q),z;try{z=await u8(X.path,W,J)}catch(U){if(U instanceof R$)throw new O(422,U.message);throw U}B(Y,200,z)})}function H0($){let Z=$.get("since");if(Z===null)return 0;if(!/^\d+$/.test(Z))throw new O(400,`Invalid "since" (expected a non-negative integer): ${Z}`);return Number(Z)}function f4($,Z){let{registry:K}=Z;$.get("/repos/:id/journal",({params:V,query:Q,res:Y})=>{let X=I(K,V.id),J=H0(Q);B(Y,200,m6(X.manager.journal.journalStore,J))})}function h4($,Z){let{registry:K}=Z;$.post("/repos/:id/push",async({params:V,res:Q})=>{let Y=I(K,V.id);await g(Y,Q,()=>Y.manager.remote.push())}),$.post("/repos/:id/fetch",async({params:V,res:Q})=>{let Y=I(K,V.id);await g(Y,Q,()=>Y.manager.remote.fetchRemote())}),$.post("/repos/:id/pull",async({params:V,res:Q})=>{let Y=I(K,V.id);await g(Y,Q,()=>Y.manager.remote.pullRebase())}),$.post("/repos/:id/stash",async({params:V,body:Q,res:Y})=>{let X=I(K,V.id),J=E4(Q,"message");await g(X,Y,()=>X.manager.remote.stash(J))}),$.post("/repos/:id/stash-pop",async({params:V,body:Q,res:Y})=>{let X=I(K,V.id),J=A6(Q,"index",{min:0,fallback:0});await g(X,Y,()=>X.manager.remote.stashPop(J))}),$.post("/repos/:id/switch-branch",async({params:V,body:Q,res:Y})=>{let X=I(K,V.id),J=H$(Q,"name");await g(X,Y,()=>X.manager.remote.switchBranch(J))}),$.post("/repos/:id/create-branch",async({params:V,body:Q,res:Y})=>{let X=I(K,V.id),J=H$(Q,"name");await g(X,Y,()=>X.manager.remote.createBranch(J))}),$.post("/repos/:id/soft-reset",async({params:V,body:Q,res:Y})=>{let X=I(K,V.id),J=A6(Q,"count",{min:1,fallback:1});if(!await $$(X.path,`HEAD~${J}`))throw new O(400,`Cannot soft-reset ${J} commit(s): HEAD~${J} does not exist`);await g(X,Y,()=>X.manager.remote.softReset(J))}),$.post("/repos/:id/cherry-pick",async({params:V,body:Q,res:Y})=>{let X=I(K,V.id),J=H$(Q,"hash");await g(X,Y,()=>X.manager.remote.cherryPick(J))}),$.post("/repos/:id/revert",async({params:V,body:Q,res:Y})=>{let X=I(K,V.id),J=H$(Q,"hash");await g(X,Y,()=>X.manager.remote.revertCommit(J))}),$.post("/repos/:id/abort",async({params:V,res:Q})=>{let Y=I(K,V.id);if(!await t(Y.path))throw new O(409,"No operation in progress to abort");await g(Y,Q,()=>Y.manager.remote.abortOperation())}),$.post("/repos/:id/rebase-continue",async({params:V,res:Q})=>{let Y=I(K,V.id);if(await t(Y.path)!=="rebase")throw new O(409,"No rebase in progress to continue");await g(Y,Q,()=>Y.manager.remote.rebaseContinue())})}import*as B$ from"node:fs";import*as e$ from"node:path";var x$=8388608;var d4=65536;function _$($){return Array.from($,(Z)=>Z.charCodeAt(0))}function P$($,Z,K){if(Z+K.length>$.length)return!1;for(let V=0;V<K.length;V++)if($[Z+V]!==K[V])return!1;return!0}function SZ($,Z){return $[Z]*16777216+($[Z+1]<<16)+($[Z+2]<<8)+$[Z+3]}function D6($,Z){return($[Z]<<8)+$[Z+1]}function RZ($,Z){return $[Z]+($[Z+1]<<8)}function l4($,Z){return String.fromCharCode($[Z],$[Z+1],$[Z+2],$[Z+3])}function w($){return{ok:!1,refusal:$}}function b$($){return w($?"malformed":"header-not-found")}function F6($,Z){if($<1||Z<1)return"malformed";if($>8192||Z>8192)return"too-many-pixels";if($*Z>16777216)return"too-many-pixels";return null}var C0=[137,80,78,71,13,10,26,10],N0=[255,216,255],B0=_$("GIF87a"),A0=_$("GIF89a"),i=_$("ftyp");function d($){return{offset:8,bytes:_$($)}}var I0=[{label:"webp",offset:0,bytes:_$("RIFF"),brand:d("WEBP")},{label:"avif",offset:4,bytes:i,brand:d("avif")},{label:"avis",offset:4,bytes:i,brand:d("avis")},{label:"heic",offset:4,bytes:i,brand:d("heic")},{label:"heix",offset:4,bytes:i,brand:d("heix")},{label:"heim",offset:4,bytes:i,brand:d("heim")},{label:"heis",offset:4,bytes:i,brand:d("heis")},{label:"hevc",offset:4,bytes:i,brand:d("hevc")},{label:"hevx",offset:4,bytes:i,brand:d("hevx")},{label:"mif1",offset:4,bytes:i,brand:d("mif1")},{label:"msf1",offset:4,bytes:i,brand:d("msf1")},{label:"tiff-le",offset:0,bytes:[73,73,42,0]},{label:"tiff-be",offset:0,bytes:[77,77,0,42]},{label:"bmp",offset:0,bytes:_$("BM")},{label:"ico",offset:0,bytes:[0,0,1,0]},{label:"cur",offset:0,bytes:[0,0,2,0]},{label:"jxl-codestream",offset:0,bytes:[255,10]},{label:"jxl-container",offset:0,bytes:[0,0,0,12,74,88,76,32,13,10,135,10]}];function L0($){return I0.some((Z)=>P$($,Z.offset,Z.bytes)&&(Z.brand===void 0||P$($,Z.brand.offset,Z.brand.bytes)))}var T0={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},D0=26;function F0($,Z,K){if($.length<D0)return b$(K);if(SZ($,8)!==13)return w("malformed");if(l4($,12)!=="IHDR")return w("malformed");let V=SZ($,16),Q=SZ($,20),Y=F6(V,Q);if(Y)return w(Y);let X=T0[$[25]];if(!X||!X.includes($[24]))return w("malformed");let J=q0($,K);if(J)return J;return{ok:!0,info:{format:"png",mime:"image/png",width:V,height:Q,bytes:Z}}}function q0($,Z){let K=8;for(let V=0;V<256;V++){if(K+8>$.length)return b$(Z);let Q=SZ($,K),Y=l4($,K+4);if(Y==="IDAT")return null;if(Y==="acTL")return w("animation");if(Y==="iCCP"&&Q>65536)return w("malformed");let X=K+12+Q;if(X<=K||!Number.isSafeInteger(X))return w("malformed");K=X}return w("malformed")}var S0=218,R0=226,v0=new Set([219,238,192,193,194,196]);function w0($){return $>=224&&$<=239||v0.has($)}function k0($){return $===1||$>=208&&$<=217}function E0($){return $>=192&&$<=207&&$!==196&&$!==200&&$!==204}var _0=new Set([192,193,194]);function P0($,Z,K){if($.length<4)return b$(K);if(!w0($[3]))return w("malformed");return y0($,Z,K)}function x0($,Z,K,V,Q){if(!_0.has(K))return w("malformed");if(Z+9>$.length)return b$(Q);let Y=D6($,Z+5),X=D6($,Z+7),J=F6(X,Y);if(J)return w(J);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:X,height:Y,bytes:V}}}function b0($,Z){if(Z+1>=$.length)return{kind:"ran-out"};if($[Z]!==255)return{kind:"malformed"};let K=$[Z+1];if(K===255)return{kind:"skip",next:Z+1};if(k0(K))return{kind:"skip",next:Z+2};if(K===S0)return{kind:"malformed"};if(Z+4>$.length)return{kind:"ran-out"};let V=D6($,Z+2);if(V<2)return{kind:"malformed"};if(E0(K))return{kind:"sof",marker:K};return{kind:"segment",marker:K,length:V}}function y0($,Z,K){let V=2,Q=0;for(let Y=0;Y<1024;Y++){let X=b0($,V);if(X.kind==="ran-out")return b$(K);if(X.kind==="malformed")return w("malformed");if(X.kind==="sof")return x0($,V,X.marker,Z,K);if(X.kind==="skip"){V=X.next;continue}if(X.marker===R0){if(Q+=X.length-2,Q>65536)return w("malformed")}V+=2+X.length}return w("malformed")}var m0=59,g0=44,c0=33;function n4($){return($&128)===0?0:3*(1<<($&7)+1)}function u0($,Z,K){if(Z>2097152)return w("too-large");if(!K)return w("header-not-found");if($.length<13)return b$(K);let V=RZ($,6),Q=RZ($,8),Y=F6(V,Q);if(Y)return w(Y);let X={pos:13+n4($[10]),left:8192,pixels:0,overBudget:!1},J=p0($,X);if(J===null)return w("malformed");if(J<1)return w("malformed");if(J>256)return w("too-many-pixels");if(X.overBudget)return w("too-many-pixels");if(J*V*Q>33554432)return w("too-many-pixels");let W={format:"gif",mime:"image/gif",width:V,height:Q,bytes:Z};if(J>1)W.frames=J;return{ok:!0,info:W}}function p0($,Z){let K=0;while(Z.left-- >0){if(Z.pos>=$.length)return null;let V=$[Z.pos];if(V===m0)return K;let Q=V===g0;if(!(Q?h0($,Z):f0($,Z,V)))return null;if(Q&&++K>256)return K;if(Z.overBudget)return K}return null}function f0($,Z,K){if(K!==c0)return!1;return Z.pos+=2,o4($,Z)}function h0($,Z){if(Z.pos+10>$.length)return!1;d0(Z,RZ($,Z.pos+5),RZ($,Z.pos+7));let K=$[Z.pos+9];return Z.pos+=10+n4(K)+1,o4($,Z)}function d0($,Z,K){let V=Z*K;if(Z>8192||K>8192||V>16777216){$.overBudget=!0;return}if($.pixels+=V,$.pixels>33554432)$.overBudget=!0}function o4($,Z){while(Z.left-- >0){if(Z.pos>=$.length)return!1;let K=$[Z.pos];if(Z.pos+=1+K,K===0)return Z.pos<=$.length}return!1}function a4($){return P$($,0,B0)||P$($,0,A0)}function y$($,Z,K){if(Z>8388608)return w("too-large");if(P$($,0,C0))return F0($,Z,K);if(P$($,0,N0))return P0($,Z,K);if(a4($))return u0($,Z,K);if(L0($))return w("unsupported-format");return w("not-an-image")}function vZ($,Z){return a4($)?Math.min(Z,2097152):65536}function q6($){let Z={files:new Map,directories:new Set};for(let K of $){Z.files.set(K.path,{status:K.status,staged:K.staged});let V=K.path.split("/"),Q="";for(let Y=0;Y<V.length-1;Y++)Q=Q?`${Q}/${V[Y]}`:V[Y],Z.directories.add(Q);Z.directories.add("")}return Z}var l0=1048576,i4=5000;class $Z extends Error{constructor($){super(`Not a regular file: ${$}`);this.name="NotRegularFileError"}}async function r4($,Z,K,V){let Q=K?.hideHidden??!0,Y=K?.hideGitignored??!0,X=e$.join($,Z),J=await B$.promises.readdir(X,{withFileTypes:!0}),W=J.map((j)=>Z?e$.join(Z,j.name):j.name),z=Y?await F$($,W):new Set,U=[];for(let j of J){if(Q&&j.name.startsWith("."))continue;let G=Z?e$.join(Z,j.name):j.name;if(Y&&z.has(G))continue;let M=j.isDirectory(),C={name:j.name,path:G,type:M?"dir":"file"};if(V)if(M){if(V.directories.has(G))C.hasChanges=!0}else{let H=V.files.get(G);if(H)C.gitStatus=H.status,C.staged=H.staged}U.push(C)}return U.sort((j,G)=>{if(j.type==="dir"&&G.type!=="dir")return-1;if(j.type!=="dir"&&G.type==="dir")return 1;return j.name.localeCompare(G.name)}),U}var n0=16,o0=B$.constants.O_RDONLY|(B$.constants.O_NONBLOCK??0);async function S6($,Z,K){let V=Buffer.alloc(Z),Q=0;while(Q<Z){let{bytesRead:Y}=await $.read(V,Q,Z-Q,K+Q);if(Y===0)break;Q+=Y}return Q===Z?V:V.subarray(0,Q)}async function a0($,Z){let K=await S6($,Math.min(n0,Z),0),V=y$(K,Z,K.length>=Z);if(!V.ok&&V.refusal==="too-large")return{head:K,result:V};let Q=Math.min(vZ(K,Z),Z),Y=Q<=K.length?K.subarray(0,Q):Buffer.concat([K,await S6($,Q-K.length,K.length)]);return{head:Y,result:y$(Y,Z,Y.length>=Z)}}function i0($,Z){return $.ok?{image:$.info,refusal:null,version:Z}:{image:null,refusal:$.refusal,version:Z}}function s4($,Z){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:$,totalLines:0,media:Z}}function R6($,Z){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:$,totalLines:0,media:Z}}function s0($,Z){let K=$.toString("utf-8"),V=K.split(`
51
- `),Q=!1;if(V.length>i4)K=V.slice(0,i4).join(`
52
- `),Q=!0;return{content:K,binary:!1,truncated:Q,tooLarge:!1,size:Z,totalLines:V.length}}async function r0($,Z){let K=await $.stat();if(!K.isFile())throw new $Z(Z);let V=K.size;if(V>x$)return R6(V);let{head:Q,result:Y}=await a0($,V),X=i0(Y,`${V}-${K.mtimeMs}`);if(Y.ok)return s4(V,X);if(V>l0)return R6(V,a$(Q)?X:void 0);let J=Q.length>=V?Q:Buffer.concat([Q,await S6($,V-Q.length,Q.length)]);return a$(J)?s4(V,X):s0(J,V)}async function t4($,Z){let K=e$.join($,Z),V=await B$.promises.stat(K);if(!V.isFile())throw new $Z(Z);if(V.size>x$)return R6(V.size);let Q=await B$.promises.open(K,o0);try{return await r0(Q,Z)}finally{await Q.close()}}function e4($,Z){let{registry:K,symbols:V}=Z;async function Q(Y,X,J){if(!J)return Y;if(Y.binary||Y.tooLarge)return Y;if(V===null)return{...Y,symbols:{status:"unavailable",reason:"error"}};if(!V.pool.supported(X))return{...Y,symbols:{status:"unsupported",reason:"language"}};let W=V.gate.acquire();if(W===null)throw new O(503,"Symbol extraction busy");try{return{...Y,symbols:await V.pool.extract(X,Y.content)}}finally{(await W)()}}$.get("/repos/:id/tree",async({params:Y,query:X,res:J})=>{let W=I(K,Y.id),z=X.get("dir")??"",U=m(X,"hidden",!1),j=m(X,"ignored",!1),G=z===""?"":C$(W.path,z);await N$(W,G);let M=await K$(W.manager.workingTree),C=q6(M.files),H;try{H=await r4(W.path,G,{hideHidden:!U,hideGitignored:!j},C)}catch(q){let S=L6(q);if(S==="ENOENT")throw new O(404,`No such directory: ${z||"/"}`);if(S==="ENOTDIR")throw new O(400,`Not a directory: ${z}`);throw q}let D=H.filter((q)=>!I6(q.name));B(J,200,await b4(W.path,D))}),$.get("/repos/:id/file",async({params:Y,query:X,res:J})=>{let W=I(K,Y.id),z=X.get("path");if(!z)throw new O(400,'Missing "path" query parameter');let U=C$(W.path,z);await N$(W,U);try{let j=await t4(W.path,U);B(J,200,await Q(j,U,m(X,"symbols",!1)))}catch(j){if(j instanceof $Z)throw new O(400,j.message);let G=L6(j);if(G==="ENOENT"||G==="ENOTDIR")throw new O(404,`No such file: ${z}`);throw j}}),$.get("/repos/:id/files",async({params:Y,res:X})=>{let J=I(K,Y.id);B(X,200,await E8(J.path))})}import{execFile as t0}from"node:child_process";import{promisify as e0}from"node:util";var $9=e0(t0),wZ=3,Z9=20,$5=500,K9=500,V9=4194304,Q9=5000,Z5=400,Y9=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"];class kZ extends Error{constructor(){super(`Query must be at least ${wZ} characters`);this.name="GrepQueryTooShortError"}}class m$ extends Error{constructor($){super($);this.name="GrepQueryInvalidError"}}var K5={matches:[],capped:!1,incomplete:!1,binarySkipped:0};function X9($){return $===$.toLowerCase()}function v6($){return Buffer.from($).toString("utf8")}function J9($,Z){let K=$.indexOf(0,Z);if(K===-1)return null;let V=$.indexOf(0,K+1);if(V===-1)return null;let Q=$.indexOf(10,V+1);if(Q===-1)Q=$.length;return{pathBytes:$.subarray(Z,K),lineBytes:$.subarray(K+1,V),contentBytes:$.subarray(V+1,Q),next:Q+1}}function V5($,Z=K9){let K=[],V=new Map,Q=0,Y=!1,X=0;while(X<$.length){let J=J9($,X);if(J===null)break;if(X=J.next,J.contentBytes.includes(0)){Q+=1;continue}let W=Number.parseInt(v6(J.lineBytes),10);if(!Number.isSafeInteger(W)||W<1)continue;if(K.length>=Z){Y=!0;break}let z=v6(J.pathBytes),U=V.get(z)??0;if(U>=Z9){Y=!0;continue}V.set(z,U+1);let j=v6(J.contentBytes),G=j.length>Z5;K.push({path:z,line:W,text:G?j.slice(0,Z5):j,truncated:G})}return{matches:K,capped:Y,incomplete:!1,binarySkipped:Q}}function W9($){return[...Y9,"grep","--no-textconv","--no-recurse-submodules","--full-name","--no-color","--no-column","-I","-n","-z","-F",...X9($)?["-i"]:[],"-e",$,"--untracked","--","."]}async function Q5($,Z){if(Z.length<wZ)throw new kZ;if(Z.length>$5)throw new m$(`Query must be at most ${$5} characters`);if(Z.includes("\x00"))throw new m$("Query cannot contain a NUL byte");if(Z.includes(`
53
- `))throw new m$("Query cannot span lines — this searches for literal text");try{let{stdout:K}=await $9("git",W9(Z),{cwd:$,env:f(),encoding:"buffer",maxBuffer:V9,timeout:Q9,windowsHide:!0});return V5(K)}catch(K){let V=K;if(V.code===1)return K5;if(V.killed===!0||V.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...V.stdout?V5(V.stdout):K5,incomplete:!0};throw K}}function Y5($,Z){let{registry:K}=Z;$.post("/repos/:id/search",async({params:V,body:Q,res:Y})=>{let X=I(K,V.id),J=u(Q,"query");try{let W=await Q5(X.path,J);B(Y,200,W)}catch(W){if(W instanceof kZ)throw new O(400,`Query must be at least ${wZ} characters`);if(W instanceof m$)throw new O(400,W.message);throw W}})}import{Worker as z9}from"node:worker_threads";var U9=1000,j9=64,G9={status:"unavailable",reason:"deadline"},ZZ={status:"unavailable",reason:"error"};function M9(){let $=import.meta.url;return $.endsWith(".ts")?new URL("./symbolWorker.ts",$):new URL("./symbolWorker.js",$)}function X5($){let Z=$.timeoutMs??U9,K=new Set($.extensions),V=null,Q=0,Y=Promise.resolve(),X=!1,J=new Map;function W(G,M){J.delete(G),J.set(G,M);while(J.size>j9){let C=J.keys().next().value;if(C===void 0)break;J.delete(C)}}function z(){let G=V;if(V=null,G!==null)G.terminate()}function U(){let G=new z9(M9(),{workerData:{grammarDir:$.grammarDir,queryDir:$.queryDir}});return G.unref(),G}function j(G,M){return new Promise((C)=>{if(V===null)try{V=U()}catch{C(ZZ);return}let H=V,D=++Q,q=!1,S=(F,Q$)=>{if(q)return;if(q=!0,clearTimeout(A),H.off("message",R),H.off("error",v),H.off("exit",N),Q$)z();C(F)},R=(F)=>{if(F.seq!==D)return;S(F.outcome,!1)},v=()=>S(ZZ,!0),N=()=>S(ZZ,!0),A=setTimeout(()=>S(G9,!0),Z);A.unref?.(),H.on("message",R),H.on("error",v),H.on("exit",N);let T={seq:D,relPath:G,content:M};try{H.postMessage(T)}catch{S(ZZ,!0)}})}return{supported(G){let M=G.lastIndexOf(".");if(M<=G.lastIndexOf("/"))return!1;return K.has(G.slice(M).toLowerCase())},async extract(G,M){if(X)return ZZ;let C=`${G}\x00${M}`,H=J.get(C);if(H!==void 0)return W(C,H),H;let D=Y.then(()=>j(G,M));Y=D.catch(()=>{return});let q=await D;return W(C,q),q},async dispose(){X=!0;let G=V;if(V=null,J.clear(),G!==null)await G.terminate()}}}import{execFile as O9,spawn as H9}from"node:child_process";import*as KZ from"node:fs";import*as W5 from"node:path";import{promisify as C9}from"node:util";var N9=C9(O9);class g$ extends Error{constructor($){super(`Not a regular blob: ${$}`);this.name="NotRegularBlobError"}}class c$ extends Error{size;constructor($,Z){super(`Blob too large: ${$} (${Z} bytes)`);this.name="BlobTooLargeError",this.size=Z}}class A$ extends Error{constructor($){super(`Unsafe blob path: ${$}`);this.name="UnsafeBlobPathError"}}var z5=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"],U5=5000,EZ=65536,j5=/^[0-9a-f]{40}([0-9a-f]{24})?$/,B9=new Set(["100644","100755"]);function A9($){if($==="")throw new A$("empty");if($.includes("\x00"))throw new A$("contains NUL");if($.startsWith("-"))throw new A$('starts with "-"');if($.startsWith(":"))throw new A$('starts with ":"')}async function _Z($,Z,K){let{stdout:V}=await N9("git",[...z5,...Z],{cwd:$,env:f(),encoding:"buffer",maxBuffer:K,timeout:U5,windowsHide:!0});return V}function G5($){let Z=[],K=0;for(let V=0;V<$.length;V++){if($[V]!==0)continue;if(V>K)Z.push($.subarray(K,V));K=V+1}if(K<$.length)Z.push($.subarray(K));return Z}function M5($,Z){let K=Buffer.from(Z,"utf8");for(let V of $){let Q=V.indexOf(9);if(Q<0)continue;if(!V.subarray(Q+1).equals(K))continue;return V.subarray(0,Q).toString("utf8").trim().split(/\s+/)}return null}var I9=1;async function L9($){let Z;try{Z=(await _Z($,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],EZ)).toString("utf8").trim()}catch(K){if(K?.code===I9)return null;throw K}return j5.test(Z)?Z:null}async function T9($,Z){let K=await L9($);if(K===null)return null;let V=await _Z($,["ls-tree","-z","--full-tree","-l",K,"--",Z],EZ),Q=M5(G5(V),Z);if(Q===null||Q.length!==4)return null;return{mode:Q[0],oid:Q[2],sizeText:Q[3]}}async function D9($,Z){let K=await _Z($,["ls-files","--stage","-z","--",Z],EZ),V=M5(G5(K),Z);if(V===null||V.length!==3)return null;if(V[2]!=="0")return null;return{mode:V[0],oid:V[1],sizeText:null}}function O5($,Z){let K=Number.parseInt($,10);if(!Number.isSafeInteger(K)||K<0)throw Error(`git reported a malformed size for ${Z}`);return K}async function F9($,Z,K){let V=await _Z($,["cat-file","-s",Z],EZ);return O5(V.toString("utf8").trim(),K)}var J5=Buffer.alloc(0);async function q9($,Z,K){let V=Buffer.alloc(K),Q=0;while(Q<K){let{bytesRead:Y}=await $.read(V,Q,K-Q,Z+Q);if(Y===0)break;Q+=Y}return Q===K?V:V.subarray(0,Q)}function H5($,Z){let K=J5,V=!1;return{async read(Q){let Y=Math.max(0,Math.min(Q,$));if(Y>K.length&&!V){let X=await Z(Y,K);V=X.length<Y,K=X}return K.subarray(0,Math.min(Y,K.length))},release(){K=J5,V=!1}}}function S9($,Z){let K=null,V=[],Q=0,Y=!1,X=null,J=null,W=!1,z=null,U=()=>Y&&X!==null,j=()=>{if(V.length!==1){let H=Buffer.concat(V,Q);V.length=0,V.push(H)}return V[0]};function G(){if(z===null)return;if(J===null&&U()&&X?.signal===null&&X.code!==0)J=Error(`git cat-file blob failed for ${Z} (exit ${X.code??"null"})`);if(J===null&&Q<z.want&&!U())return;let H=z;if(z=null,clearTimeout(H.timer),K?.stdout?.pause(),J!==null)H.reject(J);else H.resolve(j().subarray(0,Math.min(H.want,Q)))}function M(H){J??=H,G()}function C(){let H=H9("git",[...z5,"cat-file","blob",Z],{cwd:$,env:f(),stdio:["ignore","pipe","ignore"],windowsHide:!0});K=H,H.stdout?.on("data",(D)=>{if(W)return;V.push(D),Q+=D.length,G()}),H.stdout?.on("end",()=>{Y=!0,G()}),H.stdout?.on("error",M),H.on("error",M),H.on("close",(D,q)=>{X={code:D,signal:q},G()})}return{read(H){if(J!==null)return Promise.reject(J);if(W)return Promise.reject(Error(`read after close for ${Z}`));if(H<=Q||U())return Promise.resolve(j().subarray(0,Math.min(H,Q)));if(z!==null)return Promise.reject(Error(`concurrent read of ${Z}`));return new Promise((D,q)=>{let S=setTimeout(()=>{K?.kill("SIGKILL"),M(Error(`git cat-file blob timed out for ${Z}`))},U5);if(z={want:H,resolve:D,reject:q,timer:S},K===null)C();else K.stdout?.resume()})},release(){if(W=!0,z!==null)M(Error(`git cat-file blob closed while reading ${Z}`));V.length=0,Q=0,K?.kill("SIGKILL"),K=null}}}function R9($){let Z=$?.code;return Z==="ENOENT"||Z==="ENOTDIR"}async function v9($,Z,K){let V=W5.join($,Z),Q;try{Q=await KZ.promises.open(V,KZ.constants.O_RDONLY|(KZ.constants.O_NONBLOCK??0))}catch(Y){if(R9(Y))return null;throw Y}try{let Y=await Q.stat();if(!Y.isFile())throw new g$(Z);if(Y.size>K)throw new c$(Z,Y.size);let X=Y.size,J=H5(X,async(W,z)=>{let U=await q9(Q,z.length,W-z.length);return z.length===0?U:Buffer.concat([z,U])});return{oid:null,size:X,version:`${X}-${Y.mtimeMs}`,read:(W)=>J.read(W),close:()=>{return J.release(),Q.close()}}}catch(Y){try{await Q.close()}catch{}throw Y}}async function w9($,Z,K,V){let Q=Z==="head"?await T9($,K):await D9($,K);if(Q===null)return null;if(!B9.has(Q.mode))throw new g$(K);if(!j5.test(Q.oid))throw Error(`git reported a malformed object id for ${K}`);let Y=Q.oid,X=Q.sizeText===null?await F9($,Y,K):O5(Q.sizeText,K);if(X>V)throw new c$(K,X);let J=S9($,Y),W=H5(X,(z)=>J.read(z));return{oid:Y,size:X,version:Y,read:(z)=>W.read(z),close(){return W.release(),J.release(),Promise.resolve()}}}async function C5($,Z,K,V){if(A9(K),Z==="worktree")return v9($,K,V);return w9($,Z,K,V)}var k9=["worktree","index","head"],E9=16,_9=d4,P9=x$,x9=["too-large","too-many-pixels"];function N5($){let Z=$.get("path");if(Z===null)throw new O(400,'Missing "path" query parameter');return Z}function b9($){let Z=$.get("side");if(Z===null||!k9.includes(Z))throw new O(400,'Invalid "side" (expected worktree, index or head)');return Z}function y9($){let Z=$.get("staged");if(Z==="1")return!0;if(Z==="0")return!1;throw new O(400,'Invalid "staged" (expected 0 or 1)')}function L5($){if($ instanceof g$)throw new O(400,$.message);if($ instanceof A$)throw new O(400,$.message);if($ instanceof c$)throw new O(413,$.message);throw $}async function B5($,Z){let K=await $.read(Z);return{bytes:K,sniff:y$(K,$.size,K.length>=$.size)}}async function m9($,Z){let{size:K}=$,V=await $.read(E9),Q=y$(V,K,V.length>=K);if(!Q.ok&&Q.refusal==="too-large")return{bytes:V,sniff:Q};let Y=Math.min(vZ(V,K),K),X=await B5($,Math.max(Y,Math.min(Z,K)));if(X.sniff.ok||X.sniff.refusal!=="header-not-found")return X;if(X.bytes.length>=K)return X;return B5($,K)}async function T5($,Z,K,V){let Q=await C5($,Z,K,x$);if(Q===null)return null;try{let{bytes:Y,sniff:X}=await m9(Q,V);return{bytes:Y,size:Q.size,oid:Q.oid,version:Q.version,sniff:X}}finally{await Q.close()}}function g9($,Z,K){let V={"content-type":Z,"content-disposition":"inline","x-content-type-options":"nosniff","cross-origin-resource-policy":"same-origin",vary:"sec-fetch-site, sec-fetch-dest","cache-control":$==="worktree"?"no-store":"private, no-cache"};if($!=="worktree"&&K!==null)V.etag=`"${K}"`;return V}function c9($){let Z=x9.includes($)?413:415;return new O(Z,`Image not served: ${$}`)}function u9($,Z){let K=$.originalPath??$.path;switch($.status){case"untracked":return{old:null,new:{side:"worktree",path:$.path}};case"added":return{old:null,new:{side:Z?"index":"worktree",path:$.path}};case"deleted":return{old:{side:Z?"head":"index",path:K},new:null};default:return Z?{old:{side:"head",path:K},new:{side:"index",path:$.path}}:{old:{side:"index",path:K},new:{side:"worktree",path:$.path}}}}function p9($,Z,K){return{path:$.path,side:$.side,bytes:Z,oid:null,image:null,refusal:K,version:""}}async function A5($,Z){let K=C$($.path,Z.path);await N$($,K);let V;try{V=await T5($.path,Z.side,K,_9)}catch(Q){if(Q instanceof c$)return p9(Z,Q.size,"too-large");if(Q instanceof g$)return null;L5(Q)}if(V===null)return null;return{path:Z.path,side:Z.side,bytes:V.size,oid:V.oid,version:V.version,image:V.sniff.ok?V.sniff.info:null,refusal:V.sniff.ok?null:V.sniff.refusal}}function f9($,Z){return Z.writableEnded||Z.destroyed===!0||$.destroyed===!0}async function I5($,Z,K){let V=$.acquire();if(V===null)throw new O(503,"Too many image requests in flight");let Q=await V;if(K.once("finish",Q),K.once("close",Q),Z.once("close",Q),f9(Z,K))return Q(),!1;return!0}function D5($,Z,K){let{registry:V}=Z;$.get("/repos/:id/media",async({params:Q,query:Y,req:X,res:J})=>{let W=I(V,Q.id),z=y9(Y),U=C$(W.path,N5(Y));if(await N$(W,U),!await I5(K,X,J))return;let j=await E$(W.manager.workingTree,U,z),G=u9(j,z),M={old:G.old===null?null:await A5(W,G.old),new:G.new===null?null:await A5(W,G.new)};B(J,200,M)}),$.get("/repos/:id/blob",async({params:Q,query:Y,req:X,res:J})=>{let W=I(V,Q.id),z=n6(X);if(z)throw new O(z.status,z.message);let U=b9(Y),j=C$(W.path,N5(Y));if(await N$(W,j),!await I5(K,X,J))return;let G;try{G=await T5(W.path,U,j,P9)}catch(C){L5(C)}if(G===null)throw new O(404,`No such blob on side ${U}: ${j}`);if(!G.sniff.ok)throw c9(G.sniff.refusal);let M=g9(U,G.sniff.info.mime,G.oid);g6(J,200,G.bytes,M)})}function F5($,Z){let{registry:K,sse:V,daemonEvents:Q,follow:Y}=Z;$.get("/events",({req:X,res:J,query:W})=>{let z=K.listRepos().map((j)=>({id:j.id,path:j.path}));Q.subscribe(X,J,z);let U=W.get("repo");if(!U)return;V.attach(U,K.getRepo(U)?.manager??null,X,J)}),$.get("/follow",({res:X})=>{B(X,200,Y?Y.state:O4)})}import*as w6 from"node:os";import*as u$ from"node:path";function q5($,Z){let{settings:K,discovery:V,daemonEvents:Q}=Z;$.get("/settings",({res:Y})=>{B(Y,200,{...K.settings,persisted:K.persisted})}),$.put("/settings",async({body:Y,res:X})=>{let J=k4(Y,"watchRoots"),W;try{W=C4(J)}catch(U){throw new O(400,U instanceof Error?U.message:String(U))}try{K.save({...K.settings,watchRoots:W})}catch(U){let j=U instanceof Error?U.message:String(U);throw new O(500,`Could not save settings: ${j}`)}await V.setRoots(W);let z={...K.settings,persisted:K.persisted};Q.broadcast("settings-change",z),B(X,200,z)}),$.get("/discovered",({res:Y})=>{B(Y,200,V.state)}),$.get("/browse",async({query:Y,res:X})=>{let J=Y.get("path"),W=J?l(J):w6.homedir();if(!u$.isAbsolute(W))throw new O(400,`Path must be absolute: ${J}`);let z=u$.resolve(W),U;try{U=await B4(z)}catch{throw new O(404,`Cannot read directory: ${z}`)}let j=u$.dirname(z);B(X,200,{path:z,parent:j===z?null:j,home:w6.homedir(),entries:U})}),$.post("/discovered/rescan",async({res:Y})=>{B(Y,200,await V.rescan())})}function k6($=4,Z=64){let K=0,V=[];function Q(){let Y=!1;return()=>{if(Y)return;Y=!0;let X=V.shift();if(X)X(Q());else K--}}return{acquire(){if(K<$)return K++,Promise.resolve(Q());if(V.length>=Z)return null;return new Promise((Y)=>{V.push(Y)})},get active(){return K},get queued(){return V.length}}}function h9($){if(!I$.existsSync($))return Promise.resolve(!1);return new Promise((Z)=>{try{let K=R5.connect($);K.once("connect",()=>{K.destroy(),Z(!0)}),K.once("error",()=>{K.destroy(),Z(!1)})}catch{Z(!1)}})}function v5($={}){let Z=new W6,K=new z6,V=new J6({onOpened:(N)=>K.broadcast("repo-opened",{id:N.id,path:N.path}),onClosed:(N)=>{Z.closeRepo(N),K.broadcast("repo-closed",{id:N})}}),Q=$.followFile?new j6(V,K,$.followFile):null,Y=q4($.updateCheck===!1?()=>Promise.resolve(null):$.fetchLatestVersion),X=new M6($.settingsFile??null),J=new H6(K),W=new Map,z=k6(),U=$.symbols??null,j=U===null?null:{pool:X5(U),gate:k6(1,4),extensions:U.extensions};function G(N){let A=W.get(N);if(A)return A;let T=new pZ,F={registry:V,sse:Z,daemonEvents:K,follow:Q,settings:X,discovery:J,apiMode:N,version:Y,symbols:j,httpPort:q};if(R4(T,F),v4(T,F),y4(T,F),c4(T,F),p4(T,F),f4(T,F),N==="full")h4(T,F);return e4(T,F),Y5(T,F),D5(T,F,z),F5(T,F),q5(T,F),W.set(N,T),T}let M=(N)=>$.apiMode??(N==="tcp"?"web":"full");Q?.start(),J.setRoots(X.load().watchRoots);let C=$.webRoot?p6($.webRoot):void 0,H=new Set,D=[];function q(){for(let N of D){let A=N.server.address();if(A!==null&&typeof A==="object")return A.port}return null}function S(N){let A=G(N),T=S5.createServer((F,Q$)=>{for(let[J$,VZ]of Object.entries(o6))Q$.setHeader(J$,VZ);if(d6(T.address())){let J$=l6(F);if(J$){B(Q$,J$.status,{error:J$.message});return}}A.handle(F,Q$,C).catch(()=>Q$.end())});return T.on("connection",(F)=>{H.add(F),F.on("close",()=>H.delete(F))}),T}async function R(N,A){let T=N==="unix"?A.socketPath??null:null;if(T){if(await h9(T))throw Error(`diffstalkerd already running at ${T}`);I$.rmSync(T,{force:!0})}let F={server:S(M(N)),socketPath:T};D.push(F),await new Promise((Q$,J$)=>{let VZ=(g5)=>J$(g5);F.server.once("error",VZ);let xZ=()=>{if(F.server.removeListener("error",VZ),T)I$.chmodSync(T,384);Q$()};if(N==="fd")F.server.listen({fd:A.fd},xZ);else if(T)process.umask(63),F.server.listen(T,xZ);else F.server.listen(A.port,"127.0.0.1",xZ)})}function v(N){return new Promise((A,T)=>{N.server.close((F)=>{if(N.socketPath)I$.rmSync(N.socketPath,{force:!0});if(F&&F.code!=="ERR_SERVER_NOT_RUNNING")T(F);else A()})})}return{address(){return D[0]?.server.address()??null},addresses(){return D.map((N)=>N.server.address()).filter((N)=>N!==null)},getRepo(N){return V.getRepo(N)},async openRepo(N){let{handle:A}=await FZ(V,N);return{id:A.id,path:A.path}},async listen(N){let A=[];if(N.fd!==void 0)A.push("fd");if(N.socketPath)A.push("unix");if(N.port!==void 0)A.push("tcp");if(A.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let T of A)await R(T,N)},close(){Q?.dispose(),J.dispose(),Z.destroy(),K.destroy(),V.disposeAll();for(let A of H)A.destroy();let N=j?.pool.dispose()??Promise.resolve();return Promise.all([N,...D.splice(0).map(v)]).then(()=>{})}}}import*as E6 from"node:fs";import*as p$ from"node:path";import*as x5 from"node:crypto";import{createRequire as l9}from"node:module";var w5=new Map([[".ts",{grammar:"typescript",container:null}],[".mts",{grammar:"typescript",container:null}],[".cts",{grammar:"typescript",container:null}],[".vue",{grammar:"typescript",container:"vue"}],[".js",{grammar:"javascript",container:null}],[".mjs",{grammar:"javascript",container:null}],[".cjs",{grammar:"javascript",container:null}],[".jsx",{grammar:"javascript",container:null}],[".java",{grammar:"java",container:null}]]);function k5(){return[...w5.keys()]}function d9($){let Z=$.slice($.lastIndexOf("/")+1),K=Z.lastIndexOf(".");if(K<=0)return"";return Z.slice(K).toLowerCase()}function E5($){return w5.get(d9($))??null}var n9="diffstalkerd-grammars";function o9($){return x5.createHash("sha256").update($).digest("hex")}function a9($){try{let Z=JSON.parse(E6.readFileSync(p$.join($,"checksums.json"),"utf8"));if(typeof Z.webTreeSitterVersion!=="string"||typeof Z.files!=="object")return null;return Z}catch{return null}}var _5="0.26.11";function i9($,Z,K){for(let[V,Q]of Object.entries(Z.files)){let Y;try{Y=E6.readFileSync(p$.join($,V))}catch{return K(`grammars: missing ${V}`),!1}if(o9(Y)!==Q)return K(`grammars: checksum mismatch for ${V}`),!1}return!0}function s9($){let Z=new Set;for(let K of Object.keys($.files)){let V=/^tree-sitter-(.+)\.wasm$/.exec(K);if(V!==null&&$.files[`queries/${V[1]}.scm`]!==void 0)Z.add(V[1])}return Z}function P5($,Z=()=>{}){let K=a9($);if(K===null)return Z(`grammars: no readable checksums.json in ${$}`),null;if(K.webTreeSitterVersion!==_5)return Z(`grammars: built for web-tree-sitter ${K.webTreeSitterVersion}, this daemon bundles ${_5} — symbols disabled`),null;if(!i9($,K,Z))return null;let V=s9(K),Q=k5().filter((Y)=>{let X=E5(`x${Y}`);return X!==null&&V.has(X.grammar)});if(Q.length===0)return Z("grammars: no usable grammar found"),null;return{grammarDir:$,queryDir:p$.join($,"queries"),extensions:Q}}function b5($,Z=()=>{}){if($!==null)return P5($,Z);try{let V=l9(import.meta.url).resolve(`${n9}/checksums.json`);return P5(p$.dirname(V),Z)}catch{return null}}var m5="diffstalkerd.sock";function t9($){return $===void 0?m5:`${$}.sock`}var e9=3,y5=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
37
+ `)},zs),this.keepAlive.unref();t.on("close",()=>{if(this.subscribers.delete(e),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),$t(e,"snapshot",JSON.stringify(n))}broadcast(t,e){let n=JSON.stringify(e);for(let r of this.subscribers)$t(r,t,n)}destroy(){if(this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null;for(let t of this.subscribers)t.end();this.subscribers.clear()}}import*as yt from"node:fs";import*as Oe from"node:path";import{watch as Pc}from"chokidar";import{EventEmitter as Mc}from"node:events";class $n extends Mc{targetFile;watcher=null;debounceTimer=null;lastReadPath=null;_state={path:null,rawContent:null};constructor(t){super();this.targetFile=t}get state(){return this._state}updateState(t){this._state={...this._state,...t},this.emit("path-change",this._state)}processContent(t){if(!t)return null;let e=J(t);return Oe.isAbsolute(e)?e:Oe.resolve(e)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let t=yt.readFileSync(this.targetFile,"utf-8"),e=tn(t);if(e&&e!==this.lastReadPath){let n=this.processContent(e);this.lastReadPath=n,this.updateState({path:n,rawContent:e})}}catch(t){if(t.code==="ENOENT")return;k("Cannot read the follow hook file",t,{file:this.targetFile})}}start(){if(ye(this.targetFile),!yt.existsSync(this.targetFile))yt.writeFileSync(this.targetFile,"");try{let t=yt.readFileSync(this.targetFile,"utf-8"),e=tn(t);if(e){let n=this.processContent(e);this.lastReadPath=n,this._state={path:n,rawContent:e}}}catch(t){k("Cannot read the follow hook file",t,{file:this.targetFile})}this.watcher=Pc(this.targetFile,{persistent:!0,ignoreInitial:!0}),this.watcher.on("change",()=>this.readTargetDebounced()),this.watcher.on("add",()=>this.readTargetDebounced()),this.watcher.on("error",(t)=>{k("Follow hook file watcher error",t,{file:this.targetFile})})}stop(){if(this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.watcher)this.watcher.close().catch((t)=>{k("Failed to close the follow hook file watcher",t,{file:this.targetFile})}),this.watcher=null}}var Ys={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class On{registry;hub;targetFile;watcher;followedRepoId=null;followedPath=null;disposed=!1;queue=Promise.resolve();constructor(t,e,n){this.registry=t,this.hub=e,this.targetFile=n,this.watcher=new $n(n)}get state(){return{targetFile:this.targetFile,enabled:!0,followedRepoId:this.followedRepoId,followedPath:this.followedPath}}start(){if(this.watcher.on("path-change",(t)=>this.enqueue(t)),this.watcher.start(),this.watcher.state.path)this.enqueue(this.watcher.state)}enqueue(t){this.queue=this.queue.then(()=>this.follow(t)).catch((e)=>{F("Follow switch threw",e,{path:t.path})})}async follow(t){if(this.disposed||!t.path)return;let e;try{e=await this.registry.openRepo(t.path)}catch(n){L("Follow target ignored",n,{path:t.path});return}if(this.disposed){this.registry.closeRepo(e.handle.id);return}if(e.created)Mn(e.handle);if(e.handle.id===this.followedRepoId)this.registry.closeRepo(e.handle.id);else{let n=this.followedRepoId;if(this.followedRepoId=e.handle.id,this.followedPath=e.handle.path,n)this.registry.closeRepo(n)}this.hub.broadcast("follow-change",{repoId:e.handle.id,path:t.path,rawContent:t.rawContent})}dispose(){if(this.disposed)return;if(this.disposed=!0,this.watcher.stop(),this.followedRepoId)this.registry.closeRepo(this.followedRepoId),this.followedRepoId=null,this.followedPath=null}}import*as U from"node:fs";import*as Ot from"node:path";function Ks(){return{watchRoots:[]}}var Nn=16;function Fc(t){let e=t.trim();if(!e)throw Error("Watch directory cannot be empty");let n=J(e);if(!Ot.isAbsolute(n))throw Error(`Watch directory must be absolute: ${t}`);let r=Ot.resolve(n),s;try{s=U.statSync(r)}catch{throw Error(`No such directory: ${r}`)}if(!s.isDirectory())throw Error(`Not a directory: ${r}`);return r}function Vs(t){if(t.length>Nn)throw Error(`Too many watch directories (max ${Nn})`);let e=new Set,n=[];for(let r of t){let s=Fc(r);if(e.has(s))continue;e.add(s),n.push(s)}return n}function Tc(t){let e=Ks();if(typeof t!=="object"||t===null)return e;let n=t;if(Array.isArray(n.watchRoots))e.watchRoots=n.watchRoots.filter((r)=>typeof r==="string").slice(0,Nn);return e}class Cn{file;current=Ks();constructor(t){this.file=t}get settings(){return this.current}get persisted(){return this.file!==null}load(){if(!this.file)return this.current;let t;try{t=U.readFileSync(this.file,"utf-8")}catch(e){if(e.code!=="ENOENT")F("Cannot read the settings file; running with defaults",e,{file:this.file});return this.current}try{this.current=Tc(JSON.parse(t))}catch(e){k("Ignoring the settings file: not valid JSON",e,{file:this.file})}return this.current}save(t){if(this.current=t,!this.file)return this.current;U.mkdirSync(Ot.dirname(this.file),{recursive:!0});let e=`${this.file}.${process.pid}.tmp`;try{U.writeFileSync(e,`${JSON.stringify(this.current,null,2)}
38
+ `,{mode:384}),U.renameSync(e,this.file)}catch(n){throw U.rmSync(e,{force:!0}),n}return this.current}}import*as eo from"node:path";import{watch as Gc}from"chokidar";import*as V from"node:fs/promises";import*as B from"node:path";var $c=2,Oc=500,Nc=new Set(["node_modules","vendor","target","dist","build","venv","__pycache__"]);async function Qs(t){try{return await V.stat(B.join(t,".git")),!0}catch{return!1}}async function Cc(t){let e=B.join(t,".git"),n;try{n=await V.stat(e)}catch{return null}if(n.isDirectory())return e;try{let r=await V.readFile(e,"utf-8"),s=/^gitdir:\s*(.+)$/m.exec(r);if(!s)return null;let o=s[1].trim(),i=B.isAbsolute(o)?o:B.resolve(t,o);return await V.stat(i),i}catch{return null}}async function Lc(t){let e;try{e=(await V.readFile(B.join(t,"HEAD"),"utf-8")).trim()}catch{return null}let n=/^ref:\s*refs\/heads\/(.+)$/.exec(e);if(n)return n[1].trim();if(/^[0-9a-f]{40}$/i.test(e))return e.slice(0,7);return null}async function Hc(t){let n=(await Promise.all(["index","HEAD"].map(async(r)=>{try{return(await V.stat(B.join(t,r))).mtimeMs}catch{return null}}))).filter((r)=>r!==null);return n.length===0?null:Math.max(...n)}async function Bc(t){let e=await Cc(t);if(e===null)return null;let[n,r]=await Promise.all([Lc(e),Hc(e)]);return{path:t,name:B.basename(t),branch:n,lastActivity:r}}function Wc(t){if(!t.isDirectory())return!1;if(t.name.startsWith("."))return!1;return!Nc.has(t.name)}async function Zs(t){let e=await Ln(t);return Promise.all(e.map(async(n)=>({name:B.basename(n),path:n,isRepo:await Qs(n)})))}async function Ln(t){return(await V.readdir(t,{withFileTypes:!0})).filter(Wc).map((n)=>B.join(t,n.name)).sort()}async function jc(t,e,n){let r=[],s=[];for(let o of t){if(r.length>=n)return{repos:r,next:s,capped:!0};if(await Qs(o)){r.push(o);continue}if(!e)continue;try{s.push(...await Ln(o))}catch{}}return{repos:r,next:s,capped:!1}}async function to(t,e={}){let n=e.depth??$c,r=e.limit??Oc,s=await Ln(t),o=[],i=!1;for(let c=1;c<=n&&s.length>0&&!i;c++){let l=await jc(s,c<n,r-o.length);o.push(...l.repos),i=l.capped,s=l.next.sort()}return{repos:(await Promise.all(o.map(Bc))).filter((c)=>c!==null),capped:i}}var Uc=300;function qc(t){let e=eo.basename(t);return e.startsWith(".")&&e!=="."||e==="node_modules"}class Hn{hub;roots=new Map;disposed=!1;constructor(t){this.hub=t}get state(){return{roots:[...this.roots.values()].map((t)=>t.state)}}async setRoots(t){if(this.disposed)return;for(let[r,s]of this.roots)if(!t.includes(r))this.teardown(s),this.roots.delete(r);let e=[],n=new Map;for(let r of t){let s=this.roots.get(r);if(s){n.set(r,s);continue}n.set(r,{state:{path:r,repos:[],error:null,capped:!1},watcher:null,timer:null}),e.push(r)}this.roots=n,await Promise.all(e.map((r)=>this.scan(r)));for(let r of e)this.startWatching(r);this.broadcast()}async rescan(){return await Promise.all([...this.roots.keys()].map((t)=>this.scan(t))),this.broadcast(),this.state}dispose(){this.disposed=!0;for(let t of this.roots.values())this.teardown(t);this.roots.clear()}teardown(t){if(t.timer)clearTimeout(t.timer);t.timer=null,t.watcher?.close().catch((e)=>{k("Failed to close a watch directory watcher",e,{root:t.state.path})}),t.watcher=null}async scan(t){let e=this.roots.get(t);if(!e)return;try{let n=await to(t);e.state={path:t,repos:n.repos,error:null,capped:n.capped}}catch(n){k("Watch directory scan failed",n,{root:t}),e.state={path:t,repos:[],error:n instanceof Error?n.message:String(n),capped:!1}}}startWatching(t){let e=this.roots.get(t);if(!e||e.watcher)return;let n=Gc(t,{persistent:!0,ignoreInitial:!0,depth:1,ignored:qc});n.on("error",(r)=>{k("Watch directory watcher error",r,{root:t}),e.state={...e.state,error:r instanceof Error?r.message:String(r)},this.broadcast()}),n.on("addDir",()=>this.scheduleRescan(t)),n.on("unlinkDir",()=>this.scheduleRescan(t)),e.watcher=n}scheduleRescan(t){let e=this.roots.get(t);if(!e)return;if(e.timer)clearTimeout(e.timer);e.timer=setTimeout(()=>{e.timer=null,this.scan(t).then(()=>this.broadcast())},Uc),e.timer.unref?.()}broadcast(){if(this.disposed)return;this.hub.broadcast("discovery-change",this.state)}}import*as oo from"node:fs";import{execFile as Xc}from"node:child_process";import*as ft from"node:fs";import*as ot from"node:path";import{fileURLToPath as zc}from"node:url";var no={method:"unknown",package:null,command:null},ue="diffstalkerd",Jc=3000,Yc=["paru","yay"],Kc=[{method:"bun",pattern:/\/install\/global\/node_modules\/diffstalkerd$/,command:`bun add -g ${ue}`},{method:"pnpm",pattern:/\/pnpm\/global\/\d+\/node_modules\/diffstalkerd$/,command:`pnpm add -g ${ue}`},{method:"yarn",pattern:/\/yarn\/global\/node_modules\/diffstalkerd$/,command:`yarn global add ${ue}`},{method:"npm",pattern:/\/lib\/node_modules\/diffstalkerd$/,command:`npm install -g ${ue}`}];async function Vc(t,e){let n=t.split(ot.sep).join("/").replace(/\/+$/,"");for(let s of Kc){if(!s.pattern.test(n))continue;let o=e.writable(t)?"":"sudo ";return{method:s.method,package:ue,command:`${o}${s.command}`}}let r=await e.pacmanOwner(ot.join(t,"package.json"));if(r!==null){let s=e.onPath(Yc);return{method:"pacman",package:r,command:s?`${s} -S ${r}`:`sudo pacman -Syu ${r}`}}return no}var Qc={onPath(t){let e=(process.env.PATH??"").split(ot.delimiter).filter(Boolean);for(let n of t)for(let r of e)try{return ft.accessSync(ot.join(r,n),ft.constants.X_OK),n}catch{}return null},pacmanOwner(t){return new Promise((e)=>{Xc("pacman",["-Qoq","--",t],{timeout:Jc},(n,r)=>{if(n)return e(null);let s=r.trim().split(`
39
+ `)[0]?.trim();e(s?s:null)})})},writable(t){try{return ft.accessSync(t,ft.constants.W_OK),!0}catch{return!1}}};function Zc(){let t=ot.dirname(zc(new URL("../package.json",import.meta.url)));try{return ft.realpathSync(t)}catch{return t}}function ro(t=Zc(),e=Qc){let n=null;return{info(){return n??=Vc(t,e).catch((r)=>(k("Install detection failed",r,{dir:t}),no)),n}}}var tl="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",el=21600000,nl=300000,rl=5000;function Bn(){try{let t=oo.readFileSync(new URL("../package.json",import.meta.url),"utf-8"),e=JSON.parse(t);return typeof e.version==="string"?e.version:null}catch(t){return k("Cannot read the daemon version from its package.json",t),null}}async function sl(){let t=await fetch(tl,{headers:{accept:"application/json"},signal:AbortSignal.timeout(rl)});if(!t.ok)return null;let e=await t.json();return typeof e.latest==="string"?e.latest:null}function so(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());if(!e)return null;return[Number(e[1]),Number(e[2]),Number(e[3])]}function ol(t,e){if(t===null||e===null)return"unknown";let n=so(t),r=so(e);if(!n||!r)return"unknown";for(let s=0;s<n.length;s++){if(n[s]<r[s])return"outdated";if(n[s]>r[s])return"ahead"}return"current"}function io(t=sl,e=Bn(),n=ro()){let r=null,s=null;function o(){if(r&&Date.now()<r.expiresAt)return Promise.resolve(r.value);if(s)return s;return s=t().catch((i)=>(L("Latest version lookup failed",i),null)).then((i)=>{let a=i===null?nl:el;return r={value:i,expiresAt:Date.now()+a},s=null,i}),s}return{async state(){let[i,a]=await Promise.all([o(),n.info()]);return{current:e,latest:i,status:ol(e,i),install:a}}}}import*as ao from"node:os";function co(t,e){t.get("/health",({res:n})=>{S(n,200,{ok:!0,ready:!0,home:ao.homedir(),http:{port:e.httpPort()},symbols:{extensions:e.symbols?.extensions??[]}})})}function lo(t,e){t.get("/version",async({res:n})=>{S(n,200,await e.version.state())})}import*as So from"node:fs";import*as Nt from"node:fs";import*as O from"node:path";function Ct(t,e){let n=t.getRepo(e);if(!n)throw new m(404,`Unknown repo id: ${e}`);return n}function R(t,e){let n=Ct(t,e),r=n.manager.workingTree.unavailable;if(r!==null)throw new m(410,r);return n}function q(t,e,n){if(typeof t!=="object"||t===null)throw new m(400,`Expected a JSON body with "${e}"`);let r=t[e];if(typeof r!=="string"||!n?.allowEmpty&&r.length===0)throw new m(400,`Missing "${e}" (string) in body`);return r}function fo(t,e){if(t.length===0)throw new m(400,`Invalid "${e}" (expected a ref)`);if(t.startsWith("-"))throw new m(400,`Invalid "${e}" (must not start with "-"): ${t}`);return t}function bt(t,e){return fo(q(t,e),e)}function Gn(t,e){let n=t.get(e);return n===null?null:fo(n,e)}function ho(t,e){if(typeof t!=="object"||t===null)throw new m(400,`Expected a JSON body with "${e}"`);let n=t[e];if(!Array.isArray(n)||n.some((r)=>typeof r!=="string"))throw new m(400,`Missing "${e}" (array of strings) in body`);return n}function po(t,e){if(typeof t!=="object"||t===null)return;let n=t[e];if(n===void 0)return;if(typeof n!=="string"||n.length===0)throw new m(400,`Invalid "${e}" (expected a non-empty string)`);return n}function Un(t,e,n){if(typeof t!=="object"||t===null)return n.fallback;let r=t[e];if(r===void 0)return n.fallback;if(typeof r!=="number"||!Number.isInteger(r)||r<n.min)throw new m(400,`Invalid "${e}" (expected an integer >= ${n.min})`);return r}function mo(t,e){if(typeof t!=="object"||t===null)return!1;let n=t[e];if(n===void 0)return!1;if(typeof n!=="boolean")throw new m(400,`Invalid "${e}" (expected a boolean)`);return n}function W(t,e,n){let r=t.get(e);if(r===null){if(n===void 0)throw new m(400,`Missing "${e}" query parameter (expected true or false)`);return n}if(r==="true")return!0;if(r==="false")return!1;throw new m(400,`Invalid "${e}" (expected true or false): ${r}`)}function Q(t){let e=t.get("path");if(!e)throw new m(400,'Missing "path" query parameter');return e}function fe(t,e){let n=W(t,"whole",!1);if(n&&!e)throw new m(400,"whole=true requires a path (one file at a time)");return n?hs:void 0}function go(t,e,n,r){let s=t.get(e);if(s===null)return n;let o=Number(s);if(!Number.isInteger(o)||o<1)throw new m(400,`Invalid "${e}" (expected a positive integer): ${s}`);if(r!==void 0&&o>r)throw new m(400,`Invalid "${e}" (must be <= ${r}): ${s}`);return o}async function it(t){if(!t.state.status)await t.refresh();let e=t.state.status;if(!e)throw new m(500,"Repository status unavailable");return e}function uo(t,e,n){let r=t.files.filter((s)=>s.path===e);if(r.length===0)return null;return r.find((s)=>s.staged===n)??r[0]}async function Lt(t,e,n){let r=await it(t),s=uo(r,e,n);if(!s)await t.refresh(),r=await it(t),s=uo(r,e,n);if(!s)throw new m(404,`File not in status: ${e}`);return s}function jn(t,e){return t===e||t.startsWith(e+O.sep)}function qn(t){return t.replace(/[. ]+$/,"").toLowerCase()===".git"}function St(t,e){if(e.length===0)throw new m(400,"Empty path");if(e.includes("\x00"))throw new m(400,"Path contains a NUL byte");let n=O.resolve(t),r=O.relative(n,O.resolve(n,e));if(r==="")throw new m(400,`Path resolves to the repository root: ${e}`);if(O.isAbsolute(r)||r===".."||r.startsWith(`..${O.sep}`))throw new m(400,`Path escapes repository root: ${e}`);if(r.startsWith("-"))throw new m(400,`Path must not start with "-": ${e}`);if(r.startsWith(":"))throw new m(400,`Path must not start with ":": ${e}`);if(r.split(O.sep).some(qn))throw new m(400,`Path addresses the git directory: ${e}`);return r}async function wo(t){try{return await Nt.promises.realpath(t)}catch{return null}}var Wn=new WeakMap;async function il(t){let e=Wn.get(t);if(!e)e=(async()=>{let n=await E(t.path).raw(["rev-parse","--absolute-git-dir"]);return await Nt.promises.realpath(n.trim())})(),Wn.set(t,e),e.catch(()=>Wn.delete(t));try{return await e}catch(n){throw new m(500,"Cannot resolve the git directory for this repository",{cause:n})}}async function Et(t,e){let n=await Nt.promises.realpath(O.resolve(t.path)),r=await wo(O.join(t.path,e));if(r===null)return;if(!jn(r,n))throw new m(400,`Path escapes repository root: ${e}`);if(jn(r,await il(t)))throw new m(400,`Path addresses the git directory: ${e}`)}async function yo(t,e){let n=await Nt.promises.realpath(O.resolve(t)),r=[];for(let s of e){let o=await wo(O.join(t,s.path));if(o===null||jn(o,n))r.push(s)}return r}function Ne(t){return t?.code??null}async function Xn(t){let e;try{e=await Nt.promises.stat(t)}catch(n){let r=Ne(n);if(r==="ENOENT"||r==="ENOTDIR")return null;throw n}if(e.isDirectory())return"a directory";if(e.isFile())return"a file";if(e.isFIFO())return"a FIFO";if(e.isSocket())return"a socket";return"a device"}function al(t){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test(t)?409:500}function bo(t,e){return new m(t,e)}async function at(t,e,n){t.clearError(),await n();let r=t.state.error;if(r)throw bo(al(r),r);await t.refresh(),S(e,200,{state:lt(t.state)})}var cl=/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged|no tracking information|no upstream|no configured push destination/i;function ll(t){return cl.test(t)?409:500}async function j(t,e,n){let r=t.manager.remote,s=()=>new m(409,`A ${r.remoteState.operation??"remote"} operation is already in progress`);if(r.remoteState.inProgress)throw s();let o=await n();if(o===null)throw s();let i=t.manager.workingTree;if(await i.refresh(),o.error)throw bo(ll(o.error),o.error);S(e,200,{state:lt(i.state),result:o.lastResult})}function ul(t){if(t.reason==="not-a-repo"&&!So.existsSync(t.requested))return new m(404,`No such directory: ${t.requested}`,{cause:t});return new m(400,t.message,{cause:t})}function Eo(t,e){let{registry:n}=e;t.get("/repos",({res:r})=>{let s=n.listRepos().map((o)=>({id:o.id,path:o.path,branch:o.manager.workingTree.state.status?.branch.current??null}));S(r,200,s)}),t.post("/repos",async({body:r,res:s})=>{let o=q(r,"path"),i;try{i=await $e(n,o)}catch(a){if(a instanceof Te)throw ul(a);throw a}S(s,i.created?201:200,{id:i.handle.id,path:i.handle.path})}),t.get("/resolve",async({query:r,res:s})=>{let o=Q(r),i=await _e(o,{mustExist:!0});if(!i.ok&&i.reason==="not-absolute")throw new m(400,`Repo path must be absolute: ${i.requested}`);S(s,200,{openable:i.ok,root:i.ok?i.root:null})}),t.get("/repos/:id/worktrees",async({params:r,res:s})=>{let o=R(n,r.id);S(s,200,await En(o.path))}),t.get("/worktrees",async({query:r,res:s})=>{S(s,200,await En(Q(r)))}),t.delete("/repos/:id",({params:r,res:s})=>{Ct(n,r.id),n.closeRepo(r.id),S(s,200,{})})}function xo(t,e,n){if(!t.trim())return{valid:!1,error:"Commit message cannot be empty"};if(e===0&&!n)return{valid:!1,error:"No changes staged for commit"};return{valid:!0,error:null}}function vo(t){return t.trim()}async function fl(t){let e=(r)=>r.filter((s)=>s.staged).length,n=e((await it(t)).files);if(n===0)await t.refresh(),n=e((await it(t)).files);return n}function ko(t,e){let{registry:n,sse:r}=e;if(t.get("/repos/:id/status",async({params:s,res:o})=>{let i=Ct(n,s.id);await it(i.manager.workingTree),S(o,200,lt(i.manager.workingTree.state))}),t.get("/repos/:id/diff",async({params:s,query:o,res:i})=>{let a=R(n,s.id),c=o.get("path")??void 0,l=W(o,"staged",!1),u=fe(o,c),f,h=!1;if(c){let d=(await it(a.manager.workingTree)).files.some((p)=>p.path===c&&p.status==="untracked");if(d&&l)throw new m(400,`staged=true is meaningless for untracked file: ${c} (untracked files have no staged diff)`);h=u!==void 0&&!d,f=d?await wt(a.path,c):await Tt(a.path,c,l,{context:u})}else f=await Tt(a.path,void 0,l);if(!h)a.manager.workingTree.stampDiff(f);S(i,200,f)}),t.post("/repos/:id/stage",async({params:s,body:o,res:i})=>{let a=R(n,s.id),c=q(o,"path"),l=a.manager.workingTree,u=await Lt(l,c,!1);await at(l,i,()=>l.stage(u))}),t.post("/repos/:id/unstage",async({params:s,body:o,res:i})=>{let a=R(n,s.id),c=q(o,"path"),l=a.manager.workingTree,u=await Lt(l,c,!0);await at(l,i,()=>l.unstage(u))}),t.get("/repos/:id/events",({params:s,req:o,res:i})=>{let a=Ct(n,s.id);r.subscribe(s.id,a.manager,o,i)}),e.apiMode==="full")hl(t,e)}function hl(t,e){let{registry:n}=e;t.post("/repos/:id/stage-all",async({params:r,res:s})=>{let i=R(n,r.id).manager.workingTree;await at(i,s,()=>i.stageAll())}),t.post("/repos/:id/unstage-all",async({params:r,res:s})=>{let i=R(n,r.id).manager.workingTree;await at(i,s,()=>i.unstageAll())}),t.post("/repos/:id/discard",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"path"),c=i.manager.workingTree,l=await Lt(c,a,!1);if(l.staged)throw new m(409,`Cannot discard a staged file: ${a} (unstage it first)`);await at(c,o,()=>c.discard(l))}),t.post("/repos/:id/commit",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"message",{allowEmpty:!0}),c=mo(s,"amend"),l=i.manager.workingTree,u=await fl(l),f=xo(a,u,c);if(!f.valid)throw new m(400,f.error??"Invalid commit");await at(l,o,()=>l.commit(vo(a),c))}),t.post("/repos/:id/stage-hunk",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"patch"),c=i.manager.workingTree;await at(c,o,()=>c.stageHunk(a))}),t.post("/repos/:id/unstage-hunk",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"patch"),c=i.manager.workingTree;await at(c,o,()=>c.unstageHunk(a))})}var dl=1000,Ce="refs/heads/",Ro="refs/remotes/";async function _o(t,e,n){let r=["for-each-ref","--format=%(objectname) %(refname) %(symref)",`--no-merged=${e}`];if(n!==void 0)r.push(`--contains=${n}`);r.push("refs/heads","refs/remotes");let s=await t.raw(r),o=[];for(let i of s.split(`
40
+ `)){if(!i)continue;let[a,c,l]=i.split(" ");if(l)continue;if(c.startsWith(Ce))o.push({tip:a,name:c.slice(Ce.length),local:!0});else if(c.startsWith(Ro))o.push({tip:a,name:c.slice(Ro.length),local:!1})}return o}function pl(t){return new Map(t.filter((e)=>e.local).map((e)=>[e.name,e.tip]))}function Ao(t,e){return t.filter((n)=>{if(n.local)return!0;let r=e.get(n.name.slice(n.name.indexOf("/")+1));return r===void 0||r===n.tip})}async function Io(t,e,n){return(await t.raw(["rev-list","--first-parent",`--max-count=${dl}`,"--end-of-options",`${e}..${n}`])).split(`
41
+ `).filter(Boolean).reverse()}async function ml(t){let e=await t.raw(["rev-parse","HEAD","--symbolic-full-name","HEAD"]),[n,r]=e.split(`
42
+ `),s=r.startsWith(Ce)?r.slice(Ce.length):null;return{tip:n,name:s??"HEAD",branch:s}}async function gl(t,e){if(e.length<2)return e;return(await t.raw(["merge-base","--independent","--end-of-options",...e])).split(`
43
+ `).filter(Boolean)}function wl(t,e){if(t.length===0)return null;let n=t.filter((i)=>i.local).map((i)=>i.name).sort(),r=t.filter((i)=>!i.local).map((i)=>i.name).sort(),s=[...n,...r];return{name:e!==null&&n.includes(e)?e:s.find((i)=>!i.startsWith("-"))??s[0],refs:s}}function Do(t,e,n){let r=[],s=-1;for(let o=0;o<t.length;o++){let i=t[o],a=i===n?.tip,c=wl(e.get(i)??[],n?.branch??null)??(a?{name:n.name,refs:[]}:null);if(c===null)continue;r.push({...c,tip:i,commits:o-s,isHead:a}),s=o}return r}async function yl(t,e,n,r,s){let o=Ao(await _o(t,e,n),r).filter((l)=>l.tip!==n),i=[...new Set(o.map((l)=>l.tip))];if(i.length===0)return{layers:[],forked:!1};let a=await gl(t,i);if(a.length!==1)return{layers:[],forked:!0};let c=await Io(t,n,a[0]);return{layers:Do(c,s,null),forked:!1}}async function Po(t,e){let n=E(t),r=await ml(n),s=(await n.raw(["merge-base","--end-of-options",e,r.tip])).trim();if(!s)return{trunk:e,layers:[],forkedAbove:!1};let[o,i]=await Promise.all([_o(n,e),Io(n,s,r.tip)]),a=pl(o),c=new Map;for(let f of Ao(o,a)){let h=c.get(f.tip);if(h)h.push(f);else c.set(f.tip,[f])}let l=Do(i,c,r);if(!l.some((f)=>f.isHead))l.push({name:r.name,refs:[],tip:r.tip,commits:0,isHead:!0});let u=await yl(n,e,r.tip,a,c);return{trunk:e,layers:[...l,...u.layers],forkedAbove:u.forked}}function zn(t){if(!/^[0-9a-f]{4,40}$/i.test(t))throw new m(400,`Invalid commit hash: ${t}`);return t}async function Mo(t,e){if(!await st(t,e))throw new m(404,`Unknown commit: ${e}`)}async function Fo(t){try{return await t()}catch(e){if(e instanceof ae)throw new m(422,e.message,{cause:e});throw e}}async function bl(t){let e=await yn(t);if(e&&await st(t,e))return e;if(Mt(t)){let n=await ce(t);if(n&&await st(t,n))return n}throw new m(422,"No usable base branch")}async function Le(t,e){let n=Gn(e,"base");if(n===null)return bl(t);if(!await st(t,n))throw new m(400,`Unknown base ref: ${n}`);return n}async function Jn(t,e){let n=Gn(e,"head");if(n===null)return;if(!await st(t,n))throw new m(400,`Unknown head ref: ${n}`);return n}function To(t,e){if(e&&t.get("head")!==null)throw new m(400,"head cannot be combined with uncommitted work (it only exists against HEAD)")}var Sl=new Set(["staged","unstaged","both","untracked"]);function El(t){let e=t.get("uncommitted");if(e===null)return null;if(!Sl.has(e))throw new m(400,`Invalid "uncommitted" (expected staged, unstaged, both or untracked): ${e}`);return e}function xl(t){return{staged:W(t,"staged",!1),unstaged:W(t,"unstaged",!1),untracked:W(t,"untracked",!1)}}function $o(t,e){let{registry:n}=e;if(t.get("/repos/:id/history",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=go(s,"count",100,5000);S(o,200,await Yr(i.path,a))}),t.get("/repos/:id/commits/:hash",async({params:r,res:s})=>{let o=R(n,r.id),i=zn(r.hash),a=await Kr(o.path,i);if(a===null)throw new m(404,`Unknown commit: ${i}`);S(s,200,a)}),t.get("/repos/:id/commits/:hash/diff",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=zn(r.hash);await Mo(i.path,a);let c=s.get("path")??void 0,l=fe(s,c),u=c?await bn(i.path,{kind:"commit",hash:a},c,{context:l}):await Ss(i.path,a);S(o,200,u)}),t.get("/repos/:id/commits/:hash/files",async({params:r,res:s})=>{let o=R(n,r.id),i=zn(r.hash);await Mo(o.path,i),S(s,200,await bs(o.path,i))}),t.get("/repos/:id/compare/file",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=Q(s),c=fe(s,a),l=El(s);if(To(s,l!==null),l==="untracked"){S(o,200,await wt(i.path,a));return}let u=l===null?{kind:"compare",base:await Le(i.path,s),head:await Jn(i.path,s)}:{kind:l==="both"?"head":l};S(o,200,await bn(i.path,u,a,{context:c}))}),t.get("/repos/:id/head-message",async({params:r,res:s})=>{let o=R(n,r.id);S(s,200,{message:await jr(o.path)})}),t.get("/repos/:id/branches",async({params:r,res:s})=>{let o=R(n,r.id);S(s,200,await Zr(o.path))}),t.get("/repos/:id/base-branches",async({params:r,res:s})=>{let o=R(n,r.id);S(s,200,await wn(o.path))}),t.get("/repos/:id/compare/base",async({params:r,res:s})=>{let o=R(n,r.id);S(s,200,{base:await yn(o.path)})}),e.apiMode==="full")t.put("/repos/:id/compare/base",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=bt(s,"branch");if(!await st(i.path,a))throw new m(400,`Not a valid base ref: ${a}`);ls(i.path,a),S(o,200,{base:a})});t.get("/repos/:id/compare/count",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=await Le(i.path,s),c=await Jn(i.path,s),l=await Fo(()=>ys(i.path,a,c));S(o,200,{baseBranch:a,commits:l})}),t.get("/repos/:id/compare/stack",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=await Le(i.path,s);S(o,200,await Po(i.path,a))}),t.get("/repos/:id/compare",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=xl(s);To(s,a.staged||a.unstaged||a.untracked);let c=await Le(i.path,s),l=await Jn(i.path,s),u=await Fo(()=>Es(i.path,c,a,l));S(o,200,u)})}function vl(t){let e=t.get("since");if(e===null)return 0;if(!/^\d+$/.test(e))throw new m(400,`Invalid "since" (expected a non-negative integer): ${e}`);return Number(e)}function Oo(t,e){let{registry:n}=e;t.get("/repos/:id/journal",({params:r,query:s,res:o})=>{let i=R(n,r.id),a=vl(s);S(o,200,hr(i.manager.journal.journalStore,a))})}function No(t,e){let{registry:n}=e;t.post("/repos/:id/push",async({params:r,res:s})=>{let o=R(n,r.id);await j(o,s,()=>o.manager.remote.push())}),t.post("/repos/:id/fetch",async({params:r,res:s})=>{let o=R(n,r.id);await j(o,s,()=>o.manager.remote.fetchRemote())}),t.post("/repos/:id/pull",async({params:r,res:s})=>{let o=R(n,r.id);await j(o,s,()=>o.manager.remote.pullRebase())}),t.post("/repos/:id/stash",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=po(s,"message");await j(i,o,()=>i.manager.remote.stash(a))}),t.post("/repos/:id/stash-pop",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=Un(s,"index",{min:0,fallback:0});await j(i,o,()=>i.manager.remote.stashPop(a))}),t.post("/repos/:id/switch-branch",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=bt(s,"name");await j(i,o,()=>i.manager.remote.switchBranch(a))}),t.post("/repos/:id/create-branch",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=bt(s,"name");await j(i,o,()=>i.manager.remote.createBranch(a))}),t.post("/repos/:id/soft-reset",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=Un(s,"count",{min:1,fallback:1});if(!await st(i.path,`HEAD~${a}`))throw new m(400,`Cannot soft-reset ${a} commit(s): HEAD~${a} does not exist`);await j(i,o,()=>i.manager.remote.softReset(a))}),t.post("/repos/:id/cherry-pick",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=bt(s,"hash");await j(i,o,()=>i.manager.remote.cherryPick(a))}),t.post("/repos/:id/revert",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=bt(s,"hash");await j(i,o,()=>i.manager.remote.revertCommit(a))}),t.post("/repos/:id/abort",async({params:r,res:s})=>{let o=R(n,r.id);if(!await Pt(o.path))throw new m(409,"No operation in progress to abort");await j(o,s,()=>o.manager.remote.abortOperation())}),t.post("/repos/:id/rebase-continue",async({params:r,res:s})=>{let o=R(n,r.id);if(await Pt(o.path)!=="rebase")throw new m(409,"No rebase in progress to continue");await j(o,s,()=>o.manager.remote.rebaseContinue())})}import*as Ge from"node:fs";import*as he from"node:path";import*as Yn from"node:fs";var He=Yn.constants.O_RDONLY|(Yn.constants.O_NONBLOCK??0);async function Ht(t,e,n){let r=Buffer.alloc(n),s=0;while(s<n){let{bytesRead:o}=await t.read(r,s,n-s,e+s);if(o===0)break;s+=o}return s===n?r:r.subarray(0,s)}var jt=8388608;var Co=65536;function Bt(t){return Array.from(t,(e)=>e.charCodeAt(0))}function Wt(t,e,n){if(e+n.length>t.length)return!1;for(let r=0;r<n.length;r++)if(t[e+r]!==n[r])return!1;return!0}function Be(t,e){return t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function Kn(t,e){return(t[e]<<8)+t[e+1]}function We(t,e){return t[e]+(t[e+1]<<8)}function Lo(t,e){return String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3])}function P(t){return{ok:!1,refusal:t}}function Gt(t){return P(t?"malformed":"header-not-found")}function Vn(t,e){if(t<1||e<1)return"malformed";if(t>8192||e>8192)return"too-many-pixels";if(t*e>16777216)return"too-many-pixels";return null}var kl=[137,80,78,71,13,10,26,10],Rl=[255,216,255],_l=Bt("GIF87a"),Al=Bt("GIF89a"),Z=Bt("ftyp");function z(t){return{offset:8,bytes:Bt(t)}}var Il=[{label:"webp",offset:0,bytes:Bt("RIFF"),brand:z("WEBP")},{label:"avif",offset:4,bytes:Z,brand:z("avif")},{label:"avis",offset:4,bytes:Z,brand:z("avis")},{label:"heic",offset:4,bytes:Z,brand:z("heic")},{label:"heix",offset:4,bytes:Z,brand:z("heix")},{label:"heim",offset:4,bytes:Z,brand:z("heim")},{label:"heis",offset:4,bytes:Z,brand:z("heis")},{label:"hevc",offset:4,bytes:Z,brand:z("hevc")},{label:"hevx",offset:4,bytes:Z,brand:z("hevx")},{label:"mif1",offset:4,bytes:Z,brand:z("mif1")},{label:"msf1",offset:4,bytes:Z,brand:z("msf1")},{label:"tiff-le",offset:0,bytes:[73,73,42,0]},{label:"tiff-be",offset:0,bytes:[77,77,0,42]},{label:"bmp",offset:0,bytes:Bt("BM")},{label:"ico",offset:0,bytes:[0,0,1,0]},{label:"cur",offset:0,bytes:[0,0,2,0]},{label:"jxl-codestream",offset:0,bytes:[255,10]},{label:"jxl-container",offset:0,bytes:[0,0,0,12,74,88,76,32,13,10,135,10]}];function Dl(t){return Il.some((e)=>Wt(t,e.offset,e.bytes)&&(e.brand===void 0||Wt(t,e.brand.offset,e.brand.bytes)))}var Pl={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},Ml=26;function Fl(t,e,n){if(t.length<Ml)return Gt(n);if(Be(t,8)!==13)return P("malformed");if(Lo(t,12)!=="IHDR")return P("malformed");let r=Be(t,16),s=Be(t,20),o=Vn(r,s);if(o)return P(o);let i=Pl[t[25]];if(!i||!i.includes(t[24]))return P("malformed");let a=Tl(t,n);if(a)return a;return{ok:!0,info:{format:"png",mime:"image/png",width:r,height:s,bytes:e}}}function Tl(t,e){let n=8;for(let r=0;r<256;r++){if(n+8>t.length)return Gt(e);let s=Be(t,n),o=Lo(t,n+4);if(o==="IDAT")return null;if(o==="acTL")return P("animation");if(o==="iCCP"&&s>65536)return P("malformed");let i=n+12+s;if(i<=n||!Number.isSafeInteger(i))return P("malformed");n=i}return P("malformed")}var $l=218,Ol=226,Nl=new Set([219,238,192,193,194,196]);function Cl(t){return t>=224&&t<=239||Nl.has(t)}function Ll(t){return t===1||t>=208&&t<=217}function Hl(t){return t>=192&&t<=207&&t!==196&&t!==200&&t!==204}var Bl=new Set([192,193,194]);function Wl(t,e,n){if(t.length<4)return Gt(n);if(!Cl(t[3]))return P("malformed");return Ul(t,e,n)}function jl(t,e,n,r,s){if(!Bl.has(n))return P("malformed");if(e+9>t.length)return Gt(s);let o=Kn(t,e+5),i=Kn(t,e+7),a=Vn(i,o);if(a)return P(a);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:i,height:o,bytes:r}}}function Gl(t,e){if(e+1>=t.length)return{kind:"ran-out"};if(t[e]!==255)return{kind:"malformed"};let n=t[e+1];if(n===255)return{kind:"skip",next:e+1};if(Ll(n))return{kind:"skip",next:e+2};if(n===$l)return{kind:"malformed"};if(e+4>t.length)return{kind:"ran-out"};let r=Kn(t,e+2);if(r<2)return{kind:"malformed"};if(Hl(n))return{kind:"sof",marker:n};return{kind:"segment",marker:n,length:r}}function Ul(t,e,n){let r=2,s=0;for(let o=0;o<1024;o++){let i=Gl(t,r);if(i.kind==="ran-out")return Gt(n);if(i.kind==="malformed")return P("malformed");if(i.kind==="sof")return jl(t,r,i.marker,e,n);if(i.kind==="skip"){r=i.next;continue}if(i.marker===Ol){if(s+=i.length-2,s>65536)return P("malformed")}r+=2+i.length}return P("malformed")}var ql=59,Xl=44,zl=33;function Ho(t){return(t&128)===0?0:3*(1<<(t&7)+1)}function Jl(t,e,n){if(e>2097152)return P("too-large");if(!n)return P("header-not-found");if(t.length<13)return Gt(n);let r=We(t,6),s=We(t,8),o=Vn(r,s);if(o)return P(o);let i={pos:13+Ho(t[10]),left:8192,pixels:0,overBudget:!1},a=Yl(t,i);if(a===null)return P("malformed");if(a<1)return P("malformed");if(a>256)return P("too-many-pixels");if(i.overBudget)return P("too-many-pixels");if(a*r*s>33554432)return P("too-many-pixels");let c={format:"gif",mime:"image/gif",width:r,height:s,bytes:e};if(a>1)c.frames=a;return{ok:!0,info:c}}function Yl(t,e){let n=0;while(e.left-- >0){if(e.pos>=t.length)return null;let r=t[e.pos];if(r===ql)return n;let s=r===Xl;if(!(s?Vl(t,e):Kl(t,e,r)))return null;if(s&&++n>256)return n;if(e.overBudget)return n}return null}function Kl(t,e,n){if(n!==zl)return!1;return e.pos+=2,Bo(t,e)}function Vl(t,e){if(e.pos+10>t.length)return!1;Ql(e,We(t,e.pos+5),We(t,e.pos+7));let n=t[e.pos+9];return e.pos+=10+Ho(n)+1,Bo(t,e)}function Ql(t,e,n){let r=e*n;if(e>8192||n>8192||r>16777216){t.overBudget=!0;return}if(t.pixels+=r,t.pixels>33554432)t.overBudget=!0}function Bo(t,e){while(e.left-- >0){if(e.pos>=t.length)return!1;let n=t[e.pos];if(e.pos+=1+n,n===0)return e.pos<=t.length}return!1}function Wo(t){return Wt(t,0,_l)||Wt(t,0,Al)}function Ut(t,e,n){if(e>8388608)return P("too-large");if(Wt(t,0,kl))return Fl(t,e,n);if(Wt(t,0,Rl))return Wl(t,e,n);if(Wo(t))return Jl(t,e,n);if(Dl(t))return P("unsupported-format");return P("not-an-image")}function je(t,e){return Wo(t)?Math.min(e,2097152):65536}function Qn(t){let e={files:new Map,directories:new Set};for(let n of t){e.files.set(n.path,{status:n.status,staged:n.staged});let r=n.path.split("/"),s="";for(let o=0;o<r.length-1;o++)s=s?`${s}/${r[o]}`:r[o],e.directories.add(s);e.directories.add("")}return e}var Zl=1048576,jo=5000;class de extends Error{constructor(t){super(`Not a regular file: ${t}`);this.name="NotRegularFileError"}}async function Uo(t,e,n,r){let s=n?.hideHidden??!0,o=n?.hideGitignored??!0,i=he.join(t,e),a=await Ge.promises.readdir(i,{withFileTypes:!0}),c=a.map((f)=>e?he.join(e,f.name):f.name),l=o?await _t(t,c):new Set,u=[];for(let f of a){if(s&&f.name.startsWith("."))continue;let h=e?he.join(e,f.name):f.name;if(o&&l.has(h))continue;let g=f.isDirectory(),d={name:f.name,path:h,type:g?"dir":"file"};if(r)if(g){if(r.directories.has(h))d.hasChanges=!0}else{let p=r.files.get(h);if(p)d.gitStatus=p.status,d.staged=p.staged}u.push(d)}return u.sort((f,h)=>{if(f.type==="dir"&&h.type!=="dir")return-1;if(f.type!=="dir"&&h.type==="dir")return 1;return f.name.localeCompare(h.name)}),u}var tu=16;async function eu(t,e){let n=await Ht(t,0,Math.min(tu,e)),r=Ut(n,e,n.length>=e);if(!r.ok&&r.refusal==="too-large")return{head:n,result:r};let s=Math.min(je(n,e),e),o=s<=n.length?n.subarray(0,s):Buffer.concat([n,await Ht(t,n.length,s-n.length)]);return{head:o,result:Ut(o,e,o.length>=e)}}function nu(t,e){return t.ok?{image:t.info,refusal:null,version:e}:{image:null,refusal:t.refusal,version:e}}function Go(t,e){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:t,totalLines:0,media:e}}function Zn(t,e){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:t,totalLines:0,media:e}}function ru(t,e){let n=t.toString("utf-8"),r=n.split(`
44
+ `),s=!1;if(r.length>jo)n=r.slice(0,jo).join(`
45
+ `),s=!0;return{content:n,binary:!1,truncated:s,tooLarge:!1,size:e,totalLines:r.length}}async function su(t,e){let n=await t.stat();if(!n.isFile())throw new de(e);let r=n.size;if(r>jt)return Zn(r);let{head:s,result:o}=await eu(t,r),i=nu(o,`${r}-${n.mtimeMs}`);if(o.ok)return Go(r,i);if(r>Zl)return Zn(r,oe(s)?i:void 0);let a=s.length>=r?s:Buffer.concat([s,await Ht(t,s.length,r-s.length)]);return oe(a)?Go(r,i):ru(a,r)}async function qo(t,e){let n=he.join(t,e),r=await Ge.promises.stat(n);if(!r.isFile())throw new de(e);if(r.size>jt)return Zn(r.size);let s=await Ge.promises.open(n,He);try{return await su(s,e)}finally{await s.close()}}import*as tr from"node:path";function Xo(t,e){let{registry:n,symbols:r}=e;async function s(o,i,a){if(!a)return o;if(o.binary||o.tooLarge)return o;if(r===null)return{...o,symbols:{status:"unavailable",reason:"error"}};if(!r.pool.supported(i))return{...o,symbols:{status:"unsupported",reason:"language"}};let c=r.gate.acquire();if(c===null)throw new m(503,"Symbol extraction busy");try{return{...o,symbols:await r.pool.extract(i,o.content)}}finally{(await c)()}}t.get("/repos/:id/tree",async({params:o,query:i,res:a})=>{let c=R(n,o.id),l=i.get("dir")??"",u=W(i,"hidden",!1),f=W(i,"ignored",!1),h=l===""?"":St(c.path,l);await Et(c,h);let g=await it(c.manager.workingTree),d=Qn(g.files),p;try{p=await Uo(c.path,h,{hideHidden:!u,hideGitignored:!f},d)}catch(v){let A=Ne(v);if(A==="ENOENT"||A==="ENOTDIR"){let I=await Xn(tr.join(c.path,h));if(I===null)throw new m(404,`No such directory: ${l||"/"}`,{cause:v});throw new m(400,`Not a directory (${I}): ${l}`,{cause:v})}throw v}let y=p.filter((v)=>!qn(v.name));S(a,200,await yo(c.path,y))}),t.get("/repos/:id/file",async({params:o,query:i,res:a})=>{let c=R(n,o.id),l=Q(i),u=St(c.path,l);await Et(c,u);try{let f=await qo(c.path,u);S(a,200,await s(f,u,W(i,"symbols",!1)))}catch(f){if(f instanceof de){let g=await Xn(tr.join(c.path,u));throw new m(400,`Not a regular file (${g??"unknown"}): ${l}`,{cause:f})}let h=Ne(f);if(h==="ENOENT"||h==="ENOTDIR")throw new m(404,`No such file: ${l}`,{cause:f});throw f}}),t.get("/repos/:id/files",async({params:o,res:i})=>{let a=R(n,o.id);S(i,200,await as(a.path))})}var Ue=3,ou=20,zo=500,iu=500,au=4194304,Jo=400;class qe extends Error{constructor(){super(`Query must be at least ${Ue} characters`);this.name="GrepQueryTooShortError"}}class qt extends Error{constructor(t){super(t);this.name="GrepQueryInvalidError"}}var Yo={matches:[],capped:!1,incomplete:!1,binarySkipped:0};function cu(t){return t===t.toLowerCase()}function er(t){return Buffer.from(t).toString("utf8")}function lu(t,e){let n=t.indexOf(0,e);if(n===-1)return null;let r=t.indexOf(0,n+1);if(r===-1)return null;let s=t.indexOf(10,r+1);if(s===-1)s=t.length;return{pathBytes:t.subarray(e,n),lineBytes:t.subarray(n+1,r),contentBytes:t.subarray(r+1,s),next:s+1}}function Ko(t,e=iu){let n=[],r=new Map,s=0,o=!1,i=0;while(i<t.length){let a=lu(t,i);if(a===null)break;if(i=a.next,a.contentBytes.includes(0)){s+=1;continue}let c=Number.parseInt(er(a.lineBytes),10);if(!Number.isSafeInteger(c)||c<1)continue;if(n.length>=e){o=!0;break}let l=er(a.pathBytes),u=r.get(l)??0;if(u>=ou){o=!0;continue}r.set(l,u+1);let f=er(a.contentBytes),h=f.length>Jo;n.push({path:l,line:c,text:h?f.slice(0,Jo):f,truncated:h})}return{matches:n,capped:o,incomplete:!1,binarySkipped:s}}function uu(t){return[...ee,"grep","--no-textconv","--no-recurse-submodules","--full-name","--no-color","--no-column","-I","-n","-z","-F",...cu(t)?["-i"]:[],"-e",t,"--untracked","--","."]}async function Vo(t,e){if(e.length<Ue)throw new qe;if(e.length>zo)throw new qt(`Query must be at most ${zo} characters`);if(e.includes("\x00"))throw new qt("Query cannot contain a NUL byte");if(e.includes(`
46
+ `))throw new qt("Query cannot span lines — this searches for literal text");try{return Ko(await be(t,uu(e),au))}catch(n){let r=n;if(r.code===1)return Yo;if(r.killed===!0||r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...r.stdout?Ko(r.stdout):Yo,incomplete:!0};throw n}}function Qo(t,e){let{registry:n}=e;t.post("/repos/:id/search",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"query");try{let c=await Vo(i.path,a);S(o,200,c)}catch(c){if(c instanceof qe)throw new m(400,`Query must be at least ${Ue} characters`,{cause:c});if(c instanceof qt)throw new m(400,c.message,{cause:c});throw c}})}import{Worker as fu}from"node:worker_threads";var hu=1000,du=64,pu={status:"unavailable",reason:"deadline"},pe={status:"unavailable",reason:"error"};function mu(){let t=import.meta.url;return t.endsWith(".ts")?new URL("./symbolWorker.ts",t):new URL("./symbolWorker.js",t)}function Zo(t){let e=t.timeoutMs??hu,n=new Set(t.extensions),r=null,s=0,o=Promise.resolve(),i=!1,a=new Map;function c(h,g){a.delete(h),a.set(h,g);while(a.size>du){let d=a.keys().next().value;if(d===void 0)break;a.delete(d)}}function l(){let h=r;if(r=null,h!==null)h.terminate()}function u(){let h=new fu(mu(),{workerData:{grammarDir:t.grammarDir,queryDir:t.queryDir}});return h.unref(),h}function f(h,g){return new Promise((d)=>{if(r===null)try{r=u()}catch(b){k("Cannot start the symbol worker",b,{path:h}),d(pe);return}let p=r,y=++s,v=!1,A=(b,ct)=>{if(v)return;if(v=!0,clearTimeout(x),p.off("message",I),p.off("error",D),p.off("exit",w),ct)l();d(b)},I=(b)=>{if(b.seq!==y)return;A(b.outcome,!1)},D=(b)=>{k("Symbol worker failed; discarding it",b,{path:h}),A(pe,!0)},w=(b)=>{k(`Symbol worker exited with code ${b}; discarding it`,void 0,{path:h}),A(pe,!0)},x=setTimeout(()=>{k(`Symbol extraction passed its ${e}ms deadline; discarding the worker`,void 0,{path:h}),A(pu,!0)},e);x.unref?.(),p.on("message",I),p.on("error",D),p.on("exit",w);let _={seq:y,relPath:h,content:g};try{p.postMessage(_)}catch(b){k("Cannot send a file to the symbol worker; discarding it",b,{path:h}),A(pe,!0)}})}return{supported(h){let g=h.lastIndexOf(".");if(g<=h.lastIndexOf("/"))return!1;return n.has(h.slice(g).toLowerCase())},async extract(h,g){if(i)return pe;let d=`${h}\x00${g}`,p=a.get(d);if(p!==void 0)return c(d,p),p;let y=o.then(()=>f(h,g));o=y.catch(()=>{return});let v=await y;return c(d,v),v},async dispose(){i=!0;let h=r;if(r=null,a.clear(),h!==null)await h.terminate()}}}import{spawn as gu}from"node:child_process";import*as ei from"node:fs";import*as ni from"node:path";class Xt extends Error{constructor(t){super(`Not a regular blob: ${t}`);this.name="NotRegularBlobError"}}class zt extends Error{size;constructor(t,e){super(`Blob too large: ${t} (${e} bytes)`);this.name="BlobTooLargeError",this.size=e}}class xt extends Error{constructor(t){super(`Unsafe blob path: ${t}`);this.name="UnsafeBlobPathError"}}var Xe=65536,ri=/^[0-9a-f]{40}([0-9a-f]{24})?$/,wu=new Set(["100644","100755"]);function yu(t){if(t==="")throw new xt("empty");if(t.includes("\x00"))throw new xt("contains NUL");if(t.startsWith("-"))throw new xt('starts with "-"');if(t.startsWith(":"))throw new xt('starts with ":"')}function ze(t,e,n){return be(t,[...ee,...e],n)}function si(t){let e=[],n=0;for(let r=0;r<t.length;r++){if(t[r]!==0)continue;if(r>n)e.push(t.subarray(n,r));n=r+1}if(n<t.length)e.push(t.subarray(n));return e}function oi(t,e){let n=Buffer.from(e,"utf8");for(let r of t){let s=r.indexOf(9);if(s<0)continue;if(!r.subarray(s+1).equals(n))continue;return r.subarray(0,s).toString("utf8").trim().split(/\s+/)}return null}var bu=1;async function Su(t){let e;try{e=(await ze(t,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],Xe)).toString("utf8").trim()}catch(n){if(n?.code===bu)return null;throw n}return ri.test(e)?e:null}async function Eu(t,e){let n=await Su(t);if(n===null)return null;let r=await ze(t,["ls-tree","-z","--full-tree","-l",n,"--",e],Xe),s=oi(si(r),e);if(s===null||s.length!==4)return null;return{mode:s[0],oid:s[2],sizeText:s[3]}}async function xu(t,e){let n=await ze(t,["ls-files","--stage","-z","--",e],Xe),r=oi(si(n),e);if(r===null||r.length!==3)return null;if(r[2]!=="0")return null;return{mode:r[0],oid:r[1],sizeText:null}}function ii(t,e){let n=Number.parseInt(t,10);if(!Number.isSafeInteger(n)||n<0)throw Error(`git reported a malformed size for ${e}`);return n}async function vu(t,e,n){let r=await ze(t,["cat-file","-s",e],Xe);return ii(r.toString("utf8").trim(),n)}var ti=Buffer.alloc(0);function ai(t,e){let n=ti,r=!1;return{async read(s){let o=Math.max(0,Math.min(s,t));if(o>n.length&&!r){let i=await e(o,n);r=i.length<o,n=i}return n.subarray(0,Math.min(o,n.length))},release(){n=ti,r=!1}}}function ku(t,e){let n=null,r=[],s=0,o=!1,i=null,a=null,c=!1,l=null,u=()=>o&&i!==null,f=()=>{if(r.length!==1){let p=Buffer.concat(r,s);r.length=0,r.push(p)}return r[0]};function h(){if(l===null)return;if(a===null&&u()&&i?.signal===null&&i.code!==0)a=Error(`git cat-file blob failed for ${e} (exit ${i.code??"null"})`);if(a===null&&s<l.want&&!u())return;let p=l;if(l=null,clearTimeout(p.timer),n?.stdout?.pause(),a!==null)p.reject(a);else p.resolve(f().subarray(0,Math.min(p.want,s)))}function g(p){a??=p,h()}function d(){let p=gu("git",[...ee,"cat-file","blob",e],{cwd:t,env:ut(),stdio:["ignore","pipe","ignore"],windowsHide:!0});n=p,p.stdout?.on("data",(y)=>{if(c)return;r.push(y),s+=y.length,h()}),p.stdout?.on("end",()=>{o=!0,h()}),p.stdout?.on("error",g),p.on("error",g),p.on("close",(y,v)=>{i={code:y,signal:v},h()})}return{read(p){if(a!==null)return Promise.reject(a);if(c)return Promise.reject(Error(`read after close for ${e}`));if(p<=s||u())return Promise.resolve(f().subarray(0,Math.min(p,s)));if(l!==null)return Promise.reject(Error(`concurrent read of ${e}`));return new Promise((y,v)=>{let A=setTimeout(()=>{n?.kill("SIGKILL"),g(Error(`git cat-file blob timed out for ${e}`))},cn);if(l={want:p,resolve:y,reject:v,timer:A},n===null)d();else n.stdout?.resume()})},release(){if(c=!0,l!==null)g(Error(`git cat-file blob closed while reading ${e}`));r.length=0,s=0,n?.kill("SIGKILL"),n=null}}}function Ru(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function _u(t,e,n){let r=ni.join(t,e),s;try{s=await ei.promises.open(r,He)}catch(o){if(Ru(o))return null;throw o}try{let o=await s.stat();if(!o.isFile())throw new Xt(e);if(o.size>n)throw new zt(e,o.size);let i=o.size,a=ai(i,async(c,l)=>{let u=await Ht(s,l.length,c-l.length);return l.length===0?u:Buffer.concat([l,u])});return{oid:null,size:i,version:`${i}-${o.mtimeMs}`,read:(c)=>a.read(c),close:()=>(a.release(),s.close())}}catch(o){try{await s.close()}catch{}throw o}}async function Au(t,e,n,r){let s=e==="head"?await Eu(t,n):await xu(t,n);if(s===null)return null;if(!wu.has(s.mode))throw new Xt(n);if(!ri.test(s.oid))throw Error(`git reported a malformed object id for ${n}`);let o=s.oid,i=s.sizeText===null?await vu(t,o,n):ii(s.sizeText,n);if(i>r)throw new zt(n,i);let a=ku(t,o),c=ai(i,(l)=>a.read(l));return{oid:o,size:i,version:o,read:(l)=>c.read(l),close(){return c.release(),a.release(),Promise.resolve()}}}async function ci(t,e,n,r){if(yu(n),e==="worktree")return _u(t,n,r);return Au(t,e,n,r)}var Iu=["worktree","index","head"],Du=16,Pu=Co,Mu=jt,Fu=["too-large","too-many-pixels"];function Tu(t){let e=t.get("side");if(e===null||!Iu.includes(e))throw new m(400,'Invalid "side" (expected worktree, index or head)');return e}function hi(t){if(t instanceof Xt)throw new m(400,t.message,{cause:t});if(t instanceof xt)throw new m(400,t.message,{cause:t});if(t instanceof zt)throw new m(413,t.message,{cause:t});throw t}async function li(t,e){let n=await t.read(e);return{bytes:n,sniff:Ut(n,t.size,n.length>=t.size)}}async function $u(t,e){let{size:n}=t,r=await t.read(Du),s=Ut(r,n,r.length>=n);if(!s.ok&&s.refusal==="too-large")return{bytes:r,sniff:s};let o=Math.min(je(r,n),n),i=await li(t,Math.max(o,Math.min(e,n)));if(i.sniff.ok||i.sniff.refusal!=="header-not-found")return i;if(i.bytes.length>=n)return i;return li(t,n)}async function di(t,e,n,r){let s=await ci(t,e,n,jt);if(s===null)return null;try{let{bytes:o,sniff:i}=await $u(s,r);return{bytes:o,size:s.size,oid:s.oid,version:s.version,sniff:i}}finally{await s.close()}}function Ou(t,e,n){let r={"content-type":e,"content-disposition":"inline","x-content-type-options":"nosniff","cross-origin-resource-policy":"same-origin",vary:"sec-fetch-site, sec-fetch-dest","cache-control":t==="worktree"?"no-store":"private, no-cache"};if(t!=="worktree"&&n!==null)r.etag=`"${n}"`;return r}function Nu(t){let e=Fu.includes(t)?413:415;return new m(e,`Image not served: ${t}`)}function Cu(t,e){let n=t.originalPath??t.path;switch(t.status){case"untracked":return{old:null,new:{side:"worktree",path:t.path}};case"added":return{old:null,new:{side:e?"index":"worktree",path:t.path}};case"deleted":return{old:{side:e?"head":"index",path:n},new:null};default:return e?{old:{side:"head",path:n},new:{side:"index",path:t.path}}:{old:{side:"index",path:n},new:{side:"worktree",path:t.path}}}}function Lu(t,e,n){return{path:t.path,side:t.side,bytes:e,oid:null,image:null,refusal:n,version:""}}async function ui(t,e){let n=St(t.path,e.path);await Et(t,n);let r;try{r=await di(t.path,e.side,n,Pu)}catch(s){if(s instanceof zt)return Lu(e,s.size,"too-large");if(s instanceof Xt)return null;hi(s)}if(r===null)return null;return{path:e.path,side:e.side,bytes:r.size,oid:r.oid,version:r.version,image:r.sniff.ok?r.sniff.info:null,refusal:r.sniff.ok?null:r.sniff.refusal}}function Hu(t,e){return e.writableEnded||e.destroyed===!0||t.destroyed===!0}async function fi(t,e,n){let r=t.acquire();if(r===null)throw new m(503,"Too many image requests in flight");let s=await r;if(n.once("finish",s),n.once("close",s),e.once("close",s),Hu(e,n))return s(),!1;return!0}function pi(t,e,n){let{registry:r}=e;t.get("/repos/:id/media",async({params:s,query:o,req:i,res:a})=>{let c=R(r,s.id),l=W(o,"staged"),u=St(c.path,Q(o));if(await Et(c,u),!await fi(n,i,a))return;let f=await Lt(c.manager.workingTree,u,l),h=Cu(f,l),g={old:h.old===null?null:await ui(c,h.old),new:h.new===null?null:await ui(c,h.new)};S(a,200,g)}),t.get("/repos/:id/blob",async({params:s,query:o,req:i,res:a})=>{let c=R(r,s.id),l=Er(i);if(l)throw new m(l.status,l.message);let u=Tu(o),f=St(c.path,Q(o));if(await Et(c,f),!await fi(n,i,a))return;let h;try{h=await di(c.path,u,f,Mu)}catch(d){hi(d)}if(h===null)throw new m(404,`No such blob on side ${u}: ${f}`);if(!h.sniff.ok)throw Nu(h.sniff.refusal);let g=Ou(u,h.sniff.info.mime,h.oid);dr(a,200,h.bytes,g)})}function mi(t,e){let{registry:n,sse:r,daemonEvents:s,follow:o}=e;t.get("/events",({req:i,res:a,query:c})=>{let l=n.listRepos().map((f)=>({id:f.id,path:f.path}));s.subscribe(i,a,l);let u=c.get("repo");if(!u)return;r.attach(u,n.getRepo(u)?.manager??null,i,a)}),t.get("/follow",({res:i})=>{S(i,200,o?o.state:Ys)})}import*as nr from"node:os";import*as Jt from"node:path";function gi(t,e){let{settings:n,discovery:r,daemonEvents:s}=e,o=()=>({...n.settings,persisted:n.persisted});t.get("/settings",({res:i})=>{S(i,200,o())}),t.put("/settings",async({body:i,res:a})=>{let c=ho(i,"watchRoots"),l;try{l=Vs(c)}catch(f){throw new m(400,f instanceof Error?f.message:String(f),{cause:f})}try{n.save({...n.settings,watchRoots:l})}catch(f){let h=f instanceof Error?f.message:String(f);throw new m(500,`Could not save settings: ${h}`,{cause:f})}await r.setRoots(l);let u=o();s.broadcast("settings-change",u),S(a,200,u)}),t.get("/discovered",({res:i})=>{S(i,200,r.state)}),t.get("/browse",async({query:i,res:a})=>{let c=i.get("path"),l=c?J(c):nr.homedir();if(!Jt.isAbsolute(l))throw new m(400,`Path must be absolute: ${c}`);let u=Jt.resolve(l),f;try{f=await Zs(u)}catch(g){throw new m(404,`Cannot read directory: ${u}`,{cause:g})}let h=Jt.dirname(u);S(a,200,{path:u,parent:h===u?null:h,home:nr.homedir(),entries:f})}),t.post("/discovered/rescan",async({res:i})=>{S(i,200,await r.rescan())})}function rr(t=4,e=64){let n=0,r=[];function s(){let o=!1;return()=>{if(o)return;o=!0;let i=r.shift();if(i)i(s());else n--}}return{acquire(){if(n<t)return n++,Promise.resolve(s());if(r.length>=e)return null;return new Promise((o)=>{r.push(o)})},get active(){return n},get queued(){return r.length}}}function Bu(t){if(!vt.existsSync(t))return Promise.resolve(!1);return new Promise((e)=>{try{let n=yi.connect(t);n.once("connect",()=>{n.destroy(),e(!0)}),n.once("error",()=>{n.destroy(),e(!1)})}catch{e(!1)}})}function bi(t={}){let e=new Fn,n=new Tn,r=new Pn({onOpened:(w)=>n.broadcast("repo-opened",{id:w.id,path:w.path}),onClosed:(w)=>{e.closeRepo(w),n.broadcast("repo-closed",{id:w})}}),s=t.followFile?new On(r,n,t.followFile):null,o=io(t.updateCheck===!1?()=>Promise.resolve(null):t.fetchLatestVersion),i=new Cn(t.settingsFile??null),a=new Hn(n),c=new Map,l=rr(),u=t.symbols??null,f=u===null?null:{pool:Zo(u),gate:rr(1,4),extensions:u.extensions};function h(w){let x=c.get(w);if(x)return x;let _=new sn,b={registry:r,sse:e,daemonEvents:n,follow:s,settings:i,discovery:a,apiMode:w,version:o,symbols:f,httpPort:v};if(co(_,b),lo(_,b),Eo(_,b),ko(_,b),$o(_,b),Oo(_,b),w==="full")No(_,b);return Xo(_,b),Qo(_,b),pi(_,b,l),mi(_,b),gi(_,b),c.set(w,_),_}let g=(w)=>t.apiMode??(w==="tcp"?"web":"full");s?.start(),a.setRoots(i.load().watchRoots);let d=t.webRoot?gr(t.webRoot):void 0,p=new Set,y=[];function v(){for(let w of y){let x=w.server.address();if(x!==null&&typeof x==="object")return x.port}return null}function A(w){let x=h(w),_=wi.createServer((b,ct)=>{for(let[tt,me]of Object.entries(xr))ct.setHeader(tt,me);if(br(_.address())){let tt=Sr(b);if(tt){S(ct,tt.status,{error:tt.message});return}}x.handle(b,ct,d).catch((tt)=>{F(`${b.method??"GET"} ${b.url??"/"} escaped the router`,tt),ct.end()})});return _.on("connection",(b)=>{p.add(b),b.on("close",()=>p.delete(b))}),_}async function I(w,x){let _=w==="unix"?x.socketPath??null:null;if(_){if(await Bu(_))throw Error(`diffstalkerd already running at ${_}`);vt.rmSync(_,{force:!0})}let b={server:A(g(w)),socketPath:_};y.push(b),await new Promise((ct,tt)=>{let me=(Di)=>tt(Di);b.server.once("error",me);let Ye=()=>{if(b.server.removeListener("error",me),_)vt.chmodSync(_,384);ct()};if(w==="fd")b.server.listen({fd:x.fd},Ye);else if(_)process.umask(63),b.server.listen(_,Ye);else b.server.listen(x.port,"127.0.0.1",Ye)})}function D(w){return new Promise((x,_)=>{w.server.close((b)=>{if(w.socketPath)vt.rmSync(w.socketPath,{force:!0});if(b&&b.code!=="ERR_SERVER_NOT_RUNNING")_(b);else x()})})}return{address(){return y[0]?.server.address()??null},addresses(){return y.map((w)=>w.server.address()).filter((w)=>w!==null)},getRepo(w){return r.getRepo(w)},async openRepo(w){let{handle:x}=await $e(r,w);return{id:x.id,path:x.path}},async listen(w){let x=[];if(w.fd!==void 0)x.push("fd");if(w.socketPath)x.push("unix");if(w.port!==void 0)x.push("tcp");if(x.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let _ of x)await I(_,w)},close(){s?.dispose(),a.dispose(),e.destroy(),n.destroy(),r.disposeAll();for(let x of p)x.destroy();let w=f?.pool.dispose()??Promise.resolve();return Promise.all([w,...y.splice(0).map(D)]).then(()=>{})}}}import*as sr from"node:fs";import*as Yt from"node:path";import*as Ri from"node:crypto";import{createRequire as ju}from"node:module";var Si=new Map([[".ts",{grammar:"typescript",container:null}],[".mts",{grammar:"typescript",container:null}],[".cts",{grammar:"typescript",container:null}],[".vue",{grammar:"typescript",container:"vue"}],[".js",{grammar:"javascript",container:null}],[".mjs",{grammar:"javascript",container:null}],[".cjs",{grammar:"javascript",container:null}],[".jsx",{grammar:"javascript",container:null}],[".java",{grammar:"java",container:null}]]);function Ei(){return[...Si.keys()]}function Wu(t){let e=t.slice(t.lastIndexOf("/")+1),n=e.lastIndexOf(".");if(n<=0)return"";return e.slice(n).toLowerCase()}function xi(t){return Si.get(Wu(t))??null}var Gu="diffstalkerd-grammars";function Uu(t){return Ri.createHash("sha256").update(t).digest("hex")}function qu(t){try{let e=JSON.parse(sr.readFileSync(Yt.join(t,"checksums.json"),"utf8"));if(typeof e.webTreeSitterVersion!=="string"||typeof e.files!=="object")return null;return e}catch{return null}}var vi="0.26.11";function Xu(t,e,n){for(let[r,s]of Object.entries(e.files)){let o;try{o=sr.readFileSync(Yt.join(t,r))}catch{return n(`grammars: missing ${r}`),!1}if(Uu(o)!==s)return n(`grammars: checksum mismatch for ${r}`),!1}return!0}function zu(t){let e=new Set;for(let n of Object.keys(t.files)){let r=/^tree-sitter-(.+)\.wasm$/.exec(n);if(r!==null&&t.files[`queries/${r[1]}.scm`]!==void 0)e.add(r[1])}return e}function ki(t,e=()=>{}){let n=qu(t);if(n===null)return e(`grammars: no readable checksums.json in ${t}`),null;if(n.webTreeSitterVersion!==vi)return e(`grammars: built for web-tree-sitter ${n.webTreeSitterVersion}, this daemon bundles ${vi} — symbols disabled`),null;if(!Xu(t,n,e))return null;let r=zu(n),s=Ei().filter((o)=>{let i=xi(`x${o}`);return i!==null&&r.has(i.grammar)});if(s.length===0)return e("grammars: no usable grammar found"),null;return{grammarDir:t,queryDir:Yt.join(t,"queries"),extensions:s}}function _i(t,e=()=>{}){if(t!==null)return ki(t,e);try{let r=ju(import.meta.url).resolve(`${Gu}/checksums.json`);return ki(Yt.dirname(r),e)}catch{return null}}var Ii="diffstalkerd.sock";function Yu(t){return t===void 0?Ii:`${t}.sock`}var Ku=3,Ai=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
54
47
 
55
48
  Usage: diffstalkerd [options] [REPO_PATH...]
56
49
 
@@ -62,7 +55,7 @@ Arguments:
62
55
 
63
56
  Options:
64
57
  --socket PATH Bind a unix socket at PATH
65
- (default: $XDG_RUNTIME_DIR/diffstalker/${m5})
58
+ (default: $XDG_RUNTIME_DIR/diffstalker/${Ii})
66
59
  --instance NAME Bind <NAME>.sock in the runtime dir, so several
67
60
  daemons can run side by side (default: the shared
68
61
  socket every client looks for first)
@@ -78,8 +71,10 @@ Options:
78
71
  when missing, the daemon serves the API only)
79
72
  --no-update-check Never ask npm which version is latest; GET /version
80
73
  then reports the running version only
74
+ --debug Also log debug lines (every refused request, every
75
+ ignored follow target) to stderr
81
76
  --version, -v Print the running version and exit
82
77
  --help, -h Show this help
83
- `;function f$($,Z,K){let V=$[Z];if(V===void 0||V.startsWith("--"))throw Error(`${K} requires a value`);return V}function $K($,Z){if(Z.startsWith("-"))throw Error(`Unknown argument: ${Z}`);if(Z==="")throw Error("Empty repo path argument");$.repoPaths??=[],$.repoPaths.push(Z)}function ZK($){let Z={};for(let K=0;K<$.length;K++){let V=$[K];switch(V){case"--help":case"-h":return"help";case"--version":case"-v":return"version";case"--socket":Z.socketPath=f$($,++K,"--socket");break;case"--instance":Z.instance=f$($,++K,"--instance");break;case"--no-socket":Z.noSocket=!0;break;case"--port":if(Z.port=Number(f$($,++K,"--port")),!Number.isInteger(Z.port)||Z.port<0)throw Error("--port requires a non-negative integer");break;case"--follow-file":Z.followFile=f$($,++K,"--follow-file");break;case"--no-follow":Z.noFollow=!0;break;case"--web-root":Z.webRoot=f$($,++K,"--web-root");break;case"--grammars":Z.grammarsDir=f$($,++K,"--grammars");break;case"--no-update-check":Z.noUpdateCheck=!0;break;default:$K(Z,V);break}}if(Z.socketPath!==void 0&&Z.noSocket)throw Error("--socket and --no-socket are mutually exclusive");if(Z.noSocket&&Z.port===void 0)throw Error("--no-socket requires --port (nothing would be listening)");if(Z.followFile!==void 0&&Z.noFollow)throw Error("--follow-file and --no-follow are mutually exclusive");return Z}function KK(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function VK($){if($.noSocket||$.socketPath!==void 0)return;if(KK()){$.fd=e9;return}let Z=x6();if(!Z){if($.port!==void 0){console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set; binding the TCP port only.
78
+ `;function Kt(t,e,n){let r=t[e];if(r===void 0||r.startsWith("--"))throw Error(`${n} requires a value`);return r}function Vu(t,e){if(e.startsWith("-"))throw Error(`Unknown argument: ${e}`);if(e==="")throw Error("Empty repo path argument");t.repoPaths??=[],t.repoPaths.push(e)}function Qu(t){let e={};for(let n=0;n<t.length;n++){let r=t[n];switch(r){case"--help":case"-h":return"help";case"--version":case"-v":return"version";case"--socket":e.socketPath=Kt(t,++n,"--socket");break;case"--instance":e.instance=Kt(t,++n,"--instance");break;case"--no-socket":e.noSocket=!0;break;case"--port":if(e.port=Number(Kt(t,++n,"--port")),!Number.isInteger(e.port)||e.port<0)throw Error("--port requires a non-negative integer");break;case"--follow-file":e.followFile=Kt(t,++n,"--follow-file");break;case"--no-follow":e.noFollow=!0;break;case"--web-root":e.webRoot=Kt(t,++n,"--web-root");break;case"--grammars":e.grammarsDir=Kt(t,++n,"--grammars");break;case"--no-update-check":e.noUpdateCheck=!0;break;case"--debug":e.debug=!0;break;default:Vu(e,r);break}}if(e.socketPath!==void 0&&e.noSocket)throw Error("--socket and --no-socket are mutually exclusive");if(e.noSocket&&e.port===void 0)throw Error("--no-socket requires --port (nothing would be listening)");if(e.followFile!==void 0&&e.noFollow)throw Error("--follow-file and --no-follow are mutually exclusive");return e}function Zu(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function tf(t){if(t.noSocket||t.socketPath!==void 0)return;if(Zu()){t.fd=Ku;return}let e=cr();if(!e){if(t.port!==void 0){console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set; binding the TCP port only.
84
79
  Pass --socket PATH to also accept CLI connections.`);return}console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set and no --socket/--port given.
85
- Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}PZ.mkdirSync(Z,{recursive:!0,mode:448}),$.socketPath=h$.join(Z,t9($.instance))}function QK($){let Z=$??r9(new URL("web/",import.meta.url));if(PZ.existsSync(Z))return Z;console.error(`diffstalkerd: web UI assets not found at ${Z}; serving API only`);return}function YK($){console.error(`diffstalkerd: web UI at http://diffstalker.localhost:${$}/`)}async function XK($,Z){for(let K of Z){let V=h$.resolve(l(K));try{let Q=await $.openRepo(V);console.error(`diffstalkerd opened ${Q.path}`)}catch(Q){console.error(`diffstalkerd: cannot open ${V}: ${Q instanceof Error?Q.message:String(Q)}`),await $.close().catch(()=>{}),process.exit(1)}}}async function JK(){process.title="diffstalkerd";let $;try{$=ZK(process.argv.slice(2))}catch(U){console.error(U instanceof Error?U.message:String(U)),console.error(y5),process.exit(2)}if($==="help"){console.log(y5);return}if($==="version"){let U=C6();if(U===null)console.error("diffstalkerd: version unknown (package.json unreadable)"),process.exit(1);console.log(U);return}VK($);let Z=$.noFollow?void 0:$.followFile??h$.join(T$(),"target"),K=QK($.webRoot),V=b5($.grammarsDir??process.env.DIFFSTALKER_GRAMMARS_DIR??null,(U)=>console.error(`diffstalkerd: ${U}`)),Q=v5({followFile:Z,settingsFile:h$.join(P6(),"daemon.json"),webRoot:K,symbols:V,updateCheck:!$.noUpdateCheck});await XK(Q,$.repoPaths??[]),await Q.listen($);let X=Q.addresses().find((U)=>typeof U!=="string")?.port??$.port;if($.fd!==void 0)console.error(`diffstalkerd listening on inherited socket (fd ${$.fd})`);if($.socketPath)console.error(`diffstalkerd listening on unix socket ${$.socketPath}`);if(X!==void 0)console.error(`diffstalkerd listening on 127.0.0.1:${X}`);if(Z)console.error(`diffstalkerd following ${Z}`);if(K){if(console.error(`diffstalkerd serving web UI from ${K}`),X!==void 0)YK(X)}let J=!1,W=(U)=>{if(J)return;J=!0,console.error(`Received ${U}, shutting down`),Q.close().then(()=>process.exit(0)).catch((j)=>{console.error(j instanceof Error?j.message:String(j)),process.exit(1)})};process.on("SIGINT",()=>W("SIGINT")),process.on("SIGTERM",()=>W("SIGTERM")),process.on("SIGHUP",()=>W("SIGHUP"));let z=(U,j)=>{console.error(`diffstalkerd ${U}:`,j instanceof Error?j.stack??j.message:j),Q.close().catch(()=>{}).finally(()=>process.exit(1))};process.on("uncaughtException",(U)=>z("uncaught exception",U)),process.on("unhandledRejection",(U)=>z("unhandled rejection",U))}JK().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});export{ZK as parseArgs};
80
+ Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}Je.mkdirSync(e,{recursive:!0,mode:448}),t.socketPath=Vt.join(e,Yu(t.instance))}function ef(t){let e=t??Ju(new URL("web/",import.meta.url));if(Je.existsSync(e))return e;console.error(`diffstalkerd: web UI assets not found at ${e}; serving API only`);return}function nf(t){console.error(`diffstalkerd: web UI at http://diffstalker.localhost:${t}/`)}async function rf(t,e){for(let n of e){let r=Vt.resolve(J(n));try{let s=await t.openRepo(r);console.error(`diffstalkerd opened ${s.path}`)}catch(s){console.error(`diffstalkerd: cannot open ${r}: ${s instanceof Error?s.message:String(s)}`),await t.close().catch(()=>{}),process.exit(1)}}}async function sf(){process.title="diffstalkerd";let t;try{t=Qu(process.argv.slice(2))}catch(u){console.error(u instanceof Error?u.message:String(u)),console.error(Ai),process.exit(2)}if(t==="help"){console.log(Ai);return}if(t==="version"){let u=Bn();if(u===null)console.error("diffstalkerd: version unknown (package.json unreadable)"),process.exit(1);console.log(u);return}ur(t.debug??!1),tf(t);let e=t.noFollow?void 0:t.followFile??Vt.join(Rt(),"target"),n=ef(t.webRoot),r=_i(t.grammarsDir??process.env.DIFFSTALKER_GRAMMARS_DIR??null,(u)=>console.error(`diffstalkerd: ${u}`)),s=bi({followFile:e,settingsFile:Vt.join(ar(),"daemon.json"),webRoot:n,symbols:r,updateCheck:!t.noUpdateCheck});await rf(s,t.repoPaths??[]),await s.listen(t);let i=s.addresses().find((u)=>typeof u!=="string")?.port??t.port;if(t.fd!==void 0)console.error(`diffstalkerd listening on inherited socket (fd ${t.fd})`);if(t.socketPath)console.error(`diffstalkerd listening on unix socket ${t.socketPath}`);if(i!==void 0)console.error(`diffstalkerd listening on 127.0.0.1:${i}`);if(e)console.error(`diffstalkerd following ${e}`);if(n){if(console.error(`diffstalkerd serving web UI from ${n}`),i!==void 0)nf(i)}let a=!1,c=(u)=>{if(a)return;a=!0,console.error(`Received ${u}, shutting down`),s.close().then(()=>process.exit(0)).catch((f)=>{console.error(f instanceof Error?f.message:String(f)),process.exit(1)})};process.on("SIGINT",()=>c("SIGINT")),process.on("SIGTERM",()=>c("SIGTERM")),process.on("SIGHUP",()=>c("SIGHUP"));let l=(u,f)=>{F(`${u}; shutting down`,f),s.close().catch(()=>{}).finally(()=>process.exit(1))};process.on("uncaughtException",(u)=>l("uncaught exception",u)),process.on("unhandledRejection",(u)=>l("unhandled rejection",u))}sf().catch((t)=>{console.error(t instanceof Error?t.message:String(t)),process.exit(1)});export{Qu as parseArgs};