diffstalkerd 0.12.1 → 0.12.3
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/CHANGELOG.md +43 -0
- package/README.md +1 -1
- package/dist/index.js +40 -39
- package/dist/web/assets/index-DCu3bn_X.js +14 -0
- package/dist/web/assets/index-Dgf4Da4P.css +1 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/web/assets/index-BqYkaNhX.css +0 -1
- package/dist/web/assets/index-D-xCHiMB.js +0 -14
package/dist/index.js
CHANGED
|
@@ -1,55 +1,56 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);for(let K=Z.length-1;K>=0;K--){let V=Z[K].trim();if(V)return V}return""}import*as
|
|
3
|
-
`)}function
|
|
4
|
-
`)}function
|
|
1
|
+
var E5=Object.create;var{getPrototypeOf:_5,defineProperty:F6,getOwnPropertyNames:P5}=Object;var x5=Object.prototype.hasOwnProperty;function b5($){return this[$]}var y5,m5,g5=($,Z,K)=>{var V=$!=null&&typeof $==="object";if(V){var Q=Z?y5??=new WeakMap:m5??=new WeakMap,X=Q.get($);if(X)return X}K=$!=null?E5(_5($)):{};let Y=Z||!$||!$.__esModule?F6(K,"default",{value:$,enumerable:!0}):K;for(let W of P5($))if(!x5.call(Y,W))F6(Y,W,{get:b5.bind($,W),enumerable:!0});if(V)Q.set($,Y);return Y};var c5=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var s8=c5((wK,i8)=>{var y=-1,x=1,k=0;function n$($,Z,K,V,Q){if($===Z){if($)return[[k,$]];return[]}if(K!=null){var X=c0($,Z,K);if(X)return X}var Y=iZ($,Z),W=$.substring(0,Y);$=$.substring(Y),Z=Z.substring(Y),Y=MZ($,Z);var J=$.substring($.length-Y);$=$.substring(0,$.length-Y),Z=Z.substring(0,Z.length-Y);var z=E0($,Z);if(W)z.unshift([k,W]);if(J)z.push([k,J]);if(sZ(z,Q),V)x0(z);return z}function E0($,Z){var K;if(!$)return[[x,Z]];if(!Z)return[[y,$]];var V=$.length>Z.length?$:Z,Q=$.length>Z.length?Z:$,X=V.indexOf(Q);if(X!==-1){if(K=[[x,V.substring(0,X)],[k,Q],[x,V.substring(X+Q.length)]],$.length>Z.length)K[0][0]=K[2][0]=y;return K}if(Q.length===1)return[[y,$],[x,Z]];var Y=P0($,Z);if(Y){var W=Y[0],J=Y[1],z=Y[2],U=Y[3],j=Y[4],G=n$(W,z),M=n$(J,U);return G.concat([[k,j]],M)}return _0($,Z)}function _0($,Z){var K=$.length,V=Z.length,Q=Math.ceil((K+V)/2),X=Q,Y=2*Q,W=Array(Y),J=Array(Y);for(var z=0;z<Y;z++)W[z]=-1,J[z]=-1;W[X+1]=0,J[X+1]=0;var U=K-V,j=U%2!==0,G=0,M=0,B=0,I=0;for(var L=0;L<Q;L++){for(var D=-L+G;D<=L-M;D+=2){var S=X+D,v;if(D===-L||D!==L&&W[S-1]<W[S+1])v=W[S+1];else v=W[S-1]+1;var O=v-D;while(v<K&&O<V&&$.charAt(v)===Z.charAt(O))v++,O++;if(W[S]=v,v>K)M+=2;else if(O>V)G+=2;else if(j){var H=X+U-D;if(H>=0&&H<Y&&J[H]!==-1){var C=K-J[H];if(v>=C)return u8($,Z,v,O)}}}for(var A=-L+B;A<=L-I;A+=2){var H=X+A,C;if(A===-L||A!==L&&J[H-1]<J[H+1])C=J[H+1];else C=J[H-1]+1;var R=C-A;while(C<K&&R<V&&$.charAt(K-C-1)===Z.charAt(V-R-1))C++,R++;if(J[H]=C,C>K)I+=2;else if(R>V)B+=2;else if(!j){var S=X+U-A;if(S>=0&&S<Y&&W[S]!==-1){var v=W[S],O=X+v-S;if(C=K-C,v>=C)return u8($,Z,v,O)}}}}return[[y,$],[x,Z]]}function u8($,Z,K,V){var Q=$.substring(0,K),X=Z.substring(0,V),Y=$.substring(K),W=Z.substring(V),J=n$(Q,X),z=n$(Y,W);return J.concat(z)}function iZ($,Z){if(!$||!Z||$.charAt(0)!==Z.charAt(0))return 0;var K=0,V=Math.min($.length,Z.length),Q=V,X=0;while(K<Q){if($.substring(X,Q)==Z.substring(X,Q))K=Q,X=K;else V=Q;Q=Math.floor((V-K)/2+K)}if(l8($.charCodeAt(Q-1)))Q--;return Q}function p8($,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 X=0,Y=1;while(!0){var W=$.substring(Q-Y),J=Z.indexOf(W);if(J==-1)return X;if(Y+=J,J==0||$.substring(Q-Y)==Z.substring(0,Y))X=Y,Y++}}function MZ($,Z){if(!$||!Z||$.slice(-1)!==Z.slice(-1))return 0;var K=0,V=Math.min($.length,Z.length),Q=V,X=0;while(K<Q){if($.substring($.length-Q,$.length-X)==Z.substring(Z.length-Q,Z.length-X))K=Q,X=K;else V=Q;Q=Math.floor((V-K)/2+K)}if(n8($.charCodeAt($.length-Q)))Q--;return Q}function P0($,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,B,I){var L=M.substring(I,I+Math.floor(M.length/4)),D=-1,S="",v,O,H,C;while((D=B.indexOf(L,D+1))!==-1){var A=iZ(M.substring(I),B.substring(D)),R=MZ(M.substring(0,I),B.substring(0,D));if(S.length<R+A)S=B.substring(D-R,D)+B.substring(D,D+A),v=M.substring(0,I-R),O=M.substring(I+A),H=B.substring(0,D-R),C=B.substring(D+A)}if(S.length*2>=M.length)return[v,O,H,C,S];else return null}var X=Q(K,V,Math.ceil(K.length/4)),Y=Q(K,V,Math.ceil(K.length/2)),W;if(!X&&!Y)return null;else if(!Y)W=X;else if(!X)W=Y;else W=X[4].length>Y[4].length?X:Y;var J,z,U,j;if($.length>Z.length)J=W[0],z=W[1],U=W[2],j=W[3];else U=W[0],j=W[1],J=W[2],z=W[3];var G=W[4];return[J,z,U,j,G]}function x0($){var Z=!1,K=[],V=0,Q=null,X=0,Y=0,W=0,J=0,z=0;while(X<$.length){if($[X][0]==k)K[V++]=X,Y=J,W=z,J=0,z=0,Q=$[X][1];else{if($[X][0]==x)J+=$[X][1].length;else z+=$[X][1].length;if(Q&&Q.length<=Math.max(Y,W)&&Q.length<=Math.max(J,z))$.splice(K[V-1],0,[y,Q]),$[K[V-1]+1][0]=x,V--,V--,X=V>0?K[V-1]:-1,Y=0,W=0,J=0,z=0,Q=null,Z=!0}X++}if(Z)sZ($);m0($),X=1;while(X<$.length){if($[X-1][0]==y&&$[X][0]==x){var U=$[X-1][1],j=$[X][1],G=p8(U,j),M=p8(j,U);if(G>=M){if(G>=U.length/2||G>=j.length/2)$.splice(X,0,[k,j.substring(0,G)]),$[X-1][1]=U.substring(0,U.length-G),$[X+1][1]=j.substring(G),X++}else if(M>=U.length/2||M>=j.length/2)$.splice(X,0,[k,U.substring(0,M)]),$[X-1][0]=x,$[X-1][1]=j.substring(0,j.length-M),$[X+1][0]=y,$[X+1][1]=U.substring(M),X++;X++}X++}}var f8=/[^a-zA-Z0-9]/,h8=/\s/,d8=/[\r\n]/,b0=/\n\r?\n$/,y0=/^\r?\n\r?\n/;function m0($){function Z(M,B){if(!M||!B)return 6;var I=M.charAt(M.length-1),L=B.charAt(0),D=I.match(f8),S=L.match(f8),v=D&&I.match(h8),O=S&&L.match(h8),H=v&&I.match(d8),C=O&&L.match(d8),A=H&&M.match(b0),R=C&&B.match(y0);if(A||R)return 5;else if(H||C)return 4;else if(D&&!v&&O)return 3;else if(v||O)return 2;else if(D||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],X=$[K+1][1],Y=MZ(V,Q);if(Y){var W=Q.substring(Q.length-Y);V=V.substring(0,V.length-Y),Q=W+Q.substring(0,Q.length-Y),X=W+X}var J=V,z=Q,U=X,j=Z(V,Q)+Z(Q,X);while(Q.charAt(0)===X.charAt(0)){V+=Q.charAt(0),Q=Q.substring(1)+X.charAt(0),X=X.substring(1);var G=Z(V,Q)+Z(Q,X);if(G>=j)j=G,J=V,z=Q,U=X}if($[K-1][1]!=J){if(J)$[K-1][1]=J;else $.splice(K-1,1),K--;if($[K][1]=z,U)$[K+1][1]=U;else $.splice(K+1,1),K--}}K++}}function sZ($,Z){$.push([k,""]);var K=0,V=0,Q=0,X="",Y="",W;while(K<$.length){if(K<$.length-1&&!$[K][1]){$.splice(K,1);continue}switch($[K][0]){case x:Q++,Y+=$[K][1],K++;break;case y:V++,X+=$[K][1],K++;break;case k:var J=K-Q-V-1;if(Z){if(J>=0&&a8($[J][1])){var z=$[J][1].slice(-1);if($[J][1]=$[J][1].slice(0,-1),X=z+X,Y=z+Y,!$[J][1]){$.splice(J,1),K--;var U=J-1;if($[U]&&$[U][0]===x)Q++,Y=$[U][1]+Y,U--;if($[U]&&$[U][0]===y)V++,X=$[U][1]+X,U--;J=U}}if(o8($[K][1])){var z=$[K][1].charAt(0);$[K][1]=$[K][1].slice(1),X+=z,Y+=z}}if(K<$.length-1&&!$[K][1]){$.splice(K,1);break}if(X.length>0||Y.length>0){if(X.length>0&&Y.length>0){if(W=iZ(Y,X),W!==0){if(J>=0)$[J][1]+=Y.substring(0,W);else $.splice(0,0,[k,Y.substring(0,W)]),K++;Y=Y.substring(W),X=X.substring(W)}if(W=MZ(Y,X),W!==0)$[K][1]=Y.substring(Y.length-W)+$[K][1],Y=Y.substring(0,Y.length-W),X=X.substring(0,X.length-W)}var j=Q+V;if(X.length===0&&Y.length===0)$.splice(K-j,j),K=K-j;else if(X.length===0)$.splice(K-j,j,[x,Y]),K=K-j+1;else if(Y.length===0)$.splice(K-j,j,[y,X]),K=K-j+1;else $.splice(K-j,j,[y,X],[x,Y]),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,X="",Y="";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)sZ($,Z)}function l8($){return $>=55296&&$<=56319}function n8($){return $>=56320&&$<=57343}function o8($){return n8($.charCodeAt(0))}function a8($){return l8($.charCodeAt($.length-1))}function g0($){var Z=[];for(var K=0;K<$.length;K++)if($[K][1].length>0)Z.push($[K]);return Z}function aZ($,Z,K,V){if(a8($)||o8(V))return null;return g0([[k,$],[y,Z],[x,K],[k,V]])}function c0($,Z,K){var V=typeof K==="number"?{index:K,length:0}:K.oldRange,Q=typeof K==="number"?null:K.newRange,X=$.length,Y=Z.length;if(V.length===0&&(Q===null||Q.length===0)){var W=V.index,J=$.slice(0,W),z=$.slice(W),U=Q?Q.index:null;$:{var j=W+Y-X;if(U!==null&&U!==j)break $;if(j<0||j>Y)break $;var G=Z.slice(0,j),M=Z.slice(j);if(M!==z)break $;var B=Math.min(W,j),I=J.slice(0,B),L=G.slice(0,B);if(I!==L)break $;var D=J.slice(B),S=G.slice(B);return aZ(I,D,S,z)}$:{if(U!==null&&U!==W)break $;var v=W,G=Z.slice(0,v),M=Z.slice(v);if(G!==J)break $;var O=Math.min(X-v,Y-v),H=z.slice(z.length-O),C=M.slice(M.length-O);if(H!==C)break $;var D=z.slice(0,z.length-O),S=M.slice(0,M.length-O);return aZ(J,D,S,H)}}if(V.length>0&&Q&&Q.length===0)$:{var I=$.slice(0,V.index),H=$.slice(V.index+V.length),B=I.length,O=H.length;if(Y<B+O)break $;var L=Z.slice(0,B),C=Z.slice(Y-O);if(I!==L||H!==C)break $;var D=$.slice(B,X-O),S=Z.slice(B,Y-O);return aZ(I,D,S,H)}return null}function HZ($,Z,K,V){return n$($,Z,K,V,!0)}HZ.INSERT=x;HZ.DELETE=y;HZ.EQUAL=k;i8.exports=HZ});import*as wZ from"node:fs";import*as g$ from"node:path";import{fileURLToPath as w9}from"node:url";import*as EZ from"node:os";import*as C$ from"node:path";var _Z="diffstalker";function S6(){return C$.join(process.env.XDG_CONFIG_HOME||C$.join(EZ.homedir(),".config"),_Z)}function B$(){return C$.join(process.env.XDG_CACHE_HOME||C$.join(EZ.homedir(),".cache"),_Z)}function R6(){return process.env.XDG_RUNTIME_DIR?C$.join(process.env.XDG_RUNTIME_DIR,_Z):null}import*as ZZ from"node:fs";import*as KZ from"node:path";import*as PZ from"node:os";function l($){if($.startsWith("~/"))return KZ.join(PZ.homedir(),$.slice(2));if($==="~")return PZ.homedir();return $}function v6($){let Z=KZ.dirname($);if(!ZZ.existsSync(Z))ZZ.mkdirSync(Z,{recursive:!0})}function xZ($){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 B5 from"node:http";import*as N$ from"node:fs";import*as I5 from"node:net";function VZ($){process.stderr.write(`[diffstalker warn] ${$}
|
|
3
|
+
`)}function u5($){if($ instanceof Error)return $.message;if($)return String($);return""}function QZ($,Z){let K=Z?`: ${u5(Z)}`:"";process.stderr.write(`[diffstalker error] ${$}${K}
|
|
4
|
+
`)}function bZ($){let Z={};for(let[K,V]of $)Z[K]=V;return Z}function p5($){if(!$)return null;return{staged:bZ($.staged),unstaged:bZ($.unstaged)}}function Z$($){return{status:$.status,hunkCounts:p5($.hunkCounts),error:$.error,stashList:$.stashList,operationInProgress:$.operationInProgress,mtimes:$.mtimes?bZ($.mtimes):null}}function yZ($){return $}function f5($){return $.entries.length>0?$.entries[0].seq-1:$.nextSeq-1}function k6($,Z){let K=Z>0?$.entries.filter((V)=>V.seq>Z):$.entries;return{epoch:$.epoch,prunedBefore:f5($),entries:yZ(K)}}function c$($){if($ instanceof Date)return $.toISOString();if($ instanceof Map){let Z={};for(let[K,V]of $)Z[String(K)]=c$(V);return Z}if(Array.isArray($))return $.map(c$);if($!==null&&typeof $==="object"){let Z={};for(let[K,V]of Object.entries($))Z[K]=c$(V);return Z}return $}var h5=1048576;class N extends Error{status;constructor($,Z){super(Z);this.status=$,this.name="HttpError"}}function T($,Z,K){let V=JSON.stringify(c$(K));$.writeHead(Z,{"content-type":"application/json"}),$.end(V)}function E6($,Z,K,V){$.writeHead(Z,{...V,"content-length":String(K.byteLength)}),$.end(K)}function d5($,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 N(400,`Malformed percent-encoding in path: ${Z[V]}`)}else if(Q!==Z[V])return null}return K}async function l5($){if($.method!=="POST"&&$.method!=="PUT"&&$.method!=="PATCH")return;let Z=[],K=0;for await(let Q of $){let X=Q;if(K+=X.length,K>h5)throw new N(413,"Request body too large");Z.push(X)}let V=Buffer.concat(Z).toString("utf-8");if(!V.trim())return;try{return JSON.parse(V)}catch{throw new N(400,"Invalid JSON body")}}class mZ{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=d5(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),X=$.method??"GET",Y=this.match(X,Q);if(!Y){if(K&&X==="GET"){await K($,Z,V.pathname);return}throw new N(404,`Unknown route: ${X} ${V.pathname}`)}let W=await l5($);await Y.handler({req:$,res:Z,params:Y.params,query:V.searchParams,body:W})}catch(V){if(Z.headersSent){Z.end();return}if(V instanceof N){T(Z,V.status,{error:V.message});return}QZ(`${$.method??"GET"} ${$.url??"/"}`,V),T(Z,500,{error:"Internal server error"})}}}import*as gZ from"node:fs";import*as p from"node:path";var n5=new Set(["health","repos","events","follow"]),o5={".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"},_6="no-cache",a5="public, max-age=31536000, immutable";async function P6($,Z,K){let V;try{V=await gZ.promises.readFile(Z)}catch{throw new N(404,`Not found: ${p.basename(Z)}`)}$.writeHead(200,{"content-type":o5[p.extname(Z)]??"application/octet-stream","cache-control":K,"content-length":V.length}),$.end(V)}function x6($){let Z=p.resolve($);return async(K,V,Q)=>{let X;try{X=decodeURIComponent(Q)}catch{throw new N(400,`Malformed percent-encoding in path: ${Q}`)}if(X.includes("\x00"))throw new N(400,"Invalid path");let Y=X.split("/").filter(Boolean);if(Y.length>0&&n5.has(Y[0]))throw new N(404,`Unknown route: GET ${Q}`);let W=Y.length>0?p.resolve(Z,Y.join("/")):Z;if(W!==Z&&!W.startsWith(Z+p.sep))throw new N(403,"Forbidden");if((await gZ.promises.stat(W).catch(()=>null))?.isFile()){await P6(V,W,Y[0]==="assets"?a5:_6);return}await P6(V,p.join(Z,"index.html"),_6)}}function i5($){try{let Z=new URL(`http://${$}`).hostname.toLowerCase();return Z.startsWith("[")&&Z.endsWith("]")?Z.slice(1,-1):Z}catch{return null}}function s5($){try{let Z=new URL($).hostname.toLowerCase();return Z.startsWith("[")&&Z.endsWith("]")?Z.slice(1,-1):Z}catch{return null}}function y6($){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 r5($){return $.length>10&&$.endsWith(".localhost")}function b6($){return $==="localhost"||$==="::1"||r5($)||y6($)}function t5($){return $==="::1"||y6($)}function m6($){if($===null)return!1;if(typeof $==="string")return!0;return t5($.address)}function g6($){let Z=$.headers.host;if(Z!==void 0){let Y=i5(Z);if(Y===null||!b6(Y))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 X=$.headers.origin;if(X!==void 0&&X!==""){let Y=s5(X);if(Y===null||!b6(Y))return{status:403,message:"Cross-origin request blocked"}}return null}function c6($){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 u6={"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 J1}from"node:crypto";import*as V4 from"node:path";class p6{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 cZ=new Map;function f6($){let Z=cZ.get($);if(!Z)Z=new p6,cZ.set($,Z);return Z}function h6($){cZ.delete($)}import*as _ from"node:path";import*as h from"node:fs";import{execFileSync as f0}from"node:child_process";import{watch as t8}from"chokidar";import{EventEmitter as h0}from"node:events";import e8 from"ignore";import*as d6 from"node:fs";function XZ($,Z){let K=Z;if(!K||K.isSymbolicLink())try{K=d6.statSync($)}catch{return!1}return!K.isFile()&&!K.isDirectory()}import{simpleGit as Q0}from"simple-git";import*as n from"node:fs";import*as l6 from"node:os";import*as I$ from"node:path";import{execFileSync as e5}from"node:child_process";var $0=[["*.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 Z0(){return`# Generated by diffstalker: turns on git's built-in funcname drivers.
|
|
5
5
|
`+`# Lowest-priority attributes source — a repo's own .gitattributes wins.
|
|
6
|
-
|
|
6
|
+
`+$0.map(([Z,K])=>`${Z} diff=${K}`).join(`
|
|
7
7
|
`)+`
|
|
8
|
-
`}var
|
|
9
|
-
`).filter((z)=>z.length>0);for(let z of J)V.add(z)}catch{}}return V}function
|
|
8
|
+
`}var u$=null,Y$=null;function K0(){if(Y$!==null)return Y$;try{if(e5("git",["config","--get","core.attributesFile"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:process.env}).trim()!=="")return Y$=!0,!0}catch(Z){if(Z.status!==1)return Y$=!0,!0}let $=process.env.XDG_CONFIG_HOME||I$.join(l6.homedir(),".config");return Y$=n.existsSync(I$.join($,"git","attributes")),Y$}function n6(){if(u$!==null)return u$;if(K0())return null;let $=I$.join(B$(),"funcname.gitattributes"),Z=Z0();try{let K=null;try{K=n.readFileSync($,"utf8")}catch{K=null}if(K!==Z)n.mkdirSync(I$.dirname($),{recursive:!0}),V0($,Z);return u$=$,u$}catch{return u$=null,Y$=!0,null}}function V0($,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 X0={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0},Y0=1e4,W0=600000;function F($,Z={}){let K=n6(),V=K===null?[]:[`core.attributesFile=${K}`];return Q0({baseDir:$,unsafe:X0,timeout:{block:Z.longRunning===!0?W0:Y0},config:V}).env(f())}import{execFileSync as e6}from"node:child_process";import*as f$ from"node:fs";import*as pZ from"node:path";async function YZ($,Z){if(Z.length===0)return new Set;let K=F($),V=new Set,Q=100;for(let X=0;X<Z.length;X+=Q){let Y=Z.slice(X,X+Q);try{let J=(await K.raw(["check-ignore","--",...Y])).trim().split(`
|
|
9
|
+
`).filter((z)=>z.length>0);for(let z of J)V.add(z)}catch{}}return V}function W$($){if($.length===0)return"";return $.map((Z)=>Z.content).join(`
|
|
10
10
|
`)+`
|
|
11
|
-
`}function
|
|
12
|
-
`,K+1))!==-1)Z++;return Z}function
|
|
13
|
-
`),Q=V.findIndex((Y)=>Y.startsWith("@@"));return`${[...V.slice(0,Q===-1?4:Q),
|
|
11
|
+
`}function WZ($){let Z=0;for(let K of $)Z+=K.content.length+1;return Z}var J0=5000,p$=262144,i6="Large file — diff not shown";function z0($){return String($).replace(/\B(?=(\d{3})+(?!\d))/g,",")}function U0($){let Z=$/1048576;if(Z>=1)return`${Z.toFixed(1)} MB`;return`${Math.round($/1024)} KB`}function uZ($,Z){let K=U0($),V=Z===void 0?K:`${K}, ${z0(Z)} lines`;return`${i6} (${V})`}function o6($){if($.length===0)return 0;let Z=1,K=-1;while((K=$.indexOf(`
|
|
12
|
+
`,K+1))!==-1)Z++;return Z}function a6($,Z,K){let V=$.split(`
|
|
13
|
+
`),Q=V.findIndex((Y)=>Y.startsWith("@@"));return`${[...V.slice(0,Q===-1?4:Q),uZ(Z,K)].join(`
|
|
14
14
|
`)}
|
|
15
|
-
`}function
|
|
16
|
-
`);if(Z.length>1&&Z[Z.length-1]==="")Z.pop();let K=[],V=0,Q=0;for(let X of Z)if(
|
|
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
|
|
18
|
-
`)){if(!K)continue;let V=K.split("\t");if(V.length>=3){let Q=V[0]==="-"?0:parseInt(V[0],10),X=V[1]==="-"?0:parseInt(V[1],10),Y=V.slice(2).join("\t");Z.set(Y,{insertions:Q,deletions:X})}}return Z}var
|
|
19
|
-
`).filter((X)=>X.length>0).length}catch{return null}}var
|
|
20
|
-
`)[0],author:Q.author_name,date:new Date(Q.date),refs:Q.refs||""}))}catch{return[]}}async function
|
|
21
|
-
`)[0],author:Q.author_name,date:new Date(Q.date),refs:Q.refs||""}}catch{return null}}async function
|
|
22
|
-
`).join(", ")}`);return"Stash popped"}async function
|
|
23
|
-
`)}function
|
|
15
|
+
`}function A$($){if($.length===0)return $;let Z=$.split(/(?=^diff --git )/m),K=!1,V=Z.map((Q)=>{let X=Q.length;if(X<=p$){let Y=o6(Q);if(Y<=J0)return Q;return K=!0,a6(Q,X,Y)}return K=!0,a6(Q,X,o6(Q))});return K?V.join(""):$}function j0($){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(i6)}function O0($){return $.startsWith("\\ ")}function s6($){let Z=$.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(Z)return{oldStart:parseInt(Z[1],10),newStart:parseInt(Z[2],10)};return null}function K$($){if($==="")return[];let Z=$.split(`
|
|
16
|
+
`);if(Z.length>1&&Z[Z.length-1]==="")Z.pop();let K=[],V=0,Q=0;for(let X of Z)if(j0(X))K.push({type:"header",content:X});else if(O0(X))K.push({type:"context",content:X});else if(X.startsWith("@@")){let Y=s6(X);if(Y)V=Y.oldStart,Q=Y.newStart;K.push({type:"hunk",content:X})}else if(X.startsWith("+"))K.push({type:"addition",content:X,newLineNum:Q++});else if(X.startsWith("-"))K.push({type:"deletion",content:X,oldLineNum:V++});else K.push({type:"context",content:X,oldLineNum:V++,newLineNum:Q++});return K}function JZ($){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 r6($){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),X=V[1]==="-"?0:parseInt(V[1],10),Y=V.slice(2).join("\t");Z.set(Y,{insertions:Q,deletions:X})}}return Z}var G0=p$;async function M0($,Z){try{let K=pZ.join($,Z),V=await f$.promises.stat(K);if(!V.isFile())return null;if(V.size>G0)return null;return(await f$.promises.readFile(K,"utf-8")).split(`
|
|
19
|
+
`).filter((X)=>X.length>0).length}catch{return null}}var H0=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function N0($,Z){return H0.has(`${$}${Z}`)}function t6($,Z){return Z?"conflicted":C0($)}function C0($){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 fZ($){let Z=F($);if(!await Z.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let V=await Z.status(),Q=[],X=new Set,Y=V.files.filter((M)=>M.working_dir==="?").map((M)=>M.path),W=await YZ($,Y);for(let M of V.files){if(M.index==="!"||M.working_dir==="!"||W.has(M.path))continue;let B=`${M.path}-${M.index!==" "&&M.index!=="?"}`;if(X.has(B))continue;X.add(B);let I=N0(M.index,M.working_dir);if(M.index&&M.index!==" "&&M.index!=="?"){let L=t6(M.index,I);Q.push({path:M.path,status:L,staged:!0,...M.from&&(L==="renamed"||L==="copied")?{originalPath:M.from}:{}})}if(M.working_dir&&M.working_dir!==" ")Q.push({path:M.path,status:t6(M.working_dir,I),staged:!1})}let[J,z]=await Promise.all([Z.diff(["--cached","--numstat"]).catch(()=>""),Z.diff(["--numstat"]).catch(()=>"")]),U=r6(J),j=r6(z);for(let M of Q){let B=M.staged?U.get(M.path):j.get(M.path);if(B)M.insertions=B.insertions,M.deletions=B.deletions}let G=Q.filter((M)=>M.status==="untracked");if(G.length>0){let M=await Promise.all(G.map((B)=>M0($,B.path)));for(let B=0;B<G.length;B++){let I=M[B];if(I===null)continue;G[B].insertions=I,G[B].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 $8($,Z){await F($).add(["--",Z])}async function Z8($,Z){await F($).reset(["HEAD","--",Z])}async function K8($){await F($).add("-A")}async function V8($){await F($).reset(["HEAD"])}async function Q8($,Z){await F($).checkout(["--",Z])}async function X8($,Z){await F($).clean("f",["--",Z])}async function Y8($,Z,K=!1){if(!(await F($,{longRunning:!0}).commit(Z,void 0,K?{"--amend":null}:void 0)).commit)throw Error("Nothing to commit: no staged changes")}async function W8($){let Z=F($);try{return(await Z.log({n:1})).latest?.message||""}catch{return""}}function J8($,Z){e6("git",["apply","--cached","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:f()})}function z8($,Z){e6("git",["apply","--cached","--reverse","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:f()})}async function U8($){let V=(await F($,{longRunning:!0}).push()).pushed;if(V.length===0)return"Everything up-to-date";return V.map((Q)=>`${Q.local} → ${Q.remote}`).join(", ")}async function j8($){return await F($,{longRunning:!0}).fetch(),"Fetch complete"}async function O8($){let K=await F($,{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 G8($,Z=50){let K=F($);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 M8($,Z){let K=F($);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 zZ($){let Z=F($);try{return(await Z.stashList()).all.map((V,Q)=>({index:Q,message:V.message}))}catch{return[]}}async function H8($,Z){let K=F($),V=["push"];if(Z)V.push("-m",Z);return await K.stash(V),"Stashed"}async function N8($,Z=0){let K=F($);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 UZ($){let K=await F($).branchLocal();return K.all.map((V)=>({name:V,current:V===K.current,tracking:K.branches[V]?.label||void 0}))}async function C8($,Z){return await F($).raw(["switch","--",Z]),`Switched to ${Z}`}async function B8($,Z){return await F($).raw(["switch","-c",Z]),`Created ${Z}`}async function I8($,Z=1){return await F($).reset(["--soft",`HEAD~${Z}`]),"Reset done"}async function A8($,Z){return await F($,{longRunning:!0}).raw(["cherry-pick","--end-of-options",Z]),"Cherry-picked"}async function L8($,Z){return await F($,{longRunning:!0}).raw(["revert","--no-edit","--end-of-options",Z]),"Reverted"}async function i($){let Z=F($),K;try{K=(await Z.raw(["rev-parse","--absolute-git-dir"])).trim()}catch{return null}let V=(Q)=>f$.existsSync(pZ.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 T8($){let Z=await i($);if(!Z)throw Error("No operation in progress to abort");return await F($).raw([Z,"--abort"]),`Aborted ${Z}`}async function D8($){return await F($,{longRunning:!0}).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function q8($){return(await F($).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((V)=>V.length>0)}import*as z$ from"node:fs";import*as T$ from"node:path";import*as s from"node:fs";import*as J$ from"node:path";function hZ(){return J$.join(B$(),"base-branches.json")}function B0(){let $=J$.dirname(hZ());if(!s.existsSync($))s.mkdirSync($,{recursive:!0})}function F8(){try{let $=hZ();if(s.existsSync($))return JSON.parse(s.readFileSync($,"utf-8"))}catch{}return{}}function I0($){B0(),s.writeFileSync(hZ(),JSON.stringify($,null,2)+`
|
|
23
|
+
`)}function L$($){let Z=F8(),K=J$.resolve($);return Z[K]}function S8($,Z){let K=F8(),V=J$.resolve($);K[V]=Z,I0(K)}function h$($){let Z=Math.min($.length,8192);for(let K=0;K<Z;K++)if($[K]===0)return!0;return!1}class D$ extends Error{constructor($){super(`No common history with ${$}`);this.name="NoCommonHistoryError"}}async function q$($,Z,K=!1){let V=F($);try{let Q=[];if(K)Q.push("--cached");if(Z)Q.push("--",Z);let X=A$(await V.diff(Q));return{lines:K$(X)}}catch{return{lines:[]}}}var A0="4b825dc642cb6eb9a060e54bf8d69288fbee4904",R8="(unborn)",L0=/unknown revision|ambiguous argument 'HEAD'|needed a single revision/i;async function jZ($){let Z=F($);try{return(await Z.raw(["rev-parse","HEAD"])).trim()}catch(K){let V=K instanceof Error?K.message:String(K);if(L0.test(V))return R8;throw K}}async function v8($){let Z=F($),V=await jZ($)===R8?A0:"HEAD",Q=A$(await Z.raw(["diff","-U3",V,"--"]));return{lines:K$(Q)}}var T0=p$;function D0($,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:uZ(Z)}]}}function q0($){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 F0($,Z){let K=T$.resolve($),V=T$.resolve(K,Z);if(V!==K&&!V.startsWith(K+T$.sep))return null;let Q,X;try{Q=z$.realpathSync(V),X=z$.realpathSync(K)}catch{return null}if(Q!==X&&!Q.startsWith(X+T$.sep))return null;let Y=z$.statSync(Q);if(!Y.isFile())return null;return{path:V,size:Y.size}}async function OZ($,Z){try{let K=F0($,Z);if(K===null)return{lines:[]};if(K.size>T0)return D0(Z,K.size);let V=z$.readFileSync(K.path);if(h$(V))return q0(Z);let Q=V.toString("utf-8"),X=[{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}`}],Y=Q.endsWith(`
|
|
24
24
|
`),W=Q.split(`
|
|
25
|
-
`);if(Y)W.pop();if(Q.length>0){X.push({type:"hunk",content:`@@ -0,0 +1,${W.length} @@`});let U=1;for(let j of W)X.push({type:"addition",content:"+"+j,newLineNum:U++});if(!Y)X.push({type:"context",content:"\"})}let J=
|
|
26
|
-
`)){let W=X.exec(Y);if(W){let J=W[1].split(",").map((z)=>z.trim());for(let z of J){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)}}X.lastIndex=0}if(V.length>0)V.sort((Y,W)=>{let J=Y.split("/").slice(1).join("/"),z=W.split("/").slice(1).join("/"),U=J==="main"||J==="master",j=z==="main"||z==="master";if(U&&!j)return-1;if(!U&&j)return 1;if(U&&j){let G=Y.startsWith("origin/"),M=W.startsWith("origin/");if(G&&!M)return 1;if(!G&&M)return-1}return 0})}catch{}return[...new Set(V)]}async function
|
|
27
|
-
`).filter((O)=>O),z=new Map;for(let O of J){let
|
|
28
|
-
`).filter((O)=>O),j=new Map;for(let O of U){let
|
|
29
|
-
`)[0],author:O.author_name,date:new Date(O.date),refs:O.refs||""}));return G.sort((O,
|
|
30
|
-
`).filter((
|
|
31
|
-
`).filter((
|
|
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 y8($){try{if(r.statSync($).isDirectory())return $;return b.dirname($)}catch{let Z=b.dirname($);return Z!==$&&r.existsSync(Z)?Z:null}}var b0=P5(o8(),1);var y0=/^diff --git a\/.+ b\/(.+)$/;function a8($){return y0.exec($)?.[1]??null}function GZ($){let Z=new Map,K=null;for(let Q of $.lines){if(Q.type==="header"){let X=a8(Q.content);if(X!==null)K=Z.get(X)??[],Z.set(X,K)}K?.push(Q)}let V=new Map;for(let[Q,X]of Z)V.set(Q,{lines:X});return V}var MZ="diffstalker-journal: oversize untracked snapshot omitted";var c0=262144;class NZ extends g0{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 dZ($)}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=s8();Z.add(".git");let K=_.join(this.repoPath,".gitignore");if(h.existsSync(K))Z.add(h.readFileSync(K,"utf-8"));let V=_.join(this.repoPath,".git","info","exclude");if(h.existsSync(V))Z.add(h.readFileSync(V,"utf-8"));$.set("",Z);try{let Q=m0("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:f()});for(let X of Q.split("\x00")){if(!X||X===".gitignore")continue;if(!X.endsWith(".gitignore"))continue;let Y=_.dirname(X),W=_.join(this.repoPath,X);try{let J=h.readFileSync(W,"utf-8"),z=s8();z.add(J),$.set(Y,z)}catch(J){$Z(`Failed to read ${W}: ${J instanceof Error?J.message:J}`)}}}catch{}return $}startWatching(){let $=b8(this.repoPath);if($===null)return;let Z=_.join($.gitDir,"index"),K=_.join($.gitDir,"HEAD"),V=_.join($.commonDir,"refs"),Q=_.join($.commonDir,"packed-refs"),X=_.join(this.repoPath,".gitignore");this.gitWatcher=i8([Z,K,V,Q,X],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=i8(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(W,J)=>{let z=_.relative(this.repoPath,W);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 B=j===0?z:U.slice(j).join("/");if(M.ignores(B))return!0}}return KZ(W,J)},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let Y=()=>this.scheduleRefresh();this.gitWatcher.on("change",(W)=>{if(W===X)this.ignorers=this.loadGitignores();Y()}),this.gitWatcher.on("add",Y),this.gitWatcher.on("unlink",Y),this.gitWatcher.on("error",(W)=>{let J=W instanceof Error?W.message:String(W);this.setError(`Git watcher error: ${J}`)}),this.workingDirWatcher.on("change",Y),this.workingDirWatcher.on("add",Y),this.workingDirWatcher.on("unlink",Y),this.workingDirWatcher.on("error",(W)=>{let J=W instanceof Error?W.message:String(W);this.setError(`Working dir watcher error: ${J}`)})}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(_.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 cZ(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 JZ(this.repoPath).catch(()=>null);try{let K=await cZ(this.repoPath);if(!K.isRepo){this.updateState({status:K,isLoading:!1,error:"Not a git repository"});return}let[V,Q,X,Y,W]=await Promise.all([T$(this.repoPath,void 0,!1),T$(this.repoPath,void 0,!0),YZ(this.repoPath),i(this.repoPath),this.gatherJournalInputs(K,Z,$)]),J={unstaged:XZ(X$(V.lines)),staged:XZ(X$(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:J,stashList:X,operationInProgress:Y,mtimes:z,isLoading:!1}),W!==null)this.emit("journal-observation",{status:K,headDiff:W.headDiff,headOid:W.headOid,stashCount:W.stashCount,operationInProgress:W.operationInProgress,mtimes:W.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([i(this.repoPath),YZ(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 X=h.statSync(_.join(this.repoPath,Q));if(Math.floor(X.mtimeMs)>K)return!0}catch{}return!1}async gatherJournalInputs($,Z,K){if(Z===null)return null;try{let V=await this.snapshotJournalGuard($),Q=await F8(this.repoPath),X=new Set(GZ(Q).keys()),Y=[...Q.lines];await this.appendUntrackedSections($,X,Y);let W=await JZ(this.repoPath);if(Z!==W)return null;let J=await this.snapshotJournalGuard($);if(NZ.journalGuardMoved(V,J))return null;if(this.sectionWrittenDuringGather($,X,K))return null;return{headDiff:{lines:Y},headOid:W,stashCount:J.stashCount,operationInProgress:J.operation,mtimes:J.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 X;try{X=h.statSync(_.join(this.repoPath,Q.path))}catch{continue}if(!X.isFile())continue;if(X.size>c0){this.appendOversizeSection(Q.path,X,K);continue}let Y=await zZ(this.repoPath,Q.path);if(Y.lines.length===0)continue;K.push(...Y.lines)}}appendOversizeSection($,Z,K){let V=[`diff --git a/${$} b/${$}`,"new file mode 100644",`${MZ} size=${Z.size} mtime=${Math.round(Z.mtimeMs)}`];K.push(...V.map((Q)=>({type:"header",content:Q})))}async stage($){try{await this.queue.enqueueMutation(()=>r6(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(()=>t6(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()=>X8(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()=>Y8(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"?()=>K8(this.repoPath,$.path):()=>Z8(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(()=>e6(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to stage all: ${$ instanceof Error?$.message:String($)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>$8(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(()=>V8(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(()=>YZ(this.repoPath));this.updateState({stashList:$})}catch{}}}import{EventEmitter as u0}from"node:events";class aZ extends u0{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",()=>W8(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>J8(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>z8(this.repoPath))}async stash($){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stash",()=>O8(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async stashPop($=0){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stashPop",()=>G8(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async getLocalBranches(){return this.queue.enqueue(()=>WZ(this.repoPath))}async switchBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>M8(this.repoPath,$))}async createBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>N8(this.repoPath,$))}async softReset($=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>H8(this.repoPath,$))}async cherryPick($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>C8(this.repoPath,$))}async revertCommit($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>B8(this.repoPath,$))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>I8(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>A8(this.repoPath))}}import{EventEmitter as p0}from"node:events";import{randomBytes as f0}from"node:crypto";var h0=262144,d0=500,l0=16777216,e8=Number.MAX_SAFE_INTEGER,n0=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function o0($){let Z=n0.exec($);if(!Z)return null;return{oldStart:parseInt(Z[1],10),oldCount:Z[2]!==void 0?parseInt(Z[2],10):1}}function a0($,Z){let K=o0(Z);if(!K)return[];let V=K.oldCount===0?K.oldStart+1:K.oldStart,Q=[],X=null;for(let Y of $){let W=Y.content[0];if(W==="\\")continue;if(W==="-")X=i0(X,V),V++;else if(W==="+")X=X??{hasDel:!1,delStart:0,delEnd:0,anchor:V-1};else r8(Q,X),X=null,V++}return r8(Q,X),Q}function i0($,Z){if(!$)return{hasDel:!0,delStart:Z,delEnd:Z,anchor:Z-1};if(!$.hasDel)$.hasDel=!0,$.delStart=Z;return $.delEnd=Z,$}function r8($,Z){if(!Z)return;$.push(Z.hasDel?[2*Z.delStart,2*Z.delEnd]:[2*Z.anchor,2*Z.anchor+2])}function iZ($){if($.length===0)return{start:0,count:0};let Z=1/0,K=-1/0;for(let[X,Y]of $){if(X<Z)Z=X;if(Y>K)K=Y}if(K>=e8)return{start:0,count:0};let V=Math.ceil(Z/2),Q=Math.floor(K/2);return{start:V,count:Q-V+1}}function s0($){let Z=[],K=null,V=[],Q=null;for(let Y of $.lines)if(Y.type==="hunk")Q={header:Y,body:[]},V.push(Q);else if(Q)Q.body.push(Y);else if(Z.push(Y),Y.content.startsWith("rename from "))K=Y.content.slice(12);if(V.length===0){let Y=Z.some((W)=>W.content.startsWith(MZ));return{hunks:[{runs:[[0,e8]],bodyHash:UZ([X$($.lines)]),ins:0,del:0,span:{start:0,count:0},diff:$,oversize:Y}],renamedFrom:K,hunkless:!0}}return{hunks:V.map(({header:Y,body:W})=>{let J=a0(W,Y.content),z=[],U=0,j=0;for(let M of W){let B=M.content[0];if(B==="\\")continue;if(B==="+")U++,z.push(M.content);else if(B==="-")j++,z.push(M.content)}let G=[...Z,Y,...W];return{runs:J,bodyHash:UZ(z),ins:U,del:j,span:iZ(J),diff:{lines:G}}}),renamedFrom:K,hunkless:!1}}function r0($){if($.oversize===!0)return null;return QZ($.diff.lines)>h0?null:$.diff}function t0($,Z,K){if($===0&&Z>0)return"shrunk";let V=$+Z;if(V>K)return"expanded";if(V<K)return"shrunk";return"edited"}function t8($,Z){let K=[];return $.forEach((V,Q)=>{for(let[X,Y]of V.runs)K.push({lo:X,hi:Y,node:Z+Q})}),K.sort((V,Q)=>V.lo-Q.lo),K}function e0($,Z){let K=Array.from({length:$.length+Z.length},(J,z)=>z),V=(J)=>{while(K[J]!==J)K[J]=K[K[J]],J=K[J];return J},Q=(J,z)=>{let U=V(J),j=V(z);if(U!==j)K[U]=j},X=t8($,0),Y=t8(Z,$.length),W=0;for(let J of X){while(W<Y.length&&Y[W].hi<J.lo)W++;for(let z=W;z<Y.length&&Y[z].lo<=J.hi;z++)Q(J.node,Y[z].node)}return K.map((J,z)=>V(z))}function $1($,Z){let K=e0($,Z),V=new Map,Q=(X)=>{let Y=V.get(X);if(!Y)Y={prevIdx:[],nextIdx:[],minLo:1/0},V.set(X,Y);return Y};return $.forEach((X,Y)=>{let W=Q(K[Y]);W.prevIdx.push(Y);for(let[J]of X.runs)if(J<W.minLo)W.minLo=J}),Z.forEach((X,Y)=>{let W=Q(K[$.length+Y]);W.nextIdx.push(Y);for(let[J]of X.runs)if(J<W.minLo)W.minLo=J}),[...V.values()].sort((X,Y)=>X.minLo-Y.minLo)}function Z1($,Z,K){let V=[],Q=Z.map(()=>null),X=K;for(let Y of $1($,Z)){let W=Y.prevIdx.map((j)=>$[j]),J=Y.nextIdx.map((j)=>Z[j]);if(W.length===1&&J.length===1&&W[0].bodyHash===J[0].bodyHash){let j=J[0];Q[Y.nextIdx[0]]={seq:W[0].seq,runs:j.runs,bodyHash:j.bodyHash,ins:j.ins,del:j.del};continue}if(J.length===0){for(let j of W)V.push({seq:X++,kind:"reverted",span:iZ(j.runs),stats:{insertions:0,deletions:0},diff:null,supersedes:[j.seq],siblings:1});continue}let z=W.map((j)=>j.seq),U=W.reduce((j,G)=>j+G.ins+G.del,0);for(let j of Y.nextIdx){let G=Z[j],M={seq:X++,kind:W.length===0?"created":t0(G.ins,G.del,U),span:G.span,stats:{insertions:G.ins,deletions:G.del},diff:r0(G),supersedes:[...z],siblings:J.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((Y)=>Y!==null)}}function K1($,Z){let K=Array($.length).fill(!1),V=Array(Z.length).fill(null);for(let W=0;W<Z.length;W++){let J=$.findIndex((z,U)=>!K[U]&&z.bodyHash===Z[W].bodyHash);if(J!==-1)K[J]=!0,V[W]=$[J].seq}for(let W=0;W<Z.length;W++){if(V[W]!==null)continue;let J=K.findIndex((z)=>!z);if(J!==-1)K[J]=!0,V[W]=$[J].seq}let Q=$[$.length-1].seq,X=Z.map((W,J)=>{return{seq:V[J]??Q,runs:W.runs,bodyHash:W.bodyHash,ins:W.ins,del:W.del}}),Y=$.filter((W,J)=>!K[J]).map((W)=>W.seq);return{carried:X,retired:Y}}function HZ(){return{entries:[],epoch:`${Date.now().toString(36)}-${f0(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class sZ extends p0{store;constructor($){super();this.store=$}get journalStore(){return this.store}observe($){try{this.doObserve($)}catch(Z){$Z(`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+=QZ(K.diff.lines);for(let K of this.store.entries){if(Z<=l0)return;if(K.type!=="hunk"||K.diff===null||$.has(K.seq))continue;Z-=QZ(K.diff.lines),K.diff=null}}pruneEntries($){let Z=this.store.entries,K=0;while(Z.length-K>d0&&(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,X)=>this.tsFor($,Q)-this.tsFor($,X));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,X=Q?"commit":"checkout",Y=Q?$.headOid.slice(0,7):$.status.branch.current,{resolves:W,newLive:J}=this.carrySurvivors(K,V);Z.push(this.boundary(X,Y,W,$.at)),this.store.live=J;for(let[z,{hunks:U}]of K){if(J.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,X]of this.store.live){if(Z.has(Q)){V.set(Q,X);continue}let Y=$.get(Q);if(!Y){K.push(...X.map((z)=>z.seq));continue}let{carried:W,retired:J}=K1(X,Y.hunks);K.push(...J),V.set(Q,W)}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:X,renamedFrom:Y,hunkless:W}]of K){let J=this.store.live.get(Q)??[];if(W&&Y!==null&&J.length>0)continue;this.classifyPath(Q,J,X,$,!1,Z)}this.store.lastBranch=$.status.branch.current,this.store.lastStashCount=$.stashCount}handleRenames($,Z,K){for(let[V,Q]of Z){let X=Q.renamedFrom;if(X===null||X===V)continue;if(!this.store.live.has(X)||Z.has(X))continue;let Y=(this.store.live.get(V)??[]).map((W)=>W.seq);this.store.live.set(V,this.store.live.get(X)),this.store.live.delete(X),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:Y,siblings:1,seeded:!1})}}handleDisappearances($,Z,K,V){let Q=[...this.store.live.keys()].filter((X)=>!Z.has(X)&&!K.has(X));if(Q.length===0)return;if($.stashCount>this.store.lastStashCount){let X=Q.flatMap((Y)=>this.store.live.get(Y).map((W)=>W.seq));V.push(this.boundary("stash","stash",X,$.at));for(let Y of Q)this.store.live.delete(Y);return}for(let X of Q){let Y=this.store.live.get(X);V.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor($,X),path:X,status:this.statusOf($,X),kind:"reverted",span:iZ(Y.flatMap((W)=>W.runs)),stats:{insertions:0,deletions:0},diff:null,supersedes:Y.map((W)=>W.seq),siblings:1,seeded:!1}),this.store.live.delete(X)}}classifyPath($,Z,K,V,Q,X){let{entries:Y,nextLive:W}=Z1(Z,K,this.store.nextSeq);this.store.nextSeq+=Y.length;let J=this.tsFor(V,$),z=this.statusOf(V,$);for(let U of Y){let j={type:"hunk",seq:U.seq,ts:J,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};X.push(j)}if(W.length>0)this.store.live.set($,W);else this.store.live.delete($)}parseObservation($){let Z=new Map;for(let[V,Q]of GZ($.headDiff))Z.set(V,s0(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 rZ{workingTree;remote;journal;repoPath;constructor($,Z){this.repoPath=$;let K=c6($);this.workingTree=new NZ($,K),this.remote=new aZ($,K,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new sZ(Z??HZ()),this.workingTree.on("journal-observation",(V)=>this.journal.observe(V))}dispose(){this.workingTree.dispose(),u6(this.repoPath)}}function Q1($){return V1("sha256").update($).digest("hex").slice(0,12)}var X1=32;class Z4{cap;stores=new Map;constructor($=X1){this.cap=$}acquire($){let Z=this.stores.get($);if(Z)this.stores.delete($);else Z=HZ();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 tZ{events;byId=new Map;byPath=new Map;journalStores=new Z4;constructor($={}){this.events=$}async openRepo($){let Z=l($);if(!$4.isAbsolute(Z))throw Error(`Repo path must be absolute: ${$}`);let K=await E8(Z);if(!K){let W=_8(await h$(Z));if(!W)throw Error(`Not a git repository: ${Z}`);K=W.path}let V=this.byPath.get(K);if(V)return V.refCount++,{handle:V,created:!1};let Q=Q1(K),X=new rZ(K,this.journalStores.acquire(Q));X.workingTree.startWatching();let Y={id:Q,path:K,manager:X,refCount:1};return this.byId.set(Y.id,Y),this.byPath.set(K,Y),this.journalStores.prune((W)=>this.byId.has(W)),this.events.onOpened?.(Y),{handle:Y,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 CZ($,Z){let K=await $.openRepo(Z);if(K.created)K.handle.manager.workingTree.refresh().catch(()=>{});return K}var K4=25000;function l$($,Z,K){$.write(`event: ${Z}
|
|
25
|
+
`);if(Y)W.pop();if(Q.length>0){X.push({type:"hunk",content:`@@ -0,0 +1,${W.length} @@`});let U=1;for(let j of W)X.push({type:"addition",content:"+"+j,newLineNum:U++});if(!Y)X.push({type:"context",content:"\"})}let J=W$(X),z=A$(J);if(z!==J)return{lines:K$(z)};return{lines:X}}catch{return{lines:[]}}}async function dZ($){let Z=F($),K=new Set,V=[];try{let Q=await Z.raw(["log","--oneline","--decorate=short","--all","-n","200"]),X=/\(([^)]+)\)/g;for(let Y of Q.split(`
|
|
26
|
+
`)){let W=X.exec(Y);if(W){let J=W[1].split(",").map((z)=>z.trim());for(let z of J){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)}}X.lastIndex=0}if(V.length>0)V.sort((Y,W)=>{let J=Y.split("/").slice(1).join("/"),z=W.split("/").slice(1).join("/"),U=J==="main"||J==="master",j=z==="main"||z==="master";if(U&&!j)return-1;if(!U&&j)return 1;if(U&&j){let G=Y.startsWith("origin/"),M=W.startsWith("origin/");if(G&&!M)return 1;if(!G&&M)return-1}return 0})}catch{}return[...new Set(V)]}async function d$($){return(await dZ($))[0]??null}async function lZ($){return L$($)??await d$($)}async function V$($,Z){let K=F($);try{return await K.raw(["cat-file","-e","--end-of-options",`${Z}^{commit}`]),!0}catch{return!1}}async function nZ($,Z){let K=F($),Q=(await K.raw(["merge-base","--end-of-options",Z,"HEAD"])).trim();if(!Q)throw new D$(Z);let X=await K.raw(["diff","--numstat",`${Q}...HEAD`]),Y=await K.raw(["diff","--name-status",`${Q}...HEAD`]),W=A$(await K.raw(["diff",`${Q}...HEAD`])),J=X.trim().split(`
|
|
27
|
+
`).filter((O)=>O),z=new Map;for(let O of J){let H=O.split("\t");if(H.length>=3){let C=H[0]==="-"?0:parseInt(H[0],10),A=H[1]==="-"?0:parseInt(H[1],10),R=H.slice(2).join("\t");z.set(R,{additions:C,deletions:A})}}let U=Y.trim().split(`
|
|
28
|
+
`).filter((O)=>O),j=new Map;for(let O of U){let H=O.split("\t");if(H.length>=2){let C=H[0][0],A=H[H.length-1],R;switch(C){case"A":R="added";break;case"D":R="deleted";break;case"R":R="renamed";break;default:R="modified"}j.set(A,R)}}let G=[],M=W.split(/(?=^diff --git )/m).filter((O)=>O.trim());for(let O of M){let H=O.match(/^diff --git a\/.+ b\/(.+)$/m);if(!H)continue;let C=H[1],A=K$(O),R=z.get(C)||{additions:0,deletions:0},E=j.get(C)||"modified";G.push({path:C,status:E,additions:R.additions,deletions:R.deletions,diff:{lines:A}})}let B=0,I=0;for(let O of G)B+=O.additions,I+=O.deletions;let D=(await K.status()).files.length,v=(await K.log({from:Q,to:"HEAD"})).all.map((O)=>({hash:O.hash,shortHash:O.hash.slice(0,7),message:O.message.split(`
|
|
29
|
+
`)[0],author:O.author_name,date:new Date(O.date),refs:O.refs||""}));return G.sort((O,H)=>O.path.localeCompare(H.path)),{baseBranch:Z,stats:{filesChanged:G.length,additions:B,deletions:I},files:G,commits:v,uncommittedCount:D}}async function w8($,Z){let K=F($),Q=(await K.raw(["merge-base","--end-of-options",Z,"HEAD"])).trim();if(!Q)throw new D$(Z);let X=await K.raw(["rev-list","--count","--end-of-options",`${Q}..HEAD`]);return Number.parseInt(X.trim(),10)}async function k8($,Z){let K=F($);try{let V=A$(await K.raw(["show","--format=","--end-of-options",Z]));return{lines:K$(V)}}catch{return{lines:[]}}}async function E8($,Z){let K=F($),V=await nZ($,Z),Q=await K.diff(["--cached","--numstat"]),X=await K.diff(["--numstat"]),Y=await K.diff(["--cached"]),W=await K.diff([]),J=new Map;for(let O of Q.trim().split(`
|
|
30
|
+
`).filter((H)=>H)){let H=O.split("\t");if(H.length>=3){let C=H[0]==="-"?0:parseInt(H[0],10),A=H[1]==="-"?0:parseInt(H[1],10),R=H.slice(2).join("\t");J.set(R,{additions:C,deletions:A,staged:!0,unstaged:!1})}}for(let O of X.trim().split(`
|
|
31
|
+
`).filter((H)=>H)){let H=O.split("\t");if(H.length>=3){let C=H[0]==="-"?0:parseInt(H[0],10),A=H[1]==="-"?0:parseInt(H[1],10),R=H.slice(2).join("\t"),E=J.get(R);if(E)E.additions+=C,E.deletions+=A,E.unstaged=!0;else J.set(R,{additions:C,deletions:A,staged:!1,unstaged:!0})}}let z=await K.status(),U=new Map;for(let O of z.files)if(O.index==="A"||O.working_dir==="?")U.set(O.path,"added");else if(O.index==="D"||O.working_dir==="D")U.set(O.path,"deleted");else if(O.index==="R")U.set(O.path,"renamed");else U.set(O.path,"modified");let j=[],M=(Y+W).split(/(?=^diff --git )/m).filter((O)=>O.trim()),B=new Set;for(let O of M){let H=O.match(/^diff --git a\/.+ b\/(.+)$/m);if(!H)continue;let C=H[1];if(B.has(C))continue;B.add(C);let A=K$(O),R=J.get(C)||{additions:0,deletions:0},E=U.get(C)||"modified";j.push({path:C,status:E,additions:R.additions,deletions:R.deletions,diff:{lines:A},isUncommitted:!0})}let I=new Set(V.files.map((O)=>O.path)),L=[];for(let O of V.files){let H=j.find((C)=>C.path===O.path);if(H)L.push(O),L.push(H);else L.push(O)}for(let O of j)if(!I.has(O.path))L.push(O);let D=0,S=0,v=new Set;for(let O of L)v.add(O.path),D+=O.additions,S+=O.deletions;return L.sort((O,H)=>O.path.localeCompare(H.path)),{baseBranch:V.baseBranch,stats:{filesChanged:v.size,additions:D,deletions:S},files:L,commits:V.commits,uncommittedCount:V.uncommittedCount}}import*as _8 from"node:fs";import*as P8 from"node:path";var S0=/^diff --git a\/.+ b\/(.+)$/;function GZ($){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 R0($){let Z=[],K="",V=null,Q=()=>{if(V&&K)Z.push({file:K,key:`${K}\x00${GZ(V.body)}`,headerLine:V.headerLine});V=null};for(let X of $.lines)if(X.type==="header"){Q();let Y=X.content.match(S0);if(Y)K=Y[1]}else if(X.type==="hunk")Q(),V={headerLine:X,body:[]};else if(V&&(X.type==="addition"||X.type==="deletion"))V.body.push(X.content);return Q(),Z}class oZ{repoPath;stamps=new Map;constructor($){this.repoPath=$}stamp($){if(!$)return;let Z=new Map;for(let K of R0($)){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 _8.statSync(P8.join(this.repoPath,$)).mtimeMs}catch{return Date.now()}}}import*as r from"node:fs";import*as b from"node:path";async function x8($){let Z=c8($);if(!Z)return null;try{let K=F(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 l$($){let Z=c8($);if(!Z)return[];try{let V=await F(Z).raw(["worktree","list","--porcelain"]),Q=k0(V),X=await w0(Q,Z);return Q.map((Y)=>({...Y,lastActivity:Y.isBare?null:v0(y8(Y.path)),aheadOfBase:X.get(Y.path)??null}))}catch{return[]}}function v0($){return Number.isFinite($)?$:null}async function w0($,Z){let K=$.filter((X)=>!X.isBare);if(K.length===0)return new Map;let V=await d$(Z).catch(()=>null),Q=await Promise.all(K.map(async(X)=>{let Y=L$(X.path)??V;if(!Y)return null;try{let J=await F(X.path).raw(["rev-list","--count","--end-of-options",`${Y}..HEAD`]);return[X.path,parseInt(J.trim(),10)]}catch{return null}}));return new Map(Q.filter((X)=>X!==null))}function b8($){let Z=null,K=-1/0;for(let V of $){if(V.isBare)continue;let Q=y8(V.path);if(Q>K)K=Q,Z=V}return Z}function y8($){let Z=m8($),K=Z?[b.join(Z,"index"),b.join(Z,"HEAD")]:[$],V=-1/0;for(let Q of K)try{let X=r.statSync(Q).mtimeMs;if(X>V)V=X}catch{}return V}function m8($){let Z=b.join($,".git");try{if(r.statSync(Z).isDirectory())return Z;let K=r.readFileSync(Z,"utf8").match(/^gitdir:\s*(.+)$/m);if(!K)return null;let V=K[1].trim();return b.isAbsolute(V)?V:b.resolve($,V)}catch{return null}}function g8($){let Z=m8($);if(Z===null)return null;let K=Z;try{let V=r.readFileSync(b.join(Z,"commondir"),"utf8").trim();if(V)K=b.isAbsolute(V)?V:b.resolve(Z,V)}catch{}return{gitDir:Z,commonDir:K}}function k0($){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 c8($){try{if(r.statSync($).isDirectory())return $;return b.dirname($)}catch{let Z=b.dirname($);return Z!==$&&r.existsSync(Z)?Z:null}}var u0=g5(s8(),1);var p0=/^diff --git a\/.+ b\/(.+)$/;function r8($){return p0.exec($)?.[1]??null}function NZ($){let Z=new Map,K=null;for(let Q of $.lines){if(Q.type==="header"){let X=r8(Q.content);if(X!==null)K=Z.get(X)??[],Z.set(X,K)}K?.push(Q)}let V=new Map;for(let[Q,X]of Z)V.set(Q,{lines:X});return V}var CZ="diffstalker-journal: oversize untracked snapshot omitted";var d0=262144;class BZ extends h0{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 oZ($)}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=e8();Z.add(".git");let K=_.join(this.repoPath,".gitignore");if(h.existsSync(K))Z.add(h.readFileSync(K,"utf-8"));let V=_.join(this.repoPath,".git","info","exclude");if(h.existsSync(V))Z.add(h.readFileSync(V,"utf-8"));$.set("",Z);try{let Q=f0("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:f()});for(let X of Q.split("\x00")){if(!X||X===".gitignore")continue;if(!X.endsWith(".gitignore"))continue;let Y=_.dirname(X),W=_.join(this.repoPath,X);try{let J=h.readFileSync(W,"utf-8"),z=e8();z.add(J),$.set(Y,z)}catch(J){VZ(`Failed to read ${W}: ${J instanceof Error?J.message:J}`)}}}catch{}return $}startWatching(){let $=g8(this.repoPath);if($===null)return;let Z=_.join($.gitDir,"index"),K=_.join($.gitDir,"HEAD"),V=_.join($.commonDir,"refs"),Q=_.join($.commonDir,"packed-refs"),X=_.join(this.repoPath,".gitignore");this.gitWatcher=t8([Z,K,V,Q,X],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=t8(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(W,J)=>{let z=_.relative(this.repoPath,W);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 B=j===0?z:U.slice(j).join("/");if(M.ignores(B))return!0}}return XZ(W,J)},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let Y=()=>this.scheduleRefresh();this.gitWatcher.on("change",(W)=>{if(W===X)this.ignorers=this.loadGitignores();Y()}),this.gitWatcher.on("add",Y),this.gitWatcher.on("unlink",Y),this.gitWatcher.on("error",(W)=>{let J=W instanceof Error?W.message:String(W);this.setError(`Git watcher error: ${J}`)}),this.workingDirWatcher.on("change",Y),this.workingDirWatcher.on("add",Y),this.workingDirWatcher.on("unlink",Y),this.workingDirWatcher.on("error",(W)=>{let J=W instanceof Error?W.message:String(W);this.setError(`Working dir watcher error: ${J}`)})}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(_.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 fZ(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 jZ(this.repoPath).catch(()=>null);try{let K=await fZ(this.repoPath);if(!K.isRepo){this.updateState({status:K,isLoading:!1,error:"Not a git repository"});return}let[V,Q,X,Y,W]=await Promise.all([q$(this.repoPath,void 0,!1),q$(this.repoPath,void 0,!0),zZ(this.repoPath),i(this.repoPath),this.gatherJournalInputs(K,Z,$)]),J={unstaged:JZ(W$(V.lines)),staged:JZ(W$(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:J,stashList:X,operationInProgress:Y,mtimes:z,isLoading:!1}),W!==null)this.emit("journal-observation",{status:K,headDiff:W.headDiff,headOid:W.headOid,stashCount:W.stashCount,operationInProgress:W.operationInProgress,mtimes:W.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([i(this.repoPath),zZ(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 X=h.statSync(_.join(this.repoPath,Q));if(Math.floor(X.mtimeMs)>K)return!0}catch{}return!1}async gatherJournalInputs($,Z,K){if(Z===null)return null;try{let V=await this.snapshotJournalGuard($),Q=await v8(this.repoPath),X=new Set(NZ(Q).keys()),Y=[...Q.lines];await this.appendUntrackedSections($,X,Y);let W=await jZ(this.repoPath);if(Z!==W)return null;let J=await this.snapshotJournalGuard($);if(BZ.journalGuardMoved(V,J))return null;if(this.sectionWrittenDuringGather($,X,K))return null;return{headDiff:{lines:Y},headOid:W,stashCount:J.stashCount,operationInProgress:J.operation,mtimes:J.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 X;try{X=h.statSync(_.join(this.repoPath,Q.path))}catch{continue}if(!X.isFile())continue;if(X.size>d0){this.appendOversizeSection(Q.path,X,K);continue}let Y=await OZ(this.repoPath,Q.path);if(Y.lines.length===0)continue;K.push(...Y.lines)}}appendOversizeSection($,Z,K){let V=[`diff --git a/${$} b/${$}`,"new file mode 100644",`${CZ} size=${Z.size} mtime=${Math.round(Z.mtimeMs)}`];K.push(...V.map((Q)=>({type:"header",content:Q})))}async stage($){try{await this.queue.enqueueMutation(()=>$8(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(()=>Z8(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()=>J8(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()=>z8(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"?()=>X8(this.repoPath,$.path):()=>Q8(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(()=>K8(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to stage all: ${$ instanceof Error?$.message:String($)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>V8(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(()=>Y8(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(()=>zZ(this.repoPath));this.updateState({stashList:$})}catch{}}}import{EventEmitter as l0}from"node:events";class rZ extends l0{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",()=>U8(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>j8(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>O8(this.repoPath))}async stash($){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stash",()=>H8(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async stashPop($=0){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stashPop",()=>N8(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async getLocalBranches(){return this.queue.enqueue(()=>UZ(this.repoPath))}async switchBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>C8(this.repoPath,$))}async createBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>B8(this.repoPath,$))}async softReset($=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>I8(this.repoPath,$))}async cherryPick($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>A8(this.repoPath,$))}async revertCommit($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>L8(this.repoPath,$))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>T8(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>D8(this.repoPath))}}import{EventEmitter as n0}from"node:events";import{randomBytes as o0}from"node:crypto";var a0=262144,i0=500,s0=16777216,K4=Number.MAX_SAFE_INTEGER,r0=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function t0($){let Z=r0.exec($);if(!Z)return null;return{oldStart:parseInt(Z[1],10),oldCount:Z[2]!==void 0?parseInt(Z[2],10):1}}function e0($,Z){let K=t0(Z);if(!K)return[];let V=K.oldCount===0?K.oldStart+1:K.oldStart,Q=[],X=null;for(let Y of $){let W=Y.content[0];if(W==="\\")continue;if(W==="-")X=$1(X,V),V++;else if(W==="+")X=X??{hasDel:!1,delStart:0,delEnd:0,anchor:V-1};else $4(Q,X),X=null,V++}return $4(Q,X),Q}function $1($,Z){if(!$)return{hasDel:!0,delStart:Z,delEnd:Z,anchor:Z-1};if(!$.hasDel)$.hasDel=!0,$.delStart=Z;return $.delEnd=Z,$}function $4($,Z){if(!Z)return;$.push(Z.hasDel?[2*Z.delStart,2*Z.delEnd]:[2*Z.anchor,2*Z.anchor+2])}function tZ($){if($.length===0)return{start:0,count:0};let Z=1/0,K=-1/0;for(let[X,Y]of $){if(X<Z)Z=X;if(Y>K)K=Y}if(K>=K4)return{start:0,count:0};let V=Math.ceil(Z/2),Q=Math.floor(K/2);return{start:V,count:Q-V+1}}function Z1($){let Z=[],K=null,V=[],Q=null;for(let Y of $.lines)if(Y.type==="hunk")Q={header:Y,body:[]},V.push(Q);else if(Q)Q.body.push(Y);else if(Z.push(Y),Y.content.startsWith("rename from "))K=Y.content.slice(12);if(V.length===0){let Y=Z.some((W)=>W.content.startsWith(CZ));return{hunks:[{runs:[[0,K4]],bodyHash:GZ([W$($.lines)]),ins:0,del:0,span:{start:0,count:0},diff:$,oversize:Y}],renamedFrom:K,hunkless:!0}}return{hunks:V.map(({header:Y,body:W})=>{let J=e0(W,Y.content),z=[],U=0,j=0;for(let M of W){let B=M.content[0];if(B==="\\")continue;if(B==="+")U++,z.push(M.content);else if(B==="-")j++,z.push(M.content)}let G=[...Z,Y,...W];return{runs:J,bodyHash:GZ(z),ins:U,del:j,span:tZ(J),diff:{lines:G}}}),renamedFrom:K,hunkless:!1}}function K1($){if($.oversize===!0)return null;return WZ($.diff.lines)>a0?null:$.diff}function V1($,Z,K){if($===0&&Z>0)return"shrunk";let V=$+Z;if(V>K)return"expanded";if(V<K)return"shrunk";return"edited"}function Z4($,Z){let K=[];return $.forEach((V,Q)=>{for(let[X,Y]of V.runs)K.push({lo:X,hi:Y,node:Z+Q})}),K.sort((V,Q)=>V.lo-Q.lo),K}function Q1($,Z){let K=Array.from({length:$.length+Z.length},(J,z)=>z),V=(J)=>{while(K[J]!==J)K[J]=K[K[J]],J=K[J];return J},Q=(J,z)=>{let U=V(J),j=V(z);if(U!==j)K[U]=j},X=Z4($,0),Y=Z4(Z,$.length),W=0;for(let J of X){while(W<Y.length&&Y[W].hi<J.lo)W++;for(let z=W;z<Y.length&&Y[z].lo<=J.hi;z++)Q(J.node,Y[z].node)}return K.map((J,z)=>V(z))}function X1($,Z){let K=Q1($,Z),V=new Map,Q=(X)=>{let Y=V.get(X);if(!Y)Y={prevIdx:[],nextIdx:[],minLo:1/0},V.set(X,Y);return Y};return $.forEach((X,Y)=>{let W=Q(K[Y]);W.prevIdx.push(Y);for(let[J]of X.runs)if(J<W.minLo)W.minLo=J}),Z.forEach((X,Y)=>{let W=Q(K[$.length+Y]);W.nextIdx.push(Y);for(let[J]of X.runs)if(J<W.minLo)W.minLo=J}),[...V.values()].sort((X,Y)=>X.minLo-Y.minLo)}function Y1($,Z,K){let V=[],Q=Z.map(()=>null),X=K;for(let Y of X1($,Z)){let W=Y.prevIdx.map((j)=>$[j]),J=Y.nextIdx.map((j)=>Z[j]);if(W.length===1&&J.length===1&&W[0].bodyHash===J[0].bodyHash){let j=J[0];Q[Y.nextIdx[0]]={seq:W[0].seq,runs:j.runs,bodyHash:j.bodyHash,ins:j.ins,del:j.del};continue}if(J.length===0){for(let j of W)V.push({seq:X++,kind:"reverted",span:tZ(j.runs),stats:{insertions:0,deletions:0},diff:null,supersedes:[j.seq],siblings:1});continue}let z=W.map((j)=>j.seq),U=W.reduce((j,G)=>j+G.ins+G.del,0);for(let j of Y.nextIdx){let G=Z[j],M={seq:X++,kind:W.length===0?"created":V1(G.ins,G.del,U),span:G.span,stats:{insertions:G.ins,deletions:G.del},diff:K1(G),supersedes:[...z],siblings:J.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((Y)=>Y!==null)}}function W1($,Z){let K=Array($.length).fill(!1),V=Array(Z.length).fill(null);for(let W=0;W<Z.length;W++){let J=$.findIndex((z,U)=>!K[U]&&z.bodyHash===Z[W].bodyHash);if(J!==-1)K[J]=!0,V[W]=$[J].seq}for(let W=0;W<Z.length;W++){if(V[W]!==null)continue;let J=K.findIndex((z)=>!z);if(J!==-1)K[J]=!0,V[W]=$[J].seq}let Q=$[$.length-1].seq,X=Z.map((W,J)=>{return{seq:V[J]??Q,runs:W.runs,bodyHash:W.bodyHash,ins:W.ins,del:W.del}}),Y=$.filter((W,J)=>!K[J]).map((W)=>W.seq);return{carried:X,retired:Y}}function IZ(){return{entries:[],epoch:`${Date.now().toString(36)}-${o0(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class eZ extends n0{store;constructor($){super();this.store=$}get journalStore(){return this.store}observe($){try{this.doObserve($)}catch(Z){VZ(`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+=WZ(K.diff.lines);for(let K of this.store.entries){if(Z<=s0)return;if(K.type!=="hunk"||K.diff===null||$.has(K.seq))continue;Z-=WZ(K.diff.lines),K.diff=null}}pruneEntries($){let Z=this.store.entries,K=0;while(Z.length-K>i0&&(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,X)=>this.tsFor($,Q)-this.tsFor($,X));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,X=Q?"commit":"checkout",Y=Q?$.headOid.slice(0,7):$.status.branch.current,{resolves:W,newLive:J}=this.carrySurvivors(K,V);Z.push(this.boundary(X,Y,W,$.at)),this.store.live=J;for(let[z,{hunks:U}]of K){if(J.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,X]of this.store.live){if(Z.has(Q)){V.set(Q,X);continue}let Y=$.get(Q);if(!Y){K.push(...X.map((z)=>z.seq));continue}let{carried:W,retired:J}=W1(X,Y.hunks);K.push(...J),V.set(Q,W)}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:X,renamedFrom:Y,hunkless:W}]of K){let J=this.store.live.get(Q)??[];if(W&&Y!==null&&J.length>0)continue;this.classifyPath(Q,J,X,$,!1,Z)}this.store.lastBranch=$.status.branch.current,this.store.lastStashCount=$.stashCount}handleRenames($,Z,K){for(let[V,Q]of Z){let X=Q.renamedFrom;if(X===null||X===V)continue;if(!this.store.live.has(X)||Z.has(X))continue;let Y=(this.store.live.get(V)??[]).map((W)=>W.seq);this.store.live.set(V,this.store.live.get(X)),this.store.live.delete(X),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:Y,siblings:1,seeded:!1})}}handleDisappearances($,Z,K,V){let Q=[...this.store.live.keys()].filter((X)=>!Z.has(X)&&!K.has(X));if(Q.length===0)return;if($.stashCount>this.store.lastStashCount){let X=Q.flatMap((Y)=>this.store.live.get(Y).map((W)=>W.seq));V.push(this.boundary("stash","stash",X,$.at));for(let Y of Q)this.store.live.delete(Y);return}for(let X of Q){let Y=this.store.live.get(X);V.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor($,X),path:X,status:this.statusOf($,X),kind:"reverted",span:tZ(Y.flatMap((W)=>W.runs)),stats:{insertions:0,deletions:0},diff:null,supersedes:Y.map((W)=>W.seq),siblings:1,seeded:!1}),this.store.live.delete(X)}}classifyPath($,Z,K,V,Q,X){let{entries:Y,nextLive:W}=Y1(Z,K,this.store.nextSeq);this.store.nextSeq+=Y.length;let J=this.tsFor(V,$),z=this.statusOf(V,$);for(let U of Y){let j={type:"hunk",seq:U.seq,ts:J,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};X.push(j)}if(W.length>0)this.store.live.set($,W);else this.store.live.delete($)}parseObservation($){let Z=new Map;for(let[V,Q]of NZ($.headDiff))Z.set(V,Z1(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 $6{workingTree;remote;journal;repoPath;constructor($,Z){this.repoPath=$;let K=f6($);this.workingTree=new BZ($,K),this.remote=new rZ($,K,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new eZ(Z??IZ()),this.workingTree.on("journal-observation",(V)=>this.journal.observe(V))}dispose(){this.workingTree.dispose(),h6(this.repoPath)}}function z1($){return J1("sha256").update($).digest("hex").slice(0,12)}var U1=32;class Q4{cap;stores=new Map;constructor($=U1){this.cap=$}acquire($){let Z=this.stores.get($);if(Z)this.stores.delete($);else Z=IZ();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 Z6{events;byId=new Map;byPath=new Map;journalStores=new Q4;constructor($={}){this.events=$}async openRepo($){let Z=l($);if(!V4.isAbsolute(Z))throw Error(`Repo path must be absolute: ${$}`);let K=await x8(Z);if(!K){let W=b8(await l$(Z));if(!W)throw Error(`Not a git repository: ${Z}`);K=W.path}let V=this.byPath.get(K);if(V)return V.refCount++,{handle:V,created:!1};let Q=z1(K),X=new $6(K,this.journalStores.acquire(Q));X.workingTree.startWatching();let Y={id:Q,path:K,manager:X,refCount:1};return this.byId.set(Y.id,Y),this.byPath.set(K,Y),this.journalStores.prune((W)=>this.byId.has(W)),this.events.onOpened?.(Y),{handle:Y,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 AZ($,Z){let K=await $.openRepo(Z);if(K.created)K.handle.manager.workingTree.refresh().catch(()=>{});return K}var X4=25000;function o$($,Z,K){$.write(`event: ${Z}
|
|
33
33
|
data: ${K}
|
|
34
34
|
|
|
35
|
-
`)}class
|
|
35
|
+
`)}class K6{channels=new Map;subscribe($,Z,K,V){V.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});let Q=this.channels.get($);if(!Q){let Y=new Set,W={manager:Z,subscribers:Y,listener:(J)=>{let z=JSON.stringify(Z$(J));if(z===W.lastData)return;W.lastData=z;for(let U of Y)o$(U,"state-change",z)},journalListener:(J)=>{let z=JSON.stringify({epoch:Z.journal.journalStore.epoch,entries:yZ(J)});for(let U of Y)o$(U,"journal-append",z)},keepAlive:setInterval(()=>{for(let J of Y)J.write(`: ping
|
|
36
36
|
|
|
37
|
-
`)},
|
|
37
|
+
`)},X4),lastData:null};Z.workingTree.on("state-change",W.listener),Z.journal.on("append",W.journalListener),W.keepAlive.unref(),Q=W,this.channels.set($,Q)}Q.subscribers.add(V),K.on("close",()=>this.unsubscribe($,V));let X=JSON.stringify(Z$(Z.workingTree.state));o$(V,"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 of Z.subscribers)K.end();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 V6{subscribers=new Set;keepAlive=null;subscribe($,Z,K){if(Z.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),this.subscribers.add(Z),!this.keepAlive)this.keepAlive=setInterval(()=>{for(let V of this.subscribers)V.write(`: ping
|
|
38
38
|
|
|
39
|
-
`)},
|
|
39
|
+
`)},X4),this.keepAlive.unref();$.on("close",()=>{if(this.subscribers.delete(Z),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),o$(Z,"snapshot",JSON.stringify(K))}broadcast($,Z){let K=JSON.stringify(Z);for(let V of this.subscribers)o$(V,$,K)}destroy(){if(this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null;for(let $ of this.subscribers)$.end();this.subscribers.clear()}}import*as U$ from"node:fs";import*as LZ from"node:path";import{watch as j1}from"chokidar";import{EventEmitter as O1}from"node:events";class Q6 extends O1{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 LZ.isAbsolute(Z)?Z:LZ.resolve(Z)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let $=U$.readFileSync(this.targetFile,"utf-8"),Z=xZ($);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
40
|
`),process.stderr.write(` Source file: ${this.targetFile}
|
|
41
41
|
`),process.stderr.write(` Raw content: "${Z}"
|
|
42
42
|
`),process.stderr.write(` Previous: "${this.lastReadPath??"(none)"}"
|
|
43
43
|
`),process.stderr.write(` Resolved: "${K}"
|
|
44
|
-
`);this.lastReadPath=K,this.updateState({path:K,lastUpdate:V,rawContent:Z})}}catch{}}start(){if(
|
|
44
|
+
`);this.lastReadPath=K,this.updateState({path:K,lastUpdate:V,rawContent:Z})}}catch{}}start(){if(v6(this.targetFile),!U$.existsSync(this.targetFile))U$.writeFileSync(this.targetFile,"");try{let $=U$.readFileSync(this.targetFile,"utf-8"),Z=xZ($);if(Z){let K=this.processContent(Z),V=new Date;if(this.debug&&K)process.stderr.write(`[diffstalker ${V.toISOString()}] Initial path read
|
|
45
45
|
`),process.stderr.write(` Source file: ${this.targetFile}
|
|
46
46
|
`),process.stderr.write(` Raw content: "${Z}"
|
|
47
47
|
`),process.stderr.write(` Resolved: "${K}"
|
|
48
|
-
`);this.lastReadPath=K,this._state={path:K,lastUpdate:V,rawContent:Z,sourceFile:this.targetFile}}}catch{}this.watcher=
|
|
49
|
-
`,{mode:384}),c.renameSync(Z,this.file)}catch(K){throw c.rmSync(Z,{force:!0}),K}return this.current}}import*as z4 from"node:path";import{watch as I1}from"chokidar";import*as o from"node:fs/promises";import*as m from"node:path";var U1=2,j1=500,O1=new Set(["node_modules","vendor","target","dist","build","venv","__pycache__"]);async function Y4($){try{return await o.stat(m.join($,".git")),!0}catch{return!1}}async function G1($){let Z=m.join($,".git"),K;try{K=await o.stat(Z)}catch{return null}if(K.isDirectory())return Z;try{let V=await o.readFile(Z,"utf-8"),Q=/^gitdir:\s*(.+)$/m.exec(V);if(!Q)return null;let X=Q[1].trim(),Y=m.isAbsolute(X)?X:m.resolve($,X);return await o.stat(Y),Y}catch{return null}}async function M1($){let Z;try{Z=(await o.readFile(m.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 N1($){let K=(await Promise.all(["index","HEAD"].map(async(V)=>{try{return(await o.stat(m.join($,V))).mtimeMs}catch{return null}}))).filter((V)=>V!==null);return K.length===0?null:Math.max(...K)}async function H1($){let Z=await G1($);if(Z===null)return null;let[K,V]=await Promise.all([M1(Z),N1(Z)]);return{path:$,name:m.basename($),branch:K,lastActivity:V}}function C1($){if(!$.isDirectory())return!1;if($.name.startsWith("."))return!1;return!O1.has($.name)}async function W4($){let Z=await X6($);return Promise.all(Z.map(async(K)=>({name:m.basename(K),path:K,isRepo:await Y4(K)})))}async function X6($){return(await o.readdir($,{withFileTypes:!0})).filter(C1).map((K)=>m.join($,K.name)).sort()}async function B1($,Z,K){let V=[],Q=[];for(let X of $){if(V.length>=K)return{repos:V,next:Q,capped:!0};if(await Y4(X)){V.push(X);continue}if(!Z)continue;try{Q.push(...await X6(X))}catch{}}return{repos:V,next:Q,capped:!1}}async function J4($,Z={}){let K=Z.depth??U1,V=Z.limit??j1,Q=await X6($),X=[],Y=!1;for(let J=1;J<=K&&Q.length>0&&!Y;J++){let z=await B1(Q,J<K,V-X.length);X.push(...z.repos),Y=z.capped,Q=z.next.sort()}return{repos:(await Promise.all(X.map(H1))).filter((J)=>J!==null),capped:Y}}var A1=300;function L1($,Z){let K=z4.basename($);if(K.startsWith(".")&&K!==".")return!0;if(K==="node_modules")return!0;return KZ($,Z)}class Y6{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 J4($);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=I1($,{persistent:!0,ignoreInitial:!0,depth:1,ignored:L1});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())},A1),Z.timer.unref?.()}broadcast(){if(this.disposed)return;this.hub.broadcast("discovery-change",this.state)}}import*as j4 from"node:fs";var T1="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",D1=21600000,q1=300000,F1=5000;function W6(){try{let $=j4.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 S1(){let $=await fetch(T1,{headers:{accept:"application/json"},signal:AbortSignal.timeout(F1)});if(!$.ok)return null;let Z=await $.json();return typeof Z.latest==="string"?Z.latest:null}function U4($){let Z=/^(\d+)\.(\d+)\.(\d+)/.exec($.trim());if(!Z)return null;return[Number(Z[1]),Number(Z[2]),Number(Z[3])]}function R1($,Z){if($===null||Z===null)return"unknown";let K=U4($),V=U4(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 O4($=S1,Z=W6()){let K=null,V=null;function Q(){if(K&&Date.now()<K.expiresAt)return Promise.resolve(K.value);if(V)return V;return V=$().catch(()=>null).then((X)=>{let Y=X===null?q1:D1;return K={value:X,expiresAt:Date.now()+Y},V=null,X}),V}return{async state(){let X=await Q();return{current:Z,latest:X,status:R1(Z,X)}}}}import*as G4 from"node:os";function M4($,Z){$.get("/health",({res:K})=>{T(K,200,{ok:!0,ready:!0,home:G4.homedir(),symbols:{extensions:Z.symbols?.extensions??[]}})})}function N4($,Z){$.get("/version",async({res:K})=>{T(K,200,await Z.version.state())})}import*as n$ from"node:fs";import*as P from"node:path";function q($,Z){let K=$.getRepo(Z);if(!K)throw new H(404,`Unknown repo id: ${Z}`);return K}function u($,Z,K){if(typeof $!=="object"||$===null)throw new H(400,`Expected a JSON body with "${Z}"`);let V=$[Z];if(typeof V!=="string"||!K?.allowEmpty&&V.length===0)throw new H(400,`Missing "${Z}" (string) in body`);return V}function z$($,Z){let K=u($,Z);if(K.startsWith("-"))throw new H(400,`Invalid "${Z}" (must not start with "-"): ${K}`);return K}function C4($,Z){if(typeof $!=="object"||$===null)throw new H(400,`Expected a JSON body with "${Z}"`);let K=$[Z];if(!Array.isArray(K)||K.some((V)=>typeof V!=="string"))throw new H(400,`Missing "${Z}" (array of strings) in body`);return K}function B4($,Z){if(typeof $!=="object"||$===null)return;let K=$[Z];if(K===void 0)return;if(typeof K!=="string"||K.length===0)throw new H(400,`Invalid "${Z}" (expected a non-empty string)`);return K}function U6($,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 H(400,`Invalid "${Z}" (expected an integer >= ${K.min})`);return V}function I4($,Z){if(typeof $!=="object"||$===null)return!1;let K=$[Z];if(K===void 0)return!1;if(typeof K!=="boolean")throw new H(400,`Invalid "${Z}" (expected a boolean)`);return K}function V$($,Z,K){let V=$.get(Z);if(V===null)return K;if(V==="true")return!0;if(V==="false")return!1;throw new H(400,`Invalid "${Z}" (expected true or false): ${V}`)}function A4($,Z,K,V){let Q=$.get(Z);if(Q===null)return K;let X=Number(Q);if(!Number.isInteger(X)||X<1)throw new H(400,`Invalid "${Z}" (expected a positive integer): ${Q}`);if(V!==void 0&&X>V)throw new H(400,`Invalid "${Z}" (must be <= ${V}): ${Q}`);return X}async function t($){if(!$.state.status)await $.refresh();let Z=$.state.status;if(!Z)throw new H(500,"Repository status unavailable");return Z}function H4($,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 q$($,Z,K){let V=await t($),Q=H4(V,Z,K);if(!Q)await $.refresh(),V=await t($),Q=H4(V,Z,K);if(!Q)throw new H(404,`File not in status: ${Z}`);return Q}function z6($,Z){return $===Z||$.startsWith(Z+P.sep)}function j6($){return $.replace(/[. ]+$/,"").toLowerCase()===".git"}function U$($,Z){if(Z.length===0)throw new H(400,"Empty path");if(Z.includes("\x00"))throw new H(400,"Path contains a NUL byte");let K=P.resolve($),V=P.relative(K,P.resolve(K,Z));if(V==="")throw new H(400,`Path resolves to the repository root: ${Z}`);if(P.isAbsolute(V)||V===".."||V.startsWith(`..${P.sep}`))throw new H(400,`Path escapes repository root: ${Z}`);if(V.startsWith("-"))throw new H(400,`Path must not start with "-": ${Z}`);if(V.startsWith(":"))throw new H(400,`Path must not start with ":": ${Z}`);if(V.split(P.sep).some(j6))throw new H(400,`Path addresses the git directory: ${Z}`);return V}async function L4($){try{return await n$.promises.realpath($)}catch{return null}}var J6=new WeakMap;async function v1($){let Z=J6.get($);if(!Z)Z=(async()=>{let K=await F($.path).raw(["rev-parse","--absolute-git-dir"]);return await n$.promises.realpath(K.trim())})(),J6.set($,Z),Z.catch(()=>J6.delete($));try{return await Z}catch{throw new H(500,"Cannot resolve the git directory for this repository")}}async function j$($,Z){let K=await n$.promises.realpath(P.resolve($.path)),V=await L4(P.join($.path,Z));if(V===null)return;if(!z6(V,K))throw new H(400,`Path escapes repository root: ${Z}`);if(z6(V,await v1($)))throw new H(400,`Path addresses the git directory: ${Z}`)}async function T4($,Z){let K=await n$.promises.realpath(P.resolve($)),V=[];for(let Q of Z){let X=await L4(P.join($,Q.path));if(X===null||z6(X,K))V.push(Q)}return V}function O6($){return $?.code??null}function w1($){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test($)?409:500}async function e($,Z,K){$.clearError(),await K();let V=$.state.error;if(V){T(Z,w1(V),{error:V});return}await $.refresh(),T(Z,200,{state:$$($.state)})}function k1($){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 H(409,`A ${V.remoteState.operation??"remote"} operation is already in progress`);if(V.remoteState.inProgress)throw Q();let X=await K();if(X===null)throw Q();if(X.error){T(Z,k1(X.error),{error:X.error});return}let Y=$.manager.workingTree;await Y.refresh(),T(Z,200,{state:$$(Y.state),result:X.lastResult})}function D4($,Z){let{registry:K}=Z;$.get("/repos",({res:V})=>{let Q=K.listRepos().map((X)=>({id:X.id,path:X.path,branch:X.manager.workingTree.state.status?.branch.current??null}));T(V,200,Q)}),$.post("/repos",async({body:V,res:Q})=>{let X=u(V,"path"),Y;try{Y=await CZ(K,X)}catch(W){throw new H(400,W instanceof Error?W.message:String(W))}T(Q,Y.created?201:200,{id:Y.handle.id,path:Y.handle.path})}),$.get("/repos/:id/worktrees",async({params:V,res:Q})=>{let X=q(K,V.id);T(Q,200,await h$(X.path))}),$.get("/worktrees",async({query:V,res:Q})=>{let X=V.get("path");if(!X)throw new H(400,'Missing "path" query parameter');T(Q,200,await h$(X))}),$.delete("/repos/:id",({params:V,res:Q})=>{q(K,V.id),K.closeRepo(V.id),T(Q,200,{})})}function q4($,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 F4($){return $.trim()}async function E1($){let Z=(V)=>V.filter((Q)=>Q.staged).length,K=Z((await t($)).files);if(K===0)await $.refresh(),K=Z((await t($)).files);return K}function S4($,Z){let{registry:K,sse:V}=Z;if($.get("/repos/:id/status",async({params:Q,res:X})=>{let Y=q(K,Q.id);await t(Y.manager.workingTree);let W=$$(Y.manager.workingTree.state);W.operationInProgress=await i(Y.path),T(X,200,W)}),$.get("/repos/:id/diff",async({params:Q,query:X,res:Y})=>{let W=q(K,Q.id),J=X.get("path")??void 0,z=V$(X,"staged",!1),U;if(J){let G=(await t(W.manager.workingTree)).files.some((M)=>M.path===J&&M.status==="untracked");if(G&&z)throw new H(400,`staged=true is meaningless for untracked file: ${J} (untracked files have no staged diff)`);U=G?await zZ(W.path,J):await T$(W.path,J,z)}else U=await T$(W.path,void 0,z);W.manager.workingTree.stampDiff(U),T(Y,200,U)}),$.post("/repos/:id/stage",async({params:Q,body:X,res:Y})=>{let W=q(K,Q.id),J=u(X,"path"),z=W.manager.workingTree,U=await q$(z,J,!1);await e(z,Y,()=>z.stage(U))}),$.post("/repos/:id/unstage",async({params:Q,body:X,res:Y})=>{let W=q(K,Q.id),J=u(X,"path"),z=W.manager.workingTree,U=await q$(z,J,!0);await e(z,Y,()=>z.unstage(U))}),$.get("/repos/:id/events",({params:Q,req:X,res:Y})=>{let W=q(K,Q.id);V.subscribe(Q.id,W.manager,X,Y)}),Z.apiMode==="full")_1($,Z)}function _1($,Z){let{registry:K}=Z;$.post("/repos/:id/stage-all",async({params:V,res:Q})=>{let Y=q(K,V.id).manager.workingTree;await e(Y,Q,()=>Y.stageAll())}),$.post("/repos/:id/unstage-all",async({params:V,res:Q})=>{let Y=q(K,V.id).manager.workingTree;await e(Y,Q,()=>Y.unstageAll())}),$.post("/repos/:id/discard",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=u(Q,"path"),J=Y.manager.workingTree,z=await q$(J,W,!1);if(z.staged)throw new H(409,`Cannot discard a staged file: ${W} (unstage it first)`);await e(J,X,()=>J.discard(z))}),$.post("/repos/:id/commit",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=u(Q,"message",{allowEmpty:!0}),J=I4(Q,"amend"),z=Y.manager.workingTree,U=await E1(z),j=q4(W,U,J);if(!j.valid)throw new H(400,j.error??"Invalid commit");await e(z,X,()=>z.commit(F4(W),J))}),$.post("/repos/:id/stage-hunk",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=u(Q,"patch"),J=Y.manager.workingTree;await e(J,X,()=>J.stageHunk(W))}),$.post("/repos/:id/unstage-hunk",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=u(Q,"patch"),J=Y.manager.workingTree;await e(J,X,()=>J.unstageHunk(W))})}async function P1($){let Z=await fZ($);if(Z&&await K$($,Z))return Z;if(I$($)){let K=await f$($);if(K&&await K$($,K))return K}throw new H(422,"No usable base branch")}async function R4($,Z){let K=Z.get("base");if(K===null)return P1($);if(!await K$($,K))throw new H(400,`Unknown base ref: ${K}`);return K}function v4($,Z){let{registry:K}=Z;if($.get("/repos/:id/history",async({params:V,query:Q,res:X})=>{let Y=q(K,V.id),W=A4(Q,"count",100,5000);T(X,200,await U8(Y.path,W))}),$.get("/repos/:id/commits/:hash",async({params:V,res:Q})=>{let X=q(K,V.id),Y=V.hash;if(!/^[0-9a-f]{4,40}$/i.test(Y))throw new H(400,`Invalid commit hash: ${Y}`);let W=await j8(X.path,Y);if(W===null)throw new H(404,`Unknown commit: ${Y}`);T(Q,200,W)}),$.get("/repos/:id/commits/:hash/diff",async({params:V,res:Q})=>{let X=q(K,V.id),Y=V.hash;if(!/^[0-9a-f]{4,40}$/i.test(Y))throw new H(400,`Invalid commit hash: ${Y}`);if(!await K$(X.path,Y))throw new H(404,`Unknown commit: ${Y}`);T(Q,200,await R8(X.path,Y))}),$.get("/repos/:id/head-message",async({params:V,res:Q})=>{let X=q(K,V.id);T(Q,200,{message:await Q8(X.path)})}),$.get("/repos/:id/branches",async({params:V,res:Q})=>{let X=q(K,V.id);T(Q,200,await WZ(X.path))}),$.get("/repos/:id/base-branches",async({params:V,res:Q})=>{let X=q(K,V.id);T(Q,200,await pZ(X.path))}),$.get("/repos/:id/compare/base",async({params:V,res:Q})=>{let X=q(K,V.id);T(Q,200,{base:await fZ(X.path)})}),Z.apiMode==="full")$.put("/repos/:id/compare/base",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=z$(Q,"branch");if(!await K$(Y.path,W))throw new H(400,`Not a valid base ref: ${W}`);D8(Y.path,W),T(X,200,{base:W})});$.get("/repos/:id/compare/count",async({params:V,query:Q,res:X})=>{let Y=q(K,V.id),W=await R4(Y.path,Q);try{T(X,200,{baseBranch:W,commits:await S8(Y.path,W)})}catch(J){if(J instanceof L$)throw new H(422,J.message);throw J}}),$.get("/repos/:id/compare",async({params:V,query:Q,res:X})=>{let Y=q(K,V.id),W=V$(Q,"uncommitted",!1),J=await R4(Y.path,Q),z;try{z=W?await v8(Y.path,J):await hZ(Y.path,J)}catch(U){if(U instanceof L$)throw new H(422,U.message);throw U}T(X,200,z)})}function x1($){let Z=$.get("since");if(Z===null)return 0;if(!/^\d+$/.test(Z))throw new H(400,`Invalid "since" (expected a non-negative integer): ${Z}`);return Number(Z)}function w4($,Z){let{registry:K}=Z;$.get("/repos/:id/journal",({params:V,query:Q,res:X})=>{let Y=q(K,V.id),W=x1(Q);T(X,200,R6(Y.manager.journal.journalStore,W))})}function k4($,Z){let{registry:K}=Z;$.post("/repos/:id/push",async({params:V,res:Q})=>{let X=q(K,V.id);await g(X,Q,()=>X.manager.remote.push())}),$.post("/repos/:id/fetch",async({params:V,res:Q})=>{let X=q(K,V.id);await g(X,Q,()=>X.manager.remote.fetchRemote())}),$.post("/repos/:id/pull",async({params:V,res:Q})=>{let X=q(K,V.id);await g(X,Q,()=>X.manager.remote.pullRebase())}),$.post("/repos/:id/stash",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=B4(Q,"message");await g(Y,X,()=>Y.manager.remote.stash(W))}),$.post("/repos/:id/stash-pop",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=U6(Q,"index",{min:0,fallback:0});await g(Y,X,()=>Y.manager.remote.stashPop(W))}),$.post("/repos/:id/switch-branch",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=z$(Q,"name");await g(Y,X,()=>Y.manager.remote.switchBranch(W))}),$.post("/repos/:id/create-branch",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=z$(Q,"name");await g(Y,X,()=>Y.manager.remote.createBranch(W))}),$.post("/repos/:id/soft-reset",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=U6(Q,"count",{min:1,fallback:1});if(!await K$(Y.path,`HEAD~${W}`))throw new H(400,`Cannot soft-reset ${W} commit(s): HEAD~${W} does not exist`);await g(Y,X,()=>Y.manager.remote.softReset(W))}),$.post("/repos/:id/cherry-pick",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=z$(Q,"hash");await g(Y,X,()=>Y.manager.remote.cherryPick(W))}),$.post("/repos/:id/revert",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=z$(Q,"hash");await g(Y,X,()=>Y.manager.remote.revertCommit(W))}),$.post("/repos/:id/abort",async({params:V,res:Q})=>{let X=q(K,V.id);if(!await i(X.path))throw new H(409,"No operation in progress to abort");await g(X,Q,()=>X.manager.remote.abortOperation())}),$.post("/repos/:id/rebase-continue",async({params:V,res:Q})=>{let X=q(K,V.id);if(await i(X.path)!=="rebase")throw new H(409,"No rebase in progress to continue");await g(X,Q,()=>X.manager.remote.rebaseContinue())})}import*as O$ from"node:fs";import*as o$ from"node:path";var R$=8388608;var E4=65536;function F$($){return Array.from($,(Z)=>Z.charCodeAt(0))}function S$($,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 IZ($,Z){return $[Z]*16777216+($[Z+1]<<16)+($[Z+2]<<8)+$[Z+3]}function G6($,Z){return($[Z]<<8)+$[Z+1]}function AZ($,Z){return $[Z]+($[Z+1]<<8)}function _4($,Z){return String.fromCharCode($[Z],$[Z+1],$[Z+2],$[Z+3])}function w($){return{ok:!1,refusal:$}}function v$($){return w($?"malformed":"header-not-found")}function M6($,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 b1=[137,80,78,71,13,10,26,10],y1=[255,216,255],m1=F$("GIF87a"),g1=F$("GIF89a"),a=F$("ftyp");function d($){return{offset:8,bytes:F$($)}}var c1=[{label:"webp",offset:0,bytes:F$("RIFF"),brand:d("WEBP")},{label:"avif",offset:4,bytes:a,brand:d("avif")},{label:"avis",offset:4,bytes:a,brand:d("avis")},{label:"heic",offset:4,bytes:a,brand:d("heic")},{label:"heix",offset:4,bytes:a,brand:d("heix")},{label:"heim",offset:4,bytes:a,brand:d("heim")},{label:"heis",offset:4,bytes:a,brand:d("heis")},{label:"hevc",offset:4,bytes:a,brand:d("hevc")},{label:"hevx",offset:4,bytes:a,brand:d("hevx")},{label:"mif1",offset:4,bytes:a,brand:d("mif1")},{label:"msf1",offset:4,bytes:a,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:F$("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 u1($){return c1.some((Z)=>S$($,Z.offset,Z.bytes)&&(Z.brand===void 0||S$($,Z.brand.offset,Z.brand.bytes)))}var p1={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},f1=26;function h1($,Z,K){if($.length<f1)return v$(K);if(IZ($,8)!==13)return w("malformed");if(_4($,12)!=="IHDR")return w("malformed");let V=IZ($,16),Q=IZ($,20),X=M6(V,Q);if(X)return w(X);let Y=p1[$[25]];if(!Y||!Y.includes($[24]))return w("malformed");let W=d1($,K);if(W)return W;return{ok:!0,info:{format:"png",mime:"image/png",width:V,height:Q,bytes:Z}}}function d1($,Z){let K=8;for(let V=0;V<256;V++){if(K+8>$.length)return v$(Z);let Q=IZ($,K),X=_4($,K+4);if(X==="IDAT")return null;if(X==="acTL")return w("animation");if(X==="iCCP"&&Q>65536)return w("malformed");let Y=K+12+Q;if(Y<=K||!Number.isSafeInteger(Y))return w("malformed");K=Y}return w("malformed")}var l1=218,n1=226,o1=new Set([219,238,192,193,194,196]);function a1($){return $>=224&&$<=239||o1.has($)}function i1($){return $===1||$>=208&&$<=217}function s1($){return $>=192&&$<=207&&$!==196&&$!==200&&$!==204}var r1=new Set([192,193,194]);function t1($,Z,K){if($.length<4)return v$(K);if(!a1($[3]))return w("malformed");return Z7($,Z,K)}function e1($,Z,K,V,Q){if(!r1.has(K))return w("malformed");if(Z+9>$.length)return v$(Q);let X=G6($,Z+5),Y=G6($,Z+7),W=M6(Y,X);if(W)return w(W);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:Y,height:X,bytes:V}}}function $7($,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(i1(K))return{kind:"skip",next:Z+2};if(K===l1)return{kind:"malformed"};if(Z+4>$.length)return{kind:"ran-out"};let V=G6($,Z+2);if(V<2)return{kind:"malformed"};if(s1(K))return{kind:"sof",marker:K};return{kind:"segment",marker:K,length:V}}function Z7($,Z,K){let V=2,Q=0;for(let X=0;X<1024;X++){let Y=$7($,V);if(Y.kind==="ran-out")return v$(K);if(Y.kind==="malformed")return w("malformed");if(Y.kind==="sof")return e1($,V,Y.marker,Z,K);if(Y.kind==="skip"){V=Y.next;continue}if(Y.marker===n1){if(Q+=Y.length-2,Q>65536)return w("malformed")}V+=2+Y.length}return w("malformed")}var K7=59,V7=44,Q7=33;function P4($){return($&128)===0?0:3*(1<<($&7)+1)}function X7($,Z,K){if(Z>2097152)return w("too-large");if(!K)return w("header-not-found");if($.length<13)return v$(K);let V=AZ($,6),Q=AZ($,8),X=M6(V,Q);if(X)return w(X);let Y={pos:13+P4($[10]),left:8192,pixels:0,overBudget:!1},W=Y7($,Y);if(W===null)return w("malformed");if(W<1)return w("malformed");if(W>256)return w("too-many-pixels");if(Y.overBudget)return w("too-many-pixels");if(W*V*Q>33554432)return w("too-many-pixels");let J={format:"gif",mime:"image/gif",width:V,height:Q,bytes:Z};if(W>1)J.frames=W;return{ok:!0,info:J}}function Y7($,Z){let K=0;while(Z.left-- >0){if(Z.pos>=$.length)return null;let V=$[Z.pos];if(V===K7)return K;let Q=V===V7;if(!(Q?J7($,Z):W7($,Z,V)))return null;if(Q&&++K>256)return K;if(Z.overBudget)return K}return null}function W7($,Z,K){if(K!==Q7)return!1;return Z.pos+=2,x4($,Z)}function J7($,Z){if(Z.pos+10>$.length)return!1;z7(Z,AZ($,Z.pos+5),AZ($,Z.pos+7));let K=$[Z.pos+9];return Z.pos+=10+P4(K)+1,x4($,Z)}function z7($,Z,K){let V=Z*K;if(Z>8192||K>8192||V>16777216){$.overBudget=!0;return}if($.pixels+=V,$.pixels>33554432)$.overBudget=!0}function x4($,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 b4($){return S$($,0,m1)||S$($,0,g1)}function w$($,Z,K){if(Z>8388608)return w("too-large");if(S$($,0,b1))return h1($,Z,K);if(S$($,0,y1))return t1($,Z,K);if(b4($))return X7($,Z,K);if(u1($))return w("unsupported-format");return w("not-an-image")}function LZ($,Z){return b4($)?Math.min(Z,2097152):65536}function N6($){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 X=0;X<V.length-1;X++)Q=Q?`${Q}/${V[X]}`:V[X],Z.directories.add(Q);Z.directories.add("")}return Z}var U7=1048576,y4=5000;class a$ extends Error{constructor($){super(`Not a regular file: ${$}`);this.name="NotRegularFileError"}}async function g4($,Z,K,V){let Q=K?.hideHidden??!0,X=K?.hideGitignored??!0,Y=o$.join($,Z),W=await O$.promises.readdir(Y,{withFileTypes:!0}),J=W.map((j)=>Z?o$.join(Z,j.name):j.name),z=X?await VZ($,J):new Set,U=[];for(let j of W){if(Q&&j.name.startsWith("."))continue;let G=Z?o$.join(Z,j.name):j.name;if(X&&z.has(G))continue;let M=j.isDirectory(),B={name:j.name,path:G,type:M?"dir":"file"};if(V)if(M){if(V.directories.has(G))B.hasChanges=!0}else{let I=V.files.get(G);if(I)B.gitStatus=I.status,B.staged=I.staged}U.push(B)}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 j7=16,O7=O$.constants.O_RDONLY|(O$.constants.O_NONBLOCK??0);async function H6($,Z,K){let V=Buffer.alloc(Z),Q=0;while(Q<Z){let{bytesRead:X}=await $.read(V,Q,Z-Q,K+Q);if(X===0)break;Q+=X}return Q===Z?V:V.subarray(0,Q)}async function G7($,Z){let K=await H6($,Math.min(j7,Z),0),V=w$(K,Z,K.length>=Z);if(!V.ok&&V.refusal==="too-large")return{head:K,result:V};let Q=Math.min(LZ(K,Z),Z),X=Q<=K.length?K.subarray(0,Q):Buffer.concat([K,await H6($,Q-K.length,K.length)]);return{head:X,result:w$(X,Z,X.length>=Z)}}function M7($,Z){return $.ok?{image:$.info,refusal:null,version:Z}:{image:null,refusal:$.refusal,version:Z}}function m4($,Z){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:$,totalLines:0,media:Z}}function C6($,Z){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:$,totalLines:0,media:Z}}function N7($,Z){let K=$.toString("utf-8"),V=K.split(`
|
|
50
|
-
`),Q=!1;if(V.length>y4)K=V.slice(0,y4).join(`
|
|
51
|
-
`),Q=!
|
|
52
|
-
`))throw new k$("Query cannot span lines — this searches for literal text");try{let{stdout:K}=await I7("git",R7(Z),{cwd:$,env:f(),encoding:"buffer",maxBuffer:T7,timeout:D7,windowsHide:!0});return d4(K)}catch(K){let V=K;if(V.code===1)return h4;if(V.killed===!0||V.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...V.stdout?d4(V.stdout):h4,incomplete:!0};throw K}}function n4($,Z){let{registry:K}=Z;$.post("/repos/:id/search",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=u(Q,"query");try{let J=await l4(Y.path,W);T(X,200,J)}catch(J){if(J instanceof DZ)throw new H(400,`Query must be at least ${TZ} characters`);if(J instanceof k$)throw new H(400,J.message);throw J}})}import{Worker as v7}from"node:worker_threads";var w7=1000,k7=64,E7={status:"unavailable",reason:"deadline"},i$={status:"unavailable",reason:"error"};function _7(){let $=import.meta.url;return $.endsWith(".ts")?new URL("./symbolWorker.ts",$):new URL("./symbolWorker.js",$)}function o4($){let Z=$.timeoutMs??w7,K=new Set($.extensions),V=null,Q=0,X=Promise.resolve(),Y=!1,W=new Map;function J(G,M){W.delete(G),W.set(G,M);while(W.size>k7){let B=W.keys().next().value;if(B===void 0)break;W.delete(B)}}function z(){let G=V;if(V=null,G!==null)G.terminate()}function U(){let G=new v7(_7(),{workerData:{grammarDir:$.grammarDir,queryDir:$.queryDir}});return G.unref(),G}function j(G,M){return new Promise((B)=>{if(V===null)try{V=U()}catch{B(i$);return}let I=V,L=++Q,D=!1,S=(R,E)=>{if(D)return;if(D=!0,clearTimeout(C),I.off("message",v),I.off("error",O),I.off("exit",N),E)z();B(R)},v=(R)=>{if(R.seq!==L)return;S(R.outcome,!1)},O=()=>S(i$,!0),N=()=>S(i$,!0),C=setTimeout(()=>S(E7,!0),Z);C.unref?.(),I.on("message",v),I.on("error",O),I.on("exit",N);let A={seq:L,relPath:G,content:M};try{I.postMessage(A)}catch{S(i$,!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(Y)return i$;let B=`${G}\x00${M}`,I=W.get(B);if(I!==void 0)return J(B,I),I;let L=X.then(()=>j(G,M));X=L.catch(()=>{return});let D=await L;return J(B,D),D},async dispose(){Y=!0;let G=V;if(V=null,W.clear(),G!==null)await G.terminate()}}}import{execFile as P7,spawn as x7}from"node:child_process";import*as s$ from"node:fs";import*as i4 from"node:path";import{promisify as b7}from"node:util";var y7=b7(P7);class E$ extends Error{constructor($){super(`Not a regular blob: ${$}`);this.name="NotRegularBlobError"}}class _$ extends Error{size;constructor($,Z){super(`Blob too large: ${$} (${Z} bytes)`);this.name="BlobTooLargeError",this.size=Z}}class G$ extends Error{constructor($){super(`Unsafe blob path: ${$}`);this.name="UnsafeBlobPathError"}}var s4=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"],r4=5000,qZ=65536,t4=/^[0-9a-f]{40}([0-9a-f]{24})?$/,m7=new Set(["100644","100755"]);function g7($){if($==="")throw new G$("empty");if($.includes("\x00"))throw new G$("contains NUL");if($.startsWith("-"))throw new G$('starts with "-"');if($.startsWith(":"))throw new G$('starts with ":"')}async function FZ($,Z,K){let{stdout:V}=await y7("git",[...s4,...Z],{cwd:$,env:f(),encoding:"buffer",maxBuffer:K,timeout:r4,windowsHide:!0});return V}function e4($){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 $5($,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 c7=1;async function u7($){let Z;try{Z=(await FZ($,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],qZ)).toString("utf8").trim()}catch(K){if(K?.code===c7)return null;throw K}return t4.test(Z)?Z:null}async function p7($,Z){let K=await u7($);if(K===null)return null;let V=await FZ($,["ls-tree","-z","--full-tree","-l",K,"--",Z],qZ),Q=$5(e4(V),Z);if(Q===null||Q.length!==4)return null;return{mode:Q[0],oid:Q[2],sizeText:Q[3]}}async function f7($,Z){let K=await FZ($,["ls-files","--stage","-z","--",Z],qZ),V=$5(e4(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 Z5($,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 h7($,Z,K){let V=await FZ($,["cat-file","-s",Z],qZ);return Z5(V.toString("utf8").trim(),K)}var a4=Buffer.alloc(0);async function d7($,Z,K){let V=Buffer.alloc(K),Q=0;while(Q<K){let{bytesRead:X}=await $.read(V,Q,K-Q,Z+Q);if(X===0)break;Q+=X}return Q===K?V:V.subarray(0,Q)}function K5($,Z){let K=a4,V=!1;return{async read(Q){let X=Math.max(0,Math.min(Q,$));if(X>K.length&&!V){let Y=await Z(X,K);V=Y.length<X,K=Y}return K.subarray(0,Math.min(X,K.length))},release(){K=a4,V=!1}}}function l7($,Z){let K=null,V=[],Q=0,X=!1,Y=null,W=null,J=!1,z=null,U=()=>X&&Y!==null,j=()=>{if(V.length!==1){let I=Buffer.concat(V,Q);V.length=0,V.push(I)}return V[0]};function G(){if(z===null)return;if(W===null&&U()&&Y?.signal===null&&Y.code!==0)W=Error(`git cat-file blob failed for ${Z} (exit ${Y.code??"null"})`);if(W===null&&Q<z.want&&!U())return;let I=z;if(z=null,clearTimeout(I.timer),K?.stdout?.pause(),W!==null)I.reject(W);else I.resolve(j().subarray(0,Math.min(I.want,Q)))}function M(I){W??=I,G()}function B(){let I=x7("git",[...s4,"cat-file","blob",Z],{cwd:$,env:f(),stdio:["ignore","pipe","ignore"],windowsHide:!0});K=I,I.stdout?.on("data",(L)=>{if(J)return;V.push(L),Q+=L.length,G()}),I.stdout?.on("end",()=>{X=!0,G()}),I.stdout?.on("error",M),I.on("error",M),I.on("close",(L,D)=>{Y={code:L,signal:D},G()})}return{read(I){if(W!==null)return Promise.reject(W);if(J)return Promise.reject(Error(`read after close for ${Z}`));if(I<=Q||U())return Promise.resolve(j().subarray(0,Math.min(I,Q)));if(z!==null)return Promise.reject(Error(`concurrent read of ${Z}`));return new Promise((L,D)=>{let S=setTimeout(()=>{K?.kill("SIGKILL"),M(Error(`git cat-file blob timed out for ${Z}`))},r4);if(z={want:I,resolve:L,reject:D,timer:S},K===null)B();else K.stdout?.resume()})},release(){if(J=!0,z!==null)M(Error(`git cat-file blob closed while reading ${Z}`));V.length=0,Q=0,K?.kill("SIGKILL"),K=null}}}function n7($){let Z=$?.code;return Z==="ENOENT"||Z==="ENOTDIR"}async function o7($,Z,K){let V=i4.join($,Z),Q;try{Q=await s$.promises.open(V,s$.constants.O_RDONLY|(s$.constants.O_NONBLOCK??0))}catch(X){if(n7(X))return null;throw X}try{let X=await Q.stat();if(!X.isFile())throw new E$(Z);if(X.size>K)throw new _$(Z,X.size);let Y=X.size,W=K5(Y,async(J,z)=>{let U=await d7(Q,z.length,J-z.length);return z.length===0?U:Buffer.concat([z,U])});return{oid:null,size:Y,version:`${Y}-${X.mtimeMs}`,read:(J)=>W.read(J),close:()=>{return W.release(),Q.close()}}}catch(X){try{await Q.close()}catch{}throw X}}async function a7($,Z,K,V){let Q=Z==="head"?await p7($,K):await f7($,K);if(Q===null)return null;if(!m7.has(Q.mode))throw new E$(K);if(!t4.test(Q.oid))throw Error(`git reported a malformed object id for ${K}`);let X=Q.oid,Y=Q.sizeText===null?await h7($,X,K):Z5(Q.sizeText,K);if(Y>V)throw new _$(K,Y);let W=l7($,X),J=K5(Y,(z)=>W.read(z));return{oid:X,size:Y,version:X,read:(z)=>J.read(z),close(){return J.release(),W.release(),Promise.resolve()}}}async function V5($,Z,K,V){if(g7(K),Z==="worktree")return o7($,K,V);return a7($,Z,K,V)}var i7=["worktree","index","head"],s7=16,r7=E4,t7=R$,e7=["too-large","too-many-pixels"];function Q5($){let Z=$.get("path");if(Z===null)throw new H(400,'Missing "path" query parameter');return Z}function $9($){let Z=$.get("side");if(Z===null||!i7.includes(Z))throw new H(400,'Invalid "side" (expected worktree, index or head)');return Z}function Z9($){let Z=$.get("staged");if(Z==="1")return!0;if(Z==="0")return!1;throw new H(400,'Invalid "staged" (expected 0 or 1)')}function J5($){if($ instanceof E$)throw new H(400,$.message);if($ instanceof G$)throw new H(400,$.message);if($ instanceof _$)throw new H(413,$.message);throw $}async function X5($,Z){let K=await $.read(Z);return{bytes:K,sniff:w$(K,$.size,K.length>=$.size)}}async function K9($,Z){let{size:K}=$,V=await $.read(s7),Q=w$(V,K,V.length>=K);if(!Q.ok&&Q.refusal==="too-large")return{bytes:V,sniff:Q};let X=Math.min(LZ(V,K),K),Y=await X5($,Math.max(X,Math.min(Z,K)));if(Y.sniff.ok||Y.sniff.refusal!=="header-not-found")return Y;if(Y.bytes.length>=K)return Y;return X5($,K)}async function z5($,Z,K,V){let Q=await V5($,Z,K,R$);if(Q===null)return null;try{let{bytes:X,sniff:Y}=await K9(Q,V);return{bytes:X,size:Q.size,oid:Q.oid,version:Q.version,sniff:Y}}finally{await Q.close()}}function V9($,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 Q9($){let Z=e7.includes($)?413:415;return new H(Z,`Image not served: ${$}`)}function X9($,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 Y9($,Z,K){return{path:$.path,side:$.side,bytes:Z,oid:null,image:null,refusal:K,version:""}}async function Y5($,Z){let K=U$($.path,Z.path);await j$($,K);let V;try{V=await z5($.path,Z.side,K,r7)}catch(Q){if(Q instanceof _$)return Y9(Z,Q.size,"too-large");if(Q instanceof E$)return null;J5(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 W9($,Z){return Z.writableEnded||Z.destroyed===!0||$.destroyed===!0}async function W5($,Z,K){let V=$.acquire();if(V===null)throw new H(503,"Too many image requests in flight");let Q=await V;if(K.once("finish",Q),K.once("close",Q),Z.once("close",Q),W9(Z,K))return Q(),!1;return!0}function U5($,Z,K){let{registry:V}=Z;$.get("/repos/:id/media",async({params:Q,query:X,req:Y,res:W})=>{let J=q(V,Q.id),z=Z9(X),U=U$(J.path,Q5(X));if(await j$(J,U),!await W5(K,Y,W))return;let j=await q$(J.manager.workingTree,U,z),G=X9(j,z),M={old:G.old===null?null:await Y5(J,G.old),new:G.new===null?null:await Y5(J,G.new)};T(W,200,M)}),$.get("/repos/:id/blob",async({params:Q,query:X,req:Y,res:W})=>{let J=q(V,Q.id),z=y6(Y);if(z)throw new H(z.status,z.message);let U=$9(X),j=U$(J.path,Q5(X));if(await j$(J,j),!await W5(K,Y,W))return;let G;try{G=await z5(J.path,U,j,t7)}catch(B){J5(B)}if(G===null)throw new H(404,`No such blob on side ${U}: ${j}`);if(!G.sniff.ok)throw Q9(G.sniff.refusal);let M=V9(U,G.sniff.info.mime,G.oid);v6(W,200,G.bytes,M)})}function j5($,Z){let{registry:K,daemonEvents:V,follow:Q}=Z;$.get("/events",({req:X,res:Y})=>{let W=K.listRepos().map((J)=>({id:J.id,path:J.path}));V.subscribe(X,Y,W)}),$.get("/follow",({res:X})=>{T(X,200,Q?Q.state:V4)})}import*as I6 from"node:os";import*as P$ from"node:path";function O5($,Z){let{settings:K,discovery:V,daemonEvents:Q}=Z;$.get("/settings",({res:X})=>{T(X,200,{...K.settings,persisted:K.persisted})}),$.put("/settings",async({body:X,res:Y})=>{let W=C4(X,"watchRoots"),J;try{J=X4(W)}catch(U){throw new H(400,U instanceof Error?U.message:String(U))}try{K.save({...K.settings,watchRoots:J})}catch(U){let j=U instanceof Error?U.message:String(U);throw new H(500,`Could not save settings: ${j}`)}await V.setRoots(J);let z={...K.settings,persisted:K.persisted};Q.broadcast("settings-change",z),T(Y,200,z)}),$.get("/discovered",({res:X})=>{T(X,200,V.state)}),$.get("/browse",async({query:X,res:Y})=>{let W=X.get("path"),J=W?l(W):I6.homedir();if(!P$.isAbsolute(J))throw new H(400,`Path must be absolute: ${W}`);let z=P$.resolve(J),U;try{U=await W4(z)}catch{throw new H(404,`Cannot read directory: ${z}`)}let j=P$.dirname(z);T(Y,200,{path:z,parent:j===z?null:j,home:I6.homedir(),entries:U})}),$.post("/discovered/rescan",async({res:X})=>{T(X,200,await V.rescan())})}function A6($=4,Z=64){let K=0,V=[];function Q(){let X=!1;return()=>{if(X)return;X=!0;let Y=V.shift();if(Y)Y(Q());else K--}}return{acquire(){if(K<$)return K++,Promise.resolve(Q());if(V.length>=Z)return null;return new Promise((X)=>{V.push(X)})},get active(){return K},get queued(){return V.length}}}function J9($){if(!M$.existsSync($))return Promise.resolve(!1);return new Promise((Z)=>{try{let K=M5.connect($);K.once("connect",()=>{K.destroy(),Z(!0)}),K.once("error",()=>{K.destroy(),Z(!1)})}catch{Z(!1)}})}function N5($={}){let Z=new eZ,K=new $6,V=new tZ({onOpened:(O)=>K.broadcast("repo-opened",{id:O.id,path:O.path}),onClosed:(O)=>{Z.closeRepo(O),K.broadcast("repo-closed",{id:O})}}),Q=$.followFile?new K6(V,K,$.followFile):null,X=O4($.updateCheck===!1?()=>Promise.resolve(null):$.fetchLatestVersion),Y=new Q6($.settingsFile??null),W=new Y6(K),J=new Map,z=A6(),U=$.symbols??null,j=U===null?null:{pool:o4(U),gate:A6(1,4),extensions:U.extensions};function G(O){let N=J.get(O);if(N)return N;let C=new xZ,A={registry:V,sse:Z,daemonEvents:K,follow:Q,settings:Y,discovery:W,apiMode:O,version:X,symbols:j};if(M4(C,A),N4(C,A),D4(C,A),S4(C,A),v4(C,A),w4(C,A),O==="full")k4(C,A);return u4(C,A),n4(C,A),U5(C,A,z),j5(C,A),O5(C,A),J.set(O,C),C}let M=(O)=>$.apiMode??(O==="tcp"?"web":"full");Q?.start(),W.setRoots(Y.load().watchRoots);let B=$.webRoot?E6($.webRoot):void 0,I=new Set,L=[];function D(O){let N=G(O),C=G5.createServer((A,R)=>{for(let[E,r$]of Object.entries(m6))R.setHeader(E,r$);if(x6(C.address())){let E=b6(A);if(E){T(R,E.status,{error:E.message});return}}N.handle(A,R,B).catch(()=>R.end())});return C.on("connection",(A)=>{I.add(A),A.on("close",()=>I.delete(A))}),C}async function S(O,N){let C=O==="unix"?N.socketPath??null:null;if(C){if(await J9(C))throw Error(`diffstalkerd already running at ${C}`);M$.rmSync(C,{force:!0})}let A={server:D(M(O)),socketPath:C};L.push(A),await new Promise((R,E)=>{let r$=(F5)=>E(F5);A.server.once("error",r$);let RZ=()=>{if(A.server.removeListener("error",r$),C)M$.chmodSync(C,384);R()};if(O==="fd")A.server.listen({fd:N.fd},RZ);else if(C)process.umask(63),A.server.listen(C,RZ);else A.server.listen(N.port,"127.0.0.1",RZ)})}function v(O){return new Promise((N,C)=>{O.server.close((A)=>{if(O.socketPath)M$.rmSync(O.socketPath,{force:!0});if(A&&A.code!=="ERR_SERVER_NOT_RUNNING")C(A);else N()})})}return{address(){return L[0]?.server.address()??null},addresses(){return L.map((O)=>O.server.address()).filter((O)=>O!==null)},getRepo(O){return V.getRepo(O)},async openRepo(O){let{handle:N}=await CZ(V,O);return{id:N.id,path:N.path}},async listen(O){let N=[];if(O.fd!==void 0)N.push("fd");if(O.socketPath)N.push("unix");if(O.port!==void 0)N.push("tcp");if(N.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let C of N)await S(C,O)},close(){Q?.dispose(),W.dispose(),Z.destroy(),K.destroy(),V.disposeAll();for(let N of I)N.destroy();let O=j?.pool.dispose()??Promise.resolve();return Promise.all([O,...L.splice(0).map(v)]).then(()=>{})}}}import*as L6 from"node:fs";import*as x$ from"node:path";import*as L5 from"node:crypto";import{createRequire as U9}from"node:module";var H5=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 C5(){return[...H5.keys()]}function z9($){let Z=$.slice($.lastIndexOf("/")+1),K=Z.lastIndexOf(".");if(K<=0)return"";return Z.slice(K).toLowerCase()}function B5($){return H5.get(z9($))??null}var j9="diffstalkerd-grammars";function O9($){return L5.createHash("sha256").update($).digest("hex")}function G9($){try{let Z=JSON.parse(L6.readFileSync(x$.join($,"checksums.json"),"utf8"));if(typeof Z.webTreeSitterVersion!=="string"||typeof Z.files!=="object")return null;return Z}catch{return null}}var I5="0.26.11";function M9($,Z,K){for(let[V,Q]of Object.entries(Z.files)){let X;try{X=L6.readFileSync(x$.join($,V))}catch{return K(`grammars: missing ${V}`),!1}if(O9(X)!==Q)return K(`grammars: checksum mismatch for ${V}`),!1}return!0}function N9($){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 A5($,Z=()=>{}){let K=G9($);if(K===null)return Z(`grammars: no readable checksums.json in ${$}`),null;if(K.webTreeSitterVersion!==I5)return Z(`grammars: built for web-tree-sitter ${K.webTreeSitterVersion}, this daemon bundles ${I5} — symbols disabled`),null;if(!M9($,K,Z))return null;let V=N9(K),Q=C5().filter((X)=>{let Y=B5(`x${X}`);return Y!==null&&V.has(Y.grammar)});if(Q.length===0)return Z("grammars: no usable grammar found"),null;return{grammarDir:$,queryDir:x$.join($,"queries"),extensions:Q}}function T5($,Z=()=>{}){if($!==null)return A5($,Z);try{let V=U9(import.meta.url).resolve(`${j9}/checksums.json`);return A5(x$.dirname(V),Z)}catch{return null}}var q5="diffstalkerd.sock";function C9($){return $===void 0?q5:`${$}.sock`}var B9=3,D5=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
|
|
48
|
+
`);this.lastReadPath=K,this._state={path:K,lastUpdate:V,rawContent:Z,sourceFile:this.targetFile}}}catch{}this.watcher=j1(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 Y4={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class X6{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 Q6(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 F$ from"node:path";function W4(){return{watchRoots:[]}}var Y6=16;function G1($){let Z=$.trim();if(!Z)throw Error("Watch directory cannot be empty");let K=l(Z);if(!F$.isAbsolute(K))throw Error(`Watch directory must be absolute: ${$}`);let V=F$.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 J4($){if($.length>Y6)throw Error(`Too many watch directories (max ${Y6})`);let Z=new Set,K=[];for(let V of $){let Q=G1(V);if(Z.has(Q))continue;Z.add(Q),K.push(Q)}return K}function M1($){let Z=W4();if(typeof $!=="object"||$===null)return Z;let K=$;if(Array.isArray(K.watchRoots))Z.watchRoots=K.watchRoots.filter((V)=>typeof V==="string").slice(0,Y6);return Z}class W6{file;current=W4();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=M1(JSON.parse($))}catch(Z){QZ(`Ignoring invalid settings file ${this.file}: ${String(Z)}`)}return this.current}save($){if(this.current=$,!this.file)return this.current;c.mkdirSync(F$.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 O4 from"node:path";import{watch as q1}from"chokidar";import*as o from"node:fs/promises";import*as m from"node:path";var H1=2,N1=500,C1=new Set(["node_modules","vendor","target","dist","build","venv","__pycache__"]);async function z4($){try{return await o.stat(m.join($,".git")),!0}catch{return!1}}async function B1($){let Z=m.join($,".git"),K;try{K=await o.stat(Z)}catch{return null}if(K.isDirectory())return Z;try{let V=await o.readFile(Z,"utf-8"),Q=/^gitdir:\s*(.+)$/m.exec(V);if(!Q)return null;let X=Q[1].trim(),Y=m.isAbsolute(X)?X:m.resolve($,X);return await o.stat(Y),Y}catch{return null}}async function I1($){let Z;try{Z=(await o.readFile(m.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 A1($){let K=(await Promise.all(["index","HEAD"].map(async(V)=>{try{return(await o.stat(m.join($,V))).mtimeMs}catch{return null}}))).filter((V)=>V!==null);return K.length===0?null:Math.max(...K)}async function L1($){let Z=await B1($);if(Z===null)return null;let[K,V]=await Promise.all([I1(Z),A1(Z)]);return{path:$,name:m.basename($),branch:K,lastActivity:V}}function T1($){if(!$.isDirectory())return!1;if($.name.startsWith("."))return!1;return!C1.has($.name)}async function U4($){let Z=await J6($);return Promise.all(Z.map(async(K)=>({name:m.basename(K),path:K,isRepo:await z4(K)})))}async function J6($){return(await o.readdir($,{withFileTypes:!0})).filter(T1).map((K)=>m.join($,K.name)).sort()}async function D1($,Z,K){let V=[],Q=[];for(let X of $){if(V.length>=K)return{repos:V,next:Q,capped:!0};if(await z4(X)){V.push(X);continue}if(!Z)continue;try{Q.push(...await J6(X))}catch{}}return{repos:V,next:Q,capped:!1}}async function j4($,Z={}){let K=Z.depth??H1,V=Z.limit??N1,Q=await J6($),X=[],Y=!1;for(let J=1;J<=K&&Q.length>0&&!Y;J++){let z=await D1(Q,J<K,V-X.length);X.push(...z.repos),Y=z.capped,Q=z.next.sort()}return{repos:(await Promise.all(X.map(L1))).filter((J)=>J!==null),capped:Y}}var F1=300;function S1($,Z){let K=O4.basename($);if(K.startsWith(".")&&K!==".")return!0;if(K==="node_modules")return!0;return XZ($,Z)}class z6{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 j4($);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=q1($,{persistent:!0,ignoreInitial:!0,depth:1,ignored:S1});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())},F1),Z.timer.unref?.()}broadcast(){if(this.disposed)return;this.hub.broadcast("discovery-change",this.state)}}import*as N4 from"node:fs";import{execFile as R1}from"node:child_process";import*as Q$ from"node:fs";import*as t from"node:path";import{fileURLToPath as v1}from"node:url";var G4={method:"unknown",package:null,command:null},a$="diffstalkerd",w1=3000,k1=["paru","yay"],E1=[{method:"bun",pattern:/\/install\/global\/node_modules\/diffstalkerd$/,command:`bun add -g ${a$}`},{method:"pnpm",pattern:/\/pnpm\/global\/\d+\/node_modules\/diffstalkerd$/,command:`pnpm add -g ${a$}`},{method:"yarn",pattern:/\/yarn\/global\/node_modules\/diffstalkerd$/,command:`yarn global add ${a$}`},{method:"npm",pattern:/\/lib\/node_modules\/diffstalkerd$/,command:`npm install -g ${a$}`}];async function _1($,Z){let K=$.split(t.sep).join("/").replace(/\/+$/,"");for(let Q of E1){if(!Q.pattern.test(K))continue;let X=Z.writable($)?"":"sudo ";return{method:Q.method,package:a$,command:`${X}${Q.command}`}}let V=await Z.pacmanOwner(t.join($,"package.json"));if(V!==null){let Q=Z.onPath(k1);return{method:"pacman",package:V,command:Q?`${Q} -S ${V}`:`sudo pacman -Syu ${V}`}}return G4}var P1={onPath($){let Z=(process.env.PATH??"").split(t.delimiter).filter(Boolean);for(let K of $)for(let V of Z)try{return Q$.accessSync(t.join(V,K),Q$.constants.X_OK),K}catch{}return null},pacmanOwner($){return new Promise((Z)=>{R1("pacman",["-Qoq","--",$],{timeout:w1},(K,V)=>{if(K)return Z(null);let Q=V.trim().split(`
|
|
50
|
+
`)[0]?.trim();Z(Q?Q:null)})})},writable($){try{return Q$.accessSync($,Q$.constants.W_OK),!0}catch{return!1}}};function x1(){let $=t.dirname(v1(new URL("../package.json",import.meta.url)));try{return Q$.realpathSync($)}catch{return $}}function M4($=x1(),Z=P1){let K=null;return{info(){return K??=_1($,Z).catch(()=>G4),K}}}var b1="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",y1=21600000,m1=300000,g1=5000;function U6(){try{let $=N4.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 c1(){let $=await fetch(b1,{headers:{accept:"application/json"},signal:AbortSignal.timeout(g1)});if(!$.ok)return null;let Z=await $.json();return typeof Z.latest==="string"?Z.latest:null}function H4($){let Z=/^(\d+)\.(\d+)\.(\d+)/.exec($.trim());if(!Z)return null;return[Number(Z[1]),Number(Z[2]),Number(Z[3])]}function u1($,Z){if($===null||Z===null)return"unknown";let K=H4($),V=H4(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 C4($=c1,Z=U6(),K=M4()){let V=null,Q=null;function X(){if(V&&Date.now()<V.expiresAt)return Promise.resolve(V.value);if(Q)return Q;return Q=$().catch(()=>null).then((Y)=>{let W=Y===null?m1:y1;return V={value:Y,expiresAt:Date.now()+W},Q=null,Y}),Q}return{async state(){let[Y,W]=await Promise.all([X(),K.info()]);return{current:Z,latest:Y,status:u1(Z,Y),install:W}}}}import*as B4 from"node:os";function I4($,Z){$.get("/health",({res:K})=>{T(K,200,{ok:!0,ready:!0,home:B4.homedir(),symbols:{extensions:Z.symbols?.extensions??[]}})})}function A4($,Z){$.get("/version",async({res:K})=>{T(K,200,await Z.version.state())})}import*as i$ from"node:fs";import*as P from"node:path";function q($,Z){let K=$.getRepo(Z);if(!K)throw new N(404,`Unknown repo id: ${Z}`);return K}function u($,Z,K){if(typeof $!=="object"||$===null)throw new N(400,`Expected a JSON body with "${Z}"`);let V=$[Z];if(typeof V!=="string"||!K?.allowEmpty&&V.length===0)throw new N(400,`Missing "${Z}" (string) in body`);return V}function j$($,Z){let K=u($,Z);if(K.startsWith("-"))throw new N(400,`Invalid "${Z}" (must not start with "-"): ${K}`);return K}function T4($,Z){if(typeof $!=="object"||$===null)throw new N(400,`Expected a JSON body with "${Z}"`);let K=$[Z];if(!Array.isArray(K)||K.some((V)=>typeof V!=="string"))throw new N(400,`Missing "${Z}" (array of strings) in body`);return K}function D4($,Z){if(typeof $!=="object"||$===null)return;let K=$[Z];if(K===void 0)return;if(typeof K!=="string"||K.length===0)throw new N(400,`Invalid "${Z}" (expected a non-empty string)`);return K}function G6($,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 N(400,`Invalid "${Z}" (expected an integer >= ${K.min})`);return V}function q4($,Z){if(typeof $!=="object"||$===null)return!1;let K=$[Z];if(K===void 0)return!1;if(typeof K!=="boolean")throw new N(400,`Invalid "${Z}" (expected a boolean)`);return K}function X$($,Z,K){let V=$.get(Z);if(V===null)return K;if(V==="true")return!0;if(V==="false")return!1;throw new N(400,`Invalid "${Z}" (expected true or false): ${V}`)}function F4($,Z,K,V){let Q=$.get(Z);if(Q===null)return K;let X=Number(Q);if(!Number.isInteger(X)||X<1)throw new N(400,`Invalid "${Z}" (expected a positive integer): ${Q}`);if(V!==void 0&&X>V)throw new N(400,`Invalid "${Z}" (must be <= ${V}): ${Q}`);return X}async function e($){if(!$.state.status)await $.refresh();let Z=$.state.status;if(!Z)throw new N(500,"Repository status unavailable");return Z}function L4($,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 S$($,Z,K){let V=await e($),Q=L4(V,Z,K);if(!Q)await $.refresh(),V=await e($),Q=L4(V,Z,K);if(!Q)throw new N(404,`File not in status: ${Z}`);return Q}function O6($,Z){return $===Z||$.startsWith(Z+P.sep)}function M6($){return $.replace(/[. ]+$/,"").toLowerCase()===".git"}function O$($,Z){if(Z.length===0)throw new N(400,"Empty path");if(Z.includes("\x00"))throw new N(400,"Path contains a NUL byte");let K=P.resolve($),V=P.relative(K,P.resolve(K,Z));if(V==="")throw new N(400,`Path resolves to the repository root: ${Z}`);if(P.isAbsolute(V)||V===".."||V.startsWith(`..${P.sep}`))throw new N(400,`Path escapes repository root: ${Z}`);if(V.startsWith("-"))throw new N(400,`Path must not start with "-": ${Z}`);if(V.startsWith(":"))throw new N(400,`Path must not start with ":": ${Z}`);if(V.split(P.sep).some(M6))throw new N(400,`Path addresses the git directory: ${Z}`);return V}async function S4($){try{return await i$.promises.realpath($)}catch{return null}}var j6=new WeakMap;async function p1($){let Z=j6.get($);if(!Z)Z=(async()=>{let K=await F($.path).raw(["rev-parse","--absolute-git-dir"]);return await i$.promises.realpath(K.trim())})(),j6.set($,Z),Z.catch(()=>j6.delete($));try{return await Z}catch{throw new N(500,"Cannot resolve the git directory for this repository")}}async function G$($,Z){let K=await i$.promises.realpath(P.resolve($.path)),V=await S4(P.join($.path,Z));if(V===null)return;if(!O6(V,K))throw new N(400,`Path escapes repository root: ${Z}`);if(O6(V,await p1($)))throw new N(400,`Path addresses the git directory: ${Z}`)}async function R4($,Z){let K=await i$.promises.realpath(P.resolve($)),V=[];for(let Q of Z){let X=await S4(P.join($,Q.path));if(X===null||O6(X,K))V.push(Q)}return V}function H6($){return $?.code??null}function f1($){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test($)?409:500}async function $$($,Z,K){$.clearError(),await K();let V=$.state.error;if(V){T(Z,f1(V),{error:V});return}await $.refresh(),T(Z,200,{state:Z$($.state)})}function h1($){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 N(409,`A ${V.remoteState.operation??"remote"} operation is already in progress`);if(V.remoteState.inProgress)throw Q();let X=await K();if(X===null)throw Q();if(X.error){T(Z,h1(X.error),{error:X.error});return}let Y=$.manager.workingTree;await Y.refresh(),T(Z,200,{state:Z$(Y.state),result:X.lastResult})}function v4($,Z){let{registry:K}=Z;$.get("/repos",({res:V})=>{let Q=K.listRepos().map((X)=>({id:X.id,path:X.path,branch:X.manager.workingTree.state.status?.branch.current??null}));T(V,200,Q)}),$.post("/repos",async({body:V,res:Q})=>{let X=u(V,"path"),Y;try{Y=await AZ(K,X)}catch(W){throw new N(400,W instanceof Error?W.message:String(W))}T(Q,Y.created?201:200,{id:Y.handle.id,path:Y.handle.path})}),$.get("/repos/:id/worktrees",async({params:V,res:Q})=>{let X=q(K,V.id);T(Q,200,await l$(X.path))}),$.get("/worktrees",async({query:V,res:Q})=>{let X=V.get("path");if(!X)throw new N(400,'Missing "path" query parameter');T(Q,200,await l$(X))}),$.delete("/repos/:id",({params:V,res:Q})=>{q(K,V.id),K.closeRepo(V.id),T(Q,200,{})})}function w4($,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 k4($){return $.trim()}async function d1($){let Z=(V)=>V.filter((Q)=>Q.staged).length,K=Z((await e($)).files);if(K===0)await $.refresh(),K=Z((await e($)).files);return K}function E4($,Z){let{registry:K,sse:V}=Z;if($.get("/repos/:id/status",async({params:Q,res:X})=>{let Y=q(K,Q.id);await e(Y.manager.workingTree);let W=Z$(Y.manager.workingTree.state);W.operationInProgress=await i(Y.path),T(X,200,W)}),$.get("/repos/:id/diff",async({params:Q,query:X,res:Y})=>{let W=q(K,Q.id),J=X.get("path")??void 0,z=X$(X,"staged",!1),U;if(J){let G=(await e(W.manager.workingTree)).files.some((M)=>M.path===J&&M.status==="untracked");if(G&&z)throw new N(400,`staged=true is meaningless for untracked file: ${J} (untracked files have no staged diff)`);U=G?await OZ(W.path,J):await q$(W.path,J,z)}else U=await q$(W.path,void 0,z);W.manager.workingTree.stampDiff(U),T(Y,200,U)}),$.post("/repos/:id/stage",async({params:Q,body:X,res:Y})=>{let W=q(K,Q.id),J=u(X,"path"),z=W.manager.workingTree,U=await S$(z,J,!1);await $$(z,Y,()=>z.stage(U))}),$.post("/repos/:id/unstage",async({params:Q,body:X,res:Y})=>{let W=q(K,Q.id),J=u(X,"path"),z=W.manager.workingTree,U=await S$(z,J,!0);await $$(z,Y,()=>z.unstage(U))}),$.get("/repos/:id/events",({params:Q,req:X,res:Y})=>{let W=q(K,Q.id);V.subscribe(Q.id,W.manager,X,Y)}),Z.apiMode==="full")l1($,Z)}function l1($,Z){let{registry:K}=Z;$.post("/repos/:id/stage-all",async({params:V,res:Q})=>{let Y=q(K,V.id).manager.workingTree;await $$(Y,Q,()=>Y.stageAll())}),$.post("/repos/:id/unstage-all",async({params:V,res:Q})=>{let Y=q(K,V.id).manager.workingTree;await $$(Y,Q,()=>Y.unstageAll())}),$.post("/repos/:id/discard",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=u(Q,"path"),J=Y.manager.workingTree,z=await S$(J,W,!1);if(z.staged)throw new N(409,`Cannot discard a staged file: ${W} (unstage it first)`);await $$(J,X,()=>J.discard(z))}),$.post("/repos/:id/commit",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=u(Q,"message",{allowEmpty:!0}),J=q4(Q,"amend"),z=Y.manager.workingTree,U=await d1(z),j=w4(W,U,J);if(!j.valid)throw new N(400,j.error??"Invalid commit");await $$(z,X,()=>z.commit(k4(W),J))}),$.post("/repos/:id/stage-hunk",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=u(Q,"patch"),J=Y.manager.workingTree;await $$(J,X,()=>J.stageHunk(W))}),$.post("/repos/:id/unstage-hunk",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=u(Q,"patch"),J=Y.manager.workingTree;await $$(J,X,()=>J.unstageHunk(W))})}async function n1($){let Z=await lZ($);if(Z&&await V$($,Z))return Z;if(L$($)){let K=await d$($);if(K&&await V$($,K))return K}throw new N(422,"No usable base branch")}async function _4($,Z){let K=Z.get("base");if(K===null)return n1($);if(!await V$($,K))throw new N(400,`Unknown base ref: ${K}`);return K}function P4($,Z){let{registry:K}=Z;if($.get("/repos/:id/history",async({params:V,query:Q,res:X})=>{let Y=q(K,V.id),W=F4(Q,"count",100,5000);T(X,200,await G8(Y.path,W))}),$.get("/repos/:id/commits/:hash",async({params:V,res:Q})=>{let X=q(K,V.id),Y=V.hash;if(!/^[0-9a-f]{4,40}$/i.test(Y))throw new N(400,`Invalid commit hash: ${Y}`);let W=await M8(X.path,Y);if(W===null)throw new N(404,`Unknown commit: ${Y}`);T(Q,200,W)}),$.get("/repos/:id/commits/:hash/diff",async({params:V,res:Q})=>{let X=q(K,V.id),Y=V.hash;if(!/^[0-9a-f]{4,40}$/i.test(Y))throw new N(400,`Invalid commit hash: ${Y}`);if(!await V$(X.path,Y))throw new N(404,`Unknown commit: ${Y}`);T(Q,200,await k8(X.path,Y))}),$.get("/repos/:id/head-message",async({params:V,res:Q})=>{let X=q(K,V.id);T(Q,200,{message:await W8(X.path)})}),$.get("/repos/:id/branches",async({params:V,res:Q})=>{let X=q(K,V.id);T(Q,200,await UZ(X.path))}),$.get("/repos/:id/base-branches",async({params:V,res:Q})=>{let X=q(K,V.id);T(Q,200,await dZ(X.path))}),$.get("/repos/:id/compare/base",async({params:V,res:Q})=>{let X=q(K,V.id);T(Q,200,{base:await lZ(X.path)})}),Z.apiMode==="full")$.put("/repos/:id/compare/base",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=j$(Q,"branch");if(!await V$(Y.path,W))throw new N(400,`Not a valid base ref: ${W}`);S8(Y.path,W),T(X,200,{base:W})});$.get("/repos/:id/compare/count",async({params:V,query:Q,res:X})=>{let Y=q(K,V.id),W=await _4(Y.path,Q);try{T(X,200,{baseBranch:W,commits:await w8(Y.path,W)})}catch(J){if(J instanceof D$)throw new N(422,J.message);throw J}}),$.get("/repos/:id/compare",async({params:V,query:Q,res:X})=>{let Y=q(K,V.id),W=X$(Q,"uncommitted",!1),J=await _4(Y.path,Q),z;try{z=W?await E8(Y.path,J):await nZ(Y.path,J)}catch(U){if(U instanceof D$)throw new N(422,U.message);throw U}T(X,200,z)})}function o1($){let Z=$.get("since");if(Z===null)return 0;if(!/^\d+$/.test(Z))throw new N(400,`Invalid "since" (expected a non-negative integer): ${Z}`);return Number(Z)}function x4($,Z){let{registry:K}=Z;$.get("/repos/:id/journal",({params:V,query:Q,res:X})=>{let Y=q(K,V.id),W=o1(Q);T(X,200,k6(Y.manager.journal.journalStore,W))})}function b4($,Z){let{registry:K}=Z;$.post("/repos/:id/push",async({params:V,res:Q})=>{let X=q(K,V.id);await g(X,Q,()=>X.manager.remote.push())}),$.post("/repos/:id/fetch",async({params:V,res:Q})=>{let X=q(K,V.id);await g(X,Q,()=>X.manager.remote.fetchRemote())}),$.post("/repos/:id/pull",async({params:V,res:Q})=>{let X=q(K,V.id);await g(X,Q,()=>X.manager.remote.pullRebase())}),$.post("/repos/:id/stash",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=D4(Q,"message");await g(Y,X,()=>Y.manager.remote.stash(W))}),$.post("/repos/:id/stash-pop",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=G6(Q,"index",{min:0,fallback:0});await g(Y,X,()=>Y.manager.remote.stashPop(W))}),$.post("/repos/:id/switch-branch",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=j$(Q,"name");await g(Y,X,()=>Y.manager.remote.switchBranch(W))}),$.post("/repos/:id/create-branch",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=j$(Q,"name");await g(Y,X,()=>Y.manager.remote.createBranch(W))}),$.post("/repos/:id/soft-reset",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=G6(Q,"count",{min:1,fallback:1});if(!await V$(Y.path,`HEAD~${W}`))throw new N(400,`Cannot soft-reset ${W} commit(s): HEAD~${W} does not exist`);await g(Y,X,()=>Y.manager.remote.softReset(W))}),$.post("/repos/:id/cherry-pick",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=j$(Q,"hash");await g(Y,X,()=>Y.manager.remote.cherryPick(W))}),$.post("/repos/:id/revert",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=j$(Q,"hash");await g(Y,X,()=>Y.manager.remote.revertCommit(W))}),$.post("/repos/:id/abort",async({params:V,res:Q})=>{let X=q(K,V.id);if(!await i(X.path))throw new N(409,"No operation in progress to abort");await g(X,Q,()=>X.manager.remote.abortOperation())}),$.post("/repos/:id/rebase-continue",async({params:V,res:Q})=>{let X=q(K,V.id);if(await i(X.path)!=="rebase")throw new N(409,"No rebase in progress to continue");await g(X,Q,()=>X.manager.remote.rebaseContinue())})}import*as M$ from"node:fs";import*as s$ from"node:path";var w$=8388608;var y4=65536;function R$($){return Array.from($,(Z)=>Z.charCodeAt(0))}function v$($,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 TZ($,Z){return $[Z]*16777216+($[Z+1]<<16)+($[Z+2]<<8)+$[Z+3]}function N6($,Z){return($[Z]<<8)+$[Z+1]}function DZ($,Z){return $[Z]+($[Z+1]<<8)}function m4($,Z){return String.fromCharCode($[Z],$[Z+1],$[Z+2],$[Z+3])}function w($){return{ok:!1,refusal:$}}function k$($){return w($?"malformed":"header-not-found")}function C6($,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 a1=[137,80,78,71,13,10,26,10],i1=[255,216,255],s1=R$("GIF87a"),r1=R$("GIF89a"),a=R$("ftyp");function d($){return{offset:8,bytes:R$($)}}var t1=[{label:"webp",offset:0,bytes:R$("RIFF"),brand:d("WEBP")},{label:"avif",offset:4,bytes:a,brand:d("avif")},{label:"avis",offset:4,bytes:a,brand:d("avis")},{label:"heic",offset:4,bytes:a,brand:d("heic")},{label:"heix",offset:4,bytes:a,brand:d("heix")},{label:"heim",offset:4,bytes:a,brand:d("heim")},{label:"heis",offset:4,bytes:a,brand:d("heis")},{label:"hevc",offset:4,bytes:a,brand:d("hevc")},{label:"hevx",offset:4,bytes:a,brand:d("hevx")},{label:"mif1",offset:4,bytes:a,brand:d("mif1")},{label:"msf1",offset:4,bytes:a,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:R$("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 e1($){return t1.some((Z)=>v$($,Z.offset,Z.bytes)&&(Z.brand===void 0||v$($,Z.brand.offset,Z.brand.bytes)))}var $7={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},Z7=26;function K7($,Z,K){if($.length<Z7)return k$(K);if(TZ($,8)!==13)return w("malformed");if(m4($,12)!=="IHDR")return w("malformed");let V=TZ($,16),Q=TZ($,20),X=C6(V,Q);if(X)return w(X);let Y=$7[$[25]];if(!Y||!Y.includes($[24]))return w("malformed");let W=V7($,K);if(W)return W;return{ok:!0,info:{format:"png",mime:"image/png",width:V,height:Q,bytes:Z}}}function V7($,Z){let K=8;for(let V=0;V<256;V++){if(K+8>$.length)return k$(Z);let Q=TZ($,K),X=m4($,K+4);if(X==="IDAT")return null;if(X==="acTL")return w("animation");if(X==="iCCP"&&Q>65536)return w("malformed");let Y=K+12+Q;if(Y<=K||!Number.isSafeInteger(Y))return w("malformed");K=Y}return w("malformed")}var Q7=218,X7=226,Y7=new Set([219,238,192,193,194,196]);function W7($){return $>=224&&$<=239||Y7.has($)}function J7($){return $===1||$>=208&&$<=217}function z7($){return $>=192&&$<=207&&$!==196&&$!==200&&$!==204}var U7=new Set([192,193,194]);function j7($,Z,K){if($.length<4)return k$(K);if(!W7($[3]))return w("malformed");return M7($,Z,K)}function O7($,Z,K,V,Q){if(!U7.has(K))return w("malformed");if(Z+9>$.length)return k$(Q);let X=N6($,Z+5),Y=N6($,Z+7),W=C6(Y,X);if(W)return w(W);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:Y,height:X,bytes:V}}}function G7($,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(J7(K))return{kind:"skip",next:Z+2};if(K===Q7)return{kind:"malformed"};if(Z+4>$.length)return{kind:"ran-out"};let V=N6($,Z+2);if(V<2)return{kind:"malformed"};if(z7(K))return{kind:"sof",marker:K};return{kind:"segment",marker:K,length:V}}function M7($,Z,K){let V=2,Q=0;for(let X=0;X<1024;X++){let Y=G7($,V);if(Y.kind==="ran-out")return k$(K);if(Y.kind==="malformed")return w("malformed");if(Y.kind==="sof")return O7($,V,Y.marker,Z,K);if(Y.kind==="skip"){V=Y.next;continue}if(Y.marker===X7){if(Q+=Y.length-2,Q>65536)return w("malformed")}V+=2+Y.length}return w("malformed")}var H7=59,N7=44,C7=33;function g4($){return($&128)===0?0:3*(1<<($&7)+1)}function B7($,Z,K){if(Z>2097152)return w("too-large");if(!K)return w("header-not-found");if($.length<13)return k$(K);let V=DZ($,6),Q=DZ($,8),X=C6(V,Q);if(X)return w(X);let Y={pos:13+g4($[10]),left:8192,pixels:0,overBudget:!1},W=I7($,Y);if(W===null)return w("malformed");if(W<1)return w("malformed");if(W>256)return w("too-many-pixels");if(Y.overBudget)return w("too-many-pixels");if(W*V*Q>33554432)return w("too-many-pixels");let J={format:"gif",mime:"image/gif",width:V,height:Q,bytes:Z};if(W>1)J.frames=W;return{ok:!0,info:J}}function I7($,Z){let K=0;while(Z.left-- >0){if(Z.pos>=$.length)return null;let V=$[Z.pos];if(V===H7)return K;let Q=V===N7;if(!(Q?L7($,Z):A7($,Z,V)))return null;if(Q&&++K>256)return K;if(Z.overBudget)return K}return null}function A7($,Z,K){if(K!==C7)return!1;return Z.pos+=2,c4($,Z)}function L7($,Z){if(Z.pos+10>$.length)return!1;T7(Z,DZ($,Z.pos+5),DZ($,Z.pos+7));let K=$[Z.pos+9];return Z.pos+=10+g4(K)+1,c4($,Z)}function T7($,Z,K){let V=Z*K;if(Z>8192||K>8192||V>16777216){$.overBudget=!0;return}if($.pixels+=V,$.pixels>33554432)$.overBudget=!0}function c4($,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 u4($){return v$($,0,s1)||v$($,0,r1)}function E$($,Z,K){if(Z>8388608)return w("too-large");if(v$($,0,a1))return K7($,Z,K);if(v$($,0,i1))return j7($,Z,K);if(u4($))return B7($,Z,K);if(e1($))return w("unsupported-format");return w("not-an-image")}function qZ($,Z){return u4($)?Math.min(Z,2097152):65536}function B6($){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 X=0;X<V.length-1;X++)Q=Q?`${Q}/${V[X]}`:V[X],Z.directories.add(Q);Z.directories.add("")}return Z}var D7=1048576,p4=5000;class r$ extends Error{constructor($){super(`Not a regular file: ${$}`);this.name="NotRegularFileError"}}async function h4($,Z,K,V){let Q=K?.hideHidden??!0,X=K?.hideGitignored??!0,Y=s$.join($,Z),W=await M$.promises.readdir(Y,{withFileTypes:!0}),J=W.map((j)=>Z?s$.join(Z,j.name):j.name),z=X?await YZ($,J):new Set,U=[];for(let j of W){if(Q&&j.name.startsWith("."))continue;let G=Z?s$.join(Z,j.name):j.name;if(X&&z.has(G))continue;let M=j.isDirectory(),B={name:j.name,path:G,type:M?"dir":"file"};if(V)if(M){if(V.directories.has(G))B.hasChanges=!0}else{let I=V.files.get(G);if(I)B.gitStatus=I.status,B.staged=I.staged}U.push(B)}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 q7=16,F7=M$.constants.O_RDONLY|(M$.constants.O_NONBLOCK??0);async function I6($,Z,K){let V=Buffer.alloc(Z),Q=0;while(Q<Z){let{bytesRead:X}=await $.read(V,Q,Z-Q,K+Q);if(X===0)break;Q+=X}return Q===Z?V:V.subarray(0,Q)}async function S7($,Z){let K=await I6($,Math.min(q7,Z),0),V=E$(K,Z,K.length>=Z);if(!V.ok&&V.refusal==="too-large")return{head:K,result:V};let Q=Math.min(qZ(K,Z),Z),X=Q<=K.length?K.subarray(0,Q):Buffer.concat([K,await I6($,Q-K.length,K.length)]);return{head:X,result:E$(X,Z,X.length>=Z)}}function R7($,Z){return $.ok?{image:$.info,refusal:null,version:Z}:{image:null,refusal:$.refusal,version:Z}}function f4($,Z){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:$,totalLines:0,media:Z}}function A6($,Z){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:$,totalLines:0,media:Z}}function v7($,Z){let K=$.toString("utf-8"),V=K.split(`
|
|
51
|
+
`),Q=!1;if(V.length>p4)K=V.slice(0,p4).join(`
|
|
52
|
+
`),Q=!0;return{content:K,binary:!1,truncated:Q,tooLarge:!1,size:Z,totalLines:V.length}}async function w7($,Z){let K=await $.stat();if(!K.isFile())throw new r$(Z);let V=K.size;if(V>w$)return A6(V);let{head:Q,result:X}=await S7($,V),Y=R7(X,`${V}-${K.mtimeMs}`);if(X.ok)return f4(V,Y);if(V>D7)return A6(V,h$(Q)?Y:void 0);let W=Q.length>=V?Q:Buffer.concat([Q,await I6($,V-Q.length,Q.length)]);return h$(W)?f4(V,Y):v7(W,V)}async function d4($,Z){let K=s$.join($,Z),V=await M$.promises.stat(K);if(!V.isFile())throw new r$(Z);if(V.size>w$)return A6(V.size);let Q=await M$.promises.open(K,F7);try{return await w7(Q,Z)}finally{await Q.close()}}function l4($,Z){let{registry:K,symbols:V}=Z;async function Q(X,Y,W){if(!W)return X;if(X.binary||X.tooLarge)return X;if(V===null)return{...X,symbols:{status:"unavailable",reason:"error"}};if(!V.pool.supported(Y))return{...X,symbols:{status:"unsupported",reason:"language"}};let J=V.gate.acquire();if(J===null)throw new N(503,"Symbol extraction busy");try{return{...X,symbols:await V.pool.extract(Y,X.content)}}finally{(await J)()}}$.get("/repos/:id/tree",async({params:X,query:Y,res:W})=>{let J=q(K,X.id),z=Y.get("dir")??"",U=X$(Y,"hidden",!1),j=X$(Y,"ignored",!1),G=z===""?"":O$(J.path,z);await G$(J,G);let M=await e(J.manager.workingTree),B=B6(M.files),I;try{I=await h4(J.path,G,{hideHidden:!U,hideGitignored:!j},B)}catch(D){let S=H6(D);if(S==="ENOENT")throw new N(404,`No such directory: ${z||"/"}`);if(S==="ENOTDIR")throw new N(400,`Not a directory: ${z}`);throw D}let L=I.filter((D)=>!M6(D.name));T(W,200,await R4(J.path,L))}),$.get("/repos/:id/file",async({params:X,query:Y,res:W})=>{let J=q(K,X.id),z=Y.get("path");if(!z)throw new N(400,'Missing "path" query parameter');let U=O$(J.path,z);await G$(J,U);try{let j=await d4(J.path,U);T(W,200,await Q(j,U,X$(Y,"symbols",!1)))}catch(j){if(j instanceof r$)throw new N(400,j.message);let G=H6(j);if(G==="ENOENT"||G==="ENOTDIR")throw new N(404,`No such file: ${z}`);throw j}}),$.get("/repos/:id/files",async({params:X,res:Y})=>{let W=q(K,X.id);T(Y,200,await q8(W.path))})}import{execFile as k7}from"node:child_process";import{promisify as E7}from"node:util";var _7=E7(k7),FZ=3,P7=20,n4=500,x7=500,b7=4194304,y7=5000,o4=400,m7=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"];class SZ extends Error{constructor(){super(`Query must be at least ${FZ} characters`);this.name="GrepQueryTooShortError"}}class _$ extends Error{constructor($){super($);this.name="GrepQueryInvalidError"}}var a4={matches:[],capped:!1,incomplete:!1,binarySkipped:0};function g7($){return $===$.toLowerCase()}function L6($){return Buffer.from($).toString("utf8")}function c7($,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 i4($,Z=x7){let K=[],V=new Map,Q=0,X=!1,Y=0;while(Y<$.length){let W=c7($,Y);if(W===null)break;if(Y=W.next,W.contentBytes.includes(0)){Q+=1;continue}let J=Number.parseInt(L6(W.lineBytes),10);if(!Number.isSafeInteger(J)||J<1)continue;if(K.length>=Z){X=!0;break}let z=L6(W.pathBytes),U=V.get(z)??0;if(U>=P7){X=!0;continue}V.set(z,U+1);let j=L6(W.contentBytes),G=j.length>o4;K.push({path:z,line:J,text:G?j.slice(0,o4):j,truncated:G})}return{matches:K,capped:X,incomplete:!1,binarySkipped:Q}}function u7($){return[...m7,"grep","--no-textconv","--no-recurse-submodules","--full-name","--no-color","--no-column","-I","-n","-z","-F",...g7($)?["-i"]:[],"-e",$,"--untracked","--","."]}async function s4($,Z){if(Z.length<FZ)throw new SZ;if(Z.length>n4)throw new _$(`Query must be at most ${n4} characters`);if(Z.includes("\x00"))throw new _$("Query cannot contain a NUL byte");if(Z.includes(`
|
|
53
|
+
`))throw new _$("Query cannot span lines — this searches for literal text");try{let{stdout:K}=await _7("git",u7(Z),{cwd:$,env:f(),encoding:"buffer",maxBuffer:b7,timeout:y7,windowsHide:!0});return i4(K)}catch(K){let V=K;if(V.code===1)return a4;if(V.killed===!0||V.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...V.stdout?i4(V.stdout):a4,incomplete:!0};throw K}}function r4($,Z){let{registry:K}=Z;$.post("/repos/:id/search",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=u(Q,"query");try{let J=await s4(Y.path,W);T(X,200,J)}catch(J){if(J instanceof SZ)throw new N(400,`Query must be at least ${FZ} characters`);if(J instanceof _$)throw new N(400,J.message);throw J}})}import{Worker as p7}from"node:worker_threads";var f7=1000,h7=64,d7={status:"unavailable",reason:"deadline"},t$={status:"unavailable",reason:"error"};function l7(){let $=import.meta.url;return $.endsWith(".ts")?new URL("./symbolWorker.ts",$):new URL("./symbolWorker.js",$)}function t4($){let Z=$.timeoutMs??f7,K=new Set($.extensions),V=null,Q=0,X=Promise.resolve(),Y=!1,W=new Map;function J(G,M){W.delete(G),W.set(G,M);while(W.size>h7){let B=W.keys().next().value;if(B===void 0)break;W.delete(B)}}function z(){let G=V;if(V=null,G!==null)G.terminate()}function U(){let G=new p7(l7(),{workerData:{grammarDir:$.grammarDir,queryDir:$.queryDir}});return G.unref(),G}function j(G,M){return new Promise((B)=>{if(V===null)try{V=U()}catch{B(t$);return}let I=V,L=++Q,D=!1,S=(R,E)=>{if(D)return;if(D=!0,clearTimeout(C),I.off("message",v),I.off("error",O),I.off("exit",H),E)z();B(R)},v=(R)=>{if(R.seq!==L)return;S(R.outcome,!1)},O=()=>S(t$,!0),H=()=>S(t$,!0),C=setTimeout(()=>S(d7,!0),Z);C.unref?.(),I.on("message",v),I.on("error",O),I.on("exit",H);let A={seq:L,relPath:G,content:M};try{I.postMessage(A)}catch{S(t$,!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(Y)return t$;let B=`${G}\x00${M}`,I=W.get(B);if(I!==void 0)return J(B,I),I;let L=X.then(()=>j(G,M));X=L.catch(()=>{return});let D=await L;return J(B,D),D},async dispose(){Y=!0;let G=V;if(V=null,W.clear(),G!==null)await G.terminate()}}}import{execFile as n7,spawn as o7}from"node:child_process";import*as e$ from"node:fs";import*as $5 from"node:path";import{promisify as a7}from"node:util";var i7=a7(n7);class P$ extends Error{constructor($){super(`Not a regular blob: ${$}`);this.name="NotRegularBlobError"}}class x$ extends Error{size;constructor($,Z){super(`Blob too large: ${$} (${Z} bytes)`);this.name="BlobTooLargeError",this.size=Z}}class H$ 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"],K5=5000,RZ=65536,V5=/^[0-9a-f]{40}([0-9a-f]{24})?$/,s7=new Set(["100644","100755"]);function r7($){if($==="")throw new H$("empty");if($.includes("\x00"))throw new H$("contains NUL");if($.startsWith("-"))throw new H$('starts with "-"');if($.startsWith(":"))throw new H$('starts with ":"')}async function vZ($,Z,K){let{stdout:V}=await i7("git",[...Z5,...Z],{cwd:$,env:f(),encoding:"buffer",maxBuffer:K,timeout:K5,windowsHide:!0});return V}function Q5($){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 X5($,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 t7=1;async function e7($){let Z;try{Z=(await vZ($,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],RZ)).toString("utf8").trim()}catch(K){if(K?.code===t7)return null;throw K}return V5.test(Z)?Z:null}async function $9($,Z){let K=await e7($);if(K===null)return null;let V=await vZ($,["ls-tree","-z","--full-tree","-l",K,"--",Z],RZ),Q=X5(Q5(V),Z);if(Q===null||Q.length!==4)return null;return{mode:Q[0],oid:Q[2],sizeText:Q[3]}}async function Z9($,Z){let K=await vZ($,["ls-files","--stage","-z","--",Z],RZ),V=X5(Q5(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 Y5($,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 K9($,Z,K){let V=await vZ($,["cat-file","-s",Z],RZ);return Y5(V.toString("utf8").trim(),K)}var e4=Buffer.alloc(0);async function V9($,Z,K){let V=Buffer.alloc(K),Q=0;while(Q<K){let{bytesRead:X}=await $.read(V,Q,K-Q,Z+Q);if(X===0)break;Q+=X}return Q===K?V:V.subarray(0,Q)}function W5($,Z){let K=e4,V=!1;return{async read(Q){let X=Math.max(0,Math.min(Q,$));if(X>K.length&&!V){let Y=await Z(X,K);V=Y.length<X,K=Y}return K.subarray(0,Math.min(X,K.length))},release(){K=e4,V=!1}}}function Q9($,Z){let K=null,V=[],Q=0,X=!1,Y=null,W=null,J=!1,z=null,U=()=>X&&Y!==null,j=()=>{if(V.length!==1){let I=Buffer.concat(V,Q);V.length=0,V.push(I)}return V[0]};function G(){if(z===null)return;if(W===null&&U()&&Y?.signal===null&&Y.code!==0)W=Error(`git cat-file blob failed for ${Z} (exit ${Y.code??"null"})`);if(W===null&&Q<z.want&&!U())return;let I=z;if(z=null,clearTimeout(I.timer),K?.stdout?.pause(),W!==null)I.reject(W);else I.resolve(j().subarray(0,Math.min(I.want,Q)))}function M(I){W??=I,G()}function B(){let I=o7("git",[...Z5,"cat-file","blob",Z],{cwd:$,env:f(),stdio:["ignore","pipe","ignore"],windowsHide:!0});K=I,I.stdout?.on("data",(L)=>{if(J)return;V.push(L),Q+=L.length,G()}),I.stdout?.on("end",()=>{X=!0,G()}),I.stdout?.on("error",M),I.on("error",M),I.on("close",(L,D)=>{Y={code:L,signal:D},G()})}return{read(I){if(W!==null)return Promise.reject(W);if(J)return Promise.reject(Error(`read after close for ${Z}`));if(I<=Q||U())return Promise.resolve(j().subarray(0,Math.min(I,Q)));if(z!==null)return Promise.reject(Error(`concurrent read of ${Z}`));return new Promise((L,D)=>{let S=setTimeout(()=>{K?.kill("SIGKILL"),M(Error(`git cat-file blob timed out for ${Z}`))},K5);if(z={want:I,resolve:L,reject:D,timer:S},K===null)B();else K.stdout?.resume()})},release(){if(J=!0,z!==null)M(Error(`git cat-file blob closed while reading ${Z}`));V.length=0,Q=0,K?.kill("SIGKILL"),K=null}}}function X9($){let Z=$?.code;return Z==="ENOENT"||Z==="ENOTDIR"}async function Y9($,Z,K){let V=$5.join($,Z),Q;try{Q=await e$.promises.open(V,e$.constants.O_RDONLY|(e$.constants.O_NONBLOCK??0))}catch(X){if(X9(X))return null;throw X}try{let X=await Q.stat();if(!X.isFile())throw new P$(Z);if(X.size>K)throw new x$(Z,X.size);let Y=X.size,W=W5(Y,async(J,z)=>{let U=await V9(Q,z.length,J-z.length);return z.length===0?U:Buffer.concat([z,U])});return{oid:null,size:Y,version:`${Y}-${X.mtimeMs}`,read:(J)=>W.read(J),close:()=>{return W.release(),Q.close()}}}catch(X){try{await Q.close()}catch{}throw X}}async function W9($,Z,K,V){let Q=Z==="head"?await $9($,K):await Z9($,K);if(Q===null)return null;if(!s7.has(Q.mode))throw new P$(K);if(!V5.test(Q.oid))throw Error(`git reported a malformed object id for ${K}`);let X=Q.oid,Y=Q.sizeText===null?await K9($,X,K):Y5(Q.sizeText,K);if(Y>V)throw new x$(K,Y);let W=Q9($,X),J=W5(Y,(z)=>W.read(z));return{oid:X,size:Y,version:X,read:(z)=>J.read(z),close(){return J.release(),W.release(),Promise.resolve()}}}async function J5($,Z,K,V){if(r7(K),Z==="worktree")return Y9($,K,V);return W9($,Z,K,V)}var J9=["worktree","index","head"],z9=16,U9=y4,j9=w$,O9=["too-large","too-many-pixels"];function z5($){let Z=$.get("path");if(Z===null)throw new N(400,'Missing "path" query parameter');return Z}function G9($){let Z=$.get("side");if(Z===null||!J9.includes(Z))throw new N(400,'Invalid "side" (expected worktree, index or head)');return Z}function M9($){let Z=$.get("staged");if(Z==="1")return!0;if(Z==="0")return!1;throw new N(400,'Invalid "staged" (expected 0 or 1)')}function G5($){if($ instanceof P$)throw new N(400,$.message);if($ instanceof H$)throw new N(400,$.message);if($ instanceof x$)throw new N(413,$.message);throw $}async function U5($,Z){let K=await $.read(Z);return{bytes:K,sniff:E$(K,$.size,K.length>=$.size)}}async function H9($,Z){let{size:K}=$,V=await $.read(z9),Q=E$(V,K,V.length>=K);if(!Q.ok&&Q.refusal==="too-large")return{bytes:V,sniff:Q};let X=Math.min(qZ(V,K),K),Y=await U5($,Math.max(X,Math.min(Z,K)));if(Y.sniff.ok||Y.sniff.refusal!=="header-not-found")return Y;if(Y.bytes.length>=K)return Y;return U5($,K)}async function M5($,Z,K,V){let Q=await J5($,Z,K,w$);if(Q===null)return null;try{let{bytes:X,sniff:Y}=await H9(Q,V);return{bytes:X,size:Q.size,oid:Q.oid,version:Q.version,sniff:Y}}finally{await Q.close()}}function N9($,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=O9.includes($)?413:415;return new N(Z,`Image not served: ${$}`)}function B9($,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 I9($,Z,K){return{path:$.path,side:$.side,bytes:Z,oid:null,image:null,refusal:K,version:""}}async function j5($,Z){let K=O$($.path,Z.path);await G$($,K);let V;try{V=await M5($.path,Z.side,K,U9)}catch(Q){if(Q instanceof x$)return I9(Z,Q.size,"too-large");if(Q instanceof P$)return null;G5(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 A9($,Z){return Z.writableEnded||Z.destroyed===!0||$.destroyed===!0}async function O5($,Z,K){let V=$.acquire();if(V===null)throw new N(503,"Too many image requests in flight");let Q=await V;if(K.once("finish",Q),K.once("close",Q),Z.once("close",Q),A9(Z,K))return Q(),!1;return!0}function H5($,Z,K){let{registry:V}=Z;$.get("/repos/:id/media",async({params:Q,query:X,req:Y,res:W})=>{let J=q(V,Q.id),z=M9(X),U=O$(J.path,z5(X));if(await G$(J,U),!await O5(K,Y,W))return;let j=await S$(J.manager.workingTree,U,z),G=B9(j,z),M={old:G.old===null?null:await j5(J,G.old),new:G.new===null?null:await j5(J,G.new)};T(W,200,M)}),$.get("/repos/:id/blob",async({params:Q,query:X,req:Y,res:W})=>{let J=q(V,Q.id),z=c6(Y);if(z)throw new N(z.status,z.message);let U=G9(X),j=O$(J.path,z5(X));if(await G$(J,j),!await O5(K,Y,W))return;let G;try{G=await M5(J.path,U,j,j9)}catch(B){G5(B)}if(G===null)throw new N(404,`No such blob on side ${U}: ${j}`);if(!G.sniff.ok)throw C9(G.sniff.refusal);let M=N9(U,G.sniff.info.mime,G.oid);E6(W,200,G.bytes,M)})}function N5($,Z){let{registry:K,daemonEvents:V,follow:Q}=Z;$.get("/events",({req:X,res:Y})=>{let W=K.listRepos().map((J)=>({id:J.id,path:J.path}));V.subscribe(X,Y,W)}),$.get("/follow",({res:X})=>{T(X,200,Q?Q.state:Y4)})}import*as T6 from"node:os";import*as b$ from"node:path";function C5($,Z){let{settings:K,discovery:V,daemonEvents:Q}=Z;$.get("/settings",({res:X})=>{T(X,200,{...K.settings,persisted:K.persisted})}),$.put("/settings",async({body:X,res:Y})=>{let W=T4(X,"watchRoots"),J;try{J=J4(W)}catch(U){throw new N(400,U instanceof Error?U.message:String(U))}try{K.save({...K.settings,watchRoots:J})}catch(U){let j=U instanceof Error?U.message:String(U);throw new N(500,`Could not save settings: ${j}`)}await V.setRoots(J);let z={...K.settings,persisted:K.persisted};Q.broadcast("settings-change",z),T(Y,200,z)}),$.get("/discovered",({res:X})=>{T(X,200,V.state)}),$.get("/browse",async({query:X,res:Y})=>{let W=X.get("path"),J=W?l(W):T6.homedir();if(!b$.isAbsolute(J))throw new N(400,`Path must be absolute: ${W}`);let z=b$.resolve(J),U;try{U=await U4(z)}catch{throw new N(404,`Cannot read directory: ${z}`)}let j=b$.dirname(z);T(Y,200,{path:z,parent:j===z?null:j,home:T6.homedir(),entries:U})}),$.post("/discovered/rescan",async({res:X})=>{T(X,200,await V.rescan())})}function D6($=4,Z=64){let K=0,V=[];function Q(){let X=!1;return()=>{if(X)return;X=!0;let Y=V.shift();if(Y)Y(Q());else K--}}return{acquire(){if(K<$)return K++,Promise.resolve(Q());if(V.length>=Z)return null;return new Promise((X)=>{V.push(X)})},get active(){return K},get queued(){return V.length}}}function L9($){if(!N$.existsSync($))return Promise.resolve(!1);return new Promise((Z)=>{try{let K=I5.connect($);K.once("connect",()=>{K.destroy(),Z(!0)}),K.once("error",()=>{K.destroy(),Z(!1)})}catch{Z(!1)}})}function A5($={}){let Z=new K6,K=new V6,V=new Z6({onOpened:(O)=>K.broadcast("repo-opened",{id:O.id,path:O.path}),onClosed:(O)=>{Z.closeRepo(O),K.broadcast("repo-closed",{id:O})}}),Q=$.followFile?new X6(V,K,$.followFile):null,X=C4($.updateCheck===!1?()=>Promise.resolve(null):$.fetchLatestVersion),Y=new W6($.settingsFile??null),W=new z6(K),J=new Map,z=D6(),U=$.symbols??null,j=U===null?null:{pool:t4(U),gate:D6(1,4),extensions:U.extensions};function G(O){let H=J.get(O);if(H)return H;let C=new mZ,A={registry:V,sse:Z,daemonEvents:K,follow:Q,settings:Y,discovery:W,apiMode:O,version:X,symbols:j};if(I4(C,A),A4(C,A),v4(C,A),E4(C,A),P4(C,A),x4(C,A),O==="full")b4(C,A);return l4(C,A),r4(C,A),H5(C,A,z),N5(C,A),C5(C,A),J.set(O,C),C}let M=(O)=>$.apiMode??(O==="tcp"?"web":"full");Q?.start(),W.setRoots(Y.load().watchRoots);let B=$.webRoot?x6($.webRoot):void 0,I=new Set,L=[];function D(O){let H=G(O),C=B5.createServer((A,R)=>{for(let[E,$Z]of Object.entries(u6))R.setHeader(E,$Z);if(m6(C.address())){let E=g6(A);if(E){T(R,E.status,{error:E.message});return}}H.handle(A,R,B).catch(()=>R.end())});return C.on("connection",(A)=>{I.add(A),A.on("close",()=>I.delete(A))}),C}async function S(O,H){let C=O==="unix"?H.socketPath??null:null;if(C){if(await L9(C))throw Error(`diffstalkerd already running at ${C}`);N$.rmSync(C,{force:!0})}let A={server:D(M(O)),socketPath:C};L.push(A),await new Promise((R,E)=>{let $Z=(k5)=>E(k5);A.server.once("error",$Z);let kZ=()=>{if(A.server.removeListener("error",$Z),C)N$.chmodSync(C,384);R()};if(O==="fd")A.server.listen({fd:H.fd},kZ);else if(C)process.umask(63),A.server.listen(C,kZ);else A.server.listen(H.port,"127.0.0.1",kZ)})}function v(O){return new Promise((H,C)=>{O.server.close((A)=>{if(O.socketPath)N$.rmSync(O.socketPath,{force:!0});if(A&&A.code!=="ERR_SERVER_NOT_RUNNING")C(A);else H()})})}return{address(){return L[0]?.server.address()??null},addresses(){return L.map((O)=>O.server.address()).filter((O)=>O!==null)},getRepo(O){return V.getRepo(O)},async openRepo(O){let{handle:H}=await AZ(V,O);return{id:H.id,path:H.path}},async listen(O){let H=[];if(O.fd!==void 0)H.push("fd");if(O.socketPath)H.push("unix");if(O.port!==void 0)H.push("tcp");if(H.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let C of H)await S(C,O)},close(){Q?.dispose(),W.dispose(),Z.destroy(),K.destroy(),V.disposeAll();for(let H of I)H.destroy();let O=j?.pool.dispose()??Promise.resolve();return Promise.all([O,...L.splice(0).map(v)]).then(()=>{})}}}import*as q6 from"node:fs";import*as y$ from"node:path";import*as S5 from"node:crypto";import{createRequire as D9}from"node:module";var L5=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 T5(){return[...L5.keys()]}function T9($){let Z=$.slice($.lastIndexOf("/")+1),K=Z.lastIndexOf(".");if(K<=0)return"";return Z.slice(K).toLowerCase()}function D5($){return L5.get(T9($))??null}var q9="diffstalkerd-grammars";function F9($){return S5.createHash("sha256").update($).digest("hex")}function S9($){try{let Z=JSON.parse(q6.readFileSync(y$.join($,"checksums.json"),"utf8"));if(typeof Z.webTreeSitterVersion!=="string"||typeof Z.files!=="object")return null;return Z}catch{return null}}var q5="0.26.11";function R9($,Z,K){for(let[V,Q]of Object.entries(Z.files)){let X;try{X=q6.readFileSync(y$.join($,V))}catch{return K(`grammars: missing ${V}`),!1}if(F9(X)!==Q)return K(`grammars: checksum mismatch for ${V}`),!1}return!0}function v9($){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 F5($,Z=()=>{}){let K=S9($);if(K===null)return Z(`grammars: no readable checksums.json in ${$}`),null;if(K.webTreeSitterVersion!==q5)return Z(`grammars: built for web-tree-sitter ${K.webTreeSitterVersion}, this daemon bundles ${q5} — symbols disabled`),null;if(!R9($,K,Z))return null;let V=v9(K),Q=T5().filter((X)=>{let Y=D5(`x${X}`);return Y!==null&&V.has(Y.grammar)});if(Q.length===0)return Z("grammars: no usable grammar found"),null;return{grammarDir:$,queryDir:y$.join($,"queries"),extensions:Q}}function R5($,Z=()=>{}){if($!==null)return F5($,Z);try{let V=D9(import.meta.url).resolve(`${q9}/checksums.json`);return F5(y$.dirname(V),Z)}catch{return null}}var w5="diffstalkerd.sock";function k9($){return $===void 0?w5:`${$}.sock`}var E9=3,v5=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
|
|
53
54
|
|
|
54
55
|
Usage: diffstalkerd [options] [REPO_PATH...]
|
|
55
56
|
|
|
@@ -61,7 +62,7 @@ Arguments:
|
|
|
61
62
|
|
|
62
63
|
Options:
|
|
63
64
|
--socket PATH Bind a unix socket at PATH
|
|
64
|
-
(default: $XDG_RUNTIME_DIR/diffstalker/${
|
|
65
|
+
(default: $XDG_RUNTIME_DIR/diffstalker/${w5})
|
|
65
66
|
--instance NAME Bind <NAME>.sock in the runtime dir, so several
|
|
66
67
|
daemons can run side by side (default: the shared
|
|
67
68
|
socket every client looks for first)
|
|
@@ -79,6 +80,6 @@ Options:
|
|
|
79
80
|
then reports the running version only
|
|
80
81
|
--version, -v Print the running version and exit
|
|
81
82
|
--help, -h Show this help
|
|
82
|
-
`;function
|
|
83
|
+
`;function m$($,Z,K){let V=$[Z];if(V===void 0||V.startsWith("--"))throw Error(`${K} requires a value`);return V}function _9($,Z){if(Z.startsWith("-"))throw Error(`Unknown argument: ${Z}`);if(Z==="")throw Error("Empty repo path argument");$.repoPaths??=[],$.repoPaths.push(Z)}function P9($){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=m$($,++K,"--socket");break;case"--instance":Z.instance=m$($,++K,"--instance");break;case"--no-socket":Z.noSocket=!0;break;case"--port":if(Z.port=Number(m$($,++K,"--port")),!Number.isInteger(Z.port)||Z.port<0)throw Error("--port requires a non-negative integer");break;case"--follow-file":Z.followFile=m$($,++K,"--follow-file");break;case"--no-follow":Z.noFollow=!0;break;case"--web-root":Z.webRoot=m$($,++K,"--web-root");break;case"--grammars":Z.grammarsDir=m$($,++K,"--grammars");break;case"--no-update-check":Z.noUpdateCheck=!0;break;default:_9(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 x9(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function b9($){if($.noSocket||$.socketPath!==void 0)return;if(x9()){$.fd=E9;return}let Z=R6();if(!Z){if($.port!==void 0){console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set; binding the TCP port only.
|
|
83
84
|
Pass --socket PATH to also accept CLI connections.`);return}console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set and no --socket/--port given.
|
|
84
|
-
Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}
|
|
85
|
+
Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}wZ.mkdirSync(Z,{recursive:!0,mode:448}),$.socketPath=g$.join(Z,k9($.instance))}function y9($){let Z=$??w9(new URL("web/",import.meta.url));if(wZ.existsSync(Z))return Z;console.error(`diffstalkerd: web UI assets not found at ${Z}; serving API only`);return}function m9($){console.error(`diffstalkerd: web UI at http://diffstalker.localhost:${$}/`)}async function g9($,Z){for(let K of Z){let V=g$.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 c9(){process.title="diffstalkerd";let $;try{$=P9(process.argv.slice(2))}catch(U){console.error(U instanceof Error?U.message:String(U)),console.error(v5),process.exit(2)}if($==="help"){console.log(v5);return}if($==="version"){let U=U6();if(U===null)console.error("diffstalkerd: version unknown (package.json unreadable)"),process.exit(1);console.log(U);return}b9($);let Z=$.noFollow?void 0:$.followFile??g$.join(B$(),"target"),K=y9($.webRoot),V=R5($.grammarsDir??process.env.DIFFSTALKER_GRAMMARS_DIR??null,(U)=>console.error(`diffstalkerd: ${U}`)),Q=A5({followFile:Z,settingsFile:g$.join(S6(),"daemon.json"),webRoot:K,symbols:V,updateCheck:!$.noUpdateCheck});await g9(Q,$.repoPaths??[]),await Q.listen($);let Y=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(Y!==void 0)console.error(`diffstalkerd listening on 127.0.0.1:${Y}`);if(Z)console.error(`diffstalkerd following ${Z}`);if(K){if(console.error(`diffstalkerd serving web UI from ${K}`),Y!==void 0)m9(Y)}let W=!1,J=(U)=>{if(W)return;W=!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",()=>J("SIGINT")),process.on("SIGTERM",()=>J("SIGTERM")),process.on("SIGHUP",()=>J("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))}c9().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});export{P9 as parseArgs};
|