diffstalkerd 0.13.9 → 0.13.11

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,51 +1,52 @@
1
- var Ci=Object.create;var{getPrototypeOf:Li,defineProperty:cr,getOwnPropertyNames:Hi}=Object;var lr=Object.prototype.hasOwnProperty;function Bi(t){return this[t]}var ji,Wi,Gi=(t,e,n)=>{var r=t!=null&&typeof t==="object";if(r){var s=e?ji??=new WeakMap:Wi??=new WeakMap,o=s.get(t);if(o)return o}n=t!=null?Ci(Li(t)):{};let i=e||!t||!t.__esModule||!lr.call(t,"default")?cr(n,"default",{value:t,enumerable:!0}):n;if(t&&typeof t==="object"||typeof t==="function"){for(let a of Hi(t))if(!lr.call(i,a))cr(i,a,{get:Bi.bind(t,a),enumerable:!0})}if(r)s.set(t,i);return i};var Ui=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Us=Ui(function(ph,Gs){var B=-1,L=1,M=0;function ce(t,e,n,r,s){if(t===e){if(t)return[[M,t]];return[]}if(n!=null){var o=uc(t,e,n);if(o)return o}var i=_n(t,e),a=t.substring(0,i);t=t.substring(i),e=e.substring(i),i=Ie(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=nc(t,e);if(a)l.unshift([M,a]);if(c)l.push([M,c]);if(An(l,s),r)oc(l);return l}function nc(t,e){var n;if(!t)return[[L,e]];if(!e)return[[B,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=[[L,r.substring(0,o)],[M,s],[L,r.substring(o+s.length)]],t.length>e.length)n[0][0]=n[2][0]=B;return n}if(s.length===1)return[[B,t],[L,e]];var i=sc(t,e);if(i){var a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],h=ce(a,l),p=ce(c,u);return h.concat([[M,f]],p)}return rc(t,e)}function rc(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,d=0,g=0;for(var R=0;R<s;R++){for(var y=-R+h;y<=R-p;y+=2){var A=o+y,I;if(y===-R||y!==R&&a[A-1]<a[A+1])I=a[A+1];else I=a[A-1]+1;var D=I-y;while(I<n&&D<r&&t.charAt(I)===e.charAt(D))I++,D++;if(a[A]=I,I>n)p+=2;else if(D>r)h+=2;else if(f){var w=o+u-y;if(w>=0&&w<i&&c[w]!==-1){var x=n-c[w];if(I>=x)return $s(t,e,I,D)}}}for(var _=-R+d;_<=R-g;_+=2){var w=o+_,x;if(_===-R||_!==R&&c[w-1]<c[w+1])x=c[w+1];else x=c[w-1]+1;var b=x-_;while(x<n&&b<r&&t.charAt(n-x-1)===e.charAt(r-b-1))x++,b++;if(c[w]=x,x>n)g+=2;else if(b>r)d+=2;else if(!f){var A=o+u-_;if(A>=0&&A<i&&a[A]!==-1){var I=a[A],D=o+I-A;if(x=n-x,I>=x)return $s(t,e,I,D)}}}}return[[B,t],[L,e]]}function $s(t,e,n,r){var s=t.substring(0,n),o=e.substring(0,r),i=t.substring(n),a=e.substring(r),c=ce(s,o),l=ce(i,a);return c.concat(l)}function _n(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(Hs(t.charCodeAt(s-1)))s--;return s}function Os(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 Ie(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(Bs(t.charCodeAt(t.length-s)))s--;return s}function sc(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,d,g){var R=p.substring(g,g+Math.floor(p.length/4)),y=-1,A="",I,D,w,x;while((y=d.indexOf(R,y+1))!==-1){var _=_n(p.substring(g),d.substring(y)),b=Ie(p.substring(0,g),d.substring(0,y));if(A.length<b+_)A=d.substring(y-b,y)+d.substring(y,y+_),I=p.substring(0,g-b),D=p.substring(g+_),w=d.substring(0,y-b),x=d.substring(y+_)}if(A.length*2>=p.length)return[I,D,w,x,A];else return null}var o=s(n,r,Math.ceil(n.length/4)),i=s(n,r,Math.ceil(n.length/2)),a;if(!o&&!i)return null;else if(!i)a=o;else if(!o)a=i;else a=o[4].length>i[4].length?o:i;var c,l,u,f;if(t.length>e.length)c=a[0],l=a[1],u=a[2],f=a[3];else u=a[0],f=a[1],c=a[2],l=a[3];var h=a[4];return[c,l,u,f,h]}function oc(t){var e=!1,n=[],r=0,s=null,o=0,i=0,a=0,c=0,l=0;while(o<t.length){if(t[o][0]==M)n[r++]=o,i=c,a=l,c=0,l=0,s=t[o][1];else{if(t[o][0]==L)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,[B,s]),t[n[r-1]+1][0]=L,r--,r--,o=r>0?n[r-1]:-1,i=0,a=0,c=0,l=0,s=null,e=!0}o++}if(e)An(t);cc(t),o=1;while(o<t.length){if(t[o-1][0]==B&&t[o][0]==L){var u=t[o-1][1],f=t[o][1],h=Os(u,f),p=Os(f,u);if(h>=p){if(h>=u.length/2||h>=f.length/2)t.splice(o,0,[M,f.substring(0,h)]),t[o-1][1]=u.substring(0,u.length-h),t[o+1][1]=f.substring(h),o++}else if(p>=u.length/2||p>=f.length/2)t.splice(o,0,[M,u.substring(0,p)]),t[o-1][0]=L,t[o-1][1]=f.substring(0,f.length-p),t[o+1][0]=B,t[o+1][1]=u.substring(p),o++;o++}o++}}var Ns=/[^a-zA-Z0-9]/,Cs=/\s/,Ls=/[\r\n]/,ic=/\n\r?\n$/,ac=/^\r?\n\r?\n/;function cc(t){function e(p,d){if(!p||!d)return 6;var g=p.charAt(p.length-1),R=d.charAt(0),y=g.match(Ns),A=R.match(Ns),I=y&&g.match(Cs),D=A&&R.match(Cs),w=I&&g.match(Ls),x=D&&R.match(Ls),_=w&&p.match(ic),b=x&&d.match(ac);if(_||b)return 5;else if(w||x)return 4;else if(y&&!I&&D)return 3;else if(I||D)return 2;else if(y||A)return 1;return 0}var n=1;while(n<t.length-1){if(t[n-1][0]==M&&t[n+1][0]==M){var r=t[n-1][1],s=t[n][1],o=t[n+1][1],i=Ie(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 An(t,e){t.push([M,""]);var n=0,r=0,s=0,o="",i="",a;while(n<t.length){if(n<t.length-1&&!t[n][1]){t.splice(n,1);continue}switch(t[n][0]){case L:s++,i+=t[n][1],n++;break;case B:r++,o+=t[n][1],n++;break;case M:var c=n-s-r-1;if(e){if(c>=0&&Ws(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]===L)s++,i=t[u][1]+i,u--;if(t[u]&&t[u][0]===B)r++,o=t[u][1]+o,u--;c=u}}if(js(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=_n(i,o),a!==0){if(c>=0)t[c][1]+=i.substring(0,a);else t.splice(0,0,[M,i.substring(0,a)]),n++;i=i.substring(a),o=o.substring(a)}if(a=Ie(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,[L,i]),n=n-f+1;else if(i.length===0)t.splice(n-f,f,[B,o]),n=n-f+1;else t.splice(n-f,f,[B,o],[L,i]),n=n-f+2}if(n!==0&&t[n-1][0]===M)t[n-1][1]+=t[n][1],t.splice(n,1);else n++;s=0,r=0,o="",i="";break}}if(t[t.length-1][1]==="")t.pop();var h=!1;n=1;while(n<t.length-1){if(t[n-1][0]===M&&t[n+1][0]===M){if(t[n][1].substring(t[n][1].length-t[n-1][1].length)===t[n-1][1])t[n][1]=t[n-1][1]+t[n][1].substring(0,t[n][1].length-t[n-1][1].length),t[n+1][1]=t[n-1][1]+t[n+1][1],t.splice(n-1,1),h=!0;else if(t[n][1].substring(0,t[n+1][1].length)==t[n+1][1])t[n-1][1]+=t[n+1][1],t[n][1]=t[n][1].substring(t[n+1][1].length)+t[n+1][1],t.splice(n+1,1),h=!0}n++}if(h)An(t,e)}function Hs(t){return t>=55296&&t<=56319}function Bs(t){return t>=56320&&t<=57343}function js(t){return Bs(t.charCodeAt(0))}function Ws(t){return Hs(t.charCodeAt(t.length-1))}function lc(t){var e=[];for(var n=0;n<t.length;n++)if(t[n][1].length>0)e.push(t[n]);return e}function Rn(t,e,n,r){if(Ws(t)||js(r))return null;return lc([[M,t],[B,e],[L,n],[M,r]])}function uc(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 d=Math.min(a,f),g=c.slice(0,d),R=h.slice(0,d);if(g!==R)break t;var y=c.slice(d),A=h.slice(d);return Rn(g,y,A,l)}t:{if(u!==null&&u!==a)break t;var I=a,h=e.slice(0,I),p=e.slice(I);if(h!==c)break t;var D=Math.min(o-I,i-I),w=l.slice(l.length-D),x=p.slice(p.length-D);if(w!==x)break t;var y=l.slice(0,l.length-D),A=p.slice(0,p.length-D);return Rn(c,y,A,w)}}if(r.length>0&&s&&s.length===0)t:{var g=t.slice(0,r.index),w=t.slice(r.index+r.length),d=g.length,D=w.length;if(i<d+D)break t;var R=e.slice(0,d),x=e.slice(i-D);if(g!==R||w!==x)break t;var y=t.slice(d,o-D),A=e.slice(d,i-D);return Rn(g,y,A,w)}return null}function De(t,e,n,r){return ce(t,e,n,r,!0)}De.INSERT=L;De.DELETE=B;De.EQUAL=M;Gs.exports=De});import*as Ke from"node:fs";import*as Vt from"node:path";import{fileURLToPath as sf}from"node:url";import*as Ve from"node:os";import*as vt from"node:path";var Qe="diffstalker";function Ze(){return process.env.XDG_CONFIG_HOME||vt.join(Ve.homedir(),".config")}function ur(){return vt.join(Ze(),Qe)}function kt(){return vt.join(process.env.XDG_CACHE_HOME||vt.join(Ve.homedir(),".cache"),Qe)}function fr(){return process.env.XDG_RUNTIME_DIR?vt.join(process.env.XDG_RUNTIME_DIR,Qe):null}import*as me from"node:fs";import*as ge from"node:path";import*as tn from"node:os";function K(t){if(t.startsWith("~/"))return ge.join(tn.homedir(),t.slice(2));if(t==="~")return tn.homedir();return t}function we(t){let e=ge.dirname(t);if(!me.existsSync(e))me.mkdirSync(e,{recursive:!0})}function en(t){let e=t.split(`
2
- `);for(let n=e.length-1;n>=0;n--){let r=e[n].trim();if(r)return r}return""}var hr=!1;function dr(t){hr=t}function pr(t){let e="";for(let n of t){let r=n.charCodeAt(0);if(r>=32&&r!==127)e+=n;else if(n===`
3
- `)e+="\\n";else if(n==="\r")e+="\\r";else if(n==="\t")e+="\\t";else e+=`\\x${r.toString(16).padStart(2,"0")}`}return e}var qi=/(\w+:\/\/)[^/\s@]+@/g;function Xi(t){return t.replace(qi,"$1***@")}function zi(t){if(!t)return"";let e=[];for(let[n,r]of Object.entries(t)){if(r===void 0)continue;let s=pr(String(r));e.push(`${n}=${/\s/.test(s)||s===""?JSON.stringify(s):s}`)}return e.length===0?"":` ${e.join(" ")}`}function Ji(t){if(t instanceof Error)return`${t.name}: ${t.message}`;return String(t)}function nn(t,e={stacks:!0}){let n=[],r=t;for(let s=0;s<10&&r!==void 0&&r!==null;s++){let o=s===0?"":"caused by: ",i=e.stacks&&r instanceof Error&&r.stack?r.stack:Ji(r);n.push(o+i),r=r instanceof Error?r.cause:void 0}return n.join(`
4
- `)}function rn(t,e,n,r){let s=`${new Date().toISOString()} ${t.padEnd(5)} ${pr(e)}${zi(n)}`,o=r?`
5
- ${r.replace(/^/gm," ")}`:"";process.stderr.write(Xi(`${s}${o}
6
- `))}function H(t,e,n){if(!hr)return;rn("debug",t,n,e===void 0?void 0:nn(e,{stacks:!1}))}function v(t,e,n){rn("warn",t,n,e===void 0?void 0:nn(e,{stacks:!1}))}function T(t,e,n){rn("error",t,n,e===void 0?void 0:nn(e))}import*as ki from"node:http";import*as xt from"node:fs";import*as Ri from"node:net";function sn(t){let e={};for(let[n,r]of t)e[n]=r;return e}function Ki(t){if(!t)return null;return{staged:sn(t.staged),unstaged:sn(t.unstaged)}}function at(t){return{status:t.status,hunkCounts:Ki(t.hunkCounts),error:t.error,stashList:t.stashList,operationInProgress:t.operationInProgress,mtimes:t.mtimes?sn(t.mtimes):null}}function Yi(t){return t.entries.length>0?t.entries[0].seq-1:t.nextSeq-1}function mr(t,e){let n=e>0?t.entries.filter((r)=>r.seq>e):t.entries;return{epoch:t.epoch,prunedBefore:Yi(t),entries:n}}function Qt(t){if(t instanceof Date)return t.toISOString();if(t instanceof Map){let e={};for(let[n,r]of t)e[String(n)]=Qt(r);return e}if(Array.isArray(t))return t.map(Qt);if(t!==null&&typeof t==="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=Qt(r);return e}return t}var Vi=1048576;class m extends Error{status;constructor(t,e,n){super(e,n);this.status=t,this.name="HttpError"}}function E(t,e,n){let r=JSON.stringify(Qt(n));t.writeHead(e,{"content-type":"application/json"}),t.end(r)}function gr(t,e,n,r){t.writeHead(e,{...r,"content-length":String(n.byteLength)}),t.end(n)}function Qi(t,e){if(t.segments.length!==e.length)return null;let n={};for(let r=0;r<t.segments.length;r++){let s=t.segments[r];if(s.startsWith(":"))try{n[s.slice(1)]=decodeURIComponent(e[r])}catch{throw new m(400,`Malformed percent-encoding in path: ${e[r]}`)}else if(s!==e[r])return null}return n}async function Zi(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>Vi)throw new m(413,"Request body too large");e.push(o)}let r=Buffer.concat(e).toString("utf-8");if(!r.trim())return;try{return JSON.parse(r)}catch{throw new m(400,"Invalid JSON body")}}class on{routes=[];get(t,e){this.add("GET",t,e)}post(t,e){this.add("POST",t,e)}put(t,e){this.add("PUT",t,e)}delete(t,e){this.add("DELETE",t,e)}add(t,e,n){this.routes.push({method:t,segments:e.split("/").filter(Boolean),handler:n})}match(t,e){for(let n of this.routes){if(n.method!==t)continue;let r=Qi(n,e);if(r)return{handler:n.handler,params:r}}return null}async handle(t,e,n){try{let r=new URL(t.url??"/","http://localhost"),s=r.pathname.split("/").filter(Boolean),o=t.method??"GET",i=this.match(o,s);if(!i){if(n&&o==="GET"){await n(t,e,r.pathname);return}throw new m(404,`Unknown route: ${o} ${r.pathname}`)}let a=await Zi(t);await i.handler({req:t,res:e,params:i.params,query:r.searchParams,body:a})}catch(r){let s=`${t.method??"GET"} ${t.url??"/"}`;if(e.headersSent){T(`${s} failed after the response headers were sent`,r),e.end();return}if(r instanceof m){ta(s,r),E(e,r.status,{error:r.message});return}T(`${s} -> 500`,r),E(e,500,{error:"Internal server error"})}}}function ta(t,e){let n=`${t} -> ${e.status} ${e.message}`;if(e.cause!==void 0||e.status>=500)v(n,e.cause);else H(n)}import*as an from"node:fs";import*as X from"node:path";var ea=new Set(["health","version","repos","resolve","worktrees","events","follow","settings","discovered","browse"]),na={".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"},wr="no-cache",ra="public, max-age=31536000, immutable";async function yr(t,e,n){let r;try{r=await an.promises.readFile(e)}catch(s){throw new m(404,`Not found: ${X.basename(e)}`,{cause:s})}t.writeHead(200,{"content-type":na[X.extname(e)]??"application/octet-stream","cache-control":n,"content-length":r.length}),t.end(r)}function br(t){let e=X.resolve(t);return async(n,r,s)=>{let o;try{o=decodeURIComponent(s)}catch{throw new m(400,`Malformed percent-encoding in path: ${s}`)}if(o.includes("\x00"))throw new m(400,"Invalid path");let i=o.split("/").filter(Boolean);if(i.length>0&&ea.has(i[0]))throw new m(404,`Unknown route: GET ${s}`);let a=i.length>0?X.resolve(e,i.join("/")):e;if(a!==e&&!a.startsWith(e+X.sep))throw new m(403,"Forbidden");if((await an.promises.stat(a).catch(()=>null))?.isFile()){await yr(r,a,i[0]==="assets"?ra:wr);return}await yr(r,X.join(e,"index.html"),wr)}}function sa(t){try{let e=new URL(`http://${t}`).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function oa(t){try{let e=new URL(t).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function Sr(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 ia(t){return t.length>10&&t.endsWith(".localhost")}function Er(t){return t==="localhost"||t==="::1"||ia(t)||Sr(t)}function aa(t){return t==="::1"||Sr(t)}function xr(t){if(t===null)return!1;if(typeof t==="string")return!0;return aa(t.address)}function vr(t){let e=t.headers.host;if(e!==void 0){let i=sa(e);if(i===null||!Er(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=oa(o);if(i===null||!Er(i))return{status:403,message:"Cross-origin request blocked"}}return null}function kr(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 Rr={"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 Oc}from"node:crypto";class _r{repoPath;queue=[];isProcessing=!1;pendingMutations=0;refreshScheduled=!1;constructor(t){this.repoPath=t}enqueue(t){return new Promise((e,n)=>{this.queue.push({execute:t,resolve:e,reject:n}),this.processNext()})}enqueueMutation(t){return this.pendingMutations++,this.enqueue(t).finally(()=>{this.pendingMutations--})}hasPendingMutations(){return this.pendingMutations>0}scheduleRefresh(t){if(this.pendingMutations>0)return;if(this.refreshScheduled)return;this.refreshScheduled=!0,this.enqueue(async()=>{this.refreshScheduled=!1,await t()}).catch((e)=>{T("Scheduled refresh threw",e,{repo:this.repoPath}),this.refreshScheduled=!1})}isBusy(){return this.isProcessing||this.queue.length>0}async processNext(){if(this.isProcessing||this.queue.length===0)return;this.isProcessing=!0;let t=this.queue.shift();try{let e=await t.execute();t.resolve(e)}catch(e){t.reject(e instanceof Error?e:Error(String(e)))}finally{this.isProcessing=!1,this.processNext()}}}var cn=new Map;function Ar(t){let e=cn.get(t);if(!e)e=new _r(t),cn.set(t,e);return e}function Ir(t){cn.delete(t)}import*as F from"node:path";import*as G from"node:fs";import{execFileSync as hc}from"node:child_process";import{watch as Xs}from"chokidar";import{EventEmitter as dc}from"node:events";import zs from"ignore";import{execFile as da}from"node:child_process";import{promisify as pa}from"node:util";import{simpleGit as ma}from"simple-git";import*as Y from"node:fs";import*as te from"node:path";import{execFileSync as ca}from"node:child_process";var la=[["*.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 ua(){return`# Generated by diffstalker: turns on git's built-in funcname drivers.
1
+ var qi=Object.create;var{getPrototypeOf:Xi,defineProperty:hr,getOwnPropertyNames:zi}=Object;var dr=Object.prototype.hasOwnProperty;function Ji(t){return this[t]}var Ki,Yi,Vi=(t,e,n)=>{var r=t!=null&&typeof t==="object";if(r){var s=e?Ki??=new WeakMap:Yi??=new WeakMap,o=s.get(t);if(o)return o}n=t!=null?qi(Xi(t)):{};let i=e||!t||!t.__esModule||!dr.call(t,"default")?hr(n,"default",{value:t,enumerable:!0}):n;if(t&&typeof t==="object"||typeof t==="function"){for(let a of zi(t))if(!dr.call(i,a))hr(i,a,{get:Ji.bind(t,a),enumerable:!0})}if(r)s.set(t,i);return i};var Qi=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ys=Qi(function(Lh,Ks){var H=-1,O=1,M=0;function le(t,e,n,r,s){if(t===e){if(t)return[[M,t]];return[]}if(n!=null){var o=_c(t,e,n);if(o)return o}var i=Dn(t,e),a=t.substring(0,i);t=t.substring(i),e=e.substring(i),i=De(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=yc(t,e);if(a)l.unshift([M,a]);if(c)l.push([M,c]);if(Pn(l,s),r)Sc(l);return l}function yc(t,e){var n;if(!t)return[[O,e]];if(!e)return[[H,t]];var r=t.length>e.length?t:e,s=t.length>e.length?e:t,o=r.indexOf(s);if(o!==-1){if(n=[[O,r.substring(0,o)],[M,s],[O,r.substring(o+s.length)]],t.length>e.length)n[0][0]=n[2][0]=H;return n}if(s.length===1)return[[H,t],[O,e]];var i=Ec(t,e);if(i){var a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],h=le(a,l),d=le(c,u);return h.concat([[M,f]],d)}return bc(t,e)}function bc(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,d=0,p=0,g=0;for(var S=0;S<s;S++){for(var y=-S+h;y<=S-d;y+=2){var A=o+y,I;if(y===-S||y!==S&&a[A-1]<a[A+1])I=a[A+1];else I=a[A-1]+1;var D=I-y;while(I<n&&D<r&&t.charAt(I)===e.charAt(D))I++,D++;if(a[A]=I,I>n)d+=2;else if(D>r)h+=2;else if(f){var w=o+u-y;if(w>=0&&w<i&&c[w]!==-1){var k=n-c[w];if(I>=k)return Hs(t,e,I,D)}}}for(var _=-S+p;_<=S-g;_+=2){var w=o+_,k;if(_===-S||_!==S&&c[w-1]<c[w+1])k=c[w+1];else k=c[w-1]+1;var b=k-_;while(k<n&&b<r&&t.charAt(n-k-1)===e.charAt(r-b-1))k++,b++;if(c[w]=k,k>n)g+=2;else if(b>r)p+=2;else if(!f){var A=o+u-_;if(A>=0&&A<i&&a[A]!==-1){var I=a[A],D=o+I-A;if(k=n-k,I>=k)return Hs(t,e,I,D)}}}}return[[H,t],[O,e]]}function Hs(t,e,n,r){var s=t.substring(0,n),o=e.substring(0,r),i=t.substring(n),a=e.substring(r),c=le(s,o),l=le(i,a);return c.concat(l)}function Dn(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(qs(t.charCodeAt(s-1)))s--;return s}function Ws(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 De(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(Xs(t.charCodeAt(t.length-s)))s--;return s}function Ec(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(d,p,g){var S=d.substring(g,g+Math.floor(d.length/4)),y=-1,A="",I,D,w,k;while((y=p.indexOf(S,y+1))!==-1){var _=Dn(d.substring(g),p.substring(y)),b=De(d.substring(0,g),p.substring(0,y));if(A.length<b+_)A=p.substring(y-b,y)+p.substring(y,y+_),I=d.substring(0,g-b),D=d.substring(g+_),w=p.substring(0,y-b),k=p.substring(y+_)}if(A.length*2>=d.length)return[I,D,w,k,A];else return null}var o=s(n,r,Math.ceil(n.length/4)),i=s(n,r,Math.ceil(n.length/2)),a;if(!o&&!i)return null;else if(!i)a=o;else if(!o)a=i;else a=o[4].length>i[4].length?o:i;var c,l,u,f;if(t.length>e.length)c=a[0],l=a[1],u=a[2],f=a[3];else u=a[0],f=a[1],c=a[2],l=a[3];var h=a[4];return[c,l,u,f,h]}function Sc(t){var e=!1,n=[],r=0,s=null,o=0,i=0,a=0,c=0,l=0;while(o<t.length){if(t[o][0]==M)n[r++]=o,i=c,a=l,c=0,l=0,s=t[o][1];else{if(t[o][0]==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,[H,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)Pn(t);kc(t),o=1;while(o<t.length){if(t[o-1][0]==H&&t[o][0]==O){var u=t[o-1][1],f=t[o][1],h=Ws(u,f),d=Ws(f,u);if(h>=d){if(h>=u.length/2||h>=f.length/2)t.splice(o,0,[M,f.substring(0,h)]),t[o-1][1]=u.substring(0,u.length-h),t[o+1][1]=f.substring(h),o++}else if(d>=u.length/2||d>=f.length/2)t.splice(o,0,[M,u.substring(0,d)]),t[o-1][0]=O,t[o-1][1]=f.substring(0,f.length-d),t[o+1][0]=H,t[o+1][1]=u.substring(d),o++;o++}o++}}var js=/[^a-zA-Z0-9]/,Us=/\s/,Gs=/[\r\n]/,vc=/\n\r?\n$/,xc=/^\r?\n\r?\n/;function kc(t){function e(d,p){if(!d||!p)return 6;var g=d.charAt(d.length-1),S=p.charAt(0),y=g.match(js),A=S.match(js),I=y&&g.match(Us),D=A&&S.match(Us),w=I&&g.match(Gs),k=D&&S.match(Gs),_=w&&d.match(vc),b=k&&p.match(xc);if(_||b)return 5;else if(w||k)return 4;else if(y&&!I&&D)return 3;else if(I||D)return 2;else if(y||A)return 1;return 0}var n=1;while(n<t.length-1){if(t[n-1][0]==M&&t[n+1][0]==M){var r=t[n-1][1],s=t[n][1],o=t[n+1][1],i=De(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 Pn(t,e){t.push([M,""]);var n=0,r=0,s=0,o="",i="",a;while(n<t.length){if(n<t.length-1&&!t[n][1]){t.splice(n,1);continue}switch(t[n][0]){case O:s++,i+=t[n][1],n++;break;case H:r++,o+=t[n][1],n++;break;case M:var c=n-s-r-1;if(e){if(c>=0&&Js(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]===H)r++,o=t[u][1]+o,u--;c=u}}if(zs(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=Dn(i,o),a!==0){if(c>=0)t[c][1]+=i.substring(0,a);else t.splice(0,0,[M,i.substring(0,a)]),n++;i=i.substring(a),o=o.substring(a)}if(a=De(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,[H,o]),n=n-f+1;else t.splice(n-f,f,[H,o],[O,i]),n=n-f+2}if(n!==0&&t[n-1][0]===M)t[n-1][1]+=t[n][1],t.splice(n,1);else n++;s=0,r=0,o="",i="";break}}if(t[t.length-1][1]==="")t.pop();var h=!1;n=1;while(n<t.length-1){if(t[n-1][0]===M&&t[n+1][0]===M){if(t[n][1].substring(t[n][1].length-t[n-1][1].length)===t[n-1][1])t[n][1]=t[n-1][1]+t[n][1].substring(0,t[n][1].length-t[n-1][1].length),t[n+1][1]=t[n-1][1]+t[n+1][1],t.splice(n-1,1),h=!0;else if(t[n][1].substring(0,t[n+1][1].length)==t[n+1][1])t[n-1][1]+=t[n+1][1],t[n][1]=t[n][1].substring(t[n+1][1].length)+t[n+1][1],t.splice(n+1,1),h=!0}n++}if(h)Pn(t,e)}function qs(t){return t>=55296&&t<=56319}function Xs(t){return t>=56320&&t<=57343}function zs(t){return Xs(t.charCodeAt(0))}function Js(t){return qs(t.charCodeAt(t.length-1))}function Rc(t){var e=[];for(var n=0;n<t.length;n++)if(t[n][1].length>0)e.push(t[n]);return e}function In(t,e,n,r){if(Js(t)||zs(r))return null;return Rc([[M,t],[H,e],[O,n],[M,r]])}function _c(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),d=e.slice(f);if(d!==l)break t;var p=Math.min(a,f),g=c.slice(0,p),S=h.slice(0,p);if(g!==S)break t;var y=c.slice(p),A=h.slice(p);return In(g,y,A,l)}t:{if(u!==null&&u!==a)break t;var I=a,h=e.slice(0,I),d=e.slice(I);if(h!==c)break t;var D=Math.min(o-I,i-I),w=l.slice(l.length-D),k=d.slice(d.length-D);if(w!==k)break t;var y=l.slice(0,l.length-D),A=d.slice(0,d.length-D);return In(c,y,A,w)}}if(r.length>0&&s&&s.length===0)t:{var g=t.slice(0,r.index),w=t.slice(r.index+r.length),p=g.length,D=w.length;if(i<p+D)break t;var S=e.slice(0,p),k=e.slice(i-D);if(g!==S||w!==k)break t;var y=t.slice(p,o-D),A=e.slice(p,i-D);return In(g,y,A,w)}return null}function Pe(t,e,n,r){return le(t,e,n,r,!0)}Pe.INSERT=O;Pe.DELETE=H;Pe.EQUAL=M;Ks.exports=Pe});import*as Ye from"node:fs";import*as Vt from"node:path";import{fileURLToPath as Df}from"node:url";import*as Qe from"node:os";import*as xt from"node:path";var Ze="diffstalker";function tn(){return process.env.XDG_CONFIG_HOME||xt.join(Qe.homedir(),".config")}function pr(){return xt.join(tn(),Ze)}function kt(){return xt.join(process.env.XDG_CACHE_HOME||xt.join(Qe.homedir(),".cache"),Ze)}function mr(){return process.env.XDG_RUNTIME_DIR?xt.join(process.env.XDG_RUNTIME_DIR,Ze):null}import*as ge from"node:fs";import*as we from"node:path";import*as en from"node:os";function K(t){if(t.startsWith("~/"))return we.join(en.homedir(),t.slice(2));if(t==="~")return en.homedir();return t}function ye(t){let e=we.dirname(t);if(!ge.existsSync(e))ge.mkdirSync(e,{recursive:!0})}function nn(t){let e=t.split(`
2
+ `);for(let n=e.length-1;n>=0;n--){let r=e[n].trim();if(r)return r}return""}var gr=!1;function wr(t){gr=t}function yr(t){let e="";for(let n of t){let r=n.charCodeAt(0);if(r>=32&&r!==127)e+=n;else if(n===`
3
+ `)e+="\\n";else if(n==="\r")e+="\\r";else if(n==="\t")e+="\\t";else e+=`\\x${r.toString(16).padStart(2,"0")}`}return e}var Zi=/(\w+:\/\/)[^/\s@]+@/g;function ta(t){return t.replace(Zi,"$1***@")}function ea(t){if(!t)return"";let e=[];for(let[n,r]of Object.entries(t)){if(r===void 0)continue;let s=yr(String(r));e.push(`${n}=${/\s/.test(s)||s===""?JSON.stringify(s):s}`)}return e.length===0?"":` ${e.join(" ")}`}function na(t){if(t instanceof Error)return`${t.name}: ${t.message}`;return String(t)}function rn(t,e={stacks:!0}){let n=[],r=t;for(let s=0;s<10&&r!==void 0&&r!==null;s++){let o=s===0?"":"caused by: ",i=e.stacks&&r instanceof Error&&r.stack?r.stack:na(r);n.push(o+i),r=r instanceof Error?r.cause:void 0}return n.join(`
4
+ `)}function sn(t,e,n,r){let s=`${new Date().toISOString()} ${t.padEnd(5)} ${yr(e)}${ea(n)}`,o=r?`
5
+ ${r.replace(/^/gm," ")}`:"";process.stderr.write(ta(`${s}${o}
6
+ `))}function L(t,e,n){if(!gr)return;sn("debug",t,n,e===void 0?void 0:rn(e,{stacks:!1}))}function E(t,e,n){sn("warn",t,n,e===void 0?void 0:rn(e,{stacks:!1}))}function T(t,e,n){sn("error",t,n,e===void 0?void 0:rn(e))}import*as Mi from"node:http";import*as vt from"node:fs";import*as Fi from"node:net";function on(t){let e={};for(let[n,r]of t)e[n]=r;return e}function ra(t){if(!t)return null;return{staged:on(t.staged),unstaged:on(t.unstaged)}}function at(t){return{status:t.status,hunkCounts:ra(t.hunkCounts),error:t.error,stashList:t.stashList,operationInProgress:t.operationInProgress,mtimes:t.mtimes?on(t.mtimes):null}}function sa(t){return t.entries.length>0?t.entries[0].seq-1:t.nextSeq-1}function br(t,e){let n=e>0?t.entries.filter((r)=>r.seq>e):t.entries;return{epoch:t.epoch,prunedBefore:sa(t),entries:n}}function Qt(t){if(t instanceof Date)return t.toISOString();if(t instanceof Map){let e={};for(let[n,r]of t)e[String(n)]=Qt(r);return e}if(Array.isArray(t))return t.map(Qt);if(t!==null&&typeof t==="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=Qt(r);return e}return t}var oa=1048576;class m extends Error{status;constructor(t,e,n){super(e,n);this.status=t,this.name="HttpError"}}function v(t,e,n){let r=JSON.stringify(Qt(n));t.writeHead(e,{"content-type":"application/json"}),t.end(r)}function Er(t,e,n,r){t.writeHead(e,{...r,"content-length":String(n.byteLength)}),t.end(n)}function ia(t,e){if(t.segments.length!==e.length)return null;let n={};for(let r=0;r<t.segments.length;r++){let s=t.segments[r];if(s.startsWith(":"))try{n[s.slice(1)]=decodeURIComponent(e[r])}catch{throw new m(400,`Malformed percent-encoding in path: ${e[r]}`)}else if(s!==e[r])return null}return n}async function aa(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>oa)throw new m(413,"Request body too large");e.push(o)}let r=Buffer.concat(e).toString("utf-8");if(!r.trim())return;try{return JSON.parse(r)}catch{throw new m(400,"Invalid JSON body")}}class an{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=ia(n,e);if(r)return{handler:n.handler,params:r}}return null}async handle(t,e,n){try{let r=new URL(t.url??"/","http://localhost"),s=r.pathname.split("/").filter(Boolean),o=t.method??"GET",i=this.match(o,s);if(!i){if(n&&o==="GET"){await n(t,e,r.pathname);return}throw new m(404,`Unknown route: ${o} ${r.pathname}`)}let a=await aa(t);await i.handler({req:t,res:e,params:i.params,query:r.searchParams,body:a})}catch(r){let s=`${t.method??"GET"} ${t.url??"/"}`;if(e.headersSent){T(`${s} failed after the response headers were sent`,r),e.end();return}if(r instanceof m){ca(s,r),v(e,r.status,{error:r.message});return}T(`${s} -> 500`,r),v(e,500,{error:"Internal server error"})}}}function ca(t,e){let n=`${t} -> ${e.status} ${e.message}`;if(e.cause!==void 0||e.status>=500)E(n,e.cause);else L(n)}import*as cn from"node:fs";import*as X from"node:path";var la=new Set(["health","version","repos","resolve","worktrees","events","follow","settings","discovered","browse"]),ua={".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"},Sr="no-cache",fa="public, max-age=31536000, immutable";async function vr(t,e,n){let r;try{r=await cn.promises.readFile(e)}catch(s){throw new m(404,`Not found: ${X.basename(e)}`,{cause:s})}t.writeHead(200,{"content-type":ua[X.extname(e)]??"application/octet-stream","cache-control":n,"content-length":r.length}),t.end(r)}function xr(t){let e=X.resolve(t);return async(n,r,s)=>{let o;try{o=decodeURIComponent(s)}catch{throw new m(400,`Malformed percent-encoding in path: ${s}`)}if(o.includes("\x00"))throw new m(400,"Invalid path");let i=o.split("/").filter(Boolean);if(i.length>0&&la.has(i[0]))throw new m(404,`Unknown route: GET ${s}`);let a=i.length>0?X.resolve(e,i.join("/")):e;if(a!==e&&!a.startsWith(e+X.sep))throw new m(403,"Forbidden");if((await cn.promises.stat(a).catch(()=>null))?.isFile()){await vr(r,a,i[0]==="assets"?fa:Sr);return}await vr(r,X.join(e,"index.html"),Sr)}}function ha(t){try{let e=new URL(`http://${t}`).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function da(t){try{let e=new URL(t).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function Rr(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 pa(t){return t.length>10&&t.endsWith(".localhost")}function kr(t){return t==="localhost"||t==="::1"||pa(t)||Rr(t)}function ma(t){return t==="::1"||Rr(t)}function _r(t){if(t===null)return!1;if(typeof t==="string")return!0;return ma(t.address)}function Ar(t){let e=t.headers.host;if(e!==void 0){let i=ha(e);if(i===null||!kr(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=da(o);if(i===null||!kr(i))return{status:403,message:"Cross-origin request blocked"}}return null}function Ir(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 Dr={"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 Qc}from"node:crypto";class Pr{repoPath;queue=[];isProcessing=!1;pendingMutations=0;refreshScheduled=!1;constructor(t){this.repoPath=t}enqueue(t){return new Promise((e,n)=>{this.queue.push({execute:t,resolve:e,reject:n}),this.processNext()})}enqueueMutation(t){return this.pendingMutations++,this.enqueue(t).finally(()=>{this.pendingMutations--})}hasPendingMutations(){return this.pendingMutations>0}scheduleRefresh(t){if(this.pendingMutations>0)return;if(this.refreshScheduled)return;this.refreshScheduled=!0,this.enqueue(async()=>{this.refreshScheduled=!1,await t()}).catch((e)=>{T("Scheduled refresh threw",e,{repo:this.repoPath}),this.refreshScheduled=!1})}isBusy(){return this.isProcessing||this.queue.length>0}async processNext(){if(this.isProcessing||this.queue.length===0)return;this.isProcessing=!0;let t=this.queue.shift();try{let e=await t.execute();t.resolve(e)}catch(e){t.reject(e instanceof Error?e:Error(String(e)))}finally{this.isProcessing=!1,this.processNext()}}}var ln=new Map;function Tr(t){let e=ln.get(t);if(!e)e=new Pr(t),ln.set(t,e);return e}function Mr(t){ln.delete(t)}import*as B from"node:path";import*as U from"node:fs";import{execFileSync as Ic}from"node:child_process";import{watch as Qs}from"chokidar";import{EventEmitter as Dc}from"node:events";import Zs from"ignore";import{execFile as Sa}from"node:child_process";import{promisify as va}from"node:util";import{simpleGit as xa}from"simple-git";import*as Y from"node:fs";import*as te from"node:path";import{execFileSync as ga}from"node:child_process";var wa=[["*.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 ya(){return`# Generated by diffstalker: turns on git's built-in funcname drivers.
7
7
  `+`# Lowest-priority attributes source — a repo's own .gitattributes wins.
8
- `+la.map(([e,n])=>`${e} diff=${n}`).join(`
8
+ `+wa.map(([e,n])=>`${e} diff=${n}`).join(`
9
9
  `)+`
10
- `}var Zt=null,ht=null;function fa(){if(ht!==null)return ht;try{if(ca("git",["config","--get","core.attributesFile"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:process.env}).trim()!=="")return ht=!0,!0}catch(t){if(t.status!==1)return v("git config core.attributesFile failed; funcname drivers are off",t),ht=!0,!0}return ht=Y.existsSync(te.join(Ze(),"git","attributes")),ht}function Dr(){if(Zt!==null)return Zt;if(fa())return null;let t=te.join(kt(),"funcname.gitattributes"),e=ua();try{let n=null;try{n=Y.readFileSync(t,"utf8")}catch{n=null}if(n!==e)Y.mkdirSync(te.dirname(t),{recursive:!0}),ha(t,e);return Zt=t,Zt}catch(n){return v("Cannot write the attributes file; funcname drivers are off",n,{file:t}),Zt=null,ht=!0,null}}function ha(t,e){let n=`${t}.${process.pid}.tmp`;Y.writeFileSync(n,e,"utf8"),Y.renameSync(n,t)}var ga=pa(da);function ct(){return{...process.env,LC_ALL:"C",LANG:"C"}}var ee=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"],ln=5000;async function ye(t,e,n){let{stdout:r}=await ga("git",e,{cwd:t,env:ct(),encoding:"buffer",maxBuffer:n,timeout:ln,windowsHide:!0});return r}var wa={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0},ya=1e4,ba=600000;function S(t,e={}){let n=Dr(),r=n===null?[]:[`core.attributesFile=${n}`],s=ct();return ma({baseDir:t,unsafe:wa,allowEnvironment:Object.keys(s),timeout:{block:e.longRunning===!0?ba:ya},config:r}).env(s)}import{execFileSync as Ia}from"node:child_process";import*as se from"node:fs";import*as hn from"node:path";async function Rt(t,e){if(e.length===0)return new Set;let n=S(t),r=100,s=[];for(let a=0;a<e.length;a+=r)s.push(e.slice(a,a+r));let o=await Promise.all(s.map(async(a)=>{try{return await n.raw(["check-ignore","--",...a])}catch(c){if(c instanceof Error?c.message.trim():String(c))v("git check-ignore failed; ignored files may show as untracked",c,{repo:t});return""}})),i=new Set;for(let a of o)for(let c of a.trim().split(`
10
+ `}var Zt=null,ht=null;function ba(){if(ht!==null)return ht;try{if(ga("git",["config","--get","core.attributesFile"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:process.env}).trim()!=="")return ht=!0,!0}catch(t){if(t.status!==1)return E("git config core.attributesFile failed; funcname drivers are off",t),ht=!0,!0}return ht=Y.existsSync(te.join(tn(),"git","attributes")),ht}function Fr(){if(Zt!==null)return Zt;if(ba())return null;let t=te.join(kt(),"funcname.gitattributes"),e=ya();try{let n=null;try{n=Y.readFileSync(t,"utf8")}catch{n=null}if(n!==e)Y.mkdirSync(te.dirname(t),{recursive:!0}),Ea(t,e);return Zt=t,Zt}catch(n){return E("Cannot write the attributes file; funcname drivers are off",n,{file:t}),Zt=null,ht=!0,null}}function Ea(t,e){let n=`${t}.${process.pid}.tmp`;Y.writeFileSync(n,e,"utf8"),Y.renameSync(n,t)}var ka=va(Sa);function ct(){return{...process.env,LC_ALL:"C",LANG:"C"}}var ee=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"],un=5000;async function be(t,e,n){let{stdout:r}=await ka("git",e,{cwd:t,env:ct(),encoding:"buffer",maxBuffer:n,timeout:un,windowsHide:!0});return r}var Ra={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0},_a=1e4,Aa=600000;function x(t,e={}){let n=Fr(),r=n===null?[]:[`core.attributesFile=${n}`],s=ct();return xa({baseDir:t,unsafe:Ra,allowEnvironment:Object.keys(s),timeout:{block:e.longRunning===!0?Aa:_a},config:r}).env(s)}import{execFileSync as Na}from"node:child_process";import*as se from"node:fs";import*as dn from"node:path";async function Rt(t,e){if(e.length===0)return new Set;let n=x(t),r=100,s=[];for(let a=0;a<e.length;a+=r)s.push(e.slice(a,a+r));let o=await Promise.all(s.map(async(a)=>{try{return await n.raw(["check-ignore","--",...a])}catch(c){if(c instanceof Error?c.message.trim():String(c))E("git check-ignore failed; ignored files may show as untracked",c,{repo:t});return""}})),i=new Set;for(let a of o)for(let c of a.trim().split(`
11
11
  `))if(c.length>0)i.add(c);return i}function dt(t){if(t.length===0)return"";return t.map((e)=>e.content).join(`
12
12
  `)+`
13
- `}function be(t){let e=0;for(let n of t)e+=n.content.length+1;return e}var Ea=5000,ne=262144,Fr="Large file — diff not shown";function Sa(t){return String(t).replace(/\B(?=(\d{3})+(?!\d))/g,",")}function xa(t){let e=t/1048576;if(e>=1)return`${e.toFixed(1)} MB`;return`${Math.round(t/1024)} KB`}function un(t,e){let n=xa(t),r=e===void 0?n:`${n}, ${Sa(e)} lines`;return`${Fr} (${r})`}function Pr(t){if(t.length===0)return 0;let e=1,n=-1;while((n=t.indexOf(`
14
- `,n+1))!==-1)e++;return e}function Mr(t,e,n){let r=t.split(`
15
- `),s=r.findIndex((i)=>i.startsWith("@@"));return`${[...r.slice(0,s===-1?4:s),un(e,n)].join(`
13
+ `}function Ee(t){let e=0;for(let n of t)e+=n.content.length+1;return e}var Ia=5000,ne=262144,Or="Large file — diff not shown";function Da(t){return String(t).replace(/\B(?=(\d{3})+(?!\d))/g,",")}function Pa(t){let e=t/1048576;if(e>=1)return`${e.toFixed(1)} MB`;return`${Math.round(t/1024)} KB`}function fn(t,e){let n=Pa(t),r=e===void 0?n:`${n}, ${Da(e)} lines`;return`${Or} (${r})`}function $r(t){if(t.length===0)return 0;let e=1,n=-1;while((n=t.indexOf(`
14
+ `,n+1))!==-1)e++;return e}function Cr(t,e,n){let r=t.split(`
15
+ `),s=r.findIndex((i)=>i.startsWith("@@"));return`${[...r.slice(0,s===-1?4:s),fn(e,n)].join(`
16
16
  `)}
17
- `}function lt(t){if(t.length===0)return t;let e=t.split(/(?=^diff --git )/m),n=!1,r=e.map((s)=>{let o=s.length;if(o<=ne){let i=Pr(s);if(i<=Ea)return s;return n=!0,Mr(s,o,i)}return n=!0,Mr(s,o,Pr(s))});return n?r.join(""):t}function va(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(Fr)}function ka(t){return t.startsWith("\\ ")}function $r(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 ut(t){if(t==="")return[];let e=t.split(`
18
- `);if(e.length>1&&e[e.length-1]==="")e.pop();let n=[],r=0,s=0;for(let o of e)if(va(o))n.push({type:"header",content:o});else if(ka(o))n.push({type:"context",content:o});else if(o.startsWith("@@")){let i=$r(o);if(i)r=i.oldStart,s=i.newStart;n.push({type:"hunk",content:o})}else if(o.startsWith("+"))n.push({type:"addition",content:o,newLineNum:s++});else if(o.startsWith("-"))n.push({type:"deletion",content:o,oldLineNum:r++});else n.push({type:"context",content:o,oldLineNum:r++,newLineNum:s++});return n}function Ee(t){let e=new Map;if(!t)return e;let n=null;for(let r of t.split(`
19
- `))if(r.startsWith("diff --git")){let s=pt(r);if(s!==null){if(n=s,!e.has(n))e.set(n,0)}}else if(r.startsWith("@@")&&n)e.set(n,(e.get(n)??0)+1);return e}var Or=new Map([["a",7],["b",8],["f",12],["n",10],["r",13],["t",9],["v",11],["\\",92],['"',34]]),Ra=new Map([...Or].map(([t,e])=>[e,t]));function Tr(t){return t<32||t===127||t>=128||t===34||t===92}function _t(t){let e=new TextEncoder().encode(t);if(!e.some(Tr))return t;let n='"';for(let r of e){let s=Ra.get(r);if(s!==void 0)n+=`\\${s}`;else if(Tr(r))n+=`\\${r.toString(8).padStart(3,"0")}`;else n+=String.fromCharCode(r)}return`${n}"`}function _a(t){if(t.length<2||!t.startsWith('"')||!t.endsWith('"'))return t;let e=t.slice(1,-1),n=new TextEncoder,r=[],s=0;while(s<e.length){let o=e.indexOf("\\",s);if(o===-1){r.push(...n.encode(e.slice(s)));break}r.push(...n.encode(e.slice(s,o)));let i=/^[0-7]{1,3}/.exec(e.slice(o+1,o+4));if(i!==null){r.push(parseInt(i[0],8)),s=o+1+i[0].length;continue}let a=Or.get(e[o+1]??"");if(a!==void 0){r.push(a),s=o+2;continue}r.push(92),s=o+1}return new TextDecoder().decode(Uint8Array.from(r))}function Aa(t){for(let e=t.length-2;e>=0;e--){if(t[e]!=='"')continue;let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r--)n++;if(n%2===0)return e}return-1}function pt(t){if(!t.startsWith("diff --git "))return null;let n=t.slice(11);if(n.endsWith('"')){let s=Aa(n);if(s===-1)return null;let o=_a(n.slice(s));return o.startsWith("b/")?o.slice(2):null}let r=n.lastIndexOf(" b/");return r===-1?null:n.slice(r+3)}function re(t){let e=new Map,n=t.split("\x00");for(let r=0;r<n.length;r++){let s=n[r];if(s==="")continue;let o=s.split("\t");if(o.length<3)continue;let i=o[0]==="-"?0:parseInt(o[0],10),a=o[1]==="-"?0:parseInt(o[1],10),c=o.slice(2).join("\t");if(c==="")c=n[r+2]??"",r+=2;if(c!=="")e.set(c,{additions:i,deletions:a})}return e}function fn(t){let e=[],n=t.split("\x00");for(let r=0;r<n.length;r++){let s=n[r];if(s==="")continue;let o=s[0];if(o==="R"||o==="C"){let i=n[r+1],a=n[r+2];if(i!==void 0&&a!==void 0)e.push({code:o,path:a,oldPath:i});r+=2}else{let i=n[r+1];if(i!==void 0)e.push({code:o,path:i});r+=1}}return e}function At(t){return t instanceof Error?t.message:String(t)}function Cr(t){return/does not have any commits yet|bad default revision/i.test(At(t))}var Da=ne;async function Pa(t,e){try{let n=hn.join(t,e),r=await se.promises.stat(n);if(!r.isFile())return null;if(r.size>Da)return null;return(await se.promises.readFile(n,"utf-8")).split(`
20
- `).filter((o)=>o.length>0).length}catch{return null}}var Ma=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function Ta(t,e){return Ma.has(`${t}${e}`)}function Nr(t,e){return e?"conflicted":Fa(t)}function Fa(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 dn(t){let e=S(t);if(!await e.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let r=await e.status(),s=[],o=new Set,i=r.files.filter((d)=>d.working_dir==="?").map((d)=>d.path),a=await Rt(t,i);for(let d of r.files){if(d.index==="!"||d.working_dir==="!"||a.has(d.path))continue;let g=`${d.path}-${d.index!==" "&&d.index!=="?"}`;if(o.has(g))continue;o.add(g);let R=Ta(d.index,d.working_dir);if(d.index&&d.index!==" "&&d.index!=="?"){let y=Nr(d.index,R);s.push({path:d.path,status:y,staged:!0,...d.from&&(y==="renamed"||y==="copied")?{originalPath:d.from}:{}})}if(d.working_dir&&d.working_dir!==" ")s.push({path:d.path,status:Nr(d.working_dir,R),staged:!1})}let c=(d)=>e.diff([...d,"--numstat","-z"]).catch((g)=>(v(`git diff ${d.join(" ")} --numstat failed in ${t}: ${At(g)}`),"")),[l,u]=await Promise.all([c(["--cached"]),c([])]),f=re(l),h=re(u);for(let d of s){let g=d.staged?f.get(d.path):h.get(d.path);if(g)d.insertions=g.additions,d.deletions=g.deletions}let p=s.filter((d)=>d.status==="untracked");if(p.length>0){let d=await Promise.all(p.map((g)=>Pa(t,g.path)));for(let g=0;g<p.length;g++){let R=d[g];if(R===null)continue;p[g].insertions=R,p[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 S(t).add(["--",e])}async function Hr(t,e){await S(t).reset(["HEAD","--",e])}async function Br(t){await S(t).add("-A")}async function jr(t){await S(t).reset(["HEAD"])}async function Wr(t,e){await S(t).checkout(["--",e])}async function Gr(t,e){await S(t).clean("f",["--",e])}async function Ur(t,e,n=!1){if(!(await S(t,{longRunning:!0}).commit(e,void 0,n?{"--amend":null}:void 0)).commit)throw Error("Nothing to commit: no staged changes")}async function qr(t){let e=S(t);try{return(await e.log({n:1})).latest?.message||""}catch(n){if(!Cr(n))v(`git log for the HEAD message failed in ${t}: ${At(n)}`);return""}}function Xr(t,e,n){Ia("git",["apply","--cached",...n?["--reverse"]:[],"--unidiff-zero"],{cwd:t,input:e,encoding:"utf-8",env:ct(),stdio:["pipe","pipe","pipe"]})}function zr(t,e){Xr(t,e,!1)}function Jr(t,e){Xr(t,e,!0)}async function Kr(t){let r=(await S(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 Yr(t){return await S(t,{longRunning:!0}).fetch(),"Fetch complete"}async function Vr(t){let n=await S(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 Qr(t,e=50){let n=S(t);try{return(await n.log({n:e})).all.map((s)=>({hash:s.hash,shortHash:s.hash.slice(0,7),message:s.message.split(`
21
- `)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}))}catch(r){if(!Cr(r))v(`git log failed in ${t}: ${At(r)}`);return[]}}async function Zr(t,e){let n=S(t);try{let s=(await n.log(["--no-walk",e])).all[0];if(!s)return null;return{hash:s.hash,shortHash:s.hash.slice(0,7),message:s.message.split(`
22
- `)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}}catch{return null}}async function pn(t){let e=S(t);try{return(await e.stashList()).all.map((r,s)=>({index:s,message:r.message}))}catch(n){return v(`git stash list failed in ${t}, reporting no stashes: ${At(n)}`),[]}}async function ts(t,e){let n=S(t),r=["push"];if(e)r.push("-m",e);return await n.stash(r),"Stashed"}async function es(t,e=0){let n=S(t);await n.stash(["pop",`stash@{${e}}`]);let r=(await n.raw(["diff","--name-only","--diff-filter=U"])).trim();if(r)throw Error(`Stash pop hit conflicts in: ${r.split(`
23
- `).join(", ")}`);return"Stash popped"}async function ns(t){let n=await S(t).branchLocal();return n.all.map((r)=>({name:r,current:r===n.current,tracking:n.branches[r]?.label||void 0}))}async function rs(t,e){return await S(t).raw(["switch","--",e]),`Switched to ${e}`}async function ss(t,e){return await S(t).raw(["switch","-c",e]),`Created ${e}`}async function os(t,e=1){return await S(t).reset(["--soft",`HEAD~${e}`]),"Reset done"}async function is(t,e){return await S(t,{longRunning:!0}).raw(["cherry-pick","--end-of-options",e]),"Cherry-picked"}async function as(t,e){return await S(t,{longRunning:!0}).raw(["revert","--no-edit","--end-of-options",e]),"Reverted"}async function It(t){let e=S(t),n;try{n=(await e.raw(["rev-parse","--absolute-git-dir"])).trim()}catch(s){return v(`git rev-parse --absolute-git-dir failed in ${t}: ${At(s)}`),null}let r=(s)=>se.existsSync(hn.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 cs(t){let e=await It(t);if(!e)throw Error("No operation in progress to abort");return await S(t).raw([e,"--abort"]),`Aborted ${e}`}async function ls(t){return await S(t,{longRunning:!0}).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function us(t){return(await S(t).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((r)=>r.length>0)}import*as mt from"node:fs";import*as Mt from"node:path";import*as Se from"node:fs";import*as oe from"node:path";function mn(){return oe.join(kt(),"base-branches.json")}function fs(){let t=mn();try{return JSON.parse(Se.readFileSync(t,"utf-8"))}catch(e){if(e.code!=="ENOENT")v("Ignoring the base-branch cache",e,{file:t});return{}}}function $a(t){we(mn()),Se.writeFileSync(mn(),JSON.stringify(t,null,2)+`
24
- `)}function Dt(t){let e=fs(),n=oe.resolve(t);return e[n]}function hs(t,e){let n=fs(),r=oe.resolve(t);n[r]=e,$a(n)}function ie(t){let e=Math.min(t.length,8192);for(let n=0;n<e;n++)if(t[n]===0)return!0;return!1}var ds={staged:!1,unstaged:!1,untracked:!1};class xe extends Error{constructor(t){super(`No common history with ${t}`);this.name="NoCommonHistoryError"}}var Tt=3,ws=1e5;function ve(t){return t instanceof Error?t.message:String(t)}function ke(t,e,n){v(`${t} failed in ${e}, answering an empty diff: ${ve(n)}`)}async function Ft(t,e,n=!1,r={}){let s=S(t);try{let o=[`-U${r.context??Tt}`];if(n)o.push("--cached");if(e)o.push("--",e);let i=lt(await s.diff(o));return{lines:ut(i)}}catch(o){let i=e===void 0?"":` -- ${e}`;return ke(`git diff${n?" --cached":""}${i}`,t,o),{lines:[]}}}var Oa="4b825dc642cb6eb9a060e54bf8d69288fbee4904",ys="(unborn)",Na=/unknown revision|ambiguous argument 'HEAD'|needed a single revision/i;async function Re(t){let e=S(t);try{return(await e.raw(["rev-parse","HEAD"])).trim()}catch(n){let r=n instanceof Error?n.message:String(n);if(Na.test(r))return ys;throw n}}async function bs(t,e){let n=S(t),s=(e??await Re(t))===ys?Oa:"HEAD",o=lt(await n.raw(["diff",`-U${Tt}`,s,"--"]));return{lines:ut(o)}}var Ca=ne;function gn(t,e={}){let n=_t(`a/${t}`),r=_t(`b/${t}`),s=[{type:"header",content:`diff --git ${n} ${r}`},{type:"header",content:"new file mode 100644"}];if(e.binary)s.push({type:"header",content:`Binary files /dev/null and ${r} differ`});else s.push({type:"header",content:"--- /dev/null"}),s.push({type:"header",content:`+++ ${r}`});return s}function La(t,e){return{lines:[...gn(t),{type:"header",content:un(e)}]}}function Ha(t){return{lines:gn(t,{binary:!0})}}function Ba(t,e){let n=Mt.resolve(t),r=Mt.resolve(n,e);if(r!==n&&!r.startsWith(n+Mt.sep))return null;let s,o;try{s=mt.realpathSync(r),o=mt.realpathSync(n)}catch{return null}if(s!==o&&!s.startsWith(o+Mt.sep))return null;let i=mt.statSync(s);if(!i.isFile())return null;return{path:r,size:i.size}}async function gt(t,e){try{let n=Ba(t,e);if(n===null)return{lines:[]};if(n.size>Ca)return La(e,n.size);let r=mt.readFileSync(n.path);if(ie(r))return Ha(e);let s=r.toString("utf-8"),o=gn(e),i=s.endsWith(`
17
+ `}function lt(t){if(t.length===0)return t;let e=t.split(/(?=^diff --git )/m),n=!1,r=e.map((s)=>{let o=s.length;if(o<=ne){let i=$r(s);if(i<=Ia)return s;return n=!0,Cr(s,o,i)}return n=!0,Cr(s,o,$r(s))});return n?r.join(""):t}function Ta(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(Or)}function Ma(t){return t.startsWith("\\ ")}function Lr(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 ut(t){if(t==="")return[];let e=t.split(`
18
+ `);if(e.length>1&&e[e.length-1]==="")e.pop();let n=[],r=0,s=0;for(let o of e)if(Ta(o))n.push({type:"header",content:o});else if(Ma(o))n.push({type:"context",content:o});else if(o.startsWith("@@")){let i=Lr(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 Se(t){let e=new Map;if(!t)return e;let n=null;for(let r of t.split(`
19
+ `))if(r.startsWith("diff --git")){let s=pt(r);if(s!==null){if(n=s,!e.has(n))e.set(n,0)}}else if(r.startsWith("@@")&&n)e.set(n,(e.get(n)??0)+1);return e}var Br=new Map([["a",7],["b",8],["f",12],["n",10],["r",13],["t",9],["v",11],["\\",92],['"',34]]),Fa=new Map([...Br].map(([t,e])=>[e,t]));function Nr(t){return t<32||t===127||t>=128||t===34||t===92}function _t(t){let e=new TextEncoder().encode(t);if(!e.some(Nr))return t;let n='"';for(let r of e){let s=Fa.get(r);if(s!==void 0)n+=`\\${s}`;else if(Nr(r))n+=`\\${r.toString(8).padStart(3,"0")}`;else n+=String.fromCharCode(r)}return`${n}"`}function $a(t){if(t.length<2||!t.startsWith('"')||!t.endsWith('"'))return t;let e=t.slice(1,-1),n=new TextEncoder,r=[],s=0;while(s<e.length){let o=e.indexOf("\\",s);if(o===-1){r.push(...n.encode(e.slice(s)));break}r.push(...n.encode(e.slice(s,o)));let i=/^[0-7]{1,3}/.exec(e.slice(o+1,o+4));if(i!==null){r.push(parseInt(i[0],8)),s=o+1+i[0].length;continue}let a=Br.get(e[o+1]??"");if(a!==void 0){r.push(a),s=o+2;continue}r.push(92),s=o+1}return new TextDecoder().decode(Uint8Array.from(r))}function Ca(t){for(let e=t.length-2;e>=0;e--){if(t[e]!=='"')continue;let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r--)n++;if(n%2===0)return e}return-1}function pt(t){if(!t.startsWith("diff --git "))return null;let n=t.slice(11);if(n.endsWith('"')){let s=Ca(n);if(s===-1)return null;let o=$a(n.slice(s));return o.startsWith("b/")?o.slice(2):null}let r=n.lastIndexOf(" b/");return r===-1?null:n.slice(r+3)}function re(t){let e=new Map,n=t.split("\x00");for(let r=0;r<n.length;r++){let s=n[r];if(s==="")continue;let o=s.split("\t");if(o.length<3)continue;let i=o[0]==="-"?0:parseInt(o[0],10),a=o[1]==="-"?0:parseInt(o[1],10),c=o.slice(2).join("\t");if(c==="")c=n[r+2]??"",r+=2;if(c!=="")e.set(c,{additions:i,deletions:a})}return e}function hn(t){let e=[],n=t.split("\x00");for(let r=0;r<n.length;r++){let s=n[r];if(s==="")continue;let o=s[0];if(o==="R"||o==="C"){let i=n[r+1],a=n[r+2];if(i!==void 0&&a!==void 0)e.push({code:o,path:a,oldPath:i});r+=2}else{let i=n[r+1];if(i!==void 0)e.push({code:o,path:i});r+=1}}return e}function At(t){return t instanceof Error?t.message:String(t)}function Wr(t){return/does not have any commits yet|bad default revision/i.test(At(t))}var Oa=ne;async function La(t,e){try{let n=dn.join(t,e),r=await se.promises.stat(n);if(!r.isFile())return null;if(r.size>Oa)return null;return(await se.promises.readFile(n,"utf-8")).split(`
20
+ `).filter((o)=>o.length>0).length}catch{return null}}var Ba=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function Ha(t,e){return Ba.has(`${t}${e}`)}function Hr(t,e){return e?"conflicted":Wa(t)}function Wa(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 pn(t){let e=x(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 Rt(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 S=Ha(p.index,p.working_dir);if(p.index&&p.index!==" "&&p.index!=="?"){let y=Hr(p.index,S);s.push({path:p.path,status:y,staged:!0,...p.from&&(y==="renamed"||y==="copied")?{originalPath:p.from}:{}})}if(p.working_dir&&p.working_dir!==" ")s.push({path:p.path,status:Hr(p.working_dir,S),staged:!1})}let c=(p)=>e.diff([...p,"--numstat","-z"]).catch((g)=>(E(`git diff ${p.join(" ")} --numstat failed in ${t}: ${At(g)}`),"")),[l,u]=await Promise.all([c(["--cached"]),c([])]),f=re(l),h=re(u);for(let p of s){let g=p.staged?f.get(p.path):h.get(p.path);if(g)p.insertions=g.additions,p.deletions=g.deletions}let d=s.filter((p)=>p.status==="untracked");if(d.length>0){let p=await Promise.all(d.map((g)=>La(t,g.path)));for(let g=0;g<d.length;g++){let S=p[g];if(S===null)continue;d[g].insertions=S,d[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 jr(t,e){await x(t).add(["--",e])}async function Ur(t,e){await x(t).reset(["HEAD","--",e])}async function Gr(t){await x(t).add("-A")}async function qr(t){await x(t).reset(["HEAD"])}async function Xr(t,e){await x(t).checkout(["--",e])}async function zr(t,e){await x(t).clean("f",["--",e])}async function Jr(t,e,n=!1){if(!(await x(t,{longRunning:!0}).commit(e,void 0,n?{"--amend":null}:void 0)).commit)throw Error("Nothing to commit: no staged changes")}async function Kr(t){let e=x(t);try{return(await e.log({n:1})).latest?.message||""}catch(n){if(!Wr(n))E(`git log for the HEAD message failed in ${t}: ${At(n)}`);return""}}function Yr(t,e,n){Na("git",["apply","--cached",...n?["--reverse"]:[],"--unidiff-zero"],{cwd:t,input:e,encoding:"utf-8",env:ct(),stdio:["pipe","pipe","pipe"]})}function Vr(t,e){Yr(t,e,!1)}function Qr(t,e){Yr(t,e,!0)}async function Zr(t){let r=(await x(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 ts(t){return await x(t,{longRunning:!0}).fetch(),"Fetch complete"}async function es(t){let n=await x(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 ns(t,e=50){let n=x(t);try{return(await n.log({n:e})).all.map((s)=>({hash:s.hash,shortHash:s.hash.slice(0,7),message:s.message.split(`
21
+ `)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}))}catch(r){if(!Wr(r))E(`git log failed in ${t}: ${At(r)}`);return[]}}async function rs(t,e){let n=x(t);try{let s=(await n.log(["--no-walk",e])).all[0];if(!s)return null;return{hash:s.hash,shortHash:s.hash.slice(0,7),message:s.message.split(`
22
+ `)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}}catch{return null}}async function mn(t){let e=x(t);try{return(await e.stashList()).all.map((r,s)=>({index:s,message:r.message}))}catch(n){return E(`git stash list failed in ${t}, reporting no stashes: ${At(n)}`),[]}}async function ss(t,e){let n=x(t),r=["push"];if(e)r.push("-m",e);return await n.stash(r),"Stashed"}async function os(t,e=0){let n=x(t);await n.stash(["pop",`stash@{${e}}`]);let r=(await n.raw(["diff","--name-only","--diff-filter=U"])).trim();if(r)throw Error(`Stash pop hit conflicts in: ${r.split(`
23
+ `).join(", ")}`);return"Stash popped"}async function is(t){let n=await x(t).branchLocal();return n.all.map((r)=>({name:r,current:r===n.current,tracking:n.branches[r]?.label||void 0}))}async function as(t,e){return await x(t).raw(["switch","--",e]),`Switched to ${e}`}async function cs(t,e){return await x(t).raw(["switch","-c",e]),`Created ${e}`}async function ls(t,e=1){return await x(t).reset(["--soft",`HEAD~${e}`]),"Reset done"}async function us(t,e){return await x(t,{longRunning:!0}).raw(["cherry-pick","--end-of-options",e]),"Cherry-picked"}async function fs(t,e){return await x(t,{longRunning:!0}).raw(["revert","--no-edit","--end-of-options",e]),"Reverted"}async function It(t){let e=x(t),n;try{n=(await e.raw(["rev-parse","--absolute-git-dir"])).trim()}catch(s){return E(`git rev-parse --absolute-git-dir failed in ${t}: ${At(s)}`),null}let r=(s)=>se.existsSync(dn.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 hs(t){let e=await It(t);if(!e)throw Error("No operation in progress to abort");return await x(t).raw([e,"--abort"]),`Aborted ${e}`}async function ds(t){return await x(t,{longRunning:!0}).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function ps(t){return(await x(t).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((r)=>r.length>0)}import*as mt from"node:fs";import*as Tt from"node:path";import*as ve from"node:fs";import*as oe from"node:path";function gn(){return oe.join(kt(),"base-branches.json")}function ms(){let t=gn();try{return JSON.parse(ve.readFileSync(t,"utf-8"))}catch(e){if(e.code!=="ENOENT")E("Ignoring the base-branch cache",e,{file:t});return{}}}function ja(t){ye(gn()),ve.writeFileSync(gn(),JSON.stringify(t,null,2)+`
24
+ `)}function Dt(t){let e=ms(),n=oe.resolve(t);return e[n]}function gs(t,e){let n=ms(),r=oe.resolve(t);n[r]=e,ja(n)}function ie(t){let e=Math.min(t.length,8192);for(let n=0;n<e;n++)if(t[n]===0)return!0;return!1}var ws={staged:!1,unstaged:!1,untracked:!1};class xe extends Error{constructor(t){super(`No common history with ${t}`);this.name="NoCommonHistoryError"}}var Mt=3,Ss=1e5;function ke(t){return t instanceof Error?t.message:String(t)}function Re(t,e,n){E(`${t} failed in ${e}, answering an empty diff: ${ke(n)}`)}async function ce(t,e,n=!1,r={}){let s=x(t);try{let o=[`-U${r.context??Mt}`];if(n)o.push("--cached");if(e)o.push("--",e);let i=lt(await s.diff(o));return{lines:ut(i)}}catch(o){let i=e===void 0?"":` -- ${e}`;return Re(`git diff${n?" --cached":""}${i}`,t,o),{lines:[]}}}var Ua="4b825dc642cb6eb9a060e54bf8d69288fbee4904",vs="(unborn)",Ga=/unknown revision|ambiguous argument 'HEAD'|needed a single revision/i;async function _e(t){let e=x(t);try{return(await e.raw(["rev-parse","HEAD"])).trim()}catch(n){let r=n instanceof Error?n.message:String(n);if(Ga.test(r))return vs;throw n}}async function xs(t,e){let n=x(t),s=(e??await _e(t))===vs?Ua:"HEAD",o=lt(await n.raw(["diff",`-U${Mt}`,s,"--"]));return{lines:ut(o)}}var qa=ne;function wn(t,e={}){let n=_t(`a/${t}`),r=_t(`b/${t}`),s=[{type:"header",content:`diff --git ${n} ${r}`},{type:"header",content:"new file mode 100644"}];if(e.binary)s.push({type:"header",content:`Binary files /dev/null and ${r} differ`});else s.push({type:"header",content:"--- /dev/null"}),s.push({type:"header",content:`+++ ${r}`});return s}function Xa(t,e){return{lines:[...wn(t),{type:"header",content:fn(e)}]}}function za(t){return{lines:wn(t,{binary:!0})}}function Ja(t,e){let n=Tt.resolve(t),r=Tt.resolve(n,e);if(r!==n&&!r.startsWith(n+Tt.sep))return null;let s,o;try{s=mt.realpathSync(r),o=mt.realpathSync(n)}catch{return null}if(s!==o&&!s.startsWith(o+Tt.sep))return null;let i=mt.statSync(s);if(!i.isFile())return null;return{path:r,size:i.size}}async function gt(t,e){try{let n=Ja(t,e);if(n===null)return{lines:[]};if(n.size>qa)return Xa(e,n.size);let r=mt.readFileSync(n.path);if(ie(r))return za(e);let s=r.toString("utf-8"),o=wn(e),i=s.endsWith(`
25
25
  `),a=s.split(`
26
- `);if(i)a.pop();if(s.length>0){o.push({type:"hunk",content:`@@ -0,0 +1,${a.length} @@`});let u=1;for(let f of a)o.push({type:"addition",content:"+"+f,newLineNum:u++});if(!i)o.push({type:"context",content:"\"})}let c=dt(o),l=lt(c);if(l!==c)return{lines:ut(l)};return{lines:o}}catch(n){return ke(`reading untracked file ${e}`,t,n),{lines:[]}}}var ae="refs/remotes/";async function Es(t){let e=S(t),n=new Set,r=[];try{let s=await e.raw(["log","--oneline","--decorate=full","--all","-n","200"]),o=/\(([^)]+)\)/g;for(let a of s.split(`
27
- `)){let c=o.exec(a);if(c)for(let l of c[1].split(",")){let u=l.trim().replace(/^.*-> /,"");if(!u.startsWith(ae))continue;let f=u.slice(ae.length);if(f.endsWith("/HEAD")||n.has(f))continue;n.add(f),r.push(f)}o.lastIndex=0}let i=(a)=>{let c=a.split("/").slice(1).join("/");return c==="main"||c==="master"};r.sort((a,c)=>Number(i(c))-Number(i(a)))}catch(s){v(`git log for base-branch discovery failed in ${t}: ${ve(s)}`)}return r}var ps=["upstream","origin"];function ms(t){let e=ps.indexOf(t);return e===-1?ps.length:e}async function ja(t){let e=(await t.raw(["remote"])).split(`
28
- `).filter(Boolean),n=new Map,r=await t.raw(["for-each-ref","--format=%(refname) %(symref)",ae]);for(let o of r.split(`
29
- `)){let[i,a=""]=o.split(" ");if(i)n.set(i,a)}let s=[];for(let o of e){let i=`${ae}${o}/`,a=n.get(`${i}HEAD`),c=a&&n.has(a)?a:[`${i}main`,`${i}master`].find((l)=>n.has(l));if(c)s.push({remote:o,ref:c})}return s}async function wn(t){let e=S(t);try{let n=await Promise.all((await ja(e)).map(async({remote:s,ref:o})=>({remote:s,branch:o.slice(ae.length),ahead:parseInt((await e.raw(["rev-list","--count",`${o}..HEAD`])).trim(),10)})));n.sort((s,o)=>s.ahead-o.ahead||ms(s.remote)-ms(o.remote)||(s.remote<o.remote?-1:1));let r=n[0];return r?{branch:r.branch,ahead:r.ahead}:null}catch(n){return v(`default base-branch discovery failed in ${t}: ${ve(n)}`),null}}async function yn(t){return(await wn(t))?.branch??null}async function bn(t){return Dt(t)??await yn(t)}async function nt(t,e){let n=S(t);try{return await n.raw(["cat-file","-e","--end-of-options",`${e}^{commit}`]),!0}catch{return!1}}function Wa(t){let e=t.indexOf(`
30
- `);return pt(e===-1?t:t.slice(0,e))}function Ss(t,e,n){let r=re(t),s=new Map;for(let a of fn(e)){let c;switch(a.code){case"A":c="added";break;case"D":c="deleted";break;case"R":c="renamed";break;default:c="modified"}s.set(a.path,c)}let o=[],i=n.split(/(?=^diff --git )/m).filter((a)=>a.trim());for(let a of i){let c=Wa(a);if(c===null)continue;let l=ut(a),u=r.get(c)||{additions:0,deletions:0},f=s.get(c)||"modified";o.push({path:c,status:f,additions:u.additions,deletions:u.deletions,diff:{lines:l}})}return o.sort((a,c)=>a.path.localeCompare(c.path)),o}async function Ga(t,e,n){let r=S(t);return xs(r,e,r.status(),n)}async function xs(t,e,n,r="HEAD",s){let o=await En(t,e,r),i=s===void 0?{kind:"compare",base:o,head:r}:{kind:"compare-uncommitted",mergeBase:o,tip:s},[a,c,l,{files:u},f]=await Promise.all([t.raw(Pt(i,["--numstat","-z"])),t.raw(Pt(i,["--name-status","-z"])),t.raw(Pt(i,[`-U${Tt}`])).then(lt),n,t.log({from:o,to:r})]),h=Ss(a,c,l),p=0,d=0;for(let y of h)p+=y.additions,d+=y.deletions;let g=u.length,R=f.all.map((y)=>({hash:y.hash,shortHash:y.hash.slice(0,7),message:y.message.split(`
31
- `)[0],author:y.author_name,date:new Date(y.date),refs:y.refs||""}));return{baseBranch:e,stats:{filesChanged:h.length,additions:p,deletions:d},files:h,commits:R,uncommittedCount:g}}async function vs(t,e,n="HEAD"){let r=S(t),s=await En(r,e,n),o=await r.raw(["rev-list","--count","--end-of-options",`${s}..${n}`]);return Number.parseInt(o.trim(),10)}async function ks(t,e,n="HEAD"){return En(S(t),e,n)}async function En(t,e,n){let r=(await t.raw(["merge-base","--end-of-options",e,n])).trim();if(!r)throw new xe(e);return r}function Pt(t,e){switch(t.kind){case"commit":return["show","--format=",...e,"--end-of-options",t.hash];case"compare":return["diff",...e,`${t.base}...${t.head??"HEAD"}`];case"compare-uncommitted":return["diff",...t.tip==="index"?["--cached"]:[],...e,t.mergeBase]}}async function Ua(t,e,n){let r=S(t),s=Pt(e,["--name-status","-z","-M","--diff-filter=R"]),o;try{o=await r.raw(s)}catch(i){return v(`rename lookup for ${n} failed in ${t}: ${ve(i)}`),null}return fn(o).find((i)=>i.path===n)?.oldPath??null}async function Sn(t,e,n,r={}){let s=S(t),o=r.context??Tt;try{let i=await Ua(t,e,n),a=i===null?[n]:[i,n],c=Pt(e,["-M",`-U${o}`]),l=lt(await s.raw([...c,"--",...a]));return{lines:ut(l)}}catch(i){return ke(`git ${Pt(e,[]).join(" ")} -- ${n}`,t,i),{lines:[]}}}async function Rs(t,e){let n=S(t),r=(a)=>n.raw(["show","--format=",...a,"--end-of-options",e]),[s,o,i]=await Promise.all([r(["--numstat","-z"]),r(["--name-status","-z"]),r([`-U${Tt}`]).then(lt)]);return Ss(s,o,i)}async function _s(t,e){let n=S(t);try{let r=lt(await n.raw(["show","--format=",`-U${Tt}`,"--end-of-options",e]));return{lines:ut(r)}}catch(r){return ke(`git show ${e}`,t,r),{lines:[]}}}function qa(t){if(t.unstaged&&!t.staged)throw Error("Unstaged work sits on top of staged work, so it needs staged too");if(t.unstaged)return"worktree";if(t.staged)return"index";return null}function gs(t){return t!==""&&t!==" "&&t!=="?"&&t!=="!"}function Xa(t,e,n){let r=new Set,s=new Set;for(let o of e.files){if(gs(o.index)){if(r.add(o.path),o.from)r.add(o.from)}if(n==="worktree"&&gs(o.working_dir))s.add(o.path)}return t.map((o)=>{let i=za(r.has(o.path),s.has(o.path));return i===null?o:{...o,uncommitted:i}})}function za(t,e){if(t&&e)return"both";if(t)return"staged";if(e)return"unstaged";return null}async function Ja(t,e){let n=e.files.filter((o)=>o.working_dir==="?").map((o)=>o.path),r=await Rt(t,n),s=[];for(let o of n){if(r.has(o))continue;let i=await gt(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 As(t,e,n=ds,r){let s=qa(n);if(s===null&&!n.untracked)return Ga(t,e,r);if(r!==void 0)throw Error("Uncommitted work can only be compared against HEAD, not a named head");let o=S(t),i=o.status(),[a,c,l]=await Promise.all([xs(o,e,i,"HEAD",s??void 0),i,n.untracked?i.then((h)=>Ja(t,h)):[]]),f=[...s===null?a.files:Xa(a.files,c,s),...l].sort((h,p)=>h.path.localeCompare(p.path));return{baseBranch:a.baseBranch,stats:{filesChanged:new Set(f.map((h)=>h.path)).size,additions:f.reduce((h,p)=>h+p.additions,0),deletions:f.reduce((h,p)=>h+p.deletions,0)},files:f,commits:a.commits,uncommittedCount:a.uncommittedCount}}import*as Is from"node:fs";import*as Ds from"node:path";function _e(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 Ka(t){let e=[],n="",r=null,s=()=>{if(r&&n)e.push({file:n,key:`${n}\x00${_e(r.body)}`,headerLine:r.headerLine});r=null};for(let o of t.lines)if(o.type==="header"){if(s(),o.content.startsWith("diff --git"))n=pt(o.content)??""}else if(o.type==="hunk")s(),r={headerLine:o,body:[]};else if(r&&(o.type==="addition"||o.type==="deletion"))r.body.push(o.content);return s(),e}class xn{repoPath;stamps=new Map;constructor(t){this.repoPath=t}stamp(t){if(!t)return;let e=new Map;for(let n of Ka(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 Is.statSync(Ds.join(this.repoPath,t)).mtimeMs}catch{return Date.now()}}}import*as V from"node:fs";import*as C from"node:path";async function Ya(t){let e=kn(t);if(!e)return null;try{let n=S(e);if((await n.raw(["rev-parse","--is-bare-repository"])).trim()==="true")return null;return(await n.raw(["rev-parse","--show-toplevel"])).trim()||null}catch(n){return H("rev-parse failed",n,{dir:e}),null}}async function Ae(t,{mustExist:e}){let n=K(t);if(!C.isAbsolute(n))return{ok:!1,reason:"not-absolute",requested:n};if(e&&!Va(n))return{ok:!1,reason:"not-a-repo",requested:n};let r=await Ya(n);if(r)return{ok:!0,root:r};let s=ec(await Qa(n));return s?{ok:!0,root:s.path}:{ok:!1,reason:"not-a-repo",requested:n}}function Va(t){try{return V.statSync(t).isDirectory()}catch{return!1}}async function Qa(t){let e=kn(t);if(!e)return[];try{let n=S(e);return Fs(await n.raw(["worktree","list","--porcelain"]))}catch(n){return H("worktree list failed",n,{dir:e}),[]}}async function vn(t){let e=kn(t);if(!e)return[];try{let r=await S(e).raw(["worktree","list","--porcelain"]),s=Fs(r),o=await tc(s);return s.map((i)=>({...i,lastActivity:i.isBare?null:Za(Ps(i.path)),aheadOfBase:o.get(i.path)??null}))}catch(n){return H("worktree list failed",n,{dir:e}),[]}}function Za(t){return Number.isFinite(t)?t:null}async function tc(t){let e=await Promise.all(t.filter((n)=>!n.isBare).map(async(n)=>{let r=Dt(n.path);if(r===void 0){let s=await wn(n.path);return s?[n.path,s.ahead]:null}try{let o=await S(n.path).raw(["rev-list","--count","--end-of-options",`${r}..HEAD`]);return[n.path,parseInt(o.trim(),10)]}catch{return null}}));return new Map(e.filter((n)=>n!==null))}function ec(t){let e=null,n=-1/0;for(let r of t){if(r.isBare)continue;let s=Ps(r.path);if(s>n)n=s,e=r}return e}function Ps(t){let e=Ms(t),n=e?[C.join(e,"index"),C.join(e,"HEAD")]:[t],r=-1/0;for(let s of n)try{let o=V.statSync(s).mtimeMs;if(o>r)r=o}catch{}return r}function Ms(t){let e=C.join(t,".git");try{if(V.statSync(e).isDirectory())return e;let n=V.readFileSync(e,"utf8").match(/^gitdir:\s*(.+)$/m);if(!n)return null;let r=n[1].trim();return C.isAbsolute(r)?r:C.resolve(t,r)}catch{return null}}function Ts(t){let e=Ms(t);if(e===null)return null;let n=e;try{let r=V.readFileSync(C.join(e,"commondir"),"utf8").trim();if(r)n=C.isAbsolute(r)?r:C.resolve(e,r)}catch{}return{gitDir:e,commonDir:n}}function Fs(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 kn(t){try{if(V.statSync(t).isDirectory())return t;return C.dirname(t)}catch{let e=C.dirname(t);return e!==t&&V.existsSync(e)?e:null}}var fc=Gi(Us(),1);function qs(t){return pt(t)}function Pe(t){let e=new Map,n=null;for(let s of t.lines){if(s.type==="header"&&s.content.startsWith("diff --git")){let o=qs(s.content);if(o!==null)n=e.get(o)??[],e.set(o,n);else n=null}n?.push(s)}let r=new Map;for(let[s,o]of e)r.set(s,{lines:o});return r}var Me="diffstalker-journal: oversize untracked snapshot omitted";var pc=262144,mc=new Set(["EACCES","EPERM","ENOENT"]);function gc(t){let e=t?.code;return typeof e==="string"&&mc.has(e)}function wc(){return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1}}class Te extends dc{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 xn(t)}get state(){return this._state}get unavailable(){return this._state.status?.isRepo===!1?this.unavailableReason:null}unavailableReason=null;updateState(t){this._state={...this._state,...t},this.emit("state-change",this._state)}setError(t){this.updateState({error:t})}clearError(){if(this._state.error!==null)this.updateState({error:null})}stampDiff(t){this.hunkTimes.stamp(t)}loadGitignores(){let t=new Map,e=zs();e.add(".git");let n=F.join(this.repoPath,".gitignore");if(G.existsSync(n))e.add(G.readFileSync(n,"utf-8"));let r=F.join(this.repoPath,".git","info","exclude");if(G.existsSync(r))e.add(G.readFileSync(r,"utf-8"));t.set("",e);try{let s=hc("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:ct(),stdio:["ignore","pipe","pipe"]});for(let o of s.split("\x00")){if(!o||o===".gitignore")continue;if(!o.endsWith(".gitignore"))continue;let i=F.dirname(o),a=F.join(this.repoPath,o);try{let c=G.readFileSync(a,"utf-8"),l=zs();l.add(c),t.set(i,l)}catch(c){v(`Failed to read ${a}`,c,{repo:this.repoPath})}}}catch(s){v("git ls-files failed; nested .gitignore files are not applied",s,{repo:this.repoPath})}return t}startWatching(){let t=Ts(this.repoPath);if(t===null)return;let e=F.join(t.gitDir,"index"),n=F.join(t.gitDir,"HEAD"),r=F.join(t.commonDir,"refs"),s=F.join(t.commonDir,"packed-refs"),o=F.join(this.repoPath,".gitignore");this.gitWatcher=Xs([e,n,r,s,o],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=Xs(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(a)=>{let c=F.relative(this.repoPath,a);if(!c)return!1;let l=c.split("/");for(let u=0;u<l.length;u++){let f=u===0?"":l.slice(0,u).join("/"),h=this.ignorers.get(f);if(h){let p=u===0?c:l.slice(u).join("/");if(h.ignores(p))return!0}}return!1},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let i=()=>this.scheduleRefresh();this.gitWatcher.on("change",(a)=>{if(a===o)this.ignorers=this.loadGitignores();i()}),this.gitWatcher.on("add",i),this.gitWatcher.on("unlink",i),this.gitWatcher.on("error",(a)=>{this.logWatchError("Git dir watcher error",a),this.setError(`Git watcher error: ${a instanceof Error?a.message:String(a)}`)}),this.workingDirWatcher.on("change",i),this.workingDirWatcher.on("add",i),this.workingDirWatcher.on("unlink",i),this.workingDirWatcher.on("error",(a)=>{this.logWatchError("Working dir watcher error",a),this.setError(`Working dir watcher error: ${a instanceof Error?a.message:String(a)}`)})}logWatchError(t,e){if(gc(e))H(t,e,{repo:this.repoPath});else v(t,e,{repo:this.repoPath})}dispose(){let t=(e)=>(n)=>v(`Failed to close the ${e} watcher`,n,{repo:this.repoPath});this.gitWatcher?.close().catch(t("git dir")),this.workingDirWatcher?.close().catch(t("working dir"))}statMtimes(t){let e=new Map;for(let n of t.files){if(e.has(n.path))continue;try{e.set(n.path,G.statSync(F.join(this.repoPath,n.path)).mtimeMs)}catch{}}return e}pendingRefreshKind=null;scheduleRefresh(){this.requestRefresh("full")}scheduleStatusRefresh(){this.requestRefresh("status")}requestRefresh(t){if(this.pendingRefreshKind!==null){if(t==="full")this.pendingRefreshKind="full";return}if(this.queue.hasPendingMutations())return;this.pendingRefreshKind=t,this.queue.scheduleRefresh(async()=>{let e=this.pendingRefreshKind??"full";if(this.pendingRefreshKind=null,e==="full")await this.doRefresh();else await this.doStatusRefresh()})}notARepo(t,e){if(this._state.status?.isRepo!==!1)v(`${e} (was open as one)`,void 0,{repo:this.repoPath});this.unavailableReason=e,this.updateState({status:t,isLoading:!1,error:e})}refreshFailed(t,e){if(!G.existsSync(this.repoPath)){this.notARepo(wc(),"Repository directory no longer exists");return}v(t,e,{repo:this.repoPath}),this.updateState({isLoading:!1,error:e instanceof Error?e.message:"Unknown error"})}async doStatusRefresh(){try{let t=await dn(this.repoPath);if(!t.isRepo){this.notARepo(t,"Not a git repository");return}this.updateState({status:t,mtimes:this.statMtimes(t),isLoading:!1})}catch(t){this.refreshFailed("Status refresh failed",t)}}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.updateState({isLoading:!0,error:null});let t=Date.now(),e=await Re(this.repoPath).catch((n)=>(H("HEAD oid unreadable; journal observation skipped",n,{repo:this.repoPath}),null));try{let n=await dn(this.repoPath);if(!n.isRepo){this.notARepo(n,"Not a git repository");return}let r=this.snapshotJournalGuard(n),[s,o,{stashList:i,operation:a},c]=await Promise.all([Ft(this.repoPath,void 0,!1),Ft(this.repoPath,void 0,!0),r,this.gatherJournalInputs(n,e,t,r)]),l={unstaged:Ee(dt(s.lines)),staged:Ee(dt(o.lines))};this.hunkTimes.stamp(s),this.hunkTimes.stamp(o),this.hunkTimes.prune(new Set(n.files.map((f)=>f.path)));let u=this.statMtimes(n);if(this.updateState({status:n,hunkCounts:l,stashList:i,operationInProgress:a,mtimes:u,isLoading:!1}),c!==null)this.emit("journal-observation",{status:n,headDiff:c.headDiff,headOid:c.headOid,stashCount:c.stashCount,operationInProgress:c.operationInProgress,mtimes:c.mtimes,at:Date.now()})}catch(n){this.refreshFailed("Refresh failed",n)}}async snapshotJournalGuard(t){let[e,n]=await Promise.all([It(this.repoPath),pn(this.repoPath)]);return{operation:e,stashList:n,mtimes:this.statMtimes(t)}}static journalGuardMoved(t,e){if(t.operation!==e.operation||t.stashList.length!==e.stashList.length)return!0;if(t.mtimes.size!==e.mtimes.size)return!0;for(let[n,r]of t.mtimes)if(e.mtimes.get(n)!==r)return!0;return!1}sectionWrittenDuringGather(t,e,n){let r=new Set(e);for(let s of t.files)if(s.status==="untracked")r.add(s.path);for(let s of r)try{let o=G.statSync(F.join(this.repoPath,s));if(Math.floor(o.mtimeMs)>n)return!0}catch{}return!1}async gatherJournalInputs(t,e,n,r){if(e===null)return null;try{let s=await r,o=await bs(this.repoPath,e),i=new Set(Pe(o).keys()),a=[...o.lines];await this.appendUntrackedSections(t,i,a);let c=await Re(this.repoPath);if(e!==c)return null;let l=await this.snapshotJournalGuard(t);if(Te.journalGuardMoved(s,l))return null;if(this.sectionWrittenDuringGather(t,i,n))return null;return{headDiff:{lines:a},headOid:c,stashCount:l.stashList.length,operationInProgress:l.operation,mtimes:l.mtimes}}catch(s){return H("Journal observation skipped: git read failed",s,{repo:this.repoPath}),null}}async appendUntrackedSections(t,e,n){let r=new Set;for(let s of t.files){if(s.status!=="untracked"||r.has(s.path)||e.has(s.path))continue;r.add(s.path);let o;try{o=G.statSync(F.join(this.repoPath,s.path))}catch{continue}if(!o.isFile())continue;if(o.size>pc){this.appendOversizeSection(s.path,o,n);continue}let i=await gt(this.repoPath,s.path);if(i.lines.length===0)continue;n.push(...i.lines)}}appendOversizeSection(t,e,n){let r=[`diff --git ${_t("a/"+t)} ${_t("b/"+t)}`,"new file mode 100644",`${Me} size=${e.size} mtime=${Math.round(e.mtimeMs)}`];n.push(...r.map((s)=>({type:"header",content:s})))}failed(t,e,n){v(`Failed to ${t}`,e,{repo:this.repoPath,file:n}),this.updateState({error:`Failed to ${t}: ${e instanceof Error?e.message:String(e)}`})}async stage(t){try{await this.queue.enqueueMutation(()=>Lr(this.repoPath,t.path)),this.scheduleStatusRefresh()}catch(e){await this.refresh(),this.failed(`stage ${t.path}`,e,t.path)}}async unstage(t){try{await this.queue.enqueueMutation(()=>Hr(this.repoPath,t.path)),this.scheduleStatusRefresh()}catch(e){await this.refresh(),this.failed(`unstage ${t.path}`,e,t.path)}}async stageHunk(t){try{await this.queue.enqueueMutation(async()=>zr(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.failed("stage hunk",e)}}async unstageHunk(t){try{await this.queue.enqueueMutation(async()=>Jr(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.failed("unstage hunk",e)}}async discard(t){if(t.staged)return;let e=t.status==="untracked"?()=>Gr(this.repoPath,t.path):()=>Wr(this.repoPath,t.path);try{await this.queue.enqueueMutation(e),await this.refresh()}catch(n){this.failed(`discard ${t.path}`,n,t.path)}}async stageAll(){try{await this.queue.enqueueMutation(()=>Br(this.repoPath)),await this.refresh()}catch(t){this.failed("stage all",t)}}async unstageAll(){try{await this.queue.enqueueMutation(()=>jr(this.repoPath)),await this.refresh()}catch(t){this.failed("unstage all",t)}}async commit(t,e=!1){try{await this.queue.enqueue(()=>Ur(this.repoPath,t,e)),await this.refresh()}catch(n){this.failed("commit",n)}}async loadStashList(){try{let t=await this.queue.enqueue(()=>pn(this.repoPath));this.updateState({stashList:t})}catch(t){v("Failed to load the stash list",t,{repo:this.repoPath})}}}import{EventEmitter as yc}from"node:events";class In extends yc{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){v(`git ${t} failed`,n,{repo:this.repoPath});let r=n instanceof Error?n.message:String(n);this.updateRemoteState({inProgress:!1,error:r})}return this._remoteState}async push(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("push",()=>Kr(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>Yr(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",()=>ts(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",()=>es(this.repoPath,t));return await this.callbacks.loadStashList(),e}async switchBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>rs(this.repoPath,t))}async createBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>ss(this.repoPath,t))}async softReset(t=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>os(this.repoPath,t))}async cherryPick(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>is(this.repoPath,t))}async revertCommit(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>as(this.repoPath,t))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>cs(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>ls(this.repoPath))}}import{EventEmitter as bc}from"node:events";import{randomBytes as Ec}from"node:crypto";var Sc=262144,xc=500,vc=16777216,Ys=Number.MAX_SAFE_INTEGER,kc=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function Rc(t){let e=kc.exec(t);if(!e)return null;return{oldStart:parseInt(e[1],10),oldCount:e[2]!==void 0?parseInt(e[2],10):1}}function _c(t,e){let n=Rc(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=Ac(o,r),r++;else if(a==="+")o=o??{hasDel:!1,delStart:0,delEnd:0,anchor:r-1};else Js(s,o),o=null,r++}return Js(s,o),s}function Ac(t,e){if(!t)return{hasDel:!0,delStart:e,delEnd:e,anchor:e-1};if(!t.hasDel)t.hasDel=!0,t.delStart=e;return t.delEnd=e,t}function Js(t,e){if(!e)return;t.push(e.hasDel?[2*e.delStart,2*e.delEnd]:[2*e.anchor,2*e.anchor+2])}function Dn(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>=Ys)return{start:0,count:0};let r=Math.ceil(e/2),s=Math.floor(n/2);return{start:r,count:s-r+1}}function Ic(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(Me));return{hunks:[{runs:[[0,Ys]],bodyHash:_e([dt(t.lines)]),ins:0,del:0,span:{start:0,count:0},diff:t,oversize:i}],renamedFrom:n,hunkless:!0}}return{hunks:r.map(({header:i,body:a})=>{let c=_c(a,i.content),l=[],u=0,f=0;for(let p of a){let d=p.content[0];if(d==="\\")continue;if(d==="+")u++,l.push(p.content);else if(d==="-")f++,l.push(p.content)}let h=[...e,i,...a];return{runs:c,bodyHash:_e(l),ins:u,del:f,span:Dn(c),diff:{lines:h}}}),renamedFrom:n,hunkless:!1}}function Dc(t){if(t.oversize===!0)return null;return be(t.diff.lines)>Sc?null:t.diff}function Pc(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 Ks(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 Mc(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=Ks(t,0),i=Ks(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 Tc(t,e){let n=Mc(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 Fc(t,e,n){let r=[],s=e.map(()=>null),o=n;for(let i of Tc(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:Dn(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":Pc(h.ins,h.del,u),span:h.span,stats:{insertions:h.ins,deletions:h.del},diff:Dc(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 $c(t,e){let n=Array(t.length).fill(!1),r=Array(e.length).fill(null);for(let a=0;a<e.length;a++){let c=t.findIndex((l,u)=>!n[u]&&l.bodyHash===e[a].bodyHash);if(c!==-1)n[c]=!0,r[a]=t[c].seq}for(let a=0;a<e.length;a++){if(r[a]!==null)continue;let c=n.findIndex((l)=>!l);if(c!==-1)n[c]=!0,r[a]=t[c].seq}let s=t[t.length-1].seq,o=e.map((a,c)=>({seq:r[c]??s,runs:a.runs,bodyHash:a.bodyHash,ins:a.ins,del:a.del})),i=t.filter((a,c)=>!n[c]).map((a)=>a.seq);return{carried:o,retired:i}}function Fe(){return{entries:[],epoch:`${Date.now().toString(36)}-${Ec(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class Pn extends bc{store;constructor(t){super();this.store=t}get journalStore(){return this.store}observe(t){try{this.doObserve(t)}catch(e){T("Journal observation skipped: classifier threw",e)}}doObserve(t){let e=[];if(this.store.lastHeadOid===null){if(t.operationInProgress===null)this.seed(t,e)}else if(this.handleOperations(t,e));else if(t.headOid!==this.store.lastHeadOid)this.rebaseline(t,e);else this.classify(t,e);if(e.length>0)this.store.entries.push(...e),this.emit("append",e),this.pruneStore()}pruneStore(){let t=new Set;for(let e of this.store.live.values())for(let n of e)t.add(n.seq);this.pruneBodies(t),this.pruneEntries(t)}pruneBodies(t){let e=0;for(let n of this.store.entries)if(n.type==="hunk"&&n.diff!==null)e+=be(n.diff.lines);for(let n of this.store.entries){if(e<=vc)return;if(n.type!=="hunk"||n.diff===null||t.has(n.seq))continue;e-=be(n.diff.lines),n.diff=null}}pruneEntries(t){let e=this.store.entries,n=0;while(e.length-n>xc&&(e[n].type==="boundary"||!t.has(e[n].seq)))n++;if(n>0)e.splice(0,n)}handleOperations(t,e){let n=this.store.lastOperation;if(t.operationInProgress!==null){if(n===null)e.push(this.boundary("op-start",t.operationInProgress,[],t.at)),this.store.lastOperation=t.operationInProgress;return!0}if(n!==null)e.push(this.boundary("op-end",n,[],t.at)),this.store.lastOperation=null;return!1}seed(t,e){e.push(this.boundary("journal-start",t.status.branch.current,[],t.at));let{files:n}=this.parseObservation(t),r=[...n.keys()].sort((s,o)=>this.tsFor(t,s)-this.tsFor(t,o));for(let s of r)this.classifyPath(s,[],n.get(s).hunks,t,!0,e);this.store.lastHeadOid=t.headOid,this.store.lastBranch=t.status.branch.current,this.store.lastStashCount=t.stashCount,this.store.lastOperation=null}rebaseline(t,e){let{files:n,deferred:r}=this.parseObservation(t),s=t.status.branch.current===this.store.lastBranch,o=s?"commit":"checkout",i=s?t.headOid.slice(0,7):t.status.branch.current,{resolves:a,newLive:c}=this.carrySurvivors(n,r);e.push(this.boundary(o,i,a,t.at)),this.store.live=c;for(let[l,{hunks:u}]of n){if(c.has(l))continue;this.classifyPath(l,[],u,t,!1,e)}this.store.lastHeadOid=t.headOid,this.store.lastBranch=t.status.branch.current,this.store.lastStashCount=t.stashCount}carrySurvivors(t,e){let n=[],r=new Map;for(let[s,o]of this.store.live){if(e.has(s)){r.set(s,o);continue}let i=t.get(s);if(!i){n.push(...o.map((l)=>l.seq));continue}let{carried:a,retired:c}=$c(o,i.hunks);n.push(...c),r.set(s,a)}return{resolves:n,newLive:r}}classify(t,e){let{files:n,deferred:r}=this.parseObservation(t);this.handleRenames(t,n,e),this.handleDisappearances(t,n,r,e);for(let[s,{hunks:o,renamedFrom:i,hunkless:a}]of n){let c=this.store.live.get(s)??[];if(a&&i!==null&&c.length>0)continue;this.classifyPath(s,c,o,t,!1,e)}this.store.lastBranch=t.status.branch.current,this.store.lastStashCount=t.stashCount}handleRenames(t,e,n){for(let[r,s]of e){let o=s.renamedFrom;if(o===null||o===r)continue;if(!this.store.live.has(o)||e.has(o))continue;let i=(this.store.live.get(r)??[]).map((a)=>a.seq);this.store.live.set(r,this.store.live.get(o)),this.store.live.delete(o),n.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor(t,r),path:r,status:"renamed",kind:"renamed",span:{start:0,count:0},stats:{insertions:0,deletions:0},diff:null,supersedes:i,siblings:1,seeded:!1})}}handleDisappearances(t,e,n,r){let s=[...this.store.live.keys()].filter((o)=>!e.has(o)&&!n.has(o));if(s.length===0)return;if(t.stashCount>this.store.lastStashCount){let o=s.flatMap((i)=>this.store.live.get(i).map((a)=>a.seq));r.push(this.boundary("stash","stash",o,t.at));for(let i of s)this.store.live.delete(i);return}for(let o of s){let i=this.store.live.get(o);r.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor(t,o),path:o,status:this.statusOf(t,o),kind:"reverted",span:Dn(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}=Fc(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 Pe(t.headDiff))e.set(r,Ic(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 Mn{workingTree;remote;journal;repoPath;constructor(t,e){this.repoPath=t;let n=Ar(t);this.workingTree=new Te(t,n),this.remote=new In(t,n,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new Pn(e??Fe()),this.workingTree.on("journal-observation",(r)=>this.journal.observe(r))}dispose(){this.workingTree.dispose(),Ir(this.repoPath)}}function Nc(t){return Oc("sha256").update(t).digest("hex").slice(0,12)}var Cc=32;class Vs{cap;stores=new Map;constructor(t=Cc){this.cap=t}acquire(t){let e=this.stores.get(t);if(e)this.stores.delete(t);else e=Fe();return this.stores.set(t,e),e}prune(t){if(this.stores.size<=this.cap)return;for(let e of this.stores.keys()){if(this.stores.size<=this.cap)return;if(t(e))continue;this.stores.delete(e)}}has(t){return this.stores.has(t)}get size(){return this.stores.size}}class $e extends Error{reason;requested;constructor(t,e){super(t==="not-absolute"?`Repo path must be absolute: ${e}`:`Not a git repository: ${e}`);this.reason=t,this.requested=e,this.name="RepoOpenRefused"}}class Tn{events;byId=new Map;byPath=new Map;journalStores=new Vs;constructor(t={}){this.events=t}async openRepo(t){let e=await Ae(t,{mustExist:!1});if(!e.ok)throw new $e(e.reason,e.requested);let n=e.root,r=this.byPath.get(n);if(r)return r.refCount++,{handle:r,created:!1};let s=Nc(n),o=new Mn(n,this.journalStores.acquire(s));o.workingTree.startWatching();let i={id:s,path:n,manager:o,refCount:1};return this.byId.set(i.id,i),this.byPath.set(n,i),this.journalStores.prune((a)=>this.byId.has(a)),this.events.onOpened?.(i),{handle:i,created:!0}}getRepo(t){return this.byId.get(t)}listRepos(){return[...this.byId.values()]}closeRepo(t){let e=this.byId.get(t);if(!e)return!1;if(e.refCount--,e.refCount>0)return!1;return this.byId.delete(e.id),this.byPath.delete(e.path),e.manager.dispose(),this.events.onClosed?.(e.id),!0}disposeAll(){for(let t of this.byId.values())t.manager.dispose();this.byId.clear(),this.byPath.clear()}}function Fn(t){t.manager.workingTree.refresh().catch((e)=>{T("First refresh threw",e,{repo:t.path})})}async function Oe(t,e){let n=await t.openRepo(e);if(n.created)Fn(n.handle);return n}var Zs=25000;function $t(t,e,n){t.write(`event: ${e}
26
+ `);if(i)a.pop();if(s.length>0){o.push({type:"hunk",content:`@@ -0,0 +1,${a.length} @@`});let u=1;for(let f of a)o.push({type:"addition",content:"+"+f,newLineNum:u++});if(!i)o.push({type:"context",content:"\"})}let c=dt(o),l=lt(c);if(l!==c)return{lines:ut(l)};return{lines:o}}catch(n){return Re(`reading untracked file ${e}`,t,n),{lines:[]}}}var ae="refs/remotes/";async function ks(t){let e=x(t),n=new Set,r=[];try{let s=await e.raw(["log","--oneline","--decorate=full","--all","-n","200"]),o=/\(([^)]+)\)/g;for(let a of s.split(`
27
+ `)){let c=o.exec(a);if(c)for(let l of c[1].split(",")){let u=l.trim().replace(/^.*-> /,"");if(!u.startsWith(ae))continue;let f=u.slice(ae.length);if(f.endsWith("/HEAD")||n.has(f))continue;n.add(f),r.push(f)}o.lastIndex=0}let i=(a)=>{let c=a.split("/").slice(1).join("/");return c==="main"||c==="master"};r.sort((a,c)=>Number(i(c))-Number(i(a)))}catch(s){E(`git log for base-branch discovery failed in ${t}: ${ke(s)}`)}return r}var ys=["upstream","origin"];function bs(t){let e=ys.indexOf(t);return e===-1?ys.length:e}async function yn(t){let e=x(t),n=(await e.raw(["remote"])).split(`
28
+ `).filter(Boolean),r=new Map,s=await e.raw(["for-each-ref","--format=%(refname) %(objectname) %(symref)",ae]);for(let i of s.split(`
29
+ `)){let[a,c,l=""]=i.split(" ");if(a)r.set(a,{commit:c,symref:l})}let o=[];for(let i of n){let a=`${ae}${i}/`,c=r.get(`${a}HEAD`)?.symref,l=c&&r.has(c)?c:[`${a}main`,`${a}master`].find((u)=>r.has(u));if(l)o.push({remote:i,ref:l,commit:r.get(l).commit})}return o}async function bn(t,e,n="HEAD"){let r=await x(t).raw(["rev-list","--count",`${e}..${n}`]);return parseInt(r.trim(),10)}function En(t){let e=[...t].sort((n,r)=>n.ahead-r.ahead||bs(n.remote)-bs(r.remote)||(n.remote<r.remote?-1:1))[0];return e?{branch:e.ref.slice(ae.length),ahead:e.ahead}:null}async function Ka(t){try{let e=await yn(t),n=await Promise.all(e.map(async({remote:r,ref:s})=>({remote:r,ref:s,ahead:await bn(t,s)})));return En(n)}catch(e){return E(`default base-branch discovery failed in ${t}: ${ke(e)}`),null}}async function Sn(t){return(await Ka(t))?.branch??null}async function vn(t){return Dt(t)??await Sn(t)}async function nt(t,e){let n=x(t);try{return await n.raw(["cat-file","-e","--end-of-options",`${e}^{commit}`]),!0}catch{return!1}}function Ya(t){let e=t.indexOf(`
30
+ `);return pt(e===-1?t:t.slice(0,e))}function Rs(t,e,n){let r=re(t),s=new Map;for(let a of hn(e)){let c;switch(a.code){case"A":c="added";break;case"D":c="deleted";break;case"R":c="renamed";break;default:c="modified"}s.set(a.path,c)}let o=[],i=n.split(/(?=^diff --git )/m).filter((a)=>a.trim());for(let a of i){let c=Ya(a);if(c===null)continue;let l=ut(a),u=r.get(c)||{additions:0,deletions:0},f=s.get(c)||"modified";o.push({path:c,status:f,additions:u.additions,deletions:u.deletions,diff:{lines:l}})}return o.sort((a,c)=>a.path.localeCompare(c.path)),o}async function Va(t,e,n){let r=x(t);return _s(r,e,r.status(),n)}async function _s(t,e,n,r="HEAD",s){let o=await xn(t,e,r),i=s===void 0?{kind:"compare",base:o,head:r}:{kind:"compare-uncommitted",mergeBase:o,tip:s},[a,c,l,{files:u},f]=await Promise.all([t.raw(Pt(i,["--numstat","-z"])),t.raw(Pt(i,["--name-status","-z"])),t.raw(Pt(i,[`-U${Mt}`])).then(lt),n,t.log({from:o,to:r})]),h=Rs(a,c,l),d=0,p=0;for(let y of h)d+=y.additions,p+=y.deletions;let g=u.length,S=f.all.map((y)=>({hash:y.hash,shortHash:y.hash.slice(0,7),message:y.message.split(`
31
+ `)[0],author:y.author_name,date:new Date(y.date),refs:y.refs||""}));return{baseBranch:e,stats:{filesChanged:h.length,additions:d,deletions:p},files:h,commits:S,uncommittedCount:g}}async function As(t,e,n="HEAD"){let r=x(t),s=await xn(r,e,n),o=await r.raw(["rev-list","--count","--end-of-options",`${s}..${n}`]);return Number.parseInt(o.trim(),10)}async function Is(t,e,n="HEAD"){return xn(x(t),e,n)}async function xn(t,e,n){let r=(await t.raw(["merge-base","--end-of-options",e,n])).trim();if(!r)throw new xe(e);return r}function Pt(t,e){switch(t.kind){case"commit":return["show","--format=",...e,"--end-of-options",t.hash];case"compare":return["diff",...e,`${t.base}...${t.head??"HEAD"}`];case"compare-uncommitted":return["diff",...t.tip==="index"?["--cached"]:[],...e,t.mergeBase]}}async function Qa(t,e,n){let r=x(t),s=Pt(e,["--name-status","-z","-M","--diff-filter=R"]),o;try{o=await r.raw(s)}catch(i){return E(`rename lookup for ${n} failed in ${t}: ${ke(i)}`),null}return hn(o).find((i)=>i.path===n)?.oldPath??null}async function kn(t,e,n,r={}){let s=x(t),o=r.context??Mt;try{let i=await Qa(t,e,n),a=i===null?[n]:[i,n],c=Pt(e,["-M",`-U${o}`]),l=lt(await s.raw([...c,"--",...a]));return{lines:ut(l)}}catch(i){return Re(`git ${Pt(e,[]).join(" ")} -- ${n}`,t,i),{lines:[]}}}async function Ds(t,e){let n=x(t),r=(a)=>n.raw(["show","--format=",...a,"--end-of-options",e]),[s,o,i]=await Promise.all([r(["--numstat","-z"]),r(["--name-status","-z"]),r([`-U${Mt}`]).then(lt)]);return Rs(s,o,i)}async function Ps(t,e){let n=x(t);try{let r=lt(await n.raw(["show","--format=",`-U${Mt}`,"--end-of-options",e]));return{lines:ut(r)}}catch(r){return Re(`git show ${e}`,t,r),{lines:[]}}}function Za(t){if(t.unstaged&&!t.staged)throw Error("Unstaged work sits on top of staged work, so it needs staged too");if(t.unstaged)return"worktree";if(t.staged)return"index";return null}function Es(t){return t!==""&&t!==" "&&t!=="?"&&t!=="!"}function tc(t,e,n){let r=new Set,s=new Set;for(let o of e.files){if(Es(o.index)){if(r.add(o.path),o.from)r.add(o.from)}if(n==="worktree"&&Es(o.working_dir))s.add(o.path)}return t.map((o)=>{let i=ec(r.has(o.path),s.has(o.path));return i===null?o:{...o,uncommitted:i}})}function ec(t,e){if(t&&e)return"both";if(t)return"staged";if(e)return"unstaged";return null}async function nc(t,e){let n=e.files.filter((o)=>o.working_dir==="?").map((o)=>o.path),r=await Rt(t,n),s=[];for(let o of n){if(r.has(o))continue;let i=await gt(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 Ts(t,e,n=ws,r){let s=Za(n);if(s===null&&!n.untracked)return Va(t,e,r);if(r!==void 0)throw Error("Uncommitted work can only be compared against HEAD, not a named head");let o=x(t),i=o.status(),[a,c,l]=await Promise.all([_s(o,e,i,"HEAD",s??void 0),i,n.untracked?i.then((h)=>nc(t,h)):[]]),f=[...s===null?a.files:tc(a.files,c,s),...l].sort((h,d)=>h.path.localeCompare(d.path));return{baseBranch:a.baseBranch,stats:{filesChanged:new Set(f.map((h)=>h.path)).size,additions:f.reduce((h,d)=>h+d.additions,0),deletions:f.reduce((h,d)=>h+d.deletions,0)},files:f,commits:a.commits,uncommittedCount:a.uncommittedCount}}import*as Ms from"node:fs";import*as Fs from"node:path";function Ae(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 rc(t){let e=[],n="",r=null,s=()=>{if(r&&n)e.push({file:n,key:`${n}\x00${Ae(r.body)}`,headerLine:r.headerLine});r=null};for(let o of t.lines)if(o.type==="header"){if(s(),o.content.startsWith("diff --git"))n=pt(o.content)??""}else if(o.type==="hunk")s(),r={headerLine:o,body:[]};else if(r&&(o.type==="addition"||o.type==="deletion"))r.body.push(o.content);return s(),e}class Rn{repoPath;stamps=new Map;constructor(t){this.repoPath=t}stamp(t){if(!t)return;let e=new Map;for(let n of rc(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 Ms.statSync(Fs.join(this.repoPath,t)).mtimeMs}catch{return Date.now()}}}import*as V from"node:fs";import*as N from"node:path";async function sc(t){let e=An(t);if(!e)return null;try{let n=x(e);if((await n.raw(["rev-parse","--is-bare-repository"])).trim()==="true")return null;return(await n.raw(["rev-parse","--show-toplevel"])).trim()||null}catch(n){return L("rev-parse failed",n,{dir:e}),null}}async function Ie(t,{mustExist:e}){let n=K(t);if(!N.isAbsolute(n))return{ok:!1,reason:"not-absolute",requested:n};if(e&&!oc(n))return{ok:!1,reason:"not-a-repo",requested:n};let r=await sc(n);if(r)return{ok:!0,root:r};let s=wc(await ic(n));return s?{ok:!0,root:s.path}:{ok:!1,reason:"not-a-repo",requested:n}}function oc(t){try{return V.statSync(t).isDirectory()}catch{return!1}}async function ic(t){let e=An(t);if(!e)return[];try{let n=x(e);return Bs(await n.raw(["worktree","list","--porcelain"]))}catch(n){return L("worktree list failed",n,{dir:e}),[]}}async function _n(t){let e=An(t);if(!e)return[];try{let r=await x(e).raw(["worktree","list","--porcelain"]),s=Bs(r),o=await gc(e,s);return s.map((i)=>({...i,lastActivity:i.isBare?null:ac(Ns(i.path)),aheadOfBase:o.get(i.path)??null}))}catch(n){return L("worktree list failed",n,{dir:e}),[]}}function ac(t){return Number.isFinite(t)?t:null}class $s{size;active=0;waiting=[];constructor(t){this.size=t}async run(t){if(this.active>=this.size)await new Promise((e)=>this.waiting.push(e));this.active++;try{return await t()}finally{this.active--,this.waiting.shift()?.()}}}var cc=8,Cs=new $s(cc),lc=512,Ft=new Map,uc=/^0+$/;function fc(t,e){if(Ft.delete(t),Ft.set(t,e),Ft.size>lc)Ft.delete(Ft.keys().next().value)}function hc(t,e){return[t,...e.map((n)=>`${n.ref}=${n.commit}`).sort()].join(`
32
+ `)}async function dc(t,e,n){let r=await Promise.all(n.map(async({remote:s,ref:o,commit:i})=>({remote:s,ref:o,ahead:await Cs.run(()=>bn(t,i,e))})));return En(r)?.ahead??null}async function pc(t,e){if(t.head===null||uc.test(t.head))return null;let n=hc(t.head,e),r=Ft.get(t.path);if(r!==void 0&&r.key===n)return r.ahead;try{let s=await dc(t.path,t.head,e);return fc(t.path,{key:n,ahead:s}),s}catch(s){return E("default base-branch count failed",s,{worktree:t.path}),null}}async function mc(t,e){try{let n=x(t),r=await Cs.run(()=>n.raw(["rev-list","--count","--end-of-options",`${e}..HEAD`]));return parseInt(r.trim(),10)}catch{return null}}async function gc(t,e){let n;try{n=await yn(t)}catch(s){E("default base-branch discovery failed",s,{repo:t}),n=null}let r=await Promise.all(e.filter((s)=>!s.isBare).map(async(s)=>{let o=Dt(s.path),i=null;if(o!==void 0)i=await mc(s.path,o);else if(n!==null)i=await pc(s,n);return i===null?null:[s.path,i]}));return new Map(r.filter((s)=>s!==null))}function wc(t){let e=null,n=-1/0;for(let r of t){if(r.isBare)continue;let s=Ns(r.path);if(s>n)n=s,e=r}return e}function Ns(t){let e=Os(t),n=e?[N.join(e,"index"),N.join(e,"HEAD")]:[t],r=-1/0;for(let s of n)try{let o=V.statSync(s).mtimeMs;if(o>r)r=o}catch{}return r}function Os(t){let e=N.join(t,".git");try{if(V.statSync(e).isDirectory())return e;let n=V.readFileSync(e,"utf8").match(/^gitdir:\s*(.+)$/m);if(!n)return null;let r=n[1].trim();return N.isAbsolute(r)?r:N.resolve(t,r)}catch{return null}}function Ls(t){let e=Os(t);if(e===null)return null;let n=e;try{let r=V.readFileSync(N.join(e,"commondir"),"utf8").trim();if(r)n=N.isAbsolute(r)?r:N.resolve(e,r)}catch{}return{gitDir:e,commonDir:n}}function Bs(t){let e=[],n=null;for(let r of t.split(`
33
+ `))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 An(t){try{if(V.statSync(t).isDirectory())return t;return N.dirname(t)}catch{let e=N.dirname(t);return e!==t&&V.existsSync(e)?e:null}}var Ac=Vi(Ys(),1);function Vs(t){return pt(t)}function Te(t){let e=new Map,n=null;for(let s of t.lines){if(s.type==="header"&&s.content.startsWith("diff --git")){let o=Vs(s.content);if(o!==null)n=e.get(o)??[],e.set(o,n);else n=null}n?.push(s)}let r=new Map;for(let[s,o]of e)r.set(s,{lines:o});return r}var Me="diffstalker-journal: oversize untracked snapshot omitted";var Pc=262144,Tc=new Set(["EACCES","EPERM","ENOENT"]),Tn=47;function Mc(t,e){if(e==="")return t;if(t.startsWith(e)&&t.charCodeAt(e.length)===Tn)return t.slice(e.length+1);return null}function Fc(t){let e=t?.code;return typeof e==="string"&&Tc.has(e)}function $c(){return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1}}class Fe extends Dc{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 Rn(t)}get state(){return this._state}_wholeTreeDiffs=null;fullRefreshRunning=!1;diffWaiters=[];async wholeTreeDiffs(){if(this._wholeTreeDiffs)return this._wholeTreeDiffs;let t=new Promise((e)=>this.diffWaiters.push(e));if(!this.fullRefreshRunning)this.refresh().catch((e)=>{T("Refresh for whole-tree diffs threw",e,{repo:this.repoPath})});return await t,this._wholeTreeDiffs}settleDiffWaiters(){let t=this.diffWaiters;this.diffWaiters=[];for(let e of t)e()}get unavailable(){return this._state.status?.isRepo===!1?this.unavailableReason:null}unavailableReason=null;updateState(t){this._state={...this._state,...t},this.emit("state-change",this._state)}setError(t){this.updateState({error:t})}clearError(){if(this._state.error!==null)this.updateState({error:null})}stampDiff(t){this.hunkTimes.stamp(t)}loadGitignores(){let t=new Map,e=Zs();e.add(".git");let n=B.join(this.repoPath,".gitignore");if(U.existsSync(n))e.add(U.readFileSync(n,"utf-8"));let r=B.join(this.repoPath,".git","info","exclude");if(U.existsSync(r))e.add(U.readFileSync(r,"utf-8"));t.set("",e);try{let s=Ic("git",["ls-files","-z","--cached","--others","--exclude-standard","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:ct(),stdio:["ignore","pipe","pipe"]});for(let o of s.split("\x00")){if(!o||o===".gitignore")continue;if(!o.endsWith(".gitignore"))continue;let i=B.dirname(o),a=B.join(this.repoPath,o);try{let c=U.readFileSync(a,"utf-8"),l=Zs();l.add(c),t.set(i,l)}catch(c){E(`Failed to read ${a}`,c,{repo:this.repoPath})}}}catch(s){E("git ls-files failed; nested .gitignore files are not applied",s,{repo:this.repoPath})}return t}startWatching(){let t=Ls(this.repoPath);if(t===null)return;let e=B.join(t.gitDir,"index"),n=B.join(t.gitDir,"HEAD"),r=B.join(t.commonDir,"refs"),s=B.join(t.commonDir,"packed-refs"),o=B.join(this.repoPath,".gitignore");this.gitWatcher=Qs([e,n,r,s,o],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=Qs(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(a)=>this.isIgnored(a),awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let i=()=>this.scheduleRefresh();this.gitWatcher.on("change",(a)=>{if(a===o)this.ignorers=this.loadGitignores();i()}),this.gitWatcher.on("add",i),this.gitWatcher.on("unlink",i),this.gitWatcher.on("error",(a)=>{this.logWatchError("Git dir watcher error",a),this.setError(`Git watcher error: ${a instanceof Error?a.message:String(a)}`)}),this.workingDirWatcher.on("change",i),this.workingDirWatcher.on("add",i),this.workingDirWatcher.on("unlink",i),this.workingDirWatcher.on("error",(a)=>{this.logWatchError("Working dir watcher error",a),this.setError(`Working dir watcher error: ${a instanceof Error?a.message:String(a)}`)})}isIgnored(t){let e=this.relativeToRoot(t);if(e==="")return!1;for(let[n,r]of this.ignorers){let s=Mc(e,n);if(s!==null&&r.ignores(s))return!0}return!1}relativeToRoot(t){let e=this.repoPath.length;if(this.repoPath.charCodeAt(e-1)===Tn)e--;let n=t.length;if(t.charCodeAt(n-1)===Tn)n--;return n<=e?"":t.slice(e+1,n)}logWatchError(t,e){if(Fc(e))L(t,e,{repo:this.repoPath});else E(t,e,{repo:this.repoPath})}dispose(){let t=(e)=>(n)=>E(`Failed to close the ${e} watcher`,n,{repo:this.repoPath});this.gitWatcher?.close().catch(t("git dir")),this.workingDirWatcher?.close().catch(t("working dir")),this.settleDiffWaiters()}statMtimes(t){let e=new Map;for(let n of t.files){if(e.has(n.path))continue;try{e.set(n.path,U.statSync(B.join(this.repoPath,n.path)).mtimeMs)}catch{}}return e}pendingRefreshKind=null;scheduleRefresh(){this.requestRefresh("full")}scheduleStatusRefresh(){this.requestRefresh("status")}requestRefresh(t){if(this.pendingRefreshKind!==null){if(t==="full")this.pendingRefreshKind="full";return}if(this.queue.hasPendingMutations())return;this.pendingRefreshKind=t,this.queue.scheduleRefresh(async()=>{let e=this.pendingRefreshKind??"full";if(this.pendingRefreshKind=null,e==="full")await this.doRefresh();else await this.doStatusRefresh()})}notARepo(t,e){if(this._state.status?.isRepo!==!1)E(`${e} (was open as one)`,void 0,{repo:this.repoPath});this.unavailableReason=e,this._wholeTreeDiffs=null,this.updateState({status:t,isLoading:!1,error:e})}refreshFailed(t,e){if(!U.existsSync(this.repoPath)){this.notARepo($c(),"Repository directory no longer exists");return}E(t,e,{repo:this.repoPath}),this.updateState({isLoading:!1,error:e instanceof Error?e.message:"Unknown error"})}async doStatusRefresh(){try{let t=await pn(this.repoPath);if(!t.isRepo){this.notARepo(t,"Not a git repository");return}this._wholeTreeDiffs=null,this.updateState({status:t,mtimes:this.statMtimes(t),isLoading:!1})}catch(t){this.refreshFailed("Status refresh failed",t)}}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.fullRefreshRunning=!0;try{await this.readFullState()}finally{this.fullRefreshRunning=!1,this.settleDiffWaiters()}}async readFullState(){this.updateState({isLoading:!0,error:null});let t=Date.now(),e=await _e(this.repoPath).catch((n)=>(L("HEAD oid unreadable; journal observation skipped",n,{repo:this.repoPath}),null));try{let n=await pn(this.repoPath);if(!n.isRepo){this.notARepo(n,"Not a git repository");return}let r=this.snapshotJournalGuard(n),[s,o,{stashList:i,operation:a},c]=await Promise.all([ce(this.repoPath,void 0,!1),ce(this.repoPath,void 0,!0),r,this.gatherJournalInputs(n,e,t,r)]),l={unstaged:Se(dt(s.lines)),staged:Se(dt(o.lines))};this.hunkTimes.stamp(s),this.hunkTimes.stamp(o),this.hunkTimes.prune(new Set(n.files.map((f)=>f.path)));let u=this.statMtimes(n);if(this._wholeTreeDiffs={unstaged:s,staged:o},this.updateState({status:n,hunkCounts:l,stashList:i,operationInProgress:a,mtimes:u,isLoading:!1}),c!==null)this.emit("journal-observation",{status:n,headDiff:c.headDiff,headOid:c.headOid,stashCount:c.stashCount,operationInProgress:c.operationInProgress,mtimes:c.mtimes,at:Date.now()})}catch(n){this.refreshFailed("Refresh failed",n)}}async snapshotJournalGuard(t){let[e,n]=await Promise.all([It(this.repoPath),mn(this.repoPath)]);return{operation:e,stashList:n,mtimes:this.statMtimes(t)}}static journalGuardMoved(t,e){if(t.operation!==e.operation||t.stashList.length!==e.stashList.length)return!0;if(t.mtimes.size!==e.mtimes.size)return!0;for(let[n,r]of t.mtimes)if(e.mtimes.get(n)!==r)return!0;return!1}sectionWrittenDuringGather(t,e,n){let r=new Set(e);for(let s of t.files)if(s.status==="untracked")r.add(s.path);for(let s of r)try{let o=U.statSync(B.join(this.repoPath,s));if(Math.floor(o.mtimeMs)>n)return!0}catch{}return!1}async gatherJournalInputs(t,e,n,r){if(e===null)return null;try{let s=await r,o=await xs(this.repoPath,e),i=new Set(Te(o).keys()),a=[...o.lines];await this.appendUntrackedSections(t,i,a);let c=await _e(this.repoPath);if(e!==c)return null;let l=await this.snapshotJournalGuard(t);if(Fe.journalGuardMoved(s,l))return null;if(this.sectionWrittenDuringGather(t,i,n))return null;return{headDiff:{lines:a},headOid:c,stashCount:l.stashList.length,operationInProgress:l.operation,mtimes:l.mtimes}}catch(s){return L("Journal observation skipped: git read failed",s,{repo:this.repoPath}),null}}async appendUntrackedSections(t,e,n){let r=new Set;for(let s of t.files){if(s.status!=="untracked"||r.has(s.path)||e.has(s.path))continue;r.add(s.path);let o;try{o=U.statSync(B.join(this.repoPath,s.path))}catch{continue}if(!o.isFile())continue;if(o.size>Pc){this.appendOversizeSection(s.path,o,n);continue}let i=await gt(this.repoPath,s.path);if(i.lines.length===0)continue;n.push(...i.lines)}}appendOversizeSection(t,e,n){let r=[`diff --git ${_t("a/"+t)} ${_t("b/"+t)}`,"new file mode 100644",`${Me} size=${e.size} mtime=${Math.round(e.mtimeMs)}`];n.push(...r.map((s)=>({type:"header",content:s})))}failed(t,e,n){E(`Failed to ${t}`,e,{repo:this.repoPath,file:n}),this.updateState({error:`Failed to ${t}: ${e instanceof Error?e.message:String(e)}`})}async stage(t){try{await this.queue.enqueueMutation(()=>jr(this.repoPath,t.path)),this.scheduleStatusRefresh()}catch(e){await this.refresh(),this.failed(`stage ${t.path}`,e,t.path)}}async unstage(t){try{await this.queue.enqueueMutation(()=>Ur(this.repoPath,t.path)),this.scheduleStatusRefresh()}catch(e){await this.refresh(),this.failed(`unstage ${t.path}`,e,t.path)}}async stageHunk(t){try{await this.queue.enqueueMutation(async()=>Vr(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.failed("stage hunk",e)}}async unstageHunk(t){try{await this.queue.enqueueMutation(async()=>Qr(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.failed("unstage hunk",e)}}async discard(t){if(t.staged)return;let e=t.status==="untracked"?()=>zr(this.repoPath,t.path):()=>Xr(this.repoPath,t.path);try{await this.queue.enqueueMutation(e),await this.refresh()}catch(n){this.failed(`discard ${t.path}`,n,t.path)}}async stageAll(){try{await this.queue.enqueueMutation(()=>Gr(this.repoPath)),await this.refresh()}catch(t){this.failed("stage all",t)}}async unstageAll(){try{await this.queue.enqueueMutation(()=>qr(this.repoPath)),await this.refresh()}catch(t){this.failed("unstage all",t)}}async commit(t,e=!1){try{await this.queue.enqueue(()=>Jr(this.repoPath,t,e)),await this.refresh()}catch(n){this.failed("commit",n)}}async loadStashList(){try{let t=await this.queue.enqueue(()=>mn(this.repoPath));this.updateState({stashList:t})}catch(t){E("Failed to load the stash list",t,{repo:this.repoPath})}}}import{EventEmitter as Cc}from"node:events";class Mn extends Cc{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){E(`git ${t} failed`,n,{repo:this.repoPath});let r=n instanceof Error?n.message:String(n);this.updateRemoteState({inProgress:!1,error:r})}return this._remoteState}async push(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("push",()=>Zr(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>ts(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>es(this.repoPath))}async stash(t){if(this._remoteState.inProgress)return null;let e=await this.runRemoteOperation("stash",()=>ss(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",()=>os(this.repoPath,t));return await this.callbacks.loadStashList(),e}async switchBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>as(this.repoPath,t))}async createBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>cs(this.repoPath,t))}async softReset(t=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>ls(this.repoPath,t))}async cherryPick(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>us(this.repoPath,t))}async revertCommit(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>fs(this.repoPath,t))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>hs(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>ds(this.repoPath))}}import{EventEmitter as Nc}from"node:events";import{randomBytes as Oc}from"node:crypto";var Lc=262144,Bc=500,Hc=16777216,no=Number.MAX_SAFE_INTEGER,Wc=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function jc(t){let e=Wc.exec(t);if(!e)return null;return{oldStart:parseInt(e[1],10),oldCount:e[2]!==void 0?parseInt(e[2],10):1}}function Uc(t,e){let n=jc(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=Gc(o,r),r++;else if(a==="+")o=o??{hasDel:!1,delStart:0,delEnd:0,anchor:r-1};else to(s,o),o=null,r++}return to(s,o),s}function Gc(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 to(t,e){if(!e)return;t.push(e.hasDel?[2*e.delStart,2*e.delEnd]:[2*e.anchor,2*e.anchor+2])}function Fn(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>=no)return{start:0,count:0};let r=Math.ceil(e/2),s=Math.floor(n/2);return{start:r,count:s-r+1}}function qc(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(Me));return{hunks:[{runs:[[0,no]],bodyHash:Ae([dt(t.lines)]),ins:0,del:0,span:{start:0,count:0},diff:t,oversize:i}],renamedFrom:n,hunkless:!0}}return{hunks:r.map(({header:i,body:a})=>{let c=Uc(a,i.content),l=[],u=0,f=0;for(let d of a){let p=d.content[0];if(p==="\\")continue;if(p==="+")u++,l.push(d.content);else if(p==="-")f++,l.push(d.content)}let h=[...e,i,...a];return{runs:c,bodyHash:Ae(l),ins:u,del:f,span:Fn(c),diff:{lines:h}}}),renamedFrom:n,hunkless:!1}}function Xc(t){if(t.oversize===!0)return null;return Ee(t.diff.lines)>Lc?null:t.diff}function zc(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 eo(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 Jc(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=eo(t,0),i=eo(e,t.length),a=0;for(let c of o){while(a<i.length&&i[a].hi<c.lo)a++;for(let l=a;l<i.length&&i[l].lo<=c.hi;l++)s(c.node,i[l].node)}return n.map((c,l)=>r(l))}function Kc(t,e){let n=Jc(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 Yc(t,e,n){let r=[],s=e.map(()=>null),o=n;for(let i of Kc(t,e)){let a=i.prevIdx.map((f)=>t[f]),c=i.nextIdx.map((f)=>e[f]);if(a.length===1&&c.length===1&&a[0].bodyHash===c[0].bodyHash){let f=c[0];s[i.nextIdx[0]]={seq:a[0].seq,runs:f.runs,bodyHash:f.bodyHash,ins:f.ins,del:f.del};continue}if(c.length===0){for(let f of a)r.push({seq:o++,kind:"reverted",span:Fn(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],d={seq:o++,kind:a.length===0?"created":zc(h.ins,h.del,u),span:h.span,stats:{insertions:h.ins,deletions:h.del},diff:Xc(h),supersedes:[...l],siblings:c.length};r.push(d),s[f]={seq:d.seq,runs:h.runs,bodyHash:h.bodyHash,ins:h.ins,del:h.del}}}return{entries:r,nextLive:s.filter((i)=>i!==null)}}function Vc(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 $e(){return{entries:[],epoch:`${Date.now().toString(36)}-${Oc(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class $n extends Nc{store;constructor(t){super();this.store=t}get journalStore(){return this.store}observe(t){try{this.doObserve(t)}catch(e){T("Journal observation skipped: classifier threw",e)}}doObserve(t){let e=[];if(this.store.lastHeadOid===null){if(t.operationInProgress===null)this.seed(t,e)}else if(this.handleOperations(t,e));else if(t.headOid!==this.store.lastHeadOid)this.rebaseline(t,e);else this.classify(t,e);if(e.length>0)this.store.entries.push(...e),this.emit("append",e),this.pruneStore()}pruneStore(){let t=new Set;for(let e of this.store.live.values())for(let n of e)t.add(n.seq);this.pruneBodies(t),this.pruneEntries(t)}pruneBodies(t){let e=0;for(let n of this.store.entries)if(n.type==="hunk"&&n.diff!==null)e+=Ee(n.diff.lines);for(let n of this.store.entries){if(e<=Hc)return;if(n.type!=="hunk"||n.diff===null||t.has(n.seq))continue;e-=Ee(n.diff.lines),n.diff=null}}pruneEntries(t){let e=this.store.entries,n=0;while(e.length-n>Bc&&(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}=Vc(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:Fn(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}=Yc(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 Te(t.headDiff))e.set(r,qc(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=Tr(t);this.workingTree=new Fe(t,n),this.remote=new Mn(t,n,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new $n(e??$e()),this.workingTree.on("journal-observation",(r)=>this.journal.observe(r))}dispose(){this.workingTree.dispose(),Mr(this.repoPath)}}function Zc(t){return Qc("sha256").update(t).digest("hex").slice(0,12)}var tl=32,el=600000,nl=4;class ro{cap;stores=new Map;constructor(t=tl){this.cap=t}acquire(t){let e=this.stores.get(t);if(e)this.stores.delete(t);else e=$e();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 Ce extends Error{reason;requested;constructor(t,e){super(t==="not-absolute"?`Repo path must be absolute: ${e}`:`Not a git repository: ${e}`);this.reason=t,this.requested=e,this.name="RepoOpenRefused"}}class Nn{events;byId=new Map;byPath=new Map;lingering=new Map;journalStores=new ro;lingerMs;lingerCap;constructor(t={},e={}){this.events=t,this.lingerMs=e.lingerMs??el,this.lingerCap=e.lingerCap??nl}async openRepo(t){let e=await Ie(t,{mustExist:!1});if(!e.ok)throw new Ce(e.reason,e.requested);let n=e.root,r=this.byPath.get(n);if(r)return r.refCount++,{handle:r,created:!1};let s=this.takeLingering(n);if(s)return s.refCount=1,this.byId.set(s.id,s),this.byPath.set(n,s),this.journalStores.acquire(s.id),s.manager.workingTree.scheduleRefresh(),this.events.onOpened?.(s),{handle:s,created:!1};let o=Zc(n),i=new Cn(n,this.journalStores.acquire(o));i.workingTree.startWatching();let a={id:o,path:n,manager:i,refCount:1};return this.byId.set(a.id,a),this.byPath.set(n,a),this.pruneJournalStores(),this.events.onOpened?.(a),{handle:a,created:!0}}takeLingering(t){let e=this.lingering.get(t);if(!e)return null;if(clearTimeout(e.timer),this.lingering.delete(t),e.handle.manager.workingTree.unavailable)return e.handle.manager.dispose(),null;return e.handle}pruneJournalStores(){let t=new Set([...this.lingering.values()].map((e)=>e.handle.id));this.journalStores.prune((e)=>this.byId.has(e)||t.has(e))}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),this.linger(e),this.events.onClosed?.(e.id),!0}linger(t){if(this.lingering.size>=this.lingerCap){let n=this.lingering.keys().next().value;this.disposeLingering(n)}let e=setTimeout(()=>this.disposeLingering(t.path),this.lingerMs);e.unref(),this.lingering.set(t.path,{handle:t,timer:e})}disposeLingering(t){let e=this.lingering.get(t);if(!e)return;clearTimeout(e.timer),this.lingering.delete(t),e.handle.manager.dispose()}disposeAll(){for(let t of this.byId.values())t.manager.dispose();this.byId.clear(),this.byPath.clear();for(let t of[...this.lingering.keys()])this.disposeLingering(t)}}function On(t){t.manager.workingTree.refresh().catch((e)=>{T("First refresh threw",e,{repo:t.path})})}async function Ne(t,e){let n=await t.openRepo(e);if(n.created)On(n.handle);return n}var oo=25000;function $t(t,e,n){t.write(`event: ${e}
33
34
  data: ${n}
34
35
 
35
- `)}function to(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Qs(t,e){$t(t,"repo-missing",JSON.stringify({id:e}))}class $n{channels=new Map;subscribe(t,e,n,r){to(r),this.join(t,e,n,r,{owned:!0})}attach(t,e,n,r){if(!e){Qs(r,t);return}this.join(t,e,n,r,{owned:!1})}join(t,e,n,r,s){let o=this.channels.get(t);if(!o){let a=new Map,c={manager:e,subscribers:a,listener:(l)=>{let u=JSON.stringify(at(l));if(u===c.lastData)return;c.lastData=u;for(let f of a.keys())$t(f,"state-change",u)},journalListener:(l)=>{let u=JSON.stringify({epoch:e.journal.journalStore.epoch,entries:l});for(let f of a.keys())$t(f,"journal-append",u)},keepAlive:setInterval(()=>{for(let[l,{owned:u}]of a)if(u)l.write(`: ping
36
+ `)}function io(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function so(t,e){$t(t,"repo-missing",JSON.stringify({id:e}))}class Ln{channels=new Map;subscribe(t,e,n,r){io(r),this.join(t,e,n,r,{owned:!0})}attach(t,e,n,r){if(!e){so(r,t);return}this.join(t,e,n,r,{owned:!1})}join(t,e,n,r,s){let o=this.channels.get(t);if(!o){let a=new Map,c={manager:e,subscribers:a,listener:(l)=>{let u=JSON.stringify(at(l));if(u===c.lastData)return;c.lastData=u;for(let f of a.keys())$t(f,"state-change",u)},journalListener:(l)=>{let u=JSON.stringify({epoch:e.journal.journalStore.epoch,entries:l});for(let f of a.keys())$t(f,"journal-append",u)},keepAlive:setInterval(()=>{for(let[l,{owned:u}]of a)if(u)l.write(`: ping
36
37
 
37
- `)},Zs),lastData:null};e.workingTree.on("state-change",c.listener),e.journal.on("append",c.journalListener),c.keepAlive.unref(),o=c,this.channels.set(t,o)}o.subscribers.set(r,s),n.on("close",()=>this.unsubscribe(t,r));let i=JSON.stringify(at(e.workingTree.state));$t(r,s.owned?"snapshot":"repo-snapshot",i)}unsubscribe(t,e){let n=this.channels.get(t);if(!n)return;if(n.subscribers.delete(e),n.subscribers.size===0)this.teardown(t,n)}teardown(t,e){e.manager.workingTree.off("state-change",e.listener),e.manager.journal.off("append",e.journalListener),clearInterval(e.keepAlive);for(let[n,{owned:r}]of e.subscribers)if(r)n.end();else Qs(n,t);e.subscribers.clear(),this.channels.delete(t)}closeRepo(t){let e=this.channels.get(t);if(e)this.teardown(t,e)}destroy(){for(let[t,e]of this.channels)this.teardown(t,e)}}class On{subscribers=new Set;keepAlive=null;subscribe(t,e,n){if(to(e),this.subscribers.add(e),!this.keepAlive)this.keepAlive=setInterval(()=>{for(let r of this.subscribers)r.write(`: ping
38
+ `)},oo),lastData:null};e.workingTree.on("state-change",c.listener),e.journal.on("append",c.journalListener),c.keepAlive.unref(),o=c,this.channels.set(t,o)}o.subscribers.set(r,s),n.on("close",()=>this.unsubscribe(t,r));let i=JSON.stringify(at(e.workingTree.state));$t(r,s.owned?"snapshot":"repo-snapshot",i)}unsubscribe(t,e){let n=this.channels.get(t);if(!n)return;if(n.subscribers.delete(e),n.subscribers.size===0)this.teardown(t,n)}teardown(t,e){e.manager.workingTree.off("state-change",e.listener),e.manager.journal.off("append",e.journalListener),clearInterval(e.keepAlive);for(let[n,{owned:r}]of e.subscribers)if(r)n.end();else so(n,t);e.subscribers.clear(),this.channels.delete(t)}closeRepo(t){let e=this.channels.get(t);if(e)this.teardown(t,e)}destroy(){for(let[t,e]of this.channels)this.teardown(t,e)}}class Bn{subscribers=new Set;keepAlive=null;subscribe(t,e,n){if(io(e),this.subscribers.add(e),!this.keepAlive)this.keepAlive=setInterval(()=>{for(let r of this.subscribers)r.write(`: ping
38
39
 
39
- `)},Zs),this.keepAlive.unref();t.on("close",()=>{if(this.subscribers.delete(e),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),$t(e,"snapshot",JSON.stringify(n))}broadcast(t,e){let n=JSON.stringify(e);for(let r of this.subscribers)$t(r,t,n)}destroy(){if(this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null;for(let t of this.subscribers)t.end();this.subscribers.clear()}}import*as wt from"node:fs";import*as Ne from"node:path";import{watch as Lc}from"chokidar";import{EventEmitter as Hc}from"node:events";class Nn extends Hc{targetFile;watcher=null;debounceTimer=null;lastReadPath=null;_state={path:null,rawContent:null};constructor(t){super();this.targetFile=t}get state(){return this._state}updateState(t){this._state={...this._state,...t},this.emit("path-change",this._state)}processContent(t){if(!t)return null;let e=K(t);return Ne.isAbsolute(e)?e:Ne.resolve(e)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let t=wt.readFileSync(this.targetFile,"utf-8"),e=en(t);if(e&&e!==this.lastReadPath){let n=this.processContent(e);this.lastReadPath=n,this.updateState({path:n,rawContent:e})}}catch(t){if(t.code==="ENOENT")return;v("Cannot read the follow hook file",t,{file:this.targetFile})}}start(){if(we(this.targetFile),!wt.existsSync(this.targetFile))wt.writeFileSync(this.targetFile,"");try{let t=wt.readFileSync(this.targetFile,"utf-8"),e=en(t);if(e){let n=this.processContent(e);this.lastReadPath=n,this._state={path:n,rawContent:e}}}catch(t){v("Cannot read the follow hook file",t,{file:this.targetFile})}this.watcher=Lc(this.targetFile,{persistent:!0,ignoreInitial:!0}),this.watcher.on("change",()=>this.readTargetDebounced()),this.watcher.on("add",()=>this.readTargetDebounced()),this.watcher.on("error",(t)=>{v("Follow hook file watcher error",t,{file:this.targetFile})})}stop(){if(this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.watcher)this.watcher.close().catch((t)=>{v("Failed to close the follow hook file watcher",t,{file:this.targetFile})}),this.watcher=null}}var eo={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class Cn{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 Nn(n)}get state(){return{targetFile:this.targetFile,enabled:!0,followedRepoId:this.followedRepoId,followedPath:this.followedPath}}start(){if(this.watcher.on("path-change",(t)=>this.enqueue(t)),this.watcher.start(),this.watcher.state.path)this.enqueue(this.watcher.state)}enqueue(t){this.queue=this.queue.then(()=>this.follow(t)).catch((e)=>{T("Follow switch threw",e,{path:t.path})})}async follow(t){if(this.disposed||!t.path)return;let e;try{e=await this.registry.openRepo(t.path)}catch(n){H("Follow target ignored",n,{path:t.path});return}if(this.disposed){this.registry.closeRepo(e.handle.id);return}if(e.created)Fn(e.handle);if(e.handle.id===this.followedRepoId)this.registry.closeRepo(e.handle.id);else{let n=this.followedRepoId;if(this.followedRepoId=e.handle.id,this.followedPath=e.handle.path,n)this.registry.closeRepo(n)}this.hub.broadcast("follow-change",{repoId:e.handle.id,path:t.path,rawContent:t.rawContent})}dispose(){if(this.disposed)return;if(this.disposed=!0,this.watcher.stop(),this.followedRepoId)this.registry.closeRepo(this.followedRepoId),this.followedRepoId=null,this.followedPath=null}}import*as U from"node:fs";import*as Ot from"node:path";function no(){return{watchRoots:[]}}var Ln=16;function Bc(t){let e=t.trim();if(!e)throw Error("Watch directory cannot be empty");let n=K(e);if(!Ot.isAbsolute(n))throw Error(`Watch directory must be absolute: ${t}`);let r=Ot.resolve(n),s;try{s=U.statSync(r)}catch{throw Error(`No such directory: ${r}`)}if(!s.isDirectory())throw Error(`Not a directory: ${r}`);return r}function ro(t){if(t.length>Ln)throw Error(`Too many watch directories (max ${Ln})`);let e=new Set,n=[];for(let r of t){let s=Bc(r);if(e.has(s))continue;e.add(s),n.push(s)}return n}function jc(t){let e=no();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,Ln);return e}class Hn{file;current=no();constructor(t){this.file=t}get settings(){return this.current}get persisted(){return this.file!==null}load(){if(!this.file)return this.current;let t;try{t=U.readFileSync(this.file,"utf-8")}catch(e){if(e.code!=="ENOENT")T("Cannot read the settings file; running with defaults",e,{file:this.file});return this.current}try{this.current=jc(JSON.parse(t))}catch(e){v("Ignoring the settings file: not valid JSON",e,{file:this.file})}return this.current}save(t){if(this.current=t,!this.file)return this.current;U.mkdirSync(Ot.dirname(this.file),{recursive:!0});let e=`${this.file}.${process.pid}.tmp`;try{U.writeFileSync(e,`${JSON.stringify(this.current,null,2)}
40
- `,{mode:384}),U.renameSync(e,this.file)}catch(n){throw U.rmSync(e,{force:!0}),n}return this.current}}import*as ao from"node:path";import{watch as Vc}from"chokidar";import*as z from"node:fs/promises";import*as O from"node:path";var Wc=2,Gc=500,Uc=new Set(["node_modules","vendor","target","dist","build","venv","__pycache__"]);async function so(t){try{return await z.stat(O.join(t,".git")),!0}catch{return!1}}async function qc(t){let e=O.join(t,".git"),n;try{n=await z.stat(e)}catch{return null}if(n.isDirectory())return e;try{let r=await z.readFile(e,"utf-8"),s=/^gitdir:\s*(.+)$/m.exec(r);if(!s)return null;let o=s[1].trim(),i=O.isAbsolute(o)?o:O.resolve(t,o);return await z.stat(i),i}catch{return null}}async function Xc(t){let e;try{e=(await z.readFile(O.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 zc(t){let e=[t];try{let o=await z.readdir(O.join(t,"worktrees"));e.push(...o.map((i)=>O.join(t,"worktrees",i)))}catch{}let n=e.flatMap((o)=>[O.join(o,"index"),O.join(o,"HEAD")]),s=(await Promise.all(n.map(async(o)=>{try{return(await z.stat(o)).mtimeMs}catch{return null}}))).filter((o)=>o!==null);return s.length===0?null:Math.max(...s)}async function Jc(t){let e=await qc(t);if(e===null)return null;let[n,r]=await Promise.all([Xc(e),zc(e)]);return{path:t,name:O.basename(t),branch:n,lastActivity:r}}function Kc(t){if(!t.isDirectory())return!1;if(t.name.startsWith("."))return!1;return!Uc.has(t.name)}async function oo(t){let e=await Bn(t);return Promise.all(e.map(async(n)=>({name:O.basename(n),path:n,isRepo:await so(n)})))}async function Bn(t){return(await z.readdir(t,{withFileTypes:!0})).filter(Kc).map((n)=>O.join(t,n.name)).sort()}async function Yc(t,e,n){let r=[],s=[];for(let o of t){if(r.length>=n)return{repos:r,next:s,capped:!0};if(await so(o)){r.push(o);continue}if(!e)continue;try{s.push(...await Bn(o))}catch{}}return{repos:r,next:s,capped:!1}}async function io(t,e={}){let n=e.depth??Wc,r=e.limit??Gc,s=await Bn(t),o=[],i=!1;for(let c=1;c<=n&&s.length>0&&!i;c++){let l=await Yc(s,c<n,r-o.length);o.push(...l.repos),i=l.capped,s=l.next.sort()}return{repos:(await Promise.all(o.map(Jc))).filter((c)=>c!==null),capped:i}}var Qc=300;function Zc(t){let e=ao.basename(t);return e.startsWith(".")&&e!=="."||e==="node_modules"}class jn{hub;roots=new Map;disposed=!1;constructor(t){this.hub=t}get state(){return{roots:[...this.roots.values()].map((t)=>t.state)}}async setRoots(t){if(this.disposed)return;for(let[r,s]of this.roots)if(!t.includes(r))this.teardown(s),this.roots.delete(r);let e=[],n=new Map;for(let r of t){let s=this.roots.get(r);if(s){n.set(r,s);continue}n.set(r,{state:{path:r,repos:[],error:null,capped:!1},watcher:null,timer:null}),e.push(r)}this.roots=n,await Promise.all(e.map((r)=>this.scan(r)));for(let r of e)this.startWatching(r);this.broadcast()}async rescan(){return await Promise.all([...this.roots.keys()].map((t)=>this.scan(t))),this.broadcast(),this.state}dispose(){this.disposed=!0;for(let t of this.roots.values())this.teardown(t);this.roots.clear()}teardown(t){if(t.timer)clearTimeout(t.timer);t.timer=null,t.watcher?.close().catch((e)=>{v("Failed to close a watch directory watcher",e,{root:t.state.path})}),t.watcher=null}async scan(t){let e=this.roots.get(t);if(!e)return;try{let n=await io(t);e.state={path:t,repos:n.repos,error:null,capped:n.capped}}catch(n){v("Watch directory scan failed",n,{root:t}),e.state={path:t,repos:[],error:n instanceof Error?n.message:String(n),capped:!1}}}startWatching(t){let e=this.roots.get(t);if(!e||e.watcher)return;let n=Vc(t,{persistent:!0,ignoreInitial:!0,depth:1,ignored:Zc});n.on("error",(r)=>{v("Watch directory watcher error",r,{root:t}),e.state={...e.state,error:r instanceof Error?r.message:String(r)},this.broadcast()}),n.on("addDir",()=>this.scheduleRescan(t)),n.on("unlinkDir",()=>this.scheduleRescan(t)),e.watcher=n}scheduleRescan(t){let e=this.roots.get(t);if(!e)return;if(e.timer)clearTimeout(e.timer);e.timer=setTimeout(()=>{e.timer=null,this.scan(t).then(()=>this.broadcast())},Qc),e.timer.unref?.()}broadcast(){if(this.disposed)return;this.hub.broadcast("discovery-change",this.state)}}import*as fo from"node:fs";import{execFile as tl}from"node:child_process";import*as ft from"node:fs";import*as rt from"node:path";import{fileURLToPath as el}from"node:url";var co={method:"unknown",package:null,command:null},le="diffstalkerd",nl=3000,rl=["paru","yay"],sl=[{method:"bun",pattern:/\/install\/global\/node_modules\/diffstalkerd$/,command:`bun add -g ${le}`},{method:"pnpm",pattern:/\/pnpm\/global\/\d+\/node_modules\/diffstalkerd$/,command:`pnpm add -g ${le}`},{method:"yarn",pattern:/\/yarn\/global\/node_modules\/diffstalkerd$/,command:`yarn global add ${le}`},{method:"npm",pattern:/\/lib\/node_modules\/diffstalkerd$/,command:`npm install -g ${le}`}];async function ol(t,e){let n=t.split(rt.sep).join("/").replace(/\/+$/,"");for(let s of sl){if(!s.pattern.test(n))continue;let o=e.writable(t)?"":"sudo ";return{method:s.method,package:le,command:`${o}${s.command}`}}let r=await e.pacmanOwner(rt.join(t,"package.json"));if(r!==null){let s=e.onPath(rl);return{method:"pacman",package:r,command:s?`${s} -S ${r}`:`sudo pacman -Syu ${r}`}}return co}var il={onPath(t){let e=(process.env.PATH??"").split(rt.delimiter).filter(Boolean);for(let n of t)for(let r of e)try{return ft.accessSync(rt.join(r,n),ft.constants.X_OK),n}catch{}return null},pacmanOwner(t){return new Promise((e)=>{tl("pacman",["-Qoq","--",t],{timeout:nl},(n,r)=>{if(n)return e(null);let s=r.trim().split(`
41
- `)[0]?.trim();e(s?s:null)})})},writable(t){try{return ft.accessSync(t,ft.constants.W_OK),!0}catch{return!1}}};function al(){let t=rt.dirname(el(new URL("../package.json",import.meta.url)));try{return ft.realpathSync(t)}catch{return t}}function lo(t=al(),e=il){let n=null;return{info(){return n??=ol(t,e).catch((r)=>(v("Install detection failed",r,{dir:t}),co)),n}}}var cl="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",ll=21600000,ul=300000,fl=5000;function Wn(){try{let t=fo.readFileSync(new URL("../package.json",import.meta.url),"utf-8"),e=JSON.parse(t);return typeof e.version==="string"?e.version:null}catch(t){return v("Cannot read the daemon version from its package.json",t),null}}async function hl(){let t=await fetch(cl,{headers:{accept:"application/json"},signal:AbortSignal.timeout(fl)});if(!t.ok)return null;let e=await t.json();return typeof e.latest==="string"?e.latest:null}function uo(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());if(!e)return null;return[Number(e[1]),Number(e[2]),Number(e[3])]}function dl(t,e){if(t===null||e===null)return"unknown";let n=uo(t),r=uo(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 ho(t=hl,e=Wn(),n=lo()){let r=null,s=null;function o(){if(r&&Date.now()<r.expiresAt)return Promise.resolve(r.value);if(s)return s;return s=t().catch((i)=>(H("Latest version lookup failed",i),null)).then((i)=>{let a=i===null?ul:ll;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:dl(e,i),install:a}}}}import*as po from"node:os";function mo(t,e){t.get("/health",({res:n})=>{E(n,200,{ok:!0,ready:!0,home:po.homedir(),http:{port:e.httpPort()},symbols:{extensions:e.symbols?.extensions??[]}})})}function go(t,e){t.get("/version",async({res:n})=>{E(n,200,await e.version.state())})}import*as _o from"node:fs";import*as Nt from"node:fs";import*as N from"node:path";function Ct(t,e){let n=t.getRepo(e);if(!n)throw new m(404,`Unknown repo id: ${e}`);return n}function k(t,e){let n=Ct(t,e),r=n.manager.workingTree.unavailable;if(r!==null)throw new m(410,r);return n}function q(t,e,n){if(typeof t!=="object"||t===null)throw new m(400,`Expected a JSON body with "${e}"`);let r=t[e];if(typeof r!=="string"||!n?.allowEmpty&&r.length===0)throw new m(400,`Missing "${e}" (string) in body`);return r}function yo(t,e){if(t.length===0)throw new m(400,`Invalid "${e}" (expected a ref)`);if(t.startsWith("-"))throw new m(400,`Invalid "${e}" (must not start with "-"): ${t}`);return t}function yt(t,e){return yo(q(t,e),e)}function qn(t,e){let n=t.get(e);return n===null?null:yo(n,e)}function bo(t,e){if(typeof t!=="object"||t===null)throw new m(400,`Expected a JSON body with "${e}"`);let n=t[e];if(!Array.isArray(n)||n.some((r)=>typeof r!=="string"))throw new m(400,`Missing "${e}" (array of strings) in body`);return n}function Eo(t,e){if(typeof t!=="object"||t===null)return;let n=t[e];if(n===void 0)return;if(typeof n!=="string"||n.length===0)throw new m(400,`Invalid "${e}" (expected a non-empty string)`);return n}function Xn(t,e,n){if(typeof t!=="object"||t===null)return n.fallback;let r=t[e];if(r===void 0)return n.fallback;if(typeof r!=="number"||!Number.isInteger(r)||r<n.min)throw new m(400,`Invalid "${e}" (expected an integer >= ${n.min})`);return r}function So(t,e){if(typeof t!=="object"||t===null)return!1;let n=t[e];if(n===void 0)return!1;if(typeof n!=="boolean")throw new m(400,`Invalid "${e}" (expected a boolean)`);return n}function j(t,e,n){let r=t.get(e);if(r===null){if(n===void 0)throw new m(400,`Missing "${e}" query parameter (expected true or false)`);return n}if(r==="true")return!0;if(r==="false")return!1;throw new m(400,`Invalid "${e}" (expected true or false): ${r}`)}function Q(t){let e=t.get("path");if(!e)throw new m(400,'Missing "path" query parameter');return e}function ue(t,e){let n=j(t,"whole",!1);if(n&&!e)throw new m(400,"whole=true requires a path (one file at a time)");return n?ws:void 0}function xo(t,e,n,r){let s=t.get(e);if(s===null)return n;let o=Number(s);if(!Number.isInteger(o)||o<1)throw new m(400,`Invalid "${e}" (expected a positive integer): ${s}`);if(r!==void 0&&o>r)throw new m(400,`Invalid "${e}" (must be <= ${r}): ${s}`);return o}async function st(t){if(!t.state.status)await t.refresh();let e=t.state.status;if(!e)throw new m(500,"Repository status unavailable");return e}function wo(t,e,n){let r=t.files.filter((s)=>s.path===e);if(r.length===0)return null;return r.find((s)=>s.staged===n)??r[0]}async function Lt(t,e,n){let r=await st(t),s=wo(r,e,n);if(!s)await t.refresh(),r=await st(t),s=wo(r,e,n);if(!s)throw new m(404,`File not in status: ${e}`);return s}function Un(t,e){return t===e||t.startsWith(e+N.sep)}function zn(t){return t.replace(/[. ]+$/,"").toLowerCase()===".git"}function bt(t,e){if(e.length===0)throw new m(400,"Empty path");if(e.includes("\x00"))throw new m(400,"Path contains a NUL byte");let n=N.resolve(t),r=N.relative(n,N.resolve(n,e));if(r==="")throw new m(400,`Path resolves to the repository root: ${e}`);if(N.isAbsolute(r)||r===".."||r.startsWith(`..${N.sep}`))throw new m(400,`Path escapes repository root: ${e}`);if(r.startsWith("-"))throw new m(400,`Path must not start with "-": ${e}`);if(r.startsWith(":"))throw new m(400,`Path must not start with ":": ${e}`);if(r.split(N.sep).some(zn))throw new m(400,`Path addresses the git directory: ${e}`);return r}async function vo(t){try{return await Nt.promises.realpath(t)}catch{return null}}var Gn=new WeakMap;async function pl(t){let e=Gn.get(t);if(!e)e=(async()=>{let n=await S(t.path).raw(["rev-parse","--absolute-git-dir"]);return await Nt.promises.realpath(n.trim())})(),Gn.set(t,e),e.catch(()=>Gn.delete(t));try{return await e}catch(n){throw new m(500,"Cannot resolve the git directory for this repository",{cause:n})}}async function Et(t,e){let n=await Nt.promises.realpath(N.resolve(t.path)),r=await vo(N.join(t.path,e));if(r===null)return;if(!Un(r,n))throw new m(400,`Path escapes repository root: ${e}`);if(Un(r,await pl(t)))throw new m(400,`Path addresses the git directory: ${e}`)}async function ko(t,e){let n=await Nt.promises.realpath(N.resolve(t)),r=[];for(let s of e){let o=await vo(N.join(t,s.path));if(o===null||Un(o,n))r.push(s)}return r}function Ce(t){return t?.code??null}async function Jn(t){let e;try{e=await Nt.promises.stat(t)}catch(n){let r=Ce(n);if(r==="ENOENT"||r==="ENOTDIR")return null;throw n}if(e.isDirectory())return"a directory";if(e.isFile())return"a file";if(e.isFIFO())return"a FIFO";if(e.isSocket())return"a socket";return"a device"}function ml(t){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test(t)?409:500}function Ro(t,e){return new m(t,e)}async function ot(t,e,n){t.clearError(),await n();let r=t.state.error;if(r)throw Ro(ml(r),r);await t.refresh(),E(e,200,{state:at(t.state)})}var gl=/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged|no tracking information|no upstream|no configured push destination/i;function wl(t){return gl.test(t)?409:500}async function W(t,e,n){let r=t.manager.remote,s=()=>new m(409,`A ${r.remoteState.operation??"remote"} operation is already in progress`);if(r.remoteState.inProgress)throw s();let o=await n();if(o===null)throw s();let i=t.manager.workingTree;if(await i.refresh(),o.error)throw Ro(wl(o.error),o.error);E(e,200,{state:at(i.state),result:o.lastResult})}function yl(t){if(t.reason==="not-a-repo"&&!_o.existsSync(t.requested))return new m(404,`No such directory: ${t.requested}`,{cause:t});return new m(400,t.message,{cause:t})}function Ao(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=q(r,"path"),i;try{i=await Oe(n,o)}catch(a){if(a instanceof $e)throw yl(a);throw 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=Q(r),i=await Ae(o,{mustExist:!0});if(!i.ok&&i.reason==="not-absolute")throw new m(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=k(n,r.id);E(s,200,await vn(o.path))}),t.get("/worktrees",async({query:r,res:s})=>{E(s,200,await vn(Q(r)))}),t.delete("/repos/:id",({params:r,res:s})=>{Ct(n,r.id),n.closeRepo(r.id),E(s,200,{})})}function Io(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 Do(t){return t.trim()}async function bl(t){let e=(r)=>r.filter((s)=>s.staged).length,n=e((await st(t)).files);if(n===0)await t.refresh(),n=e((await st(t)).files);return n}function Po(t,e){let{registry:n,sse:r}=e;if(t.get("/repos/:id/status",async({params:s,res:o})=>{let i=Ct(n,s.id);await st(i.manager.workingTree),E(o,200,at(i.manager.workingTree.state))}),t.get("/repos/:id/diff",async({params:s,query:o,res:i})=>{let a=k(n,s.id),c=o.get("path")??void 0,l=j(o,"staged",!1),u=ue(o,c),f,h=!1;if(c){let d=(await st(a.manager.workingTree)).files.some((g)=>g.path===c&&g.status==="untracked");if(d&&l)throw new m(400,`staged=true is meaningless for untracked file: ${c} (untracked files have no staged diff)`);h=u!==void 0&&!d,f=d?await gt(a.path,c):await Ft(a.path,c,l,{context:u})}else f=await Ft(a.path,void 0,l);if(!h)a.manager.workingTree.stampDiff(f);E(i,200,f)}),t.post("/repos/:id/stage",async({params:s,body:o,res:i})=>{let a=k(n,s.id),c=q(o,"path"),l=a.manager.workingTree,u=await Lt(l,c,!1);await ot(l,i,()=>l.stage(u))}),t.post("/repos/:id/unstage",async({params:s,body:o,res:i})=>{let a=k(n,s.id),c=q(o,"path"),l=a.manager.workingTree,u=await Lt(l,c,!0);await ot(l,i,()=>l.unstage(u))}),t.get("/repos/:id/events",({params:s,req:o,res:i})=>{let a=Ct(n,s.id);r.subscribe(s.id,a.manager,o,i)}),e.apiMode==="full")El(t,e)}function El(t,e){let{registry:n}=e;t.post("/repos/:id/stage-all",async({params:r,res:s})=>{let i=k(n,r.id).manager.workingTree;await ot(i,s,()=>i.stageAll())}),t.post("/repos/:id/unstage-all",async({params:r,res:s})=>{let i=k(n,r.id).manager.workingTree;await ot(i,s,()=>i.unstageAll())}),t.post("/repos/:id/discard",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=q(s,"path"),c=i.manager.workingTree,l=await Lt(c,a,!1);if(l.staged)throw new m(409,`Cannot discard a staged file: ${a} (unstage it first)`);await ot(c,o,()=>c.discard(l))}),t.post("/repos/:id/commit",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=q(s,"message",{allowEmpty:!0}),c=So(s,"amend"),l=i.manager.workingTree,u=await bl(l),f=Io(a,u,c);if(!f.valid)throw new m(400,f.error??"Invalid commit");await ot(l,o,()=>l.commit(Do(a),c))}),t.post("/repos/:id/stage-hunk",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=q(s,"patch"),c=i.manager.workingTree;await ot(c,o,()=>c.stageHunk(a))}),t.post("/repos/:id/unstage-hunk",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=q(s,"patch"),c=i.manager.workingTree;await ot(c,o,()=>c.unstageHunk(a))})}var Sl=1000,Le="refs/heads/",Mo="refs/remotes/";async function Fo(t,e,n){let r=["for-each-ref","--format=%(objectname) %(refname) %(symref)",`--no-merged=${e}`];if(n!==void 0)r.push(`--contains=${n}`);r.push("refs/heads","refs/remotes");let s=await t.raw(r),o=[];for(let i of s.split(`
42
- `)){if(!i)continue;let[a,c,l]=i.split(" ");if(l)continue;if(c.startsWith(Le))o.push({tip:a,name:c.slice(Le.length),local:!0});else if(c.startsWith(Mo))o.push({tip:a,name:c.slice(Mo.length),local:!1})}return o}function xl(t){return new Map(t.filter((e)=>e.local).map((e)=>[e.name,e.tip]))}function $o(t,e){return t.filter((n)=>{if(n.local)return!0;let r=e.get(n.name.slice(n.name.indexOf("/")+1));return r===void 0||r===n.tip})}function vl(t){return new Set(t.filter((e)=>!e.local).map((e)=>e.name.slice(e.name.indexOf("/")+1)))}function Oo(t,e){return!t.local||e.has(t.name)}async function No(t,e,n){return(await t.raw(["rev-list","--first-parent",`--max-count=${Sl}`,"--end-of-options",`${e}..${n}`])).split(`
43
- `).filter(Boolean).reverse()}async function kl(t){let e=await t.raw(["rev-parse","HEAD","--symbolic-full-name","HEAD"]),[n,r]=e.split(`
44
- `),s=r.startsWith(Le)?r.slice(Le.length):null;return{tip:n,name:s??"HEAD",branch:s}}async function To(t,e){if(e.length<2)return e;return(await t.raw(["merge-base","--independent","--end-of-options",...e])).split(`
45
- `).filter(Boolean)}function Rl(t,e,n){if(t.length===0)return null;let r=t.filter((c)=>c.local).map((c)=>c.name).sort(),s=t.filter((c)=>!c.local).map((c)=>c.name).sort(),o=[...r,...s],i=[...r.filter((c)=>n.has(c)),...s,...r.filter((c)=>!n.has(c))];return{name:e!==null&&r.includes(e)?e:i.find((c)=>!c.startsWith("-"))??i[0],refs:o}}function Co(t,e,n,r){let s=[],o=-1;for(let i=0;i<t.length;i++){let a=t[i],c=a===n?.tip,l=Rl(e.get(a)??[],n?.branch??null,r)??(c?{name:n.name,refs:[]}:null);if(l===null)continue;s.push({...l,tip:a,commits:i-o,isHead:c}),o=i}return s}async function _l(t,e,n,r,s,o){let i=$o(await Fo(t,e,n),r).filter((u)=>u.tip!==n),a=[...new Set(i.map((u)=>u.tip))];if(a.length===0)return{layers:[],forked:!1};let c=await To(t,a);if(c.length>1){let u=[...new Set(i.filter((f)=>Oo(f,o)).map((f)=>f.tip))];if(u.length>0)c=await To(t,u)}if(c.length!==1)return{layers:[],forked:!0};let l=await No(t,n,c[0]);return{layers:Co(l,s,null,o),forked:!1}}function Al(t,e){let n=[],r=!1;for(let s of[...t].reverse()){let o=e.has(s.tip);if(r&&!o&&!s.isHead){n[n.length-1].commits+=s.commits;continue}if(n.push({...s}),o)r=!0}return n.reverse()}async function Lo(t,e){let n=S(t),r=await kl(n),s=(await n.raw(["merge-base","--end-of-options",e,r.tip])).trim();if(!s)return{trunk:e,layers:[],forkedAbove:!1};let[o,i]=await Promise.all([Fo(n,e),No(n,s,r.tip)]),a=xl(o),c=vl(o),l=new Map,u=new Set;for(let p of $o(o,a)){let d=l.get(p.tip);if(d)d.push(p);else l.set(p.tip,[p]);if(Oo(p,c))u.add(p.tip)}let f=Co(i,l,r,c);if(!f.some((p)=>p.isHead))f.push({name:r.name,refs:[],tip:r.tip,commits:0,isHead:!0});let h=await _l(n,e,r.tip,a,l,c);return{trunk:e,layers:Al([...f,...h.layers],u),forkedAbove:h.forked}}function Kn(t){if(!/^[0-9a-f]{4,40}$/i.test(t))throw new m(400,`Invalid commit hash: ${t}`);return t}async function Ho(t,e){if(!await nt(t,e))throw new m(404,`Unknown commit: ${e}`)}async function Yn(t){try{return await t()}catch(e){if(e instanceof xe)throw new m(422,e.message,{cause:e});throw e}}async function Il(t){let e=await bn(t);if(e&&await nt(t,e))return e;if(Dt(t)){let n=await yn(t);if(n&&await nt(t,n))return n}throw new m(422,"No usable base branch")}async function He(t,e){let n=qn(e,"base");if(n===null)return Il(t);if(!await nt(t,n))throw new m(400,`Unknown base ref: ${n}`);return n}async function Vn(t,e){let n=qn(e,"head");if(n===null)return;if(!await nt(t,n))throw new m(400,`Unknown head ref: ${n}`);return n}function Bo(t,e){if(e&&t.get("head")!==null)throw new m(400,"head cannot be combined with uncommitted work (it only exists against HEAD)")}var Dl=new Set(["staged","unstaged","both","untracked"]);function Pl(t){let e=t.get("uncommitted");if(e===null)return null;if(!Dl.has(e))throw new m(400,`Invalid "uncommitted" (expected staged, unstaged, both or untracked): ${e}`);return e}function Ml(t){return{staged:j(t,"staged",!1),unstaged:j(t,"unstaged",!1),untracked:j(t,"untracked",!1)}}function Tl(t){if(t.unstaged&&!t.staged)throw new m(400,"unstaged needs staged too (unstaged edits sit on top of staged ones)")}function jo(t,e){let{registry:n}=e;if(t.get("/repos/:id/history",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=xo(s,"count",100,5000);E(o,200,await Qr(i.path,a))}),t.get("/repos/:id/commits/:hash",async({params:r,res:s})=>{let o=k(n,r.id),i=Kn(r.hash),a=await Zr(o.path,i);if(a===null)throw new m(404,`Unknown commit: ${i}`);E(s,200,a)}),t.get("/repos/:id/commits/:hash/diff",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=Kn(r.hash);await Ho(i.path,a);let c=s.get("path")??void 0,l=ue(s,c),u=c?await Sn(i.path,{kind:"commit",hash:a},c,{context:l}):await _s(i.path,a);E(o,200,u)}),t.get("/repos/:id/commits/:hash/files",async({params:r,res:s})=>{let o=k(n,r.id),i=Kn(r.hash);await Ho(o.path,i),E(s,200,await Rs(o.path,i))}),t.get("/repos/:id/compare/file",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=Q(s),c=ue(s,a),l=Pl(s);if(Bo(s,l!==null),l==="untracked"){E(o,200,await gt(i.path,a));return}let u=await He(i.path,s),f=l===null?{kind:"compare",base:u,head:await Vn(i.path,s)}:{kind:"compare-uncommitted",mergeBase:await Yn(()=>ks(i.path,u)),tip:l==="staged"?"index":"worktree"};E(o,200,await Sn(i.path,f,a,{context:c}))}),t.get("/repos/:id/head-message",async({params:r,res:s})=>{let o=k(n,r.id);E(s,200,{message:await qr(o.path)})}),t.get("/repos/:id/branches",async({params:r,res:s})=>{let o=k(n,r.id);E(s,200,await ns(o.path))}),t.get("/repos/:id/base-branches",async({params:r,res:s})=>{let o=k(n,r.id);E(s,200,await Es(o.path))}),t.get("/repos/:id/compare/base",async({params:r,res:s})=>{let o=k(n,r.id);E(s,200,{base:await bn(o.path)})}),e.apiMode==="full")t.put("/repos/:id/compare/base",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=yt(s,"branch");if(!await nt(i.path,a))throw new m(400,`Not a valid base ref: ${a}`);hs(i.path,a),E(o,200,{base:a})});t.get("/repos/:id/compare/count",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=await He(i.path,s),c=await Vn(i.path,s),l=await Yn(()=>vs(i.path,a,c));E(o,200,{baseBranch:a,commits:l})}),t.get("/repos/:id/compare/stack",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=await He(i.path,s);E(o,200,await Lo(i.path,a))}),t.get("/repos/:id/compare",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=Ml(s);Bo(s,a.staged||a.unstaged||a.untracked),Tl(a);let c=await He(i.path,s),l=await Vn(i.path,s),u=await Yn(()=>As(i.path,c,a,l));E(o,200,u)})}function Fl(t){let e=t.get("since");if(e===null)return 0;if(!/^\d+$/.test(e))throw new m(400,`Invalid "since" (expected a non-negative integer): ${e}`);return Number(e)}function Wo(t,e){let{registry:n}=e;t.get("/repos/:id/journal",({params:r,query:s,res:o})=>{let i=k(n,r.id),a=Fl(s);E(o,200,mr(i.manager.journal.journalStore,a))})}function Go(t,e){let{registry:n}=e;t.post("/repos/:id/push",async({params:r,res:s})=>{let o=k(n,r.id);await W(o,s,()=>o.manager.remote.push())}),t.post("/repos/:id/fetch",async({params:r,res:s})=>{let o=k(n,r.id);await W(o,s,()=>o.manager.remote.fetchRemote())}),t.post("/repos/:id/pull",async({params:r,res:s})=>{let o=k(n,r.id);await W(o,s,()=>o.manager.remote.pullRebase())}),t.post("/repos/:id/stash",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=Eo(s,"message");await W(i,o,()=>i.manager.remote.stash(a))}),t.post("/repos/:id/stash-pop",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=Xn(s,"index",{min:0,fallback:0});await W(i,o,()=>i.manager.remote.stashPop(a))}),t.post("/repos/:id/switch-branch",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=yt(s,"name");await W(i,o,()=>i.manager.remote.switchBranch(a))}),t.post("/repos/:id/create-branch",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=yt(s,"name");await W(i,o,()=>i.manager.remote.createBranch(a))}),t.post("/repos/:id/soft-reset",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=Xn(s,"count",{min:1,fallback:1});if(!await nt(i.path,`HEAD~${a}`))throw new m(400,`Cannot soft-reset ${a} commit(s): HEAD~${a} does not exist`);await W(i,o,()=>i.manager.remote.softReset(a))}),t.post("/repos/:id/cherry-pick",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=yt(s,"hash");await W(i,o,()=>i.manager.remote.cherryPick(a))}),t.post("/repos/:id/revert",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=yt(s,"hash");await W(i,o,()=>i.manager.remote.revertCommit(a))}),t.post("/repos/:id/abort",async({params:r,res:s})=>{let o=k(n,r.id);if(!await It(o.path))throw new m(409,"No operation in progress to abort");await W(o,s,()=>o.manager.remote.abortOperation())}),t.post("/repos/:id/rebase-continue",async({params:r,res:s})=>{let o=k(n,r.id);if(await It(o.path)!=="rebase")throw new m(409,"No rebase in progress to continue");await W(o,s,()=>o.manager.remote.rebaseContinue())})}import*as Ue from"node:fs";import*as fe from"node:path";import*as Qn from"node:fs";var Be=Qn.constants.O_RDONLY|(Qn.constants.O_NONBLOCK??0);async function Ht(t,e,n){let r=Buffer.alloc(n),s=0;while(s<n){let{bytesRead:o}=await t.read(r,s,n-s,e+s);if(o===0)break;s+=o}return s===n?r:r.subarray(0,s)}var Wt=8388608;var Uo=65536;function Bt(t){return Array.from(t,(e)=>e.charCodeAt(0))}function jt(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 je(t,e){return t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function Zn(t,e){return(t[e]<<8)+t[e+1]}function We(t,e){return t[e]+(t[e+1]<<8)}function qo(t,e){return String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3])}function P(t){return{ok:!1,refusal:t}}function Gt(t){return P(t?"malformed":"header-not-found")}function tr(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 $l=[137,80,78,71,13,10,26,10],Ol=[255,216,255],Nl=Bt("GIF87a"),Cl=Bt("GIF89a"),Z=Bt("ftyp");function J(t){return{offset:8,bytes:Bt(t)}}var Ll=[{label:"webp",offset:0,bytes:Bt("RIFF"),brand:J("WEBP")},{label:"avif",offset:4,bytes:Z,brand:J("avif")},{label:"avis",offset:4,bytes:Z,brand:J("avis")},{label:"heic",offset:4,bytes:Z,brand:J("heic")},{label:"heix",offset:4,bytes:Z,brand:J("heix")},{label:"heim",offset:4,bytes:Z,brand:J("heim")},{label:"heis",offset:4,bytes:Z,brand:J("heis")},{label:"hevc",offset:4,bytes:Z,brand:J("hevc")},{label:"hevx",offset:4,bytes:Z,brand:J("hevx")},{label:"mif1",offset:4,bytes:Z,brand:J("mif1")},{label:"msf1",offset:4,bytes:Z,brand:J("msf1")},{label:"tiff-le",offset:0,bytes:[73,73,42,0]},{label:"tiff-be",offset:0,bytes:[77,77,0,42]},{label:"bmp",offset:0,bytes:Bt("BM")},{label:"ico",offset:0,bytes:[0,0,1,0]},{label:"cur",offset:0,bytes:[0,0,2,0]},{label:"jxl-codestream",offset:0,bytes:[255,10]},{label:"jxl-container",offset:0,bytes:[0,0,0,12,74,88,76,32,13,10,135,10]}];function Hl(t){return Ll.some((e)=>jt(t,e.offset,e.bytes)&&(e.brand===void 0||jt(t,e.brand.offset,e.brand.bytes)))}var Bl={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},jl=26;function Wl(t,e,n){if(t.length<jl)return Gt(n);if(je(t,8)!==13)return P("malformed");if(qo(t,12)!=="IHDR")return P("malformed");let r=je(t,16),s=je(t,20),o=tr(r,s);if(o)return P(o);let i=Bl[t[25]];if(!i||!i.includes(t[24]))return P("malformed");let a=Gl(t,n);if(a)return a;return{ok:!0,info:{format:"png",mime:"image/png",width:r,height:s,bytes:e}}}function Gl(t,e){let n=8;for(let r=0;r<256;r++){if(n+8>t.length)return Gt(e);let s=je(t,n),o=qo(t,n+4);if(o==="IDAT")return null;if(o==="acTL")return P("animation");if(o==="iCCP"&&s>65536)return P("malformed");let i=n+12+s;if(i<=n||!Number.isSafeInteger(i))return P("malformed");n=i}return P("malformed")}var Ul=218,ql=226,Xl=new Set([219,238,192,193,194,196]);function zl(t){return t>=224&&t<=239||Xl.has(t)}function Jl(t){return t===1||t>=208&&t<=217}function Kl(t){return t>=192&&t<=207&&t!==196&&t!==200&&t!==204}var Yl=new Set([192,193,194]);function Vl(t,e,n){if(t.length<4)return Gt(n);if(!zl(t[3]))return P("malformed");return tu(t,e,n)}function Ql(t,e,n,r,s){if(!Yl.has(n))return P("malformed");if(e+9>t.length)return Gt(s);let o=Zn(t,e+5),i=Zn(t,e+7),a=tr(i,o);if(a)return P(a);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:i,height:o,bytes:r}}}function Zl(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(Jl(n))return{kind:"skip",next:e+2};if(n===Ul)return{kind:"malformed"};if(e+4>t.length)return{kind:"ran-out"};let r=Zn(t,e+2);if(r<2)return{kind:"malformed"};if(Kl(n))return{kind:"sof",marker:n};return{kind:"segment",marker:n,length:r}}function tu(t,e,n){let r=2,s=0;for(let o=0;o<1024;o++){let i=Zl(t,r);if(i.kind==="ran-out")return Gt(n);if(i.kind==="malformed")return P("malformed");if(i.kind==="sof")return Ql(t,r,i.marker,e,n);if(i.kind==="skip"){r=i.next;continue}if(i.marker===ql){if(s+=i.length-2,s>65536)return P("malformed")}r+=2+i.length}return P("malformed")}var eu=59,nu=44,ru=33;function Xo(t){return(t&128)===0?0:3*(1<<(t&7)+1)}function su(t,e,n){if(e>2097152)return P("too-large");if(!n)return P("header-not-found");if(t.length<13)return Gt(n);let r=We(t,6),s=We(t,8),o=tr(r,s);if(o)return P(o);let i={pos:13+Xo(t[10]),left:8192,pixels:0,overBudget:!1},a=ou(t,i);if(a===null)return P("malformed");if(a<1)return P("malformed");if(a>256)return P("too-many-pixels");if(i.overBudget)return P("too-many-pixels");if(a*r*s>33554432)return P("too-many-pixels");let c={format:"gif",mime:"image/gif",width:r,height:s,bytes:e};if(a>1)c.frames=a;return{ok:!0,info:c}}function ou(t,e){let n=0;while(e.left-- >0){if(e.pos>=t.length)return null;let r=t[e.pos];if(r===eu)return n;let s=r===nu;if(!(s?au(t,e):iu(t,e,r)))return null;if(s&&++n>256)return n;if(e.overBudget)return n}return null}function iu(t,e,n){if(n!==ru)return!1;return e.pos+=2,zo(t,e)}function au(t,e){if(e.pos+10>t.length)return!1;cu(e,We(t,e.pos+5),We(t,e.pos+7));let n=t[e.pos+9];return e.pos+=10+Xo(n)+1,zo(t,e)}function cu(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 zo(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 Jo(t){return jt(t,0,Nl)||jt(t,0,Cl)}function Ut(t,e,n){if(e>8388608)return P("too-large");if(jt(t,0,$l))return Wl(t,e,n);if(jt(t,0,Ol))return Vl(t,e,n);if(Jo(t))return su(t,e,n);if(Hl(t))return P("unsupported-format");return P("not-an-image")}function Ge(t,e){return Jo(t)?Math.min(e,2097152):65536}function er(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 lu=1048576,Ko=5000;class he extends Error{constructor(t){super(`Not a regular file: ${t}`);this.name="NotRegularFileError"}}async function Vo(t,e,n,r){let s=n?.hideHidden??!0,o=n?.hideGitignored??!0,i=fe.join(t,e),a=await Ue.promises.readdir(i,{withFileTypes:!0}),c=a.map((f)=>e?fe.join(e,f.name):f.name),l=o?await Rt(t,c):new Set,u=[];for(let f of a){if(s&&f.name.startsWith("."))continue;let h=e?fe.join(e,f.name):f.name;if(o&&l.has(h))continue;let p=f.isDirectory(),d={name:f.name,path:h,type:p?"dir":"file"};if(r)if(p){if(r.directories.has(h))d.hasChanges=!0}else{let g=r.files.get(h);if(g)d.gitStatus=g.status,d.staged=g.staged}u.push(d)}return u.sort((f,h)=>{if(f.type==="dir"&&h.type!=="dir")return-1;if(f.type!=="dir"&&h.type==="dir")return 1;return f.name.localeCompare(h.name)}),u}var uu=16;async function fu(t,e){let n=await Ht(t,0,Math.min(uu,e)),r=Ut(n,e,n.length>=e);if(!r.ok&&r.refusal==="too-large")return{head:n,result:r};let s=Math.min(Ge(n,e),e),o=s<=n.length?n.subarray(0,s):Buffer.concat([n,await Ht(t,n.length,s-n.length)]);return{head:o,result:Ut(o,e,o.length>=e)}}function hu(t,e){return t.ok?{image:t.info,refusal:null,version:e}:{image:null,refusal:t.refusal,version:e}}function Yo(t,e){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:t,totalLines:0,media:e}}function nr(t,e){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:t,totalLines:0,media:e}}function du(t,e){let n=t.toString("utf-8"),r=n.split(`
46
- `),s=!1;if(r.length>Ko)n=r.slice(0,Ko).join(`
47
- `),s=!0;return{content:n,binary:!1,truncated:s,tooLarge:!1,size:e,totalLines:r.length}}async function pu(t,e){let n=await t.stat();if(!n.isFile())throw new he(e);let r=n.size;if(r>Wt)return nr(r);let{head:s,result:o}=await fu(t,r),i=hu(o,`${r}-${n.mtimeMs}`);if(o.ok)return Yo(r,i);if(r>lu)return nr(r,ie(s)?i:void 0);let a=s.length>=r?s:Buffer.concat([s,await Ht(t,s.length,r-s.length)]);return ie(a)?Yo(r,i):du(a,r)}async function Qo(t,e){let n=fe.join(t,e),r=await Ue.promises.stat(n);if(!r.isFile())throw new he(e);if(r.size>Wt)return nr(r.size);let s=await Ue.promises.open(n,Be);try{return await pu(s,e)}finally{await s.close()}}import*as rr from"node:path";function Zo(t,e){let{registry:n,symbols:r}=e;async function s(o,i,a){if(!a)return o;if(o.binary||o.tooLarge)return o;if(r===null)return{...o,symbols:{status:"unavailable",reason:"error"}};if(!r.pool.supported(i))return{...o,symbols:{status:"unsupported",reason:"language"}};let c=r.gate.acquire();if(c===null)throw new m(503,"Symbol extraction busy");try{return{...o,symbols:await r.pool.extract(i,o.content)}}finally{(await c)()}}t.get("/repos/:id/tree",async({params:o,query:i,res:a})=>{let c=k(n,o.id),l=i.get("dir")??"",u=j(i,"hidden",!1),f=j(i,"ignored",!1),h=l===""?"":bt(c.path,l);await Et(c,h);let p=await st(c.manager.workingTree),d=er(p.files),g;try{g=await Vo(c.path,h,{hideHidden:!u,hideGitignored:!f},d)}catch(y){let A=Ce(y);if(A==="ENOENT"||A==="ENOTDIR"){let I=await Jn(rr.join(c.path,h));if(I===null)throw new m(404,`No such directory: ${l||"/"}`,{cause:y});throw new m(400,`Not a directory (${I}): ${l}`,{cause:y})}throw y}let R=g.filter((y)=>!zn(y.name));E(a,200,await ko(c.path,R))}),t.get("/repos/:id/file",async({params:o,query:i,res:a})=>{let c=k(n,o.id),l=Q(i),u=bt(c.path,l);await Et(c,u);try{let f=await Qo(c.path,u);E(a,200,await s(f,u,j(i,"symbols",!1)))}catch(f){if(f instanceof he){let p=await Jn(rr.join(c.path,u));throw new m(400,`Not a regular file (${p??"unknown"}): ${l}`,{cause:f})}let h=Ce(f);if(h==="ENOENT"||h==="ENOTDIR")throw new m(404,`No such file: ${l}`,{cause:f});throw f}}),t.get("/repos/:id/files",async({params:o,res:i})=>{let a=k(n,o.id);E(i,200,await us(a.path))})}var qe=3,mu=20,ti=500,gu=500,wu=4194304,ei=400;class Xe extends Error{constructor(){super(`Query must be at least ${qe} characters`);this.name="GrepQueryTooShortError"}}class qt extends Error{constructor(t){super(t);this.name="GrepQueryInvalidError"}}var ni={matches:[],capped:!1,incomplete:!1,binarySkipped:0};function yu(t){return t===t.toLowerCase()}function sr(t){return Buffer.from(t).toString("utf8")}function bu(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 ri(t,e=gu){let n=[],r=new Map,s=0,o=!1,i=0;while(i<t.length){let a=bu(t,i);if(a===null)break;if(i=a.next,a.contentBytes.includes(0)){s+=1;continue}let c=Number.parseInt(sr(a.lineBytes),10);if(!Number.isSafeInteger(c)||c<1)continue;if(n.length>=e){o=!0;break}let l=sr(a.pathBytes),u=r.get(l)??0;if(u>=mu){o=!0;continue}r.set(l,u+1);let f=sr(a.contentBytes),h=f.length>ei;n.push({path:l,line:c,text:h?f.slice(0,ei):f,truncated:h})}return{matches:n,capped:o,incomplete:!1,binarySkipped:s}}function Eu(t){return[...ee,"grep","--no-textconv","--no-recurse-submodules","--full-name","--no-color","--no-column","-I","-n","-z","-F",...yu(t)?["-i"]:[],"-e",t,"--untracked","--","."]}async function si(t,e){if(e.length<qe)throw new Xe;if(e.length>ti)throw new qt(`Query must be at most ${ti} characters`);if(e.includes("\x00"))throw new qt("Query cannot contain a NUL byte");if(e.includes(`
48
- `))throw new qt("Query cannot span lines — this searches for literal text");try{return ri(await ye(t,Eu(e),wu))}catch(n){let r=n;if(r.code===1)return ni;if(r.killed===!0||r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...r.stdout?ri(r.stdout):ni,incomplete:!0};throw n}}function oi(t,e){let{registry:n}=e;t.post("/repos/:id/search",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=q(s,"query");try{let c=await si(i.path,a);E(o,200,c)}catch(c){if(c instanceof Xe)throw new m(400,`Query must be at least ${qe} characters`,{cause:c});if(c instanceof qt)throw new m(400,c.message,{cause:c});throw c}})}import{Worker as Su}from"node:worker_threads";var xu=1000,vu=64,ku={status:"unavailable",reason:"deadline"},de={status:"unavailable",reason:"error"};function Ru(){let t=import.meta.url;return t.endsWith(".ts")?new URL("./symbolWorker.ts",t):new URL("./symbolWorker.js",t)}function ii(t){let e=t.timeoutMs??xu,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>vu){let d=a.keys().next().value;if(d===void 0)break;a.delete(d)}}function l(){let h=r;if(r=null,h!==null)h.terminate()}function u(){let h=new Su(Ru(),{workerData:{grammarDir:t.grammarDir,queryDir:t.queryDir}});return h.unref(),h}function f(h,p){return new Promise((d)=>{if(r===null)try{r=u()}catch(b){v("Cannot start the symbol worker",b,{path:h}),d(de);return}let g=r,R=++s,y=!1,A=(b,it)=>{if(y)return;if(y=!0,clearTimeout(x),g.off("message",I),g.off("error",D),g.off("exit",w),it)l();d(b)},I=(b)=>{if(b.seq!==R)return;A(b.outcome,!1)},D=(b)=>{v("Symbol worker failed; discarding it",b,{path:h}),A(de,!0)},w=(b)=>{v(`Symbol worker exited with code ${b}; discarding it`,void 0,{path:h}),A(de,!0)},x=setTimeout(()=>{v(`Symbol extraction passed its ${e}ms deadline; discarding the worker`,void 0,{path:h}),A(ku,!0)},e);x.unref?.(),g.on("message",I),g.on("error",D),g.on("exit",w);let _={seq:R,relPath:h,content:p};try{g.postMessage(_)}catch(b){v("Cannot send a file to the symbol worker; discarding it",b,{path:h}),A(de,!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 de;let d=`${h}\x00${p}`,g=a.get(d);if(g!==void 0)return c(d,g),g;let R=o.then(()=>f(h,p));o=R.catch(()=>{return});let y=await R;return c(d,y),y},async dispose(){i=!0;let h=r;if(r=null,a.clear(),h!==null)await h.terminate()}}}import{spawn as _u}from"node:child_process";import*as ci from"node:fs";import*as li from"node:path";class Xt extends Error{constructor(t){super(`Not a regular blob: ${t}`);this.name="NotRegularBlobError"}}class zt extends Error{size;constructor(t,e){super(`Blob too large: ${t} (${e} bytes)`);this.name="BlobTooLargeError",this.size=e}}class St extends Error{constructor(t){super(`Unsafe blob path: ${t}`);this.name="UnsafeBlobPathError"}}var ze=65536,ui=/^[0-9a-f]{40}([0-9a-f]{24})?$/,Au=new Set(["100644","100755"]);function Iu(t){if(t==="")throw new St("empty");if(t.includes("\x00"))throw new St("contains NUL");if(t.startsWith("-"))throw new St('starts with "-"');if(t.startsWith(":"))throw new St('starts with ":"')}function Je(t,e,n){return ye(t,[...ee,...e],n)}function fi(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 hi(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 Du=1;async function Pu(t){let e;try{e=(await Je(t,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],ze)).toString("utf8").trim()}catch(n){if(n?.code===Du)return null;throw n}return ui.test(e)?e:null}async function Mu(t,e){let n=await Pu(t);if(n===null)return null;let r=await Je(t,["ls-tree","-z","--full-tree","-l",n,"--",e],ze),s=hi(fi(r),e);if(s===null||s.length!==4)return null;return{mode:s[0],oid:s[2],sizeText:s[3]}}async function Tu(t,e){let n=await Je(t,["ls-files","--stage","-z","--",e],ze),r=hi(fi(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 di(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 Fu(t,e,n){let r=await Je(t,["cat-file","-s",e],ze);return di(r.toString("utf8").trim(),n)}var ai=Buffer.alloc(0);function pi(t,e){let n=ai,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=ai,r=!1}}}function $u(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 d(){let g=_u("git",[...ee,"cat-file","blob",e],{cwd:t,env:ct(),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,y)=>{i={code:R,signal:y},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,y)=>{let A=setTimeout(()=>{n?.kill("SIGKILL"),p(Error(`git cat-file blob timed out for ${e}`))},ln);if(l={want:g,resolve:R,reject:y,timer:A},n===null)d();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 Ou(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Nu(t,e,n){let r=li.join(t,e),s;try{s=await ci.promises.open(r,Be)}catch(o){if(Ou(o))return null;throw o}try{let o=await s.stat();if(!o.isFile())throw new Xt(e);if(o.size>n)throw new zt(e,o.size);let i=o.size,a=pi(i,async(c,l)=>{let u=await Ht(s,l.length,c-l.length);return l.length===0?u:Buffer.concat([l,u])});return{oid:null,size:i,version:`${i}-${o.mtimeMs}`,read:(c)=>a.read(c),close:()=>(a.release(),s.close())}}catch(o){try{await s.close()}catch{}throw o}}async function Cu(t,e,n,r){let s=e==="head"?await Mu(t,n):await Tu(t,n);if(s===null)return null;if(!Au.has(s.mode))throw new Xt(n);if(!ui.test(s.oid))throw Error(`git reported a malformed object id for ${n}`);let o=s.oid,i=s.sizeText===null?await Fu(t,o,n):di(s.sizeText,n);if(i>r)throw new zt(n,i);let a=$u(t,o),c=pi(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 mi(t,e,n,r){if(Iu(n),e==="worktree")return Nu(t,n,r);return Cu(t,e,n,r)}var Lu=["worktree","index","head"],Hu=16,Bu=Uo,ju=Wt,Wu=["too-large","too-many-pixels"];function Gu(t){let e=t.get("side");if(e===null||!Lu.includes(e))throw new m(400,'Invalid "side" (expected worktree, index or head)');return e}function bi(t){if(t instanceof Xt)throw new m(400,t.message,{cause:t});if(t instanceof St)throw new m(400,t.message,{cause:t});if(t instanceof zt)throw new m(413,t.message,{cause:t});throw t}async function gi(t,e){let n=await t.read(e);return{bytes:n,sniff:Ut(n,t.size,n.length>=t.size)}}async function Uu(t,e){let{size:n}=t,r=await t.read(Hu),s=Ut(r,n,r.length>=n);if(!s.ok&&s.refusal==="too-large")return{bytes:r,sniff:s};let o=Math.min(Ge(r,n),n),i=await gi(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 gi(t,n)}async function Ei(t,e,n,r){let s=await mi(t,e,n,Wt);if(s===null)return null;try{let{bytes:o,sniff:i}=await Uu(s,r);return{bytes:o,size:s.size,oid:s.oid,version:s.version,sniff:i}}finally{await s.close()}}function qu(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 Xu(t){let e=Wu.includes(t)?413:415;return new m(e,`Image not served: ${t}`)}function zu(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 Ju(t,e,n){return{path:t.path,side:t.side,bytes:e,oid:null,image:null,refusal:n,version:""}}async function wi(t,e){let n=bt(t.path,e.path);await Et(t,n);let r;try{r=await Ei(t.path,e.side,n,Bu)}catch(s){if(s instanceof zt)return Ju(e,s.size,"too-large");if(s instanceof Xt)return null;bi(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 Ku(t,e){return e.writableEnded||e.destroyed===!0||t.destroyed===!0}async function yi(t,e,n){let r=t.acquire();if(r===null)throw new m(503,"Too many image requests in flight");let s=await r;if(n.once("finish",s),n.once("close",s),e.once("close",s),Ku(e,n))return s(),!1;return!0}function Si(t,e,n){let{registry:r}=e;t.get("/repos/:id/media",async({params:s,query:o,req:i,res:a})=>{let c=k(r,s.id),l=j(o,"staged"),u=bt(c.path,Q(o));if(await Et(c,u),!await yi(n,i,a))return;let f=await Lt(c.manager.workingTree,u,l),h=zu(f,l),p={old:h.old===null?null:await wi(c,h.old),new:h.new===null?null:await wi(c,h.new)};E(a,200,p)}),t.get("/repos/:id/blob",async({params:s,query:o,req:i,res:a})=>{let c=k(r,s.id),l=kr(i);if(l)throw new m(l.status,l.message);let u=Gu(o),f=bt(c.path,Q(o));if(await Et(c,f),!await yi(n,i,a))return;let h;try{h=await Ei(c.path,u,f,ju)}catch(d){bi(d)}if(h===null)throw new m(404,`No such blob on side ${u}: ${f}`);if(!h.sniff.ok)throw Xu(h.sniff.refusal);let p=qu(u,h.sniff.info.mime,h.oid);gr(a,200,h.bytes,p)})}function xi(t,e){let{registry:n,sse:r,daemonEvents:s,follow:o}=e;t.get("/events",({req:i,res:a,query:c})=>{let l=n.listRepos().map((f)=>({id:f.id,path:f.path}));s.subscribe(i,a,l);let u=c.get("repo");if(!u)return;r.attach(u,n.getRepo(u)?.manager??null,i,a)}),t.get("/follow",({res:i})=>{E(i,200,o?o.state:eo)})}import*as or from"node:os";import*as Jt from"node:path";function vi(t,e){let{settings:n,discovery:r,daemonEvents:s}=e,o=()=>({...n.settings,persisted:n.persisted});t.get("/settings",({res:i})=>{E(i,200,o())}),t.put("/settings",async({body:i,res:a})=>{let c=bo(i,"watchRoots"),l;try{l=ro(c)}catch(f){throw new m(400,f instanceof Error?f.message:String(f),{cause:f})}try{n.save({...n.settings,watchRoots:l})}catch(f){let h=f instanceof Error?f.message:String(f);throw new m(500,`Could not save settings: ${h}`,{cause:f})}await r.setRoots(l);let u=o();s.broadcast("settings-change",u),E(a,200,u)}),t.get("/discovered",({res:i})=>{E(i,200,r.state)}),t.get("/browse",async({query:i,res:a})=>{let c=i.get("path"),l=c?K(c):or.homedir();if(!Jt.isAbsolute(l))throw new m(400,`Path must be absolute: ${c}`);let u=Jt.resolve(l),f;try{f=await oo(u)}catch(p){throw new m(404,`Cannot read directory: ${u}`,{cause:p})}let h=Jt.dirname(u);E(a,200,{path:u,parent:h===u?null:h,home:or.homedir(),entries:f})}),t.post("/discovered/rescan",async({res:i})=>{E(i,200,await r.rescan())})}function ir(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 Yu(t){if(!xt.existsSync(t))return Promise.resolve(!1);return new Promise((e)=>{try{let n=Ri.connect(t);n.once("connect",()=>{n.destroy(),e(!0)}),n.once("error",()=>{n.destroy(),e(!1)})}catch{e(!1)}})}function _i(t={}){let e=new $n,n=new On,r=new Tn({onOpened:(w)=>n.broadcast("repo-opened",{id:w.id,path:w.path}),onClosed:(w)=>{e.closeRepo(w),n.broadcast("repo-closed",{id:w})}}),s=t.followFile?new Cn(r,n,t.followFile):null,o=ho(t.updateCheck===!1?()=>Promise.resolve(null):t.fetchLatestVersion),i=new Hn(t.settingsFile??null),a=new jn(n),c=new Map,l=ir(),u=t.symbols??null,f=u===null?null:{pool:ii(u),gate:ir(1,4),extensions:u.extensions};function h(w){let x=c.get(w);if(x)return x;let _=new on,b={registry:r,sse:e,daemonEvents:n,follow:s,settings:i,discovery:a,apiMode:w,version:o,symbols:f,httpPort:y};if(mo(_,b),go(_,b),Ao(_,b),Po(_,b),jo(_,b),Wo(_,b),w==="full")Go(_,b);return Zo(_,b),oi(_,b),Si(_,b,l),xi(_,b),vi(_,b),c.set(w,_),_}let p=(w)=>t.apiMode??(w==="tcp"?"web":"full");s?.start(),a.setRoots(i.load().watchRoots);let d=t.webRoot?br(t.webRoot):void 0,g=new Set,R=[];function y(){for(let w of R){let x=w.server.address();if(x!==null&&typeof x==="object")return x.port}return null}function A(w){let x=h(w),_=ki.createServer((b,it)=>{for(let[tt,pe]of Object.entries(Rr))it.setHeader(tt,pe);if(xr(_.address())){let tt=vr(b);if(tt){E(it,tt.status,{error:tt.message});return}}x.handle(b,it,d).catch((tt)=>{T(`${b.method??"GET"} ${b.url??"/"} escaped the router`,tt),it.end()})});return _.on("connection",(b)=>{g.add(b),b.on("close",()=>g.delete(b))}),_}async function I(w,x){let _=w==="unix"?x.socketPath??null:null;if(_){if(await Yu(_))throw Error(`diffstalkerd already running at ${_}`);xt.rmSync(_,{force:!0})}let b={server:A(p(w)),socketPath:_};R.push(b),await new Promise((it,tt)=>{let pe=(Ni)=>tt(Ni);b.server.once("error",pe);let Ye=()=>{if(b.server.removeListener("error",pe),_)xt.chmodSync(_,384);it()};if(w==="fd")b.server.listen({fd:x.fd},Ye);else if(_)process.umask(63),b.server.listen(_,Ye);else b.server.listen(x.port,"127.0.0.1",Ye)})}function D(w){return new Promise((x,_)=>{w.server.close((b)=>{if(w.socketPath)xt.rmSync(w.socketPath,{force:!0});if(b&&b.code!=="ERR_SERVER_NOT_RUNNING")_(b);else x()})})}return{address(){return R[0]?.server.address()??null},addresses(){return R.map((w)=>w.server.address()).filter((w)=>w!==null)},getRepo(w){return r.getRepo(w)},async openRepo(w){let{handle:x}=await Oe(r,w);return{id:x.id,path:x.path}},async listen(w){let x=[];if(w.fd!==void 0)x.push("fd");if(w.socketPath)x.push("unix");if(w.port!==void 0)x.push("tcp");if(x.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let _ of x)await I(_,w)},close(){s?.dispose(),a.dispose(),e.destroy(),n.destroy(),r.disposeAll();for(let x of g)x.destroy();let w=f?.pool.dispose()??Promise.resolve();return Promise.all([w,...R.splice(0).map(D)]).then(()=>{})}}}import*as ar from"node:fs";import*as Kt from"node:path";import*as Ti from"node:crypto";import{createRequire as Qu}from"node:module";var Ai=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 Ii(){return[...Ai.keys()]}function Vu(t){let e=t.slice(t.lastIndexOf("/")+1),n=e.lastIndexOf(".");if(n<=0)return"";return e.slice(n).toLowerCase()}function Di(t){return Ai.get(Vu(t))??null}var Zu="diffstalkerd-grammars";function tf(t){return Ti.createHash("sha256").update(t).digest("hex")}function ef(t){try{let e=JSON.parse(ar.readFileSync(Kt.join(t,"checksums.json"),"utf8"));if(typeof e.webTreeSitterVersion!=="string"||typeof e.files!=="object")return null;return e}catch{return null}}var Pi="0.26.11";function nf(t,e,n){for(let[r,s]of Object.entries(e.files)){let o;try{o=ar.readFileSync(Kt.join(t,r))}catch{return n(`grammars: missing ${r}`),!1}if(tf(o)!==s)return n(`grammars: checksum mismatch for ${r}`),!1}return!0}function rf(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 Mi(t,e=()=>{}){let n=ef(t);if(n===null)return e(`grammars: no readable checksums.json in ${t}`),null;if(n.webTreeSitterVersion!==Pi)return e(`grammars: built for web-tree-sitter ${n.webTreeSitterVersion}, this daemon bundles ${Pi} — symbols disabled`),null;if(!nf(t,n,e))return null;let r=rf(n),s=Ii().filter((o)=>{let i=Di(`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:Kt.join(t,"queries"),extensions:s}}function Fi(t,e=()=>{}){if(t!==null)return Mi(t,e);try{let r=Qu(import.meta.url).resolve(`${Zu}/checksums.json`);return Mi(Kt.dirname(r),e)}catch{return null}}var Oi="diffstalkerd.sock";function of(t){return t===void 0?Oi:`${t}.sock`}var af=3,$i=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
40
+ `)},oo),this.keepAlive.unref();t.on("close",()=>{if(this.subscribers.delete(e),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),$t(e,"snapshot",JSON.stringify(n))}broadcast(t,e){let n=JSON.stringify(e);for(let r of this.subscribers)$t(r,t,n)}destroy(){if(this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null;for(let t of this.subscribers)t.end();this.subscribers.clear()}}import*as wt from"node:fs";import*as Oe from"node:path";import{watch as rl}from"chokidar";import{EventEmitter as sl}from"node:events";var ol=100;class Hn extends sl{cooldownMs;targetFile;watcher=null;cooldownTimer=null;eventDuringCooldown=!1;lastReadPath=null;_state={path:null,rawContent:null};constructor(t,e=ol){super();this.cooldownMs=e,this.targetFile=t}get state(){return this._state}updateState(t){this._state={...this._state,...t},this.emit("path-change",this._state)}processContent(t){if(!t)return null;let e=K(t);return Oe.isAbsolute(e)?e:Oe.resolve(e)}onFileEvent(){if(this.cooldownTimer){this.eventDuringCooldown=!0;return}this.readTarget(),this.startCooldown()}startCooldown(){this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null;let t=this.eventDuringCooldown;if(this.eventDuringCooldown=!1,this.readTarget(),t)this.startCooldown()},this.cooldownMs)}readTarget(){try{let t=wt.readFileSync(this.targetFile,"utf-8"),e=nn(t);if(e&&e!==this.lastReadPath){let n=this.processContent(e);this.lastReadPath=n,this.updateState({path:n,rawContent:e})}}catch(t){if(t.code==="ENOENT")return;E("Cannot read the follow hook file",t,{file:this.targetFile})}}start(){if(ye(this.targetFile),!wt.existsSync(this.targetFile))wt.writeFileSync(this.targetFile,"");try{let t=wt.readFileSync(this.targetFile,"utf-8"),e=nn(t);if(e){let n=this.processContent(e);this.lastReadPath=n,this._state={path:n,rawContent:e}}}catch(t){E("Cannot read the follow hook file",t,{file:this.targetFile})}this.watcher=rl(this.targetFile,{persistent:!0,ignoreInitial:!0}),this.watcher.on("change",()=>this.onFileEvent()),this.watcher.on("add",()=>this.onFileEvent()),this.watcher.on("error",(t)=>{E("Follow hook file watcher error",t,{file:this.targetFile})})}stop(){if(this.cooldownTimer)clearTimeout(this.cooldownTimer),this.cooldownTimer=null;if(this.eventDuringCooldown=!1,this.watcher)this.watcher.close().catch((t)=>{E("Failed to close the follow hook file watcher",t,{file:this.targetFile})}),this.watcher=null}}var ao={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class Wn{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((e)=>{T("Follow switch threw",e,{path:t.path})})}async follow(t){if(this.disposed||!t.path)return;let e;try{e=await this.registry.openRepo(t.path)}catch(n){L("Follow target ignored",n,{path:t.path});return}if(this.disposed){this.registry.closeRepo(e.handle.id);return}if(e.created)On(e.handle);if(e.handle.id===this.followedRepoId)this.registry.closeRepo(e.handle.id);else{let n=this.followedRepoId;if(this.followedRepoId=e.handle.id,this.followedPath=e.handle.path,n)this.registry.closeRepo(n)}this.hub.broadcast("follow-change",{repoId:e.handle.id,path:t.path,rawContent:t.rawContent})}dispose(){if(this.disposed)return;if(this.disposed=!0,this.watcher.stop(),this.followedRepoId)this.registry.closeRepo(this.followedRepoId),this.followedRepoId=null,this.followedPath=null}}import*as G from"node:fs";import*as Ct from"node:path";function co(){return{watchRoots:[]}}var jn=16;function il(t){let e=t.trim();if(!e)throw Error("Watch directory cannot be empty");let n=K(e);if(!Ct.isAbsolute(n))throw Error(`Watch directory must be absolute: ${t}`);let r=Ct.resolve(n),s;try{s=G.statSync(r)}catch{throw Error(`No such directory: ${r}`)}if(!s.isDirectory())throw Error(`Not a directory: ${r}`);return r}function lo(t){if(t.length>jn)throw Error(`Too many watch directories (max ${jn})`);let e=new Set,n=[];for(let r of t){let s=il(r);if(e.has(s))continue;e.add(s),n.push(s)}return n}function al(t){let e=co();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,jn);return e}class Un{file;current=co();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=G.readFileSync(this.file,"utf-8")}catch(e){if(e.code!=="ENOENT")T("Cannot read the settings file; running with defaults",e,{file:this.file});return this.current}try{this.current=al(JSON.parse(t))}catch(e){E("Ignoring the settings file: not valid JSON",e,{file:this.file})}return this.current}save(t){if(this.current=t,!this.file)return this.current;G.mkdirSync(Ct.dirname(this.file),{recursive:!0});let e=`${this.file}.${process.pid}.tmp`;try{G.writeFileSync(e,`${JSON.stringify(this.current,null,2)}
41
+ `,{mode:384}),G.renameSync(e,this.file)}catch(n){throw G.rmSync(e,{force:!0}),n}return this.current}}import*as po from"node:path";import{watch as wl}from"chokidar";import*as z from"node:fs/promises";import*as F from"node:path";var cl=2,ll=500,ul=new Set(["node_modules","vendor","target","dist","build","venv","__pycache__"]);async function uo(t){try{return await z.stat(F.join(t,".git")),!0}catch{return!1}}async function fl(t){let e=F.join(t,".git"),n;try{n=await z.stat(e)}catch{return null}if(n.isDirectory())return e;try{let r=await z.readFile(e,"utf-8"),s=/^gitdir:\s*(.+)$/m.exec(r);if(!s)return null;let o=s[1].trim(),i=F.isAbsolute(o)?o:F.resolve(t,o);return await z.stat(i),i}catch{return null}}async function hl(t){let e;try{e=(await z.readFile(F.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 dl(t){let e=[t];try{let o=await z.readdir(F.join(t,"worktrees"));e.push(...o.map((i)=>F.join(t,"worktrees",i)))}catch{}let n=e.flatMap((o)=>[F.join(o,"index"),F.join(o,"HEAD")]),s=(await Promise.all(n.map(async(o)=>{try{return(await z.stat(o)).mtimeMs}catch{return null}}))).filter((o)=>o!==null);return s.length===0?null:Math.max(...s)}async function pl(t){let e=await fl(t);if(e===null)return null;let[n,r]=await Promise.all([hl(e),dl(e)]);return{path:t,name:F.basename(t),branch:n,lastActivity:r}}function ml(t){if(!t.isDirectory())return!1;if(t.name.startsWith("."))return!1;return!ul.has(t.name)}async function fo(t){let e=await Gn(t);return Promise.all(e.map(async(n)=>({name:F.basename(n),path:n,isRepo:await uo(n)})))}async function Gn(t){return(await z.readdir(t,{withFileTypes:!0})).filter(ml).map((n)=>F.join(t,n.name)).sort()}async function gl(t,e,n){let r=[],s=[];for(let o of t){if(r.length>=n)return{repos:r,next:s,capped:!0};if(await uo(o)){r.push(o);continue}if(!e)continue;try{s.push(...await Gn(o))}catch{}}return{repos:r,next:s,capped:!1}}async function ho(t,e={}){let n=e.depth??cl,r=e.limit??ll,s=await Gn(t),o=[],i=!1;for(let c=1;c<=n&&s.length>0&&!i;c++){let l=await gl(s,c<n,r-o.length);o.push(...l.repos),i=l.capped,s=l.next.sort()}return{repos:(await Promise.all(o.map(pl))).filter((c)=>c!==null),capped:i}}var yl=300;function bl(t){let e=po.basename(t);return e.startsWith(".")&&e!=="."||e==="node_modules"}class qn{hub;roots=new Map;disposed=!1;constructor(t){this.hub=t}get state(){return{roots:[...this.roots.values()].map((t)=>t.state)}}async setRoots(t){if(this.disposed)return;for(let[r,s]of this.roots)if(!t.includes(r))this.teardown(s),this.roots.delete(r);let e=[],n=new Map;for(let r of t){let s=this.roots.get(r);if(s){n.set(r,s);continue}n.set(r,{state:{path:r,repos:[],error:null,capped:!1},watcher:null,timer:null}),e.push(r)}this.roots=n,await Promise.all(e.map((r)=>this.scan(r)));for(let r of e)this.startWatching(r);this.broadcast()}async rescan(){return await Promise.all([...this.roots.keys()].map((t)=>this.scan(t))),this.broadcast(),this.state}dispose(){this.disposed=!0;for(let t of this.roots.values())this.teardown(t);this.roots.clear()}teardown(t){if(t.timer)clearTimeout(t.timer);t.timer=null,t.watcher?.close().catch((e)=>{E("Failed to close a watch directory watcher",e,{root:t.state.path})}),t.watcher=null}async scan(t){let e=this.roots.get(t);if(!e)return;try{let n=await ho(t);e.state={path:t,repos:n.repos,error:null,capped:n.capped}}catch(n){E("Watch directory scan failed",n,{root:t}),e.state={path:t,repos:[],error:n instanceof Error?n.message:String(n),capped:!1}}}startWatching(t){let e=this.roots.get(t);if(!e||e.watcher)return;let n=wl(t,{persistent:!0,ignoreInitial:!0,depth:1,ignored:bl});n.on("error",(r)=>{E("Watch directory watcher error",r,{root:t}),e.state={...e.state,error:r instanceof Error?r.message:String(r)},this.broadcast()}),n.on("addDir",()=>this.scheduleRescan(t)),n.on("unlinkDir",()=>this.scheduleRescan(t)),e.watcher=n}scheduleRescan(t){let e=this.roots.get(t);if(!e)return;if(e.timer)clearTimeout(e.timer);e.timer=setTimeout(()=>{e.timer=null,this.scan(t).then(()=>this.broadcast())},yl),e.timer.unref?.()}broadcast(){if(this.disposed)return;this.hub.broadcast("discovery-change",this.state)}}import*as Eo from"node:fs";import{execFile as El}from"node:child_process";import*as ft from"node:fs";import*as rt from"node:path";import{fileURLToPath as Sl}from"node:url";var mo={method:"unknown",package:null,command:null},ue="diffstalkerd",vl=3000,xl=["paru","yay"],kl=[{method:"bun",pattern:/\/install\/global\/node_modules\/diffstalkerd$/,command:`bun add -g ${ue}`},{method:"pnpm",pattern:/\/pnpm\/global\/\d+\/node_modules\/diffstalkerd$/,command:`pnpm add -g ${ue}`},{method:"yarn",pattern:/\/yarn\/global\/node_modules\/diffstalkerd$/,command:`yarn global add ${ue}`},{method:"npm",pattern:/\/lib\/node_modules\/diffstalkerd$/,command:`npm install -g ${ue}`}];async function Rl(t,e){let n=t.split(rt.sep).join("/").replace(/\/+$/,"");for(let s of kl){if(!s.pattern.test(n))continue;let o=e.writable(t)?"":"sudo ";return{method:s.method,package:ue,command:`${o}${s.command}`}}let r=await e.pacmanOwner(rt.join(t,"package.json"));if(r!==null){let s=e.onPath(xl);return{method:"pacman",package:r,command:s?`${s} -S ${r}`:`sudo pacman -Syu ${r}`}}return mo}var _l={onPath(t){let e=(process.env.PATH??"").split(rt.delimiter).filter(Boolean);for(let n of t)for(let r of e)try{return ft.accessSync(rt.join(r,n),ft.constants.X_OK),n}catch{}return null},pacmanOwner(t){return new Promise((e)=>{El("pacman",["-Qoq","--",t],{timeout:vl},(n,r)=>{if(n)return e(null);let s=r.trim().split(`
42
+ `)[0]?.trim();e(s?s:null)})})},writable(t){try{return ft.accessSync(t,ft.constants.W_OK),!0}catch{return!1}}};function Al(){let t=rt.dirname(Sl(new URL("../package.json",import.meta.url)));try{return ft.realpathSync(t)}catch{return t}}function go(t=Al(),e=_l){let n=null;return{info(){return n??=Rl(t,e).catch((r)=>(E("Install detection failed",r,{dir:t}),mo)),n}}}import*as wo from"node:fs";var Il=/^[A-Za-z0-9:_.@-]+\.service$/,Dl=/^user@\d+\.service$/,Pl=/^0::(.*)$/m;function Tl(t){let e=Pl.exec(t);if(e===null)return null;let n=e[1].split("/"),r=n.at(-1)??"";if(!Il.test(r))return null;let s=r.slice(0,-8);return n.some((o)=>Dl.test(o))?`systemctl --user restart ${s}`:`sudo systemctl restart ${s}`}function yo(t=process.pid,e=process.env,n=()=>wo.readFileSync("/proc/self/cgroup","utf-8")){if(e.SYSTEMD_EXEC_PID!==String(t))return null;try{return Tl(n())}catch(r){return E("Cannot read /proc/self/cgroup to name the systemd unit",r),null}}var Ml="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",Fl=21600000,$l=300000,Cl=5000;function Xn(){try{let t=Eo.readFileSync(new URL("../package.json",import.meta.url),"utf-8"),e=JSON.parse(t);return typeof e.version==="string"?e.version:null}catch(t){return E("Cannot read the daemon version from its package.json",t),null}}async function Nl(){let t=await fetch(Ml,{headers:{accept:"application/json"},signal:AbortSignal.timeout(Cl)});if(!t.ok)return null;let e=await t.json();return typeof e.latest==="string"?e.latest:null}function bo(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());if(!e)return null;return[Number(e[1]),Number(e[2]),Number(e[3])]}function Ol(t,e){if(t===null||e===null)return"unknown";let n=bo(t),r=bo(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 So(t=Nl,e=Xn(),n=go(),r=yo()){let s=null,o=null;function i(){if(s&&Date.now()<s.expiresAt)return Promise.resolve(s.value);if(o)return o;return o=t().catch((a)=>(L("Latest version lookup failed",a),null)).then((a)=>{let c=a===null?$l:Fl;return s={value:a,expiresAt:Date.now()+c},o=null,a}),o}return{async state(){let[a,c]=await Promise.all([i(),n.info()]);return{current:e,latest:a,status:Ol(e,a),install:c,restart:r}}}}import*as vo from"node:os";function xo(t,e){t.get("/health",({res:n})=>{v(n,200,{ok:!0,ready:!0,home:vo.homedir(),http:{port:e.httpPort()},symbols:{extensions:e.symbols?.extensions??[]}})})}function ko(t,e){t.get("/version",async({res:n})=>{v(n,200,await e.version.state())})}import*as $o from"node:fs";import*as Nt from"node:fs";import*as C from"node:path";function Ot(t,e){let n=t.getRepo(e);if(!n)throw new m(404,`Unknown repo id: ${e}`);return n}function R(t,e){let n=Ot(t,e),r=n.manager.workingTree.unavailable;if(r!==null)throw new m(410,r);return n}function q(t,e,n){if(typeof t!=="object"||t===null)throw new m(400,`Expected a JSON body with "${e}"`);let r=t[e];if(typeof r!=="string"||!n?.allowEmpty&&r.length===0)throw new m(400,`Missing "${e}" (string) in body`);return r}function _o(t,e){if(t.length===0)throw new m(400,`Invalid "${e}" (expected a ref)`);if(t.startsWith("-"))throw new m(400,`Invalid "${e}" (must not start with "-"): ${t}`);return t}function yt(t,e){return _o(q(t,e),e)}function Kn(t,e){let n=t.get(e);return n===null?null:_o(n,e)}function Ao(t,e){if(typeof t!=="object"||t===null)throw new m(400,`Expected a JSON body with "${e}"`);let n=t[e];if(!Array.isArray(n)||n.some((r)=>typeof r!=="string"))throw new m(400,`Missing "${e}" (array of strings) in body`);return n}function Io(t,e){if(typeof t!=="object"||t===null)return;let n=t[e];if(n===void 0)return;if(typeof n!=="string"||n.length===0)throw new m(400,`Invalid "${e}" (expected a non-empty string)`);return n}function Yn(t,e,n){if(typeof t!=="object"||t===null)return n.fallback;let r=t[e];if(r===void 0)return n.fallback;if(typeof r!=="number"||!Number.isInteger(r)||r<n.min)throw new m(400,`Invalid "${e}" (expected an integer >= ${n.min})`);return r}function Do(t,e){if(typeof t!=="object"||t===null)return!1;let n=t[e];if(n===void 0)return!1;if(typeof n!=="boolean")throw new m(400,`Invalid "${e}" (expected a boolean)`);return n}function W(t,e,n){let r=t.get(e);if(r===null){if(n===void 0)throw new m(400,`Missing "${e}" query parameter (expected true or false)`);return n}if(r==="true")return!0;if(r==="false")return!1;throw new m(400,`Invalid "${e}" (expected true or false): ${r}`)}function Q(t){let e=t.get("path");if(!e)throw new m(400,'Missing "path" query parameter');return e}function fe(t,e){let n=W(t,"whole",!1);if(n&&!e)throw new m(400,"whole=true requires a path (one file at a time)");return n?Ss:void 0}function Po(t,e,n,r){let s=t.get(e);if(s===null)return n;let o=Number(s);if(!Number.isInteger(o)||o<1)throw new m(400,`Invalid "${e}" (expected a positive integer): ${s}`);if(r!==void 0&&o>r)throw new m(400,`Invalid "${e}" (must be <= ${r}): ${s}`);return o}async function st(t){if(!t.state.status)await t.refresh();let e=t.state.status;if(!e)throw new m(500,"Repository status unavailable");return e}function Ro(t,e,n){let r=t.files.filter((s)=>s.path===e);if(r.length===0)return null;return r.find((s)=>s.staged===n)??r[0]}async function Lt(t,e,n){let r=await st(t),s=Ro(r,e,n);if(!s)await t.refresh(),r=await st(t),s=Ro(r,e,n);if(!s)throw new m(404,`File not in status: ${e}`);return s}function Jn(t,e){return t===e||t.startsWith(e+C.sep)}function Vn(t){return t.replace(/[. ]+$/,"").toLowerCase()===".git"}function bt(t,e){if(e.length===0)throw new m(400,"Empty path");if(e.includes("\x00"))throw new m(400,"Path contains a NUL byte");let n=C.resolve(t),r=C.relative(n,C.resolve(n,e));if(r==="")throw new m(400,`Path resolves to the repository root: ${e}`);if(C.isAbsolute(r)||r===".."||r.startsWith(`..${C.sep}`))throw new m(400,`Path escapes repository root: ${e}`);if(r.startsWith("-"))throw new m(400,`Path must not start with "-": ${e}`);if(r.startsWith(":"))throw new m(400,`Path must not start with ":": ${e}`);if(r.split(C.sep).some(Vn))throw new m(400,`Path addresses the git directory: ${e}`);return r}async function To(t){try{return await Nt.promises.realpath(t)}catch{return null}}var zn=new WeakMap;async function Ll(t){let e=zn.get(t);if(!e)e=(async()=>{let n=await x(t.path).raw(["rev-parse","--absolute-git-dir"]);return await Nt.promises.realpath(n.trim())})(),zn.set(t,e),e.catch(()=>zn.delete(t));try{return await e}catch(n){throw new m(500,"Cannot resolve the git directory for this repository",{cause:n})}}async function Et(t,e){let n=await Nt.promises.realpath(C.resolve(t.path)),r=await To(C.join(t.path,e));if(r===null)return;if(!Jn(r,n))throw new m(400,`Path escapes repository root: ${e}`);if(Jn(r,await Ll(t)))throw new m(400,`Path addresses the git directory: ${e}`)}async function Mo(t,e){let n=await Nt.promises.realpath(C.resolve(t)),r=[];for(let s of e){let o=await To(C.join(t,s.path));if(o===null||Jn(o,n))r.push(s)}return r}function Le(t){return t?.code??null}async function Qn(t){let e;try{e=await Nt.promises.stat(t)}catch(n){let r=Le(n);if(r==="ENOENT"||r==="ENOTDIR")return null;throw n}if(e.isDirectory())return"a directory";if(e.isFile())return"a file";if(e.isFIFO())return"a FIFO";if(e.isSocket())return"a socket";return"a device"}function Bl(t){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test(t)?409:500}function Fo(t,e){return new m(t,e)}async function ot(t,e,n){t.clearError(),await n();let r=t.state.error;if(r)throw Fo(Bl(r),r);await t.refresh(),v(e,200,{state:at(t.state)})}var Hl=/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged|no tracking information|no upstream|no configured push destination/i;function Wl(t){return Hl.test(t)?409:500}async function j(t,e,n){let r=t.manager.remote,s=()=>new m(409,`A ${r.remoteState.operation??"remote"} operation is already in progress`);if(r.remoteState.inProgress)throw s();let o=await n();if(o===null)throw s();let i=t.manager.workingTree;if(await i.refresh(),o.error)throw Fo(Wl(o.error),o.error);v(e,200,{state:at(i.state),result:o.lastResult})}function jl(t){if(t.reason==="not-a-repo"&&!$o.existsSync(t.requested))return new m(404,`No such directory: ${t.requested}`,{cause:t});return new m(400,t.message,{cause:t})}function Co(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}));v(r,200,s)}),t.post("/repos",async({body:r,res:s})=>{let o=q(r,"path"),i;try{i=await Ne(n,o)}catch(a){if(a instanceof Ce)throw jl(a);throw a}v(s,i.created?201:200,{id:i.handle.id,path:i.handle.path})}),t.get("/resolve",async({query:r,res:s})=>{let o=Q(r),i=await Ie(o,{mustExist:!0});if(!i.ok&&i.reason==="not-absolute")throw new m(400,`Repo path must be absolute: ${i.requested}`);v(s,200,{openable:i.ok,root:i.ok?i.root:null})}),t.get("/repos/:id/worktrees",async({params:r,res:s})=>{let o=R(n,r.id);v(s,200,await _n(o.path))}),t.get("/worktrees",async({query:r,res:s})=>{v(s,200,await _n(Q(r)))}),t.delete("/repos/:id",({params:r,res:s})=>{Ot(n,r.id),n.closeRepo(r.id),v(s,200,{})})}function No(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 Oo(t){return t.trim()}async function Ul(t){let e=(r)=>r.filter((s)=>s.staged).length,n=e((await st(t)).files);if(n===0)await t.refresh(),n=e((await st(t)).files);return n}function Lo(t,e){let{registry:n,sse:r}=e;if(t.get("/repos/:id/status",async({params:s,res:o})=>{let i=Ot(n,s.id);await st(i.manager.workingTree),v(o,200,at(i.manager.workingTree.state))}),t.get("/repos/:id/diff",async({params:s,query:o,res:i})=>{let a=R(n,s.id),c=a.manager.workingTree,l=o.get("path")??void 0,u=W(o,"staged",!1),f=fe(o,l);if(!l){let S=await c.wholeTreeDiffs();if(!S){let y=c.unavailable;throw new m(y?410:500,y??"Repository diff unavailable")}v(i,200,u?S.staged:S.unstaged);return}let d=(await st(c)).files.some((S)=>S.path===l&&S.status==="untracked");if(d&&u)throw new m(400,`staged=true is meaningless for untracked file: ${l} (untracked files have no staged diff)`);let p=f!==void 0&&!d,g=d?await gt(a.path,l):await ce(a.path,l,u,{context:f});if(!p)c.stampDiff(g);v(i,200,g)}),t.post("/repos/:id/stage",async({params:s,body:o,res:i})=>{let a=R(n,s.id),c=q(o,"path"),l=a.manager.workingTree,u=await Lt(l,c,!1);await ot(l,i,()=>l.stage(u))}),t.post("/repos/:id/unstage",async({params:s,body:o,res:i})=>{let a=R(n,s.id),c=q(o,"path"),l=a.manager.workingTree,u=await Lt(l,c,!0);await ot(l,i,()=>l.unstage(u))}),t.get("/repos/:id/events",({params:s,req:o,res:i})=>{let a=Ot(n,s.id);r.subscribe(s.id,a.manager,o,i)}),e.apiMode==="full")Gl(t,e)}function Gl(t,e){let{registry:n}=e;t.post("/repos/:id/stage-all",async({params:r,res:s})=>{let i=R(n,r.id).manager.workingTree;await ot(i,s,()=>i.stageAll())}),t.post("/repos/:id/unstage-all",async({params:r,res:s})=>{let i=R(n,r.id).manager.workingTree;await ot(i,s,()=>i.unstageAll())}),t.post("/repos/:id/discard",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"path"),c=i.manager.workingTree,l=await Lt(c,a,!1);if(l.staged)throw new m(409,`Cannot discard a staged file: ${a} (unstage it first)`);await ot(c,o,()=>c.discard(l))}),t.post("/repos/:id/commit",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"message",{allowEmpty:!0}),c=Do(s,"amend"),l=i.manager.workingTree,u=await Ul(l),f=No(a,u,c);if(!f.valid)throw new m(400,f.error??"Invalid commit");await ot(l,o,()=>l.commit(Oo(a),c))}),t.post("/repos/:id/stage-hunk",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"patch"),c=i.manager.workingTree;await ot(c,o,()=>c.stageHunk(a))}),t.post("/repos/:id/unstage-hunk",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"patch"),c=i.manager.workingTree;await ot(c,o,()=>c.unstageHunk(a))})}var ql=1000,Be="refs/heads/",Bo="refs/remotes/";async function Wo(t,e,n){let r=["for-each-ref","--format=%(objectname) %(refname) %(symref)",`--no-merged=${e}`];if(n!==void 0)r.push(`--contains=${n}`);r.push("refs/heads","refs/remotes");let s=await t.raw(r),o=[];for(let i of s.split(`
43
+ `)){if(!i)continue;let[a,c,l]=i.split(" ");if(l)continue;if(c.startsWith(Be))o.push({tip:a,name:c.slice(Be.length),local:!0});else if(c.startsWith(Bo))o.push({tip:a,name:c.slice(Bo.length),local:!1})}return o}function Xl(t){return new Map(t.filter((e)=>e.local).map((e)=>[e.name,e.tip]))}function jo(t,e){return t.filter((n)=>{if(n.local)return!0;let r=e.get(n.name.slice(n.name.indexOf("/")+1));return r===void 0||r===n.tip})}function zl(t){return new Set(t.filter((e)=>!e.local).map((e)=>e.name.slice(e.name.indexOf("/")+1)))}function Uo(t,e){return!t.local||e.has(t.name)}async function Go(t,e,n){return(await t.raw(["rev-list","--first-parent",`--max-count=${ql}`,"--end-of-options",`${e}..${n}`])).split(`
44
+ `).filter(Boolean).reverse()}async function Jl(t){let e=await t.raw(["rev-parse","HEAD","--symbolic-full-name","HEAD"]),[n,r]=e.split(`
45
+ `),s=r.startsWith(Be)?r.slice(Be.length):null;return{tip:n,name:s??"HEAD",branch:s}}async function Ho(t,e){if(e.length<2)return e;return(await t.raw(["merge-base","--independent","--end-of-options",...e])).split(`
46
+ `).filter(Boolean)}function Kl(t,e,n){if(t.length===0)return null;let r=t.filter((c)=>c.local).map((c)=>c.name).sort(),s=t.filter((c)=>!c.local).map((c)=>c.name).sort(),o=[...r,...s],i=[...r.filter((c)=>n.has(c)),...s,...r.filter((c)=>!n.has(c))];return{name:e!==null&&r.includes(e)?e:i.find((c)=>!c.startsWith("-"))??i[0],refs:o}}function qo(t,e,n,r){let s=[],o=-1;for(let i=0;i<t.length;i++){let a=t[i],c=a===n?.tip,l=Kl(e.get(a)??[],n?.branch??null,r)??(c?{name:n.name,refs:[]}:null);if(l===null)continue;s.push({...l,tip:a,commits:i-o,isHead:c}),o=i}return s}async function Yl(t,e,n,r,s,o){let i=jo(await Wo(t,e,n),r).filter((u)=>u.tip!==n),a=[...new Set(i.map((u)=>u.tip))];if(a.length===0)return{layers:[],forked:!1};let c=await Ho(t,a);if(c.length>1){let u=[...new Set(i.filter((f)=>Uo(f,o)).map((f)=>f.tip))];if(u.length>0)c=await Ho(t,u)}if(c.length!==1)return{layers:[],forked:!0};let l=await Go(t,n,c[0]);return{layers:qo(l,s,null,o),forked:!1}}function Vl(t,e){let n=[],r=!1;for(let s of[...t].reverse()){let o=e.has(s.tip);if(r&&!o&&!s.isHead){n[n.length-1].commits+=s.commits;continue}if(n.push({...s}),o)r=!0}return n.reverse()}async function Xo(t,e){let n=x(t),r=await Jl(n),s=(await n.raw(["merge-base","--end-of-options",e,r.tip])).trim();if(!s)return{trunk:e,layers:[],forkedAbove:!1};let[o,i]=await Promise.all([Wo(n,e),Go(n,s,r.tip)]),a=Xl(o),c=zl(o),l=new Map,u=new Set;for(let d of jo(o,a)){let p=l.get(d.tip);if(p)p.push(d);else l.set(d.tip,[d]);if(Uo(d,c))u.add(d.tip)}let f=qo(i,l,r,c);if(!f.some((d)=>d.isHead))f.push({name:r.name,refs:[],tip:r.tip,commits:0,isHead:!0});let h=await Yl(n,e,r.tip,a,l,c);return{trunk:e,layers:Vl([...f,...h.layers],u),forkedAbove:h.forked}}function Zn(t){if(!/^[0-9a-f]{4,40}$/i.test(t))throw new m(400,`Invalid commit hash: ${t}`);return t}async function zo(t,e){if(!await nt(t,e))throw new m(404,`Unknown commit: ${e}`)}async function tr(t){try{return await t()}catch(e){if(e instanceof xe)throw new m(422,e.message,{cause:e});throw e}}async function Ql(t){let e=await vn(t);if(e&&await nt(t,e))return e;if(Dt(t)){let n=await Sn(t);if(n&&await nt(t,n))return n}throw new m(422,"No usable base branch")}async function He(t,e){let n=Kn(e,"base");if(n===null)return Ql(t);if(!await nt(t,n))throw new m(400,`Unknown base ref: ${n}`);return n}async function er(t,e){let n=Kn(e,"head");if(n===null)return;if(!await nt(t,n))throw new m(400,`Unknown head ref: ${n}`);return n}function Jo(t,e){if(e&&t.get("head")!==null)throw new m(400,"head cannot be combined with uncommitted work (it only exists against HEAD)")}var Zl=new Set(["staged","unstaged","both","untracked"]);function tu(t){let e=t.get("uncommitted");if(e===null)return null;if(!Zl.has(e))throw new m(400,`Invalid "uncommitted" (expected staged, unstaged, both or untracked): ${e}`);return e}function eu(t){return{staged:W(t,"staged",!1),unstaged:W(t,"unstaged",!1),untracked:W(t,"untracked",!1)}}function nu(t){if(t.unstaged&&!t.staged)throw new m(400,"unstaged needs staged too (unstaged edits sit on top of staged ones)")}function Ko(t,e){let{registry:n}=e;if(t.get("/repos/:id/history",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=Po(s,"count",100,5000);v(o,200,await ns(i.path,a))}),t.get("/repos/:id/commits/:hash",async({params:r,res:s})=>{let o=R(n,r.id),i=Zn(r.hash),a=await rs(o.path,i);if(a===null)throw new m(404,`Unknown commit: ${i}`);v(s,200,a)}),t.get("/repos/:id/commits/:hash/diff",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=Zn(r.hash);await zo(i.path,a);let c=s.get("path")??void 0,l=fe(s,c),u=c?await kn(i.path,{kind:"commit",hash:a},c,{context:l}):await Ps(i.path,a);v(o,200,u)}),t.get("/repos/:id/commits/:hash/files",async({params:r,res:s})=>{let o=R(n,r.id),i=Zn(r.hash);await zo(o.path,i),v(s,200,await Ds(o.path,i))}),t.get("/repos/:id/compare/file",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=Q(s),c=fe(s,a),l=tu(s);if(Jo(s,l!==null),l==="untracked"){v(o,200,await gt(i.path,a));return}let u=await He(i.path,s),f=l===null?{kind:"compare",base:u,head:await er(i.path,s)}:{kind:"compare-uncommitted",mergeBase:await tr(()=>Is(i.path,u)),tip:l==="staged"?"index":"worktree"};v(o,200,await kn(i.path,f,a,{context:c}))}),t.get("/repos/:id/head-message",async({params:r,res:s})=>{let o=R(n,r.id);v(s,200,{message:await Kr(o.path)})}),t.get("/repos/:id/branches",async({params:r,res:s})=>{let o=R(n,r.id);v(s,200,await is(o.path))}),t.get("/repos/:id/base-branches",async({params:r,res:s})=>{let o=R(n,r.id);v(s,200,await ks(o.path))}),t.get("/repos/:id/compare/base",async({params:r,res:s})=>{let o=R(n,r.id);v(s,200,{base:await vn(o.path)})}),e.apiMode==="full")t.put("/repos/:id/compare/base",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=yt(s,"branch");if(!await nt(i.path,a))throw new m(400,`Not a valid base ref: ${a}`);gs(i.path,a),v(o,200,{base:a})});t.get("/repos/:id/compare/count",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=await He(i.path,s),c=await er(i.path,s),l=await tr(()=>As(i.path,a,c));v(o,200,{baseBranch:a,commits:l})}),t.get("/repos/:id/compare/stack",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=await He(i.path,s);v(o,200,await Xo(i.path,a))}),t.get("/repos/:id/compare",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=eu(s);Jo(s,a.staged||a.unstaged||a.untracked),nu(a);let c=await He(i.path,s),l=await er(i.path,s),u=await tr(()=>Ts(i.path,c,a,l));v(o,200,u)})}function ru(t){let e=t.get("since");if(e===null)return 0;if(!/^\d+$/.test(e))throw new m(400,`Invalid "since" (expected a non-negative integer): ${e}`);return Number(e)}function Yo(t,e){let{registry:n}=e;t.get("/repos/:id/journal",({params:r,query:s,res:o})=>{let i=R(n,r.id),a=ru(s);v(o,200,br(i.manager.journal.journalStore,a))})}function Vo(t,e){let{registry:n}=e;t.post("/repos/:id/push",async({params:r,res:s})=>{let o=R(n,r.id);await j(o,s,()=>o.manager.remote.push())}),t.post("/repos/:id/fetch",async({params:r,res:s})=>{let o=R(n,r.id);await j(o,s,()=>o.manager.remote.fetchRemote())}),t.post("/repos/:id/pull",async({params:r,res:s})=>{let o=R(n,r.id);await j(o,s,()=>o.manager.remote.pullRebase())}),t.post("/repos/:id/stash",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=Io(s,"message");await j(i,o,()=>i.manager.remote.stash(a))}),t.post("/repos/:id/stash-pop",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=Yn(s,"index",{min:0,fallback:0});await j(i,o,()=>i.manager.remote.stashPop(a))}),t.post("/repos/:id/switch-branch",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=yt(s,"name");await j(i,o,()=>i.manager.remote.switchBranch(a))}),t.post("/repos/:id/create-branch",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=yt(s,"name");await j(i,o,()=>i.manager.remote.createBranch(a))}),t.post("/repos/:id/soft-reset",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=Yn(s,"count",{min:1,fallback:1});if(!await nt(i.path,`HEAD~${a}`))throw new m(400,`Cannot soft-reset ${a} commit(s): HEAD~${a} does not exist`);await j(i,o,()=>i.manager.remote.softReset(a))}),t.post("/repos/:id/cherry-pick",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=yt(s,"hash");await j(i,o,()=>i.manager.remote.cherryPick(a))}),t.post("/repos/:id/revert",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=yt(s,"hash");await j(i,o,()=>i.manager.remote.revertCommit(a))}),t.post("/repos/:id/abort",async({params:r,res:s})=>{let o=R(n,r.id);if(!await It(o.path))throw new m(409,"No operation in progress to abort");await j(o,s,()=>o.manager.remote.abortOperation())}),t.post("/repos/:id/rebase-continue",async({params:r,res:s})=>{let o=R(n,r.id);if(await It(o.path)!=="rebase")throw new m(409,"No rebase in progress to continue");await j(o,s,()=>o.manager.remote.rebaseContinue())})}import*as qe from"node:fs";import*as he from"node:path";import*as nr from"node:fs";var We=nr.constants.O_RDONLY|(nr.constants.O_NONBLOCK??0);async function Bt(t,e,n){let r=Buffer.alloc(n),s=0;while(s<n){let{bytesRead:o}=await t.read(r,s,n-s,e+s);if(o===0)break;s+=o}return s===n?r:r.subarray(0,s)}var jt=8388608;var Qo=65536;function Ht(t){return Array.from(t,(e)=>e.charCodeAt(0))}function Wt(t,e,n){if(e+n.length>t.length)return!1;for(let r=0;r<n.length;r++)if(t[e+r]!==n[r])return!1;return!0}function je(t,e){return t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function rr(t,e){return(t[e]<<8)+t[e+1]}function Ue(t,e){return t[e]+(t[e+1]<<8)}function Zo(t,e){return String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3])}function P(t){return{ok:!1,refusal:t}}function Ut(t){return P(t?"malformed":"header-not-found")}function sr(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 su=[137,80,78,71,13,10,26,10],ou=[255,216,255],iu=Ht("GIF87a"),au=Ht("GIF89a"),Z=Ht("ftyp");function J(t){return{offset:8,bytes:Ht(t)}}var cu=[{label:"webp",offset:0,bytes:Ht("RIFF"),brand:J("WEBP")},{label:"avif",offset:4,bytes:Z,brand:J("avif")},{label:"avis",offset:4,bytes:Z,brand:J("avis")},{label:"heic",offset:4,bytes:Z,brand:J("heic")},{label:"heix",offset:4,bytes:Z,brand:J("heix")},{label:"heim",offset:4,bytes:Z,brand:J("heim")},{label:"heis",offset:4,bytes:Z,brand:J("heis")},{label:"hevc",offset:4,bytes:Z,brand:J("hevc")},{label:"hevx",offset:4,bytes:Z,brand:J("hevx")},{label:"mif1",offset:4,bytes:Z,brand:J("mif1")},{label:"msf1",offset:4,bytes:Z,brand:J("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:Ht("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 lu(t){return cu.some((e)=>Wt(t,e.offset,e.bytes)&&(e.brand===void 0||Wt(t,e.brand.offset,e.brand.bytes)))}var uu={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},fu=26;function hu(t,e,n){if(t.length<fu)return Ut(n);if(je(t,8)!==13)return P("malformed");if(Zo(t,12)!=="IHDR")return P("malformed");let r=je(t,16),s=je(t,20),o=sr(r,s);if(o)return P(o);let i=uu[t[25]];if(!i||!i.includes(t[24]))return P("malformed");let a=du(t,n);if(a)return a;return{ok:!0,info:{format:"png",mime:"image/png",width:r,height:s,bytes:e}}}function du(t,e){let n=8;for(let r=0;r<256;r++){if(n+8>t.length)return Ut(e);let s=je(t,n),o=Zo(t,n+4);if(o==="IDAT")return null;if(o==="acTL")return P("animation");if(o==="iCCP"&&s>65536)return P("malformed");let i=n+12+s;if(i<=n||!Number.isSafeInteger(i))return P("malformed");n=i}return P("malformed")}var pu=218,mu=226,gu=new Set([219,238,192,193,194,196]);function wu(t){return t>=224&&t<=239||gu.has(t)}function yu(t){return t===1||t>=208&&t<=217}function bu(t){return t>=192&&t<=207&&t!==196&&t!==200&&t!==204}var Eu=new Set([192,193,194]);function Su(t,e,n){if(t.length<4)return Ut(n);if(!wu(t[3]))return P("malformed");return ku(t,e,n)}function vu(t,e,n,r,s){if(!Eu.has(n))return P("malformed");if(e+9>t.length)return Ut(s);let o=rr(t,e+5),i=rr(t,e+7),a=sr(i,o);if(a)return P(a);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:i,height:o,bytes:r}}}function xu(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(yu(n))return{kind:"skip",next:e+2};if(n===pu)return{kind:"malformed"};if(e+4>t.length)return{kind:"ran-out"};let r=rr(t,e+2);if(r<2)return{kind:"malformed"};if(bu(n))return{kind:"sof",marker:n};return{kind:"segment",marker:n,length:r}}function ku(t,e,n){let r=2,s=0;for(let o=0;o<1024;o++){let i=xu(t,r);if(i.kind==="ran-out")return Ut(n);if(i.kind==="malformed")return P("malformed");if(i.kind==="sof")return vu(t,r,i.marker,e,n);if(i.kind==="skip"){r=i.next;continue}if(i.marker===mu){if(s+=i.length-2,s>65536)return P("malformed")}r+=2+i.length}return P("malformed")}var Ru=59,_u=44,Au=33;function ti(t){return(t&128)===0?0:3*(1<<(t&7)+1)}function Iu(t,e,n){if(e>2097152)return P("too-large");if(!n)return P("header-not-found");if(t.length<13)return Ut(n);let r=Ue(t,6),s=Ue(t,8),o=sr(r,s);if(o)return P(o);let i={pos:13+ti(t[10]),left:8192,pixels:0,overBudget:!1},a=Du(t,i);if(a===null)return P("malformed");if(a<1)return P("malformed");if(a>256)return P("too-many-pixels");if(i.overBudget)return P("too-many-pixels");if(a*r*s>33554432)return P("too-many-pixels");let c={format:"gif",mime:"image/gif",width:r,height:s,bytes:e};if(a>1)c.frames=a;return{ok:!0,info:c}}function Du(t,e){let n=0;while(e.left-- >0){if(e.pos>=t.length)return null;let r=t[e.pos];if(r===Ru)return n;let s=r===_u;if(!(s?Tu(t,e):Pu(t,e,r)))return null;if(s&&++n>256)return n;if(e.overBudget)return n}return null}function Pu(t,e,n){if(n!==Au)return!1;return e.pos+=2,ei(t,e)}function Tu(t,e){if(e.pos+10>t.length)return!1;Mu(e,Ue(t,e.pos+5),Ue(t,e.pos+7));let n=t[e.pos+9];return e.pos+=10+ti(n)+1,ei(t,e)}function Mu(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 ei(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 ni(t){return Wt(t,0,iu)||Wt(t,0,au)}function Gt(t,e,n){if(e>8388608)return P("too-large");if(Wt(t,0,su))return hu(t,e,n);if(Wt(t,0,ou))return Su(t,e,n);if(ni(t))return Iu(t,e,n);if(lu(t))return P("unsupported-format");return P("not-an-image")}function Ge(t,e){return ni(t)?Math.min(e,2097152):65536}function or(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 Fu=1048576,ri=5000;class de extends Error{constructor(t){super(`Not a regular file: ${t}`);this.name="NotRegularFileError"}}async function oi(t,e,n,r){let s=n?.hideHidden??!0,o=n?.hideGitignored??!0,i=he.join(t,e),a=await qe.promises.readdir(i,{withFileTypes:!0}),c=a.map((f)=>e?he.join(e,f.name):f.name),l=o?await Rt(t,c):new Set,u=[];for(let f of a){if(s&&f.name.startsWith("."))continue;let h=e?he.join(e,f.name):f.name;if(o&&l.has(h))continue;let d=f.isDirectory(),p={name:f.name,path:h,type:d?"dir":"file"};if(r)if(d){if(r.directories.has(h))p.hasChanges=!0}else{let g=r.files.get(h);if(g)p.gitStatus=g.status,p.staged=g.staged}u.push(p)}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 $u=16;async function Cu(t,e){let n=await Bt(t,0,Math.min($u,e)),r=Gt(n,e,n.length>=e);if(!r.ok&&r.refusal==="too-large")return{head:n,result:r};let s=Math.min(Ge(n,e),e),o=s<=n.length?n.subarray(0,s):Buffer.concat([n,await Bt(t,n.length,s-n.length)]);return{head:o,result:Gt(o,e,o.length>=e)}}function Nu(t,e){return t.ok?{image:t.info,refusal:null,version:e}:{image:null,refusal:t.refusal,version:e}}function si(t,e){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:t,totalLines:0,media:e}}function ir(t,e){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:t,totalLines:0,media:e}}function Ou(t,e){let n=t.toString("utf-8"),r=n.split(`
47
+ `),s=!1;if(r.length>ri)n=r.slice(0,ri).join(`
48
+ `),s=!0;return{content:n,binary:!1,truncated:s,tooLarge:!1,size:e,totalLines:r.length}}async function Lu(t,e){let n=await t.stat();if(!n.isFile())throw new de(e);let r=n.size;if(r>jt)return ir(r);let{head:s,result:o}=await Cu(t,r),i=Nu(o,`${r}-${n.mtimeMs}`);if(o.ok)return si(r,i);if(r>Fu)return ir(r,ie(s)?i:void 0);let a=s.length>=r?s:Buffer.concat([s,await Bt(t,s.length,r-s.length)]);return ie(a)?si(r,i):Ou(a,r)}async function ii(t,e){let n=he.join(t,e),r=await qe.promises.stat(n);if(!r.isFile())throw new de(e);if(r.size>jt)return ir(r.size);let s=await qe.promises.open(n,We);try{return await Lu(s,e)}finally{await s.close()}}import*as ar from"node:path";function ai(t,e){let{registry:n,symbols:r}=e;async function s(o,i,a){if(!a)return o;if(o.binary||o.tooLarge)return o;if(r===null)return{...o,symbols:{status:"unavailable",reason:"error"}};if(!r.pool.supported(i))return{...o,symbols:{status:"unsupported",reason:"language"}};let c=r.gate.acquire();if(c===null)throw new m(503,"Symbol extraction busy");try{return{...o,symbols:await r.pool.extract(i,o.content)}}finally{(await c)()}}t.get("/repos/:id/tree",async({params:o,query:i,res:a})=>{let c=R(n,o.id),l=i.get("dir")??"",u=W(i,"hidden",!1),f=W(i,"ignored",!1),h=l===""?"":bt(c.path,l);await Et(c,h);let d=await st(c.manager.workingTree),p=or(d.files),g;try{g=await oi(c.path,h,{hideHidden:!u,hideGitignored:!f},p)}catch(y){let A=Le(y);if(A==="ENOENT"||A==="ENOTDIR"){let I=await Qn(ar.join(c.path,h));if(I===null)throw new m(404,`No such directory: ${l||"/"}`,{cause:y});throw new m(400,`Not a directory (${I}): ${l}`,{cause:y})}throw y}let S=g.filter((y)=>!Vn(y.name));v(a,200,await Mo(c.path,S))}),t.get("/repos/:id/file",async({params:o,query:i,res:a})=>{let c=R(n,o.id),l=Q(i),u=bt(c.path,l);await Et(c,u);try{let f=await ii(c.path,u);v(a,200,await s(f,u,W(i,"symbols",!1)))}catch(f){if(f instanceof de){let d=await Qn(ar.join(c.path,u));throw new m(400,`Not a regular file (${d??"unknown"}): ${l}`,{cause:f})}let h=Le(f);if(h==="ENOENT"||h==="ENOTDIR")throw new m(404,`No such file: ${l}`,{cause:f});throw f}}),t.get("/repos/:id/files",async({params:o,res:i})=>{let a=R(n,o.id);v(i,200,await ps(a.path))})}var Xe=3,Bu=20,ci=500,Hu=500,Wu=4194304,li=400;class ze extends Error{constructor(){super(`Query must be at least ${Xe} characters`);this.name="GrepQueryTooShortError"}}class qt extends Error{constructor(t){super(t);this.name="GrepQueryInvalidError"}}var ui={matches:[],capped:!1,incomplete:!1,binarySkipped:0};function ju(t){return t===t.toLowerCase()}function cr(t){return Buffer.from(t).toString("utf8")}function Uu(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 fi(t,e=Hu){let n=[],r=new Map,s=0,o=!1,i=0;while(i<t.length){let a=Uu(t,i);if(a===null)break;if(i=a.next,a.contentBytes.includes(0)){s+=1;continue}let c=Number.parseInt(cr(a.lineBytes),10);if(!Number.isSafeInteger(c)||c<1)continue;if(n.length>=e){o=!0;break}let l=cr(a.pathBytes),u=r.get(l)??0;if(u>=Bu){o=!0;continue}r.set(l,u+1);let f=cr(a.contentBytes),h=f.length>li;n.push({path:l,line:c,text:h?f.slice(0,li):f,truncated:h})}return{matches:n,capped:o,incomplete:!1,binarySkipped:s}}function Gu(t){return[...ee,"grep","--no-textconv","--no-recurse-submodules","--full-name","--no-color","--no-column","-I","-n","-z","-F",...ju(t)?["-i"]:[],"-e",t,"--untracked","--","."]}async function hi(t,e){if(e.length<Xe)throw new ze;if(e.length>ci)throw new qt(`Query must be at most ${ci} characters`);if(e.includes("\x00"))throw new qt("Query cannot contain a NUL byte");if(e.includes(`
49
+ `))throw new qt("Query cannot span lines — this searches for literal text");try{return fi(await be(t,Gu(e),Wu))}catch(n){let r=n;if(r.code===1)return ui;if(r.killed===!0||r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...r.stdout?fi(r.stdout):ui,incomplete:!0};throw n}}function di(t,e){let{registry:n}=e;t.post("/repos/:id/search",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"query");try{let c=await hi(i.path,a);v(o,200,c)}catch(c){if(c instanceof ze)throw new m(400,`Query must be at least ${Xe} characters`,{cause:c});if(c instanceof qt)throw new m(400,c.message,{cause:c});throw c}})}import{Worker as qu}from"node:worker_threads";var Xu=1000,zu=64,Ju={status:"unavailable",reason:"deadline"},pe={status:"unavailable",reason:"error"};function Ku(){let t=import.meta.url;return t.endsWith(".ts")?new URL("./symbolWorker.ts",t):new URL("./symbolWorker.js",t)}function pi(t){let e=t.timeoutMs??Xu,n=new Set(t.extensions),r=null,s=0,o=Promise.resolve(),i=!1,a=new Map;function c(h,d){a.delete(h),a.set(h,d);while(a.size>zu){let p=a.keys().next().value;if(p===void 0)break;a.delete(p)}}function l(){let h=r;if(r=null,h!==null)h.terminate()}function u(){let h=new qu(Ku(),{workerData:{grammarDir:t.grammarDir,queryDir:t.queryDir}});return h.unref(),h}function f(h,d){return new Promise((p)=>{if(r===null)try{r=u()}catch(b){E("Cannot start the symbol worker",b,{path:h}),p(pe);return}let g=r,S=++s,y=!1,A=(b,it)=>{if(y)return;if(y=!0,clearTimeout(k),g.off("message",I),g.off("error",D),g.off("exit",w),it)l();p(b)},I=(b)=>{if(b.seq!==S)return;A(b.outcome,!1)},D=(b)=>{E("Symbol worker failed; discarding it",b,{path:h}),A(pe,!0)},w=(b)=>{E(`Symbol worker exited with code ${b}; discarding it`,void 0,{path:h}),A(pe,!0)},k=setTimeout(()=>{E(`Symbol extraction passed its ${e}ms deadline; discarding the worker`,void 0,{path:h}),A(Ju,!0)},e);k.unref?.(),g.on("message",I),g.on("error",D),g.on("exit",w);let _={seq:S,relPath:h,content:d};try{g.postMessage(_)}catch(b){E("Cannot send a file to the symbol worker; discarding it",b,{path:h}),A(pe,!0)}})}return{supported(h){let d=h.lastIndexOf(".");if(d<=h.lastIndexOf("/"))return!1;return n.has(h.slice(d).toLowerCase())},async extract(h,d){if(i)return pe;let p=`${h}\x00${d}`,g=a.get(p);if(g!==void 0)return c(p,g),g;let S=o.then(()=>f(h,d));o=S.catch(()=>{return});let y=await S;return c(p,y),y},async dispose(){i=!0;let h=r;if(r=null,a.clear(),h!==null)await h.terminate()}}}import{spawn as Yu}from"node:child_process";import*as gi from"node:fs";import*as wi from"node:path";class Xt extends Error{constructor(t){super(`Not a regular blob: ${t}`);this.name="NotRegularBlobError"}}class zt extends Error{size;constructor(t,e){super(`Blob too large: ${t} (${e} bytes)`);this.name="BlobTooLargeError",this.size=e}}class St extends Error{constructor(t){super(`Unsafe blob path: ${t}`);this.name="UnsafeBlobPathError"}}var Je=65536,yi=/^[0-9a-f]{40}([0-9a-f]{24})?$/,Vu=new Set(["100644","100755"]);function Qu(t){if(t==="")throw new St("empty");if(t.includes("\x00"))throw new St("contains NUL");if(t.startsWith("-"))throw new St('starts with "-"');if(t.startsWith(":"))throw new St('starts with ":"')}function Ke(t,e,n){return be(t,[...ee,...e],n)}function bi(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 Ei(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 Zu=1;async function tf(t){let e;try{e=(await Ke(t,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],Je)).toString("utf8").trim()}catch(n){if(n?.code===Zu)return null;throw n}return yi.test(e)?e:null}async function ef(t,e){let n=await tf(t);if(n===null)return null;let r=await Ke(t,["ls-tree","-z","--full-tree","-l",n,"--",e],Je),s=Ei(bi(r),e);if(s===null||s.length!==4)return null;return{mode:s[0],oid:s[2],sizeText:s[3]}}async function nf(t,e){let n=await Ke(t,["ls-files","--stage","-z","--",e],Je),r=Ei(bi(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 Si(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 rf(t,e,n){let r=await Ke(t,["cat-file","-s",e],Je);return Si(r.toString("utf8").trim(),n)}var mi=Buffer.alloc(0);function vi(t,e){let n=mi,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=mi,r=!1}}}function sf(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 d(g){a??=g,h()}function p(){let g=Yu("git",[...ee,"cat-file","blob",e],{cwd:t,env:ct(),stdio:["ignore","pipe","ignore"],windowsHide:!0});n=g,g.stdout?.on("data",(S)=>{if(c)return;r.push(S),s+=S.length,h()}),g.stdout?.on("end",()=>{o=!0,h()}),g.stdout?.on("error",d),g.on("error",d),g.on("close",(S,y)=>{i={code:S,signal:y},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((S,y)=>{let A=setTimeout(()=>{n?.kill("SIGKILL"),d(Error(`git cat-file blob timed out for ${e}`))},un);if(l={want:g,resolve:S,reject:y,timer:A},n===null)p();else n.stdout?.resume()})},release(){if(c=!0,l!==null)d(Error(`git cat-file blob closed while reading ${e}`));r.length=0,s=0,n?.kill("SIGKILL"),n=null}}}function of(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function af(t,e,n){let r=wi.join(t,e),s;try{s=await gi.promises.open(r,We)}catch(o){if(of(o))return null;throw o}try{let o=await s.stat();if(!o.isFile())throw new Xt(e);if(o.size>n)throw new zt(e,o.size);let i=o.size,a=vi(i,async(c,l)=>{let u=await Bt(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 cf(t,e,n,r){let s=e==="head"?await ef(t,n):await nf(t,n);if(s===null)return null;if(!Vu.has(s.mode))throw new Xt(n);if(!yi.test(s.oid))throw Error(`git reported a malformed object id for ${n}`);let o=s.oid,i=s.sizeText===null?await rf(t,o,n):Si(s.sizeText,n);if(i>r)throw new zt(n,i);let a=sf(t,o),c=vi(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 xi(t,e,n,r){if(Qu(n),e==="worktree")return af(t,n,r);return cf(t,e,n,r)}var lf=["worktree","index","head"],uf=16,ff=Qo,hf=jt,df=["too-large","too-many-pixels"];function pf(t){let e=t.get("side");if(e===null||!lf.includes(e))throw new m(400,'Invalid "side" (expected worktree, index or head)');return e}function Ai(t){if(t instanceof Xt)throw new m(400,t.message,{cause:t});if(t instanceof St)throw new m(400,t.message,{cause:t});if(t instanceof zt)throw new m(413,t.message,{cause:t});throw t}async function ki(t,e){let n=await t.read(e);return{bytes:n,sniff:Gt(n,t.size,n.length>=t.size)}}async function mf(t,e){let{size:n}=t,r=await t.read(uf),s=Gt(r,n,r.length>=n);if(!s.ok&&s.refusal==="too-large")return{bytes:r,sniff:s};let o=Math.min(Ge(r,n),n),i=await ki(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 ki(t,n)}async function Ii(t,e,n,r){let s=await xi(t,e,n,jt);if(s===null)return null;try{let{bytes:o,sniff:i}=await mf(s,r);return{bytes:o,size:s.size,oid:s.oid,version:s.version,sniff:i}}finally{await s.close()}}function gf(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 wf(t){let e=df.includes(t)?413:415;return new m(e,`Image not served: ${t}`)}function yf(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 bf(t,e,n){return{path:t.path,side:t.side,bytes:e,oid:null,image:null,refusal:n,version:""}}async function Ri(t,e){let n=bt(t.path,e.path);await Et(t,n);let r;try{r=await Ii(t.path,e.side,n,ff)}catch(s){if(s instanceof zt)return bf(e,s.size,"too-large");if(s instanceof Xt)return null;Ai(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 Ef(t,e){return e.writableEnded||e.destroyed===!0||t.destroyed===!0}async function _i(t,e,n){let r=t.acquire();if(r===null)throw new m(503,"Too many image requests in flight");let s=await r;if(n.once("finish",s),n.once("close",s),e.once("close",s),Ef(e,n))return s(),!1;return!0}function Di(t,e,n){let{registry:r}=e;t.get("/repos/:id/media",async({params:s,query:o,req:i,res:a})=>{let c=R(r,s.id),l=W(o,"staged"),u=bt(c.path,Q(o));if(await Et(c,u),!await _i(n,i,a))return;let f=await Lt(c.manager.workingTree,u,l),h=yf(f,l),d={old:h.old===null?null:await Ri(c,h.old),new:h.new===null?null:await Ri(c,h.new)};v(a,200,d)}),t.get("/repos/:id/blob",async({params:s,query:o,req:i,res:a})=>{let c=R(r,s.id),l=Ir(i);if(l)throw new m(l.status,l.message);let u=pf(o),f=bt(c.path,Q(o));if(await Et(c,f),!await _i(n,i,a))return;let h;try{h=await Ii(c.path,u,f,hf)}catch(p){Ai(p)}if(h===null)throw new m(404,`No such blob on side ${u}: ${f}`);if(!h.sniff.ok)throw wf(h.sniff.refusal);let d=gf(u,h.sniff.info.mime,h.oid);Er(a,200,h.bytes,d)})}function Pi(t,e){let{registry:n,sse:r,daemonEvents:s,follow:o}=e;t.get("/events",({req:i,res:a,query:c})=>{let l=n.listRepos().map((f)=>({id:f.id,path:f.path}));s.subscribe(i,a,l);let u=c.get("repo");if(!u)return;r.attach(u,n.getRepo(u)?.manager??null,i,a)}),t.get("/follow",({res:i})=>{v(i,200,o?o.state:ao)})}import*as lr from"node:os";import*as Jt from"node:path";function Ti(t,e){let{settings:n,discovery:r,daemonEvents:s}=e,o=()=>({...n.settings,persisted:n.persisted});t.get("/settings",({res:i})=>{v(i,200,o())}),t.put("/settings",async({body:i,res:a})=>{let c=Ao(i,"watchRoots"),l;try{l=lo(c)}catch(f){throw new m(400,f instanceof Error?f.message:String(f),{cause:f})}try{n.save({...n.settings,watchRoots:l})}catch(f){let h=f instanceof Error?f.message:String(f);throw new m(500,`Could not save settings: ${h}`,{cause:f})}await r.setRoots(l);let u=o();s.broadcast("settings-change",u),v(a,200,u)}),t.get("/discovered",({res:i})=>{v(i,200,r.state)}),t.get("/browse",async({query:i,res:a})=>{let c=i.get("path"),l=c?K(c):lr.homedir();if(!Jt.isAbsolute(l))throw new m(400,`Path must be absolute: ${c}`);let u=Jt.resolve(l),f;try{f=await fo(u)}catch(d){throw new m(404,`Cannot read directory: ${u}`,{cause:d})}let h=Jt.dirname(u);v(a,200,{path:u,parent:h===u?null:h,home:lr.homedir(),entries:f})}),t.post("/discovered/rescan",async({res:i})=>{v(i,200,await r.rescan())})}function ur(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 Sf(t){if(!vt.existsSync(t))return Promise.resolve(!1);return new Promise((e)=>{try{let n=Fi.connect(t);n.once("connect",()=>{n.destroy(),e(!0)}),n.once("error",()=>{n.destroy(),e(!1)})}catch{e(!1)}})}function $i(t={}){let e=new Ln,n=new Bn,r=new Nn({onOpened:(w)=>n.broadcast("repo-opened",{id:w.id,path:w.path}),onClosed:(w)=>{e.closeRepo(w),n.broadcast("repo-closed",{id:w})}}),s=t.followFile?new Wn(r,n,t.followFile):null,o=So(t.updateCheck===!1?()=>Promise.resolve(null):t.fetchLatestVersion),i=new Un(t.settingsFile??null),a=new qn(n),c=new Map,l=ur(),u=t.symbols??null,f=u===null?null:{pool:pi(u),gate:ur(1,4),extensions:u.extensions};function h(w){let k=c.get(w);if(k)return k;let _=new an,b={registry:r,sse:e,daemonEvents:n,follow:s,settings:i,discovery:a,apiMode:w,version:o,symbols:f,httpPort:y};if(xo(_,b),ko(_,b),Co(_,b),Lo(_,b),Ko(_,b),Yo(_,b),w==="full")Vo(_,b);return ai(_,b),di(_,b),Di(_,b,l),Pi(_,b),Ti(_,b),c.set(w,_),_}let d=(w)=>t.apiMode??(w==="tcp"?"web":"full");s?.start(),a.setRoots(i.load().watchRoots);let p=t.webRoot?xr(t.webRoot):void 0,g=new Set,S=[];function y(){for(let w of S){let k=w.server.address();if(k!==null&&typeof k==="object")return k.port}return null}function A(w){let k=h(w),_=Mi.createServer((b,it)=>{for(let[tt,me]of Object.entries(Dr))it.setHeader(tt,me);if(_r(_.address())){let tt=Ar(b);if(tt){v(it,tt.status,{error:tt.message});return}}k.handle(b,it,p).catch((tt)=>{T(`${b.method??"GET"} ${b.url??"/"} escaped the router`,tt),it.end()})});return _.on("connection",(b)=>{g.add(b),b.on("close",()=>g.delete(b))}),_}async function I(w,k){let _=w==="unix"?k.socketPath??null:null;if(_){if(await Sf(_))throw Error(`diffstalkerd already running at ${_}`);vt.rmSync(_,{force:!0})}let b={server:A(d(w)),socketPath:_};S.push(b),await new Promise((it,tt)=>{let me=(Gi)=>tt(Gi);b.server.once("error",me);let Ve=()=>{if(b.server.removeListener("error",me),_)vt.chmodSync(_,384);it()};if(w==="fd")b.server.listen({fd:k.fd},Ve);else if(_)process.umask(63),b.server.listen(_,Ve);else b.server.listen(k.port,"127.0.0.1",Ve)})}function D(w){return new Promise((k,_)=>{w.server.close((b)=>{if(w.socketPath)vt.rmSync(w.socketPath,{force:!0});if(b&&b.code!=="ERR_SERVER_NOT_RUNNING")_(b);else k()})})}return{address(){return S[0]?.server.address()??null},addresses(){return S.map((w)=>w.server.address()).filter((w)=>w!==null)},getRepo(w){return r.getRepo(w)},async openRepo(w){let{handle:k}=await Ne(r,w);return{id:k.id,path:k.path}},async listen(w){let k=[];if(w.fd!==void 0)k.push("fd");if(w.socketPath)k.push("unix");if(w.port!==void 0)k.push("tcp");if(k.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let _ of k)await I(_,w)},close(){s?.dispose(),a.dispose(),e.destroy(),n.destroy(),r.disposeAll();for(let k of g)k.destroy();let w=f?.pool.dispose()??Promise.resolve();return Promise.all([w,...S.splice(0).map(D)]).then(()=>{})}}}import*as fr from"node:fs";import*as Kt from"node:path";import*as Hi from"node:crypto";import{createRequire as xf}from"node:module";var Ci=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 Ni(){return[...Ci.keys()]}function vf(t){let e=t.slice(t.lastIndexOf("/")+1),n=e.lastIndexOf(".");if(n<=0)return"";return e.slice(n).toLowerCase()}function Oi(t){return Ci.get(vf(t))??null}var kf="diffstalkerd-grammars";function Rf(t){return Hi.createHash("sha256").update(t).digest("hex")}function _f(t){try{let e=JSON.parse(fr.readFileSync(Kt.join(t,"checksums.json"),"utf8"));if(typeof e.webTreeSitterVersion!=="string"||typeof e.files!=="object")return null;return e}catch{return null}}var Li="0.26.11";function Af(t,e,n){for(let[r,s]of Object.entries(e.files)){let o;try{o=fr.readFileSync(Kt.join(t,r))}catch{return n(`grammars: missing ${r}`),!1}if(Rf(o)!==s)return n(`grammars: checksum mismatch for ${r}`),!1}return!0}function If(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 Bi(t,e=()=>{}){let n=_f(t);if(n===null)return e(`grammars: no readable checksums.json in ${t}`),null;if(n.webTreeSitterVersion!==Li)return e(`grammars: built for web-tree-sitter ${n.webTreeSitterVersion}, this daemon bundles ${Li} — symbols disabled`),null;if(!Af(t,n,e))return null;let r=If(n),s=Ni().filter((o)=>{let i=Oi(`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:Kt.join(t,"queries"),extensions:s}}function Wi(t,e=()=>{}){if(t!==null)return Bi(t,e);try{let r=xf(import.meta.url).resolve(`${kf}/checksums.json`);return Bi(Kt.dirname(r),e)}catch{return null}}var Ui="diffstalkerd.sock";function Pf(t){return t===void 0?Ui:`${t}.sock`}var Tf=3,ji=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
49
50
 
50
51
  Usage: diffstalkerd [options] [REPO_PATH...]
51
52
 
@@ -57,7 +58,7 @@ Arguments:
57
58
 
58
59
  Options:
59
60
  --socket PATH Bind a unix socket at PATH
60
- (default: $XDG_RUNTIME_DIR/diffstalker/${Oi})
61
+ (default: $XDG_RUNTIME_DIR/diffstalker/${Ui})
61
62
  --instance NAME Bind <NAME>.sock in the runtime dir, so several
62
63
  daemons can run side by side (default: the shared
63
64
  socket every client looks for first)
@@ -77,6 +78,6 @@ Options:
77
78
  ignored follow target) to stderr
78
79
  --version, -v Print the running version and exit
79
80
  --help, -h Show this help
80
- `;function Yt(t,e,n){let r=t[e];if(r===void 0||r.startsWith("--"))throw Error(`${n} requires a value`);return r}function cf(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 lf(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=Yt(t,++n,"--socket");break;case"--instance":e.instance=Yt(t,++n,"--instance");break;case"--no-socket":e.noSocket=!0;break;case"--port":if(e.port=Number(Yt(t,++n,"--port")),!Number.isInteger(e.port)||e.port<0)throw Error("--port requires a non-negative integer");break;case"--follow-file":e.followFile=Yt(t,++n,"--follow-file");break;case"--no-follow":e.noFollow=!0;break;case"--web-root":e.webRoot=Yt(t,++n,"--web-root");break;case"--grammars":e.grammarsDir=Yt(t,++n,"--grammars");break;case"--no-update-check":e.noUpdateCheck=!0;break;case"--debug":e.debug=!0;break;default:cf(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 uf(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function ff(t){if(t.noSocket||t.socketPath!==void 0)return;if(uf()){t.fd=af;return}let e=fr();if(!e){if(t.port!==void 0){console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set; binding the TCP port only.
81
+ `;function Yt(t,e,n){let r=t[e];if(r===void 0||r.startsWith("--"))throw Error(`${n} requires a value`);return r}function Mf(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 Ff(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=Yt(t,++n,"--socket");break;case"--instance":e.instance=Yt(t,++n,"--instance");break;case"--no-socket":e.noSocket=!0;break;case"--port":if(e.port=Number(Yt(t,++n,"--port")),!Number.isInteger(e.port)||e.port<0)throw Error("--port requires a non-negative integer");break;case"--follow-file":e.followFile=Yt(t,++n,"--follow-file");break;case"--no-follow":e.noFollow=!0;break;case"--web-root":e.webRoot=Yt(t,++n,"--web-root");break;case"--grammars":e.grammarsDir=Yt(t,++n,"--grammars");break;case"--no-update-check":e.noUpdateCheck=!0;break;case"--debug":e.debug=!0;break;default:Mf(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 $f(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function Cf(t){if(t.noSocket||t.socketPath!==void 0)return;if($f()){t.fd=Tf;return}let e=mr();if(!e){if(t.port!==void 0){console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set; binding the TCP port only.
81
82
  Pass --socket PATH to also accept CLI connections.`);return}console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set and no --socket/--port given.
82
- Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}Ke.mkdirSync(e,{recursive:!0,mode:448}),t.socketPath=Vt.join(e,of(t.instance))}function hf(t){let e=t??sf(new URL("web/",import.meta.url));if(Ke.existsSync(e))return e;console.error(`diffstalkerd: web UI assets not found at ${e}; serving API only`);return}function df(t){console.error(`diffstalkerd: web UI at http://diffstalker.localhost:${t}/`)}async function pf(t,e){for(let n of e){let r=Vt.resolve(K(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 mf(){process.title="diffstalkerd";let t;try{t=lf(process.argv.slice(2))}catch(u){console.error(u instanceof Error?u.message:String(u)),console.error($i),process.exit(2)}if(t==="help"){console.log($i);return}if(t==="version"){let u=Wn();if(u===null)console.error("diffstalkerd: version unknown (package.json unreadable)"),process.exit(1);console.log(u);return}dr(t.debug??!1),ff(t);let e=t.noFollow?void 0:t.followFile??Vt.join(kt(),"target"),n=hf(t.webRoot),r=Fi(t.grammarsDir??process.env.DIFFSTALKER_GRAMMARS_DIR??null,(u)=>console.error(`diffstalkerd: ${u}`)),s=_i({followFile:e,settingsFile:Vt.join(ur(),"daemon.json"),webRoot:n,symbols:r,updateCheck:!t.noUpdateCheck});await pf(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)df(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)=>{T(`${u}; shutting down`,f),s.close().catch(()=>{}).finally(()=>process.exit(1))};process.on("uncaughtException",(u)=>l("uncaught exception",u)),process.on("unhandledRejection",(u)=>l("unhandled rejection",u))}mf().catch((t)=>{console.error(t instanceof Error?t.message:String(t)),process.exit(1)});export{lf as parseArgs};
83
+ Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}Ye.mkdirSync(e,{recursive:!0,mode:448}),t.socketPath=Vt.join(e,Pf(t.instance))}function Nf(t){let e=t??Df(new URL("web/",import.meta.url));if(Ye.existsSync(e))return e;console.error(`diffstalkerd: web UI assets not found at ${e}; serving API only`);return}function Of(t){console.error(`diffstalkerd: web UI at http://diffstalker.localhost:${t}/`)}async function Lf(t,e){for(let n of e){let r=Vt.resolve(K(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 Bf(){process.title="diffstalkerd";let t;try{t=Ff(process.argv.slice(2))}catch(u){console.error(u instanceof Error?u.message:String(u)),console.error(ji),process.exit(2)}if(t==="help"){console.log(ji);return}if(t==="version"){let u=Xn();if(u===null)console.error("diffstalkerd: version unknown (package.json unreadable)"),process.exit(1);console.log(u);return}wr(t.debug??!1),Cf(t);let e=t.noFollow?void 0:t.followFile??Vt.join(kt(),"target"),n=Nf(t.webRoot),r=Wi(t.grammarsDir??process.env.DIFFSTALKER_GRAMMARS_DIR??null,(u)=>console.error(`diffstalkerd: ${u}`)),s=$i({followFile:e,settingsFile:Vt.join(pr(),"daemon.json"),webRoot:n,symbols:r,updateCheck:!t.noUpdateCheck});await Lf(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)Of(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)=>{T(`${u}; shutting down`,f),s.close().catch(()=>{}).finally(()=>process.exit(1))};process.on("uncaughtException",(u)=>l("uncaught exception",u)),process.on("unhandledRejection",(u)=>l("unhandled rejection",u))}Bf().catch((t)=>{console.error(t instanceof Error?t.message:String(t)),process.exit(1)});export{Ff as parseArgs};