diffstalkerd 0.13.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,56 +1,56 @@
1
- var Bo=Object.create;var{getPrototypeOf:Ho,defineProperty:On,getOwnPropertyNames:Go}=Object;var Uo=Object.prototype.hasOwnProperty;function jo(t){return this[t]}var Wo,qo,Xo=(t,e,n)=>{var r=t!=null&&typeof t==="object";if(r){var s=e?Wo??=new WeakMap:qo??=new WeakMap,o=s.get(t);if(o)return o}n=t!=null?Bo(Ho(t)):{};let i=e||!t||!t.__esModule?On(n,"default",{value:t,enumerable:!0}):n;if(t&&typeof t==="object"||typeof t==="function"){for(let a of Go(t))if(!Uo.call(i,a))On(i,a,{get:jo.bind(t,a),enumerable:!0})}if(r)s.set(t,i);return i};var zo=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ss=zo(function(ju,rs){var L=-1,O=1,P=0;function Kt(t,e,n,r,s){if(t===e){if(t)return[[P,t]];return[]}if(n!=null){var o=Vi(t,e,n);if(o)return o}var i=nn(t,e),a=t.substring(0,i);t=t.substring(i),e=e.substring(i),i=ye(t,e);var c=t.substring(t.length-i);t=t.substring(0,t.length-i),e=e.substring(0,e.length-i);var l=ji(t,e);if(a)l.unshift([P,a]);if(c)l.push([P,c]);if(rn(l,s),r)Xi(l);return l}function ji(t,e){var n;if(!t)return[[O,e]];if(!e)return[[L,t]];var r=t.length>e.length?t:e,s=t.length>e.length?e:t,o=r.indexOf(s);if(o!==-1){if(n=[[O,r.substring(0,o)],[P,s],[O,r.substring(o+s.length)]],t.length>e.length)n[0][0]=n[2][0]=L;return n}if(s.length===1)return[[L,t],[O,e]];var i=qi(t,e);if(i){var a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],h=Kt(a,l),p=Kt(c,u);return h.concat([[P,f]],p)}return Wi(t,e)}function Wi(t,e){var n=t.length,r=e.length,s=Math.ceil((n+r)/2),o=s,i=2*s,a=Array(i),c=Array(i);for(var l=0;l<i;l++)a[l]=-1,c[l]=-1;a[o+1]=0,c[o+1]=0;var u=n-r,f=u%2!==0,h=0,p=0,g=0,w=0;for(var R=0;R<s;R++){for(var A=-R+h;A<=R-p;A+=2){var y=o+A,x;if(A===-R||A!==R&&a[y-1]<a[y+1])x=a[y+1];else x=a[y-1]+1;var S=x-A;while(x<n&&S<r&&t.charAt(x)===e.charAt(S))x++,S++;if(a[y]=x,x>n)p+=2;else if(S>r)h+=2;else if(f){var m=o+u-A;if(m>=0&&m<i&&c[m]!==-1){var b=n-c[m];if(x>=b)return Jr(t,e,x,S)}}}for(var E=-R+g;E<=R-w;E+=2){var m=o+E,b;if(E===-R||E!==R&&c[m-1]<c[m+1])b=c[m+1];else b=c[m-1]+1;var v=b-E;while(b<n&&v<r&&t.charAt(n-b-1)===e.charAt(r-v-1))b++,v++;if(c[m]=b,b>n)w+=2;else if(v>r)g+=2;else if(!f){var y=o+u-E;if(y>=0&&y<i&&a[y]!==-1){var x=a[y],S=o+x-y;if(b=n-b,x>=b)return Jr(t,e,x,S)}}}}return[[L,t],[O,e]]}function Jr(t,e,n,r){var s=t.substring(0,n),o=e.substring(0,r),i=t.substring(n),a=e.substring(r),c=Kt(s,o),l=Kt(i,a);return c.concat(l)}function nn(t,e){if(!t||!e||t.charAt(0)!==e.charAt(0))return 0;var n=0,r=Math.min(t.length,e.length),s=r,o=0;while(n<s){if(t.substring(o,s)==e.substring(o,s))n=s,o=n;else r=s;s=Math.floor((r-n)/2+n)}if(Zr(t.charCodeAt(s-1)))s--;return s}function Yr(t,e){var n=t.length,r=e.length;if(n==0||r==0)return 0;if(n>r)t=t.substring(n-r);else if(n<r)e=e.substring(0,n);var s=Math.min(n,r);if(t==e)return s;var o=0,i=1;while(!0){var a=t.substring(s-i),c=e.indexOf(a);if(c==-1)return o;if(i+=c,c==0||t.substring(s-i)==e.substring(0,i))o=i,i++}}function ye(t,e){if(!t||!e||t.slice(-1)!==e.slice(-1))return 0;var n=0,r=Math.min(t.length,e.length),s=r,o=0;while(n<s){if(t.substring(t.length-s,t.length-o)==e.substring(e.length-s,e.length-o))n=s,o=n;else r=s;s=Math.floor((r-n)/2+n)}if(ts(t.charCodeAt(t.length-s)))s--;return s}function qi(t,e){var n=t.length>e.length?t:e,r=t.length>e.length?e:t;if(n.length<4||r.length*2<n.length)return null;function s(p,g,w){var R=p.substring(w,w+Math.floor(p.length/4)),A=-1,y="",x,S,m,b;while((A=g.indexOf(R,A+1))!==-1){var E=nn(p.substring(w),g.substring(A)),v=ye(p.substring(0,w),g.substring(0,A));if(y.length<v+E)y=g.substring(A-v,A)+g.substring(A,A+E),x=p.substring(0,w-v),S=p.substring(w+E),m=g.substring(0,A-v),b=g.substring(A+E)}if(y.length*2>=p.length)return[x,S,m,b,y];else return null}var o=s(n,r,Math.ceil(n.length/4)),i=s(n,r,Math.ceil(n.length/2)),a;if(!o&&!i)return null;else if(!i)a=o;else if(!o)a=i;else a=o[4].length>i[4].length?o:i;var c,l,u,f;if(t.length>e.length)c=a[0],l=a[1],u=a[2],f=a[3];else u=a[0],f=a[1],c=a[2],l=a[3];var h=a[4];return[c,l,u,f,h]}function Xi(t){var e=!1,n=[],r=0,s=null,o=0,i=0,a=0,c=0,l=0;while(o<t.length){if(t[o][0]==P)n[r++]=o,i=c,a=l,c=0,l=0,s=t[o][1];else{if(t[o][0]==O)c+=t[o][1].length;else l+=t[o][1].length;if(s&&s.length<=Math.max(i,a)&&s.length<=Math.max(c,l))t.splice(n[r-1],0,[L,s]),t[n[r-1]+1][0]=O,r--,r--,o=r>0?n[r-1]:-1,i=0,a=0,c=0,l=0,s=null,e=!0}o++}if(e)rn(t);Yi(t),o=1;while(o<t.length){if(t[o-1][0]==L&&t[o][0]==O){var u=t[o-1][1],f=t[o][1],h=Yr(u,f),p=Yr(f,u);if(h>=p){if(h>=u.length/2||h>=f.length/2)t.splice(o,0,[P,f.substring(0,h)]),t[o-1][1]=u.substring(0,u.length-h),t[o+1][1]=f.substring(h),o++}else if(p>=u.length/2||p>=f.length/2)t.splice(o,0,[P,u.substring(0,p)]),t[o-1][0]=O,t[o-1][1]=f.substring(0,f.length-p),t[o+1][0]=L,t[o+1][1]=u.substring(p),o++;o++}o++}}var Kr=/[^a-zA-Z0-9]/,Vr=/\s/,Qr=/[\r\n]/,zi=/\n\r?\n$/,Ji=/^\r?\n\r?\n/;function Yi(t){function e(p,g){if(!p||!g)return 6;var w=p.charAt(p.length-1),R=g.charAt(0),A=w.match(Kr),y=R.match(Kr),x=A&&w.match(Vr),S=y&&R.match(Vr),m=x&&w.match(Qr),b=S&&R.match(Qr),E=m&&p.match(zi),v=b&&g.match(Ji);if(E||v)return 5;else if(m||b)return 4;else if(A&&!x&&S)return 3;else if(x||S)return 2;else if(A||y)return 1;return 0}var n=1;while(n<t.length-1){if(t[n-1][0]==P&&t[n+1][0]==P){var r=t[n-1][1],s=t[n][1],o=t[n+1][1],i=ye(r,s);if(i){var a=s.substring(s.length-i);r=r.substring(0,r.length-i),s=a+s.substring(0,s.length-i),o=a+o}var c=r,l=s,u=o,f=e(r,s)+e(s,o);while(s.charAt(0)===o.charAt(0)){r+=s.charAt(0),s=s.substring(1)+o.charAt(0),o=o.substring(1);var h=e(r,s)+e(s,o);if(h>=f)f=h,c=r,l=s,u=o}if(t[n-1][1]!=c){if(c)t[n-1][1]=c;else t.splice(n-1,1),n--;if(t[n][1]=l,u)t[n+1][1]=u;else t.splice(n+1,1),n--}}n++}}function rn(t,e){t.push([P,""]);var n=0,r=0,s=0,o="",i="",a;while(n<t.length){if(n<t.length-1&&!t[n][1]){t.splice(n,1);continue}switch(t[n][0]){case O:s++,i+=t[n][1],n++;break;case L:r++,o+=t[n][1],n++;break;case P:var c=n-s-r-1;if(e){if(c>=0&&ns(t[c][1])){var l=t[c][1].slice(-1);if(t[c][1]=t[c][1].slice(0,-1),o=l+o,i=l+i,!t[c][1]){t.splice(c,1),n--;var u=c-1;if(t[u]&&t[u][0]===O)s++,i=t[u][1]+i,u--;if(t[u]&&t[u][0]===L)r++,o=t[u][1]+o,u--;c=u}}if(es(t[n][1])){var l=t[n][1].charAt(0);t[n][1]=t[n][1].slice(1),o+=l,i+=l}}if(n<t.length-1&&!t[n][1]){t.splice(n,1);break}if(o.length>0||i.length>0){if(o.length>0&&i.length>0){if(a=nn(i,o),a!==0){if(c>=0)t[c][1]+=i.substring(0,a);else t.splice(0,0,[P,i.substring(0,a)]),n++;i=i.substring(a),o=o.substring(a)}if(a=ye(i,o),a!==0)t[n][1]=i.substring(i.length-a)+t[n][1],i=i.substring(0,i.length-a),o=o.substring(0,o.length-a)}var f=s+r;if(o.length===0&&i.length===0)t.splice(n-f,f),n=n-f;else if(o.length===0)t.splice(n-f,f,[O,i]),n=n-f+1;else if(i.length===0)t.splice(n-f,f,[L,o]),n=n-f+1;else t.splice(n-f,f,[L,o],[O,i]),n=n-f+2}if(n!==0&&t[n-1][0]===P)t[n-1][1]+=t[n][1],t.splice(n,1);else n++;s=0,r=0,o="",i="";break}}if(t[t.length-1][1]==="")t.pop();var h=!1;n=1;while(n<t.length-1){if(t[n-1][0]===P&&t[n+1][0]===P){if(t[n][1].substring(t[n][1].length-t[n-1][1].length)===t[n-1][1])t[n][1]=t[n-1][1]+t[n][1].substring(0,t[n][1].length-t[n-1][1].length),t[n+1][1]=t[n-1][1]+t[n+1][1],t.splice(n-1,1),h=!0;else if(t[n][1].substring(0,t[n+1][1].length)==t[n+1][1])t[n-1][1]+=t[n+1][1],t[n][1]=t[n][1].substring(t[n+1][1].length)+t[n+1][1],t.splice(n+1,1),h=!0}n++}if(h)rn(t,e)}function Zr(t){return t>=55296&&t<=56319}function ts(t){return t>=56320&&t<=57343}function es(t){return ts(t.charCodeAt(0))}function ns(t){return Zr(t.charCodeAt(t.length-1))}function Ki(t){var e=[];for(var n=0;n<t.length;n++)if(t[n][1].length>0)e.push(t[n]);return e}function en(t,e,n,r){if(ns(t)||es(r))return null;return Ki([[P,t],[L,e],[O,n],[P,r]])}function Vi(t,e,n){var r=typeof n==="number"?{index:n,length:0}:n.oldRange,s=typeof n==="number"?null:n.newRange,o=t.length,i=e.length;if(r.length===0&&(s===null||s.length===0)){var a=r.index,c=t.slice(0,a),l=t.slice(a),u=s?s.index:null;t:{var f=a+i-o;if(u!==null&&u!==f)break t;if(f<0||f>i)break t;var h=e.slice(0,f),p=e.slice(f);if(p!==l)break t;var g=Math.min(a,f),w=c.slice(0,g),R=h.slice(0,g);if(w!==R)break t;var A=c.slice(g),y=h.slice(g);return en(w,A,y,l)}t:{if(u!==null&&u!==a)break t;var x=a,h=e.slice(0,x),p=e.slice(x);if(h!==c)break t;var S=Math.min(o-x,i-x),m=l.slice(l.length-S),b=p.slice(p.length-S);if(m!==b)break t;var A=l.slice(0,l.length-S),y=p.slice(0,p.length-S);return en(c,A,y,m)}}if(r.length>0&&s&&s.length===0)t:{var w=t.slice(0,r.index),m=t.slice(r.index+r.length),g=w.length,S=m.length;if(i<g+S)break t;var R=e.slice(0,g),b=e.slice(i-S);if(w!==R||m!==b)break t;var A=t.slice(g,o-S),y=e.slice(g,i-S);return en(w,A,y,m)}return null}function be(t,e,n,r){return Kt(t,e,n,r,!0)}be.INSERT=O;be.DELETE=L;be.EQUAL=P;rs.exports=be});import*as Te from"node:fs";import*as Ut from"node:path";import{fileURLToPath as Gl}from"node:url";import*as $e from"node:os";import*as St from"node:path";var Le="diffstalker";function $n(){return St.join(process.env.XDG_CONFIG_HOME||St.join($e.homedir(),".config"),Le)}function vt(){return St.join(process.env.XDG_CACHE_HOME||St.join($e.homedir(),".cache"),Le)}function Ln(){return process.env.XDG_RUNTIME_DIR?St.join(process.env.XDG_RUNTIME_DIR,Le):null}import*as oe from"node:fs";import*as ie from"node:path";import*as Ne from"node:os";function z(t){if(t.startsWith("~/"))return ie.join(Ne.homedir(),t.slice(2));if(t==="~")return Ne.homedir();return t}function Nn(t){let e=ie.dirname(t);if(!oe.existsSync(e))oe.mkdirSync(e,{recursive:!0})}function Ce(t){let e=t.split(`
2
- `);for(let n=e.length-1;n>=0;n--){let r=e[n].trim();if(r)return r}return""}import*as _o from"node:http";import*as bt from"node:fs";import*as Ao from"node:net";function ae(t){process.stderr.write(`[diffstalker warn] ${t}
3
- `)}function Jo(t){if(t instanceof Error)return t.message;if(t)return String(t);return""}function ce(t,e){let n=e?`: ${Jo(e)}`:"";process.stderr.write(`[diffstalker error] ${t}${n}
4
- `)}function Be(t){let e={};for(let[n,r]of t)e[n]=r;return e}function Yo(t){if(!t)return null;return{staged:Be(t.staged),unstaged:Be(t.unstaged)}}function st(t){return{status:t.status,hunkCounts:Yo(t.hunkCounts),error:t.error,stashList:t.stashList,operationInProgress:t.operationInProgress,mtimes:t.mtimes?Be(t.mtimes):null}}function He(t){return t}function Ko(t){return t.entries.length>0?t.entries[0].seq-1:t.nextSeq-1}function Bn(t,e){let n=e>0?t.entries.filter((r)=>r.seq>e):t.entries;return{epoch:t.epoch,prunedBefore:Ko(t),entries:He(n)}}function jt(t){if(t instanceof Date)return t.toISOString();if(t instanceof Map){let e={};for(let[n,r]of t)e[String(n)]=jt(r);return e}if(Array.isArray(t))return t.map(jt);if(t!==null&&typeof t==="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=jt(r);return e}return t}var Vo=1048576;class d extends Error{status;constructor(t,e){super(e);this.status=t,this.name="HttpError"}}function k(t,e,n){let r=JSON.stringify(jt(n));t.writeHead(e,{"content-type":"application/json"}),t.end(r)}function Hn(t,e,n,r){t.writeHead(e,{...r,"content-length":String(n.byteLength)}),t.end(n)}function Qo(t,e){if(t.segments.length!==e.length)return null;let n={};for(let r=0;r<t.segments.length;r++){let s=t.segments[r];if(s.startsWith(":"))try{n[s.slice(1)]=decodeURIComponent(e[r])}catch{throw new d(400,`Malformed percent-encoding in path: ${e[r]}`)}else if(s!==e[r])return null}return n}async function Zo(t){if(t.method!=="POST"&&t.method!=="PUT"&&t.method!=="PATCH")return;let e=[],n=0;for await(let s of t){let o=s;if(n+=o.length,n>Vo)throw new d(413,"Request body too large");e.push(o)}let r=Buffer.concat(e).toString("utf-8");if(!r.trim())return;try{return JSON.parse(r)}catch{throw new d(400,"Invalid JSON body")}}class Ge{routes=[];get(t,e){this.add("GET",t,e)}post(t,e){this.add("POST",t,e)}put(t,e){this.add("PUT",t,e)}delete(t,e){this.add("DELETE",t,e)}add(t,e,n){this.routes.push({method:t,segments:e.split("/").filter(Boolean),handler:n})}match(t,e){for(let n of this.routes){if(n.method!==t)continue;let r=Qo(n,e);if(r)return{handler:n.handler,params:r}}return null}async handle(t,e,n){try{let r=new URL(t.url??"/","http://localhost"),s=r.pathname.split("/").filter(Boolean),o=t.method??"GET",i=this.match(o,s);if(!i){if(n&&o==="GET"){await n(t,e,r.pathname);return}throw new d(404,`Unknown route: ${o} ${r.pathname}`)}let a=await Zo(t);await i.handler({req:t,res:e,params:i.params,query:r.searchParams,body:a})}catch(r){if(e.headersSent){e.end();return}if(r instanceof d){k(e,r.status,{error:r.message});return}ce(`${t.method??"GET"} ${t.url??"/"}`,r),k(e,500,{error:"Internal server error"})}}}import*as Ue from"node:fs";import*as U from"node:path";var ti=new Set(["health","repos","events","follow"]),ei={".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"},Gn="no-cache",ni="public, max-age=31536000, immutable";async function Un(t,e,n){let r;try{r=await Ue.promises.readFile(e)}catch{throw new d(404,`Not found: ${U.basename(e)}`)}t.writeHead(200,{"content-type":ei[U.extname(e)]??"application/octet-stream","cache-control":n,"content-length":r.length}),t.end(r)}function jn(t){let e=U.resolve(t);return async(n,r,s)=>{let o;try{o=decodeURIComponent(s)}catch{throw new d(400,`Malformed percent-encoding in path: ${s}`)}if(o.includes("\x00"))throw new d(400,"Invalid path");let i=o.split("/").filter(Boolean);if(i.length>0&&ti.has(i[0]))throw new d(404,`Unknown route: GET ${s}`);let a=i.length>0?U.resolve(e,i.join("/")):e;if(a!==e&&!a.startsWith(e+U.sep))throw new d(403,"Forbidden");if((await Ue.promises.stat(a).catch(()=>null))?.isFile()){await Un(r,a,i[0]==="assets"?ni:Gn);return}await Un(r,U.join(e,"index.html"),Gn)}}function ri(t){try{let e=new URL(`http://${t}`).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function si(t){try{let e=new URL(t).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function qn(t){let e=t.split(".");if(e.length!==4)return!1;if(!e.every((n)=>/^\d{1,3}$/.test(n)&&Number(n)<=255))return!1;return e[0]==="127"}function oi(t){return t.length>10&&t.endsWith(".localhost")}function Wn(t){return t==="localhost"||t==="::1"||oi(t)||qn(t)}function ii(t){return t==="::1"||qn(t)}function Xn(t){if(t===null)return!1;if(typeof t==="string")return!0;return ii(t.address)}function zn(t){let e=t.headers.host;if(e!==void 0){let i=ri(e);if(i===null||!Wn(i))return{status:421,message:"Host not allowed (loopback only)"}}let n=t.method??"GET";if(!(n!=="GET"&&n!=="HEAD"&&n!=="OPTIONS"))return null;let s=t.headers["sec-fetch-site"];if(s&&s!=="same-origin"&&s!=="none")return{status:403,message:"Cross-site request blocked"};let o=t.headers.origin;if(o!==void 0&&o!==""){let i=si(o);if(i===null||!Wn(i))return{status:403,message:"Cross-origin request blocked"}}return null}function Jn(t){let e=t.headers["sec-fetch-site"];if(e&&e!=="same-origin"&&e!=="none")return{status:403,message:"Cross-site request blocked"};let n=t.headers["sec-fetch-dest"];if(n&&n!=="image")return{status:403,message:"Request destination must be an image"};return null}var Yn={"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 Sa}from"node:crypto";class Kn{queue=[];isProcessing=!1;pendingMutations=0;refreshScheduled=!1;enqueue(t){return new Promise((e,n)=>{this.queue.push({execute:t,resolve:e,reject:n}),this.processNext()})}enqueueMutation(t){return this.pendingMutations++,this.enqueue(t).finally(()=>{this.pendingMutations--})}hasPendingMutations(){return this.pendingMutations>0}scheduleRefresh(t){if(this.pendingMutations>0)return;if(this.refreshScheduled)return;this.refreshScheduled=!0,this.enqueue(async()=>{this.refreshScheduled=!1,await t()}).catch(()=>{this.refreshScheduled=!1})}isBusy(){return this.isProcessing||this.queue.length>0}async processNext(){if(this.isProcessing||this.queue.length===0)return;this.isProcessing=!0;let t=this.queue.shift();try{let e=await t.execute();t.resolve(e)}catch(e){t.reject(e instanceof Error?e:Error(String(e)))}finally{this.isProcessing=!1,this.processNext()}}}var je=new Map;function Vn(t){let e=je.get(t);if(!e)e=new Kn,je.set(t,e);return e}function Qn(t){je.delete(t)}import*as M from"node:path";import*as W from"node:fs";import{execFileSync as ta}from"node:child_process";import{watch as is}from"chokidar";import{EventEmitter as ea}from"node:events";import as from"ignore";import*as Zn from"node:fs";function le(t,e){let n=e;if(!n||n.isSymbolicLink())try{n=Zn.statSync(t)}catch{return!1}return!n.isFile()&&!n.isDirectory()}import{simpleGit as hi}from"simple-git";import*as J from"node:fs";import*as tr from"node:os";import*as Et from"node:path";import{execFileSync as ai}from"node:child_process";var ci=[["*.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 li(){return`# Generated by diffstalker: turns on git's built-in funcname drivers.
1
+ var Co=Object.create;var{getPrototypeOf:Bo,defineProperty:On,getOwnPropertyNames:Ho}=Object;var Uo=Object.prototype.hasOwnProperty;function Go(t){return this[t]}var jo,Wo,qo=(t,e,n)=>{var r=t!=null&&typeof t==="object";if(r){var s=e?jo??=new WeakMap:Wo??=new WeakMap,o=s.get(t);if(o)return o}n=t!=null?Co(Bo(t)):{};let i=e||!t||!t.__esModule?On(n,"default",{value:t,enumerable:!0}):n;if(t&&typeof t==="object"||typeof t==="function"){for(let a of Ho(t))if(!Uo.call(i,a))On(i,a,{get:Go.bind(t,a),enumerable:!0})}if(r)s.set(t,i);return i};var Xo=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var rs=Xo(function(Qu,ns){var N=-1,O=1,P=0;function Kt(t,e,n,r,s){if(t===e){if(t)return[[P,t]];return[]}if(n!=null){var o=sa(t,e,n);if(o)return o}var i=nn(t,e),a=t.substring(0,i);t=t.substring(i),e=e.substring(i),i=be(t,e);var c=t.substring(t.length-i);t=t.substring(0,t.length-i),e=e.substring(0,e.length-i);var l=Ki(t,e);if(a)l.unshift([P,a]);if(c)l.push([P,c]);if(rn(l,s),r)Zi(l);return l}function Ki(t,e){var n;if(!t)return[[O,e]];if(!e)return[[N,t]];var r=t.length>e.length?t:e,s=t.length>e.length?e:t,o=r.indexOf(s);if(o!==-1){if(n=[[O,r.substring(0,o)],[P,s],[O,r.substring(o+s.length)]],t.length>e.length)n[0][0]=n[2][0]=N;return n}if(s.length===1)return[[N,t],[O,e]];var i=Qi(t,e);if(i){var a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],h=Kt(a,l),p=Kt(c,u);return h.concat([[P,f]],p)}return Vi(t,e)}function Vi(t,e){var n=t.length,r=e.length,s=Math.ceil((n+r)/2),o=s,i=2*s,a=Array(i),c=Array(i);for(var l=0;l<i;l++)a[l]=-1,c[l]=-1;a[o+1]=0,c[o+1]=0;var u=n-r,f=u%2!==0,h=0,p=0,w=0,g=0;for(var R=0;R<s;R++){for(var _=-R+h;_<=R-p;_+=2){var I=o+_,A;if(_===-R||_!==R&&a[I-1]<a[I+1])A=a[I+1];else A=a[I-1]+1;var v=A-_;while(A<n&&v<r&&t.charAt(A)===e.charAt(v))A++,v++;if(a[I]=A,A>n)p+=2;else if(v>r)h+=2;else if(f){var m=o+u-_;if(m>=0&&m<i&&c[m]!==-1){var y=n-c[m];if(A>=y)return zr(t,e,A,v)}}}for(var S=-R+w;S<=R-g;S+=2){var m=o+S,y;if(S===-R||S!==R&&c[m-1]<c[m+1])y=c[m+1];else y=c[m-1]+1;var b=y-S;while(y<n&&b<r&&t.charAt(n-y-1)===e.charAt(r-b-1))y++,b++;if(c[m]=y,y>n)g+=2;else if(b>r)w+=2;else if(!f){var I=o+u-S;if(I>=0&&I<i&&a[I]!==-1){var A=a[I],v=o+A-I;if(y=n-y,A>=y)return zr(t,e,A,v)}}}}return[[N,t],[O,e]]}function zr(t,e,n,r){var s=t.substring(0,n),o=e.substring(0,r),i=t.substring(n),a=e.substring(r),c=Kt(s,o),l=Kt(i,a);return c.concat(l)}function nn(t,e){if(!t||!e||t.charAt(0)!==e.charAt(0))return 0;var n=0,r=Math.min(t.length,e.length),s=r,o=0;while(n<s){if(t.substring(o,s)==e.substring(o,s))n=s,o=n;else r=s;s=Math.floor((r-n)/2+n)}if(Qr(t.charCodeAt(s-1)))s--;return s}function Jr(t,e){var n=t.length,r=e.length;if(n==0||r==0)return 0;if(n>r)t=t.substring(n-r);else if(n<r)e=e.substring(0,n);var s=Math.min(n,r);if(t==e)return s;var o=0,i=1;while(!0){var a=t.substring(s-i),c=e.indexOf(a);if(c==-1)return o;if(i+=c,c==0||t.substring(s-i)==e.substring(0,i))o=i,i++}}function be(t,e){if(!t||!e||t.slice(-1)!==e.slice(-1))return 0;var n=0,r=Math.min(t.length,e.length),s=r,o=0;while(n<s){if(t.substring(t.length-s,t.length-o)==e.substring(e.length-s,e.length-o))n=s,o=n;else r=s;s=Math.floor((r-n)/2+n)}if(Zr(t.charCodeAt(t.length-s)))s--;return s}function Qi(t,e){var n=t.length>e.length?t:e,r=t.length>e.length?e:t;if(n.length<4||r.length*2<n.length)return null;function s(p,w,g){var R=p.substring(g,g+Math.floor(p.length/4)),_=-1,I="",A,v,m,y;while((_=w.indexOf(R,_+1))!==-1){var S=nn(p.substring(g),w.substring(_)),b=be(p.substring(0,g),w.substring(0,_));if(I.length<b+S)I=w.substring(_-b,_)+w.substring(_,_+S),A=p.substring(0,g-b),v=p.substring(g+S),m=w.substring(0,_-b),y=w.substring(_+S)}if(I.length*2>=p.length)return[A,v,m,y,I];else return null}var o=s(n,r,Math.ceil(n.length/4)),i=s(n,r,Math.ceil(n.length/2)),a;if(!o&&!i)return null;else if(!i)a=o;else if(!o)a=i;else a=o[4].length>i[4].length?o:i;var c,l,u,f;if(t.length>e.length)c=a[0],l=a[1],u=a[2],f=a[3];else u=a[0],f=a[1],c=a[2],l=a[3];var h=a[4];return[c,l,u,f,h]}function Zi(t){var e=!1,n=[],r=0,s=null,o=0,i=0,a=0,c=0,l=0;while(o<t.length){if(t[o][0]==P)n[r++]=o,i=c,a=l,c=0,l=0,s=t[o][1];else{if(t[o][0]==O)c+=t[o][1].length;else l+=t[o][1].length;if(s&&s.length<=Math.max(i,a)&&s.length<=Math.max(c,l))t.splice(n[r-1],0,[N,s]),t[n[r-1]+1][0]=O,r--,r--,o=r>0?n[r-1]:-1,i=0,a=0,c=0,l=0,s=null,e=!0}o++}if(e)rn(t);na(t),o=1;while(o<t.length){if(t[o-1][0]==N&&t[o][0]==O){var u=t[o-1][1],f=t[o][1],h=Jr(u,f),p=Jr(f,u);if(h>=p){if(h>=u.length/2||h>=f.length/2)t.splice(o,0,[P,f.substring(0,h)]),t[o-1][1]=u.substring(0,u.length-h),t[o+1][1]=f.substring(h),o++}else if(p>=u.length/2||p>=f.length/2)t.splice(o,0,[P,u.substring(0,p)]),t[o-1][0]=O,t[o-1][1]=f.substring(0,f.length-p),t[o+1][0]=N,t[o+1][1]=u.substring(p),o++;o++}o++}}var Yr=/[^a-zA-Z0-9]/,Kr=/\s/,Vr=/[\r\n]/,ta=/\n\r?\n$/,ea=/^\r?\n\r?\n/;function na(t){function e(p,w){if(!p||!w)return 6;var g=p.charAt(p.length-1),R=w.charAt(0),_=g.match(Yr),I=R.match(Yr),A=_&&g.match(Kr),v=I&&R.match(Kr),m=A&&g.match(Vr),y=v&&R.match(Vr),S=m&&p.match(ta),b=y&&w.match(ea);if(S||b)return 5;else if(m||y)return 4;else if(_&&!A&&v)return 3;else if(A||v)return 2;else if(_||I)return 1;return 0}var n=1;while(n<t.length-1){if(t[n-1][0]==P&&t[n+1][0]==P){var r=t[n-1][1],s=t[n][1],o=t[n+1][1],i=be(r,s);if(i){var a=s.substring(s.length-i);r=r.substring(0,r.length-i),s=a+s.substring(0,s.length-i),o=a+o}var c=r,l=s,u=o,f=e(r,s)+e(s,o);while(s.charAt(0)===o.charAt(0)){r+=s.charAt(0),s=s.substring(1)+o.charAt(0),o=o.substring(1);var h=e(r,s)+e(s,o);if(h>=f)f=h,c=r,l=s,u=o}if(t[n-1][1]!=c){if(c)t[n-1][1]=c;else t.splice(n-1,1),n--;if(t[n][1]=l,u)t[n+1][1]=u;else t.splice(n+1,1),n--}}n++}}function rn(t,e){t.push([P,""]);var n=0,r=0,s=0,o="",i="",a;while(n<t.length){if(n<t.length-1&&!t[n][1]){t.splice(n,1);continue}switch(t[n][0]){case O:s++,i+=t[n][1],n++;break;case N:r++,o+=t[n][1],n++;break;case P:var c=n-s-r-1;if(e){if(c>=0&&es(t[c][1])){var l=t[c][1].slice(-1);if(t[c][1]=t[c][1].slice(0,-1),o=l+o,i=l+i,!t[c][1]){t.splice(c,1),n--;var u=c-1;if(t[u]&&t[u][0]===O)s++,i=t[u][1]+i,u--;if(t[u]&&t[u][0]===N)r++,o=t[u][1]+o,u--;c=u}}if(ts(t[n][1])){var l=t[n][1].charAt(0);t[n][1]=t[n][1].slice(1),o+=l,i+=l}}if(n<t.length-1&&!t[n][1]){t.splice(n,1);break}if(o.length>0||i.length>0){if(o.length>0&&i.length>0){if(a=nn(i,o),a!==0){if(c>=0)t[c][1]+=i.substring(0,a);else t.splice(0,0,[P,i.substring(0,a)]),n++;i=i.substring(a),o=o.substring(a)}if(a=be(i,o),a!==0)t[n][1]=i.substring(i.length-a)+t[n][1],i=i.substring(0,i.length-a),o=o.substring(0,o.length-a)}var f=s+r;if(o.length===0&&i.length===0)t.splice(n-f,f),n=n-f;else if(o.length===0)t.splice(n-f,f,[O,i]),n=n-f+1;else if(i.length===0)t.splice(n-f,f,[N,o]),n=n-f+1;else t.splice(n-f,f,[N,o],[O,i]),n=n-f+2}if(n!==0&&t[n-1][0]===P)t[n-1][1]+=t[n][1],t.splice(n,1);else n++;s=0,r=0,o="",i="";break}}if(t[t.length-1][1]==="")t.pop();var h=!1;n=1;while(n<t.length-1){if(t[n-1][0]===P&&t[n+1][0]===P){if(t[n][1].substring(t[n][1].length-t[n-1][1].length)===t[n-1][1])t[n][1]=t[n-1][1]+t[n][1].substring(0,t[n][1].length-t[n-1][1].length),t[n+1][1]=t[n-1][1]+t[n+1][1],t.splice(n-1,1),h=!0;else if(t[n][1].substring(0,t[n+1][1].length)==t[n+1][1])t[n-1][1]+=t[n+1][1],t[n][1]=t[n][1].substring(t[n+1][1].length)+t[n+1][1],t.splice(n+1,1),h=!0}n++}if(h)rn(t,e)}function Qr(t){return t>=55296&&t<=56319}function Zr(t){return t>=56320&&t<=57343}function ts(t){return Zr(t.charCodeAt(0))}function es(t){return Qr(t.charCodeAt(t.length-1))}function ra(t){var e=[];for(var n=0;n<t.length;n++)if(t[n][1].length>0)e.push(t[n]);return e}function en(t,e,n,r){if(es(t)||ts(r))return null;return ra([[P,t],[N,e],[O,n],[P,r]])}function sa(t,e,n){var r=typeof n==="number"?{index:n,length:0}:n.oldRange,s=typeof n==="number"?null:n.newRange,o=t.length,i=e.length;if(r.length===0&&(s===null||s.length===0)){var a=r.index,c=t.slice(0,a),l=t.slice(a),u=s?s.index:null;t:{var f=a+i-o;if(u!==null&&u!==f)break t;if(f<0||f>i)break t;var h=e.slice(0,f),p=e.slice(f);if(p!==l)break t;var w=Math.min(a,f),g=c.slice(0,w),R=h.slice(0,w);if(g!==R)break t;var _=c.slice(w),I=h.slice(w);return en(g,_,I,l)}t:{if(u!==null&&u!==a)break t;var A=a,h=e.slice(0,A),p=e.slice(A);if(h!==c)break t;var v=Math.min(o-A,i-A),m=l.slice(l.length-v),y=p.slice(p.length-v);if(m!==y)break t;var _=l.slice(0,l.length-v),I=p.slice(0,p.length-v);return en(c,_,I,m)}}if(r.length>0&&s&&s.length===0)t:{var g=t.slice(0,r.index),m=t.slice(r.index+r.length),w=g.length,v=m.length;if(i<w+v)break t;var R=e.slice(0,w),y=e.slice(i-v);if(g!==R||m!==y)break t;var _=t.slice(w,o-v),I=e.slice(w,i-v);return en(g,_,I,m)}return null}function Se(t,e,n,r){return Kt(t,e,n,r,!0)}Se.INSERT=O;Se.DELETE=N;Se.EQUAL=P;ns.exports=Se});import*as Oe from"node:fs";import*as jt from"node:path";import{fileURLToPath as Kl}from"node:url";import*as Ne from"node:os";import*as vt from"node:path";var Le="diffstalker";function $n(){return vt.join(process.env.XDG_CONFIG_HOME||vt.join(Ne.homedir(),".config"),Le)}function Et(){return vt.join(process.env.XDG_CACHE_HOME||vt.join(Ne.homedir(),".cache"),Le)}function Nn(){return process.env.XDG_RUNTIME_DIR?vt.join(process.env.XDG_RUNTIME_DIR,Le):null}import*as oe from"node:fs";import*as ie from"node:path";import*as Ce from"node:os";function z(t){if(t.startsWith("~/"))return ie.join(Ce.homedir(),t.slice(2));if(t==="~")return Ce.homedir();return t}function Ln(t){let e=ie.dirname(t);if(!oe.existsSync(e))oe.mkdirSync(e,{recursive:!0})}function Be(t){let e=t.split(`
2
+ `);for(let n=e.length-1;n>=0;n--){let r=e[n].trim();if(r)return r}return""}import*as Ro from"node:http";import*as St from"node:fs";import*as _o from"node:net";function ae(t){process.stderr.write(`[diffstalker warn] ${t}
3
+ `)}function zo(t){if(t instanceof Error)return t.message;if(t)return String(t);return""}function ce(t,e){let n=e?`: ${zo(e)}`:"";process.stderr.write(`[diffstalker error] ${t}${n}
4
+ `)}function He(t){let e={};for(let[n,r]of t)e[n]=r;return e}function Jo(t){if(!t)return null;return{staged:He(t.staged),unstaged:He(t.unstaged)}}function st(t){return{status:t.status,hunkCounts:Jo(t.hunkCounts),error:t.error,stashList:t.stashList,operationInProgress:t.operationInProgress,mtimes:t.mtimes?He(t.mtimes):null}}function Ue(t){return t}function Yo(t){return t.entries.length>0?t.entries[0].seq-1:t.nextSeq-1}function Bn(t,e){let n=e>0?t.entries.filter((r)=>r.seq>e):t.entries;return{epoch:t.epoch,prunedBefore:Yo(t),entries:Ue(n)}}function Wt(t){if(t instanceof Date)return t.toISOString();if(t instanceof Map){let e={};for(let[n,r]of t)e[String(n)]=Wt(r);return e}if(Array.isArray(t))return t.map(Wt);if(t!==null&&typeof t==="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=Wt(r);return e}return t}var Ko=1048576;class d extends Error{status;constructor(t,e){super(e);this.status=t,this.name="HttpError"}}function E(t,e,n){let r=JSON.stringify(Wt(n));t.writeHead(e,{"content-type":"application/json"}),t.end(r)}function Hn(t,e,n,r){t.writeHead(e,{...r,"content-length":String(n.byteLength)}),t.end(n)}function Vo(t,e){if(t.segments.length!==e.length)return null;let n={};for(let r=0;r<t.segments.length;r++){let s=t.segments[r];if(s.startsWith(":"))try{n[s.slice(1)]=decodeURIComponent(e[r])}catch{throw new d(400,`Malformed percent-encoding in path: ${e[r]}`)}else if(s!==e[r])return null}return n}async function Qo(t){if(t.method!=="POST"&&t.method!=="PUT"&&t.method!=="PATCH")return;let e=[],n=0;for await(let s of t){let o=s;if(n+=o.length,n>Ko)throw new d(413,"Request body too large");e.push(o)}let r=Buffer.concat(e).toString("utf-8");if(!r.trim())return;try{return JSON.parse(r)}catch{throw new d(400,"Invalid JSON body")}}class Ge{routes=[];get(t,e){this.add("GET",t,e)}post(t,e){this.add("POST",t,e)}put(t,e){this.add("PUT",t,e)}delete(t,e){this.add("DELETE",t,e)}add(t,e,n){this.routes.push({method:t,segments:e.split("/").filter(Boolean),handler:n})}match(t,e){for(let n of this.routes){if(n.method!==t)continue;let r=Vo(n,e);if(r)return{handler:n.handler,params:r}}return null}async handle(t,e,n){try{let r=new URL(t.url??"/","http://localhost"),s=r.pathname.split("/").filter(Boolean),o=t.method??"GET",i=this.match(o,s);if(!i){if(n&&o==="GET"){await n(t,e,r.pathname);return}throw new d(404,`Unknown route: ${o} ${r.pathname}`)}let a=await Qo(t);await i.handler({req:t,res:e,params:i.params,query:r.searchParams,body:a})}catch(r){if(e.headersSent){e.end();return}if(r instanceof d){E(e,r.status,{error:r.message});return}ce(`${t.method??"GET"} ${t.url??"/"}`,r),E(e,500,{error:"Internal server error"})}}}import*as je from"node:fs";import*as G from"node:path";var Zo=new Set(["health","repos","events","follow"]),ti={".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"},Un="no-cache",ei="public, max-age=31536000, immutable";async function Gn(t,e,n){let r;try{r=await je.promises.readFile(e)}catch{throw new d(404,`Not found: ${G.basename(e)}`)}t.writeHead(200,{"content-type":ti[G.extname(e)]??"application/octet-stream","cache-control":n,"content-length":r.length}),t.end(r)}function jn(t){let e=G.resolve(t);return async(n,r,s)=>{let o;try{o=decodeURIComponent(s)}catch{throw new d(400,`Malformed percent-encoding in path: ${s}`)}if(o.includes("\x00"))throw new d(400,"Invalid path");let i=o.split("/").filter(Boolean);if(i.length>0&&Zo.has(i[0]))throw new d(404,`Unknown route: GET ${s}`);let a=i.length>0?G.resolve(e,i.join("/")):e;if(a!==e&&!a.startsWith(e+G.sep))throw new d(403,"Forbidden");if((await je.promises.stat(a).catch(()=>null))?.isFile()){await Gn(r,a,i[0]==="assets"?ei:Un);return}await Gn(r,G.join(e,"index.html"),Un)}}function ni(t){try{let e=new URL(`http://${t}`).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function ri(t){try{let e=new URL(t).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function qn(t){let e=t.split(".");if(e.length!==4)return!1;if(!e.every((n)=>/^\d{1,3}$/.test(n)&&Number(n)<=255))return!1;return e[0]==="127"}function si(t){return t.length>10&&t.endsWith(".localhost")}function Wn(t){return t==="localhost"||t==="::1"||si(t)||qn(t)}function oi(t){return t==="::1"||qn(t)}function Xn(t){if(t===null)return!1;if(typeof t==="string")return!0;return oi(t.address)}function zn(t){let e=t.headers.host;if(e!==void 0){let i=ni(e);if(i===null||!Wn(i))return{status:421,message:"Host not allowed (loopback only)"}}let n=t.method??"GET";if(!(n!=="GET"&&n!=="HEAD"&&n!=="OPTIONS"))return null;let s=t.headers["sec-fetch-site"];if(s&&s!=="same-origin"&&s!=="none")return{status:403,message:"Cross-site request blocked"};let o=t.headers.origin;if(o!==void 0&&o!==""){let i=ri(o);if(i===null||!Wn(i))return{status:403,message:"Cross-origin request blocked"}}return null}function Jn(t){let e=t.headers["sec-fetch-site"];if(e&&e!=="same-origin"&&e!=="none")return{status:403,message:"Cross-site request blocked"};let n=t.headers["sec-fetch-dest"];if(n&&n!=="image")return{status:403,message:"Request destination must be an image"};return null}var Yn={"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 Ia}from"node:crypto";class Kn{queue=[];isProcessing=!1;pendingMutations=0;refreshScheduled=!1;enqueue(t){return new Promise((e,n)=>{this.queue.push({execute:t,resolve:e,reject:n}),this.processNext()})}enqueueMutation(t){return this.pendingMutations++,this.enqueue(t).finally(()=>{this.pendingMutations--})}hasPendingMutations(){return this.pendingMutations>0}scheduleRefresh(t){if(this.pendingMutations>0)return;if(this.refreshScheduled)return;this.refreshScheduled=!0,this.enqueue(async()=>{this.refreshScheduled=!1,await t()}).catch(()=>{this.refreshScheduled=!1})}isBusy(){return this.isProcessing||this.queue.length>0}async processNext(){if(this.isProcessing||this.queue.length===0)return;this.isProcessing=!0;let t=this.queue.shift();try{let e=await t.execute();t.resolve(e)}catch(e){t.reject(e instanceof Error?e:Error(String(e)))}finally{this.isProcessing=!1,this.processNext()}}}var We=new Map;function Vn(t){let e=We.get(t);if(!e)e=new Kn,We.set(t,e);return e}function Qn(t){We.delete(t)}import*as M from"node:path";import*as W from"node:fs";import{execFileSync as aa}from"node:child_process";import{watch as os}from"chokidar";import{EventEmitter as ca}from"node:events";import is from"ignore";import*as Zn from"node:fs";function le(t,e){let n=e;if(!n||n.isSymbolicLink())try{n=Zn.statSync(t)}catch{return!1}return!n.isFile()&&!n.isDirectory()}import{simpleGit as fi}from"simple-git";import*as J from"node:fs";import*as tr from"node:os";import*as xt from"node:path";import{execFileSync as ii}from"node:child_process";var ai=[["*.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 ci(){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
- `+ci.map(([e,n])=>`${e} diff=${n}`).join(`
6
+ `+ai.map(([e,n])=>`${e} diff=${n}`).join(`
7
7
  `)+`
8
- `}var Wt=null,lt=null;function ui(){if(lt!==null)return lt;try{if(ai("git",["config","--get","core.attributesFile"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:process.env}).trim()!=="")return lt=!0,!0}catch(e){if(e.status!==1)return lt=!0,!0}let t=process.env.XDG_CONFIG_HOME||Et.join(tr.homedir(),".config");return lt=J.existsSync(Et.join(t,"git","attributes")),lt}function er(){if(Wt!==null)return Wt;if(ui())return null;let t=Et.join(vt(),"funcname.gitattributes"),e=li();try{let n=null;try{n=J.readFileSync(t,"utf8")}catch{n=null}if(n!==e)J.mkdirSync(Et.dirname(t),{recursive:!0}),fi(t,e);return Wt=t,Wt}catch{return Wt=null,lt=!0,null}}function fi(t,e){let n=`${t}.${process.pid}.tmp`;J.writeFileSync(n,e,"utf8"),J.renameSync(n,t)}function j(){return{...process.env,LC_ALL:"C",LANG:"C"}}var pi={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0},di=1e4,mi=600000;function I(t,e={}){let n=er(),r=n===null?[]:[`core.attributesFile=${n}`];return hi({baseDir:t,unsafe:pi,timeout:{block:e.longRunning===!0?mi:di},config:r}).env(j())}import{execFileSync as cr}from"node:child_process";import*as Xt from"node:fs";import*as qe from"node:path";async function xt(t,e){if(e.length===0)return new Set;let n=I(t),r=new Set,s=100;for(let o=0;o<e.length;o+=s){let i=e.slice(o,o+s);try{let c=(await n.raw(["check-ignore","--",...i])).trim().split(`
8
+ `}var qt=null,lt=null;function li(){if(lt!==null)return lt;try{if(ii("git",["config","--get","core.attributesFile"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:process.env}).trim()!=="")return lt=!0,!0}catch(e){if(e.status!==1)return lt=!0,!0}let t=process.env.XDG_CONFIG_HOME||xt.join(tr.homedir(),".config");return lt=J.existsSync(xt.join(t,"git","attributes")),lt}function er(){if(qt!==null)return qt;if(li())return null;let t=xt.join(Et(),"funcname.gitattributes"),e=ci();try{let n=null;try{n=J.readFileSync(t,"utf8")}catch{n=null}if(n!==e)J.mkdirSync(xt.dirname(t),{recursive:!0}),ui(t,e);return qt=t,qt}catch{return qt=null,lt=!0,null}}function ui(t,e){let n=`${t}.${process.pid}.tmp`;J.writeFileSync(n,e,"utf8"),J.renameSync(n,t)}function j(){return{...process.env,LC_ALL:"C",LANG:"C"}}var hi={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0},pi=1e4,di=600000;function k(t,e={}){let n=er(),r=n===null?[]:[`core.attributesFile=${n}`];return fi({baseDir:t,unsafe:hi,timeout:{block:e.longRunning===!0?di:pi},config:r}).env(j())}import{execFileSync as cr}from"node:child_process";import*as zt from"node:fs";import*as Xe from"node:path";async function kt(t,e){if(e.length===0)return new Set;let n=k(t),r=new Set,s=100;for(let o=0;o<e.length;o+=s){let i=e.slice(o,o+s);try{let c=(await n.raw(["check-ignore","--",...i])).trim().split(`
9
9
  `).filter((l)=>l.length>0);for(let l of c)r.add(l)}catch{}}return r}function ut(t){if(t.length===0)return"";return t.map((e)=>e.content).join(`
10
10
  `)+`
11
- `}function ue(t){let e=0;for(let n of t)e+=n.content.length+1;return e}var gi=5000,qt=262144,sr="Large file — diff not shown";function wi(t){return String(t).replace(/\B(?=(\d{3})+(?!\d))/g,",")}function yi(t){let e=t/1048576;if(e>=1)return`${e.toFixed(1)} MB`;return`${Math.round(t/1024)} KB`}function We(t,e){let n=yi(t),r=e===void 0?n:`${n}, ${wi(e)} lines`;return`${sr} (${r})`}function nr(t){if(t.length===0)return 0;let e=1,n=-1;while((n=t.indexOf(`
11
+ `}function ue(t){let e=0;for(let n of t)e+=n.content.length+1;return e}var mi=5000,Xt=262144,sr="Large file — diff not shown";function gi(t){return String(t).replace(/\B(?=(\d{3})+(?!\d))/g,",")}function wi(t){let e=t/1048576;if(e>=1)return`${e.toFixed(1)} MB`;return`${Math.round(t/1024)} KB`}function qe(t,e){let n=wi(t),r=e===void 0?n:`${n}, ${gi(e)} lines`;return`${sr} (${r})`}function nr(t){if(t.length===0)return 0;let e=1,n=-1;while((n=t.indexOf(`
12
12
  `,n+1))!==-1)e++;return e}function rr(t,e,n){let r=t.split(`
13
- `),s=r.findIndex((i)=>i.startsWith("@@"));return`${[...r.slice(0,s===-1?4:s),We(e,n)].join(`
13
+ `),s=r.findIndex((i)=>i.startsWith("@@"));return`${[...r.slice(0,s===-1?4:s),qe(e,n)].join(`
14
14
  `)}
15
- `}function ot(t){if(t.length===0)return t;let e=t.split(/(?=^diff --git )/m),n=!1,r=e.map((s)=>{let o=s.length;if(o<=qt){let i=nr(s);if(i<=gi)return s;return n=!0,rr(s,o,i)}return n=!0,rr(s,o,nr(s))});return n?r.join(""):t}function bi(t){return t.startsWith("diff --git")||t.startsWith("index ")||t.startsWith("---")||t.startsWith("+++")||t.startsWith("old mode")||t.startsWith("new mode")||t.startsWith("new file")||t.startsWith("deleted file")||t.startsWith("similarity index")||t.startsWith("dissimilarity index")||t.startsWith("rename from")||t.startsWith("rename to")||t.startsWith("copy from")||t.startsWith("copy to")||t.startsWith("Binary files")||t.startsWith(sr)}function Si(t){return t.startsWith("\\ ")}function or(t){let e=t.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(e)return{oldStart:parseInt(e[1],10),newStart:parseInt(e[2],10)};return null}function Q(t){if(t==="")return[];let e=t.split(`
16
- `);if(e.length>1&&e[e.length-1]==="")e.pop();let n=[],r=0,s=0;for(let o of e)if(bi(o))n.push({type:"header",content:o});else if(Si(o))n.push({type:"context",content:o});else if(o.startsWith("@@")){let i=or(o);if(i)r=i.oldStart,s=i.newStart;n.push({type:"hunk",content:o})}else if(o.startsWith("+"))n.push({type:"addition",content:o,newLineNum:s++});else if(o.startsWith("-"))n.push({type:"deletion",content:o,oldLineNum:r++});else n.push({type:"context",content:o,oldLineNum:r++,newLineNum:s++});return n}function fe(t){let e=new Map;if(!t)return e;let n=null;for(let r of t.split(`
15
+ `}function ot(t){if(t.length===0)return t;let e=t.split(/(?=^diff --git )/m),n=!1,r=e.map((s)=>{let o=s.length;if(o<=Xt){let i=nr(s);if(i<=mi)return s;return n=!0,rr(s,o,i)}return n=!0,rr(s,o,nr(s))});return n?r.join(""):t}function yi(t){return t.startsWith("diff --git")||t.startsWith("index ")||t.startsWith("---")||t.startsWith("+++")||t.startsWith("old mode")||t.startsWith("new mode")||t.startsWith("new file")||t.startsWith("deleted file")||t.startsWith("similarity index")||t.startsWith("dissimilarity index")||t.startsWith("rename from")||t.startsWith("rename to")||t.startsWith("copy from")||t.startsWith("copy to")||t.startsWith("Binary files")||t.startsWith(sr)}function bi(t){return t.startsWith("\\ ")}function or(t){let e=t.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(e)return{oldStart:parseInt(e[1],10),newStart:parseInt(e[2],10)};return null}function Q(t){if(t==="")return[];let e=t.split(`
16
+ `);if(e.length>1&&e[e.length-1]==="")e.pop();let n=[],r=0,s=0;for(let o of e)if(yi(o))n.push({type:"header",content:o});else if(bi(o))n.push({type:"context",content:o});else if(o.startsWith("@@")){let i=or(o);if(i)r=i.oldStart,s=i.newStart;n.push({type:"hunk",content:o})}else if(o.startsWith("+"))n.push({type:"addition",content:o,newLineNum:s++});else if(o.startsWith("-"))n.push({type:"deletion",content:o,oldLineNum:r++});else n.push({type:"context",content:o,oldLineNum:r++,newLineNum:s++});return n}function fe(t){let e=new Map;if(!t)return e;let n=null;for(let r of t.split(`
17
17
  `))if(r.startsWith("diff --git")){let s=r.match(/^diff --git a\/.+ b\/(.+)$/);if(s){if(n=s[1],!e.has(n))e.set(n,0)}}else if(r.startsWith("@@")&&n)e.set(n,(e.get(n)??0)+1);return e}function ir(t){let e=new Map;for(let n of t.trim().split(`
18
- `)){if(!n)continue;let r=n.split("\t");if(r.length>=3){let s=r[0]==="-"?0:parseInt(r[0],10),o=r[1]==="-"?0:parseInt(r[1],10),i=r.slice(2).join("\t");e.set(i,{insertions:s,deletions:o})}}return e}var vi=qt;async function Ei(t,e){try{let n=qe.join(t,e),r=await Xt.promises.stat(n);if(!r.isFile())return null;if(r.size>vi)return null;return(await Xt.promises.readFile(n,"utf-8")).split(`
19
- `).filter((o)=>o.length>0).length}catch{return null}}var xi=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function ki(t,e){return xi.has(`${t}${e}`)}function ar(t,e){return e?"conflicted":Ri(t)}function Ri(t){switch(t){case"M":return"modified";case"A":return"added";case"D":return"deleted";case"?":return"untracked";case"R":return"renamed";case"C":return"copied";case"U":return"conflicted";default:return"modified"}}async function Xe(t){let e=I(t);if(!await e.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let r=await e.status(),s=[],o=new Set,i=r.files.filter((p)=>p.working_dir==="?").map((p)=>p.path),a=await xt(t,i);for(let p of r.files){if(p.index==="!"||p.working_dir==="!"||a.has(p.path))continue;let g=`${p.path}-${p.index!==" "&&p.index!=="?"}`;if(o.has(g))continue;o.add(g);let w=ki(p.index,p.working_dir);if(p.index&&p.index!==" "&&p.index!=="?"){let R=ar(p.index,w);s.push({path:p.path,status:R,staged:!0,...p.from&&(R==="renamed"||R==="copied")?{originalPath:p.from}:{}})}if(p.working_dir&&p.working_dir!==" ")s.push({path:p.path,status:ar(p.working_dir,w),staged:!1})}let[c,l]=await Promise.all([e.diff(["--cached","--numstat"]).catch(()=>""),e.diff(["--numstat"]).catch(()=>"")]),u=ir(c),f=ir(l);for(let p of s){let g=p.staged?u.get(p.path):f.get(p.path);if(g)p.insertions=g.insertions,p.deletions=g.deletions}let h=s.filter((p)=>p.status==="untracked");if(h.length>0){let p=await Promise.all(h.map((g)=>Ei(t,g.path)));for(let g=0;g<h.length;g++){let w=p[g];if(w===null)continue;h[g].insertions=w,h[g].deletions=0}}return{files:s,branch:{current:r.current||"HEAD",tracking:r.tracking||void 0,ahead:r.ahead,behind:r.behind},isRepo:!0}}async function lr(t,e){await I(t).add(["--",e])}async function ur(t,e){await I(t).reset(["HEAD","--",e])}async function fr(t){await I(t).add("-A")}async function hr(t){await I(t).reset(["HEAD"])}async function pr(t,e){await I(t).checkout(["--",e])}async function dr(t,e){await I(t).clean("f",["--",e])}async function mr(t,e,n=!1){if(!(await I(t,{longRunning:!0}).commit(e,void 0,n?{"--amend":null}:void 0)).commit)throw Error("Nothing to commit: no staged changes")}async function gr(t){let e=I(t);try{return(await e.log({n:1})).latest?.message||""}catch{return""}}function wr(t,e){cr("git",["apply","--cached","--unidiff-zero"],{cwd:t,input:e,encoding:"utf-8",env:j()})}function yr(t,e){cr("git",["apply","--cached","--reverse","--unidiff-zero"],{cwd:t,input:e,encoding:"utf-8",env:j()})}async function br(t){let r=(await I(t,{longRunning:!0}).push()).pushed;if(r.length===0)return"Everything up-to-date";return r.map((s)=>`${s.local} → ${s.remote}`).join(", ")}async function Sr(t){return await I(t,{longRunning:!0}).fetch(),"Fetch complete"}async function vr(t){let n=await I(t,{longRunning:!0}).pull(["--rebase"]);if(n.summary.changes===0&&n.summary.insertions===0&&n.summary.deletions===0)return"Already up-to-date";return`${n.summary.changes} file(s) changed`}async function Er(t,e=50){let n=I(t);try{return(await n.log({n:e})).all.map((s)=>({hash:s.hash,shortHash:s.hash.slice(0,7),message:s.message.split(`
20
- `)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}))}catch{return[]}}async function xr(t,e){let n=I(t);try{let s=(await n.log(["--no-walk",e])).all[0];if(!s)return null;return{hash:s.hash,shortHash:s.hash.slice(0,7),message:s.message.split(`
21
- `)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}}catch{return null}}async function he(t){let e=I(t);try{return(await e.stashList()).all.map((r,s)=>({index:s,message:r.message}))}catch{return[]}}async function kr(t,e){let n=I(t),r=["push"];if(e)r.push("-m",e);return await n.stash(r),"Stashed"}async function Rr(t,e=0){let n=I(t);await n.stash(["pop",`stash@{${e}}`]);let r=(await n.raw(["diff","--name-only","--diff-filter=U"])).trim();if(r)throw Error(`Stash pop hit conflicts in: ${r.split(`
22
- `).join(", ")}`);return"Stash popped"}async function pe(t){let n=await I(t).branchLocal();return n.all.map((r)=>({name:r,current:r===n.current,tracking:n.branches[r]?.label||void 0}))}async function _r(t,e){return await I(t).raw(["switch","--",e]),`Switched to ${e}`}async function Ar(t,e){return await I(t).raw(["switch","-c",e]),`Created ${e}`}async function Ir(t,e=1){return await I(t).reset(["--soft",`HEAD~${e}`]),"Reset done"}async function Dr(t,e){return await I(t,{longRunning:!0}).raw(["cherry-pick","--end-of-options",e]),"Cherry-picked"}async function Pr(t,e){return await I(t,{longRunning:!0}).raw(["revert","--no-edit","--end-of-options",e]),"Reverted"}async function Z(t){let e=I(t),n;try{n=(await e.raw(["rev-parse","--absolute-git-dir"])).trim()}catch{return null}let r=(s)=>Xt.existsSync(qe.join(n,s));if(r("rebase-merge")||r("rebase-apply"))return"rebase";if(r("CHERRY_PICK_HEAD"))return"cherry-pick";if(r("REVERT_HEAD"))return"revert";if(r("MERGE_HEAD"))return"merge";return null}async function Mr(t){let e=await Z(t);if(!e)throw Error("No operation in progress to abort");return await I(t).raw([e,"--abort"]),`Aborted ${e}`}async function Fr(t){return await I(t,{longRunning:!0}).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function Tr(t){return(await I(t).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((r)=>r.length>0)}import*as ht from"node:fs";import*as Rt from"node:path";import*as tt from"node:fs";import*as ft from"node:path";function ze(){return ft.join(vt(),"base-branches.json")}function _i(){let t=ft.dirname(ze());if(!tt.existsSync(t))tt.mkdirSync(t,{recursive:!0})}function Or(){try{let t=ze();if(tt.existsSync(t))return JSON.parse(tt.readFileSync(t,"utf-8"))}catch{}return{}}function Ai(t){_i(),tt.writeFileSync(ze(),JSON.stringify(t,null,2)+`
23
- `)}function kt(t){let e=Or(),n=ft.resolve(t);return e[n]}function $r(t,e){let n=Or(),r=ft.resolve(t);n[r]=e,Ai(n)}function zt(t){let e=Math.min(t.length,8192);for(let n=0;n<e;n++)if(t[n]===0)return!0;return!1}class _t extends Error{constructor(t){super(`No common history with ${t}`);this.name="NoCommonHistoryError"}}var At=3,de=1e5;async function It(t,e,n=!1,r={}){let s=I(t);try{let o=[`-U${r.context??At}`];if(n)o.push("--cached");if(e)o.push("--",e);let i=ot(await s.diff(o));return{lines:Q(i)}}catch{return{lines:[]}}}var Ii="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Lr="(unborn)",Di=/unknown revision|ambiguous argument 'HEAD'|needed a single revision/i;async function me(t){let e=I(t);try{return(await e.raw(["rev-parse","HEAD"])).trim()}catch(n){let r=n instanceof Error?n.message:String(n);if(Di.test(r))return Lr;throw n}}async function Nr(t){let e=I(t),r=await me(t)===Lr?Ii:"HEAD",s=ot(await e.raw(["diff",`-U${At}`,r,"--"]));return{lines:Q(s)}}var Pi=qt;function Mi(t,e){return{lines:[{type:"header",content:`diff --git a/${t} b/${t}`},{type:"header",content:"new file mode 100644"},{type:"header",content:"--- /dev/null"},{type:"header",content:`+++ b/${t}`},{type:"header",content:We(e)}]}}function Fi(t){return{lines:[{type:"header",content:`diff --git a/${t} b/${t}`},{type:"header",content:"new file mode 100644"},{type:"header",content:`Binary files /dev/null and b/${t} differ`}]}}function Ti(t,e){let n=Rt.resolve(t),r=Rt.resolve(n,e);if(r!==n&&!r.startsWith(n+Rt.sep))return null;let s,o;try{s=ht.realpathSync(r),o=ht.realpathSync(n)}catch{return null}if(s!==o&&!s.startsWith(o+Rt.sep))return null;let i=ht.statSync(s);if(!i.isFile())return null;return{path:r,size:i.size}}async function Jt(t,e){try{let n=Ti(t,e);if(n===null)return{lines:[]};if(n.size>Pi)return Mi(e,n.size);let r=ht.readFileSync(n.path);if(zt(r))return Fi(e);let s=r.toString("utf-8"),o=[{type:"header",content:`diff --git a/${e} b/${e}`},{type:"header",content:"new file mode 100644"},{type:"header",content:"--- /dev/null"},{type:"header",content:`+++ b/${e}`}],i=s.endsWith(`
18
+ `)){if(!n)continue;let r=n.split("\t");if(r.length>=3){let s=r[0]==="-"?0:parseInt(r[0],10),o=r[1]==="-"?0:parseInt(r[1],10),i=r.slice(2).join("\t");e.set(i,{insertions:s,deletions:o})}}return e}var Si=Xt;async function vi(t,e){try{let n=Xe.join(t,e),r=await zt.promises.stat(n);if(!r.isFile())return null;if(r.size>Si)return null;return(await zt.promises.readFile(n,"utf-8")).split(`
19
+ `).filter((o)=>o.length>0).length}catch{return null}}var Ei=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function xi(t,e){return Ei.has(`${t}${e}`)}function ar(t,e){return e?"conflicted":ki(t)}function ki(t){switch(t){case"M":return"modified";case"A":return"added";case"D":return"deleted";case"?":return"untracked";case"R":return"renamed";case"C":return"copied";case"U":return"conflicted";default:return"modified"}}async function ze(t){let e=k(t);if(!await e.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let r=await e.status(),s=[],o=new Set,i=r.files.filter((p)=>p.working_dir==="?").map((p)=>p.path),a=await kt(t,i);for(let p of r.files){if(p.index==="!"||p.working_dir==="!"||a.has(p.path))continue;let w=`${p.path}-${p.index!==" "&&p.index!=="?"}`;if(o.has(w))continue;o.add(w);let g=xi(p.index,p.working_dir);if(p.index&&p.index!==" "&&p.index!=="?"){let R=ar(p.index,g);s.push({path:p.path,status:R,staged:!0,...p.from&&(R==="renamed"||R==="copied")?{originalPath:p.from}:{}})}if(p.working_dir&&p.working_dir!==" ")s.push({path:p.path,status:ar(p.working_dir,g),staged:!1})}let[c,l]=await Promise.all([e.diff(["--cached","--numstat"]).catch(()=>""),e.diff(["--numstat"]).catch(()=>"")]),u=ir(c),f=ir(l);for(let p of s){let w=p.staged?u.get(p.path):f.get(p.path);if(w)p.insertions=w.insertions,p.deletions=w.deletions}let h=s.filter((p)=>p.status==="untracked");if(h.length>0){let p=await Promise.all(h.map((w)=>vi(t,w.path)));for(let w=0;w<h.length;w++){let g=p[w];if(g===null)continue;h[w].insertions=g,h[w].deletions=0}}return{files:s,branch:{current:r.current||"HEAD",tracking:r.tracking||void 0,ahead:r.ahead,behind:r.behind},isRepo:!0}}async function lr(t,e){await k(t).add(["--",e])}async function ur(t,e){await k(t).reset(["HEAD","--",e])}async function fr(t){await k(t).add("-A")}async function hr(t){await k(t).reset(["HEAD"])}async function pr(t,e){await k(t).checkout(["--",e])}async function dr(t,e){await k(t).clean("f",["--",e])}async function mr(t,e,n=!1){if(!(await k(t,{longRunning:!0}).commit(e,void 0,n?{"--amend":null}:void 0)).commit)throw Error("Nothing to commit: no staged changes")}async function gr(t){let e=k(t);try{return(await e.log({n:1})).latest?.message||""}catch{return""}}function wr(t,e){cr("git",["apply","--cached","--unidiff-zero"],{cwd:t,input:e,encoding:"utf-8",env:j()})}function yr(t,e){cr("git",["apply","--cached","--reverse","--unidiff-zero"],{cwd:t,input:e,encoding:"utf-8",env:j()})}async function br(t){let r=(await k(t,{longRunning:!0}).push()).pushed;if(r.length===0)return"Everything up-to-date";return r.map((s)=>`${s.local} → ${s.remote}`).join(", ")}async function Sr(t){return await k(t,{longRunning:!0}).fetch(),"Fetch complete"}async function vr(t){let n=await k(t,{longRunning:!0}).pull(["--rebase"]);if(n.summary.changes===0&&n.summary.insertions===0&&n.summary.deletions===0)return"Already up-to-date";return`${n.summary.changes} file(s) changed`}async function Er(t,e=50){let n=k(t);try{return(await n.log({n:e})).all.map((s)=>({hash:s.hash,shortHash:s.hash.slice(0,7),message:s.message.split(`
20
+ `)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}))}catch{return[]}}async function xr(t,e){let n=k(t);try{let s=(await n.log(["--no-walk",e])).all[0];if(!s)return null;return{hash:s.hash,shortHash:s.hash.slice(0,7),message:s.message.split(`
21
+ `)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}}catch{return null}}async function he(t){let e=k(t);try{return(await e.stashList()).all.map((r,s)=>({index:s,message:r.message}))}catch{return[]}}async function kr(t,e){let n=k(t),r=["push"];if(e)r.push("-m",e);return await n.stash(r),"Stashed"}async function Rr(t,e=0){let n=k(t);await n.stash(["pop",`stash@{${e}}`]);let r=(await n.raw(["diff","--name-only","--diff-filter=U"])).trim();if(r)throw Error(`Stash pop hit conflicts in: ${r.split(`
22
+ `).join(", ")}`);return"Stash popped"}async function pe(t){let n=await k(t).branchLocal();return n.all.map((r)=>({name:r,current:r===n.current,tracking:n.branches[r]?.label||void 0}))}async function _r(t,e){return await k(t).raw(["switch","--",e]),`Switched to ${e}`}async function Ir(t,e){return await k(t).raw(["switch","-c",e]),`Created ${e}`}async function Ar(t,e=1){return await k(t).reset(["--soft",`HEAD~${e}`]),"Reset done"}async function Dr(t,e){return await k(t,{longRunning:!0}).raw(["cherry-pick","--end-of-options",e]),"Cherry-picked"}async function Pr(t,e){return await k(t,{longRunning:!0}).raw(["revert","--no-edit","--end-of-options",e]),"Reverted"}async function Z(t){let e=k(t),n;try{n=(await e.raw(["rev-parse","--absolute-git-dir"])).trim()}catch{return null}let r=(s)=>zt.existsSync(Xe.join(n,s));if(r("rebase-merge")||r("rebase-apply"))return"rebase";if(r("CHERRY_PICK_HEAD"))return"cherry-pick";if(r("REVERT_HEAD"))return"revert";if(r("MERGE_HEAD"))return"merge";return null}async function Mr(t){let e=await Z(t);if(!e)throw Error("No operation in progress to abort");return await k(t).raw([e,"--abort"]),`Aborted ${e}`}async function Fr(t){return await k(t,{longRunning:!0}).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function Tr(t){return(await k(t).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((r)=>r.length>0)}import*as ht from"node:fs";import*as _t from"node:path";import*as tt from"node:fs";import*as ft from"node:path";function Je(){return ft.join(Et(),"base-branches.json")}function Ri(){let t=ft.dirname(Je());if(!tt.existsSync(t))tt.mkdirSync(t,{recursive:!0})}function Or(){try{let t=Je();if(tt.existsSync(t))return JSON.parse(tt.readFileSync(t,"utf-8"))}catch{}return{}}function _i(t){Ri(),tt.writeFileSync(Je(),JSON.stringify(t,null,2)+`
23
+ `)}function Rt(t){let e=Or(),n=ft.resolve(t);return e[n]}function $r(t,e){let n=Or(),r=ft.resolve(t);n[r]=e,_i(n)}function Jt(t){let e=Math.min(t.length,8192);for(let n=0;n<e;n++)if(t[n]===0)return!0;return!1}class It extends Error{constructor(t){super(`No common history with ${t}`);this.name="NoCommonHistoryError"}}var Ii={staged:!1,unstaged:!1,untracked:!1};var At=3,me=1e5;async function Dt(t,e,n=!1,r={}){let s=k(t);try{let o=[`-U${r.context??At}`];if(n)o.push("--cached");if(e)o.push("--",e);let i=ot(await s.diff(o));return{lines:Q(i)}}catch{return{lines:[]}}}var Ai="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Nr="(unborn)",Di=/unknown revision|ambiguous argument 'HEAD'|needed a single revision/i;async function ge(t){let e=k(t);try{return(await e.raw(["rev-parse","HEAD"])).trim()}catch(n){let r=n instanceof Error?n.message:String(n);if(Di.test(r))return Nr;throw n}}async function Lr(t){let e=k(t),r=await ge(t)===Nr?Ai:"HEAD",s=ot(await e.raw(["diff",`-U${At}`,r,"--"]));return{lines:Q(s)}}var Pi=Xt;function Mi(t,e){return{lines:[{type:"header",content:`diff --git a/${t} b/${t}`},{type:"header",content:"new file mode 100644"},{type:"header",content:"--- /dev/null"},{type:"header",content:`+++ b/${t}`},{type:"header",content:qe(e)}]}}function Fi(t){return{lines:[{type:"header",content:`diff --git a/${t} b/${t}`},{type:"header",content:"new file mode 100644"},{type:"header",content:`Binary files /dev/null and b/${t} differ`}]}}function Ti(t,e){let n=_t.resolve(t),r=_t.resolve(n,e);if(r!==n&&!r.startsWith(n+_t.sep))return null;let s,o;try{s=ht.realpathSync(r),o=ht.realpathSync(n)}catch{return null}if(s!==o&&!s.startsWith(o+_t.sep))return null;let i=ht.statSync(s);if(!i.isFile())return null;return{path:r,size:i.size}}async function pt(t,e){try{let n=Ti(t,e);if(n===null)return{lines:[]};if(n.size>Pi)return Mi(e,n.size);let r=ht.readFileSync(n.path);if(Jt(r))return Fi(e);let s=r.toString("utf-8"),o=[{type:"header",content:`diff --git a/${e} b/${e}`},{type:"header",content:"new file mode 100644"},{type:"header",content:"--- /dev/null"},{type:"header",content:`+++ b/${e}`}],i=s.endsWith(`
24
24
  `),a=s.split(`
25
- `);if(i)a.pop();if(s.length>0){o.push({type:"hunk",content:`@@ -0,0 +1,${a.length} @@`});let u=1;for(let f of a)o.push({type:"addition",content:"+"+f,newLineNum:u++});if(!i)o.push({type:"context",content:"\"})}let c=ut(o),l=ot(c);if(l!==c)return{lines:Q(l)};return{lines:o}}catch{return{lines:[]}}}async function Je(t){let e=I(t),n=new Set,r=[];try{let s=await e.raw(["log","--oneline","--decorate=short","--all","-n","200"]),o=/\(([^)]+)\)/g;for(let i of s.split(`
26
- `)){let a=o.exec(i);if(a){let c=a[1].split(",").map((l)=>l.trim());for(let l of c){if(l.startsWith("HEAD")||l.startsWith("tag:")||!l.includes("/"))continue;let u=l.replace(/^.*-> /,"");if(u.includes("/")&&!n.has(u))n.add(u),r.push(u)}}o.lastIndex=0}if(r.length>0)r.sort((i,a)=>{let c=i.split("/").slice(1).join("/"),l=a.split("/").slice(1).join("/"),u=c==="main"||c==="master",f=l==="main"||l==="master";if(u&&!f)return-1;if(!u&&f)return 1;if(u&&f){let h=i.startsWith("origin/"),p=a.startsWith("origin/");if(h&&!p)return 1;if(!h&&p)return-1}return 0})}catch{}return[...new Set(r)]}async function Yt(t){return(await Je(t))[0]??null}async function Ye(t){return kt(t)??await Yt(t)}async function it(t,e){let n=I(t);try{return await n.raw(["cat-file","-e","--end-of-options",`${e}^{commit}`]),!0}catch{return!1}}async function Ke(t,e){let n=I(t),s=(await n.raw(["merge-base","--end-of-options",e,"HEAD"])).trim();if(!s)throw new _t(e);let o=await n.raw(["diff","--numstat",`${s}...HEAD`]),i=await n.raw(["diff","--name-status",`${s}...HEAD`]),a=ot(await n.raw(["diff",`-U${At}`,`${s}...HEAD`])),c=o.trim().split(`
27
- `).filter((S)=>S),l=new Map;for(let S of c){let m=S.split("\t");if(m.length>=3){let b=m[0]==="-"?0:parseInt(m[0],10),E=m[1]==="-"?0:parseInt(m[1],10),v=m.slice(2).join("\t");l.set(v,{additions:b,deletions:E})}}let u=i.trim().split(`
28
- `).filter((S)=>S),f=new Map;for(let S of u){let m=S.split("\t");if(m.length>=2){let b=m[0][0],E=m[m.length-1],v;switch(b){case"A":v="added";break;case"D":v="deleted";break;case"R":v="renamed";break;default:v="modified"}f.set(E,v)}}let h=[],p=a.split(/(?=^diff --git )/m).filter((S)=>S.trim());for(let S of p){let m=S.match(/^diff --git a\/.+ b\/(.+)$/m);if(!m)continue;let b=m[1],E=Q(S),v=l.get(b)||{additions:0,deletions:0},X=f.get(b)||"modified";h.push({path:b,status:X,additions:v.additions,deletions:v.deletions,diff:{lines:E}})}let g=0,w=0;for(let S of h)g+=S.additions,w+=S.deletions;let A=(await n.status()).files.length,x=(await n.log({from:s,to:"HEAD"})).all.map((S)=>({hash:S.hash,shortHash:S.hash.slice(0,7),message:S.message.split(`
29
- `)[0],author:S.author_name,date:new Date(S.date),refs:S.refs||""}));return h.sort((S,m)=>S.path.localeCompare(m.path)),{baseBranch:e,stats:{filesChanged:h.length,additions:g,deletions:w},files:h,commits:x,uncommittedCount:A}}async function Cr(t,e){let n=I(t),s=(await n.raw(["merge-base","--end-of-options",e,"HEAD"])).trim();if(!s)throw new _t(e);let o=await n.raw(["rev-list","--count","--end-of-options",`${s}..HEAD`]);return Number.parseInt(o.trim(),10)}function Br(t,e){switch(t.kind){case"commit":return["show","--format=",...e,"--end-of-options",t.hash];case"compare":return["diff",...e,`${t.base}...HEAD`];case"head":return["diff",...e,"HEAD"]}}async function Oi(t,e,n){let r=I(t),s=Br(e,["--name-status","-M","--diff-filter=R"]),o;try{o=await r.raw(s)}catch{return null}for(let i of o.trim().split(`
30
- `)){if(!i)continue;let a=i.split("\t");if(a.length>=3&&a[2]===n)return a[1]}return null}async function Ve(t,e,n,r={}){let s=I(t),o=r.context??At;try{let i=await Oi(t,e,n),a=i===null?[n]:[i,n],c=Br(e,["-M",`-U${o}`]),l=ot(await s.raw([...c,"--",...a]));return{lines:Q(l)}}catch{return{lines:[]}}}async function Hr(t,e){let n=I(t);try{let r=ot(await n.raw(["show","--format=",`-U${At}`,"--end-of-options",e]));return{lines:Q(r)}}catch{return{lines:[]}}}async function Gr(t,e){let n=I(t),r=await Ke(t,e),s=await n.diff(["HEAD","--numstat"]),o=ot(await n.diff([`-U${At}`,"HEAD"])),i=new Map;for(let y of s.trim().split(`
31
- `).filter((x)=>x)){let x=y.split("\t");if(x.length>=3){let S=x[0]==="-"?0:parseInt(x[0],10),m=x[1]==="-"?0:parseInt(x[1],10),b=x.slice(2).join("\t");i.set(b,{additions:S,deletions:m})}}let a=await n.status(),c=new Map;for(let y of a.files)if(y.index==="A"||y.working_dir==="?")c.set(y.path,"added");else if(y.index==="D"||y.working_dir==="D")c.set(y.path,"deleted");else if(y.index==="R")c.set(y.path,"renamed");else c.set(y.path,"modified");let l=[],u=o.split(/(?=^diff --git )/m).filter((y)=>y.trim());for(let y of u){let x=y.match(/^diff --git a\/.+ b\/(.+)$/m);if(!x)continue;let S=x[1],m=Q(y),b=i.get(S)||{additions:0,deletions:0},E=c.get(S)||"modified";l.push({path:S,status:E,additions:b.additions,deletions:b.deletions,diff:{lines:m},isUncommitted:!0})}let f=a.files.filter((y)=>y.working_dir==="?").map((y)=>y.path),h=await xt(t,f);for(let y of f){if(h.has(y))continue;let x=await Jt(t,y);if(x.lines.length===0)continue;l.push({path:y,status:"added",additions:x.lines.filter((S)=>S.type==="addition").length,deletions:0,diff:x,isUncommitted:!0})}let p=new Set(r.files.map((y)=>y.path)),g=[];for(let y of r.files){let x=l.find((S)=>S.path===y.path);if(x)g.push(y),g.push(x);else g.push(y)}for(let y of l)if(!p.has(y.path))g.push(y);let w=0,R=0,A=new Set;for(let y of g)A.add(y.path),w+=y.additions,R+=y.deletions;return g.sort((y,x)=>y.path.localeCompare(x.path)),{baseBranch:r.baseBranch,stats:{filesChanged:A.size,additions:w,deletions:R},files:g,commits:r.commits,uncommittedCount:r.uncommittedCount}}import*as Ur from"node:fs";import*as jr from"node:path";var $i=/^diff --git a\/.+ b\/(.+)$/;function ge(t){let e=5381;for(let n of t){for(let r=0;r<n.length;r++)e=(e<<5)+e+n.charCodeAt(r)|0;e=(e<<5)+e+10|0}return(e>>>0).toString(36)}function Li(t){let e=[],n="",r=null,s=()=>{if(r&&n)e.push({file:n,key:`${n}\x00${ge(r.body)}`,headerLine:r.headerLine});r=null};for(let o of t.lines)if(o.type==="header"){s();let i=o.content.match($i);if(i)n=i[1]}else if(o.type==="hunk")s(),r={headerLine:o,body:[]};else if(r&&(o.type==="addition"||o.type==="deletion"))r.body.push(o.content);return s(),e}class Qe{repoPath;stamps=new Map;constructor(t){this.repoPath=t}stamp(t){if(!t)return;let e=new Map;for(let n of Li(t)){let r=this.stamps.get(n.key);if(r===void 0){let s=e.get(n.file);if(s===void 0)s=this.mtimeOf(n.file),e.set(n.file,s);r=s,this.stamps.set(n.key,r)}n.headerLine.editedAt=r}}prune(t){for(let e of this.stamps.keys()){let n=e.slice(0,e.indexOf("\x00"));if(!t.has(n))this.stamps.delete(e)}}mtimeOf(t){try{return Ur.statSync(jr.join(this.repoPath,t)).mtimeMs}catch{return Date.now()}}}import*as Y from"node:fs";import*as T from"node:path";async function Ni(t){let e=tn(t);if(!e)return null;try{let n=I(e);if((await n.raw(["rev-parse","--is-bare-repository"])).trim()==="true")return null;return(await n.raw(["rev-parse","--show-toplevel"])).trim()||null}catch{return null}}async function we(t,{mustExist:e}){let n=z(t);if(!T.isAbsolute(n))return{ok:!1,reason:"not-absolute",requested:n};if(e&&!Ci(n))return{ok:!1,reason:"not-a-repo",requested:n};let r=await Ni(n);if(r)return{ok:!0,root:r};let s=Ui(await Bi(n));return s?{ok:!0,root:s.path}:{ok:!1,reason:"not-a-repo",requested:n}}function Ci(t){try{return Y.statSync(t).isDirectory()}catch{return!1}}async function Bi(t){let e=tn(t);if(!e)return[];try{let n=I(e);return zr(await n.raw(["worktree","list","--porcelain"]))}catch{return[]}}async function Ze(t){let e=tn(t);if(!e)return[];try{let r=await I(e).raw(["worktree","list","--porcelain"]),s=zr(r),o=await Gi(s,e);return s.map((i)=>({...i,lastActivity:i.isBare?null:Hi(Wr(i.path)),aheadOfBase:o.get(i.path)??null}))}catch{return[]}}function Hi(t){return Number.isFinite(t)?t:null}async function Gi(t,e){let n=t.filter((o)=>!o.isBare);if(n.length===0)return new Map;let r=await Yt(e).catch(()=>null),s=await Promise.all(n.map(async(o)=>{let i=kt(o.path)??r;if(!i)return null;try{let c=await I(o.path).raw(["rev-list","--count","--end-of-options",`${i}..HEAD`]);return[o.path,parseInt(c.trim(),10)]}catch{return null}}));return new Map(s.filter((o)=>o!==null))}function Ui(t){let e=null,n=-1/0;for(let r of t){if(r.isBare)continue;let s=Wr(r.path);if(s>n)n=s,e=r}return e}function Wr(t){let e=qr(t),n=e?[T.join(e,"index"),T.join(e,"HEAD")]:[t],r=-1/0;for(let s of n)try{let o=Y.statSync(s).mtimeMs;if(o>r)r=o}catch{}return r}function qr(t){let e=T.join(t,".git");try{if(Y.statSync(e).isDirectory())return e;let n=Y.readFileSync(e,"utf8").match(/^gitdir:\s*(.+)$/m);if(!n)return null;let r=n[1].trim();return T.isAbsolute(r)?r:T.resolve(t,r)}catch{return null}}function Xr(t){let e=qr(t);if(e===null)return null;let n=e;try{let r=Y.readFileSync(T.join(e,"commondir"),"utf8").trim();if(r)n=T.isAbsolute(r)?r:T.resolve(e,r)}catch{}return{gitDir:e,commonDir:n}}function zr(t){let e=[],n=null;for(let r of t.split(`
32
- `))if(r.startsWith("worktree ")){if(n)e.push(n);n={path:r.slice(9).trim(),branch:null,head:null,isBare:!1,isMain:e.length===0}}else if(!n)continue;else if(r.startsWith("HEAD "))n.head=r.slice(5).trim();else if(r.startsWith("branch "))n.branch=r.slice(7).trim().replace(/^refs\/heads\//,"");else if(r==="bare")n.isBare=!0;if(n)e.push(n);return e}function tn(t){try{if(Y.statSync(t).isDirectory())return t;return T.dirname(t)}catch{let e=T.dirname(t);return e!==t&&Y.existsSync(e)?e:null}}var Qi=Xo(ss(),1);var Zi=/^diff --git a\/.+ b\/(.+)$/;function os(t){return Zi.exec(t)?.[1]??null}function Se(t){let e=new Map,n=null;for(let s of t.lines){if(s.type==="header"){let o=os(s.content);if(o!==null)n=e.get(o)??[],e.set(o,n)}n?.push(s)}let r=new Map;for(let[s,o]of e)r.set(s,{lines:o});return r}var ve="diffstalker-journal: oversize untracked snapshot omitted";var na=262144;class Ee extends ea{repoPath;queue;hunkTimes;gitWatcher=null;workingDirWatcher=null;ignorers=new Map;_state={status:null,isLoading:!1,error:null,hunkCounts:null,stashList:[],operationInProgress:null,mtimes:null};constructor(t,e){super();this.repoPath=t,this.queue=e,this.hunkTimes=new Qe(t)}get state(){return this._state}updateState(t){this._state={...this._state,...t},this.emit("state-change",this._state)}setError(t){this.updateState({error:t})}clearError(){if(this._state.error!==null)this.updateState({error:null})}stampDiff(t){this.hunkTimes.stamp(t)}loadGitignores(){let t=new Map,e=as();e.add(".git");let n=M.join(this.repoPath,".gitignore");if(W.existsSync(n))e.add(W.readFileSync(n,"utf-8"));let r=M.join(this.repoPath,".git","info","exclude");if(W.existsSync(r))e.add(W.readFileSync(r,"utf-8"));t.set("",e);try{let s=ta("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:j()});for(let o of s.split("\x00")){if(!o||o===".gitignore")continue;if(!o.endsWith(".gitignore"))continue;let i=M.dirname(o),a=M.join(this.repoPath,o);try{let c=W.readFileSync(a,"utf-8"),l=as();l.add(c),t.set(i,l)}catch(c){ae(`Failed to read ${a}: ${c instanceof Error?c.message:c}`)}}}catch{}return t}startWatching(){let t=Xr(this.repoPath);if(t===null)return;let e=M.join(t.gitDir,"index"),n=M.join(t.gitDir,"HEAD"),r=M.join(t.commonDir,"refs"),s=M.join(t.commonDir,"packed-refs"),o=M.join(this.repoPath,".gitignore");this.gitWatcher=is([e,n,r,s,o],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=is(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(a,c)=>{let l=M.relative(this.repoPath,a);if(!l)return!1;let u=l.split("/");for(let f=0;f<u.length;f++){let h=f===0?"":u.slice(0,f).join("/"),p=this.ignorers.get(h);if(p){let g=f===0?l:u.slice(f).join("/");if(p.ignores(g))return!0}}return le(a,c)},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let i=()=>this.scheduleRefresh();this.gitWatcher.on("change",(a)=>{if(a===o)this.ignorers=this.loadGitignores();i()}),this.gitWatcher.on("add",i),this.gitWatcher.on("unlink",i),this.gitWatcher.on("error",(a)=>{let c=a instanceof Error?a.message:String(a);this.setError(`Git watcher error: ${c}`)}),this.workingDirWatcher.on("change",i),this.workingDirWatcher.on("add",i),this.workingDirWatcher.on("unlink",i),this.workingDirWatcher.on("error",(a)=>{let c=a instanceof Error?a.message:String(a);this.setError(`Working dir watcher error: ${c}`)})}dispose(){this.gitWatcher?.close(),this.workingDirWatcher?.close()}statMtimes(t){let e=new Map;for(let n of t.files){if(e.has(n.path))continue;try{e.set(n.path,W.statSync(M.join(this.repoPath,n.path)).mtimeMs)}catch{}}return e}pendingRefreshKind=null;scheduleRefresh(){this.requestRefresh("full")}scheduleStatusRefresh(){this.requestRefresh("status")}requestRefresh(t){if(this.pendingRefreshKind!==null){if(t==="full")this.pendingRefreshKind="full";return}if(this.queue.hasPendingMutations())return;this.pendingRefreshKind=t,this.queue.scheduleRefresh(async()=>{let e=this.pendingRefreshKind??"full";if(this.pendingRefreshKind=null,e==="full")await this.doRefresh();else await this.doStatusRefresh()})}async doStatusRefresh(){try{let t=await Xe(this.repoPath);if(!t.isRepo){this.updateState({status:t,isLoading:!1,error:"Not a git repository"});return}this.updateState({status:t,mtimes:this.statMtimes(t),isLoading:!1})}catch(t){this.updateState({isLoading:!1,error:t instanceof Error?t.message:"Unknown error"})}}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.updateState({isLoading:!0,error:null});let t=Date.now(),e=await me(this.repoPath).catch(()=>null);try{let n=await Xe(this.repoPath);if(!n.isRepo){this.updateState({status:n,isLoading:!1,error:"Not a git repository"});return}let[r,s,o,i,a]=await Promise.all([It(this.repoPath,void 0,!1),It(this.repoPath,void 0,!0),he(this.repoPath),Z(this.repoPath),this.gatherJournalInputs(n,e,t)]),c={unstaged:fe(ut(r.lines)),staged:fe(ut(s.lines))};this.hunkTimes.stamp(r),this.hunkTimes.stamp(s),this.hunkTimes.prune(new Set(n.files.map((u)=>u.path)));let l=this.statMtimes(n);if(this.updateState({status:n,hunkCounts:c,stashList:o,operationInProgress:i,mtimes:l,isLoading:!1}),a!==null)this.emit("journal-observation",{status:n,headDiff:a.headDiff,headOid:a.headOid,stashCount:a.stashCount,operationInProgress:a.operationInProgress,mtimes:a.mtimes,at:Date.now()})}catch(n){this.updateState({isLoading:!1,error:n instanceof Error?n.message:"Unknown error"})}}async snapshotJournalGuard(t){let[e,n]=await Promise.all([Z(this.repoPath),he(this.repoPath)]);return{operation:e,stashCount:n.length,mtimes:this.statMtimes(t)}}static journalGuardMoved(t,e){if(t.operation!==e.operation||t.stashCount!==e.stashCount)return!0;if(t.mtimes.size!==e.mtimes.size)return!0;for(let[n,r]of t.mtimes)if(e.mtimes.get(n)!==r)return!0;return!1}sectionWrittenDuringGather(t,e,n){let r=new Set(e);for(let s of t.files)if(s.status==="untracked")r.add(s.path);for(let s of r)try{let o=W.statSync(M.join(this.repoPath,s));if(Math.floor(o.mtimeMs)>n)return!0}catch{}return!1}async gatherJournalInputs(t,e,n){if(e===null)return null;try{let r=await this.snapshotJournalGuard(t),s=await Nr(this.repoPath),o=new Set(Se(s).keys()),i=[...s.lines];await this.appendUntrackedSections(t,o,i);let a=await me(this.repoPath);if(e!==a)return null;let c=await this.snapshotJournalGuard(t);if(Ee.journalGuardMoved(r,c))return null;if(this.sectionWrittenDuringGather(t,o,n))return null;return{headDiff:{lines:i},headOid:a,stashCount:c.stashCount,operationInProgress:c.operation,mtimes:c.mtimes}}catch{return null}}async appendUntrackedSections(t,e,n){let r=new Set;for(let s of t.files){if(s.status!=="untracked"||r.has(s.path)||e.has(s.path))continue;r.add(s.path);let o;try{o=W.statSync(M.join(this.repoPath,s.path))}catch{continue}if(!o.isFile())continue;if(o.size>na){this.appendOversizeSection(s.path,o,n);continue}let i=await Jt(this.repoPath,s.path);if(i.lines.length===0)continue;n.push(...i.lines)}}appendOversizeSection(t,e,n){let r=[`diff --git a/${t} b/${t}`,"new file mode 100644",`${ve} size=${e.size} mtime=${Math.round(e.mtimeMs)}`];n.push(...r.map((s)=>({type:"header",content:s})))}async stage(t){try{await this.queue.enqueueMutation(()=>lr(this.repoPath,t.path)),this.scheduleStatusRefresh()}catch(e){await this.refresh(),this.updateState({error:`Failed to stage ${t.path}: ${e instanceof Error?e.message:String(e)}`})}}async unstage(t){try{await this.queue.enqueueMutation(()=>ur(this.repoPath,t.path)),this.scheduleStatusRefresh()}catch(e){await this.refresh(),this.updateState({error:`Failed to unstage ${t.path}: ${e instanceof Error?e.message:String(e)}`})}}async stageHunk(t){try{await this.queue.enqueueMutation(async()=>wr(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.updateState({error:`Failed to stage hunk: ${e instanceof Error?e.message:String(e)}`})}}async unstageHunk(t){try{await this.queue.enqueueMutation(async()=>yr(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.updateState({error:`Failed to unstage hunk: ${e instanceof Error?e.message:String(e)}`})}}async discard(t){if(t.staged)return;let e=t.status==="untracked"?()=>dr(this.repoPath,t.path):()=>pr(this.repoPath,t.path);try{await this.queue.enqueueMutation(e),await this.refresh()}catch(n){this.updateState({error:`Failed to discard ${t.path}: ${n instanceof Error?n.message:String(n)}`})}}async stageAll(){try{await this.queue.enqueueMutation(()=>fr(this.repoPath)),await this.refresh()}catch(t){this.updateState({error:`Failed to stage all: ${t instanceof Error?t.message:String(t)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>hr(this.repoPath)),await this.refresh()}catch(t){this.updateState({error:`Failed to unstage all: ${t instanceof Error?t.message:String(t)}`})}}async commit(t,e=!1){try{await this.queue.enqueue(()=>mr(this.repoPath,t,e)),await this.refresh()}catch(n){this.updateState({error:`Failed to commit: ${n instanceof Error?n.message:String(n)}`})}}async loadStashList(){try{let t=await this.queue.enqueue(()=>he(this.repoPath));this.updateState({stashList:t})}catch{}}}import{EventEmitter as ra}from"node:events";class sn extends ra{repoPath;queue;callbacks;_remoteState={operation:null,inProgress:!1,error:null,lastResult:null};constructor(t,e,n){super();this.repoPath=t,this.queue=e,this.callbacks=n}get remoteState(){return this._remoteState}updateRemoteState(t){this._remoteState={...this._remoteState,...t},this.emit("remote-state-change",this._remoteState)}async runRemoteOperation(t,e){this.updateRemoteState({operation:t,inProgress:!0,error:null,lastResult:null});try{let n=await this.queue.enqueue(e);this.updateRemoteState({inProgress:!1,lastResult:n}),this.callbacks.scheduleRefresh()}catch(n){let r=n instanceof Error?n.message:String(n);this.updateRemoteState({inProgress:!1,error:r})}return this._remoteState}clearRemoteState(){this.updateRemoteState({operation:null,error:null,lastResult:null})}async push(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("push",()=>br(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>Sr(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>vr(this.repoPath))}async stash(t){if(this._remoteState.inProgress)return null;let e=await this.runRemoteOperation("stash",()=>kr(this.repoPath,t));return await this.callbacks.loadStashList(),e}async stashPop(t=0){if(this._remoteState.inProgress)return null;let e=await this.runRemoteOperation("stashPop",()=>Rr(this.repoPath,t));return await this.callbacks.loadStashList(),e}async getLocalBranches(){return this.queue.enqueue(()=>pe(this.repoPath))}async switchBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>_r(this.repoPath,t))}async createBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>Ar(this.repoPath,t))}async softReset(t=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>Ir(this.repoPath,t))}async cherryPick(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>Dr(this.repoPath,t))}async revertCommit(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>Pr(this.repoPath,t))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>Mr(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>Fr(this.repoPath))}}import{EventEmitter as sa}from"node:events";import{randomBytes as oa}from"node:crypto";var ia=262144,aa=500,ca=16777216,us=Number.MAX_SAFE_INTEGER,la=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function ua(t){let e=la.exec(t);if(!e)return null;return{oldStart:parseInt(e[1],10),oldCount:e[2]!==void 0?parseInt(e[2],10):1}}function fa(t,e){let n=ua(e);if(!n)return[];let r=n.oldCount===0?n.oldStart+1:n.oldStart,s=[],o=null;for(let i of t){let a=i.content[0];if(a==="\\")continue;if(a==="-")o=ha(o,r),r++;else if(a==="+")o=o??{hasDel:!1,delStart:0,delEnd:0,anchor:r-1};else cs(s,o),o=null,r++}return cs(s,o),s}function ha(t,e){if(!t)return{hasDel:!0,delStart:e,delEnd:e,anchor:e-1};if(!t.hasDel)t.hasDel=!0,t.delStart=e;return t.delEnd=e,t}function cs(t,e){if(!e)return;t.push(e.hasDel?[2*e.delStart,2*e.delEnd]:[2*e.anchor,2*e.anchor+2])}function on(t){if(t.length===0)return{start:0,count:0};let e=1/0,n=-1/0;for(let[o,i]of t){if(o<e)e=o;if(i>n)n=i}if(n>=us)return{start:0,count:0};let r=Math.ceil(e/2),s=Math.floor(n/2);return{start:r,count:s-r+1}}function pa(t){let e=[],n=null,r=[],s=null;for(let i of t.lines)if(i.type==="hunk")s={header:i,body:[]},r.push(s);else if(s)s.body.push(i);else if(e.push(i),i.content.startsWith("rename from "))n=i.content.slice(12);if(r.length===0){let i=e.some((a)=>a.content.startsWith(ve));return{hunks:[{runs:[[0,us]],bodyHash:ge([ut(t.lines)]),ins:0,del:0,span:{start:0,count:0},diff:t,oversize:i}],renamedFrom:n,hunkless:!0}}return{hunks:r.map(({header:i,body:a})=>{let c=fa(a,i.content),l=[],u=0,f=0;for(let p of a){let g=p.content[0];if(g==="\\")continue;if(g==="+")u++,l.push(p.content);else if(g==="-")f++,l.push(p.content)}let h=[...e,i,...a];return{runs:c,bodyHash:ge(l),ins:u,del:f,span:on(c),diff:{lines:h}}}),renamedFrom:n,hunkless:!1}}function da(t){if(t.oversize===!0)return null;return ue(t.diff.lines)>ia?null:t.diff}function ma(t,e,n){if(t===0&&e>0)return"shrunk";let r=t+e;if(r>n)return"expanded";if(r<n)return"shrunk";return"edited"}function ls(t,e){let n=[];return t.forEach((r,s)=>{for(let[o,i]of r.runs)n.push({lo:o,hi:i,node:e+s})}),n.sort((r,s)=>r.lo-s.lo),n}function ga(t,e){let n=Array.from({length:t.length+e.length},(c,l)=>l),r=(c)=>{while(n[c]!==c)n[c]=n[n[c]],c=n[c];return c},s=(c,l)=>{let u=r(c),f=r(l);if(u!==f)n[u]=f},o=ls(t,0),i=ls(e,t.length),a=0;for(let c of o){while(a<i.length&&i[a].hi<c.lo)a++;for(let l=a;l<i.length&&i[l].lo<=c.hi;l++)s(c.node,i[l].node)}return n.map((c,l)=>r(l))}function wa(t,e){let n=ga(t,e),r=new Map,s=(o)=>{let i=r.get(o);if(!i)i={prevIdx:[],nextIdx:[],minLo:1/0},r.set(o,i);return i};return t.forEach((o,i)=>{let a=s(n[i]);a.prevIdx.push(i);for(let[c]of o.runs)if(c<a.minLo)a.minLo=c}),e.forEach((o,i)=>{let a=s(n[t.length+i]);a.nextIdx.push(i);for(let[c]of o.runs)if(c<a.minLo)a.minLo=c}),[...r.values()].sort((o,i)=>o.minLo-i.minLo)}function ya(t,e,n){let r=[],s=e.map(()=>null),o=n;for(let i of wa(t,e)){let a=i.prevIdx.map((f)=>t[f]),c=i.nextIdx.map((f)=>e[f]);if(a.length===1&&c.length===1&&a[0].bodyHash===c[0].bodyHash){let f=c[0];s[i.nextIdx[0]]={seq:a[0].seq,runs:f.runs,bodyHash:f.bodyHash,ins:f.ins,del:f.del};continue}if(c.length===0){for(let f of a)r.push({seq:o++,kind:"reverted",span:on(f.runs),stats:{insertions:0,deletions:0},diff:null,supersedes:[f.seq],siblings:1});continue}let l=a.map((f)=>f.seq),u=a.reduce((f,h)=>f+h.ins+h.del,0);for(let f of i.nextIdx){let h=e[f],p={seq:o++,kind:a.length===0?"created":ma(h.ins,h.del,u),span:h.span,stats:{insertions:h.ins,deletions:h.del},diff:da(h),supersedes:[...l],siblings:c.length};r.push(p),s[f]={seq:p.seq,runs:h.runs,bodyHash:h.bodyHash,ins:h.ins,del:h.del}}}return{entries:r,nextLive:s.filter((i)=>i!==null)}}function ba(t,e){let n=Array(t.length).fill(!1),r=Array(e.length).fill(null);for(let a=0;a<e.length;a++){let c=t.findIndex((l,u)=>!n[u]&&l.bodyHash===e[a].bodyHash);if(c!==-1)n[c]=!0,r[a]=t[c].seq}for(let a=0;a<e.length;a++){if(r[a]!==null)continue;let c=n.findIndex((l)=>!l);if(c!==-1)n[c]=!0,r[a]=t[c].seq}let s=t[t.length-1].seq,o=e.map((a,c)=>({seq:r[c]??s,runs:a.runs,bodyHash:a.bodyHash,ins:a.ins,del:a.del})),i=t.filter((a,c)=>!n[c]).map((a)=>a.seq);return{carried:o,retired:i}}function xe(){return{entries:[],epoch:`${Date.now().toString(36)}-${oa(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class an extends sa{store;constructor(t){super();this.store=t}get journalStore(){return this.store}observe(t){try{this.doObserve(t)}catch(e){ae(`Journal observation skipped: ${e instanceof Error?e.message:String(e)}`)}}doObserve(t){let e=[];if(this.store.lastHeadOid===null){if(t.operationInProgress===null)this.seed(t,e)}else if(this.handleOperations(t,e));else if(t.headOid!==this.store.lastHeadOid)this.rebaseline(t,e);else this.classify(t,e);if(e.length>0)this.store.entries.push(...e),this.emit("append",e),this.pruneStore()}pruneStore(){let t=new Set;for(let e of this.store.live.values())for(let n of e)t.add(n.seq);this.pruneBodies(t),this.pruneEntries(t)}pruneBodies(t){let e=0;for(let n of this.store.entries)if(n.type==="hunk"&&n.diff!==null)e+=ue(n.diff.lines);for(let n of this.store.entries){if(e<=ca)return;if(n.type!=="hunk"||n.diff===null||t.has(n.seq))continue;e-=ue(n.diff.lines),n.diff=null}}pruneEntries(t){let e=this.store.entries,n=0;while(e.length-n>aa&&(e[n].type==="boundary"||!t.has(e[n].seq)))n++;if(n>0)e.splice(0,n)}handleOperations(t,e){let n=this.store.lastOperation;if(t.operationInProgress!==null){if(n===null)e.push(this.boundary("op-start",t.operationInProgress,[],t.at)),this.store.lastOperation=t.operationInProgress;return!0}if(n!==null)e.push(this.boundary("op-end",n,[],t.at)),this.store.lastOperation=null;return!1}seed(t,e){e.push(this.boundary("journal-start",t.status.branch.current,[],t.at));let{files:n}=this.parseObservation(t),r=[...n.keys()].sort((s,o)=>this.tsFor(t,s)-this.tsFor(t,o));for(let s of r)this.classifyPath(s,[],n.get(s).hunks,t,!0,e);this.store.lastHeadOid=t.headOid,this.store.lastBranch=t.status.branch.current,this.store.lastStashCount=t.stashCount,this.store.lastOperation=null}rebaseline(t,e){let{files:n,deferred:r}=this.parseObservation(t),s=t.status.branch.current===this.store.lastBranch,o=s?"commit":"checkout",i=s?t.headOid.slice(0,7):t.status.branch.current,{resolves:a,newLive:c}=this.carrySurvivors(n,r);e.push(this.boundary(o,i,a,t.at)),this.store.live=c;for(let[l,{hunks:u}]of n){if(c.has(l))continue;this.classifyPath(l,[],u,t,!1,e)}this.store.lastHeadOid=t.headOid,this.store.lastBranch=t.status.branch.current,this.store.lastStashCount=t.stashCount}carrySurvivors(t,e){let n=[],r=new Map;for(let[s,o]of this.store.live){if(e.has(s)){r.set(s,o);continue}let i=t.get(s);if(!i){n.push(...o.map((l)=>l.seq));continue}let{carried:a,retired:c}=ba(o,i.hunks);n.push(...c),r.set(s,a)}return{resolves:n,newLive:r}}classify(t,e){let{files:n,deferred:r}=this.parseObservation(t);this.handleRenames(t,n,e),this.handleDisappearances(t,n,r,e);for(let[s,{hunks:o,renamedFrom:i,hunkless:a}]of n){let c=this.store.live.get(s)??[];if(a&&i!==null&&c.length>0)continue;this.classifyPath(s,c,o,t,!1,e)}this.store.lastBranch=t.status.branch.current,this.store.lastStashCount=t.stashCount}handleRenames(t,e,n){for(let[r,s]of e){let o=s.renamedFrom;if(o===null||o===r)continue;if(!this.store.live.has(o)||e.has(o))continue;let i=(this.store.live.get(r)??[]).map((a)=>a.seq);this.store.live.set(r,this.store.live.get(o)),this.store.live.delete(o),n.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor(t,r),path:r,status:"renamed",kind:"renamed",span:{start:0,count:0},stats:{insertions:0,deletions:0},diff:null,supersedes:i,siblings:1,seeded:!1})}}handleDisappearances(t,e,n,r){let s=[...this.store.live.keys()].filter((o)=>!e.has(o)&&!n.has(o));if(s.length===0)return;if(t.stashCount>this.store.lastStashCount){let o=s.flatMap((i)=>this.store.live.get(i).map((a)=>a.seq));r.push(this.boundary("stash","stash",o,t.at));for(let i of s)this.store.live.delete(i);return}for(let o of s){let i=this.store.live.get(o);r.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor(t,o),path:o,status:this.statusOf(t,o),kind:"reverted",span:on(i.flatMap((a)=>a.runs)),stats:{insertions:0,deletions:0},diff:null,supersedes:i.map((a)=>a.seq),siblings:1,seeded:!1}),this.store.live.delete(o)}}classifyPath(t,e,n,r,s,o){let{entries:i,nextLive:a}=ya(e,n,this.store.nextSeq);this.store.nextSeq+=i.length;let c=this.tsFor(r,t),l=this.statusOf(r,t);for(let u of i){let f={type:"hunk",seq:u.seq,ts:c,path:t,status:l,kind:u.kind==="created"&&l==="renamed"?"renamed":u.kind,span:u.span,stats:u.stats,diff:u.diff,supersedes:u.supersedes,siblings:u.siblings,seeded:s};o.push(f)}if(a.length>0)this.store.live.set(t,a);else this.store.live.delete(t)}parseObservation(t){let e=new Map;for(let[r,s]of Se(t.headDiff))e.set(r,pa(s));let n=new Set;for(let r of t.status.files)if(r.status==="untracked"&&!e.has(r.path))n.add(r.path);return{files:e,deferred:n}}boundary(t,e,n,r){return{type:"boundary",seq:this.store.nextSeq++,ts:r,kind:t,label:e,resolves:n}}tsFor(t,e){let n=t.mtimes?.get(e);return n===void 0?t.at:Math.min(n,t.at)}statusOf(t,e){return t.status.files.find((n)=>n.path===e)?.status??"modified"}}class cn{workingTree;remote;journal;repoPath;constructor(t,e){this.repoPath=t;let n=Vn(t);this.workingTree=new Ee(t,n),this.remote=new sn(t,n,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new an(e??xe()),this.workingTree.on("journal-observation",(r)=>this.journal.observe(r))}dispose(){this.workingTree.dispose(),Qn(this.repoPath)}}function va(t){return Sa("sha256").update(t).digest("hex").slice(0,12)}var Ea=32;class fs{cap;stores=new Map;constructor(t=Ea){this.cap=t}acquire(t){let e=this.stores.get(t);if(e)this.stores.delete(t);else e=xe();return this.stores.set(t,e),e}prune(t){if(this.stores.size<=this.cap)return;for(let e of this.stores.keys()){if(this.stores.size<=this.cap)return;if(t(e))continue;this.stores.delete(e)}}has(t){return this.stores.has(t)}get size(){return this.stores.size}}class ln{events;byId=new Map;byPath=new Map;journalStores=new fs;constructor(t={}){this.events=t}async openRepo(t){let e=await we(t,{mustExist:!1});if(!e.ok)throw Error(e.reason==="not-absolute"?`Repo path must be absolute: ${e.requested}`:`Not a git repository: ${e.requested}`);let n=e.root,r=this.byPath.get(n);if(r)return r.refCount++,{handle:r,created:!1};let s=va(n),o=new cn(n,this.journalStores.acquire(s));o.workingTree.startWatching();let i={id:s,path:n,manager:o,refCount:1};return this.byId.set(i.id,i),this.byPath.set(n,i),this.journalStores.prune((a)=>this.byId.has(a)),this.events.onOpened?.(i),{handle:i,created:!0}}getRepo(t){return this.byId.get(t)}listRepos(){return[...this.byId.values()]}closeRepo(t){let e=this.byId.get(t);if(!e)return!1;if(e.refCount--,e.refCount>0)return!1;return this.byId.delete(e.id),this.byPath.delete(e.path),e.manager.dispose(),this.events.onClosed?.(e.id),!0}disposeAll(){for(let t of this.byId.values())t.manager.dispose();this.byId.clear(),this.byPath.clear()}}async function ke(t,e){let n=await t.openRepo(e);if(n.created)n.handle.manager.workingTree.refresh().catch(()=>{});return n}var hs=25000;function Vt(t,e,n){t.write(`event: ${e}
25
+ `);if(i)a.pop();if(s.length>0){o.push({type:"hunk",content:`@@ -0,0 +1,${a.length} @@`});let u=1;for(let f of a)o.push({type:"addition",content:"+"+f,newLineNum:u++});if(!i)o.push({type:"context",content:"\"})}let c=ut(o),l=ot(c);if(l!==c)return{lines:Q(l)};return{lines:o}}catch{return{lines:[]}}}async function Ye(t){let e=k(t),n=new Set,r=[];try{let s=await e.raw(["log","--oneline","--decorate=short","--all","-n","200"]),o=/\(([^)]+)\)/g;for(let i of s.split(`
26
+ `)){let a=o.exec(i);if(a){let c=a[1].split(",").map((l)=>l.trim());for(let l of c){if(l.startsWith("HEAD")||l.startsWith("tag:")||!l.includes("/"))continue;let u=l.replace(/^.*-> /,"");if(u.includes("/")&&!n.has(u))n.add(u),r.push(u)}}o.lastIndex=0}if(r.length>0)r.sort((i,a)=>{let c=i.split("/").slice(1).join("/"),l=a.split("/").slice(1).join("/"),u=c==="main"||c==="master",f=l==="main"||l==="master";if(u&&!f)return-1;if(!u&&f)return 1;if(u&&f){let h=i.startsWith("origin/"),p=a.startsWith("origin/");if(h&&!p)return 1;if(!h&&p)return-1}return 0})}catch{}return[...new Set(r)]}async function Yt(t){return(await Ye(t))[0]??null}async function Ke(t){return Rt(t)??await Yt(t)}async function it(t,e){let n=k(t);try{return await n.raw(["cat-file","-e","--end-of-options",`${e}^{commit}`]),!0}catch{return!1}}async function Oi(t,e){let n=k(t),s=(await n.raw(["merge-base","--end-of-options",e,"HEAD"])).trim();if(!s)throw new It(e);let o=await n.raw(["diff","--numstat",`${s}...HEAD`]),i=await n.raw(["diff","--name-status",`${s}...HEAD`]),a=ot(await n.raw(["diff",`-U${At}`,`${s}...HEAD`])),c=o.trim().split(`
27
+ `).filter((v)=>v),l=new Map;for(let v of c){let m=v.split("\t");if(m.length>=3){let y=m[0]==="-"?0:parseInt(m[0],10),S=m[1]==="-"?0:parseInt(m[1],10),b=m.slice(2).join("\t");l.set(b,{additions:y,deletions:S})}}let u=i.trim().split(`
28
+ `).filter((v)=>v),f=new Map;for(let v of u){let m=v.split("\t");if(m.length>=2){let y=m[0][0],S=m[m.length-1],b;switch(y){case"A":b="added";break;case"D":b="deleted";break;case"R":b="renamed";break;default:b="modified"}f.set(S,b)}}let h=[],p=a.split(/(?=^diff --git )/m).filter((v)=>v.trim());for(let v of p){let m=v.match(/^diff --git a\/.+ b\/(.+)$/m);if(!m)continue;let y=m[1],S=Q(v),b=l.get(y)||{additions:0,deletions:0},X=f.get(y)||"modified";h.push({path:y,status:X,additions:b.additions,deletions:b.deletions,diff:{lines:S}})}let w=0,g=0;for(let v of h)w+=v.additions,g+=v.deletions;let _=(await n.status()).files.length,A=(await n.log({from:s,to:"HEAD"})).all.map((v)=>({hash:v.hash,shortHash:v.hash.slice(0,7),message:v.message.split(`
29
+ `)[0],author:v.author_name,date:new Date(v.date),refs:v.refs||""}));return h.sort((v,m)=>v.path.localeCompare(m.path)),{baseBranch:e,stats:{filesChanged:h.length,additions:w,deletions:g},files:h,commits:A,uncommittedCount:_}}async function Cr(t,e){let n=k(t),s=(await n.raw(["merge-base","--end-of-options",e,"HEAD"])).trim();if(!s)throw new It(e);let o=await n.raw(["rev-list","--count","--end-of-options",`${s}..HEAD`]);return Number.parseInt(o.trim(),10)}function de(t,e){switch(t.kind){case"commit":return["show","--format=",...e,"--end-of-options",t.hash];case"compare":return["diff",...e,`${t.base}...HEAD`];case"head":return["diff",...e,"HEAD"];case"staged":return["diff","--cached",...e];case"unstaged":return["diff",...e]}}async function $i(t,e,n){let r=k(t),s=de(e,["--name-status","-M","--diff-filter=R"]),o;try{o=await r.raw(s)}catch{return null}for(let i of o.trim().split(`
30
+ `)){if(!i)continue;let a=i.split("\t");if(a.length>=3&&a[2]===n)return a[1]}return null}async function Ve(t,e,n,r={}){let s=k(t),o=r.context??At;try{let i=await $i(t,e,n),a=i===null?[n]:[i,n],c=de(e,["-M",`-U${o}`]),l=ot(await s.raw([...c,"--",...a]));return{lines:Q(l)}}catch{return{lines:[]}}}async function Br(t,e){let n=k(t);try{let r=ot(await n.raw(["show","--format=",`-U${At}`,"--end-of-options",e]));return{lines:Q(r)}}catch{return{lines:[]}}}function Ni(t){if(t.staged&&t.unstaged)return"both";if(t.staged)return"staged";if(t.unstaged)return"unstaged";return null}function Li(t){switch(t){case"both":return{kind:"head"};case"staged":return{kind:"staged"};case"unstaged":return{kind:"unstaged"}}}function Ci(t,e,n){let r=t==="staged"?[e]:t==="unstaged"?[n]:[e,n];if(r.includes("R"))return"renamed";if(r.includes("D"))return"deleted";if(r.includes("A")||r.includes("?"))return"added";return"modified"}function Bi(t){let e=new Map;for(let n of t.trim().split(`
31
+ `)){if(!n)continue;let r=n.split("\t");if(r.length<3)continue;let s=r[0]==="-"?0:parseInt(r[0],10),o=r[1]==="-"?0:parseInt(r[1],10);e.set(r.slice(2).join("\t"),{additions:s,deletions:o})}return e}async function Hi(t,e,n){let r=k(t),s=Li(e),o=Bi(await r.raw(de(s,["--numstat"]))),i=ot(await r.raw(de(s,[`-U${At}`]))),a=new Map(n.files.map((l)=>[l.path,l])),c=[];for(let l of i.split(/(?=^diff --git )/m)){if(!l.trim())continue;let u=l.match(/^diff --git a\/.+ b\/(.+)$/m);if(!u)continue;let f=u[1],h=a.get(f);c.push({path:f,status:Ci(e,h?.index??"",h?.working_dir??""),...o.get(f)??{additions:0,deletions:0},diff:{lines:Q(l)},uncommitted:e})}return c}async function Ui(t,e){let n=e.files.filter((o)=>o.working_dir==="?").map((o)=>o.path),r=await kt(t,n),s=[];for(let o of n){if(r.has(o))continue;let i=await pt(t,o);if(i.lines.length===0)continue;s.push({path:o,status:"added",additions:i.lines.filter((a)=>a.type==="addition").length,deletions:0,diff:i,uncommitted:"untracked"})}return s}async function Hr(t,e,n=Ii){let r=await Oi(t,e),s=Ni(n);if(s===null&&!n.untracked)return r;let o=await k(t).status(),i=[...s===null?[]:await Hi(t,s,o),...n.untracked?await Ui(t,o):[]],a=new Set(r.files.map((u)=>u.path)),c=[];for(let u of r.files)c.push(u),c.push(...i.filter((f)=>f.path===u.path));c.push(...i.filter((u)=>!a.has(u.path))),c.sort((u,f)=>u.path.localeCompare(f.path));let l=new Set(c.map((u)=>u.path));return{baseBranch:r.baseBranch,stats:{filesChanged:l.size,additions:c.reduce((u,f)=>u+f.additions,0),deletions:c.reduce((u,f)=>u+f.deletions,0)},files:c,commits:r.commits,uncommittedCount:r.uncommittedCount}}import*as Ur from"node:fs";import*as Gr from"node:path";var Gi=/^diff --git a\/.+ b\/(.+)$/;function we(t){let e=5381;for(let n of t){for(let r=0;r<n.length;r++)e=(e<<5)+e+n.charCodeAt(r)|0;e=(e<<5)+e+10|0}return(e>>>0).toString(36)}function ji(t){let e=[],n="",r=null,s=()=>{if(r&&n)e.push({file:n,key:`${n}\x00${we(r.body)}`,headerLine:r.headerLine});r=null};for(let o of t.lines)if(o.type==="header"){s();let i=o.content.match(Gi);if(i)n=i[1]}else if(o.type==="hunk")s(),r={headerLine:o,body:[]};else if(r&&(o.type==="addition"||o.type==="deletion"))r.body.push(o.content);return s(),e}class Qe{repoPath;stamps=new Map;constructor(t){this.repoPath=t}stamp(t){if(!t)return;let e=new Map;for(let n of ji(t)){let r=this.stamps.get(n.key);if(r===void 0){let s=e.get(n.file);if(s===void 0)s=this.mtimeOf(n.file),e.set(n.file,s);r=s,this.stamps.set(n.key,r)}n.headerLine.editedAt=r}}prune(t){for(let e of this.stamps.keys()){let n=e.slice(0,e.indexOf("\x00"));if(!t.has(n))this.stamps.delete(e)}}mtimeOf(t){try{return Ur.statSync(Gr.join(this.repoPath,t)).mtimeMs}catch{return Date.now()}}}import*as Y from"node:fs";import*as T from"node:path";async function Wi(t){let e=tn(t);if(!e)return null;try{let n=k(e);if((await n.raw(["rev-parse","--is-bare-repository"])).trim()==="true")return null;return(await n.raw(["rev-parse","--show-toplevel"])).trim()||null}catch{return null}}async function ye(t,{mustExist:e}){let n=z(t);if(!T.isAbsolute(n))return{ok:!1,reason:"not-absolute",requested:n};if(e&&!qi(n))return{ok:!1,reason:"not-a-repo",requested:n};let r=await Wi(n);if(r)return{ok:!0,root:r};let s=Yi(await Xi(n));return s?{ok:!0,root:s.path}:{ok:!1,reason:"not-a-repo",requested:n}}function qi(t){try{return Y.statSync(t).isDirectory()}catch{return!1}}async function Xi(t){let e=tn(t);if(!e)return[];try{let n=k(e);return Xr(await n.raw(["worktree","list","--porcelain"]))}catch{return[]}}async function Ze(t){let e=tn(t);if(!e)return[];try{let r=await k(e).raw(["worktree","list","--porcelain"]),s=Xr(r),o=await Ji(s,e);return s.map((i)=>({...i,lastActivity:i.isBare?null:zi(jr(i.path)),aheadOfBase:o.get(i.path)??null}))}catch{return[]}}function zi(t){return Number.isFinite(t)?t:null}async function Ji(t,e){let n=t.filter((o)=>!o.isBare);if(n.length===0)return new Map;let r=await Yt(e).catch(()=>null),s=await Promise.all(n.map(async(o)=>{let i=Rt(o.path)??r;if(!i)return null;try{let c=await k(o.path).raw(["rev-list","--count","--end-of-options",`${i}..HEAD`]);return[o.path,parseInt(c.trim(),10)]}catch{return null}}));return new Map(s.filter((o)=>o!==null))}function Yi(t){let e=null,n=-1/0;for(let r of t){if(r.isBare)continue;let s=jr(r.path);if(s>n)n=s,e=r}return e}function jr(t){let e=Wr(t),n=e?[T.join(e,"index"),T.join(e,"HEAD")]:[t],r=-1/0;for(let s of n)try{let o=Y.statSync(s).mtimeMs;if(o>r)r=o}catch{}return r}function Wr(t){let e=T.join(t,".git");try{if(Y.statSync(e).isDirectory())return e;let n=Y.readFileSync(e,"utf8").match(/^gitdir:\s*(.+)$/m);if(!n)return null;let r=n[1].trim();return T.isAbsolute(r)?r:T.resolve(t,r)}catch{return null}}function qr(t){let e=Wr(t);if(e===null)return null;let n=e;try{let r=Y.readFileSync(T.join(e,"commondir"),"utf8").trim();if(r)n=T.isAbsolute(r)?r:T.resolve(e,r)}catch{}return{gitDir:e,commonDir:n}}function Xr(t){let e=[],n=null;for(let r of t.split(`
32
+ `))if(r.startsWith("worktree ")){if(n)e.push(n);n={path:r.slice(9).trim(),branch:null,head:null,isBare:!1,isMain:e.length===0}}else if(!n)continue;else if(r.startsWith("HEAD "))n.head=r.slice(5).trim();else if(r.startsWith("branch "))n.branch=r.slice(7).trim().replace(/^refs\/heads\//,"");else if(r==="bare")n.isBare=!0;if(n)e.push(n);return e}function tn(t){try{if(Y.statSync(t).isDirectory())return t;return T.dirname(t)}catch{let e=T.dirname(t);return e!==t&&Y.existsSync(e)?e:null}}var oa=qo(rs(),1);var ia=/^diff --git a\/.+ b\/(.+)$/;function ss(t){return ia.exec(t)?.[1]??null}function ve(t){let e=new Map,n=null;for(let s of t.lines){if(s.type==="header"){let o=ss(s.content);if(o!==null)n=e.get(o)??[],e.set(o,n)}n?.push(s)}let r=new Map;for(let[s,o]of e)r.set(s,{lines:o});return r}var Ee="diffstalker-journal: oversize untracked snapshot omitted";var la=262144;class xe extends ca{repoPath;queue;hunkTimes;gitWatcher=null;workingDirWatcher=null;ignorers=new Map;_state={status:null,isLoading:!1,error:null,hunkCounts:null,stashList:[],operationInProgress:null,mtimes:null};constructor(t,e){super();this.repoPath=t,this.queue=e,this.hunkTimes=new Qe(t)}get state(){return this._state}updateState(t){this._state={...this._state,...t},this.emit("state-change",this._state)}setError(t){this.updateState({error:t})}clearError(){if(this._state.error!==null)this.updateState({error:null})}stampDiff(t){this.hunkTimes.stamp(t)}loadGitignores(){let t=new Map,e=is();e.add(".git");let n=M.join(this.repoPath,".gitignore");if(W.existsSync(n))e.add(W.readFileSync(n,"utf-8"));let r=M.join(this.repoPath,".git","info","exclude");if(W.existsSync(r))e.add(W.readFileSync(r,"utf-8"));t.set("",e);try{let s=aa("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:j()});for(let o of s.split("\x00")){if(!o||o===".gitignore")continue;if(!o.endsWith(".gitignore"))continue;let i=M.dirname(o),a=M.join(this.repoPath,o);try{let c=W.readFileSync(a,"utf-8"),l=is();l.add(c),t.set(i,l)}catch(c){ae(`Failed to read ${a}: ${c instanceof Error?c.message:c}`)}}}catch{}return t}startWatching(){let t=qr(this.repoPath);if(t===null)return;let e=M.join(t.gitDir,"index"),n=M.join(t.gitDir,"HEAD"),r=M.join(t.commonDir,"refs"),s=M.join(t.commonDir,"packed-refs"),o=M.join(this.repoPath,".gitignore");this.gitWatcher=os([e,n,r,s,o],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=os(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(a,c)=>{let l=M.relative(this.repoPath,a);if(!l)return!1;let u=l.split("/");for(let f=0;f<u.length;f++){let h=f===0?"":u.slice(0,f).join("/"),p=this.ignorers.get(h);if(p){let w=f===0?l:u.slice(f).join("/");if(p.ignores(w))return!0}}return le(a,c)},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let i=()=>this.scheduleRefresh();this.gitWatcher.on("change",(a)=>{if(a===o)this.ignorers=this.loadGitignores();i()}),this.gitWatcher.on("add",i),this.gitWatcher.on("unlink",i),this.gitWatcher.on("error",(a)=>{let c=a instanceof Error?a.message:String(a);this.setError(`Git watcher error: ${c}`)}),this.workingDirWatcher.on("change",i),this.workingDirWatcher.on("add",i),this.workingDirWatcher.on("unlink",i),this.workingDirWatcher.on("error",(a)=>{let c=a instanceof Error?a.message:String(a);this.setError(`Working dir watcher error: ${c}`)})}dispose(){this.gitWatcher?.close(),this.workingDirWatcher?.close()}statMtimes(t){let e=new Map;for(let n of t.files){if(e.has(n.path))continue;try{e.set(n.path,W.statSync(M.join(this.repoPath,n.path)).mtimeMs)}catch{}}return e}pendingRefreshKind=null;scheduleRefresh(){this.requestRefresh("full")}scheduleStatusRefresh(){this.requestRefresh("status")}requestRefresh(t){if(this.pendingRefreshKind!==null){if(t==="full")this.pendingRefreshKind="full";return}if(this.queue.hasPendingMutations())return;this.pendingRefreshKind=t,this.queue.scheduleRefresh(async()=>{let e=this.pendingRefreshKind??"full";if(this.pendingRefreshKind=null,e==="full")await this.doRefresh();else await this.doStatusRefresh()})}async doStatusRefresh(){try{let t=await ze(this.repoPath);if(!t.isRepo){this.updateState({status:t,isLoading:!1,error:"Not a git repository"});return}this.updateState({status:t,mtimes:this.statMtimes(t),isLoading:!1})}catch(t){this.updateState({isLoading:!1,error:t instanceof Error?t.message:"Unknown error"})}}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.updateState({isLoading:!0,error:null});let t=Date.now(),e=await ge(this.repoPath).catch(()=>null);try{let n=await ze(this.repoPath);if(!n.isRepo){this.updateState({status:n,isLoading:!1,error:"Not a git repository"});return}let[r,s,o,i,a]=await Promise.all([Dt(this.repoPath,void 0,!1),Dt(this.repoPath,void 0,!0),he(this.repoPath),Z(this.repoPath),this.gatherJournalInputs(n,e,t)]),c={unstaged:fe(ut(r.lines)),staged:fe(ut(s.lines))};this.hunkTimes.stamp(r),this.hunkTimes.stamp(s),this.hunkTimes.prune(new Set(n.files.map((u)=>u.path)));let l=this.statMtimes(n);if(this.updateState({status:n,hunkCounts:c,stashList:o,operationInProgress:i,mtimes:l,isLoading:!1}),a!==null)this.emit("journal-observation",{status:n,headDiff:a.headDiff,headOid:a.headOid,stashCount:a.stashCount,operationInProgress:a.operationInProgress,mtimes:a.mtimes,at:Date.now()})}catch(n){this.updateState({isLoading:!1,error:n instanceof Error?n.message:"Unknown error"})}}async snapshotJournalGuard(t){let[e,n]=await Promise.all([Z(this.repoPath),he(this.repoPath)]);return{operation:e,stashCount:n.length,mtimes:this.statMtimes(t)}}static journalGuardMoved(t,e){if(t.operation!==e.operation||t.stashCount!==e.stashCount)return!0;if(t.mtimes.size!==e.mtimes.size)return!0;for(let[n,r]of t.mtimes)if(e.mtimes.get(n)!==r)return!0;return!1}sectionWrittenDuringGather(t,e,n){let r=new Set(e);for(let s of t.files)if(s.status==="untracked")r.add(s.path);for(let s of r)try{let o=W.statSync(M.join(this.repoPath,s));if(Math.floor(o.mtimeMs)>n)return!0}catch{}return!1}async gatherJournalInputs(t,e,n){if(e===null)return null;try{let r=await this.snapshotJournalGuard(t),s=await Lr(this.repoPath),o=new Set(ve(s).keys()),i=[...s.lines];await this.appendUntrackedSections(t,o,i);let a=await ge(this.repoPath);if(e!==a)return null;let c=await this.snapshotJournalGuard(t);if(xe.journalGuardMoved(r,c))return null;if(this.sectionWrittenDuringGather(t,o,n))return null;return{headDiff:{lines:i},headOid:a,stashCount:c.stashCount,operationInProgress:c.operation,mtimes:c.mtimes}}catch{return null}}async appendUntrackedSections(t,e,n){let r=new Set;for(let s of t.files){if(s.status!=="untracked"||r.has(s.path)||e.has(s.path))continue;r.add(s.path);let o;try{o=W.statSync(M.join(this.repoPath,s.path))}catch{continue}if(!o.isFile())continue;if(o.size>la){this.appendOversizeSection(s.path,o,n);continue}let i=await pt(this.repoPath,s.path);if(i.lines.length===0)continue;n.push(...i.lines)}}appendOversizeSection(t,e,n){let r=[`diff --git a/${t} b/${t}`,"new file mode 100644",`${Ee} size=${e.size} mtime=${Math.round(e.mtimeMs)}`];n.push(...r.map((s)=>({type:"header",content:s})))}async stage(t){try{await this.queue.enqueueMutation(()=>lr(this.repoPath,t.path)),this.scheduleStatusRefresh()}catch(e){await this.refresh(),this.updateState({error:`Failed to stage ${t.path}: ${e instanceof Error?e.message:String(e)}`})}}async unstage(t){try{await this.queue.enqueueMutation(()=>ur(this.repoPath,t.path)),this.scheduleStatusRefresh()}catch(e){await this.refresh(),this.updateState({error:`Failed to unstage ${t.path}: ${e instanceof Error?e.message:String(e)}`})}}async stageHunk(t){try{await this.queue.enqueueMutation(async()=>wr(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.updateState({error:`Failed to stage hunk: ${e instanceof Error?e.message:String(e)}`})}}async unstageHunk(t){try{await this.queue.enqueueMutation(async()=>yr(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.updateState({error:`Failed to unstage hunk: ${e instanceof Error?e.message:String(e)}`})}}async discard(t){if(t.staged)return;let e=t.status==="untracked"?()=>dr(this.repoPath,t.path):()=>pr(this.repoPath,t.path);try{await this.queue.enqueueMutation(e),await this.refresh()}catch(n){this.updateState({error:`Failed to discard ${t.path}: ${n instanceof Error?n.message:String(n)}`})}}async stageAll(){try{await this.queue.enqueueMutation(()=>fr(this.repoPath)),await this.refresh()}catch(t){this.updateState({error:`Failed to stage all: ${t instanceof Error?t.message:String(t)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>hr(this.repoPath)),await this.refresh()}catch(t){this.updateState({error:`Failed to unstage all: ${t instanceof Error?t.message:String(t)}`})}}async commit(t,e=!1){try{await this.queue.enqueue(()=>mr(this.repoPath,t,e)),await this.refresh()}catch(n){this.updateState({error:`Failed to commit: ${n instanceof Error?n.message:String(n)}`})}}async loadStashList(){try{let t=await this.queue.enqueue(()=>he(this.repoPath));this.updateState({stashList:t})}catch{}}}import{EventEmitter as ua}from"node:events";class sn extends ua{repoPath;queue;callbacks;_remoteState={operation:null,inProgress:!1,error:null,lastResult:null};constructor(t,e,n){super();this.repoPath=t,this.queue=e,this.callbacks=n}get remoteState(){return this._remoteState}updateRemoteState(t){this._remoteState={...this._remoteState,...t},this.emit("remote-state-change",this._remoteState)}async runRemoteOperation(t,e){this.updateRemoteState({operation:t,inProgress:!0,error:null,lastResult:null});try{let n=await this.queue.enqueue(e);this.updateRemoteState({inProgress:!1,lastResult:n}),this.callbacks.scheduleRefresh()}catch(n){let r=n instanceof Error?n.message:String(n);this.updateRemoteState({inProgress:!1,error:r})}return this._remoteState}clearRemoteState(){this.updateRemoteState({operation:null,error:null,lastResult:null})}async push(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("push",()=>br(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>Sr(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>vr(this.repoPath))}async stash(t){if(this._remoteState.inProgress)return null;let e=await this.runRemoteOperation("stash",()=>kr(this.repoPath,t));return await this.callbacks.loadStashList(),e}async stashPop(t=0){if(this._remoteState.inProgress)return null;let e=await this.runRemoteOperation("stashPop",()=>Rr(this.repoPath,t));return await this.callbacks.loadStashList(),e}async getLocalBranches(){return this.queue.enqueue(()=>pe(this.repoPath))}async switchBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>_r(this.repoPath,t))}async createBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>Ir(this.repoPath,t))}async softReset(t=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>Ar(this.repoPath,t))}async cherryPick(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>Dr(this.repoPath,t))}async revertCommit(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>Pr(this.repoPath,t))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>Mr(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>Fr(this.repoPath))}}import{EventEmitter as fa}from"node:events";import{randomBytes as ha}from"node:crypto";var pa=262144,da=500,ma=16777216,ls=Number.MAX_SAFE_INTEGER,ga=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function wa(t){let e=ga.exec(t);if(!e)return null;return{oldStart:parseInt(e[1],10),oldCount:e[2]!==void 0?parseInt(e[2],10):1}}function ya(t,e){let n=wa(e);if(!n)return[];let r=n.oldCount===0?n.oldStart+1:n.oldStart,s=[],o=null;for(let i of t){let a=i.content[0];if(a==="\\")continue;if(a==="-")o=ba(o,r),r++;else if(a==="+")o=o??{hasDel:!1,delStart:0,delEnd:0,anchor:r-1};else as(s,o),o=null,r++}return as(s,o),s}function ba(t,e){if(!t)return{hasDel:!0,delStart:e,delEnd:e,anchor:e-1};if(!t.hasDel)t.hasDel=!0,t.delStart=e;return t.delEnd=e,t}function as(t,e){if(!e)return;t.push(e.hasDel?[2*e.delStart,2*e.delEnd]:[2*e.anchor,2*e.anchor+2])}function on(t){if(t.length===0)return{start:0,count:0};let e=1/0,n=-1/0;for(let[o,i]of t){if(o<e)e=o;if(i>n)n=i}if(n>=ls)return{start:0,count:0};let r=Math.ceil(e/2),s=Math.floor(n/2);return{start:r,count:s-r+1}}function Sa(t){let e=[],n=null,r=[],s=null;for(let i of t.lines)if(i.type==="hunk")s={header:i,body:[]},r.push(s);else if(s)s.body.push(i);else if(e.push(i),i.content.startsWith("rename from "))n=i.content.slice(12);if(r.length===0){let i=e.some((a)=>a.content.startsWith(Ee));return{hunks:[{runs:[[0,ls]],bodyHash:we([ut(t.lines)]),ins:0,del:0,span:{start:0,count:0},diff:t,oversize:i}],renamedFrom:n,hunkless:!0}}return{hunks:r.map(({header:i,body:a})=>{let c=ya(a,i.content),l=[],u=0,f=0;for(let p of a){let w=p.content[0];if(w==="\\")continue;if(w==="+")u++,l.push(p.content);else if(w==="-")f++,l.push(p.content)}let h=[...e,i,...a];return{runs:c,bodyHash:we(l),ins:u,del:f,span:on(c),diff:{lines:h}}}),renamedFrom:n,hunkless:!1}}function va(t){if(t.oversize===!0)return null;return ue(t.diff.lines)>pa?null:t.diff}function Ea(t,e,n){if(t===0&&e>0)return"shrunk";let r=t+e;if(r>n)return"expanded";if(r<n)return"shrunk";return"edited"}function cs(t,e){let n=[];return t.forEach((r,s)=>{for(let[o,i]of r.runs)n.push({lo:o,hi:i,node:e+s})}),n.sort((r,s)=>r.lo-s.lo),n}function xa(t,e){let n=Array.from({length:t.length+e.length},(c,l)=>l),r=(c)=>{while(n[c]!==c)n[c]=n[n[c]],c=n[c];return c},s=(c,l)=>{let u=r(c),f=r(l);if(u!==f)n[u]=f},o=cs(t,0),i=cs(e,t.length),a=0;for(let c of o){while(a<i.length&&i[a].hi<c.lo)a++;for(let l=a;l<i.length&&i[l].lo<=c.hi;l++)s(c.node,i[l].node)}return n.map((c,l)=>r(l))}function ka(t,e){let n=xa(t,e),r=new Map,s=(o)=>{let i=r.get(o);if(!i)i={prevIdx:[],nextIdx:[],minLo:1/0},r.set(o,i);return i};return t.forEach((o,i)=>{let a=s(n[i]);a.prevIdx.push(i);for(let[c]of o.runs)if(c<a.minLo)a.minLo=c}),e.forEach((o,i)=>{let a=s(n[t.length+i]);a.nextIdx.push(i);for(let[c]of o.runs)if(c<a.minLo)a.minLo=c}),[...r.values()].sort((o,i)=>o.minLo-i.minLo)}function Ra(t,e,n){let r=[],s=e.map(()=>null),o=n;for(let i of ka(t,e)){let a=i.prevIdx.map((f)=>t[f]),c=i.nextIdx.map((f)=>e[f]);if(a.length===1&&c.length===1&&a[0].bodyHash===c[0].bodyHash){let f=c[0];s[i.nextIdx[0]]={seq:a[0].seq,runs:f.runs,bodyHash:f.bodyHash,ins:f.ins,del:f.del};continue}if(c.length===0){for(let f of a)r.push({seq:o++,kind:"reverted",span:on(f.runs),stats:{insertions:0,deletions:0},diff:null,supersedes:[f.seq],siblings:1});continue}let l=a.map((f)=>f.seq),u=a.reduce((f,h)=>f+h.ins+h.del,0);for(let f of i.nextIdx){let h=e[f],p={seq:o++,kind:a.length===0?"created":Ea(h.ins,h.del,u),span:h.span,stats:{insertions:h.ins,deletions:h.del},diff:va(h),supersedes:[...l],siblings:c.length};r.push(p),s[f]={seq:p.seq,runs:h.runs,bodyHash:h.bodyHash,ins:h.ins,del:h.del}}}return{entries:r,nextLive:s.filter((i)=>i!==null)}}function _a(t,e){let n=Array(t.length).fill(!1),r=Array(e.length).fill(null);for(let a=0;a<e.length;a++){let c=t.findIndex((l,u)=>!n[u]&&l.bodyHash===e[a].bodyHash);if(c!==-1)n[c]=!0,r[a]=t[c].seq}for(let a=0;a<e.length;a++){if(r[a]!==null)continue;let c=n.findIndex((l)=>!l);if(c!==-1)n[c]=!0,r[a]=t[c].seq}let s=t[t.length-1].seq,o=e.map((a,c)=>({seq:r[c]??s,runs:a.runs,bodyHash:a.bodyHash,ins:a.ins,del:a.del})),i=t.filter((a,c)=>!n[c]).map((a)=>a.seq);return{carried:o,retired:i}}function ke(){return{entries:[],epoch:`${Date.now().toString(36)}-${ha(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class an extends fa{store;constructor(t){super();this.store=t}get journalStore(){return this.store}observe(t){try{this.doObserve(t)}catch(e){ae(`Journal observation skipped: ${e instanceof Error?e.message:String(e)}`)}}doObserve(t){let e=[];if(this.store.lastHeadOid===null){if(t.operationInProgress===null)this.seed(t,e)}else if(this.handleOperations(t,e));else if(t.headOid!==this.store.lastHeadOid)this.rebaseline(t,e);else this.classify(t,e);if(e.length>0)this.store.entries.push(...e),this.emit("append",e),this.pruneStore()}pruneStore(){let t=new Set;for(let e of this.store.live.values())for(let n of e)t.add(n.seq);this.pruneBodies(t),this.pruneEntries(t)}pruneBodies(t){let e=0;for(let n of this.store.entries)if(n.type==="hunk"&&n.diff!==null)e+=ue(n.diff.lines);for(let n of this.store.entries){if(e<=ma)return;if(n.type!=="hunk"||n.diff===null||t.has(n.seq))continue;e-=ue(n.diff.lines),n.diff=null}}pruneEntries(t){let e=this.store.entries,n=0;while(e.length-n>da&&(e[n].type==="boundary"||!t.has(e[n].seq)))n++;if(n>0)e.splice(0,n)}handleOperations(t,e){let n=this.store.lastOperation;if(t.operationInProgress!==null){if(n===null)e.push(this.boundary("op-start",t.operationInProgress,[],t.at)),this.store.lastOperation=t.operationInProgress;return!0}if(n!==null)e.push(this.boundary("op-end",n,[],t.at)),this.store.lastOperation=null;return!1}seed(t,e){e.push(this.boundary("journal-start",t.status.branch.current,[],t.at));let{files:n}=this.parseObservation(t),r=[...n.keys()].sort((s,o)=>this.tsFor(t,s)-this.tsFor(t,o));for(let s of r)this.classifyPath(s,[],n.get(s).hunks,t,!0,e);this.store.lastHeadOid=t.headOid,this.store.lastBranch=t.status.branch.current,this.store.lastStashCount=t.stashCount,this.store.lastOperation=null}rebaseline(t,e){let{files:n,deferred:r}=this.parseObservation(t),s=t.status.branch.current===this.store.lastBranch,o=s?"commit":"checkout",i=s?t.headOid.slice(0,7):t.status.branch.current,{resolves:a,newLive:c}=this.carrySurvivors(n,r);e.push(this.boundary(o,i,a,t.at)),this.store.live=c;for(let[l,{hunks:u}]of n){if(c.has(l))continue;this.classifyPath(l,[],u,t,!1,e)}this.store.lastHeadOid=t.headOid,this.store.lastBranch=t.status.branch.current,this.store.lastStashCount=t.stashCount}carrySurvivors(t,e){let n=[],r=new Map;for(let[s,o]of this.store.live){if(e.has(s)){r.set(s,o);continue}let i=t.get(s);if(!i){n.push(...o.map((l)=>l.seq));continue}let{carried:a,retired:c}=_a(o,i.hunks);n.push(...c),r.set(s,a)}return{resolves:n,newLive:r}}classify(t,e){let{files:n,deferred:r}=this.parseObservation(t);this.handleRenames(t,n,e),this.handleDisappearances(t,n,r,e);for(let[s,{hunks:o,renamedFrom:i,hunkless:a}]of n){let c=this.store.live.get(s)??[];if(a&&i!==null&&c.length>0)continue;this.classifyPath(s,c,o,t,!1,e)}this.store.lastBranch=t.status.branch.current,this.store.lastStashCount=t.stashCount}handleRenames(t,e,n){for(let[r,s]of e){let o=s.renamedFrom;if(o===null||o===r)continue;if(!this.store.live.has(o)||e.has(o))continue;let i=(this.store.live.get(r)??[]).map((a)=>a.seq);this.store.live.set(r,this.store.live.get(o)),this.store.live.delete(o),n.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor(t,r),path:r,status:"renamed",kind:"renamed",span:{start:0,count:0},stats:{insertions:0,deletions:0},diff:null,supersedes:i,siblings:1,seeded:!1})}}handleDisappearances(t,e,n,r){let s=[...this.store.live.keys()].filter((o)=>!e.has(o)&&!n.has(o));if(s.length===0)return;if(t.stashCount>this.store.lastStashCount){let o=s.flatMap((i)=>this.store.live.get(i).map((a)=>a.seq));r.push(this.boundary("stash","stash",o,t.at));for(let i of s)this.store.live.delete(i);return}for(let o of s){let i=this.store.live.get(o);r.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor(t,o),path:o,status:this.statusOf(t,o),kind:"reverted",span:on(i.flatMap((a)=>a.runs)),stats:{insertions:0,deletions:0},diff:null,supersedes:i.map((a)=>a.seq),siblings:1,seeded:!1}),this.store.live.delete(o)}}classifyPath(t,e,n,r,s,o){let{entries:i,nextLive:a}=Ra(e,n,this.store.nextSeq);this.store.nextSeq+=i.length;let c=this.tsFor(r,t),l=this.statusOf(r,t);for(let u of i){let f={type:"hunk",seq:u.seq,ts:c,path:t,status:l,kind:u.kind==="created"&&l==="renamed"?"renamed":u.kind,span:u.span,stats:u.stats,diff:u.diff,supersedes:u.supersedes,siblings:u.siblings,seeded:s};o.push(f)}if(a.length>0)this.store.live.set(t,a);else this.store.live.delete(t)}parseObservation(t){let e=new Map;for(let[r,s]of ve(t.headDiff))e.set(r,Sa(s));let n=new Set;for(let r of t.status.files)if(r.status==="untracked"&&!e.has(r.path))n.add(r.path);return{files:e,deferred:n}}boundary(t,e,n,r){return{type:"boundary",seq:this.store.nextSeq++,ts:r,kind:t,label:e,resolves:n}}tsFor(t,e){let n=t.mtimes?.get(e);return n===void 0?t.at:Math.min(n,t.at)}statusOf(t,e){return t.status.files.find((n)=>n.path===e)?.status??"modified"}}class cn{workingTree;remote;journal;repoPath;constructor(t,e){this.repoPath=t;let n=Vn(t);this.workingTree=new xe(t,n),this.remote=new sn(t,n,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new an(e??ke()),this.workingTree.on("journal-observation",(r)=>this.journal.observe(r))}dispose(){this.workingTree.dispose(),Qn(this.repoPath)}}function Aa(t){return Ia("sha256").update(t).digest("hex").slice(0,12)}var Da=32;class us{cap;stores=new Map;constructor(t=Da){this.cap=t}acquire(t){let e=this.stores.get(t);if(e)this.stores.delete(t);else e=ke();return this.stores.set(t,e),e}prune(t){if(this.stores.size<=this.cap)return;for(let e of this.stores.keys()){if(this.stores.size<=this.cap)return;if(t(e))continue;this.stores.delete(e)}}has(t){return this.stores.has(t)}get size(){return this.stores.size}}class ln{events;byId=new Map;byPath=new Map;journalStores=new us;constructor(t={}){this.events=t}async openRepo(t){let e=await ye(t,{mustExist:!1});if(!e.ok)throw Error(e.reason==="not-absolute"?`Repo path must be absolute: ${e.requested}`:`Not a git repository: ${e.requested}`);let n=e.root,r=this.byPath.get(n);if(r)return r.refCount++,{handle:r,created:!1};let s=Aa(n),o=new cn(n,this.journalStores.acquire(s));o.workingTree.startWatching();let i={id:s,path:n,manager:o,refCount:1};return this.byId.set(i.id,i),this.byPath.set(n,i),this.journalStores.prune((a)=>this.byId.has(a)),this.events.onOpened?.(i),{handle:i,created:!0}}getRepo(t){return this.byId.get(t)}listRepos(){return[...this.byId.values()]}closeRepo(t){let e=this.byId.get(t);if(!e)return!1;if(e.refCount--,e.refCount>0)return!1;return this.byId.delete(e.id),this.byPath.delete(e.path),e.manager.dispose(),this.events.onClosed?.(e.id),!0}disposeAll(){for(let t of this.byId.values())t.manager.dispose();this.byId.clear(),this.byPath.clear()}}async function Re(t,e){let n=await t.openRepo(e);if(n.created)n.handle.manager.workingTree.refresh().catch(()=>{});return n}var fs=25000;function Vt(t,e,n){t.write(`event: ${e}
33
33
  data: ${n}
34
34
 
35
- `)}class un{channels=new Map;subscribe(t,e,n,r){r.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});let s=this.channels.get(t);if(!s){let i=new Set,a={manager:e,subscribers:i,listener:(c)=>{let l=JSON.stringify(st(c));if(l===a.lastData)return;a.lastData=l;for(let u of i)Vt(u,"state-change",l)},journalListener:(c)=>{let l=JSON.stringify({epoch:e.journal.journalStore.epoch,entries:He(c)});for(let u of i)Vt(u,"journal-append",l)},keepAlive:setInterval(()=>{for(let c of i)c.write(`: ping
35
+ `)}class un{channels=new Map;subscribe(t,e,n,r){r.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});let s=this.channels.get(t);if(!s){let i=new Set,a={manager:e,subscribers:i,listener:(c)=>{let l=JSON.stringify(st(c));if(l===a.lastData)return;a.lastData=l;for(let u of i)Vt(u,"state-change",l)},journalListener:(c)=>{let l=JSON.stringify({epoch:e.journal.journalStore.epoch,entries:Ue(c)});for(let u of i)Vt(u,"journal-append",l)},keepAlive:setInterval(()=>{for(let c of i)c.write(`: ping
36
36
 
37
- `)},hs),lastData:null};e.workingTree.on("state-change",a.listener),e.journal.on("append",a.journalListener),a.keepAlive.unref(),s=a,this.channels.set(t,s)}s.subscribers.add(r),n.on("close",()=>this.unsubscribe(t,r));let o=JSON.stringify(st(e.workingTree.state));Vt(r,"snapshot",o)}unsubscribe(t,e){let n=this.channels.get(t);if(!n)return;if(n.subscribers.delete(e),n.subscribers.size===0)this.teardown(t,n)}teardown(t,e){e.manager.workingTree.off("state-change",e.listener),e.manager.journal.off("append",e.journalListener),clearInterval(e.keepAlive);for(let n of e.subscribers)n.end();e.subscribers.clear(),this.channels.delete(t)}closeRepo(t){let e=this.channels.get(t);if(e)this.teardown(t,e)}destroy(){for(let[t,e]of this.channels)this.teardown(t,e)}}class fn{subscribers=new Set;keepAlive=null;subscribe(t,e,n){if(e.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),this.subscribers.add(e),!this.keepAlive)this.keepAlive=setInterval(()=>{for(let r of this.subscribers)r.write(`: ping
37
+ `)},fs),lastData:null};e.workingTree.on("state-change",a.listener),e.journal.on("append",a.journalListener),a.keepAlive.unref(),s=a,this.channels.set(t,s)}s.subscribers.add(r),n.on("close",()=>this.unsubscribe(t,r));let o=JSON.stringify(st(e.workingTree.state));Vt(r,"snapshot",o)}unsubscribe(t,e){let n=this.channels.get(t);if(!n)return;if(n.subscribers.delete(e),n.subscribers.size===0)this.teardown(t,n)}teardown(t,e){e.manager.workingTree.off("state-change",e.listener),e.manager.journal.off("append",e.journalListener),clearInterval(e.keepAlive);for(let n of e.subscribers)n.end();e.subscribers.clear(),this.channels.delete(t)}closeRepo(t){let e=this.channels.get(t);if(e)this.teardown(t,e)}destroy(){for(let[t,e]of this.channels)this.teardown(t,e)}}class fn{subscribers=new Set;keepAlive=null;subscribe(t,e,n){if(e.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),this.subscribers.add(e),!this.keepAlive)this.keepAlive=setInterval(()=>{for(let r of this.subscribers)r.write(`: ping
38
38
 
39
- `)},hs),this.keepAlive.unref();t.on("close",()=>{if(this.subscribers.delete(e),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),Vt(e,"snapshot",JSON.stringify(n))}broadcast(t,e){let n=JSON.stringify(e);for(let r of this.subscribers)Vt(r,t,n)}destroy(){if(this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null;for(let t of this.subscribers)t.end();this.subscribers.clear()}}import*as pt from"node:fs";import*as Re from"node:path";import{watch as xa}from"chokidar";import{EventEmitter as ka}from"node:events";class hn extends ka{targetFile;debug;watcher=null;debounceTimer=null;lastReadPath=null;_state={path:null,lastUpdate:null,rawContent:null,sourceFile:null};constructor(t,e=!1){super();this.targetFile=t,this.debug=e,this._state.sourceFile=t}get state(){return this._state}updateState(t){this._state={...this._state,...t},this.emit("path-change",this._state)}processContent(t){if(!t)return null;let e=z(t);return Re.isAbsolute(e)?e:Re.resolve(e)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let t=pt.readFileSync(this.targetFile,"utf-8"),e=Ce(t);if(e&&e!==this.lastReadPath){let n=this.processContent(e),r=new Date;if(this.debug&&n)process.stderr.write(`[diffstalker ${r.toISOString()}] Path change detected
39
+ `)},fs),this.keepAlive.unref();t.on("close",()=>{if(this.subscribers.delete(e),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),Vt(e,"snapshot",JSON.stringify(n))}broadcast(t,e){let n=JSON.stringify(e);for(let r of this.subscribers)Vt(r,t,n)}destroy(){if(this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null;for(let t of this.subscribers)t.end();this.subscribers.clear()}}import*as dt from"node:fs";import*as _e from"node:path";import{watch as Pa}from"chokidar";import{EventEmitter as Ma}from"node:events";class hn extends Ma{targetFile;debug;watcher=null;debounceTimer=null;lastReadPath=null;_state={path:null,lastUpdate:null,rawContent:null,sourceFile:null};constructor(t,e=!1){super();this.targetFile=t,this.debug=e,this._state.sourceFile=t}get state(){return this._state}updateState(t){this._state={...this._state,...t},this.emit("path-change",this._state)}processContent(t){if(!t)return null;let e=z(t);return _e.isAbsolute(e)?e:_e.resolve(e)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let t=dt.readFileSync(this.targetFile,"utf-8"),e=Be(t);if(e&&e!==this.lastReadPath){let n=this.processContent(e),r=new Date;if(this.debug&&n)process.stderr.write(`[diffstalker ${r.toISOString()}] Path change detected
40
40
  `),process.stderr.write(` Source file: ${this.targetFile}
41
41
  `),process.stderr.write(` Raw content: "${e}"
42
42
  `),process.stderr.write(` Previous: "${this.lastReadPath??"(none)"}"
43
43
  `),process.stderr.write(` Resolved: "${n}"
44
- `);this.lastReadPath=n,this.updateState({path:n,lastUpdate:r,rawContent:e})}}catch{}}start(){if(Nn(this.targetFile),!pt.existsSync(this.targetFile))pt.writeFileSync(this.targetFile,"");try{let t=pt.readFileSync(this.targetFile,"utf-8"),e=Ce(t);if(e){let n=this.processContent(e),r=new Date;if(this.debug&&n)process.stderr.write(`[diffstalker ${r.toISOString()}] Initial path read
44
+ `);this.lastReadPath=n,this.updateState({path:n,lastUpdate:r,rawContent:e})}}catch{}}start(){if(Ln(this.targetFile),!dt.existsSync(this.targetFile))dt.writeFileSync(this.targetFile,"");try{let t=dt.readFileSync(this.targetFile,"utf-8"),e=Be(t);if(e){let n=this.processContent(e),r=new Date;if(this.debug&&n)process.stderr.write(`[diffstalker ${r.toISOString()}] Initial path read
45
45
  `),process.stderr.write(` Source file: ${this.targetFile}
46
46
  `),process.stderr.write(` Raw content: "${e}"
47
47
  `),process.stderr.write(` Resolved: "${n}"
48
- `);this.lastReadPath=n,this._state={path:n,lastUpdate:r,rawContent:e,sourceFile:this.targetFile}}}catch{}this.watcher=xa(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 ps={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class pn{registry;hub;targetFile;watcher;followedRepoId=null;followedPath=null;disposed=!1;queue=Promise.resolve();constructor(t,e,n){this.registry=t,this.hub=e,this.targetFile=n,this.watcher=new hn(n)}get state(){return{targetFile:this.targetFile,enabled:!0,followedRepoId:this.followedRepoId,followedPath:this.followedPath}}start(){if(this.watcher.on("path-change",(t)=>this.enqueue(t)),this.watcher.start(),this.watcher.state.path)this.enqueue(this.watcher.state)}enqueue(t){this.queue=this.queue.then(()=>this.follow(t)).catch(()=>{})}async follow(t){if(this.disposed||!t.path)return;let e;try{e=await this.registry.openRepo(t.path)}catch{return}if(this.disposed){this.registry.closeRepo(e.handle.id);return}if(e.created)e.handle.manager.workingTree.refresh().catch(()=>{});if(e.handle.id===this.followedRepoId)this.registry.closeRepo(e.handle.id);else{let n=this.followedRepoId;if(this.followedRepoId=e.handle.id,this.followedPath=e.handle.path,n)this.registry.closeRepo(n)}this.hub.broadcast("follow-change",{repoId:e.handle.id,path:t.path,rawContent:t.rawContent})}dispose(){if(this.disposed)return;if(this.disposed=!0,this.watcher.stop(),this.followedRepoId)this.registry.closeRepo(this.followedRepoId),this.followedRepoId=null,this.followedPath=null}}import*as B from"node:fs";import*as Dt from"node:path";function ds(){return{watchRoots:[]}}var dn=16;function Ra(t){let e=t.trim();if(!e)throw Error("Watch directory cannot be empty");let n=z(e);if(!Dt.isAbsolute(n))throw Error(`Watch directory must be absolute: ${t}`);let r=Dt.resolve(n),s;try{s=B.statSync(r)}catch{throw Error(`No such directory: ${r}`)}if(!s.isDirectory())throw Error(`Not a directory: ${r}`);return r}function ms(t){if(t.length>dn)throw Error(`Too many watch directories (max ${dn})`);let e=new Set,n=[];for(let r of t){let s=Ra(r);if(e.has(s))continue;e.add(s),n.push(s)}return n}function _a(t){let e=ds();if(typeof t!=="object"||t===null)return e;let n=t;if(Array.isArray(n.watchRoots))e.watchRoots=n.watchRoots.filter((r)=>typeof r==="string").slice(0,dn);return e}class mn{file;current=ds();constructor(t){this.file=t}get settings(){return this.current}get persisted(){return this.file!==null}load(){if(!this.file)return this.current;let t;try{t=B.readFileSync(this.file,"utf-8")}catch{return this.current}try{this.current=_a(JSON.parse(t))}catch(e){ce(`Ignoring invalid settings file ${this.file}: ${String(e)}`)}return this.current}save(t){if(this.current=t,!this.file)return this.current;B.mkdirSync(Dt.dirname(this.file),{recursive:!0});let e=`${this.file}.${process.pid}.tmp`;try{B.writeFileSync(e,`${JSON.stringify(this.current,null,2)}
49
- `,{mode:384}),B.renameSync(e,this.file)}catch(n){throw B.rmSync(e,{force:!0}),n}return this.current}}import*as bs from"node:path";import{watch as La}from"chokidar";import*as K from"node:fs/promises";import*as N from"node:path";var Aa=2,Ia=500,Da=new Set(["node_modules","vendor","target","dist","build","venv","__pycache__"]);async function gs(t){try{return await K.stat(N.join(t,".git")),!0}catch{return!1}}async function Pa(t){let e=N.join(t,".git"),n;try{n=await K.stat(e)}catch{return null}if(n.isDirectory())return e;try{let r=await K.readFile(e,"utf-8"),s=/^gitdir:\s*(.+)$/m.exec(r);if(!s)return null;let o=s[1].trim(),i=N.isAbsolute(o)?o:N.resolve(t,o);return await K.stat(i),i}catch{return null}}async function Ma(t){let e;try{e=(await K.readFile(N.join(t,"HEAD"),"utf-8")).trim()}catch{return null}let n=/^ref:\s*refs\/heads\/(.+)$/.exec(e);if(n)return n[1].trim();if(/^[0-9a-f]{40}$/i.test(e))return e.slice(0,7);return null}async function Fa(t){let n=(await Promise.all(["index","HEAD"].map(async(r)=>{try{return(await K.stat(N.join(t,r))).mtimeMs}catch{return null}}))).filter((r)=>r!==null);return n.length===0?null:Math.max(...n)}async function Ta(t){let e=await Pa(t);if(e===null)return null;let[n,r]=await Promise.all([Ma(e),Fa(e)]);return{path:t,name:N.basename(t),branch:n,lastActivity:r}}function Oa(t){if(!t.isDirectory())return!1;if(t.name.startsWith("."))return!1;return!Da.has(t.name)}async function ws(t){let e=await gn(t);return Promise.all(e.map(async(n)=>({name:N.basename(n),path:n,isRepo:await gs(n)})))}async function gn(t){return(await K.readdir(t,{withFileTypes:!0})).filter(Oa).map((n)=>N.join(t,n.name)).sort()}async function $a(t,e,n){let r=[],s=[];for(let o of t){if(r.length>=n)return{repos:r,next:s,capped:!0};if(await gs(o)){r.push(o);continue}if(!e)continue;try{s.push(...await gn(o))}catch{}}return{repos:r,next:s,capped:!1}}async function ys(t,e={}){let n=e.depth??Aa,r=e.limit??Ia,s=await gn(t),o=[],i=!1;for(let c=1;c<=n&&s.length>0&&!i;c++){let l=await $a(s,c<n,r-o.length);o.push(...l.repos),i=l.capped,s=l.next.sort()}return{repos:(await Promise.all(o.map(Ta))).filter((c)=>c!==null),capped:i}}var Na=300;function Ca(t,e){let n=bs.basename(t);if(n.startsWith(".")&&n!==".")return!0;if(n==="node_modules")return!0;return le(t,e)}class wn{hub;roots=new Map;disposed=!1;constructor(t){this.hub=t}get state(){return{roots:[...this.roots.values()].map((t)=>t.state)}}async setRoots(t){if(this.disposed)return;for(let[r,s]of this.roots)if(!t.includes(r))this.teardown(s),this.roots.delete(r);let e=[],n=new Map;for(let r of t){let s=this.roots.get(r);if(s){n.set(r,s);continue}n.set(r,{state:{path:r,repos:[],error:null,capped:!1},watcher:null,timer:null}),e.push(r)}this.roots=n,await Promise.all(e.map((r)=>this.scan(r)));for(let r of e)this.startWatching(r);this.broadcast()}async rescan(){return await Promise.all([...this.roots.keys()].map((t)=>this.scan(t))),this.broadcast(),this.state}dispose(){this.disposed=!0;for(let t of this.roots.values())this.teardown(t);this.roots.clear()}teardown(t){if(t.timer)clearTimeout(t.timer);t.timer=null,t.watcher?.close(),t.watcher=null}async scan(t){let e=this.roots.get(t);if(!e)return;try{let n=await ys(t);e.state={path:t,repos:n.repos,error:null,capped:n.capped}}catch(n){e.state={path:t,repos:[],error:n instanceof Error?n.message:String(n),capped:!1}}}startWatching(t){let e=this.roots.get(t);if(!e||e.watcher)return;let n=La(t,{persistent:!0,ignoreInitial:!0,depth:1,ignored:Ca});n.on("error",(r)=>{e.state={...e.state,error:r instanceof Error?r.message:String(r)},this.broadcast()}),n.on("addDir",()=>this.scheduleRescan(t)),n.on("unlinkDir",()=>this.scheduleRescan(t)),e.watcher=n}scheduleRescan(t){let e=this.roots.get(t);if(!e)return;if(e.timer)clearTimeout(e.timer);e.timer=setTimeout(()=>{e.timer=null,this.scan(t).then(()=>this.broadcast())},Na),e.timer.unref?.()}broadcast(){if(this.disposed)return;this.hub.broadcast("discovery-change",this.state)}}import*as xs from"node:fs";import{execFile as Ba}from"node:child_process";import*as at from"node:fs";import*as et from"node:path";import{fileURLToPath as Ha}from"node:url";var Ss={method:"unknown",package:null,command:null},Qt="diffstalkerd",Ga=3000,Ua=["paru","yay"],ja=[{method:"bun",pattern:/\/install\/global\/node_modules\/diffstalkerd$/,command:`bun add -g ${Qt}`},{method:"pnpm",pattern:/\/pnpm\/global\/\d+\/node_modules\/diffstalkerd$/,command:`pnpm add -g ${Qt}`},{method:"yarn",pattern:/\/yarn\/global\/node_modules\/diffstalkerd$/,command:`yarn global add ${Qt}`},{method:"npm",pattern:/\/lib\/node_modules\/diffstalkerd$/,command:`npm install -g ${Qt}`}];async function Wa(t,e){let n=t.split(et.sep).join("/").replace(/\/+$/,"");for(let s of ja){if(!s.pattern.test(n))continue;let o=e.writable(t)?"":"sudo ";return{method:s.method,package:Qt,command:`${o}${s.command}`}}let r=await e.pacmanOwner(et.join(t,"package.json"));if(r!==null){let s=e.onPath(Ua);return{method:"pacman",package:r,command:s?`${s} -S ${r}`:`sudo pacman -Syu ${r}`}}return Ss}var qa={onPath(t){let e=(process.env.PATH??"").split(et.delimiter).filter(Boolean);for(let n of t)for(let r of e)try{return at.accessSync(et.join(r,n),at.constants.X_OK),n}catch{}return null},pacmanOwner(t){return new Promise((e)=>{Ba("pacman",["-Qoq","--",t],{timeout:Ga},(n,r)=>{if(n)return e(null);let s=r.trim().split(`
50
- `)[0]?.trim();e(s?s:null)})})},writable(t){try{return at.accessSync(t,at.constants.W_OK),!0}catch{return!1}}};function Xa(){let t=et.dirname(Ha(new URL("../package.json",import.meta.url)));try{return at.realpathSync(t)}catch{return t}}function vs(t=Xa(),e=qa){let n=null;return{info(){return n??=Wa(t,e).catch(()=>Ss),n}}}var za="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",Ja=21600000,Ya=300000,Ka=5000;function yn(){try{let t=xs.readFileSync(new URL("../package.json",import.meta.url),"utf-8"),e=JSON.parse(t);return typeof e.version==="string"?e.version:null}catch{return null}}async function Va(){let t=await fetch(za,{headers:{accept:"application/json"},signal:AbortSignal.timeout(Ka)});if(!t.ok)return null;let e=await t.json();return typeof e.latest==="string"?e.latest:null}function Es(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());if(!e)return null;return[Number(e[1]),Number(e[2]),Number(e[3])]}function Qa(t,e){if(t===null||e===null)return"unknown";let n=Es(t),r=Es(e);if(!n||!r)return"unknown";for(let s=0;s<n.length;s++){if(n[s]<r[s])return"outdated";if(n[s]>r[s])return"ahead"}return"current"}function ks(t=Va,e=yn(),n=vs()){let r=null,s=null;function o(){if(r&&Date.now()<r.expiresAt)return Promise.resolve(r.value);if(s)return s;return s=t().catch(()=>null).then((i)=>{let a=i===null?Ya:Ja;return r={value:i,expiresAt:Date.now()+a},s=null,i}),s}return{async state(){let[i,a]=await Promise.all([o(),n.info()]);return{current:e,latest:i,status:Qa(e,i),install:a}}}}import*as Rs from"node:os";function _s(t,e){t.get("/health",({res:n})=>{k(n,200,{ok:!0,ready:!0,home:Rs.homedir(),http:{port:e.httpPort()},symbols:{extensions:e.symbols?.extensions??[]}})})}function As(t,e){t.get("/version",async({res:n})=>{k(n,200,await e.version.state())})}import*as Zt from"node:fs";import*as F from"node:path";function _(t,e){let n=t.getRepo(e);if(!n)throw new d(404,`Unknown repo id: ${e}`);return n}function H(t,e,n){if(typeof t!=="object"||t===null)throw new d(400,`Expected a JSON body with "${e}"`);let r=t[e];if(typeof r!=="string"||!n?.allowEmpty&&r.length===0)throw new d(400,`Missing "${e}" (string) in body`);return r}function dt(t,e){let n=H(t,e);if(n.startsWith("-"))throw new d(400,`Invalid "${e}" (must not start with "-"): ${n}`);return n}function Ds(t,e){if(typeof t!=="object"||t===null)throw new d(400,`Expected a JSON body with "${e}"`);let n=t[e];if(!Array.isArray(n)||n.some((r)=>typeof r!=="string"))throw new d(400,`Missing "${e}" (array of strings) in body`);return n}function Ps(t,e){if(typeof t!=="object"||t===null)return;let n=t[e];if(n===void 0)return;if(typeof n!=="string"||n.length===0)throw new d(400,`Invalid "${e}" (expected a non-empty string)`);return n}function vn(t,e,n){if(typeof t!=="object"||t===null)return n.fallback;let r=t[e];if(r===void 0)return n.fallback;if(typeof r!=="number"||!Number.isInteger(r)||r<n.min)throw new d(400,`Invalid "${e}" (expected an integer >= ${n.min})`);return r}function Ms(t,e){if(typeof t!=="object"||t===null)return!1;let n=t[e];if(n===void 0)return!1;if(typeof n!=="boolean")throw new d(400,`Invalid "${e}" (expected a boolean)`);return n}function G(t,e,n){let r=t.get(e);if(r===null)return n;if(r==="true")return!0;if(r==="false")return!1;throw new d(400,`Invalid "${e}" (expected true or false): ${r}`)}function Fs(t,e,n,r){let s=t.get(e);if(s===null)return n;let o=Number(s);if(!Number.isInteger(o)||o<1)throw new d(400,`Invalid "${e}" (expected a positive integer): ${s}`);if(r!==void 0&&o>r)throw new d(400,`Invalid "${e}" (must be <= ${r}): ${s}`);return o}async function nt(t){if(!t.state.status)await t.refresh();let e=t.state.status;if(!e)throw new d(500,"Repository status unavailable");return e}function Is(t,e,n){let r=t.files.filter((s)=>s.path===e);if(r.length===0)return null;return r.find((s)=>s.staged===n)??r[0]}async function Pt(t,e,n){let r=await nt(t),s=Is(r,e,n);if(!s)await t.refresh(),r=await nt(t),s=Is(r,e,n);if(!s)throw new d(404,`File not in status: ${e}`);return s}function Sn(t,e){return t===e||t.startsWith(e+F.sep)}function En(t){return t.replace(/[. ]+$/,"").toLowerCase()===".git"}function mt(t,e){if(e.length===0)throw new d(400,"Empty path");if(e.includes("\x00"))throw new d(400,"Path contains a NUL byte");let n=F.resolve(t),r=F.relative(n,F.resolve(n,e));if(r==="")throw new d(400,`Path resolves to the repository root: ${e}`);if(F.isAbsolute(r)||r===".."||r.startsWith(`..${F.sep}`))throw new d(400,`Path escapes repository root: ${e}`);if(r.startsWith("-"))throw new d(400,`Path must not start with "-": ${e}`);if(r.startsWith(":"))throw new d(400,`Path must not start with ":": ${e}`);if(r.split(F.sep).some(En))throw new d(400,`Path addresses the git directory: ${e}`);return r}async function Ts(t){try{return await Zt.promises.realpath(t)}catch{return null}}var bn=new WeakMap;async function Za(t){let e=bn.get(t);if(!e)e=(async()=>{let n=await I(t.path).raw(["rev-parse","--absolute-git-dir"]);return await Zt.promises.realpath(n.trim())})(),bn.set(t,e),e.catch(()=>bn.delete(t));try{return await e}catch{throw new d(500,"Cannot resolve the git directory for this repository")}}async function gt(t,e){let n=await Zt.promises.realpath(F.resolve(t.path)),r=await Ts(F.join(t.path,e));if(r===null)return;if(!Sn(r,n))throw new d(400,`Path escapes repository root: ${e}`);if(Sn(r,await Za(t)))throw new d(400,`Path addresses the git directory: ${e}`)}async function Os(t,e){let n=await Zt.promises.realpath(F.resolve(t)),r=[];for(let s of e){let o=await Ts(F.join(t,s.path));if(o===null||Sn(o,n))r.push(s)}return r}function xn(t){return t?.code??null}function tc(t){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test(t)?409:500}async function rt(t,e,n){t.clearError(),await n();let r=t.state.error;if(r){k(e,tc(r),{error:r});return}await t.refresh(),k(e,200,{state:st(t.state)})}function ec(t){return/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged/i.test(t)?409:500}async function C(t,e,n){let r=t.manager.remote,s=()=>new d(409,`A ${r.remoteState.operation??"remote"} operation is already in progress`);if(r.remoteState.inProgress)throw s();let o=await n();if(o===null)throw s();if(o.error){k(e,ec(o.error),{error:o.error});return}let i=t.manager.workingTree;await i.refresh(),k(e,200,{state:st(i.state),result:o.lastResult})}function $s(t,e){let{registry:n}=e;t.get("/repos",({res:r})=>{let s=n.listRepos().map((o)=>({id:o.id,path:o.path,branch:o.manager.workingTree.state.status?.branch.current??null}));k(r,200,s)}),t.post("/repos",async({body:r,res:s})=>{let o=H(r,"path"),i;try{i=await ke(n,o)}catch(a){throw new d(400,a instanceof Error?a.message:String(a))}k(s,i.created?201:200,{id:i.handle.id,path:i.handle.path})}),t.get("/resolve",async({query:r,res:s})=>{let o=r.get("path");if(!o)throw new d(400,'Missing "path" query parameter');let i=await we(o,{mustExist:!0});if(!i.ok&&i.reason==="not-absolute")throw new d(400,`Repo path must be absolute: ${i.requested}`);k(s,200,{openable:i.ok,root:i.ok?i.root:null})}),t.get("/repos/:id/worktrees",async({params:r,res:s})=>{let o=_(n,r.id);k(s,200,await Ze(o.path))}),t.get("/worktrees",async({query:r,res:s})=>{let o=r.get("path");if(!o)throw new d(400,'Missing "path" query parameter');k(s,200,await Ze(o))}),t.delete("/repos/:id",({params:r,res:s})=>{_(n,r.id),n.closeRepo(r.id),k(s,200,{})})}function Ls(t,e,n){if(!t.trim())return{valid:!1,error:"Commit message cannot be empty"};if(e===0&&!n)return{valid:!1,error:"No changes staged for commit"};return{valid:!0,error:null}}function Ns(t){return t.trim()}async function nc(t){let e=(r)=>r.filter((s)=>s.staged).length,n=e((await nt(t)).files);if(n===0)await t.refresh(),n=e((await nt(t)).files);return n}function Cs(t,e){let{registry:n,sse:r}=e;if(t.get("/repos/:id/status",async({params:s,res:o})=>{let i=_(n,s.id);await nt(i.manager.workingTree);let a=st(i.manager.workingTree.state);a.operationInProgress=await Z(i.path),k(o,200,a)}),t.get("/repos/:id/diff",async({params:s,query:o,res:i})=>{let a=_(n,s.id),c=o.get("path")??void 0,l=G(o,"staged",!1),u=G(o,"whole",!1);if(u&&!c)throw new d(400,"whole=true requires a path (one file at a time)");let f=u?de:void 0,h,p=!1;if(c){let w=(await nt(a.manager.workingTree)).files.some((R)=>R.path===c&&R.status==="untracked");if(w&&l)throw new d(400,`staged=true is meaningless for untracked file: ${c} (untracked files have no staged diff)`);p=u&&!w,h=w?await Jt(a.path,c):await It(a.path,c,l,{context:f})}else h=await It(a.path,void 0,l);if(!p)a.manager.workingTree.stampDiff(h);k(i,200,h)}),t.post("/repos/:id/stage",async({params:s,body:o,res:i})=>{let a=_(n,s.id),c=H(o,"path"),l=a.manager.workingTree,u=await Pt(l,c,!1);await rt(l,i,()=>l.stage(u))}),t.post("/repos/:id/unstage",async({params:s,body:o,res:i})=>{let a=_(n,s.id),c=H(o,"path"),l=a.manager.workingTree,u=await Pt(l,c,!0);await rt(l,i,()=>l.unstage(u))}),t.get("/repos/:id/events",({params:s,req:o,res:i})=>{let a=_(n,s.id);r.subscribe(s.id,a.manager,o,i)}),e.apiMode==="full")rc(t,e)}function rc(t,e){let{registry:n}=e;t.post("/repos/:id/stage-all",async({params:r,res:s})=>{let i=_(n,r.id).manager.workingTree;await rt(i,s,()=>i.stageAll())}),t.post("/repos/:id/unstage-all",async({params:r,res:s})=>{let i=_(n,r.id).manager.workingTree;await rt(i,s,()=>i.unstageAll())}),t.post("/repos/:id/discard",async({params:r,body:s,res:o})=>{let i=_(n,r.id),a=H(s,"path"),c=i.manager.workingTree,l=await Pt(c,a,!1);if(l.staged)throw new d(409,`Cannot discard a staged file: ${a} (unstage it first)`);await rt(c,o,()=>c.discard(l))}),t.post("/repos/:id/commit",async({params:r,body:s,res:o})=>{let i=_(n,r.id),a=H(s,"message",{allowEmpty:!0}),c=Ms(s,"amend"),l=i.manager.workingTree,u=await nc(l),f=Ls(a,u,c);if(!f.valid)throw new d(400,f.error??"Invalid commit");await rt(l,o,()=>l.commit(Ns(a),c))}),t.post("/repos/:id/stage-hunk",async({params:r,body:s,res:o})=>{let i=_(n,r.id),a=H(s,"patch"),c=i.manager.workingTree;await rt(c,o,()=>c.stageHunk(a))}),t.post("/repos/:id/unstage-hunk",async({params:r,body:s,res:o})=>{let i=_(n,r.id),a=H(s,"patch"),c=i.manager.workingTree;await rt(c,o,()=>c.unstageHunk(a))})}async function sc(t){let e=await Ye(t);if(e&&await it(t,e))return e;if(kt(t)){let n=await Yt(t);if(n&&await it(t,n))return n}throw new d(422,"No usable base branch")}async function kn(t,e){let n=e.get("base");if(n===null)return sc(t);if(!await it(t,n))throw new d(400,`Unknown base ref: ${n}`);return n}function Bs(t){return t?{context:de}:{}}function Hs(t,e){let{registry:n}=e;if(t.get("/repos/:id/history",async({params:r,query:s,res:o})=>{let i=_(n,r.id),a=Fs(s,"count",100,5000);k(o,200,await Er(i.path,a))}),t.get("/repos/:id/commits/:hash",async({params:r,res:s})=>{let o=_(n,r.id),i=r.hash;if(!/^[0-9a-f]{4,40}$/i.test(i))throw new d(400,`Invalid commit hash: ${i}`);let a=await xr(o.path,i);if(a===null)throw new d(404,`Unknown commit: ${i}`);k(s,200,a)}),t.get("/repos/:id/commits/:hash/diff",async({params:r,query:s,res:o})=>{let i=_(n,r.id),a=r.hash;if(!/^[0-9a-f]{4,40}$/i.test(a))throw new d(400,`Invalid commit hash: ${a}`);if(!await it(i.path,a))throw new d(404,`Unknown commit: ${a}`);let c=s.get("path")??void 0,l=G(s,"whole",!1);if(l&&!c)throw new d(400,"whole=true requires a path (one file at a time)");let u=c?await Ve(i.path,{kind:"commit",hash:a},c,Bs(l)):await Hr(i.path,a);k(o,200,u)}),t.get("/repos/:id/compare/file",async({params:r,query:s,res:o})=>{let i=_(n,r.id),a=s.get("path");if(!a)throw new d(400,"path is required");let c=G(s,"whole",!1),u=G(s,"uncommitted",!1)?{kind:"head"}:{kind:"compare",base:await kn(i.path,s)};k(o,200,await Ve(i.path,u,a,Bs(c)))}),t.get("/repos/:id/head-message",async({params:r,res:s})=>{let o=_(n,r.id);k(s,200,{message:await gr(o.path)})}),t.get("/repos/:id/branches",async({params:r,res:s})=>{let o=_(n,r.id);k(s,200,await pe(o.path))}),t.get("/repos/:id/base-branches",async({params:r,res:s})=>{let o=_(n,r.id);k(s,200,await Je(o.path))}),t.get("/repos/:id/compare/base",async({params:r,res:s})=>{let o=_(n,r.id);k(s,200,{base:await Ye(o.path)})}),e.apiMode==="full")t.put("/repos/:id/compare/base",async({params:r,body:s,res:o})=>{let i=_(n,r.id),a=dt(s,"branch");if(!await it(i.path,a))throw new d(400,`Not a valid base ref: ${a}`);$r(i.path,a),k(o,200,{base:a})});t.get("/repos/:id/compare/count",async({params:r,query:s,res:o})=>{let i=_(n,r.id),a=await kn(i.path,s);try{k(o,200,{baseBranch:a,commits:await Cr(i.path,a)})}catch(c){if(c instanceof _t)throw new d(422,c.message);throw c}}),t.get("/repos/:id/compare",async({params:r,query:s,res:o})=>{let i=_(n,r.id),a=G(s,"uncommitted",!1),c=await kn(i.path,s),l;try{l=a?await Gr(i.path,c):await Ke(i.path,c)}catch(u){if(u instanceof _t)throw new d(422,u.message);throw u}k(o,200,l)})}function oc(t){let e=t.get("since");if(e===null)return 0;if(!/^\d+$/.test(e))throw new d(400,`Invalid "since" (expected a non-negative integer): ${e}`);return Number(e)}function Gs(t,e){let{registry:n}=e;t.get("/repos/:id/journal",({params:r,query:s,res:o})=>{let i=_(n,r.id),a=oc(s);k(o,200,Bn(i.manager.journal.journalStore,a))})}function Us(t,e){let{registry:n}=e;t.post("/repos/:id/push",async({params:r,res:s})=>{let o=_(n,r.id);await C(o,s,()=>o.manager.remote.push())}),t.post("/repos/:id/fetch",async({params:r,res:s})=>{let o=_(n,r.id);await C(o,s,()=>o.manager.remote.fetchRemote())}),t.post("/repos/:id/pull",async({params:r,res:s})=>{let o=_(n,r.id);await C(o,s,()=>o.manager.remote.pullRebase())}),t.post("/repos/:id/stash",async({params:r,body:s,res:o})=>{let i=_(n,r.id),a=Ps(s,"message");await C(i,o,()=>i.manager.remote.stash(a))}),t.post("/repos/:id/stash-pop",async({params:r,body:s,res:o})=>{let i=_(n,r.id),a=vn(s,"index",{min:0,fallback:0});await C(i,o,()=>i.manager.remote.stashPop(a))}),t.post("/repos/:id/switch-branch",async({params:r,body:s,res:o})=>{let i=_(n,r.id),a=dt(s,"name");await C(i,o,()=>i.manager.remote.switchBranch(a))}),t.post("/repos/:id/create-branch",async({params:r,body:s,res:o})=>{let i=_(n,r.id),a=dt(s,"name");await C(i,o,()=>i.manager.remote.createBranch(a))}),t.post("/repos/:id/soft-reset",async({params:r,body:s,res:o})=>{let i=_(n,r.id),a=vn(s,"count",{min:1,fallback:1});if(!await it(i.path,`HEAD~${a}`))throw new d(400,`Cannot soft-reset ${a} commit(s): HEAD~${a} does not exist`);await C(i,o,()=>i.manager.remote.softReset(a))}),t.post("/repos/:id/cherry-pick",async({params:r,body:s,res:o})=>{let i=_(n,r.id),a=dt(s,"hash");await C(i,o,()=>i.manager.remote.cherryPick(a))}),t.post("/repos/:id/revert",async({params:r,body:s,res:o})=>{let i=_(n,r.id),a=dt(s,"hash");await C(i,o,()=>i.manager.remote.revertCommit(a))}),t.post("/repos/:id/abort",async({params:r,res:s})=>{let o=_(n,r.id);if(!await Z(o.path))throw new d(409,"No operation in progress to abort");await C(o,s,()=>o.manager.remote.abortOperation())}),t.post("/repos/:id/rebase-continue",async({params:r,res:s})=>{let o=_(n,r.id);if(await Z(o.path)!=="rebase")throw new d(409,"No rebase in progress to continue");await C(o,s,()=>o.manager.remote.rebaseContinue())})}import*as wt from"node:fs";import*as te from"node:path";var Tt=8388608;var js=65536;function Mt(t){return Array.from(t,(e)=>e.charCodeAt(0))}function Ft(t,e,n){if(e+n.length>t.length)return!1;for(let r=0;r<n.length;r++)if(t[e+r]!==n[r])return!1;return!0}function _e(t,e){return t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function Rn(t,e){return(t[e]<<8)+t[e+1]}function Ae(t,e){return t[e]+(t[e+1]<<8)}function Ws(t,e){return String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3])}function D(t){return{ok:!1,refusal:t}}function Ot(t){return D(t?"malformed":"header-not-found")}function _n(t,e){if(t<1||e<1)return"malformed";if(t>8192||e>8192)return"too-many-pixels";if(t*e>16777216)return"too-many-pixels";return null}var ic=[137,80,78,71,13,10,26,10],ac=[255,216,255],cc=Mt("GIF87a"),lc=Mt("GIF89a"),V=Mt("ftyp");function q(t){return{offset:8,bytes:Mt(t)}}var uc=[{label:"webp",offset:0,bytes:Mt("RIFF"),brand:q("WEBP")},{label:"avif",offset:4,bytes:V,brand:q("avif")},{label:"avis",offset:4,bytes:V,brand:q("avis")},{label:"heic",offset:4,bytes:V,brand:q("heic")},{label:"heix",offset:4,bytes:V,brand:q("heix")},{label:"heim",offset:4,bytes:V,brand:q("heim")},{label:"heis",offset:4,bytes:V,brand:q("heis")},{label:"hevc",offset:4,bytes:V,brand:q("hevc")},{label:"hevx",offset:4,bytes:V,brand:q("hevx")},{label:"mif1",offset:4,bytes:V,brand:q("mif1")},{label:"msf1",offset:4,bytes:V,brand:q("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:Mt("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 fc(t){return uc.some((e)=>Ft(t,e.offset,e.bytes)&&(e.brand===void 0||Ft(t,e.brand.offset,e.brand.bytes)))}var hc={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},pc=26;function dc(t,e,n){if(t.length<pc)return Ot(n);if(_e(t,8)!==13)return D("malformed");if(Ws(t,12)!=="IHDR")return D("malformed");let r=_e(t,16),s=_e(t,20),o=_n(r,s);if(o)return D(o);let i=hc[t[25]];if(!i||!i.includes(t[24]))return D("malformed");let a=mc(t,n);if(a)return a;return{ok:!0,info:{format:"png",mime:"image/png",width:r,height:s,bytes:e}}}function mc(t,e){let n=8;for(let r=0;r<256;r++){if(n+8>t.length)return Ot(e);let s=_e(t,n),o=Ws(t,n+4);if(o==="IDAT")return null;if(o==="acTL")return D("animation");if(o==="iCCP"&&s>65536)return D("malformed");let i=n+12+s;if(i<=n||!Number.isSafeInteger(i))return D("malformed");n=i}return D("malformed")}var gc=218,wc=226,yc=new Set([219,238,192,193,194,196]);function bc(t){return t>=224&&t<=239||yc.has(t)}function Sc(t){return t===1||t>=208&&t<=217}function vc(t){return t>=192&&t<=207&&t!==196&&t!==200&&t!==204}var Ec=new Set([192,193,194]);function xc(t,e,n){if(t.length<4)return Ot(n);if(!bc(t[3]))return D("malformed");return _c(t,e,n)}function kc(t,e,n,r,s){if(!Ec.has(n))return D("malformed");if(e+9>t.length)return Ot(s);let o=Rn(t,e+5),i=Rn(t,e+7),a=_n(i,o);if(a)return D(a);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:i,height:o,bytes:r}}}function Rc(t,e){if(e+1>=t.length)return{kind:"ran-out"};if(t[e]!==255)return{kind:"malformed"};let n=t[e+1];if(n===255)return{kind:"skip",next:e+1};if(Sc(n))return{kind:"skip",next:e+2};if(n===gc)return{kind:"malformed"};if(e+4>t.length)return{kind:"ran-out"};let r=Rn(t,e+2);if(r<2)return{kind:"malformed"};if(vc(n))return{kind:"sof",marker:n};return{kind:"segment",marker:n,length:r}}function _c(t,e,n){let r=2,s=0;for(let o=0;o<1024;o++){let i=Rc(t,r);if(i.kind==="ran-out")return Ot(n);if(i.kind==="malformed")return D("malformed");if(i.kind==="sof")return kc(t,r,i.marker,e,n);if(i.kind==="skip"){r=i.next;continue}if(i.marker===wc){if(s+=i.length-2,s>65536)return D("malformed")}r+=2+i.length}return D("malformed")}var Ac=59,Ic=44,Dc=33;function qs(t){return(t&128)===0?0:3*(1<<(t&7)+1)}function Pc(t,e,n){if(e>2097152)return D("too-large");if(!n)return D("header-not-found");if(t.length<13)return Ot(n);let r=Ae(t,6),s=Ae(t,8),o=_n(r,s);if(o)return D(o);let i={pos:13+qs(t[10]),left:8192,pixels:0,overBudget:!1},a=Mc(t,i);if(a===null)return D("malformed");if(a<1)return D("malformed");if(a>256)return D("too-many-pixels");if(i.overBudget)return D("too-many-pixels");if(a*r*s>33554432)return D("too-many-pixels");let c={format:"gif",mime:"image/gif",width:r,height:s,bytes:e};if(a>1)c.frames=a;return{ok:!0,info:c}}function Mc(t,e){let n=0;while(e.left-- >0){if(e.pos>=t.length)return null;let r=t[e.pos];if(r===Ac)return n;let s=r===Ic;if(!(s?Tc(t,e):Fc(t,e,r)))return null;if(s&&++n>256)return n;if(e.overBudget)return n}return null}function Fc(t,e,n){if(n!==Dc)return!1;return e.pos+=2,Xs(t,e)}function Tc(t,e){if(e.pos+10>t.length)return!1;Oc(e,Ae(t,e.pos+5),Ae(t,e.pos+7));let n=t[e.pos+9];return e.pos+=10+qs(n)+1,Xs(t,e)}function Oc(t,e,n){let r=e*n;if(e>8192||n>8192||r>16777216){t.overBudget=!0;return}if(t.pixels+=r,t.pixels>33554432)t.overBudget=!0}function Xs(t,e){while(e.left-- >0){if(e.pos>=t.length)return!1;let n=t[e.pos];if(e.pos+=1+n,n===0)return e.pos<=t.length}return!1}function zs(t){return Ft(t,0,cc)||Ft(t,0,lc)}function $t(t,e,n){if(e>8388608)return D("too-large");if(Ft(t,0,ic))return dc(t,e,n);if(Ft(t,0,ac))return xc(t,e,n);if(zs(t))return Pc(t,e,n);if(fc(t))return D("unsupported-format");return D("not-an-image")}function Ie(t,e){return zs(t)?Math.min(e,2097152):65536}function An(t){let e={files:new Map,directories:new Set};for(let n of t){e.files.set(n.path,{status:n.status,staged:n.staged});let r=n.path.split("/"),s="";for(let o=0;o<r.length-1;o++)s=s?`${s}/${r[o]}`:r[o],e.directories.add(s);e.directories.add("")}return e}var $c=1048576,Js=5000;class ee extends Error{constructor(t){super(`Not a regular file: ${t}`);this.name="NotRegularFileError"}}async function Ks(t,e,n,r){let s=n?.hideHidden??!0,o=n?.hideGitignored??!0,i=te.join(t,e),a=await wt.promises.readdir(i,{withFileTypes:!0}),c=a.map((f)=>e?te.join(e,f.name):f.name),l=o?await xt(t,c):new Set,u=[];for(let f of a){if(s&&f.name.startsWith("."))continue;let h=e?te.join(e,f.name):f.name;if(o&&l.has(h))continue;let p=f.isDirectory(),g={name:f.name,path:h,type:p?"dir":"file"};if(r)if(p){if(r.directories.has(h))g.hasChanges=!0}else{let w=r.files.get(h);if(w)g.gitStatus=w.status,g.staged=w.staged}u.push(g)}return u.sort((f,h)=>{if(f.type==="dir"&&h.type!=="dir")return-1;if(f.type!=="dir"&&h.type==="dir")return 1;return f.name.localeCompare(h.name)}),u}var Lc=16,Nc=wt.constants.O_RDONLY|(wt.constants.O_NONBLOCK??0);async function In(t,e,n){let r=Buffer.alloc(e),s=0;while(s<e){let{bytesRead:o}=await t.read(r,s,e-s,n+s);if(o===0)break;s+=o}return s===e?r:r.subarray(0,s)}async function Cc(t,e){let n=await In(t,Math.min(Lc,e),0),r=$t(n,e,n.length>=e);if(!r.ok&&r.refusal==="too-large")return{head:n,result:r};let s=Math.min(Ie(n,e),e),o=s<=n.length?n.subarray(0,s):Buffer.concat([n,await In(t,s-n.length,n.length)]);return{head:o,result:$t(o,e,o.length>=e)}}function Bc(t,e){return t.ok?{image:t.info,refusal:null,version:e}:{image:null,refusal:t.refusal,version:e}}function Ys(t,e){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:t,totalLines:0,media:e}}function Dn(t,e){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:t,totalLines:0,media:e}}function Hc(t,e){let n=t.toString("utf-8"),r=n.split(`
51
- `),s=!1;if(r.length>Js)n=r.slice(0,Js).join(`
52
- `),s=!0;return{content:n,binary:!1,truncated:s,tooLarge:!1,size:e,totalLines:r.length}}async function Gc(t,e){let n=await t.stat();if(!n.isFile())throw new ee(e);let r=n.size;if(r>Tt)return Dn(r);let{head:s,result:o}=await Cc(t,r),i=Bc(o,`${r}-${n.mtimeMs}`);if(o.ok)return Ys(r,i);if(r>$c)return Dn(r,zt(s)?i:void 0);let a=s.length>=r?s:Buffer.concat([s,await In(t,r-s.length,s.length)]);return zt(a)?Ys(r,i):Hc(a,r)}async function Vs(t,e){let n=te.join(t,e),r=await wt.promises.stat(n);if(!r.isFile())throw new ee(e);if(r.size>Tt)return Dn(r.size);let s=await wt.promises.open(n,Nc);try{return await Gc(s,e)}finally{await s.close()}}function Qs(t,e){let{registry:n,symbols:r}=e;async function s(o,i,a){if(!a)return o;if(o.binary||o.tooLarge)return o;if(r===null)return{...o,symbols:{status:"unavailable",reason:"error"}};if(!r.pool.supported(i))return{...o,symbols:{status:"unsupported",reason:"language"}};let c=r.gate.acquire();if(c===null)throw new d(503,"Symbol extraction busy");try{return{...o,symbols:await r.pool.extract(i,o.content)}}finally{(await c)()}}t.get("/repos/:id/tree",async({params:o,query:i,res:a})=>{let c=_(n,o.id),l=i.get("dir")??"",u=G(i,"hidden",!1),f=G(i,"ignored",!1),h=l===""?"":mt(c.path,l);await gt(c,h);let p=await nt(c.manager.workingTree),g=An(p.files),w;try{w=await Ks(c.path,h,{hideHidden:!u,hideGitignored:!f},g)}catch(A){let y=xn(A);if(y==="ENOENT")throw new d(404,`No such directory: ${l||"/"}`);if(y==="ENOTDIR")throw new d(400,`Not a directory: ${l}`);throw A}let R=w.filter((A)=>!En(A.name));k(a,200,await Os(c.path,R))}),t.get("/repos/:id/file",async({params:o,query:i,res:a})=>{let c=_(n,o.id),l=i.get("path");if(!l)throw new d(400,'Missing "path" query parameter');let u=mt(c.path,l);await gt(c,u);try{let f=await Vs(c.path,u);k(a,200,await s(f,u,G(i,"symbols",!1)))}catch(f){if(f instanceof ee)throw new d(400,f.message);let h=xn(f);if(h==="ENOENT"||h==="ENOTDIR")throw new d(404,`No such file: ${l}`);throw f}}),t.get("/repos/:id/files",async({params:o,res:i})=>{let a=_(n,o.id);k(i,200,await Tr(a.path))})}import{execFile as Uc}from"node:child_process";import{promisify as jc}from"node:util";var Wc=jc(Uc),De=3,qc=20,Zs=500,Xc=500,zc=4194304,Jc=5000,to=400,Yc=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"];class Pe extends Error{constructor(){super(`Query must be at least ${De} characters`);this.name="GrepQueryTooShortError"}}class Lt extends Error{constructor(t){super(t);this.name="GrepQueryInvalidError"}}var eo={matches:[],capped:!1,incomplete:!1,binarySkipped:0};function Kc(t){return t===t.toLowerCase()}function Pn(t){return Buffer.from(t).toString("utf8")}function Vc(t,e){let n=t.indexOf(0,e);if(n===-1)return null;let r=t.indexOf(0,n+1);if(r===-1)return null;let s=t.indexOf(10,r+1);if(s===-1)s=t.length;return{pathBytes:t.subarray(e,n),lineBytes:t.subarray(n+1,r),contentBytes:t.subarray(r+1,s),next:s+1}}function no(t,e=Xc){let n=[],r=new Map,s=0,o=!1,i=0;while(i<t.length){let a=Vc(t,i);if(a===null)break;if(i=a.next,a.contentBytes.includes(0)){s+=1;continue}let c=Number.parseInt(Pn(a.lineBytes),10);if(!Number.isSafeInteger(c)||c<1)continue;if(n.length>=e){o=!0;break}let l=Pn(a.pathBytes),u=r.get(l)??0;if(u>=qc){o=!0;continue}r.set(l,u+1);let f=Pn(a.contentBytes),h=f.length>to;n.push({path:l,line:c,text:h?f.slice(0,to):f,truncated:h})}return{matches:n,capped:o,incomplete:!1,binarySkipped:s}}function Qc(t){return[...Yc,"grep","--no-textconv","--no-recurse-submodules","--full-name","--no-color","--no-column","-I","-n","-z","-F",...Kc(t)?["-i"]:[],"-e",t,"--untracked","--","."]}async function ro(t,e){if(e.length<De)throw new Pe;if(e.length>Zs)throw new Lt(`Query must be at most ${Zs} characters`);if(e.includes("\x00"))throw new Lt("Query cannot contain a NUL byte");if(e.includes(`
53
- `))throw new Lt("Query cannot span lines — this searches for literal text");try{let{stdout:n}=await Wc("git",Qc(e),{cwd:t,env:j(),encoding:"buffer",maxBuffer:zc,timeout:Jc,windowsHide:!0});return no(n)}catch(n){let r=n;if(r.code===1)return eo;if(r.killed===!0||r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...r.stdout?no(r.stdout):eo,incomplete:!0};throw n}}function so(t,e){let{registry:n}=e;t.post("/repos/:id/search",async({params:r,body:s,res:o})=>{let i=_(n,r.id),a=H(s,"query");try{let c=await ro(i.path,a);k(o,200,c)}catch(c){if(c instanceof Pe)throw new d(400,`Query must be at least ${De} characters`);if(c instanceof Lt)throw new d(400,c.message);throw c}})}import{Worker as Zc}from"node:worker_threads";var tl=1000,el=64,nl={status:"unavailable",reason:"deadline"},ne={status:"unavailable",reason:"error"};function rl(){let t=import.meta.url;return t.endsWith(".ts")?new URL("./symbolWorker.ts",t):new URL("./symbolWorker.js",t)}function oo(t){let e=t.timeoutMs??tl,n=new Set(t.extensions),r=null,s=0,o=Promise.resolve(),i=!1,a=new Map;function c(h,p){a.delete(h),a.set(h,p);while(a.size>el){let g=a.keys().next().value;if(g===void 0)break;a.delete(g)}}function l(){let h=r;if(r=null,h!==null)h.terminate()}function u(){let h=new Zc(rl(),{workerData:{grammarDir:t.grammarDir,queryDir:t.queryDir}});return h.unref(),h}function f(h,p){return new Promise((g)=>{if(r===null)try{r=u()}catch{g(ne);return}let w=r,R=++s,A=!1,y=(v,X)=>{if(A)return;if(A=!0,clearTimeout(b),w.off("message",x),w.off("error",S),w.off("exit",m),X)l();g(v)},x=(v)=>{if(v.seq!==R)return;y(v.outcome,!1)},S=()=>y(ne,!0),m=()=>y(ne,!0),b=setTimeout(()=>y(nl,!0),e);b.unref?.(),w.on("message",x),w.on("error",S),w.on("exit",m);let E={seq:R,relPath:h,content:p};try{w.postMessage(E)}catch{y(ne,!0)}})}return{supported(h){let p=h.lastIndexOf(".");if(p<=h.lastIndexOf("/"))return!1;return n.has(h.slice(p).toLowerCase())},async extract(h,p){if(i)return ne;let g=`${h}\x00${p}`,w=a.get(g);if(w!==void 0)return c(g,w),w;let R=o.then(()=>f(h,p));o=R.catch(()=>{return});let A=await R;return c(g,A),A},async dispose(){i=!0;let h=r;if(r=null,a.clear(),h!==null)await h.terminate()}}}import{execFile as sl,spawn as ol}from"node:child_process";import*as re from"node:fs";import*as ao from"node:path";import{promisify as il}from"node:util";var al=il(sl);class Nt extends Error{constructor(t){super(`Not a regular blob: ${t}`);this.name="NotRegularBlobError"}}class Ct extends Error{size;constructor(t,e){super(`Blob too large: ${t} (${e} bytes)`);this.name="BlobTooLargeError",this.size=e}}class yt extends Error{constructor(t){super(`Unsafe blob path: ${t}`);this.name="UnsafeBlobPathError"}}var co=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"],lo=5000,Me=65536,uo=/^[0-9a-f]{40}([0-9a-f]{24})?$/,cl=new Set(["100644","100755"]);function ll(t){if(t==="")throw new yt("empty");if(t.includes("\x00"))throw new yt("contains NUL");if(t.startsWith("-"))throw new yt('starts with "-"');if(t.startsWith(":"))throw new yt('starts with ":"')}async function Fe(t,e,n){let{stdout:r}=await al("git",[...co,...e],{cwd:t,env:j(),encoding:"buffer",maxBuffer:n,timeout:lo,windowsHide:!0});return r}function fo(t){let e=[],n=0;for(let r=0;r<t.length;r++){if(t[r]!==0)continue;if(r>n)e.push(t.subarray(n,r));n=r+1}if(n<t.length)e.push(t.subarray(n));return e}function ho(t,e){let n=Buffer.from(e,"utf8");for(let r of t){let s=r.indexOf(9);if(s<0)continue;if(!r.subarray(s+1).equals(n))continue;return r.subarray(0,s).toString("utf8").trim().split(/\s+/)}return null}var ul=1;async function fl(t){let e;try{e=(await Fe(t,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],Me)).toString("utf8").trim()}catch(n){if(n?.code===ul)return null;throw n}return uo.test(e)?e:null}async function hl(t,e){let n=await fl(t);if(n===null)return null;let r=await Fe(t,["ls-tree","-z","--full-tree","-l",n,"--",e],Me),s=ho(fo(r),e);if(s===null||s.length!==4)return null;return{mode:s[0],oid:s[2],sizeText:s[3]}}async function pl(t,e){let n=await Fe(t,["ls-files","--stage","-z","--",e],Me),r=ho(fo(n),e);if(r===null||r.length!==3)return null;if(r[2]!=="0")return null;return{mode:r[0],oid:r[1],sizeText:null}}function po(t,e){let n=Number.parseInt(t,10);if(!Number.isSafeInteger(n)||n<0)throw Error(`git reported a malformed size for ${e}`);return n}async function dl(t,e,n){let r=await Fe(t,["cat-file","-s",e],Me);return po(r.toString("utf8").trim(),n)}var io=Buffer.alloc(0);async function ml(t,e,n){let r=Buffer.alloc(n),s=0;while(s<n){let{bytesRead:o}=await t.read(r,s,n-s,e+s);if(o===0)break;s+=o}return s===n?r:r.subarray(0,s)}function mo(t,e){let n=io,r=!1;return{async read(s){let o=Math.max(0,Math.min(s,t));if(o>n.length&&!r){let i=await e(o,n);r=i.length<o,n=i}return n.subarray(0,Math.min(o,n.length))},release(){n=io,r=!1}}}function gl(t,e){let n=null,r=[],s=0,o=!1,i=null,a=null,c=!1,l=null,u=()=>o&&i!==null,f=()=>{if(r.length!==1){let w=Buffer.concat(r,s);r.length=0,r.push(w)}return r[0]};function h(){if(l===null)return;if(a===null&&u()&&i?.signal===null&&i.code!==0)a=Error(`git cat-file blob failed for ${e} (exit ${i.code??"null"})`);if(a===null&&s<l.want&&!u())return;let w=l;if(l=null,clearTimeout(w.timer),n?.stdout?.pause(),a!==null)w.reject(a);else w.resolve(f().subarray(0,Math.min(w.want,s)))}function p(w){a??=w,h()}function g(){let w=ol("git",[...co,"cat-file","blob",e],{cwd:t,env:j(),stdio:["ignore","pipe","ignore"],windowsHide:!0});n=w,w.stdout?.on("data",(R)=>{if(c)return;r.push(R),s+=R.length,h()}),w.stdout?.on("end",()=>{o=!0,h()}),w.stdout?.on("error",p),w.on("error",p),w.on("close",(R,A)=>{i={code:R,signal:A},h()})}return{read(w){if(a!==null)return Promise.reject(a);if(c)return Promise.reject(Error(`read after close for ${e}`));if(w<=s||u())return Promise.resolve(f().subarray(0,Math.min(w,s)));if(l!==null)return Promise.reject(Error(`concurrent read of ${e}`));return new Promise((R,A)=>{let y=setTimeout(()=>{n?.kill("SIGKILL"),p(Error(`git cat-file blob timed out for ${e}`))},lo);if(l={want:w,resolve:R,reject:A,timer:y},n===null)g();else n.stdout?.resume()})},release(){if(c=!0,l!==null)p(Error(`git cat-file blob closed while reading ${e}`));r.length=0,s=0,n?.kill("SIGKILL"),n=null}}}function wl(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function yl(t,e,n){let r=ao.join(t,e),s;try{s=await re.promises.open(r,re.constants.O_RDONLY|(re.constants.O_NONBLOCK??0))}catch(o){if(wl(o))return null;throw o}try{let o=await s.stat();if(!o.isFile())throw new Nt(e);if(o.size>n)throw new Ct(e,o.size);let i=o.size,a=mo(i,async(c,l)=>{let u=await ml(s,l.length,c-l.length);return l.length===0?u:Buffer.concat([l,u])});return{oid:null,size:i,version:`${i}-${o.mtimeMs}`,read:(c)=>a.read(c),close:()=>(a.release(),s.close())}}catch(o){try{await s.close()}catch{}throw o}}async function bl(t,e,n,r){let s=e==="head"?await hl(t,n):await pl(t,n);if(s===null)return null;if(!cl.has(s.mode))throw new Nt(n);if(!uo.test(s.oid))throw Error(`git reported a malformed object id for ${n}`);let o=s.oid,i=s.sizeText===null?await dl(t,o,n):po(s.sizeText,n);if(i>r)throw new Ct(n,i);let a=gl(t,o),c=mo(i,(l)=>a.read(l));return{oid:o,size:i,version:o,read:(l)=>c.read(l),close(){return c.release(),a.release(),Promise.resolve()}}}async function go(t,e,n,r){if(ll(n),e==="worktree")return yl(t,n,r);return bl(t,e,n,r)}var Sl=["worktree","index","head"],vl=16,El=js,xl=Tt,kl=["too-large","too-many-pixels"];function wo(t){let e=t.get("path");if(e===null)throw new d(400,'Missing "path" query parameter');return e}function Rl(t){let e=t.get("side");if(e===null||!Sl.includes(e))throw new d(400,'Invalid "side" (expected worktree, index or head)');return e}function _l(t){let e=t.get("staged");if(e==="1")return!0;if(e==="0")return!1;throw new d(400,'Invalid "staged" (expected 0 or 1)')}function vo(t){if(t instanceof Nt)throw new d(400,t.message);if(t instanceof yt)throw new d(400,t.message);if(t instanceof Ct)throw new d(413,t.message);throw t}async function yo(t,e){let n=await t.read(e);return{bytes:n,sniff:$t(n,t.size,n.length>=t.size)}}async function Al(t,e){let{size:n}=t,r=await t.read(vl),s=$t(r,n,r.length>=n);if(!s.ok&&s.refusal==="too-large")return{bytes:r,sniff:s};let o=Math.min(Ie(r,n),n),i=await yo(t,Math.max(o,Math.min(e,n)));if(i.sniff.ok||i.sniff.refusal!=="header-not-found")return i;if(i.bytes.length>=n)return i;return yo(t,n)}async function Eo(t,e,n,r){let s=await go(t,e,n,Tt);if(s===null)return null;try{let{bytes:o,sniff:i}=await Al(s,r);return{bytes:o,size:s.size,oid:s.oid,version:s.version,sniff:i}}finally{await s.close()}}function Il(t,e,n){let r={"content-type":e,"content-disposition":"inline","x-content-type-options":"nosniff","cross-origin-resource-policy":"same-origin",vary:"sec-fetch-site, sec-fetch-dest","cache-control":t==="worktree"?"no-store":"private, no-cache"};if(t!=="worktree"&&n!==null)r.etag=`"${n}"`;return r}function Dl(t){let e=kl.includes(t)?413:415;return new d(e,`Image not served: ${t}`)}function Pl(t,e){let n=t.originalPath??t.path;switch(t.status){case"untracked":return{old:null,new:{side:"worktree",path:t.path}};case"added":return{old:null,new:{side:e?"index":"worktree",path:t.path}};case"deleted":return{old:{side:e?"head":"index",path:n},new:null};default:return e?{old:{side:"head",path:n},new:{side:"index",path:t.path}}:{old:{side:"index",path:n},new:{side:"worktree",path:t.path}}}}function Ml(t,e,n){return{path:t.path,side:t.side,bytes:e,oid:null,image:null,refusal:n,version:""}}async function bo(t,e){let n=mt(t.path,e.path);await gt(t,n);let r;try{r=await Eo(t.path,e.side,n,El)}catch(s){if(s instanceof Ct)return Ml(e,s.size,"too-large");if(s instanceof Nt)return null;vo(s)}if(r===null)return null;return{path:e.path,side:e.side,bytes:r.size,oid:r.oid,version:r.version,image:r.sniff.ok?r.sniff.info:null,refusal:r.sniff.ok?null:r.sniff.refusal}}function Fl(t,e){return e.writableEnded||e.destroyed===!0||t.destroyed===!0}async function So(t,e,n){let r=t.acquire();if(r===null)throw new d(503,"Too many image requests in flight");let s=await r;if(n.once("finish",s),n.once("close",s),e.once("close",s),Fl(e,n))return s(),!1;return!0}function xo(t,e,n){let{registry:r}=e;t.get("/repos/:id/media",async({params:s,query:o,req:i,res:a})=>{let c=_(r,s.id),l=_l(o),u=mt(c.path,wo(o));if(await gt(c,u),!await So(n,i,a))return;let f=await Pt(c.manager.workingTree,u,l),h=Pl(f,l),p={old:h.old===null?null:await bo(c,h.old),new:h.new===null?null:await bo(c,h.new)};k(a,200,p)}),t.get("/repos/:id/blob",async({params:s,query:o,req:i,res:a})=>{let c=_(r,s.id),l=Jn(i);if(l)throw new d(l.status,l.message);let u=Rl(o),f=mt(c.path,wo(o));if(await gt(c,f),!await So(n,i,a))return;let h;try{h=await Eo(c.path,u,f,xl)}catch(g){vo(g)}if(h===null)throw new d(404,`No such blob on side ${u}: ${f}`);if(!h.sniff.ok)throw Dl(h.sniff.refusal);let p=Il(u,h.sniff.info.mime,h.oid);Hn(a,200,h.bytes,p)})}function ko(t,e){let{registry:n,daemonEvents:r,follow:s}=e;t.get("/events",({req:o,res:i})=>{let a=n.listRepos().map((c)=>({id:c.id,path:c.path}));r.subscribe(o,i,a)}),t.get("/follow",({res:o})=>{k(o,200,s?s.state:ps)})}import*as Mn from"node:os";import*as Bt from"node:path";function Ro(t,e){let{settings:n,discovery:r,daemonEvents:s}=e;t.get("/settings",({res:o})=>{k(o,200,{...n.settings,persisted:n.persisted})}),t.put("/settings",async({body:o,res:i})=>{let a=Ds(o,"watchRoots"),c;try{c=ms(a)}catch(u){throw new d(400,u instanceof Error?u.message:String(u))}try{n.save({...n.settings,watchRoots:c})}catch(u){let f=u instanceof Error?u.message:String(u);throw new d(500,`Could not save settings: ${f}`)}await r.setRoots(c);let l={...n.settings,persisted:n.persisted};s.broadcast("settings-change",l),k(i,200,l)}),t.get("/discovered",({res:o})=>{k(o,200,r.state)}),t.get("/browse",async({query:o,res:i})=>{let a=o.get("path"),c=a?z(a):Mn.homedir();if(!Bt.isAbsolute(c))throw new d(400,`Path must be absolute: ${a}`);let l=Bt.resolve(c),u;try{u=await ws(l)}catch{throw new d(404,`Cannot read directory: ${l}`)}let f=Bt.dirname(l);k(i,200,{path:l,parent:f===l?null:f,home:Mn.homedir(),entries:u})}),t.post("/discovered/rescan",async({res:o})=>{k(o,200,await r.rescan())})}function Fn(t=4,e=64){let n=0,r=[];function s(){let o=!1;return()=>{if(o)return;o=!0;let i=r.shift();if(i)i(s());else n--}}return{acquire(){if(n<t)return n++,Promise.resolve(s());if(r.length>=e)return null;return new Promise((o)=>{r.push(o)})},get active(){return n},get queued(){return r.length}}}function Tl(t){if(!bt.existsSync(t))return Promise.resolve(!1);return new Promise((e)=>{try{let n=Ao.connect(t);n.once("connect",()=>{n.destroy(),e(!0)}),n.once("error",()=>{n.destroy(),e(!1)})}catch{e(!1)}})}function Io(t={}){let e=new un,n=new fn,r=new ln({onOpened:(m)=>n.broadcast("repo-opened",{id:m.id,path:m.path}),onClosed:(m)=>{e.closeRepo(m),n.broadcast("repo-closed",{id:m})}}),s=t.followFile?new pn(r,n,t.followFile):null,o=ks(t.updateCheck===!1?()=>Promise.resolve(null):t.fetchLatestVersion),i=new mn(t.settingsFile??null),a=new wn(n),c=new Map,l=Fn(),u=t.symbols??null,f=u===null?null:{pool:oo(u),gate:Fn(1,4),extensions:u.extensions};function h(m){let b=c.get(m);if(b)return b;let E=new Ge,v={registry:r,sse:e,daemonEvents:n,follow:s,settings:i,discovery:a,apiMode:m,version:o,symbols:f,httpPort:A};if(_s(E,v),As(E,v),$s(E,v),Cs(E,v),Hs(E,v),Gs(E,v),m==="full")Us(E,v);return Qs(E,v),so(E,v),xo(E,v,l),ko(E,v),Ro(E,v),c.set(m,E),E}let p=(m)=>t.apiMode??(m==="tcp"?"web":"full");s?.start(),a.setRoots(i.load().watchRoots);let g=t.webRoot?jn(t.webRoot):void 0,w=new Set,R=[];function A(){for(let m of R){let b=m.server.address();if(b!==null&&typeof b==="object")return b.port}return null}function y(m){let b=h(m),E=_o.createServer((v,X)=>{for(let[ct,se]of Object.entries(Yn))X.setHeader(ct,se);if(Xn(E.address())){let ct=zn(v);if(ct){k(X,ct.status,{error:ct.message});return}}b.handle(v,X,g).catch(()=>X.end())});return E.on("connection",(v)=>{w.add(v),v.on("close",()=>w.delete(v))}),E}async function x(m,b){let E=m==="unix"?b.socketPath??null:null;if(E){if(await Tl(E))throw Error(`diffstalkerd already running at ${E}`);bt.rmSync(E,{force:!0})}let v={server:y(p(m)),socketPath:E};R.push(v),await new Promise((X,ct)=>{let se=(Co)=>ct(Co);v.server.once("error",se);let Oe=()=>{if(v.server.removeListener("error",se),E)bt.chmodSync(E,384);X()};if(m==="fd")v.server.listen({fd:b.fd},Oe);else if(E)process.umask(63),v.server.listen(E,Oe);else v.server.listen(b.port,"127.0.0.1",Oe)})}function S(m){return new Promise((b,E)=>{m.server.close((v)=>{if(m.socketPath)bt.rmSync(m.socketPath,{force:!0});if(v&&v.code!=="ERR_SERVER_NOT_RUNNING")E(v);else b()})})}return{address(){return R[0]?.server.address()??null},addresses(){return R.map((m)=>m.server.address()).filter((m)=>m!==null)},getRepo(m){return r.getRepo(m)},async openRepo(m){let{handle:b}=await ke(r,m);return{id:b.id,path:b.path}},async listen(m){let b=[];if(m.fd!==void 0)b.push("fd");if(m.socketPath)b.push("unix");if(m.port!==void 0)b.push("tcp");if(b.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let E of b)await x(E,m)},close(){s?.dispose(),a.dispose(),e.destroy(),n.destroy(),r.disposeAll();for(let b of w)b.destroy();let m=f?.pool.dispose()??Promise.resolve();return Promise.all([m,...R.splice(0).map(S)]).then(()=>{})}}}import*as Tn from"node:fs";import*as Ht from"node:path";import*as Oo from"node:crypto";import{createRequire as $l}from"node:module";var Do=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 Po(){return[...Do.keys()]}function Ol(t){let e=t.slice(t.lastIndexOf("/")+1),n=e.lastIndexOf(".");if(n<=0)return"";return e.slice(n).toLowerCase()}function Mo(t){return Do.get(Ol(t))??null}var Ll="diffstalkerd-grammars";function Nl(t){return Oo.createHash("sha256").update(t).digest("hex")}function Cl(t){try{let e=JSON.parse(Tn.readFileSync(Ht.join(t,"checksums.json"),"utf8"));if(typeof e.webTreeSitterVersion!=="string"||typeof e.files!=="object")return null;return e}catch{return null}}var Fo="0.26.11";function Bl(t,e,n){for(let[r,s]of Object.entries(e.files)){let o;try{o=Tn.readFileSync(Ht.join(t,r))}catch{return n(`grammars: missing ${r}`),!1}if(Nl(o)!==s)return n(`grammars: checksum mismatch for ${r}`),!1}return!0}function Hl(t){let e=new Set;for(let n of Object.keys(t.files)){let r=/^tree-sitter-(.+)\.wasm$/.exec(n);if(r!==null&&t.files[`queries/${r[1]}.scm`]!==void 0)e.add(r[1])}return e}function To(t,e=()=>{}){let n=Cl(t);if(n===null)return e(`grammars: no readable checksums.json in ${t}`),null;if(n.webTreeSitterVersion!==Fo)return e(`grammars: built for web-tree-sitter ${n.webTreeSitterVersion}, this daemon bundles ${Fo} — symbols disabled`),null;if(!Bl(t,n,e))return null;let r=Hl(n),s=Po().filter((o)=>{let i=Mo(`x${o}`);return i!==null&&r.has(i.grammar)});if(s.length===0)return e("grammars: no usable grammar found"),null;return{grammarDir:t,queryDir:Ht.join(t,"queries"),extensions:s}}function $o(t,e=()=>{}){if(t!==null)return To(t,e);try{let r=$l(import.meta.url).resolve(`${Ll}/checksums.json`);return To(Ht.dirname(r),e)}catch{return null}}var No="diffstalkerd.sock";function Ul(t){return t===void 0?No:`${t}.sock`}var jl=3,Lo=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
48
+ `);this.lastReadPath=n,this._state={path:n,lastUpdate:r,rawContent:e,sourceFile:this.targetFile}}}catch{}this.watcher=Pa(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 hs={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class pn{registry;hub;targetFile;watcher;followedRepoId=null;followedPath=null;disposed=!1;queue=Promise.resolve();constructor(t,e,n){this.registry=t,this.hub=e,this.targetFile=n,this.watcher=new hn(n)}get state(){return{targetFile:this.targetFile,enabled:!0,followedRepoId:this.followedRepoId,followedPath:this.followedPath}}start(){if(this.watcher.on("path-change",(t)=>this.enqueue(t)),this.watcher.start(),this.watcher.state.path)this.enqueue(this.watcher.state)}enqueue(t){this.queue=this.queue.then(()=>this.follow(t)).catch(()=>{})}async follow(t){if(this.disposed||!t.path)return;let e;try{e=await this.registry.openRepo(t.path)}catch{return}if(this.disposed){this.registry.closeRepo(e.handle.id);return}if(e.created)e.handle.manager.workingTree.refresh().catch(()=>{});if(e.handle.id===this.followedRepoId)this.registry.closeRepo(e.handle.id);else{let n=this.followedRepoId;if(this.followedRepoId=e.handle.id,this.followedPath=e.handle.path,n)this.registry.closeRepo(n)}this.hub.broadcast("follow-change",{repoId:e.handle.id,path:t.path,rawContent:t.rawContent})}dispose(){if(this.disposed)return;if(this.disposed=!0,this.watcher.stop(),this.followedRepoId)this.registry.closeRepo(this.followedRepoId),this.followedRepoId=null,this.followedPath=null}}import*as H from"node:fs";import*as Pt from"node:path";function ps(){return{watchRoots:[]}}var dn=16;function Fa(t){let e=t.trim();if(!e)throw Error("Watch directory cannot be empty");let n=z(e);if(!Pt.isAbsolute(n))throw Error(`Watch directory must be absolute: ${t}`);let r=Pt.resolve(n),s;try{s=H.statSync(r)}catch{throw Error(`No such directory: ${r}`)}if(!s.isDirectory())throw Error(`Not a directory: ${r}`);return r}function ds(t){if(t.length>dn)throw Error(`Too many watch directories (max ${dn})`);let e=new Set,n=[];for(let r of t){let s=Fa(r);if(e.has(s))continue;e.add(s),n.push(s)}return n}function Ta(t){let e=ps();if(typeof t!=="object"||t===null)return e;let n=t;if(Array.isArray(n.watchRoots))e.watchRoots=n.watchRoots.filter((r)=>typeof r==="string").slice(0,dn);return e}class mn{file;current=ps();constructor(t){this.file=t}get settings(){return this.current}get persisted(){return this.file!==null}load(){if(!this.file)return this.current;let t;try{t=H.readFileSync(this.file,"utf-8")}catch{return this.current}try{this.current=Ta(JSON.parse(t))}catch(e){ce(`Ignoring invalid settings file ${this.file}: ${String(e)}`)}return this.current}save(t){if(this.current=t,!this.file)return this.current;H.mkdirSync(Pt.dirname(this.file),{recursive:!0});let e=`${this.file}.${process.pid}.tmp`;try{H.writeFileSync(e,`${JSON.stringify(this.current,null,2)}
49
+ `,{mode:384}),H.renameSync(e,this.file)}catch(n){throw H.rmSync(e,{force:!0}),n}return this.current}}import*as ys from"node:path";import{watch as ja}from"chokidar";import*as K from"node:fs/promises";import*as L from"node:path";var Oa=2,$a=500,Na=new Set(["node_modules","vendor","target","dist","build","venv","__pycache__"]);async function ms(t){try{return await K.stat(L.join(t,".git")),!0}catch{return!1}}async function La(t){let e=L.join(t,".git"),n;try{n=await K.stat(e)}catch{return null}if(n.isDirectory())return e;try{let r=await K.readFile(e,"utf-8"),s=/^gitdir:\s*(.+)$/m.exec(r);if(!s)return null;let o=s[1].trim(),i=L.isAbsolute(o)?o:L.resolve(t,o);return await K.stat(i),i}catch{return null}}async function Ca(t){let e;try{e=(await K.readFile(L.join(t,"HEAD"),"utf-8")).trim()}catch{return null}let n=/^ref:\s*refs\/heads\/(.+)$/.exec(e);if(n)return n[1].trim();if(/^[0-9a-f]{40}$/i.test(e))return e.slice(0,7);return null}async function Ba(t){let n=(await Promise.all(["index","HEAD"].map(async(r)=>{try{return(await K.stat(L.join(t,r))).mtimeMs}catch{return null}}))).filter((r)=>r!==null);return n.length===0?null:Math.max(...n)}async function Ha(t){let e=await La(t);if(e===null)return null;let[n,r]=await Promise.all([Ca(e),Ba(e)]);return{path:t,name:L.basename(t),branch:n,lastActivity:r}}function Ua(t){if(!t.isDirectory())return!1;if(t.name.startsWith("."))return!1;return!Na.has(t.name)}async function gs(t){let e=await gn(t);return Promise.all(e.map(async(n)=>({name:L.basename(n),path:n,isRepo:await ms(n)})))}async function gn(t){return(await K.readdir(t,{withFileTypes:!0})).filter(Ua).map((n)=>L.join(t,n.name)).sort()}async function Ga(t,e,n){let r=[],s=[];for(let o of t){if(r.length>=n)return{repos:r,next:s,capped:!0};if(await ms(o)){r.push(o);continue}if(!e)continue;try{s.push(...await gn(o))}catch{}}return{repos:r,next:s,capped:!1}}async function ws(t,e={}){let n=e.depth??Oa,r=e.limit??$a,s=await gn(t),o=[],i=!1;for(let c=1;c<=n&&s.length>0&&!i;c++){let l=await Ga(s,c<n,r-o.length);o.push(...l.repos),i=l.capped,s=l.next.sort()}return{repos:(await Promise.all(o.map(Ha))).filter((c)=>c!==null),capped:i}}var Wa=300;function qa(t,e){let n=ys.basename(t);if(n.startsWith(".")&&n!==".")return!0;if(n==="node_modules")return!0;return le(t,e)}class wn{hub;roots=new Map;disposed=!1;constructor(t){this.hub=t}get state(){return{roots:[...this.roots.values()].map((t)=>t.state)}}async setRoots(t){if(this.disposed)return;for(let[r,s]of this.roots)if(!t.includes(r))this.teardown(s),this.roots.delete(r);let e=[],n=new Map;for(let r of t){let s=this.roots.get(r);if(s){n.set(r,s);continue}n.set(r,{state:{path:r,repos:[],error:null,capped:!1},watcher:null,timer:null}),e.push(r)}this.roots=n,await Promise.all(e.map((r)=>this.scan(r)));for(let r of e)this.startWatching(r);this.broadcast()}async rescan(){return await Promise.all([...this.roots.keys()].map((t)=>this.scan(t))),this.broadcast(),this.state}dispose(){this.disposed=!0;for(let t of this.roots.values())this.teardown(t);this.roots.clear()}teardown(t){if(t.timer)clearTimeout(t.timer);t.timer=null,t.watcher?.close(),t.watcher=null}async scan(t){let e=this.roots.get(t);if(!e)return;try{let n=await ws(t);e.state={path:t,repos:n.repos,error:null,capped:n.capped}}catch(n){e.state={path:t,repos:[],error:n instanceof Error?n.message:String(n),capped:!1}}}startWatching(t){let e=this.roots.get(t);if(!e||e.watcher)return;let n=ja(t,{persistent:!0,ignoreInitial:!0,depth:1,ignored:qa});n.on("error",(r)=>{e.state={...e.state,error:r instanceof Error?r.message:String(r)},this.broadcast()}),n.on("addDir",()=>this.scheduleRescan(t)),n.on("unlinkDir",()=>this.scheduleRescan(t)),e.watcher=n}scheduleRescan(t){let e=this.roots.get(t);if(!e)return;if(e.timer)clearTimeout(e.timer);e.timer=setTimeout(()=>{e.timer=null,this.scan(t).then(()=>this.broadcast())},Wa),e.timer.unref?.()}broadcast(){if(this.disposed)return;this.hub.broadcast("discovery-change",this.state)}}import*as Es from"node:fs";import{execFile as Xa}from"node:child_process";import*as at from"node:fs";import*as et from"node:path";import{fileURLToPath as za}from"node:url";var bs={method:"unknown",package:null,command:null},Qt="diffstalkerd",Ja=3000,Ya=["paru","yay"],Ka=[{method:"bun",pattern:/\/install\/global\/node_modules\/diffstalkerd$/,command:`bun add -g ${Qt}`},{method:"pnpm",pattern:/\/pnpm\/global\/\d+\/node_modules\/diffstalkerd$/,command:`pnpm add -g ${Qt}`},{method:"yarn",pattern:/\/yarn\/global\/node_modules\/diffstalkerd$/,command:`yarn global add ${Qt}`},{method:"npm",pattern:/\/lib\/node_modules\/diffstalkerd$/,command:`npm install -g ${Qt}`}];async function Va(t,e){let n=t.split(et.sep).join("/").replace(/\/+$/,"");for(let s of Ka){if(!s.pattern.test(n))continue;let o=e.writable(t)?"":"sudo ";return{method:s.method,package:Qt,command:`${o}${s.command}`}}let r=await e.pacmanOwner(et.join(t,"package.json"));if(r!==null){let s=e.onPath(Ya);return{method:"pacman",package:r,command:s?`${s} -S ${r}`:`sudo pacman -Syu ${r}`}}return bs}var Qa={onPath(t){let e=(process.env.PATH??"").split(et.delimiter).filter(Boolean);for(let n of t)for(let r of e)try{return at.accessSync(et.join(r,n),at.constants.X_OK),n}catch{}return null},pacmanOwner(t){return new Promise((e)=>{Xa("pacman",["-Qoq","--",t],{timeout:Ja},(n,r)=>{if(n)return e(null);let s=r.trim().split(`
50
+ `)[0]?.trim();e(s?s:null)})})},writable(t){try{return at.accessSync(t,at.constants.W_OK),!0}catch{return!1}}};function Za(){let t=et.dirname(za(new URL("../package.json",import.meta.url)));try{return at.realpathSync(t)}catch{return t}}function Ss(t=Za(),e=Qa){let n=null;return{info(){return n??=Va(t,e).catch(()=>bs),n}}}var tc="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",ec=21600000,nc=300000,rc=5000;function yn(){try{let t=Es.readFileSync(new URL("../package.json",import.meta.url),"utf-8"),e=JSON.parse(t);return typeof e.version==="string"?e.version:null}catch{return null}}async function sc(){let t=await fetch(tc,{headers:{accept:"application/json"},signal:AbortSignal.timeout(rc)});if(!t.ok)return null;let e=await t.json();return typeof e.latest==="string"?e.latest:null}function vs(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());if(!e)return null;return[Number(e[1]),Number(e[2]),Number(e[3])]}function oc(t,e){if(t===null||e===null)return"unknown";let n=vs(t),r=vs(e);if(!n||!r)return"unknown";for(let s=0;s<n.length;s++){if(n[s]<r[s])return"outdated";if(n[s]>r[s])return"ahead"}return"current"}function xs(t=sc,e=yn(),n=Ss()){let r=null,s=null;function o(){if(r&&Date.now()<r.expiresAt)return Promise.resolve(r.value);if(s)return s;return s=t().catch(()=>null).then((i)=>{let a=i===null?nc:ec;return r={value:i,expiresAt:Date.now()+a},s=null,i}),s}return{async state(){let[i,a]=await Promise.all([o(),n.info()]);return{current:e,latest:i,status:oc(e,i),install:a}}}}import*as ks from"node:os";function Rs(t,e){t.get("/health",({res:n})=>{E(n,200,{ok:!0,ready:!0,home:ks.homedir(),http:{port:e.httpPort()},symbols:{extensions:e.symbols?.extensions??[]}})})}function _s(t,e){t.get("/version",async({res:n})=>{E(n,200,await e.version.state())})}import*as Zt from"node:fs";import*as F from"node:path";function x(t,e){let n=t.getRepo(e);if(!n)throw new d(404,`Unknown repo id: ${e}`);return n}function U(t,e,n){if(typeof t!=="object"||t===null)throw new d(400,`Expected a JSON body with "${e}"`);let r=t[e];if(typeof r!=="string"||!n?.allowEmpty&&r.length===0)throw new d(400,`Missing "${e}" (string) in body`);return r}function mt(t,e){let n=U(t,e);if(n.startsWith("-"))throw new d(400,`Invalid "${e}" (must not start with "-"): ${n}`);return n}function As(t,e){if(typeof t!=="object"||t===null)throw new d(400,`Expected a JSON body with "${e}"`);let n=t[e];if(!Array.isArray(n)||n.some((r)=>typeof r!=="string"))throw new d(400,`Missing "${e}" (array of strings) in body`);return n}function Ds(t,e){if(typeof t!=="object"||t===null)return;let n=t[e];if(n===void 0)return;if(typeof n!=="string"||n.length===0)throw new d(400,`Invalid "${e}" (expected a non-empty string)`);return n}function vn(t,e,n){if(typeof t!=="object"||t===null)return n.fallback;let r=t[e];if(r===void 0)return n.fallback;if(typeof r!=="number"||!Number.isInteger(r)||r<n.min)throw new d(400,`Invalid "${e}" (expected an integer >= ${n.min})`);return r}function Ps(t,e){if(typeof t!=="object"||t===null)return!1;let n=t[e];if(n===void 0)return!1;if(typeof n!=="boolean")throw new d(400,`Invalid "${e}" (expected a boolean)`);return n}function C(t,e,n){let r=t.get(e);if(r===null)return n;if(r==="true")return!0;if(r==="false")return!1;throw new d(400,`Invalid "${e}" (expected true or false): ${r}`)}function Ms(t,e,n,r){let s=t.get(e);if(s===null)return n;let o=Number(s);if(!Number.isInteger(o)||o<1)throw new d(400,`Invalid "${e}" (expected a positive integer): ${s}`);if(r!==void 0&&o>r)throw new d(400,`Invalid "${e}" (must be <= ${r}): ${s}`);return o}async function nt(t){if(!t.state.status)await t.refresh();let e=t.state.status;if(!e)throw new d(500,"Repository status unavailable");return e}function Is(t,e,n){let r=t.files.filter((s)=>s.path===e);if(r.length===0)return null;return r.find((s)=>s.staged===n)??r[0]}async function Mt(t,e,n){let r=await nt(t),s=Is(r,e,n);if(!s)await t.refresh(),r=await nt(t),s=Is(r,e,n);if(!s)throw new d(404,`File not in status: ${e}`);return s}function Sn(t,e){return t===e||t.startsWith(e+F.sep)}function En(t){return t.replace(/[. ]+$/,"").toLowerCase()===".git"}function gt(t,e){if(e.length===0)throw new d(400,"Empty path");if(e.includes("\x00"))throw new d(400,"Path contains a NUL byte");let n=F.resolve(t),r=F.relative(n,F.resolve(n,e));if(r==="")throw new d(400,`Path resolves to the repository root: ${e}`);if(F.isAbsolute(r)||r===".."||r.startsWith(`..${F.sep}`))throw new d(400,`Path escapes repository root: ${e}`);if(r.startsWith("-"))throw new d(400,`Path must not start with "-": ${e}`);if(r.startsWith(":"))throw new d(400,`Path must not start with ":": ${e}`);if(r.split(F.sep).some(En))throw new d(400,`Path addresses the git directory: ${e}`);return r}async function Fs(t){try{return await Zt.promises.realpath(t)}catch{return null}}var bn=new WeakMap;async function ic(t){let e=bn.get(t);if(!e)e=(async()=>{let n=await k(t.path).raw(["rev-parse","--absolute-git-dir"]);return await Zt.promises.realpath(n.trim())})(),bn.set(t,e),e.catch(()=>bn.delete(t));try{return await e}catch{throw new d(500,"Cannot resolve the git directory for this repository")}}async function wt(t,e){let n=await Zt.promises.realpath(F.resolve(t.path)),r=await Fs(F.join(t.path,e));if(r===null)return;if(!Sn(r,n))throw new d(400,`Path escapes repository root: ${e}`);if(Sn(r,await ic(t)))throw new d(400,`Path addresses the git directory: ${e}`)}async function Ts(t,e){let n=await Zt.promises.realpath(F.resolve(t)),r=[];for(let s of e){let o=await Fs(F.join(t,s.path));if(o===null||Sn(o,n))r.push(s)}return r}function xn(t){return t?.code??null}function ac(t){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test(t)?409:500}async function rt(t,e,n){t.clearError(),await n();let r=t.state.error;if(r){E(e,ac(r),{error:r});return}await t.refresh(),E(e,200,{state:st(t.state)})}function cc(t){return/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged/i.test(t)?409:500}async function B(t,e,n){let r=t.manager.remote,s=()=>new d(409,`A ${r.remoteState.operation??"remote"} operation is already in progress`);if(r.remoteState.inProgress)throw s();let o=await n();if(o===null)throw s();if(o.error){E(e,cc(o.error),{error:o.error});return}let i=t.manager.workingTree;await i.refresh(),E(e,200,{state:st(i.state),result:o.lastResult})}function Os(t,e){let{registry:n}=e;t.get("/repos",({res:r})=>{let s=n.listRepos().map((o)=>({id:o.id,path:o.path,branch:o.manager.workingTree.state.status?.branch.current??null}));E(r,200,s)}),t.post("/repos",async({body:r,res:s})=>{let o=U(r,"path"),i;try{i=await Re(n,o)}catch(a){throw new d(400,a instanceof Error?a.message:String(a))}E(s,i.created?201:200,{id:i.handle.id,path:i.handle.path})}),t.get("/resolve",async({query:r,res:s})=>{let o=r.get("path");if(!o)throw new d(400,'Missing "path" query parameter');let i=await ye(o,{mustExist:!0});if(!i.ok&&i.reason==="not-absolute")throw new d(400,`Repo path must be absolute: ${i.requested}`);E(s,200,{openable:i.ok,root:i.ok?i.root:null})}),t.get("/repos/:id/worktrees",async({params:r,res:s})=>{let o=x(n,r.id);E(s,200,await Ze(o.path))}),t.get("/worktrees",async({query:r,res:s})=>{let o=r.get("path");if(!o)throw new d(400,'Missing "path" query parameter');E(s,200,await Ze(o))}),t.delete("/repos/:id",({params:r,res:s})=>{x(n,r.id),n.closeRepo(r.id),E(s,200,{})})}function $s(t,e,n){if(!t.trim())return{valid:!1,error:"Commit message cannot be empty"};if(e===0&&!n)return{valid:!1,error:"No changes staged for commit"};return{valid:!0,error:null}}function Ns(t){return t.trim()}async function lc(t){let e=(r)=>r.filter((s)=>s.staged).length,n=e((await nt(t)).files);if(n===0)await t.refresh(),n=e((await nt(t)).files);return n}function Ls(t,e){let{registry:n,sse:r}=e;if(t.get("/repos/:id/status",async({params:s,res:o})=>{let i=x(n,s.id);await nt(i.manager.workingTree);let a=st(i.manager.workingTree.state);a.operationInProgress=await Z(i.path),E(o,200,a)}),t.get("/repos/:id/diff",async({params:s,query:o,res:i})=>{let a=x(n,s.id),c=o.get("path")??void 0,l=C(o,"staged",!1),u=C(o,"whole",!1);if(u&&!c)throw new d(400,"whole=true requires a path (one file at a time)");let f=u?me:void 0,h,p=!1;if(c){let g=(await nt(a.manager.workingTree)).files.some((R)=>R.path===c&&R.status==="untracked");if(g&&l)throw new d(400,`staged=true is meaningless for untracked file: ${c} (untracked files have no staged diff)`);p=u&&!g,h=g?await pt(a.path,c):await Dt(a.path,c,l,{context:f})}else h=await Dt(a.path,void 0,l);if(!p)a.manager.workingTree.stampDiff(h);E(i,200,h)}),t.post("/repos/:id/stage",async({params:s,body:o,res:i})=>{let a=x(n,s.id),c=U(o,"path"),l=a.manager.workingTree,u=await Mt(l,c,!1);await rt(l,i,()=>l.stage(u))}),t.post("/repos/:id/unstage",async({params:s,body:o,res:i})=>{let a=x(n,s.id),c=U(o,"path"),l=a.manager.workingTree,u=await Mt(l,c,!0);await rt(l,i,()=>l.unstage(u))}),t.get("/repos/:id/events",({params:s,req:o,res:i})=>{let a=x(n,s.id);r.subscribe(s.id,a.manager,o,i)}),e.apiMode==="full")uc(t,e)}function uc(t,e){let{registry:n}=e;t.post("/repos/:id/stage-all",async({params:r,res:s})=>{let i=x(n,r.id).manager.workingTree;await rt(i,s,()=>i.stageAll())}),t.post("/repos/:id/unstage-all",async({params:r,res:s})=>{let i=x(n,r.id).manager.workingTree;await rt(i,s,()=>i.unstageAll())}),t.post("/repos/:id/discard",async({params:r,body:s,res:o})=>{let i=x(n,r.id),a=U(s,"path"),c=i.manager.workingTree,l=await Mt(c,a,!1);if(l.staged)throw new d(409,`Cannot discard a staged file: ${a} (unstage it first)`);await rt(c,o,()=>c.discard(l))}),t.post("/repos/:id/commit",async({params:r,body:s,res:o})=>{let i=x(n,r.id),a=U(s,"message",{allowEmpty:!0}),c=Ps(s,"amend"),l=i.manager.workingTree,u=await lc(l),f=$s(a,u,c);if(!f.valid)throw new d(400,f.error??"Invalid commit");await rt(l,o,()=>l.commit(Ns(a),c))}),t.post("/repos/:id/stage-hunk",async({params:r,body:s,res:o})=>{let i=x(n,r.id),a=U(s,"patch"),c=i.manager.workingTree;await rt(c,o,()=>c.stageHunk(a))}),t.post("/repos/:id/unstage-hunk",async({params:r,body:s,res:o})=>{let i=x(n,r.id),a=U(s,"patch"),c=i.manager.workingTree;await rt(c,o,()=>c.unstageHunk(a))})}async function fc(t){let e=await Ke(t);if(e&&await it(t,e))return e;if(Rt(t)){let n=await Yt(t);if(n&&await it(t,n))return n}throw new d(422,"No usable base branch")}async function kn(t,e){let n=e.get("base");if(n===null)return fc(t);if(!await it(t,n))throw new d(400,`Unknown base ref: ${n}`);return n}var hc=new Set(["staged","unstaged","both","untracked"]);function pc(t){return{staged:C(t,"staged",!1),unstaged:C(t,"unstaged",!1),untracked:C(t,"untracked",!1)}}function Cs(t){return t?{context:me}:{}}function Bs(t,e){let{registry:n}=e;if(t.get("/repos/:id/history",async({params:r,query:s,res:o})=>{let i=x(n,r.id),a=Ms(s,"count",100,5000);E(o,200,await Er(i.path,a))}),t.get("/repos/:id/commits/:hash",async({params:r,res:s})=>{let o=x(n,r.id),i=r.hash;if(!/^[0-9a-f]{4,40}$/i.test(i))throw new d(400,`Invalid commit hash: ${i}`);let a=await xr(o.path,i);if(a===null)throw new d(404,`Unknown commit: ${i}`);E(s,200,a)}),t.get("/repos/:id/commits/:hash/diff",async({params:r,query:s,res:o})=>{let i=x(n,r.id),a=r.hash;if(!/^[0-9a-f]{4,40}$/i.test(a))throw new d(400,`Invalid commit hash: ${a}`);if(!await it(i.path,a))throw new d(404,`Unknown commit: ${a}`);let c=s.get("path")??void 0,l=C(s,"whole",!1);if(l&&!c)throw new d(400,"whole=true requires a path (one file at a time)");let u=c?await Ve(i.path,{kind:"commit",hash:a},c,Cs(l)):await Br(i.path,a);E(o,200,u)}),t.get("/repos/:id/compare/file",async({params:r,query:s,res:o})=>{let i=x(n,r.id),a=s.get("path");if(!a)throw new d(400,"path is required");let c=C(s,"whole",!1),l=s.get("side");if(l!==null&&!hc.has(l))throw new d(400,`Unknown side: ${l}`);let u=l;if(u==="untracked"){E(o,200,await pt(i.path,a));return}let f=u===null?{kind:"compare",base:await kn(i.path,s)}:{kind:u==="both"?"head":u};E(o,200,await Ve(i.path,f,a,Cs(c)))}),t.get("/repos/:id/head-message",async({params:r,res:s})=>{let o=x(n,r.id);E(s,200,{message:await gr(o.path)})}),t.get("/repos/:id/branches",async({params:r,res:s})=>{let o=x(n,r.id);E(s,200,await pe(o.path))}),t.get("/repos/:id/base-branches",async({params:r,res:s})=>{let o=x(n,r.id);E(s,200,await Ye(o.path))}),t.get("/repos/:id/compare/base",async({params:r,res:s})=>{let o=x(n,r.id);E(s,200,{base:await Ke(o.path)})}),e.apiMode==="full")t.put("/repos/:id/compare/base",async({params:r,body:s,res:o})=>{let i=x(n,r.id),a=mt(s,"branch");if(!await it(i.path,a))throw new d(400,`Not a valid base ref: ${a}`);$r(i.path,a),E(o,200,{base:a})});t.get("/repos/:id/compare/count",async({params:r,query:s,res:o})=>{let i=x(n,r.id),a=await kn(i.path,s);try{E(o,200,{baseBranch:a,commits:await Cr(i.path,a)})}catch(c){if(c instanceof It)throw new d(422,c.message);throw c}}),t.get("/repos/:id/compare",async({params:r,query:s,res:o})=>{let i=x(n,r.id),a=pc(s),c=await kn(i.path,s),l;try{l=await Hr(i.path,c,a)}catch(u){if(u instanceof It)throw new d(422,u.message);throw u}E(o,200,l)})}function dc(t){let e=t.get("since");if(e===null)return 0;if(!/^\d+$/.test(e))throw new d(400,`Invalid "since" (expected a non-negative integer): ${e}`);return Number(e)}function Hs(t,e){let{registry:n}=e;t.get("/repos/:id/journal",({params:r,query:s,res:o})=>{let i=x(n,r.id),a=dc(s);E(o,200,Bn(i.manager.journal.journalStore,a))})}function Us(t,e){let{registry:n}=e;t.post("/repos/:id/push",async({params:r,res:s})=>{let o=x(n,r.id);await B(o,s,()=>o.manager.remote.push())}),t.post("/repos/:id/fetch",async({params:r,res:s})=>{let o=x(n,r.id);await B(o,s,()=>o.manager.remote.fetchRemote())}),t.post("/repos/:id/pull",async({params:r,res:s})=>{let o=x(n,r.id);await B(o,s,()=>o.manager.remote.pullRebase())}),t.post("/repos/:id/stash",async({params:r,body:s,res:o})=>{let i=x(n,r.id),a=Ds(s,"message");await B(i,o,()=>i.manager.remote.stash(a))}),t.post("/repos/:id/stash-pop",async({params:r,body:s,res:o})=>{let i=x(n,r.id),a=vn(s,"index",{min:0,fallback:0});await B(i,o,()=>i.manager.remote.stashPop(a))}),t.post("/repos/:id/switch-branch",async({params:r,body:s,res:o})=>{let i=x(n,r.id),a=mt(s,"name");await B(i,o,()=>i.manager.remote.switchBranch(a))}),t.post("/repos/:id/create-branch",async({params:r,body:s,res:o})=>{let i=x(n,r.id),a=mt(s,"name");await B(i,o,()=>i.manager.remote.createBranch(a))}),t.post("/repos/:id/soft-reset",async({params:r,body:s,res:o})=>{let i=x(n,r.id),a=vn(s,"count",{min:1,fallback:1});if(!await it(i.path,`HEAD~${a}`))throw new d(400,`Cannot soft-reset ${a} commit(s): HEAD~${a} does not exist`);await B(i,o,()=>i.manager.remote.softReset(a))}),t.post("/repos/:id/cherry-pick",async({params:r,body:s,res:o})=>{let i=x(n,r.id),a=mt(s,"hash");await B(i,o,()=>i.manager.remote.cherryPick(a))}),t.post("/repos/:id/revert",async({params:r,body:s,res:o})=>{let i=x(n,r.id),a=mt(s,"hash");await B(i,o,()=>i.manager.remote.revertCommit(a))}),t.post("/repos/:id/abort",async({params:r,res:s})=>{let o=x(n,r.id);if(!await Z(o.path))throw new d(409,"No operation in progress to abort");await B(o,s,()=>o.manager.remote.abortOperation())}),t.post("/repos/:id/rebase-continue",async({params:r,res:s})=>{let o=x(n,r.id);if(await Z(o.path)!=="rebase")throw new d(409,"No rebase in progress to continue");await B(o,s,()=>o.manager.remote.rebaseContinue())})}import*as yt from"node:fs";import*as te from"node:path";var Ot=8388608;var Gs=65536;function Ft(t){return Array.from(t,(e)=>e.charCodeAt(0))}function Tt(t,e,n){if(e+n.length>t.length)return!1;for(let r=0;r<n.length;r++)if(t[e+r]!==n[r])return!1;return!0}function Ie(t,e){return t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function Rn(t,e){return(t[e]<<8)+t[e+1]}function Ae(t,e){return t[e]+(t[e+1]<<8)}function js(t,e){return String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3])}function D(t){return{ok:!1,refusal:t}}function $t(t){return D(t?"malformed":"header-not-found")}function _n(t,e){if(t<1||e<1)return"malformed";if(t>8192||e>8192)return"too-many-pixels";if(t*e>16777216)return"too-many-pixels";return null}var mc=[137,80,78,71,13,10,26,10],gc=[255,216,255],wc=Ft("GIF87a"),yc=Ft("GIF89a"),V=Ft("ftyp");function q(t){return{offset:8,bytes:Ft(t)}}var bc=[{label:"webp",offset:0,bytes:Ft("RIFF"),brand:q("WEBP")},{label:"avif",offset:4,bytes:V,brand:q("avif")},{label:"avis",offset:4,bytes:V,brand:q("avis")},{label:"heic",offset:4,bytes:V,brand:q("heic")},{label:"heix",offset:4,bytes:V,brand:q("heix")},{label:"heim",offset:4,bytes:V,brand:q("heim")},{label:"heis",offset:4,bytes:V,brand:q("heis")},{label:"hevc",offset:4,bytes:V,brand:q("hevc")},{label:"hevx",offset:4,bytes:V,brand:q("hevx")},{label:"mif1",offset:4,bytes:V,brand:q("mif1")},{label:"msf1",offset:4,bytes:V,brand:q("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:Ft("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 Sc(t){return bc.some((e)=>Tt(t,e.offset,e.bytes)&&(e.brand===void 0||Tt(t,e.brand.offset,e.brand.bytes)))}var vc={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},Ec=26;function xc(t,e,n){if(t.length<Ec)return $t(n);if(Ie(t,8)!==13)return D("malformed");if(js(t,12)!=="IHDR")return D("malformed");let r=Ie(t,16),s=Ie(t,20),o=_n(r,s);if(o)return D(o);let i=vc[t[25]];if(!i||!i.includes(t[24]))return D("malformed");let a=kc(t,n);if(a)return a;return{ok:!0,info:{format:"png",mime:"image/png",width:r,height:s,bytes:e}}}function kc(t,e){let n=8;for(let r=0;r<256;r++){if(n+8>t.length)return $t(e);let s=Ie(t,n),o=js(t,n+4);if(o==="IDAT")return null;if(o==="acTL")return D("animation");if(o==="iCCP"&&s>65536)return D("malformed");let i=n+12+s;if(i<=n||!Number.isSafeInteger(i))return D("malformed");n=i}return D("malformed")}var Rc=218,_c=226,Ic=new Set([219,238,192,193,194,196]);function Ac(t){return t>=224&&t<=239||Ic.has(t)}function Dc(t){return t===1||t>=208&&t<=217}function Pc(t){return t>=192&&t<=207&&t!==196&&t!==200&&t!==204}var Mc=new Set([192,193,194]);function Fc(t,e,n){if(t.length<4)return $t(n);if(!Ac(t[3]))return D("malformed");return $c(t,e,n)}function Tc(t,e,n,r,s){if(!Mc.has(n))return D("malformed");if(e+9>t.length)return $t(s);let o=Rn(t,e+5),i=Rn(t,e+7),a=_n(i,o);if(a)return D(a);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:i,height:o,bytes:r}}}function Oc(t,e){if(e+1>=t.length)return{kind:"ran-out"};if(t[e]!==255)return{kind:"malformed"};let n=t[e+1];if(n===255)return{kind:"skip",next:e+1};if(Dc(n))return{kind:"skip",next:e+2};if(n===Rc)return{kind:"malformed"};if(e+4>t.length)return{kind:"ran-out"};let r=Rn(t,e+2);if(r<2)return{kind:"malformed"};if(Pc(n))return{kind:"sof",marker:n};return{kind:"segment",marker:n,length:r}}function $c(t,e,n){let r=2,s=0;for(let o=0;o<1024;o++){let i=Oc(t,r);if(i.kind==="ran-out")return $t(n);if(i.kind==="malformed")return D("malformed");if(i.kind==="sof")return Tc(t,r,i.marker,e,n);if(i.kind==="skip"){r=i.next;continue}if(i.marker===_c){if(s+=i.length-2,s>65536)return D("malformed")}r+=2+i.length}return D("malformed")}var Nc=59,Lc=44,Cc=33;function Ws(t){return(t&128)===0?0:3*(1<<(t&7)+1)}function Bc(t,e,n){if(e>2097152)return D("too-large");if(!n)return D("header-not-found");if(t.length<13)return $t(n);let r=Ae(t,6),s=Ae(t,8),o=_n(r,s);if(o)return D(o);let i={pos:13+Ws(t[10]),left:8192,pixels:0,overBudget:!1},a=Hc(t,i);if(a===null)return D("malformed");if(a<1)return D("malformed");if(a>256)return D("too-many-pixels");if(i.overBudget)return D("too-many-pixels");if(a*r*s>33554432)return D("too-many-pixels");let c={format:"gif",mime:"image/gif",width:r,height:s,bytes:e};if(a>1)c.frames=a;return{ok:!0,info:c}}function Hc(t,e){let n=0;while(e.left-- >0){if(e.pos>=t.length)return null;let r=t[e.pos];if(r===Nc)return n;let s=r===Lc;if(!(s?Gc(t,e):Uc(t,e,r)))return null;if(s&&++n>256)return n;if(e.overBudget)return n}return null}function Uc(t,e,n){if(n!==Cc)return!1;return e.pos+=2,qs(t,e)}function Gc(t,e){if(e.pos+10>t.length)return!1;jc(e,Ae(t,e.pos+5),Ae(t,e.pos+7));let n=t[e.pos+9];return e.pos+=10+Ws(n)+1,qs(t,e)}function jc(t,e,n){let r=e*n;if(e>8192||n>8192||r>16777216){t.overBudget=!0;return}if(t.pixels+=r,t.pixels>33554432)t.overBudget=!0}function qs(t,e){while(e.left-- >0){if(e.pos>=t.length)return!1;let n=t[e.pos];if(e.pos+=1+n,n===0)return e.pos<=t.length}return!1}function Xs(t){return Tt(t,0,wc)||Tt(t,0,yc)}function Nt(t,e,n){if(e>8388608)return D("too-large");if(Tt(t,0,mc))return xc(t,e,n);if(Tt(t,0,gc))return Fc(t,e,n);if(Xs(t))return Bc(t,e,n);if(Sc(t))return D("unsupported-format");return D("not-an-image")}function De(t,e){return Xs(t)?Math.min(e,2097152):65536}function In(t){let e={files:new Map,directories:new Set};for(let n of t){e.files.set(n.path,{status:n.status,staged:n.staged});let r=n.path.split("/"),s="";for(let o=0;o<r.length-1;o++)s=s?`${s}/${r[o]}`:r[o],e.directories.add(s);e.directories.add("")}return e}var Wc=1048576,zs=5000;class ee extends Error{constructor(t){super(`Not a regular file: ${t}`);this.name="NotRegularFileError"}}async function Ys(t,e,n,r){let s=n?.hideHidden??!0,o=n?.hideGitignored??!0,i=te.join(t,e),a=await yt.promises.readdir(i,{withFileTypes:!0}),c=a.map((f)=>e?te.join(e,f.name):f.name),l=o?await kt(t,c):new Set,u=[];for(let f of a){if(s&&f.name.startsWith("."))continue;let h=e?te.join(e,f.name):f.name;if(o&&l.has(h))continue;let p=f.isDirectory(),w={name:f.name,path:h,type:p?"dir":"file"};if(r)if(p){if(r.directories.has(h))w.hasChanges=!0}else{let g=r.files.get(h);if(g)w.gitStatus=g.status,w.staged=g.staged}u.push(w)}return u.sort((f,h)=>{if(f.type==="dir"&&h.type!=="dir")return-1;if(f.type!=="dir"&&h.type==="dir")return 1;return f.name.localeCompare(h.name)}),u}var qc=16,Xc=yt.constants.O_RDONLY|(yt.constants.O_NONBLOCK??0);async function An(t,e,n){let r=Buffer.alloc(e),s=0;while(s<e){let{bytesRead:o}=await t.read(r,s,e-s,n+s);if(o===0)break;s+=o}return s===e?r:r.subarray(0,s)}async function zc(t,e){let n=await An(t,Math.min(qc,e),0),r=Nt(n,e,n.length>=e);if(!r.ok&&r.refusal==="too-large")return{head:n,result:r};let s=Math.min(De(n,e),e),o=s<=n.length?n.subarray(0,s):Buffer.concat([n,await An(t,s-n.length,n.length)]);return{head:o,result:Nt(o,e,o.length>=e)}}function Jc(t,e){return t.ok?{image:t.info,refusal:null,version:e}:{image:null,refusal:t.refusal,version:e}}function Js(t,e){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:t,totalLines:0,media:e}}function Dn(t,e){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:t,totalLines:0,media:e}}function Yc(t,e){let n=t.toString("utf-8"),r=n.split(`
51
+ `),s=!1;if(r.length>zs)n=r.slice(0,zs).join(`
52
+ `),s=!0;return{content:n,binary:!1,truncated:s,tooLarge:!1,size:e,totalLines:r.length}}async function Kc(t,e){let n=await t.stat();if(!n.isFile())throw new ee(e);let r=n.size;if(r>Ot)return Dn(r);let{head:s,result:o}=await zc(t,r),i=Jc(o,`${r}-${n.mtimeMs}`);if(o.ok)return Js(r,i);if(r>Wc)return Dn(r,Jt(s)?i:void 0);let a=s.length>=r?s:Buffer.concat([s,await An(t,r-s.length,s.length)]);return Jt(a)?Js(r,i):Yc(a,r)}async function Ks(t,e){let n=te.join(t,e),r=await yt.promises.stat(n);if(!r.isFile())throw new ee(e);if(r.size>Ot)return Dn(r.size);let s=await yt.promises.open(n,Xc);try{return await Kc(s,e)}finally{await s.close()}}function Vs(t,e){let{registry:n,symbols:r}=e;async function s(o,i,a){if(!a)return o;if(o.binary||o.tooLarge)return o;if(r===null)return{...o,symbols:{status:"unavailable",reason:"error"}};if(!r.pool.supported(i))return{...o,symbols:{status:"unsupported",reason:"language"}};let c=r.gate.acquire();if(c===null)throw new d(503,"Symbol extraction busy");try{return{...o,symbols:await r.pool.extract(i,o.content)}}finally{(await c)()}}t.get("/repos/:id/tree",async({params:o,query:i,res:a})=>{let c=x(n,o.id),l=i.get("dir")??"",u=C(i,"hidden",!1),f=C(i,"ignored",!1),h=l===""?"":gt(c.path,l);await wt(c,h);let p=await nt(c.manager.workingTree),w=In(p.files),g;try{g=await Ys(c.path,h,{hideHidden:!u,hideGitignored:!f},w)}catch(_){let I=xn(_);if(I==="ENOENT")throw new d(404,`No such directory: ${l||"/"}`);if(I==="ENOTDIR")throw new d(400,`Not a directory: ${l}`);throw _}let R=g.filter((_)=>!En(_.name));E(a,200,await Ts(c.path,R))}),t.get("/repos/:id/file",async({params:o,query:i,res:a})=>{let c=x(n,o.id),l=i.get("path");if(!l)throw new d(400,'Missing "path" query parameter');let u=gt(c.path,l);await wt(c,u);try{let f=await Ks(c.path,u);E(a,200,await s(f,u,C(i,"symbols",!1)))}catch(f){if(f instanceof ee)throw new d(400,f.message);let h=xn(f);if(h==="ENOENT"||h==="ENOTDIR")throw new d(404,`No such file: ${l}`);throw f}}),t.get("/repos/:id/files",async({params:o,res:i})=>{let a=x(n,o.id);E(i,200,await Tr(a.path))})}import{execFile as Vc}from"node:child_process";import{promisify as Qc}from"node:util";var Zc=Qc(Vc),Pe=3,tl=20,Qs=500,el=500,nl=4194304,rl=5000,Zs=400,sl=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"];class Me extends Error{constructor(){super(`Query must be at least ${Pe} characters`);this.name="GrepQueryTooShortError"}}class Lt extends Error{constructor(t){super(t);this.name="GrepQueryInvalidError"}}var to={matches:[],capped:!1,incomplete:!1,binarySkipped:0};function ol(t){return t===t.toLowerCase()}function Pn(t){return Buffer.from(t).toString("utf8")}function il(t,e){let n=t.indexOf(0,e);if(n===-1)return null;let r=t.indexOf(0,n+1);if(r===-1)return null;let s=t.indexOf(10,r+1);if(s===-1)s=t.length;return{pathBytes:t.subarray(e,n),lineBytes:t.subarray(n+1,r),contentBytes:t.subarray(r+1,s),next:s+1}}function eo(t,e=el){let n=[],r=new Map,s=0,o=!1,i=0;while(i<t.length){let a=il(t,i);if(a===null)break;if(i=a.next,a.contentBytes.includes(0)){s+=1;continue}let c=Number.parseInt(Pn(a.lineBytes),10);if(!Number.isSafeInteger(c)||c<1)continue;if(n.length>=e){o=!0;break}let l=Pn(a.pathBytes),u=r.get(l)??0;if(u>=tl){o=!0;continue}r.set(l,u+1);let f=Pn(a.contentBytes),h=f.length>Zs;n.push({path:l,line:c,text:h?f.slice(0,Zs):f,truncated:h})}return{matches:n,capped:o,incomplete:!1,binarySkipped:s}}function al(t){return[...sl,"grep","--no-textconv","--no-recurse-submodules","--full-name","--no-color","--no-column","-I","-n","-z","-F",...ol(t)?["-i"]:[],"-e",t,"--untracked","--","."]}async function no(t,e){if(e.length<Pe)throw new Me;if(e.length>Qs)throw new Lt(`Query must be at most ${Qs} characters`);if(e.includes("\x00"))throw new Lt("Query cannot contain a NUL byte");if(e.includes(`
53
+ `))throw new Lt("Query cannot span lines — this searches for literal text");try{let{stdout:n}=await Zc("git",al(e),{cwd:t,env:j(),encoding:"buffer",maxBuffer:nl,timeout:rl,windowsHide:!0});return eo(n)}catch(n){let r=n;if(r.code===1)return to;if(r.killed===!0||r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...r.stdout?eo(r.stdout):to,incomplete:!0};throw n}}function ro(t,e){let{registry:n}=e;t.post("/repos/:id/search",async({params:r,body:s,res:o})=>{let i=x(n,r.id),a=U(s,"query");try{let c=await no(i.path,a);E(o,200,c)}catch(c){if(c instanceof Me)throw new d(400,`Query must be at least ${Pe} characters`);if(c instanceof Lt)throw new d(400,c.message);throw c}})}import{Worker as cl}from"node:worker_threads";var ll=1000,ul=64,fl={status:"unavailable",reason:"deadline"},ne={status:"unavailable",reason:"error"};function hl(){let t=import.meta.url;return t.endsWith(".ts")?new URL("./symbolWorker.ts",t):new URL("./symbolWorker.js",t)}function so(t){let e=t.timeoutMs??ll,n=new Set(t.extensions),r=null,s=0,o=Promise.resolve(),i=!1,a=new Map;function c(h,p){a.delete(h),a.set(h,p);while(a.size>ul){let w=a.keys().next().value;if(w===void 0)break;a.delete(w)}}function l(){let h=r;if(r=null,h!==null)h.terminate()}function u(){let h=new cl(hl(),{workerData:{grammarDir:t.grammarDir,queryDir:t.queryDir}});return h.unref(),h}function f(h,p){return new Promise((w)=>{if(r===null)try{r=u()}catch{w(ne);return}let g=r,R=++s,_=!1,I=(b,X)=>{if(_)return;if(_=!0,clearTimeout(y),g.off("message",A),g.off("error",v),g.off("exit",m),X)l();w(b)},A=(b)=>{if(b.seq!==R)return;I(b.outcome,!1)},v=()=>I(ne,!0),m=()=>I(ne,!0),y=setTimeout(()=>I(fl,!0),e);y.unref?.(),g.on("message",A),g.on("error",v),g.on("exit",m);let S={seq:R,relPath:h,content:p};try{g.postMessage(S)}catch{I(ne,!0)}})}return{supported(h){let p=h.lastIndexOf(".");if(p<=h.lastIndexOf("/"))return!1;return n.has(h.slice(p).toLowerCase())},async extract(h,p){if(i)return ne;let w=`${h}\x00${p}`,g=a.get(w);if(g!==void 0)return c(w,g),g;let R=o.then(()=>f(h,p));o=R.catch(()=>{return});let _=await R;return c(w,_),_},async dispose(){i=!0;let h=r;if(r=null,a.clear(),h!==null)await h.terminate()}}}import{execFile as pl,spawn as dl}from"node:child_process";import*as re from"node:fs";import*as io from"node:path";import{promisify as ml}from"node:util";var gl=ml(pl);class Ct extends Error{constructor(t){super(`Not a regular blob: ${t}`);this.name="NotRegularBlobError"}}class Bt extends Error{size;constructor(t,e){super(`Blob too large: ${t} (${e} bytes)`);this.name="BlobTooLargeError",this.size=e}}class bt extends Error{constructor(t){super(`Unsafe blob path: ${t}`);this.name="UnsafeBlobPathError"}}var ao=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"],co=5000,Fe=65536,lo=/^[0-9a-f]{40}([0-9a-f]{24})?$/,wl=new Set(["100644","100755"]);function yl(t){if(t==="")throw new bt("empty");if(t.includes("\x00"))throw new bt("contains NUL");if(t.startsWith("-"))throw new bt('starts with "-"');if(t.startsWith(":"))throw new bt('starts with ":"')}async function Te(t,e,n){let{stdout:r}=await gl("git",[...ao,...e],{cwd:t,env:j(),encoding:"buffer",maxBuffer:n,timeout:co,windowsHide:!0});return r}function uo(t){let e=[],n=0;for(let r=0;r<t.length;r++){if(t[r]!==0)continue;if(r>n)e.push(t.subarray(n,r));n=r+1}if(n<t.length)e.push(t.subarray(n));return e}function fo(t,e){let n=Buffer.from(e,"utf8");for(let r of t){let s=r.indexOf(9);if(s<0)continue;if(!r.subarray(s+1).equals(n))continue;return r.subarray(0,s).toString("utf8").trim().split(/\s+/)}return null}var bl=1;async function Sl(t){let e;try{e=(await Te(t,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],Fe)).toString("utf8").trim()}catch(n){if(n?.code===bl)return null;throw n}return lo.test(e)?e:null}async function vl(t,e){let n=await Sl(t);if(n===null)return null;let r=await Te(t,["ls-tree","-z","--full-tree","-l",n,"--",e],Fe),s=fo(uo(r),e);if(s===null||s.length!==4)return null;return{mode:s[0],oid:s[2],sizeText:s[3]}}async function El(t,e){let n=await Te(t,["ls-files","--stage","-z","--",e],Fe),r=fo(uo(n),e);if(r===null||r.length!==3)return null;if(r[2]!=="0")return null;return{mode:r[0],oid:r[1],sizeText:null}}function ho(t,e){let n=Number.parseInt(t,10);if(!Number.isSafeInteger(n)||n<0)throw Error(`git reported a malformed size for ${e}`);return n}async function xl(t,e,n){let r=await Te(t,["cat-file","-s",e],Fe);return ho(r.toString("utf8").trim(),n)}var oo=Buffer.alloc(0);async function kl(t,e,n){let r=Buffer.alloc(n),s=0;while(s<n){let{bytesRead:o}=await t.read(r,s,n-s,e+s);if(o===0)break;s+=o}return s===n?r:r.subarray(0,s)}function po(t,e){let n=oo,r=!1;return{async read(s){let o=Math.max(0,Math.min(s,t));if(o>n.length&&!r){let i=await e(o,n);r=i.length<o,n=i}return n.subarray(0,Math.min(o,n.length))},release(){n=oo,r=!1}}}function Rl(t,e){let n=null,r=[],s=0,o=!1,i=null,a=null,c=!1,l=null,u=()=>o&&i!==null,f=()=>{if(r.length!==1){let g=Buffer.concat(r,s);r.length=0,r.push(g)}return r[0]};function h(){if(l===null)return;if(a===null&&u()&&i?.signal===null&&i.code!==0)a=Error(`git cat-file blob failed for ${e} (exit ${i.code??"null"})`);if(a===null&&s<l.want&&!u())return;let g=l;if(l=null,clearTimeout(g.timer),n?.stdout?.pause(),a!==null)g.reject(a);else g.resolve(f().subarray(0,Math.min(g.want,s)))}function p(g){a??=g,h()}function w(){let g=dl("git",[...ao,"cat-file","blob",e],{cwd:t,env:j(),stdio:["ignore","pipe","ignore"],windowsHide:!0});n=g,g.stdout?.on("data",(R)=>{if(c)return;r.push(R),s+=R.length,h()}),g.stdout?.on("end",()=>{o=!0,h()}),g.stdout?.on("error",p),g.on("error",p),g.on("close",(R,_)=>{i={code:R,signal:_},h()})}return{read(g){if(a!==null)return Promise.reject(a);if(c)return Promise.reject(Error(`read after close for ${e}`));if(g<=s||u())return Promise.resolve(f().subarray(0,Math.min(g,s)));if(l!==null)return Promise.reject(Error(`concurrent read of ${e}`));return new Promise((R,_)=>{let I=setTimeout(()=>{n?.kill("SIGKILL"),p(Error(`git cat-file blob timed out for ${e}`))},co);if(l={want:g,resolve:R,reject:_,timer:I},n===null)w();else n.stdout?.resume()})},release(){if(c=!0,l!==null)p(Error(`git cat-file blob closed while reading ${e}`));r.length=0,s=0,n?.kill("SIGKILL"),n=null}}}function _l(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Il(t,e,n){let r=io.join(t,e),s;try{s=await re.promises.open(r,re.constants.O_RDONLY|(re.constants.O_NONBLOCK??0))}catch(o){if(_l(o))return null;throw o}try{let o=await s.stat();if(!o.isFile())throw new Ct(e);if(o.size>n)throw new Bt(e,o.size);let i=o.size,a=po(i,async(c,l)=>{let u=await kl(s,l.length,c-l.length);return l.length===0?u:Buffer.concat([l,u])});return{oid:null,size:i,version:`${i}-${o.mtimeMs}`,read:(c)=>a.read(c),close:()=>(a.release(),s.close())}}catch(o){try{await s.close()}catch{}throw o}}async function Al(t,e,n,r){let s=e==="head"?await vl(t,n):await El(t,n);if(s===null)return null;if(!wl.has(s.mode))throw new Ct(n);if(!lo.test(s.oid))throw Error(`git reported a malformed object id for ${n}`);let o=s.oid,i=s.sizeText===null?await xl(t,o,n):ho(s.sizeText,n);if(i>r)throw new Bt(n,i);let a=Rl(t,o),c=po(i,(l)=>a.read(l));return{oid:o,size:i,version:o,read:(l)=>c.read(l),close(){return c.release(),a.release(),Promise.resolve()}}}async function mo(t,e,n,r){if(yl(n),e==="worktree")return Il(t,n,r);return Al(t,e,n,r)}var Dl=["worktree","index","head"],Pl=16,Ml=Gs,Fl=Ot,Tl=["too-large","too-many-pixels"];function go(t){let e=t.get("path");if(e===null)throw new d(400,'Missing "path" query parameter');return e}function Ol(t){let e=t.get("side");if(e===null||!Dl.includes(e))throw new d(400,'Invalid "side" (expected worktree, index or head)');return e}function $l(t){let e=t.get("staged");if(e==="1")return!0;if(e==="0")return!1;throw new d(400,'Invalid "staged" (expected 0 or 1)')}function So(t){if(t instanceof Ct)throw new d(400,t.message);if(t instanceof bt)throw new d(400,t.message);if(t instanceof Bt)throw new d(413,t.message);throw t}async function wo(t,e){let n=await t.read(e);return{bytes:n,sniff:Nt(n,t.size,n.length>=t.size)}}async function Nl(t,e){let{size:n}=t,r=await t.read(Pl),s=Nt(r,n,r.length>=n);if(!s.ok&&s.refusal==="too-large")return{bytes:r,sniff:s};let o=Math.min(De(r,n),n),i=await wo(t,Math.max(o,Math.min(e,n)));if(i.sniff.ok||i.sniff.refusal!=="header-not-found")return i;if(i.bytes.length>=n)return i;return wo(t,n)}async function vo(t,e,n,r){let s=await mo(t,e,n,Ot);if(s===null)return null;try{let{bytes:o,sniff:i}=await Nl(s,r);return{bytes:o,size:s.size,oid:s.oid,version:s.version,sniff:i}}finally{await s.close()}}function Ll(t,e,n){let r={"content-type":e,"content-disposition":"inline","x-content-type-options":"nosniff","cross-origin-resource-policy":"same-origin",vary:"sec-fetch-site, sec-fetch-dest","cache-control":t==="worktree"?"no-store":"private, no-cache"};if(t!=="worktree"&&n!==null)r.etag=`"${n}"`;return r}function Cl(t){let e=Tl.includes(t)?413:415;return new d(e,`Image not served: ${t}`)}function Bl(t,e){let n=t.originalPath??t.path;switch(t.status){case"untracked":return{old:null,new:{side:"worktree",path:t.path}};case"added":return{old:null,new:{side:e?"index":"worktree",path:t.path}};case"deleted":return{old:{side:e?"head":"index",path:n},new:null};default:return e?{old:{side:"head",path:n},new:{side:"index",path:t.path}}:{old:{side:"index",path:n},new:{side:"worktree",path:t.path}}}}function Hl(t,e,n){return{path:t.path,side:t.side,bytes:e,oid:null,image:null,refusal:n,version:""}}async function yo(t,e){let n=gt(t.path,e.path);await wt(t,n);let r;try{r=await vo(t.path,e.side,n,Ml)}catch(s){if(s instanceof Bt)return Hl(e,s.size,"too-large");if(s instanceof Ct)return null;So(s)}if(r===null)return null;return{path:e.path,side:e.side,bytes:r.size,oid:r.oid,version:r.version,image:r.sniff.ok?r.sniff.info:null,refusal:r.sniff.ok?null:r.sniff.refusal}}function Ul(t,e){return e.writableEnded||e.destroyed===!0||t.destroyed===!0}async function bo(t,e,n){let r=t.acquire();if(r===null)throw new d(503,"Too many image requests in flight");let s=await r;if(n.once("finish",s),n.once("close",s),e.once("close",s),Ul(e,n))return s(),!1;return!0}function Eo(t,e,n){let{registry:r}=e;t.get("/repos/:id/media",async({params:s,query:o,req:i,res:a})=>{let c=x(r,s.id),l=$l(o),u=gt(c.path,go(o));if(await wt(c,u),!await bo(n,i,a))return;let f=await Mt(c.manager.workingTree,u,l),h=Bl(f,l),p={old:h.old===null?null:await yo(c,h.old),new:h.new===null?null:await yo(c,h.new)};E(a,200,p)}),t.get("/repos/:id/blob",async({params:s,query:o,req:i,res:a})=>{let c=x(r,s.id),l=Jn(i);if(l)throw new d(l.status,l.message);let u=Ol(o),f=gt(c.path,go(o));if(await wt(c,f),!await bo(n,i,a))return;let h;try{h=await vo(c.path,u,f,Fl)}catch(w){So(w)}if(h===null)throw new d(404,`No such blob on side ${u}: ${f}`);if(!h.sniff.ok)throw Cl(h.sniff.refusal);let p=Ll(u,h.sniff.info.mime,h.oid);Hn(a,200,h.bytes,p)})}function xo(t,e){let{registry:n,daemonEvents:r,follow:s}=e;t.get("/events",({req:o,res:i})=>{let a=n.listRepos().map((c)=>({id:c.id,path:c.path}));r.subscribe(o,i,a)}),t.get("/follow",({res:o})=>{E(o,200,s?s.state:hs)})}import*as Mn from"node:os";import*as Ht from"node:path";function ko(t,e){let{settings:n,discovery:r,daemonEvents:s}=e;t.get("/settings",({res:o})=>{E(o,200,{...n.settings,persisted:n.persisted})}),t.put("/settings",async({body:o,res:i})=>{let a=As(o,"watchRoots"),c;try{c=ds(a)}catch(u){throw new d(400,u instanceof Error?u.message:String(u))}try{n.save({...n.settings,watchRoots:c})}catch(u){let f=u instanceof Error?u.message:String(u);throw new d(500,`Could not save settings: ${f}`)}await r.setRoots(c);let l={...n.settings,persisted:n.persisted};s.broadcast("settings-change",l),E(i,200,l)}),t.get("/discovered",({res:o})=>{E(o,200,r.state)}),t.get("/browse",async({query:o,res:i})=>{let a=o.get("path"),c=a?z(a):Mn.homedir();if(!Ht.isAbsolute(c))throw new d(400,`Path must be absolute: ${a}`);let l=Ht.resolve(c),u;try{u=await gs(l)}catch{throw new d(404,`Cannot read directory: ${l}`)}let f=Ht.dirname(l);E(i,200,{path:l,parent:f===l?null:f,home:Mn.homedir(),entries:u})}),t.post("/discovered/rescan",async({res:o})=>{E(o,200,await r.rescan())})}function Fn(t=4,e=64){let n=0,r=[];function s(){let o=!1;return()=>{if(o)return;o=!0;let i=r.shift();if(i)i(s());else n--}}return{acquire(){if(n<t)return n++,Promise.resolve(s());if(r.length>=e)return null;return new Promise((o)=>{r.push(o)})},get active(){return n},get queued(){return r.length}}}function Gl(t){if(!St.existsSync(t))return Promise.resolve(!1);return new Promise((e)=>{try{let n=_o.connect(t);n.once("connect",()=>{n.destroy(),e(!0)}),n.once("error",()=>{n.destroy(),e(!1)})}catch{e(!1)}})}function Io(t={}){let e=new un,n=new fn,r=new ln({onOpened:(m)=>n.broadcast("repo-opened",{id:m.id,path:m.path}),onClosed:(m)=>{e.closeRepo(m),n.broadcast("repo-closed",{id:m})}}),s=t.followFile?new pn(r,n,t.followFile):null,o=xs(t.updateCheck===!1?()=>Promise.resolve(null):t.fetchLatestVersion),i=new mn(t.settingsFile??null),a=new wn(n),c=new Map,l=Fn(),u=t.symbols??null,f=u===null?null:{pool:so(u),gate:Fn(1,4),extensions:u.extensions};function h(m){let y=c.get(m);if(y)return y;let S=new Ge,b={registry:r,sse:e,daemonEvents:n,follow:s,settings:i,discovery:a,apiMode:m,version:o,symbols:f,httpPort:_};if(Rs(S,b),_s(S,b),Os(S,b),Ls(S,b),Bs(S,b),Hs(S,b),m==="full")Us(S,b);return Vs(S,b),ro(S,b),Eo(S,b,l),xo(S,b),ko(S,b),c.set(m,S),S}let p=(m)=>t.apiMode??(m==="tcp"?"web":"full");s?.start(),a.setRoots(i.load().watchRoots);let w=t.webRoot?jn(t.webRoot):void 0,g=new Set,R=[];function _(){for(let m of R){let y=m.server.address();if(y!==null&&typeof y==="object")return y.port}return null}function I(m){let y=h(m),S=Ro.createServer((b,X)=>{for(let[ct,se]of Object.entries(Yn))X.setHeader(ct,se);if(Xn(S.address())){let ct=zn(b);if(ct){E(X,ct.status,{error:ct.message});return}}y.handle(b,X,w).catch(()=>X.end())});return S.on("connection",(b)=>{g.add(b),b.on("close",()=>g.delete(b))}),S}async function A(m,y){let S=m==="unix"?y.socketPath??null:null;if(S){if(await Gl(S))throw Error(`diffstalkerd already running at ${S}`);St.rmSync(S,{force:!0})}let b={server:I(p(m)),socketPath:S};R.push(b),await new Promise((X,ct)=>{let se=(Lo)=>ct(Lo);b.server.once("error",se);let $e=()=>{if(b.server.removeListener("error",se),S)St.chmodSync(S,384);X()};if(m==="fd")b.server.listen({fd:y.fd},$e);else if(S)process.umask(63),b.server.listen(S,$e);else b.server.listen(y.port,"127.0.0.1",$e)})}function v(m){return new Promise((y,S)=>{m.server.close((b)=>{if(m.socketPath)St.rmSync(m.socketPath,{force:!0});if(b&&b.code!=="ERR_SERVER_NOT_RUNNING")S(b);else y()})})}return{address(){return R[0]?.server.address()??null},addresses(){return R.map((m)=>m.server.address()).filter((m)=>m!==null)},getRepo(m){return r.getRepo(m)},async openRepo(m){let{handle:y}=await Re(r,m);return{id:y.id,path:y.path}},async listen(m){let y=[];if(m.fd!==void 0)y.push("fd");if(m.socketPath)y.push("unix");if(m.port!==void 0)y.push("tcp");if(y.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let S of y)await A(S,m)},close(){s?.dispose(),a.dispose(),e.destroy(),n.destroy(),r.disposeAll();for(let y of g)y.destroy();let m=f?.pool.dispose()??Promise.resolve();return Promise.all([m,...R.splice(0).map(v)]).then(()=>{})}}}import*as Tn from"node:fs";import*as Ut from"node:path";import*as To from"node:crypto";import{createRequire as Wl}from"node:module";var Ao=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 Do(){return[...Ao.keys()]}function jl(t){let e=t.slice(t.lastIndexOf("/")+1),n=e.lastIndexOf(".");if(n<=0)return"";return e.slice(n).toLowerCase()}function Po(t){return Ao.get(jl(t))??null}var ql="diffstalkerd-grammars";function Xl(t){return To.createHash("sha256").update(t).digest("hex")}function zl(t){try{let e=JSON.parse(Tn.readFileSync(Ut.join(t,"checksums.json"),"utf8"));if(typeof e.webTreeSitterVersion!=="string"||typeof e.files!=="object")return null;return e}catch{return null}}var Mo="0.26.11";function Jl(t,e,n){for(let[r,s]of Object.entries(e.files)){let o;try{o=Tn.readFileSync(Ut.join(t,r))}catch{return n(`grammars: missing ${r}`),!1}if(Xl(o)!==s)return n(`grammars: checksum mismatch for ${r}`),!1}return!0}function Yl(t){let e=new Set;for(let n of Object.keys(t.files)){let r=/^tree-sitter-(.+)\.wasm$/.exec(n);if(r!==null&&t.files[`queries/${r[1]}.scm`]!==void 0)e.add(r[1])}return e}function Fo(t,e=()=>{}){let n=zl(t);if(n===null)return e(`grammars: no readable checksums.json in ${t}`),null;if(n.webTreeSitterVersion!==Mo)return e(`grammars: built for web-tree-sitter ${n.webTreeSitterVersion}, this daemon bundles ${Mo} — symbols disabled`),null;if(!Jl(t,n,e))return null;let r=Yl(n),s=Do().filter((o)=>{let i=Po(`x${o}`);return i!==null&&r.has(i.grammar)});if(s.length===0)return e("grammars: no usable grammar found"),null;return{grammarDir:t,queryDir:Ut.join(t,"queries"),extensions:s}}function Oo(t,e=()=>{}){if(t!==null)return Fo(t,e);try{let r=Wl(import.meta.url).resolve(`${ql}/checksums.json`);return Fo(Ut.dirname(r),e)}catch{return null}}var No="diffstalkerd.sock";function Vl(t){return t===void 0?No:`${t}.sock`}var Ql=3,$o=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
54
54
 
55
55
  Usage: diffstalkerd [options] [REPO_PATH...]
56
56
 
@@ -80,6 +80,6 @@ Options:
80
80
  then reports the running version only
81
81
  --version, -v Print the running version and exit
82
82
  --help, -h Show this help
83
- `;function Gt(t,e,n){let r=t[e];if(r===void 0||r.startsWith("--"))throw Error(`${n} requires a value`);return r}function Wl(t,e){if(e.startsWith("-"))throw Error(`Unknown argument: ${e}`);if(e==="")throw Error("Empty repo path argument");t.repoPaths??=[],t.repoPaths.push(e)}function ql(t){let e={};for(let n=0;n<t.length;n++){let r=t[n];switch(r){case"--help":case"-h":return"help";case"--version":case"-v":return"version";case"--socket":e.socketPath=Gt(t,++n,"--socket");break;case"--instance":e.instance=Gt(t,++n,"--instance");break;case"--no-socket":e.noSocket=!0;break;case"--port":if(e.port=Number(Gt(t,++n,"--port")),!Number.isInteger(e.port)||e.port<0)throw Error("--port requires a non-negative integer");break;case"--follow-file":e.followFile=Gt(t,++n,"--follow-file");break;case"--no-follow":e.noFollow=!0;break;case"--web-root":e.webRoot=Gt(t,++n,"--web-root");break;case"--grammars":e.grammarsDir=Gt(t,++n,"--grammars");break;case"--no-update-check":e.noUpdateCheck=!0;break;default:Wl(e,r);break}}if(e.socketPath!==void 0&&e.noSocket)throw Error("--socket and --no-socket are mutually exclusive");if(e.noSocket&&e.port===void 0)throw Error("--no-socket requires --port (nothing would be listening)");if(e.followFile!==void 0&&e.noFollow)throw Error("--follow-file and --no-follow are mutually exclusive");return e}function Xl(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function zl(t){if(t.noSocket||t.socketPath!==void 0)return;if(Xl()){t.fd=jl;return}let e=Ln();if(!e){if(t.port!==void 0){console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set; binding the TCP port only.
83
+ `;function Gt(t,e,n){let r=t[e];if(r===void 0||r.startsWith("--"))throw Error(`${n} requires a value`);return r}function Zl(t,e){if(e.startsWith("-"))throw Error(`Unknown argument: ${e}`);if(e==="")throw Error("Empty repo path argument");t.repoPaths??=[],t.repoPaths.push(e)}function tu(t){let e={};for(let n=0;n<t.length;n++){let r=t[n];switch(r){case"--help":case"-h":return"help";case"--version":case"-v":return"version";case"--socket":e.socketPath=Gt(t,++n,"--socket");break;case"--instance":e.instance=Gt(t,++n,"--instance");break;case"--no-socket":e.noSocket=!0;break;case"--port":if(e.port=Number(Gt(t,++n,"--port")),!Number.isInteger(e.port)||e.port<0)throw Error("--port requires a non-negative integer");break;case"--follow-file":e.followFile=Gt(t,++n,"--follow-file");break;case"--no-follow":e.noFollow=!0;break;case"--web-root":e.webRoot=Gt(t,++n,"--web-root");break;case"--grammars":e.grammarsDir=Gt(t,++n,"--grammars");break;case"--no-update-check":e.noUpdateCheck=!0;break;default:Zl(e,r);break}}if(e.socketPath!==void 0&&e.noSocket)throw Error("--socket and --no-socket are mutually exclusive");if(e.noSocket&&e.port===void 0)throw Error("--no-socket requires --port (nothing would be listening)");if(e.followFile!==void 0&&e.noFollow)throw Error("--follow-file and --no-follow are mutually exclusive");return e}function eu(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function nu(t){if(t.noSocket||t.socketPath!==void 0)return;if(eu()){t.fd=Ql;return}let e=Nn();if(!e){if(t.port!==void 0){console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set; binding the TCP port only.
84
84
  Pass --socket PATH to also accept CLI connections.`);return}console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set and no --socket/--port given.
85
- Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}Te.mkdirSync(e,{recursive:!0,mode:448}),t.socketPath=Ut.join(e,Ul(t.instance))}function Jl(t){let e=t??Gl(new URL("web/",import.meta.url));if(Te.existsSync(e))return e;console.error(`diffstalkerd: web UI assets not found at ${e}; serving API only`);return}function Yl(t){console.error(`diffstalkerd: web UI at http://diffstalker.localhost:${t}/`)}async function Kl(t,e){for(let n of e){let r=Ut.resolve(z(n));try{let s=await t.openRepo(r);console.error(`diffstalkerd opened ${s.path}`)}catch(s){console.error(`diffstalkerd: cannot open ${r}: ${s instanceof Error?s.message:String(s)}`),await t.close().catch(()=>{}),process.exit(1)}}}async function Vl(){process.title="diffstalkerd";let t;try{t=ql(process.argv.slice(2))}catch(u){console.error(u instanceof Error?u.message:String(u)),console.error(Lo),process.exit(2)}if(t==="help"){console.log(Lo);return}if(t==="version"){let u=yn();if(u===null)console.error("diffstalkerd: version unknown (package.json unreadable)"),process.exit(1);console.log(u);return}zl(t);let e=t.noFollow?void 0:t.followFile??Ut.join(vt(),"target"),n=Jl(t.webRoot),r=$o(t.grammarsDir??process.env.DIFFSTALKER_GRAMMARS_DIR??null,(u)=>console.error(`diffstalkerd: ${u}`)),s=Io({followFile:e,settingsFile:Ut.join($n(),"daemon.json"),webRoot:n,symbols:r,updateCheck:!t.noUpdateCheck});await Kl(s,t.repoPaths??[]),await s.listen(t);let i=s.addresses().find((u)=>typeof u!=="string")?.port??t.port;if(t.fd!==void 0)console.error(`diffstalkerd listening on inherited socket (fd ${t.fd})`);if(t.socketPath)console.error(`diffstalkerd listening on unix socket ${t.socketPath}`);if(i!==void 0)console.error(`diffstalkerd listening on 127.0.0.1:${i}`);if(e)console.error(`diffstalkerd following ${e}`);if(n){if(console.error(`diffstalkerd serving web UI from ${n}`),i!==void 0)Yl(i)}let a=!1,c=(u)=>{if(a)return;a=!0,console.error(`Received ${u}, shutting down`),s.close().then(()=>process.exit(0)).catch((f)=>{console.error(f instanceof Error?f.message:String(f)),process.exit(1)})};process.on("SIGINT",()=>c("SIGINT")),process.on("SIGTERM",()=>c("SIGTERM")),process.on("SIGHUP",()=>c("SIGHUP"));let l=(u,f)=>{console.error(`diffstalkerd ${u}:`,f instanceof Error?f.stack??f.message:f),s.close().catch(()=>{}).finally(()=>process.exit(1))};process.on("uncaughtException",(u)=>l("uncaught exception",u)),process.on("unhandledRejection",(u)=>l("unhandled rejection",u))}Vl().catch((t)=>{console.error(t instanceof Error?t.message:String(t)),process.exit(1)});export{ql as parseArgs};
85
+ Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}Oe.mkdirSync(e,{recursive:!0,mode:448}),t.socketPath=jt.join(e,Vl(t.instance))}function ru(t){let e=t??Kl(new URL("web/",import.meta.url));if(Oe.existsSync(e))return e;console.error(`diffstalkerd: web UI assets not found at ${e}; serving API only`);return}function su(t){console.error(`diffstalkerd: web UI at http://diffstalker.localhost:${t}/`)}async function ou(t,e){for(let n of e){let r=jt.resolve(z(n));try{let s=await t.openRepo(r);console.error(`diffstalkerd opened ${s.path}`)}catch(s){console.error(`diffstalkerd: cannot open ${r}: ${s instanceof Error?s.message:String(s)}`),await t.close().catch(()=>{}),process.exit(1)}}}async function iu(){process.title="diffstalkerd";let t;try{t=tu(process.argv.slice(2))}catch(u){console.error(u instanceof Error?u.message:String(u)),console.error($o),process.exit(2)}if(t==="help"){console.log($o);return}if(t==="version"){let u=yn();if(u===null)console.error("diffstalkerd: version unknown (package.json unreadable)"),process.exit(1);console.log(u);return}nu(t);let e=t.noFollow?void 0:t.followFile??jt.join(Et(),"target"),n=ru(t.webRoot),r=Oo(t.grammarsDir??process.env.DIFFSTALKER_GRAMMARS_DIR??null,(u)=>console.error(`diffstalkerd: ${u}`)),s=Io({followFile:e,settingsFile:jt.join($n(),"daemon.json"),webRoot:n,symbols:r,updateCheck:!t.noUpdateCheck});await ou(s,t.repoPaths??[]),await s.listen(t);let i=s.addresses().find((u)=>typeof u!=="string")?.port??t.port;if(t.fd!==void 0)console.error(`diffstalkerd listening on inherited socket (fd ${t.fd})`);if(t.socketPath)console.error(`diffstalkerd listening on unix socket ${t.socketPath}`);if(i!==void 0)console.error(`diffstalkerd listening on 127.0.0.1:${i}`);if(e)console.error(`diffstalkerd following ${e}`);if(n){if(console.error(`diffstalkerd serving web UI from ${n}`),i!==void 0)su(i)}let a=!1,c=(u)=>{if(a)return;a=!0,console.error(`Received ${u}, shutting down`),s.close().then(()=>process.exit(0)).catch((f)=>{console.error(f instanceof Error?f.message:String(f)),process.exit(1)})};process.on("SIGINT",()=>c("SIGINT")),process.on("SIGTERM",()=>c("SIGTERM")),process.on("SIGHUP",()=>c("SIGHUP"));let l=(u,f)=>{console.error(`diffstalkerd ${u}:`,f instanceof Error?f.stack??f.message:f),s.close().catch(()=>{}).finally(()=>process.exit(1))};process.on("uncaughtException",(u)=>l("uncaught exception",u)),process.on("unhandledRejection",(u)=>l("unhandled rejection",u))}iu().catch((t)=>{console.error(t instanceof Error?t.message:String(t)),process.exit(1)});export{tu as parseArgs};