diffstalkerd 0.13.7 → 0.13.8
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,49 +1,49 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);for(let n=e.length-1;n>=0;n--){let r=e[n].trim();if(r)return r}return""}var
|
|
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
|
|
4
|
-
`)}function nn(t,e,n,r){let s=`${new Date().toISOString()} ${t.padEnd(5)} ${
|
|
5
|
-
${r.replace(/^/gm," ")}`:"";process.stderr.write(
|
|
6
|
-
`))}function H(t,e,n){if(!
|
|
1
|
+
var $i=Object.create;var{getPrototypeOf:Oi,defineProperty:ar,getOwnPropertyNames:Ni}=Object;var cr=Object.prototype.hasOwnProperty;function Ci(t){return this[t]}var Li,Hi,Bi=(t,e,n)=>{var r=t!=null&&typeof t==="object";if(r){var s=e?Li??=new WeakMap:Hi??=new WeakMap,o=s.get(t);if(o)return o}n=t!=null?$i(Oi(t)):{};let i=e||!t||!t.__esModule||!cr.call(t,"default")?ar(n,"default",{value:t,enumerable:!0}):n;if(t&&typeof t==="object"||typeof t==="function"){for(let a of Ni(t))if(!cr.call(i,a))ar(i,a,{get:Ci.bind(t,a),enumerable:!0})}if(r)s.set(t,i);return i};var ji=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var js=ji(function(uh,Bs){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=ic(t,e,n);if(o)return o}var i=Rn(t,e),a=t.substring(0,i);t=t.substring(i),e=e.substring(i),i=Ae(t,e);var c=t.substring(t.length-i);t=t.substring(0,t.length-i),e=e.substring(0,e.length-i);var l=Qa(t,e);if(a)l.unshift([M,a]);if(c)l.push([M,c]);if(_n(l,s),r)ec(l);return l}function Qa(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=tc(t,e);if(i){var a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],h=ce(a,l),d=ce(c,u);return h.concat([[M,f]],d)}return Za(t,e)}function Za(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 R=0;R<s;R++){for(var y=-R+h;y<=R-d;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 P=I-y;while(I<n&&P<r&&t.charAt(I)===e.charAt(P))I++,P++;if(a[A]=I,I>n)d+=2;else if(P>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 Ms(t,e,I,P)}}}for(var _=-R+p;_<=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)p+=2;else if(!f){var A=o+u-_;if(A>=0&&A<i&&a[A]!==-1){var I=a[A],P=o+I-A;if(x=n-x,I>=x)return Ms(t,e,I,P)}}}}return[[B,t],[L,e]]}function Ms(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 Rn(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(Ns(t.charCodeAt(s-1)))s--;return s}function Ts(t,e){var n=t.length,r=e.length;if(n==0||r==0)return 0;if(n>r)t=t.substring(n-r);else if(n<r)e=e.substring(0,n);var s=Math.min(n,r);if(t==e)return s;var o=0,i=1;while(!0){var a=t.substring(s-i),c=e.indexOf(a);if(c==-1)return o;if(i+=c,c==0||t.substring(s-i)==e.substring(0,i))o=i,i++}}function Ae(t,e){if(!t||!e||t.slice(-1)!==e.slice(-1))return 0;var n=0,r=Math.min(t.length,e.length),s=r,o=0;while(n<s){if(t.substring(t.length-s,t.length-o)==e.substring(e.length-s,e.length-o))n=s,o=n;else r=s;s=Math.floor((r-n)/2+n)}if(Cs(t.charCodeAt(t.length-s)))s--;return s}function tc(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 R=d.substring(g,g+Math.floor(d.length/4)),y=-1,A="",I,P,w,x;while((y=p.indexOf(R,y+1))!==-1){var _=Rn(d.substring(g),p.substring(y)),b=Ae(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),P=d.substring(g+_),w=p.substring(0,y-b),x=p.substring(y+_)}if(A.length*2>=d.length)return[I,P,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 ec(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)_n(t);sc(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=Ts(u,f),d=Ts(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]=L,t[o-1][1]=f.substring(0,f.length-d),t[o+1][0]=B,t[o+1][1]=u.substring(d),o++;o++}o++}}var Fs=/[^a-zA-Z0-9]/,$s=/\s/,Os=/[\r\n]/,nc=/\n\r?\n$/,rc=/^\r?\n\r?\n/;function sc(t){function e(d,p){if(!d||!p)return 6;var g=d.charAt(d.length-1),R=p.charAt(0),y=g.match(Fs),A=R.match(Fs),I=y&&g.match($s),P=A&&R.match($s),w=I&&g.match(Os),x=P&&R.match(Os),_=w&&d.match(nc),b=x&&p.match(rc);if(_||b)return 5;else if(w||x)return 4;else if(y&&!I&&P)return 3;else if(I||P)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=Ae(r,s);if(i){var a=s.substring(s.length-i);r=r.substring(0,r.length-i),s=a+s.substring(0,s.length-i),o=a+o}var c=r,l=s,u=o,f=e(r,s)+e(s,o);while(s.charAt(0)===o.charAt(0)){r+=s.charAt(0),s=s.substring(1)+o.charAt(0),o=o.substring(1);var h=e(r,s)+e(s,o);if(h>=f)f=h,c=r,l=s,u=o}if(t[n-1][1]!=c){if(c)t[n-1][1]=c;else t.splice(n-1,1),n--;if(t[n][1]=l,u)t[n+1][1]=u;else t.splice(n+1,1),n--}}n++}}function _n(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&&Hs(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(Ls(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=Rn(i,o),a!==0){if(c>=0)t[c][1]+=i.substring(0,a);else t.splice(0,0,[M,i.substring(0,a)]),n++;i=i.substring(a),o=o.substring(a)}if(a=Ae(i,o),a!==0)t[n][1]=i.substring(i.length-a)+t[n][1],i=i.substring(0,i.length-a),o=o.substring(0,o.length-a)}var f=s+r;if(o.length===0&&i.length===0)t.splice(n-f,f),n=n-f;else if(o.length===0)t.splice(n-f,f,[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)_n(t,e)}function Ns(t){return t>=55296&&t<=56319}function Cs(t){return t>=56320&&t<=57343}function Ls(t){return Cs(t.charCodeAt(0))}function Hs(t){return Ns(t.charCodeAt(t.length-1))}function oc(t){var e=[];for(var n=0;n<t.length;n++)if(t[n][1].length>0)e.push(t[n]);return e}function kn(t,e,n,r){if(Hs(t)||Ls(r))return null;return oc([[M,t],[B,e],[L,n],[M,r]])}function ic(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),R=h.slice(0,p);if(g!==R)break t;var y=c.slice(p),A=h.slice(p);return kn(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 P=Math.min(o-I,i-I),w=l.slice(l.length-P),x=d.slice(d.length-P);if(w!==x)break t;var y=l.slice(0,l.length-P),A=d.slice(0,d.length-P);return kn(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,P=w.length;if(i<p+P)break t;var R=e.slice(0,p),x=e.slice(i-P);if(g!==R||w!==x)break t;var y=t.slice(p,o-P),A=e.slice(p,i-P);return kn(g,y,A,w)}return null}function Ie(t,e,n,r){return ce(t,e,n,r,!0)}Ie.INSERT=L;Ie.DELETE=B;Ie.EQUAL=M;Bs.exports=Ie});import*as Je from"node:fs";import*as Vt from"node:path";import{fileURLToPath as tf}from"node:url";import*as Ke from"node:os";import*as vt from"node:path";var Ve="diffstalker";function Qe(){return process.env.XDG_CONFIG_HOME||vt.join(Ke.homedir(),".config")}function lr(){return vt.join(Qe(),Ve)}function kt(){return vt.join(process.env.XDG_CACHE_HOME||vt.join(Ke.homedir(),".cache"),Ve)}function ur(){return process.env.XDG_RUNTIME_DIR?vt.join(process.env.XDG_RUNTIME_DIR,Ve):null}import*as me from"node:fs";import*as ge from"node:path";import*as Ze from"node:os";function Y(t){if(t.startsWith("~/"))return ge.join(Ze.homedir(),t.slice(2));if(t==="~")return Ze.homedir();return t}function we(t){let e=ge.dirname(t);if(!me.existsSync(e))me.mkdirSync(e,{recursive:!0})}function tn(t){let e=t.split(`
|
|
2
|
+
`);for(let n=e.length-1;n>=0;n--){let r=e[n].trim();if(r)return r}return""}var fr=!1;function hr(t){fr=t}function dr(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 Wi=/(\w+:\/\/)[^/\s@]+@/g;function Gi(t){return t.replace(Wi,"$1***@")}function Ui(t){if(!t)return"";let e=[];for(let[n,r]of Object.entries(t)){if(r===void 0)continue;let s=dr(String(r));e.push(`${n}=${/\s/.test(s)||s===""?JSON.stringify(s):s}`)}return e.length===0?"":` ${e.join(" ")}`}function qi(t){if(t instanceof Error)return`${t.name}: ${t.message}`;return String(t)}function en(t,e={stacks:!0}){let n=[],r=t;for(let s=0;s<10&&r!==void 0&&r!==null;s++){let o=s===0?"":"caused by: ",i=e.stacks&&r instanceof Error&&r.stack?r.stack:qi(r);n.push(o+i),r=r instanceof Error?r.cause:void 0}return n.join(`
|
|
4
|
+
`)}function nn(t,e,n,r){let s=`${new Date().toISOString()} ${t.padEnd(5)} ${dr(e)}${Ui(n)}`,o=r?`
|
|
5
|
+
${r.replace(/^/gm," ")}`:"";process.stderr.write(Gi(`${s}${o}
|
|
6
|
+
`))}function H(t,e,n){if(!fr)return;nn("debug",t,n,e===void 0?void 0:en(e,{stacks:!1}))}function v(t,e,n){nn("warn",t,n,e===void 0?void 0:en(e,{stacks:!1}))}function T(t,e,n){nn("error",t,n,e===void 0?void 0:en(e))}import*as Ei from"node:http";import*as xt from"node:fs";import*as xi from"node:net";function rn(t){let e={};for(let[n,r]of t)e[n]=r;return e}function Xi(t){if(!t)return null;return{staged:rn(t.staged),unstaged:rn(t.unstaged)}}function at(t){return{status:t.status,hunkCounts:Xi(t.hunkCounts),error:t.error,stashList:t.stashList,operationInProgress:t.operationInProgress,mtimes:t.mtimes?rn(t.mtimes):null}}function zi(t){return t.entries.length>0?t.entries[0].seq-1:t.nextSeq-1}function pr(t,e){let n=e>0?t.entries.filter((r)=>r.seq>e):t.entries;return{epoch:t.epoch,prunedBefore:zi(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 Ji=1048576;class m extends Error{status;constructor(t,e,n){super(e,n);this.status=t,this.name="HttpError"}}function S(t,e,n){let r=JSON.stringify(Qt(n));t.writeHead(e,{"content-type":"application/json"}),t.end(r)}function mr(t,e,n,r){t.writeHead(e,{...r,"content-length":String(n.byteLength)}),t.end(n)}function Yi(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 Ki(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>Ji)throw new m(413,"Request body too large");e.push(o)}let r=Buffer.concat(e).toString("utf-8");if(!r.trim())return;try{return JSON.parse(r)}catch{throw new m(400,"Invalid JSON body")}}class sn{routes=[];get(t,e){this.add("GET",t,e)}post(t,e){this.add("POST",t,e)}put(t,e){this.add("PUT",t,e)}delete(t,e){this.add("DELETE",t,e)}add(t,e,n){this.routes.push({method:t,segments:e.split("/").filter(Boolean),handler:n})}match(t,e){for(let n of this.routes){if(n.method!==t)continue;let r=Yi(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 Ki(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){Vi(s,r),S(e,r.status,{error:r.message});return}T(`${s} -> 500`,r),S(e,500,{error:"Internal server error"})}}}function Vi(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 on from"node:fs";import*as X from"node:path";var Qi=new Set(["health","version","repos","resolve","worktrees","events","follow","settings","discovered","browse"]),Zi={".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"},gr="no-cache",ta="public, max-age=31536000, immutable";async function wr(t,e,n){let r;try{r=await on.promises.readFile(e)}catch(s){throw new m(404,`Not found: ${X.basename(e)}`,{cause:s})}t.writeHead(200,{"content-type":Zi[X.extname(e)]??"application/octet-stream","cache-control":n,"content-length":r.length}),t.end(r)}function yr(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&&Qi.has(i[0]))throw new m(404,`Unknown route: GET ${s}`);let a=i.length>0?X.resolve(e,i.join("/")):e;if(a!==e&&!a.startsWith(e+X.sep))throw new m(403,"Forbidden");if((await on.promises.stat(a).catch(()=>null))?.isFile()){await wr(r,a,i[0]==="assets"?ta:gr);return}await wr(r,X.join(e,"index.html"),gr)}}function ea(t){try{let e=new URL(`http://${t}`).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function na(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 ra(t){return t.length>10&&t.endsWith(".localhost")}function br(t){return t==="localhost"||t==="::1"||ra(t)||Sr(t)}function sa(t){return t==="::1"||Sr(t)}function Er(t){if(t===null)return!1;if(typeof t==="string")return!0;return sa(t.address)}function xr(t){let e=t.headers.host;if(e!==void 0){let i=ea(e);if(i===null||!br(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=na(o);if(i===null||!br(i))return{status:403,message:"Cross-origin request blocked"}}return null}function vr(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 kr={"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 Mc}from"node:crypto";class Rr{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 an=new Map;function _r(t){let e=an.get(t);if(!e)e=new Rr(t),an.set(t,e);return e}function Ar(t){an.delete(t)}import*as F from"node:path";import*as G from"node:fs";import{execFileSync as cc}from"node:child_process";import{watch as Gs}from"chokidar";import{EventEmitter as lc}from"node:events";import Us from"ignore";import{execFile as ua}from"node:child_process";import{promisify as fa}from"node:util";import{simpleGit as ha}from"simple-git";import*as K from"node:fs";import*as te from"node:path";import{execFileSync as oa}from"node:child_process";var ia=[["*.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 aa(){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
|
-
`+
|
|
8
|
+
`+ia.map(([e,n])=>`${e} diff=${n}`).join(`
|
|
9
9
|
`)+`
|
|
10
|
-
`}var Zt=null,ht=null;function
|
|
10
|
+
`}var Zt=null,ht=null;function ca(){if(ht!==null)return ht;try{if(oa("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=K.existsSync(te.join(Qe(),"git","attributes")),ht}function Ir(){if(Zt!==null)return Zt;if(ca())return null;let t=te.join(kt(),"funcname.gitattributes"),e=aa();try{let n=null;try{n=K.readFileSync(t,"utf8")}catch{n=null}if(n!==e)K.mkdirSync(te.dirname(t),{recursive:!0}),la(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 la(t,e){let n=`${t}.${process.pid}.tmp`;K.writeFileSync(n,e,"utf8"),K.renameSync(n,t)}var da=fa(ua);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"],cn=5000;async function ye(t,e,n){let{stdout:r}=await da("git",e,{cwd:t,env:ct(),encoding:"buffer",maxBuffer:n,timeout:cn,windowsHide:!0});return r}var pa={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0},ma=1e4,ga=600000;function E(t,e={}){let n=Ir(),r=n===null?[]:[`core.attributesFile=${n}`],s=ct();return ha({baseDir:t,unsafe:pa,allowEnvironment:Object.keys(s),timeout:{block:e.longRunning===!0?ga:ma},config:r}).env(s)}import{execFileSync as Ra}from"node:child_process";import*as se from"node:fs";import*as fn from"node:path";async function Rt(t,e){if(e.length===0)return new Set;let n=E(t),r=100,s=[];for(let a=0;a<e.length;a+=r)s.push(e.slice(a,a+r));let o=await Promise.all(s.map(async(a)=>{try{return await n.raw(["check-ignore","--",...a])}catch(c){if(c instanceof Error?c.message.trim():String(c))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(`
|
|
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
|
|
14
|
-
`,n+1))!==-1)e++;return e}function
|
|
13
|
+
`}function be(t){let e=0;for(let n of t)e+=n.content.length+1;return e}var wa=5000,ne=262144,Tr="Large file — diff not shown";function ya(t){return String(t).replace(/\B(?=(\d{3})+(?!\d))/g,",")}function ba(t){let e=t/1048576;if(e>=1)return`${e.toFixed(1)} MB`;return`${Math.round(t/1024)} KB`}function ln(t,e){let n=ba(t),r=e===void 0?n:`${n}, ${ya(e)} lines`;return`${Tr} (${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 Dr(t,e,n){let r=t.split(`
|
|
15
15
|
`),s=r.findIndex((i)=>i.startsWith("@@"));return`${[...r.slice(0,s===-1?4:s),ln(e,n)].join(`
|
|
16
16
|
`)}
|
|
17
|
-
`}function
|
|
18
|
-
`);if(e.length>1&&e[e.length-1]==="")e.pop();let n=[],r=0,s=0;for(let o of e)if(
|
|
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
|
|
20
|
-
`).filter((o)=>o.length>0).length}catch{return null}}var
|
|
21
|
-
`)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}))}catch(r){if(
|
|
22
|
-
`)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}}catch{return null}}async function dn(t){let e=E(t);try{return(await e.stashList()).all.map((r,s)=>({index:s,message:r.message}))}catch(n){return
|
|
23
|
-
`).join(", ")}`);return"Stash popped"}async function
|
|
24
|
-
`)}function
|
|
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<=wa)return s;return n=!0,Dr(s,o,i)}return n=!0,Dr(s,o,Pr(s))});return n?r.join(""):t}function Sa(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(Tr)}function Ea(t){return t.startsWith("\\ ")}function Fr(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(Sa(o))n.push({type:"header",content:o});else if(Ea(o))n.push({type:"context",content:o});else if(o.startsWith("@@")){let i=Fr(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 $r=new Map([["a",7],["b",8],["f",12],["n",10],["r",13],["t",9],["v",11],["\\",92],['"',34]]),xa=new Map([...$r].map(([t,e])=>[e,t]));function Mr(t){return t<32||t===127||t>=128||t===34||t===92}function _t(t){let e=new TextEncoder().encode(t);if(!e.some(Mr))return t;let n='"';for(let r of e){let s=xa.get(r);if(s!==void 0)n+=`\\${s}`;else if(Mr(r))n+=`\\${r.toString(8).padStart(3,"0")}`;else n+=String.fromCharCode(r)}return`${n}"`}function va(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=$r.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 ka(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=ka(n);if(s===-1)return null;let o=va(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 un(t){let e=[],n=t.split("\x00");for(let r=0;r<n.length;r++){let s=n[r];if(s==="")continue;let o=s[0];if(o==="R"||o==="C"){let i=n[r+1],a=n[r+2];if(i!==void 0&&a!==void 0)e.push({code:o,path:a,oldPath:i});r+=2}else{let i=n[r+1];if(i!==void 0)e.push({code:o,path:i});r+=1}}return e}function At(t){return t instanceof Error?t.message:String(t)}function Nr(t){return/does not have any commits yet|bad default revision/i.test(At(t))}var _a=ne;async function Aa(t,e){try{let n=fn.join(t,e),r=await se.promises.stat(n);if(!r.isFile())return null;if(r.size>_a)return null;return(await se.promises.readFile(n,"utf-8")).split(`
|
|
20
|
+
`).filter((o)=>o.length>0).length}catch{return null}}var Ia=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function Pa(t,e){return Ia.has(`${t}${e}`)}function Or(t,e){return e?"conflicted":Da(t)}function Da(t){switch(t){case"M":return"modified";case"A":return"added";case"D":return"deleted";case"?":return"untracked";case"R":return"renamed";case"C":return"copied";case"U":return"conflicted";default:return"modified"}}async function hn(t){let e=E(t);if(!await e.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let r=await e.status(),s=[],o=new Set,i=r.files.filter((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 R=Pa(p.index,p.working_dir);if(p.index&&p.index!==" "&&p.index!=="?"){let y=Or(p.index,R);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:Or(p.working_dir,R),staged:!1})}let c=(p)=>e.diff([...p,"--numstat","-z"]).catch((g)=>(v(`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)=>Aa(t,g.path)));for(let g=0;g<d.length;g++){let R=p[g];if(R===null)continue;d[g].insertions=R,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 Cr(t,e){await E(t).add(["--",e])}async function Lr(t,e){await E(t).reset(["HEAD","--",e])}async function Hr(t){await E(t).add("-A")}async function Br(t){await E(t).reset(["HEAD"])}async function jr(t,e){await E(t).checkout(["--",e])}async function Wr(t,e){await E(t).clean("f",["--",e])}async function Gr(t,e,n=!1){if(!(await E(t,{longRunning:!0}).commit(e,void 0,n?{"--amend":null}:void 0)).commit)throw Error("Nothing to commit: no staged changes")}async function Ur(t){let e=E(t);try{return(await e.log({n:1})).latest?.message||""}catch(n){if(!Nr(n))v(`git log for the HEAD message failed in ${t}: ${At(n)}`);return""}}function qr(t,e,n){Ra("git",["apply","--cached",...n?["--reverse"]:[],"--unidiff-zero"],{cwd:t,input:e,encoding:"utf-8",env:ct(),stdio:["pipe","pipe","pipe"]})}function Xr(t,e){qr(t,e,!1)}function zr(t,e){qr(t,e,!0)}async function Jr(t){let r=(await E(t,{longRunning:!0}).push()).pushed;if(r.length===0)return"Everything up-to-date";return r.map((s)=>`${s.local} → ${s.remote}`).join(", ")}async function Yr(t){return await E(t,{longRunning:!0}).fetch(),"Fetch complete"}async function Kr(t){let n=await E(t,{longRunning:!0}).pull(["--rebase"]);if(n.summary.changes===0&&n.summary.insertions===0&&n.summary.deletions===0)return"Already up-to-date";return`${n.summary.changes} file(s) changed`}async function Vr(t,e=50){let n=E(t);try{return(await n.log({n:e})).all.map((s)=>({hash:s.hash,shortHash:s.hash.slice(0,7),message:s.message.split(`
|
|
21
|
+
`)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}))}catch(r){if(!Nr(r))v(`git log failed in ${t}: ${At(r)}`);return[]}}async function Qr(t,e){let n=E(t);try{let s=(await n.log(["--no-walk",e])).all[0];if(!s)return null;return{hash:s.hash,shortHash:s.hash.slice(0,7),message:s.message.split(`
|
|
22
|
+
`)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}}catch{return null}}async function dn(t){let e=E(t);try{return(await e.stashList()).all.map((r,s)=>({index:s,message:r.message}))}catch(n){return v(`git stash list failed in ${t}, reporting no stashes: ${At(n)}`),[]}}async function Zr(t,e){let n=E(t),r=["push"];if(e)r.push("-m",e);return await n.stash(r),"Stashed"}async function ts(t,e=0){let n=E(t);await n.stash(["pop",`stash@{${e}}`]);let r=(await n.raw(["diff","--name-only","--diff-filter=U"])).trim();if(r)throw Error(`Stash pop hit conflicts in: ${r.split(`
|
|
23
|
+
`).join(", ")}`);return"Stash popped"}async function es(t){let n=await E(t).branchLocal();return n.all.map((r)=>({name:r,current:r===n.current,tracking:n.branches[r]?.label||void 0}))}async function ns(t,e){return await E(t).raw(["switch","--",e]),`Switched to ${e}`}async function rs(t,e){return await E(t).raw(["switch","-c",e]),`Created ${e}`}async function ss(t,e=1){return await E(t).reset(["--soft",`HEAD~${e}`]),"Reset done"}async function os(t,e){return await E(t,{longRunning:!0}).raw(["cherry-pick","--end-of-options",e]),"Cherry-picked"}async function is(t,e){return await E(t,{longRunning:!0}).raw(["revert","--no-edit","--end-of-options",e]),"Reverted"}async function It(t){let e=E(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(fn.join(n,s));if(r("rebase-merge")||r("rebase-apply"))return"rebase";if(r("CHERRY_PICK_HEAD"))return"cherry-pick";if(r("REVERT_HEAD"))return"revert";if(r("MERGE_HEAD"))return"merge";return null}async function as(t){let e=await It(t);if(!e)throw Error("No operation in progress to abort");return await E(t).raw([e,"--abort"]),`Aborted ${e}`}async function cs(t){return await E(t,{longRunning:!0}).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function ls(t){return(await E(t).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((r)=>r.length>0)}import*as mt from"node:fs";import*as Mt from"node:path";import*as Ee from"node:fs";import*as oe from"node:path";function pn(){return oe.join(kt(),"base-branches.json")}function us(){let t=pn();try{return JSON.parse(Ee.readFileSync(t,"utf-8"))}catch(e){if(e.code!=="ENOENT")v("Ignoring the base-branch cache",e,{file:t});return{}}}function Ma(t){we(pn()),Ee.writeFileSync(pn(),JSON.stringify(t,null,2)+`
|
|
24
|
+
`)}function Pt(t){let e=us(),n=oe.resolve(t);return e[n]}function fs(t,e){let n=us(),r=oe.resolve(t);n[r]=e,Ma(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 hs={staged:!1,unstaged:!1,untracked:!1};class xe extends Error{constructor(t){super(`No common history with ${t}`);this.name="NoCommonHistoryError"}}var Tt=3,ms=1e5;function mn(t){return t instanceof Error?t.message:String(t)}function ve(t,e,n){v(`${t} failed in ${e}, answering an empty diff: ${mn(n)}`)}async function Ft(t,e,n=!1,r={}){let s=E(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 ve(`git diff${n?" --cached":""}${i}`,t,o),{lines:[]}}}var Ta="4b825dc642cb6eb9a060e54bf8d69288fbee4904",gs="(unborn)",Fa=/unknown revision|ambiguous argument 'HEAD'|needed a single revision/i;async function ke(t){let e=E(t);try{return(await e.raw(["rev-parse","HEAD"])).trim()}catch(n){let r=n instanceof Error?n.message:String(n);if(Fa.test(r))return gs;throw n}}async function ws(t,e){let n=E(t),s=(e??await ke(t))===gs?Ta:"HEAD",o=lt(await n.raw(["diff",`-U${Tt}`,s,"--"]));return{lines:ut(o)}}var $a=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 Oa(t,e){return{lines:[...gn(t),{type:"header",content:ln(e)}]}}function Na(t){return{lines:gn(t,{binary:!0})}}function Ca(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=Ca(t,e);if(n===null)return{lines:[]};if(n.size>$a)return Oa(e,n.size);let r=mt.readFileSync(n.path);if(ie(r))return Na(e);let s=r.toString("utf-8"),o=gn(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=
|
|
27
|
-
`)){let a=o.exec(i);if(a)for(let c of a[1].split(",")){let l=c.trim().replace(/^.*-> /,"");if(!l.startsWith(
|
|
28
|
-
`);return pt(e===-1?t:t.slice(0,e))}function
|
|
29
|
-
`)[0],author:y.author_name,date:new Date(y.date),refs:y.refs||""}));return{baseBranch:e,stats:{filesChanged:
|
|
30
|
-
`))if(r.startsWith("worktree ")){if(n)e.push(n);n={path:r.slice(9).trim(),branch:null,head:null,isBare:!1,isMain:e.length===0}}else if(!n)continue;else if(r.startsWith("HEAD "))n.head=r.slice(5).trim();else if(r.startsWith("branch "))n.branch=r.slice(7).trim().replace(/^refs\/heads\//,"");else if(r==="bare")n.isBare=!0;if(n)e.push(n);return e}function xn(t){try{if(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 oc=Li(Ls(),1);function Hs(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=Hs(s.content);if(o!==null)n=e.get(o)??[],e.set(o,n);else n=null}n?.push(s)}let r=new Map;for(let[s,o]of e)r.set(s,{lines:o});return r}var De="diffstalker-journal: oversize untracked snapshot omitted";var cc=262144,lc=new Set(["EACCES","EPERM","ENOENT"]);function uc(t){let e=t?.code;return typeof e==="string"&&lc.has(e)}function fc(){return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1}}class Me extends ac{repoPath;queue;hunkTimes;gitWatcher=null;workingDirWatcher=null;ignorers=new Map;_state={status:null,isLoading:!1,error:null,hunkCounts:null,stashList:[],operationInProgress:null,mtimes:null};constructor(t,e){super();this.repoPath=t,this.queue=e,this.hunkTimes=new Sn(t)}get state(){return this._state}get unavailable(){return this._state.status?.isRepo===!1?this.unavailableReason:null}unavailableReason=null;updateState(t){this._state={...this._state,...t},this.emit("state-change",this._state)}setError(t){this.updateState({error:t})}clearError(){if(this._state.error!==null)this.updateState({error:null})}stampDiff(t){this.hunkTimes.stamp(t)}loadGitignores(){let t=new Map,e=js();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=ic("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:ut(),stdio:["ignore","pipe","pipe"]});for(let o of s.split("\x00")){if(!o||o===".gitignore")continue;if(!o.endsWith(".gitignore"))continue;let i=F.dirname(o),a=F.join(this.repoPath,o);try{let c=G.readFileSync(a,"utf-8"),l=js();l.add(c),t.set(i,l)}catch(c){k(`Failed to read ${a}`,c,{repo:this.repoPath})}}}catch(s){k("git ls-files failed; nested .gitignore files are not applied",s,{repo:this.repoPath})}return t}startWatching(){let t=_s(this.repoPath);if(t===null)return;let e=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=Bs([e,n,r,s,o],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=Bs(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(a)=>{let c=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(uc(e))H(t,e,{repo:this.repoPath});else k(t,e,{repo:this.repoPath})}dispose(){let t=(e)=>(n)=>k(`Failed to close the ${e} watcher`,n,{repo:this.repoPath});this.gitWatcher?.close().catch(t("git dir")),this.workingDirWatcher?.close().catch(t("working dir"))}statMtimes(t){let e=new Map;for(let n of t.files){if(e.has(n.path))continue;try{e.set(n.path,G.statSync(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)k(`${e} (was open as one)`,void 0,{repo:this.repoPath});this.unavailableReason=e,this.updateState({status:t,isLoading:!1,error:e})}refreshFailed(t,e){if(!G.existsSync(this.repoPath)){this.notARepo(fc(),"Repository directory no longer exists");return}k(t,e,{repo:this.repoPath}),this.updateState({isLoading:!1,error:e instanceof Error?e.message:"Unknown error"})}async doStatusRefresh(){try{let t=await hn(this.repoPath);if(!t.isRepo){this.notARepo(t,"Not a git repository");return}this.updateState({status:t,mtimes:this.statMtimes(t),isLoading:!1})}catch(t){this.refreshFailed("Status refresh failed",t)}}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.updateState({isLoading:!0,error:null});let t=Date.now(),e=await ke(this.repoPath).catch((n)=>(H("HEAD oid unreadable; journal observation skipped",n,{repo:this.repoPath}),null));try{let n=await hn(this.repoPath);if(!n.isRepo){this.notARepo(n,"Not a git repository");return}let r=this.snapshotJournalGuard(n),[s,o,{stashList:i,operation:a},c]=await Promise.all([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([Dt(this.repoPath),dn(this.repoPath)]);return{operation:e,stashList:n,mtimes:this.statMtimes(t)}}static journalGuardMoved(t,e){if(t.operation!==e.operation||t.stashList.length!==e.stashList.length)return!0;if(t.mtimes.size!==e.mtimes.size)return!0;for(let[n,r]of t.mtimes)if(e.mtimes.get(n)!==r)return!0;return!1}sectionWrittenDuringGather(t,e,n){let r=new Set(e);for(let s of t.files)if(s.status==="untracked")r.add(s.path);for(let s of r)try{let o=G.statSync(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 ps(this.repoPath,e),i=new Set(Pe(o).keys()),a=[...o.lines];await this.appendUntrackedSections(t,i,a);let c=await ke(this.repoPath);if(e!==c)return null;let l=await this.snapshotJournalGuard(t);if(Me.journalGuardMoved(s,l))return null;if(this.sectionWrittenDuringGather(t,i,n))return null;return{headDiff:{lines:a},headOid:c,stashCount:l.stashList.length,operationInProgress:l.operation,mtimes:l.mtimes}}catch(s){return 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>cc){this.appendOversizeSection(s.path,o,n);continue}let i=await wt(this.repoPath,s.path);if(i.lines.length===0)continue;n.push(...i.lines)}}appendOversizeSection(t,e,n){let r=[`diff --git ${At("a/"+t)} ${At("b/"+t)}`,"new file mode 100644",`${De} size=${e.size} mtime=${Math.round(e.mtimeMs)}`];n.push(...r.map((s)=>({type:"header",content:s})))}failed(t,e,n){k(`Failed to ${t}`,e,{repo:this.repoPath,file:n}),this.updateState({error:`Failed to ${t}: ${e instanceof Error?e.message:String(e)}`})}async stage(t){try{await this.queue.enqueueMutation(()=>Or(this.repoPath,t.path)),this.scheduleStatusRefresh()}catch(e){await this.refresh(),this.failed(`stage ${t.path}`,e,t.path)}}async unstage(t){try{await this.queue.enqueueMutation(()=>Nr(this.repoPath,t.path)),this.scheduleStatusRefresh()}catch(e){await this.refresh(),this.failed(`unstage ${t.path}`,e,t.path)}}async stageHunk(t){try{await this.queue.enqueueMutation(async()=>Ur(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.failed("stage hunk",e)}}async unstageHunk(t){try{await this.queue.enqueueMutation(async()=>qr(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.failed("unstage hunk",e)}}async discard(t){if(t.staged)return;let e=t.status==="untracked"?()=>Br(this.repoPath,t.path):()=>Hr(this.repoPath,t.path);try{await this.queue.enqueueMutation(e),await this.refresh()}catch(n){this.failed(`discard ${t.path}`,n,t.path)}}async stageAll(){try{await this.queue.enqueueMutation(()=>Cr(this.repoPath)),await this.refresh()}catch(t){this.failed("stage all",t)}}async unstageAll(){try{await this.queue.enqueueMutation(()=>Lr(this.repoPath)),await this.refresh()}catch(t){this.failed("unstage all",t)}}async commit(t,e=!1){try{await this.queue.enqueue(()=>jr(this.repoPath,t,e)),await this.refresh()}catch(n){this.failed("commit",n)}}async loadStashList(){try{let t=await this.queue.enqueue(()=>dn(this.repoPath));this.updateState({stashList:t})}catch(t){k("Failed to load the stash list",t,{repo:this.repoPath})}}}import{EventEmitter as hc}from"node:events";class _n extends hc{repoPath;queue;callbacks;_remoteState={operation:null,inProgress:!1,error:null,lastResult:null};constructor(t,e,n){super();this.repoPath=t,this.queue=e,this.callbacks=n}get remoteState(){return this._remoteState}updateRemoteState(t){this._remoteState={...this._remoteState,...t},this.emit("remote-state-change",this._remoteState)}async runRemoteOperation(t,e){this.updateRemoteState({operation:t,inProgress:!0,error:null,lastResult:null});try{let n=await this.queue.enqueue(e);this.updateRemoteState({inProgress:!1,lastResult:n}),this.callbacks.scheduleRefresh()}catch(n){k(`git ${t} failed`,n,{repo:this.repoPath});let r=n instanceof Error?n.message:String(n);this.updateRemoteState({inProgress:!1,error:r})}return this._remoteState}async push(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("push",()=>Xr(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>zr(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>Jr(this.repoPath))}async stash(t){if(this._remoteState.inProgress)return null;let e=await this.runRemoteOperation("stash",()=>Vr(this.repoPath,t));return await this.callbacks.loadStashList(),e}async stashPop(t=0){if(this._remoteState.inProgress)return null;let e=await this.runRemoteOperation("stashPop",()=>Qr(this.repoPath,t));return await this.callbacks.loadStashList(),e}async switchBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>ts(this.repoPath,t))}async createBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>es(this.repoPath,t))}async softReset(t=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>ns(this.repoPath,t))}async cherryPick(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>rs(this.repoPath,t))}async revertCommit(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>ss(this.repoPath,t))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>os(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>is(this.repoPath))}}import{EventEmitter as dc}from"node:events";import{randomBytes as pc}from"node:crypto";var mc=262144,gc=500,wc=16777216,Us=Number.MAX_SAFE_INTEGER,yc=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function bc(t){let e=yc.exec(t);if(!e)return null;return{oldStart:parseInt(e[1],10),oldCount:e[2]!==void 0?parseInt(e[2],10):1}}function Sc(t,e){let n=bc(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=Ec(o,r),r++;else if(a==="+")o=o??{hasDel:!1,delStart:0,delEnd:0,anchor:r-1};else Ws(s,o),o=null,r++}return Ws(s,o),s}function Ec(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 Ws(t,e){if(!e)return;t.push(e.hasDel?[2*e.delStart,2*e.delEnd]:[2*e.anchor,2*e.anchor+2])}function An(t){if(t.length===0)return{start:0,count:0};let e=1/0,n=-1/0;for(let[o,i]of t){if(o<e)e=o;if(i>n)n=i}if(n>=Us)return{start:0,count:0};let r=Math.ceil(e/2),s=Math.floor(n/2);return{start:r,count:s-r+1}}function xc(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(De));return{hunks:[{runs:[[0,Us]],bodyHash:Re([dt(t.lines)]),ins:0,del:0,span:{start:0,count:0},diff:t,oversize:i}],renamedFrom:n,hunkless:!0}}return{hunks:r.map(({header:i,body:a})=>{let c=Sc(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:Re(l),ins:u,del:f,span:An(c),diff:{lines:h}}}),renamedFrom:n,hunkless:!1}}function vc(t){if(t.oversize===!0)return null;return Se(t.diff.lines)>mc?null:t.diff}function kc(t,e,n){if(t===0&&e>0)return"shrunk";let r=t+e;if(r>n)return"expanded";if(r<n)return"shrunk";return"edited"}function Gs(t,e){let n=[];return t.forEach((r,s)=>{for(let[o,i]of r.runs)n.push({lo:o,hi:i,node:e+s})}),n.sort((r,s)=>r.lo-s.lo),n}function Rc(t,e){let n=Array.from({length:t.length+e.length},(c,l)=>l),r=(c)=>{while(n[c]!==c)n[c]=n[n[c]],c=n[c];return c},s=(c,l)=>{let u=r(c),f=r(l);if(u!==f)n[u]=f},o=Gs(t,0),i=Gs(e,t.length),a=0;for(let c of o){while(a<i.length&&i[a].hi<c.lo)a++;for(let l=a;l<i.length&&i[l].lo<=c.hi;l++)s(c.node,i[l].node)}return n.map((c,l)=>r(l))}function _c(t,e){let n=Rc(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 Ac(t,e,n){let r=[],s=e.map(()=>null),o=n;for(let i of _c(t,e)){let a=i.prevIdx.map((f)=>t[f]),c=i.nextIdx.map((f)=>e[f]);if(a.length===1&&c.length===1&&a[0].bodyHash===c[0].bodyHash){let f=c[0];s[i.nextIdx[0]]={seq:a[0].seq,runs:f.runs,bodyHash:f.bodyHash,ins:f.ins,del:f.del};continue}if(c.length===0){for(let f of a)r.push({seq:o++,kind:"reverted",span:An(f.runs),stats:{insertions:0,deletions:0},diff:null,supersedes:[f.seq],siblings:1});continue}let l=a.map((f)=>f.seq),u=a.reduce((f,h)=>f+h.ins+h.del,0);for(let f of i.nextIdx){let h=e[f],p={seq:o++,kind:a.length===0?"created":kc(h.ins,h.del,u),span:h.span,stats:{insertions:h.ins,deletions:h.del},diff:vc(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 Ic(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 Te(){return{entries:[],epoch:`${Date.now().toString(36)}-${pc(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class In extends dc{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+=Se(n.diff.lines);for(let n of this.store.entries){if(e<=wc)return;if(n.type!=="hunk"||n.diff===null||t.has(n.seq))continue;e-=Se(n.diff.lines),n.diff=null}}pruneEntries(t){let e=this.store.entries,n=0;while(e.length-n>gc&&(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}=Ic(o,i.hunks);n.push(...c),r.set(s,a)}return{resolves:n,newLive:r}}classify(t,e){let{files:n,deferred:r}=this.parseObservation(t);this.handleRenames(t,n,e),this.handleDisappearances(t,n,r,e);for(let[s,{hunks:o,renamedFrom:i,hunkless:a}]of n){let c=this.store.live.get(s)??[];if(a&&i!==null&&c.length>0)continue;this.classifyPath(s,c,o,t,!1,e)}this.store.lastBranch=t.status.branch.current,this.store.lastStashCount=t.stashCount}handleRenames(t,e,n){for(let[r,s]of e){let o=s.renamedFrom;if(o===null||o===r)continue;if(!this.store.live.has(o)||e.has(o))continue;let i=(this.store.live.get(r)??[]).map((a)=>a.seq);this.store.live.set(r,this.store.live.get(o)),this.store.live.delete(o),n.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor(t,r),path:r,status:"renamed",kind:"renamed",span:{start:0,count:0},stats:{insertions:0,deletions:0},diff:null,supersedes:i,siblings:1,seeded:!1})}}handleDisappearances(t,e,n,r){let s=[...this.store.live.keys()].filter((o)=>!e.has(o)&&!n.has(o));if(s.length===0)return;if(t.stashCount>this.store.lastStashCount){let o=s.flatMap((i)=>this.store.live.get(i).map((a)=>a.seq));r.push(this.boundary("stash","stash",o,t.at));for(let i of s)this.store.live.delete(i);return}for(let o of s){let i=this.store.live.get(o);r.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor(t,o),path:o,status:this.statusOf(t,o),kind:"reverted",span:An(i.flatMap((a)=>a.runs)),stats:{insertions:0,deletions:0},diff:null,supersedes:i.map((a)=>a.seq),siblings:1,seeded:!1}),this.store.live.delete(o)}}classifyPath(t,e,n,r,s,o){let{entries:i,nextLive:a}=Ac(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,xc(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 Pn{workingTree;remote;journal;repoPath;constructor(t,e){this.repoPath=t;let n=kr(t);this.workingTree=new Me(t,n),this.remote=new _n(t,n,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new In(e??Te()),this.workingTree.on("journal-observation",(r)=>this.journal.observe(r))}dispose(){this.workingTree.dispose(),Rr(this.repoPath)}}function Dc(t){return Pc("sha256").update(t).digest("hex").slice(0,12)}var Mc=32;class qs{cap;stores=new Map;constructor(t=Mc){this.cap=t}acquire(t){let e=this.stores.get(t);if(e)this.stores.delete(t);else e=Te();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 Fe 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 Dn{events;byId=new Map;byPath=new Map;journalStores=new qs;constructor(t={}){this.events=t}async openRepo(t){let e=await _e(t,{mustExist:!1});if(!e.ok)throw new Fe(e.reason,e.requested);let n=e.root,r=this.byPath.get(n);if(r)return r.refCount++,{handle:r,created:!1};let s=Dc(n),o=new Pn(n,this.journalStores.acquire(s));o.workingTree.startWatching();let i={id:s,path:n,manager:o,refCount:1};return this.byId.set(i.id,i),this.byPath.set(n,i),this.journalStores.prune((a)=>this.byId.has(a)),this.events.onOpened?.(i),{handle:i,created:!0}}getRepo(t){return this.byId.get(t)}listRepos(){return[...this.byId.values()]}closeRepo(t){let e=this.byId.get(t);if(!e)return!1;if(e.refCount--,e.refCount>0)return!1;return this.byId.delete(e.id),this.byPath.delete(e.path),e.manager.dispose(),this.events.onClosed?.(e.id),!0}disposeAll(){for(let t of this.byId.values())t.manager.dispose();this.byId.clear(),this.byPath.clear()}}function Mn(t){t.manager.workingTree.refresh().catch((e)=>{T("First refresh threw",e,{repo:t.path})})}async function $e(t,e){let n=await t.openRepo(e);if(n.created)Mn(n.handle);return n}var zs=25000;function $t(t,e,n){t.write(`event: ${e}
|
|
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 ve(`reading untracked file ${e}`,t,n),{lines:[]}}}var ds="refs/remotes/";async function wn(t){let e=E(t),n=new Set,r=[];try{let s=await e.raw(["log","--oneline","--decorate=full","--all","-n","200"]),o=/\(([^)]+)\)/g;for(let i of s.split(`
|
|
27
|
+
`)){let a=o.exec(i);if(a)for(let c of a[1].split(",")){let l=c.trim().replace(/^.*-> /,"");if(!l.startsWith(ds))continue;let u=l.slice(ds.length);if(u.endsWith("/HEAD")||n.has(u))continue;n.add(u),r.push(u)}o.lastIndex=0}if(r.length>0)r.sort((i,a)=>{let c=i.split("/").slice(1).join("/"),l=a.split("/").slice(1).join("/"),u=c==="main"||c==="master",f=l==="main"||l==="master";if(u&&!f)return-1;if(!u&&f)return 1;if(u&&f){let h=i.startsWith("origin/"),d=a.startsWith("origin/");if(h&&!d)return 1;if(!h&&d)return-1}return 0})}catch(s){v(`git log for base-branch discovery failed in ${t}: ${mn(s)}`)}return r}async function ae(t){return(await wn(t))[0]??null}async function yn(t){return Pt(t)??await ae(t)}async function nt(t,e){let n=E(t);try{return await n.raw(["cat-file","-e","--end-of-options",`${e}^{commit}`]),!0}catch{return!1}}function La(t){let e=t.indexOf(`
|
|
28
|
+
`);return pt(e===-1?t:t.slice(0,e))}function ys(t,e,n){let r=re(t),s=new Map;for(let a of un(e)){let c;switch(a.code){case"A":c="added";break;case"D":c="deleted";break;case"R":c="renamed";break;default:c="modified"}s.set(a.path,c)}let o=[],i=n.split(/(?=^diff --git )/m).filter((a)=>a.trim());for(let a of i){let c=La(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 Ha(t,e,n){let r=E(t);return bs(r,e,r.status(),n)}async function bs(t,e,n,r="HEAD",s){let o=await bn(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(Dt(i,["--numstat","-z"])),t.raw(Dt(i,["--name-status","-z"])),t.raw(Dt(i,[`-U${Tt}`])).then(lt),n,t.log({from:o,to:r})]),h=ys(a,c,l),d=0,p=0;for(let y of h)d+=y.additions,p+=y.deletions;let g=u.length,R=f.all.map((y)=>({hash:y.hash,shortHash:y.hash.slice(0,7),message:y.message.split(`
|
|
29
|
+
`)[0],author:y.author_name,date:new Date(y.date),refs:y.refs||""}));return{baseBranch:e,stats:{filesChanged:h.length,additions:d,deletions:p},files:h,commits:R,uncommittedCount:g}}async function Ss(t,e,n="HEAD"){let r=E(t),s=await bn(r,e,n),o=await r.raw(["rev-list","--count","--end-of-options",`${s}..${n}`]);return Number.parseInt(o.trim(),10)}async function Es(t,e,n="HEAD"){return bn(E(t),e,n)}async function bn(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 Dt(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 Ba(t,e,n){let r=E(t),s=Dt(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}: ${mn(i)}`),null}return un(o).find((i)=>i.path===n)?.oldPath??null}async function Sn(t,e,n,r={}){let s=E(t),o=r.context??Tt;try{let i=await Ba(t,e,n),a=i===null?[n]:[i,n],c=Dt(e,["-M",`-U${o}`]),l=lt(await s.raw([...c,"--",...a]));return{lines:ut(l)}}catch(i){return ve(`git ${Dt(e,[]).join(" ")} -- ${n}`,t,i),{lines:[]}}}async function xs(t,e){let n=E(t),r=(a)=>n.raw(["show","--format=",...a,"--end-of-options",e]),[s,o,i]=await Promise.all([r(["--numstat","-z"]),r(["--name-status","-z"]),r([`-U${Tt}`]).then(lt)]);return ys(s,o,i)}async function vs(t,e){let n=E(t);try{let r=lt(await n.raw(["show","--format=",`-U${Tt}`,"--end-of-options",e]));return{lines:ut(r)}}catch(r){return ve(`git show ${e}`,t,r),{lines:[]}}}function ja(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 ps(t){return t!==""&&t!==" "&&t!=="?"&&t!=="!"}function Wa(t,e,n){let r=new Set,s=new Set;for(let o of e.files){if(ps(o.index)){if(r.add(o.path),o.from)r.add(o.from)}if(n==="worktree"&&ps(o.working_dir))s.add(o.path)}return t.map((o)=>{let i=Ga(r.has(o.path),s.has(o.path));return i===null?o:{...o,uncommitted:i}})}function Ga(t,e){if(t&&e)return"both";if(t)return"staged";if(e)return"unstaged";return null}async function Ua(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 ks(t,e,n=hs,r){let s=ja(n);if(s===null&&!n.untracked)return Ha(t,e,r);if(r!==void 0)throw Error("Uncommitted work can only be compared against HEAD, not a named head");let o=E(t),i=o.status(),[a,c,l]=await Promise.all([bs(o,e,i,"HEAD",s??void 0),i,n.untracked?i.then((h)=>Ua(t,h)):[]]),f=[...s===null?a.files:Wa(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 Rs from"node:fs";import*as _s from"node:path";function Re(t){let e=5381;for(let n of t){for(let r=0;r<n.length;r++)e=(e<<5)+e+n.charCodeAt(r)|0;e=(e<<5)+e+10|0}return(e>>>0).toString(36)}function qa(t){let e=[],n="",r=null,s=()=>{if(r&&n)e.push({file:n,key:`${n}\x00${Re(r.body)}`,headerLine:r.headerLine});r=null};for(let o of t.lines)if(o.type==="header"){if(s(),o.content.startsWith("diff --git"))n=pt(o.content)??""}else if(o.type==="hunk")s(),r={headerLine:o,body:[]};else if(r&&(o.type==="addition"||o.type==="deletion"))r.body.push(o.content);return s(),e}class En{repoPath;stamps=new Map;constructor(t){this.repoPath=t}stamp(t){if(!t)return;let e=new Map;for(let n of qa(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 Rs.statSync(_s.join(this.repoPath,t)).mtimeMs}catch{return Date.now()}}}import*as V from"node:fs";import*as C from"node:path";async function Xa(t){let e=vn(t);if(!e)return null;try{let n=E(e);if((await n.raw(["rev-parse","--is-bare-repository"])).trim()==="true")return null;return(await n.raw(["rev-parse","--show-toplevel"])).trim()||null}catch(n){return H("rev-parse failed",n,{dir:e}),null}}async function _e(t,{mustExist:e}){let n=Y(t);if(!C.isAbsolute(n))return{ok:!1,reason:"not-absolute",requested:n};if(e&&!za(n))return{ok:!1,reason:"not-a-repo",requested:n};let r=await Xa(n);if(r)return{ok:!0,root:r};let s=Va(await Ja(n));return s?{ok:!0,root:s.path}:{ok:!1,reason:"not-a-repo",requested:n}}function za(t){try{return V.statSync(t).isDirectory()}catch{return!1}}async function Ja(t){let e=vn(t);if(!e)return[];try{let n=E(e);return Ds(await n.raw(["worktree","list","--porcelain"]))}catch(n){return H("worktree list failed",n,{dir:e}),[]}}async function xn(t){let e=vn(t);if(!e)return[];try{let r=await E(e).raw(["worktree","list","--porcelain"]),s=Ds(r),o=await Ka(s,e);return s.map((i)=>({...i,lastActivity:i.isBare?null:Ya(As(i.path)),aheadOfBase:o.get(i.path)??null}))}catch(n){return H("worktree list failed",n,{dir:e}),[]}}function Ya(t){return Number.isFinite(t)?t:null}async function Ka(t,e){let n=t.filter((o)=>!o.isBare);if(n.length===0)return new Map;let r=await ae(e).catch(()=>null),s=await Promise.all(n.map(async(o)=>{let i=Pt(o.path)??r;if(!i)return null;try{let c=await E(o.path).raw(["rev-list","--count","--end-of-options",`${i}..HEAD`]);return[o.path,parseInt(c.trim(),10)]}catch{return null}}));return new Map(s.filter((o)=>o!==null))}function Va(t){let e=null,n=-1/0;for(let r of t){if(r.isBare)continue;let s=As(r.path);if(s>n)n=s,e=r}return e}function As(t){let e=Is(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 Is(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 Ps(t){let e=Is(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 Ds(t){let e=[],n=null;for(let r of t.split(`
|
|
30
|
+
`))if(r.startsWith("worktree ")){if(n)e.push(n);n={path:r.slice(9).trim(),branch:null,head:null,isBare:!1,isMain:e.length===0}}else if(!n)continue;else if(r.startsWith("HEAD "))n.head=r.slice(5).trim();else if(r.startsWith("branch "))n.branch=r.slice(7).trim().replace(/^refs\/heads\//,"");else if(r==="bare")n.isBare=!0;if(n)e.push(n);return e}function vn(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 ac=Bi(js(),1);function Ws(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=Ws(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 De="diffstalker-journal: oversize untracked snapshot omitted";var uc=262144,fc=new Set(["EACCES","EPERM","ENOENT"]);function hc(t){let e=t?.code;return typeof e==="string"&&fc.has(e)}function dc(){return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1}}class Me extends lc{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 En(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=Us();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=cc("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=Us();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=Ps(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=Gs([e,n,r,s,o],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=Gs(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 d=u===0?c:l.slice(u).join("/");if(h.ignores(d))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(hc(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(dc(),"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 hn(this.repoPath);if(!t.isRepo){this.notARepo(t,"Not a git repository");return}this.updateState({status:t,mtimes:this.statMtimes(t),isLoading:!1})}catch(t){this.refreshFailed("Status refresh failed",t)}}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.updateState({isLoading:!0,error:null});let t=Date.now(),e=await ke(this.repoPath).catch((n)=>(H("HEAD oid unreadable; journal observation skipped",n,{repo:this.repoPath}),null));try{let n=await hn(this.repoPath);if(!n.isRepo){this.notARepo(n,"Not a git repository");return}let r=this.snapshotJournalGuard(n),[s,o,{stashList:i,operation:a},c]=await Promise.all([Ft(this.repoPath,void 0,!1),Ft(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.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),dn(this.repoPath)]);return{operation:e,stashList:n,mtimes:this.statMtimes(t)}}static journalGuardMoved(t,e){if(t.operation!==e.operation||t.stashList.length!==e.stashList.length)return!0;if(t.mtimes.size!==e.mtimes.size)return!0;for(let[n,r]of t.mtimes)if(e.mtimes.get(n)!==r)return!0;return!1}sectionWrittenDuringGather(t,e,n){let r=new Set(e);for(let s of t.files)if(s.status==="untracked")r.add(s.path);for(let s of r)try{let o=G.statSync(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 ws(this.repoPath,e),i=new Set(Pe(o).keys()),a=[...o.lines];await this.appendUntrackedSections(t,i,a);let c=await ke(this.repoPath);if(e!==c)return null;let l=await this.snapshotJournalGuard(t);if(Me.journalGuardMoved(s,l))return null;if(this.sectionWrittenDuringGather(t,i,n))return null;return{headDiff:{lines:a},headOid:c,stashCount:l.stashList.length,operationInProgress:l.operation,mtimes:l.mtimes}}catch(s){return 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>uc){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",`${De} 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(()=>Cr(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(()=>Lr(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()=>Xr(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.failed("stage hunk",e)}}async unstageHunk(t){try{await this.queue.enqueueMutation(async()=>zr(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"?()=>Wr(this.repoPath,t.path):()=>jr(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(()=>Hr(this.repoPath)),await this.refresh()}catch(t){this.failed("stage all",t)}}async unstageAll(){try{await this.queue.enqueueMutation(()=>Br(this.repoPath)),await this.refresh()}catch(t){this.failed("unstage all",t)}}async commit(t,e=!1){try{await this.queue.enqueue(()=>Gr(this.repoPath,t,e)),await this.refresh()}catch(n){this.failed("commit",n)}}async loadStashList(){try{let t=await this.queue.enqueue(()=>dn(this.repoPath));this.updateState({stashList:t})}catch(t){v("Failed to load the stash list",t,{repo:this.repoPath})}}}import{EventEmitter as pc}from"node:events";class An extends pc{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",()=>Jr(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",()=>Kr(this.repoPath))}async stash(t){if(this._remoteState.inProgress)return null;let e=await this.runRemoteOperation("stash",()=>Zr(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",()=>ts(this.repoPath,t));return await this.callbacks.loadStashList(),e}async switchBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>ns(this.repoPath,t))}async createBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>rs(this.repoPath,t))}async softReset(t=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>ss(this.repoPath,t))}async cherryPick(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>os(this.repoPath,t))}async revertCommit(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>is(this.repoPath,t))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>as(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>cs(this.repoPath))}}import{EventEmitter as mc}from"node:events";import{randomBytes as gc}from"node:crypto";var wc=262144,yc=500,bc=16777216,zs=Number.MAX_SAFE_INTEGER,Sc=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function Ec(t){let e=Sc.exec(t);if(!e)return null;return{oldStart:parseInt(e[1],10),oldCount:e[2]!==void 0?parseInt(e[2],10):1}}function xc(t,e){let n=Ec(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=vc(o,r),r++;else if(a==="+")o=o??{hasDel:!1,delStart:0,delEnd:0,anchor:r-1};else qs(s,o),o=null,r++}return qs(s,o),s}function vc(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 qs(t,e){if(!e)return;t.push(e.hasDel?[2*e.delStart,2*e.delEnd]:[2*e.anchor,2*e.anchor+2])}function In(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>=zs)return{start:0,count:0};let r=Math.ceil(e/2),s=Math.floor(n/2);return{start:r,count:s-r+1}}function kc(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(De));return{hunks:[{runs:[[0,zs]],bodyHash:Re([dt(t.lines)]),ins:0,del:0,span:{start:0,count:0},diff:t,oversize:i}],renamedFrom:n,hunkless:!0}}return{hunks:r.map(({header:i,body:a})=>{let c=xc(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:Re(l),ins:u,del:f,span:In(c),diff:{lines:h}}}),renamedFrom:n,hunkless:!1}}function Rc(t){if(t.oversize===!0)return null;return be(t.diff.lines)>wc?null:t.diff}function _c(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 Xs(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 Ac(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=Xs(t,0),i=Xs(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 Ic(t,e){let n=Ac(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 Pc(t,e,n){let r=[],s=e.map(()=>null),o=n;for(let i of Ic(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:In(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":_c(h.ins,h.del,u),span:h.span,stats:{insertions:h.ins,deletions:h.del},diff:Rc(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 Dc(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 Te(){return{entries:[],epoch:`${Date.now().toString(36)}-${gc(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class Pn extends mc{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<=bc)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>yc&&(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}=Dc(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:In(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}=Pc(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,kc(s));let n=new Set;for(let r of t.status.files)if(r.status==="untracked"&&!e.has(r.path))n.add(r.path);return{files:e,deferred:n}}boundary(t,e,n,r){return{type:"boundary",seq:this.store.nextSeq++,ts:r,kind:t,label:e,resolves:n}}tsFor(t,e){let n=t.mtimes?.get(e);return n===void 0?t.at:Math.min(n,t.at)}statusOf(t,e){return t.status.files.find((n)=>n.path===e)?.status??"modified"}}class Dn{workingTree;remote;journal;repoPath;constructor(t,e){this.repoPath=t;let n=_r(t);this.workingTree=new Me(t,n),this.remote=new An(t,n,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new Pn(e??Te()),this.workingTree.on("journal-observation",(r)=>this.journal.observe(r))}dispose(){this.workingTree.dispose(),Ar(this.repoPath)}}function Tc(t){return Mc("sha256").update(t).digest("hex").slice(0,12)}var Fc=32;class Js{cap;stores=new Map;constructor(t=Fc){this.cap=t}acquire(t){let e=this.stores.get(t);if(e)this.stores.delete(t);else e=Te();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 Fe 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 Mn{events;byId=new Map;byPath=new Map;journalStores=new Js;constructor(t={}){this.events=t}async openRepo(t){let e=await _e(t,{mustExist:!1});if(!e.ok)throw new Fe(e.reason,e.requested);let n=e.root,r=this.byPath.get(n);if(r)return r.refCount++,{handle:r,created:!1};let s=Tc(n),o=new Dn(n,this.journalStores.acquire(s));o.workingTree.startWatching();let i={id:s,path:n,manager:o,refCount:1};return this.byId.set(i.id,i),this.byPath.set(n,i),this.journalStores.prune((a)=>this.byId.has(a)),this.events.onOpened?.(i),{handle:i,created:!0}}getRepo(t){return this.byId.get(t)}listRepos(){return[...this.byId.values()]}closeRepo(t){let e=this.byId.get(t);if(!e)return!1;if(e.refCount--,e.refCount>0)return!1;return this.byId.delete(e.id),this.byPath.delete(e.path),e.manager.dispose(),this.events.onClosed?.(e.id),!0}disposeAll(){for(let t of this.byId.values())t.manager.dispose();this.byId.clear(),this.byPath.clear()}}function Tn(t){t.manager.workingTree.refresh().catch((e)=>{T("First refresh threw",e,{repo:t.path})})}async function $e(t,e){let n=await t.openRepo(e);if(n.created)Tn(n.handle);return n}var Ks=25000;function $t(t,e,n){t.write(`event: ${e}
|
|
31
31
|
data: ${n}
|
|
32
32
|
|
|
33
|
-
`)}function
|
|
33
|
+
`)}function Vs(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Ys(t,e){$t(t,"repo-missing",JSON.stringify({id:e}))}class Fn{channels=new Map;subscribe(t,e,n,r){Vs(r),this.join(t,e,n,r,{owned:!0})}attach(t,e,n,r){if(!e){Ys(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
|
|
34
34
|
|
|
35
|
-
`)},
|
|
35
|
+
`)},Ks),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 Ys(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 $n{subscribers=new Set;keepAlive=null;subscribe(t,e,n){if(Vs(e),this.subscribers.add(e),!this.keepAlive)this.keepAlive=setInterval(()=>{for(let r of this.subscribers)r.write(`: ping
|
|
36
36
|
|
|
37
|
-
`)},
|
|
38
|
-
`,{mode:384}),U.renameSync(e,this.file)}catch(n){throw U.rmSync(e,{force:!0}),n}return this.current}}import*as
|
|
39
|
-
`)[0]?.trim();e(s?s:null)})})},writable(t){try{return ft.accessSync(t,ft.constants.W_OK),!0}catch{return!1}}};function el(){let t=ot.dirname(Yc(new URL("../package.json",import.meta.url)));try{return ft.realpathSync(t)}catch{return t}}function ro(t=el(),e=tl){let n=null;return{info(){return n??=Zc(t,e).catch((r)=>(k("Install detection failed",r,{dir:t}),no)),n}}}var nl="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",rl=21600000,sl=300000,ol=5000;function Bn(){try{let t=oo.readFileSync(new URL("../package.json",import.meta.url),"utf-8"),e=JSON.parse(t);return typeof e.version==="string"?e.version:null}catch(t){return k("Cannot read the daemon version from its package.json",t),null}}async function il(){let t=await fetch(nl,{headers:{accept:"application/json"},signal:AbortSignal.timeout(ol)});if(!t.ok)return null;let e=await t.json();return typeof e.latest==="string"?e.latest:null}function so(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());if(!e)return null;return[Number(e[1]),Number(e[2]),Number(e[3])]}function al(t,e){if(t===null||e===null)return"unknown";let n=so(t),r=so(e);if(!n||!r)return"unknown";for(let s=0;s<n.length;s++){if(n[s]<r[s])return"outdated";if(n[s]>r[s])return"ahead"}return"current"}function io(t=il,e=Bn(),n=ro()){let r=null,s=null;function o(){if(r&&Date.now()<r.expiresAt)return Promise.resolve(r.value);if(s)return s;return s=t().catch((i)=>(H("Latest version lookup failed",i),null)).then((i)=>{let a=i===null?sl:rl;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:al(e,i),install:a}}}}import*as ao from"node:os";function co(t,e){t.get("/health",({res:n})=>{S(n,200,{ok:!0,ready:!0,home:ao.homedir(),http:{port:e.httpPort()},symbols:{extensions:e.symbols?.extensions??[]}})})}function lo(t,e){t.get("/version",async({res:n})=>{S(n,200,await e.version.state())})}import*as So from"node:fs";import*as Nt from"node:fs";import*as N from"node:path";function Ct(t,e){let n=t.getRepo(e);if(!n)throw new g(404,`Unknown repo id: ${e}`);return n}function R(t,e){let n=Ct(t,e),r=n.manager.workingTree.unavailable;if(r!==null)throw new g(410,r);return n}function q(t,e,n){if(typeof t!=="object"||t===null)throw new g(400,`Expected a JSON body with "${e}"`);let r=t[e];if(typeof r!=="string"||!n?.allowEmpty&&r.length===0)throw new g(400,`Missing "${e}" (string) in body`);return r}function fo(t,e){if(t.length===0)throw new g(400,`Invalid "${e}" (expected a ref)`);if(t.startsWith("-"))throw new g(400,`Invalid "${e}" (must not start with "-"): ${t}`);return t}function bt(t,e){return fo(q(t,e),e)}function Gn(t,e){let n=t.get(e);return n===null?null:fo(n,e)}function ho(t,e){if(typeof t!=="object"||t===null)throw new g(400,`Expected a JSON body with "${e}"`);let n=t[e];if(!Array.isArray(n)||n.some((r)=>typeof r!=="string"))throw new g(400,`Missing "${e}" (array of strings) in body`);return n}function po(t,e){if(typeof t!=="object"||t===null)return;let n=t[e];if(n===void 0)return;if(typeof n!=="string"||n.length===0)throw new g(400,`Invalid "${e}" (expected a non-empty string)`);return n}function Un(t,e,n){if(typeof t!=="object"||t===null)return n.fallback;let r=t[e];if(r===void 0)return n.fallback;if(typeof r!=="number"||!Number.isInteger(r)||r<n.min)throw new g(400,`Invalid "${e}" (expected an integer >= ${n.min})`);return r}function mo(t,e){if(typeof t!=="object"||t===null)return!1;let n=t[e];if(n===void 0)return!1;if(typeof n!=="boolean")throw new g(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 g(400,`Missing "${e}" query parameter (expected true or false)`);return n}if(r==="true")return!0;if(r==="false")return!1;throw new g(400,`Invalid "${e}" (expected true or false): ${r}`)}function Q(t){let e=t.get("path");if(!e)throw new g(400,'Missing "path" query parameter');return e}function fe(t,e){let n=j(t,"whole",!1);if(n&&!e)throw new g(400,"whole=true requires a path (one file at a time)");return n?hs:void 0}function go(t,e,n,r){let s=t.get(e);if(s===null)return n;let o=Number(s);if(!Number.isInteger(o)||o<1)throw new g(400,`Invalid "${e}" (expected a positive integer): ${s}`);if(r!==void 0&&o>r)throw new g(400,`Invalid "${e}" (must be <= ${r}): ${s}`);return o}async function it(t){if(!t.state.status)await t.refresh();let e=t.state.status;if(!e)throw new g(500,"Repository status unavailable");return e}function uo(t,e,n){let r=t.files.filter((s)=>s.path===e);if(r.length===0)return null;return r.find((s)=>s.staged===n)??r[0]}async function Lt(t,e,n){let r=await it(t),s=uo(r,e,n);if(!s)await t.refresh(),r=await it(t),s=uo(r,e,n);if(!s)throw new g(404,`File not in status: ${e}`);return s}function Wn(t,e){return t===e||t.startsWith(e+N.sep)}function qn(t){return t.replace(/[. ]+$/,"").toLowerCase()===".git"}function St(t,e){if(e.length===0)throw new g(400,"Empty path");if(e.includes("\x00"))throw new g(400,"Path contains a NUL byte");let n=N.resolve(t),r=N.relative(n,N.resolve(n,e));if(r==="")throw new g(400,`Path resolves to the repository root: ${e}`);if(N.isAbsolute(r)||r===".."||r.startsWith(`..${N.sep}`))throw new g(400,`Path escapes repository root: ${e}`);if(r.startsWith("-"))throw new g(400,`Path must not start with "-": ${e}`);if(r.startsWith(":"))throw new g(400,`Path must not start with ":": ${e}`);if(r.split(N.sep).some(qn))throw new g(400,`Path addresses the git directory: ${e}`);return r}async function wo(t){try{return await Nt.promises.realpath(t)}catch{return null}}var jn=new WeakMap;async function cl(t){let e=jn.get(t);if(!e)e=(async()=>{let n=await E(t.path).raw(["rev-parse","--absolute-git-dir"]);return await Nt.promises.realpath(n.trim())})(),jn.set(t,e),e.catch(()=>jn.delete(t));try{return await e}catch(n){throw new g(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 wo(N.join(t.path,e));if(r===null)return;if(!Wn(r,n))throw new g(400,`Path escapes repository root: ${e}`);if(Wn(r,await cl(t)))throw new g(400,`Path addresses the git directory: ${e}`)}async function yo(t,e){let n=await Nt.promises.realpath(N.resolve(t)),r=[];for(let s of e){let o=await wo(N.join(t,s.path));if(o===null||Wn(o,n))r.push(s)}return r}function Ne(t){return t?.code??null}async function Xn(t){let e;try{e=await Nt.promises.stat(t)}catch(n){let r=Ne(n);if(r==="ENOENT"||r==="ENOTDIR")return null;throw n}if(e.isDirectory())return"a directory";if(e.isFile())return"a file";if(e.isFIFO())return"a FIFO";if(e.isSocket())return"a socket";return"a device"}function ll(t){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test(t)?409:500}function bo(t,e){return new g(t,e)}async function at(t,e,n){t.clearError(),await n();let r=t.state.error;if(r)throw bo(ll(r),r);await t.refresh(),S(e,200,{state:lt(t.state)})}var ul=/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged|no tracking information|no upstream|no configured push destination/i;function fl(t){return ul.test(t)?409:500}async function W(t,e,n){let r=t.manager.remote,s=()=>new g(409,`A ${r.remoteState.operation??"remote"} operation is already in progress`);if(r.remoteState.inProgress)throw s();let o=await n();if(o===null)throw s();let i=t.manager.workingTree;if(await i.refresh(),o.error)throw bo(fl(o.error),o.error);S(e,200,{state:lt(i.state),result:o.lastResult})}function hl(t){if(t.reason==="not-a-repo"&&!So.existsSync(t.requested))return new g(404,`No such directory: ${t.requested}`,{cause:t});return new g(400,t.message,{cause:t})}function Eo(t,e){let{registry:n}=e;t.get("/repos",({res:r})=>{let s=n.listRepos().map((o)=>({id:o.id,path:o.path,branch:o.manager.workingTree.state.status?.branch.current??null}));S(r,200,s)}),t.post("/repos",async({body:r,res:s})=>{let o=q(r,"path"),i;try{i=await $e(n,o)}catch(a){if(a instanceof Fe)throw hl(a);throw a}S(s,i.created?201:200,{id:i.handle.id,path:i.handle.path})}),t.get("/resolve",async({query:r,res:s})=>{let o=Q(r),i=await _e(o,{mustExist:!0});if(!i.ok&&i.reason==="not-absolute")throw new g(400,`Repo path must be absolute: ${i.requested}`);S(s,200,{openable:i.ok,root:i.ok?i.root:null})}),t.get("/repos/:id/worktrees",async({params:r,res:s})=>{let o=R(n,r.id);S(s,200,await En(o.path))}),t.get("/worktrees",async({query:r,res:s})=>{S(s,200,await En(Q(r)))}),t.delete("/repos/:id",({params:r,res:s})=>{Ct(n,r.id),n.closeRepo(r.id),S(s,200,{})})}function xo(t,e,n){if(!t.trim())return{valid:!1,error:"Commit message cannot be empty"};if(e===0&&!n)return{valid:!1,error:"No changes staged for commit"};return{valid:!0,error:null}}function vo(t){return t.trim()}async function dl(t){let e=(r)=>r.filter((s)=>s.staged).length,n=e((await it(t)).files);if(n===0)await t.refresh(),n=e((await it(t)).files);return n}function ko(t,e){let{registry:n,sse:r}=e;if(t.get("/repos/:id/status",async({params:s,res:o})=>{let i=Ct(n,s.id);await it(i.manager.workingTree),S(o,200,lt(i.manager.workingTree.state))}),t.get("/repos/:id/diff",async({params:s,query:o,res:i})=>{let a=R(n,s.id),c=o.get("path")??void 0,l=j(o,"staged",!1),u=fe(o,c),f,h=!1;if(c){let d=(await it(a.manager.workingTree)).files.some((m)=>m.path===c&&m.status==="untracked");if(d&&l)throw new g(400,`staged=true is meaningless for untracked file: ${c} (untracked files have no staged diff)`);h=u!==void 0&&!d,f=d?await wt(a.path,c):await Ft(a.path,c,l,{context:u})}else f=await Ft(a.path,void 0,l);if(!h)a.manager.workingTree.stampDiff(f);S(i,200,f)}),t.post("/repos/:id/stage",async({params:s,body:o,res:i})=>{let a=R(n,s.id),c=q(o,"path"),l=a.manager.workingTree,u=await Lt(l,c,!1);await at(l,i,()=>l.stage(u))}),t.post("/repos/:id/unstage",async({params:s,body:o,res:i})=>{let a=R(n,s.id),c=q(o,"path"),l=a.manager.workingTree,u=await Lt(l,c,!0);await at(l,i,()=>l.unstage(u))}),t.get("/repos/:id/events",({params:s,req:o,res:i})=>{let a=Ct(n,s.id);r.subscribe(s.id,a.manager,o,i)}),e.apiMode==="full")pl(t,e)}function pl(t,e){let{registry:n}=e;t.post("/repos/:id/stage-all",async({params:r,res:s})=>{let i=R(n,r.id).manager.workingTree;await at(i,s,()=>i.stageAll())}),t.post("/repos/:id/unstage-all",async({params:r,res:s})=>{let i=R(n,r.id).manager.workingTree;await at(i,s,()=>i.unstageAll())}),t.post("/repos/:id/discard",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"path"),c=i.manager.workingTree,l=await Lt(c,a,!1);if(l.staged)throw new g(409,`Cannot discard a staged file: ${a} (unstage it first)`);await at(c,o,()=>c.discard(l))}),t.post("/repos/:id/commit",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"message",{allowEmpty:!0}),c=mo(s,"amend"),l=i.manager.workingTree,u=await dl(l),f=xo(a,u,c);if(!f.valid)throw new g(400,f.error??"Invalid commit");await at(l,o,()=>l.commit(vo(a),c))}),t.post("/repos/:id/stage-hunk",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"patch"),c=i.manager.workingTree;await at(c,o,()=>c.stageHunk(a))}),t.post("/repos/:id/unstage-hunk",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"patch"),c=i.manager.workingTree;await at(c,o,()=>c.unstageHunk(a))})}var ml=1000,Ce="refs/heads/",Ro="refs/remotes/";async function Ao(t,e,n){let r=["for-each-ref","--format=%(objectname) %(refname) %(symref)",`--no-merged=${e}`];if(n!==void 0)r.push(`--contains=${n}`);r.push("refs/heads","refs/remotes");let s=await t.raw(r),o=[];for(let i of s.split(`
|
|
40
|
-
`)){if(!i)continue;let[a,c,l]=i.split(" ");if(l)continue;if(c.startsWith(Ce))o.push({tip:a,name:c.slice(Ce.length),local:!0});else if(c.startsWith(
|
|
41
|
-
`).filter(Boolean).reverse()}async function
|
|
42
|
-
`),s=r.startsWith(Ce)?r.slice(Ce.length):null;return{tip:n,name:s??"HEAD",branch:s}}async function
|
|
43
|
-
`).filter(Boolean)}function bl(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 Mo(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=bl(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 Sl(t,e,n,r,s,o){let i=Io(await Ao(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 _o(t,a);if(c.length>1){let u=[...new Set(i.filter((f)=>Po(f,o)).map((f)=>f.tip))];if(u.length>0)c=await _o(t,u)}if(c.length!==1)return{layers:[],forked:!0};let l=await Do(t,n,c[0]);return{layers:Mo(l,s,null,o),forked:!1}}function El(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 To(t,e){let n=E(t),r=await yl(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([Ao(n,e),Do(n,s,r.tip)]),a=gl(o),c=wl(o),l=new Map,u=new Set;for(let p of Io(o,a)){let d=l.get(p.tip);if(d)d.push(p);else l.set(p.tip,[p]);if(Po(p,c))u.add(p.tip)}let f=Mo(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 Sl(n,e,r.tip,a,l,c);return{trunk:e,layers:El([...f,...h.layers],u),forkedAbove:h.forked}}function zn(t){if(!/^[0-9a-f]{4,40}$/i.test(t))throw new g(400,`Invalid commit hash: ${t}`);return t}async function Fo(t,e){if(!await st(t,e))throw new g(404,`Unknown commit: ${e}`)}async function $o(t){try{return await t()}catch(e){if(e instanceof ae)throw new g(422,e.message,{cause:e});throw e}}async function xl(t){let e=await yn(t);if(e&&await st(t,e))return e;if(Mt(t)){let n=await ce(t);if(n&&await st(t,n))return n}throw new g(422,"No usable base branch")}async function Le(t,e){let n=Gn(e,"base");if(n===null)return xl(t);if(!await st(t,n))throw new g(400,`Unknown base ref: ${n}`);return n}async function Jn(t,e){let n=Gn(e,"head");if(n===null)return;if(!await st(t,n))throw new g(400,`Unknown head ref: ${n}`);return n}function Oo(t,e){if(e&&t.get("head")!==null)throw new g(400,"head cannot be combined with uncommitted work (it only exists against HEAD)")}var vl=new Set(["staged","unstaged","both","untracked"]);function kl(t){let e=t.get("uncommitted");if(e===null)return null;if(!vl.has(e))throw new g(400,`Invalid "uncommitted" (expected staged, unstaged, both or untracked): ${e}`);return e}function Rl(t){return{staged:j(t,"staged",!1),unstaged:j(t,"unstaged",!1),untracked:j(t,"untracked",!1)}}function No(t,e){let{registry:n}=e;if(t.get("/repos/:id/history",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=go(s,"count",100,5000);S(o,200,await Yr(i.path,a))}),t.get("/repos/:id/commits/:hash",async({params:r,res:s})=>{let o=R(n,r.id),i=zn(r.hash),a=await Kr(o.path,i);if(a===null)throw new g(404,`Unknown commit: ${i}`);S(s,200,a)}),t.get("/repos/:id/commits/:hash/diff",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=zn(r.hash);await Fo(i.path,a);let c=s.get("path")??void 0,l=fe(s,c),u=c?await bn(i.path,{kind:"commit",hash:a},c,{context:l}):await Ss(i.path,a);S(o,200,u)}),t.get("/repos/:id/commits/:hash/files",async({params:r,res:s})=>{let o=R(n,r.id),i=zn(r.hash);await Fo(o.path,i),S(s,200,await bs(o.path,i))}),t.get("/repos/:id/compare/file",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=Q(s),c=fe(s,a),l=kl(s);if(Oo(s,l!==null),l==="untracked"){S(o,200,await wt(i.path,a));return}let u=l===null?{kind:"compare",base:await Le(i.path,s),head:await Jn(i.path,s)}:{kind:l==="both"?"head":l};S(o,200,await bn(i.path,u,a,{context:c}))}),t.get("/repos/:id/head-message",async({params:r,res:s})=>{let o=R(n,r.id);S(s,200,{message:await Wr(o.path)})}),t.get("/repos/:id/branches",async({params:r,res:s})=>{let o=R(n,r.id);S(s,200,await Zr(o.path))}),t.get("/repos/:id/base-branches",async({params:r,res:s})=>{let o=R(n,r.id);S(s,200,await wn(o.path))}),t.get("/repos/:id/compare/base",async({params:r,res:s})=>{let o=R(n,r.id);S(s,200,{base:await yn(o.path)})}),e.apiMode==="full")t.put("/repos/:id/compare/base",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=bt(s,"branch");if(!await st(i.path,a))throw new g(400,`Not a valid base ref: ${a}`);ls(i.path,a),S(o,200,{base:a})});t.get("/repos/:id/compare/count",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=await Le(i.path,s),c=await Jn(i.path,s),l=await $o(()=>ys(i.path,a,c));S(o,200,{baseBranch:a,commits:l})}),t.get("/repos/:id/compare/stack",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=await Le(i.path,s);S(o,200,await To(i.path,a))}),t.get("/repos/:id/compare",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=Rl(s);Oo(s,a.staged||a.unstaged||a.untracked);let c=await Le(i.path,s),l=await Jn(i.path,s),u=await $o(()=>Es(i.path,c,a,l));S(o,200,u)})}function _l(t){let e=t.get("since");if(e===null)return 0;if(!/^\d+$/.test(e))throw new g(400,`Invalid "since" (expected a non-negative integer): ${e}`);return Number(e)}function Co(t,e){let{registry:n}=e;t.get("/repos/:id/journal",({params:r,query:s,res:o})=>{let i=R(n,r.id),a=_l(s);S(o,200,hr(i.manager.journal.journalStore,a))})}function Lo(t,e){let{registry:n}=e;t.post("/repos/:id/push",async({params:r,res:s})=>{let o=R(n,r.id);await W(o,s,()=>o.manager.remote.push())}),t.post("/repos/:id/fetch",async({params:r,res:s})=>{let o=R(n,r.id);await W(o,s,()=>o.manager.remote.fetchRemote())}),t.post("/repos/:id/pull",async({params:r,res:s})=>{let o=R(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=R(n,r.id),a=po(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=R(n,r.id),a=Un(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=R(n,r.id),a=bt(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=R(n,r.id),a=bt(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=R(n,r.id),a=Un(s,"count",{min:1,fallback:1});if(!await st(i.path,`HEAD~${a}`))throw new g(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=R(n,r.id),a=bt(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=R(n,r.id),a=bt(s,"hash");await W(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 Dt(o.path))throw new g(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=R(n,r.id);if(await Dt(o.path)!=="rebase")throw new g(409,"No rebase in progress to continue");await W(o,s,()=>o.manager.remote.rebaseContinue())})}import*as Ge from"node:fs";import*as he from"node:path";import*as Yn from"node:fs";var He=Yn.constants.O_RDONLY|(Yn.constants.O_NONBLOCK??0);async function Ht(t,e,n){let r=Buffer.alloc(n),s=0;while(s<n){let{bytesRead:o}=await t.read(r,s,n-s,e+s);if(o===0)break;s+=o}return s===n?r:r.subarray(0,s)}var Wt=8388608;var Ho=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 Be(t,e){return t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function Kn(t,e){return(t[e]<<8)+t[e+1]}function je(t,e){return t[e]+(t[e+1]<<8)}function Bo(t,e){return String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3])}function D(t){return{ok:!1,refusal:t}}function Gt(t){return D(t?"malformed":"header-not-found")}function Vn(t,e){if(t<1||e<1)return"malformed";if(t>8192||e>8192)return"too-many-pixels";if(t*e>16777216)return"too-many-pixels";return null}var Al=[137,80,78,71,13,10,26,10],Il=[255,216,255],Pl=Bt("GIF87a"),Dl=Bt("GIF89a"),Z=Bt("ftyp");function J(t){return{offset:8,bytes:Bt(t)}}var Ml=[{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 Tl(t){return Ml.some((e)=>jt(t,e.offset,e.bytes)&&(e.brand===void 0||jt(t,e.brand.offset,e.brand.bytes)))}var Fl={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},$l=26;function Ol(t,e,n){if(t.length<$l)return Gt(n);if(Be(t,8)!==13)return D("malformed");if(Bo(t,12)!=="IHDR")return D("malformed");let r=Be(t,16),s=Be(t,20),o=Vn(r,s);if(o)return D(o);let i=Fl[t[25]];if(!i||!i.includes(t[24]))return D("malformed");let a=Nl(t,n);if(a)return a;return{ok:!0,info:{format:"png",mime:"image/png",width:r,height:s,bytes:e}}}function Nl(t,e){let n=8;for(let r=0;r<256;r++){if(n+8>t.length)return Gt(e);let s=Be(t,n),o=Bo(t,n+4);if(o==="IDAT")return null;if(o==="acTL")return D("animation");if(o==="iCCP"&&s>65536)return D("malformed");let i=n+12+s;if(i<=n||!Number.isSafeInteger(i))return D("malformed");n=i}return D("malformed")}var Cl=218,Ll=226,Hl=new Set([219,238,192,193,194,196]);function Bl(t){return t>=224&&t<=239||Hl.has(t)}function jl(t){return t===1||t>=208&&t<=217}function Wl(t){return t>=192&&t<=207&&t!==196&&t!==200&&t!==204}var Gl=new Set([192,193,194]);function Ul(t,e,n){if(t.length<4)return Gt(n);if(!Bl(t[3]))return D("malformed");return zl(t,e,n)}function ql(t,e,n,r,s){if(!Gl.has(n))return D("malformed");if(e+9>t.length)return Gt(s);let o=Kn(t,e+5),i=Kn(t,e+7),a=Vn(i,o);if(a)return D(a);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:i,height:o,bytes:r}}}function Xl(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===Cl)return{kind:"malformed"};if(e+4>t.length)return{kind:"ran-out"};let r=Kn(t,e+2);if(r<2)return{kind:"malformed"};if(Wl(n))return{kind:"sof",marker:n};return{kind:"segment",marker:n,length:r}}function zl(t,e,n){let r=2,s=0;for(let o=0;o<1024;o++){let i=Xl(t,r);if(i.kind==="ran-out")return Gt(n);if(i.kind==="malformed")return D("malformed");if(i.kind==="sof")return ql(t,r,i.marker,e,n);if(i.kind==="skip"){r=i.next;continue}if(i.marker===Ll){if(s+=i.length-2,s>65536)return D("malformed")}r+=2+i.length}return D("malformed")}var Jl=59,Yl=44,Kl=33;function jo(t){return(t&128)===0?0:3*(1<<(t&7)+1)}function Vl(t,e,n){if(e>2097152)return D("too-large");if(!n)return D("header-not-found");if(t.length<13)return Gt(n);let r=je(t,6),s=je(t,8),o=Vn(r,s);if(o)return D(o);let i={pos:13+jo(t[10]),left:8192,pixels:0,overBudget:!1},a=Ql(t,i);if(a===null)return D("malformed");if(a<1)return D("malformed");if(a>256)return D("too-many-pixels");if(i.overBudget)return D("too-many-pixels");if(a*r*s>33554432)return D("too-many-pixels");let c={format:"gif",mime:"image/gif",width:r,height:s,bytes:e};if(a>1)c.frames=a;return{ok:!0,info:c}}function Ql(t,e){let n=0;while(e.left-- >0){if(e.pos>=t.length)return null;let r=t[e.pos];if(r===Jl)return n;let s=r===Yl;if(!(s?tu(t,e):Zl(t,e,r)))return null;if(s&&++n>256)return n;if(e.overBudget)return n}return null}function Zl(t,e,n){if(n!==Kl)return!1;return e.pos+=2,Wo(t,e)}function tu(t,e){if(e.pos+10>t.length)return!1;eu(e,je(t,e.pos+5),je(t,e.pos+7));let n=t[e.pos+9];return e.pos+=10+jo(n)+1,Wo(t,e)}function eu(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 Wo(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 Go(t){return jt(t,0,Pl)||jt(t,0,Dl)}function Ut(t,e,n){if(e>8388608)return D("too-large");if(jt(t,0,Al))return Ol(t,e,n);if(jt(t,0,Il))return Ul(t,e,n);if(Go(t))return Vl(t,e,n);if(Tl(t))return D("unsupported-format");return D("not-an-image")}function We(t,e){return Go(t)?Math.min(e,2097152):65536}function Qn(t){let e={files:new Map,directories:new Set};for(let n of t){e.files.set(n.path,{status:n.status,staged:n.staged});let r=n.path.split("/"),s="";for(let o=0;o<r.length-1;o++)s=s?`${s}/${r[o]}`:r[o],e.directories.add(s);e.directories.add("")}return e}var nu=1048576,Uo=5000;class de extends Error{constructor(t){super(`Not a regular file: ${t}`);this.name="NotRegularFileError"}}async function Xo(t,e,n,r){let s=n?.hideHidden??!0,o=n?.hideGitignored??!0,i=he.join(t,e),a=await Ge.promises.readdir(i,{withFileTypes:!0}),c=a.map((f)=>e?he.join(e,f.name):f.name),l=o?await _t(t,c):new Set,u=[];for(let f of a){if(s&&f.name.startsWith("."))continue;let h=e?he.join(e,f.name):f.name;if(o&&l.has(h))continue;let 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 m=r.files.get(h);if(m)d.gitStatus=m.status,d.staged=m.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 ru=16;async function su(t,e){let n=await Ht(t,0,Math.min(ru,e)),r=Ut(n,e,n.length>=e);if(!r.ok&&r.refusal==="too-large")return{head:n,result:r};let s=Math.min(We(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 ou(t,e){return t.ok?{image:t.info,refusal:null,version:e}:{image:null,refusal:t.refusal,version:e}}function qo(t,e){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:t,totalLines:0,media:e}}function Zn(t,e){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:t,totalLines:0,media:e}}function iu(t,e){let n=t.toString("utf-8"),r=n.split(`
|
|
44
|
-
`),s=!1;if(r.length>
|
|
45
|
-
`),s=!0;return{content:n,binary:!1,truncated:s,tooLarge:!1,size:e,totalLines:r.length}}async function
|
|
46
|
-
`))throw new qt("Query cannot span lines — this searches for literal text");try{return Qo(await be(t,du(e),uu))}catch(n){let r=n;if(r.code===1)return Vo;if(r.killed===!0||r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...r.stdout?Qo(r.stdout):Vo,incomplete:!0};throw n}}function ti(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 Zo(i.path,a);S(o,200,c)}catch(c){if(c instanceof qe)throw new g(400,`Query must be at least ${Ue} characters`,{cause:c});if(c instanceof qt)throw new g(400,c.message,{cause:c});throw c}})}import{Worker as pu}from"node:worker_threads";var mu=1000,gu=64,wu={status:"unavailable",reason:"deadline"},pe={status:"unavailable",reason:"error"};function yu(){let t=import.meta.url;return t.endsWith(".ts")?new URL("./symbolWorker.ts",t):new URL("./symbolWorker.js",t)}function ei(t){let e=t.timeoutMs??mu,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>gu){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 pu(yu(),{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){k("Cannot start the symbol worker",b,{path:h}),d(pe);return}let m=r,y=++s,v=!1,A=(b,ct)=>{if(v)return;if(v=!0,clearTimeout(x),m.off("message",I),m.off("error",P),m.off("exit",w),ct)l();d(b)},I=(b)=>{if(b.seq!==y)return;A(b.outcome,!1)},P=(b)=>{k("Symbol worker failed; discarding it",b,{path:h}),A(pe,!0)},w=(b)=>{k(`Symbol worker exited with code ${b}; discarding it`,void 0,{path:h}),A(pe,!0)},x=setTimeout(()=>{k(`Symbol extraction passed its ${e}ms deadline; discarding the worker`,void 0,{path:h}),A(wu,!0)},e);x.unref?.(),m.on("message",I),m.on("error",P),m.on("exit",w);let _={seq:y,relPath:h,content:p};try{m.postMessage(_)}catch(b){k("Cannot send a file to the symbol worker; discarding it",b,{path:h}),A(pe,!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 pe;let d=`${h}\x00${p}`,m=a.get(d);if(m!==void 0)return c(d,m),m;let y=o.then(()=>f(h,p));o=y.catch(()=>{return});let v=await y;return c(d,v),v},async dispose(){i=!0;let h=r;if(r=null,a.clear(),h!==null)await h.terminate()}}}import{spawn as bu}from"node:child_process";import*as ri from"node:fs";import*as si from"node:path";class Xt extends Error{constructor(t){super(`Not a regular blob: ${t}`);this.name="NotRegularBlobError"}}class zt extends Error{size;constructor(t,e){super(`Blob too large: ${t} (${e} bytes)`);this.name="BlobTooLargeError",this.size=e}}class xt extends Error{constructor(t){super(`Unsafe blob path: ${t}`);this.name="UnsafeBlobPathError"}}var Xe=65536,oi=/^[0-9a-f]{40}([0-9a-f]{24})?$/,Su=new Set(["100644","100755"]);function Eu(t){if(t==="")throw new xt("empty");if(t.includes("\x00"))throw new xt("contains NUL");if(t.startsWith("-"))throw new xt('starts with "-"');if(t.startsWith(":"))throw new xt('starts with ":"')}function ze(t,e,n){return be(t,[...ee,...e],n)}function ii(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 ai(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 xu=1;async function vu(t){let e;try{e=(await ze(t,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],Xe)).toString("utf8").trim()}catch(n){if(n?.code===xu)return null;throw n}return oi.test(e)?e:null}async function ku(t,e){let n=await vu(t);if(n===null)return null;let r=await ze(t,["ls-tree","-z","--full-tree","-l",n,"--",e],Xe),s=ai(ii(r),e);if(s===null||s.length!==4)return null;return{mode:s[0],oid:s[2],sizeText:s[3]}}async function Ru(t,e){let n=await ze(t,["ls-files","--stage","-z","--",e],Xe),r=ai(ii(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 ci(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 _u(t,e,n){let r=await ze(t,["cat-file","-s",e],Xe);return ci(r.toString("utf8").trim(),n)}var ni=Buffer.alloc(0);function li(t,e){let n=ni,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=ni,r=!1}}}function Au(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 m=Buffer.concat(r,s);r.length=0,r.push(m)}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 m=l;if(l=null,clearTimeout(m.timer),n?.stdout?.pause(),a!==null)m.reject(a);else m.resolve(f().subarray(0,Math.min(m.want,s)))}function p(m){a??=m,h()}function d(){let m=bu("git",[...ee,"cat-file","blob",e],{cwd:t,env:ut(),stdio:["ignore","pipe","ignore"],windowsHide:!0});n=m,m.stdout?.on("data",(y)=>{if(c)return;r.push(y),s+=y.length,h()}),m.stdout?.on("end",()=>{o=!0,h()}),m.stdout?.on("error",p),m.on("error",p),m.on("close",(y,v)=>{i={code:y,signal:v},h()})}return{read(m){if(a!==null)return Promise.reject(a);if(c)return Promise.reject(Error(`read after close for ${e}`));if(m<=s||u())return Promise.resolve(f().subarray(0,Math.min(m,s)));if(l!==null)return Promise.reject(Error(`concurrent read of ${e}`));return new Promise((y,v)=>{let A=setTimeout(()=>{n?.kill("SIGKILL"),p(Error(`git cat-file blob timed out for ${e}`))},cn);if(l={want:m,resolve:y,reject:v,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 Iu(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Pu(t,e,n){let r=si.join(t,e),s;try{s=await ri.promises.open(r,He)}catch(o){if(Iu(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=li(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 Du(t,e,n,r){let s=e==="head"?await ku(t,n):await Ru(t,n);if(s===null)return null;if(!Su.has(s.mode))throw new Xt(n);if(!oi.test(s.oid))throw Error(`git reported a malformed object id for ${n}`);let o=s.oid,i=s.sizeText===null?await _u(t,o,n):ci(s.sizeText,n);if(i>r)throw new zt(n,i);let a=Au(t,o),c=li(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 ui(t,e,n,r){if(Eu(n),e==="worktree")return Pu(t,n,r);return Du(t,e,n,r)}var Mu=["worktree","index","head"],Tu=16,Fu=Ho,$u=Wt,Ou=["too-large","too-many-pixels"];function Nu(t){let e=t.get("side");if(e===null||!Mu.includes(e))throw new g(400,'Invalid "side" (expected worktree, index or head)');return e}function pi(t){if(t instanceof Xt)throw new g(400,t.message,{cause:t});if(t instanceof xt)throw new g(400,t.message,{cause:t});if(t instanceof zt)throw new g(413,t.message,{cause:t});throw t}async function fi(t,e){let n=await t.read(e);return{bytes:n,sniff:Ut(n,t.size,n.length>=t.size)}}async function Cu(t,e){let{size:n}=t,r=await t.read(Tu),s=Ut(r,n,r.length>=n);if(!s.ok&&s.refusal==="too-large")return{bytes:r,sniff:s};let o=Math.min(We(r,n),n),i=await fi(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 fi(t,n)}async function mi(t,e,n,r){let s=await ui(t,e,n,Wt);if(s===null)return null;try{let{bytes:o,sniff:i}=await Cu(s,r);return{bytes:o,size:s.size,oid:s.oid,version:s.version,sniff:i}}finally{await s.close()}}function Lu(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 Hu(t){let e=Ou.includes(t)?413:415;return new g(e,`Image not served: ${t}`)}function Bu(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 hi(t,e){let n=St(t.path,e.path);await Et(t,n);let r;try{r=await mi(t.path,e.side,n,Fu)}catch(s){if(s instanceof zt)return ju(e,s.size,"too-large");if(s instanceof Xt)return null;pi(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 Wu(t,e){return e.writableEnded||e.destroyed===!0||t.destroyed===!0}async function di(t,e,n){let r=t.acquire();if(r===null)throw new g(503,"Too many image requests in flight");let s=await r;if(n.once("finish",s),n.once("close",s),e.once("close",s),Wu(e,n))return s(),!1;return!0}function gi(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=j(o,"staged"),u=St(c.path,Q(o));if(await Et(c,u),!await di(n,i,a))return;let f=await Lt(c.manager.workingTree,u,l),h=Bu(f,l),p={old:h.old===null?null:await hi(c,h.old),new:h.new===null?null:await hi(c,h.new)};S(a,200,p)}),t.get("/repos/:id/blob",async({params:s,query:o,req:i,res:a})=>{let c=R(r,s.id),l=Er(i);if(l)throw new g(l.status,l.message);let u=Nu(o),f=St(c.path,Q(o));if(await Et(c,f),!await di(n,i,a))return;let h;try{h=await mi(c.path,u,f,$u)}catch(d){pi(d)}if(h===null)throw new g(404,`No such blob on side ${u}: ${f}`);if(!h.sniff.ok)throw Hu(h.sniff.refusal);let p=Lu(u,h.sniff.info.mime,h.oid);dr(a,200,h.bytes,p)})}function wi(t,e){let{registry:n,sse:r,daemonEvents:s,follow:o}=e;t.get("/events",({req:i,res:a,query:c})=>{let l=n.listRepos().map((f)=>({id:f.id,path:f.path}));s.subscribe(i,a,l);let u=c.get("repo");if(!u)return;r.attach(u,n.getRepo(u)?.manager??null,i,a)}),t.get("/follow",({res:i})=>{S(i,200,o?o.state:Ys)})}import*as nr from"node:os";import*as Jt from"node:path";function yi(t,e){let{settings:n,discovery:r,daemonEvents:s}=e,o=()=>({...n.settings,persisted:n.persisted});t.get("/settings",({res:i})=>{S(i,200,o())}),t.put("/settings",async({body:i,res:a})=>{let c=ho(i,"watchRoots"),l;try{l=Vs(c)}catch(f){throw new g(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 g(500,`Could not save settings: ${h}`,{cause:f})}await r.setRoots(l);let u=o();s.broadcast("settings-change",u),S(a,200,u)}),t.get("/discovered",({res:i})=>{S(i,200,r.state)}),t.get("/browse",async({query:i,res:a})=>{let c=i.get("path"),l=c?Y(c):nr.homedir();if(!Jt.isAbsolute(l))throw new g(400,`Path must be absolute: ${c}`);let u=Jt.resolve(l),f;try{f=await Zs(u)}catch(p){throw new g(404,`Cannot read directory: ${u}`,{cause:p})}let h=Jt.dirname(u);S(a,200,{path:u,parent:h===u?null:h,home:nr.homedir(),entries:f})}),t.post("/discovered/rescan",async({res:i})=>{S(i,200,await r.rescan())})}function rr(t=4,e=64){let n=0,r=[];function s(){let o=!1;return()=>{if(o)return;o=!0;let i=r.shift();if(i)i(s());else n--}}return{acquire(){if(n<t)return n++,Promise.resolve(s());if(r.length>=e)return null;return new Promise((o)=>{r.push(o)})},get active(){return n},get queued(){return r.length}}}function Gu(t){if(!vt.existsSync(t))return Promise.resolve(!1);return new Promise((e)=>{try{let n=Si.connect(t);n.once("connect",()=>{n.destroy(),e(!0)}),n.once("error",()=>{n.destroy(),e(!1)})}catch{e(!1)}})}function Ei(t={}){let e=new Tn,n=new Fn,r=new Dn({onOpened:(w)=>n.broadcast("repo-opened",{id:w.id,path:w.path}),onClosed:(w)=>{e.closeRepo(w),n.broadcast("repo-closed",{id:w})}}),s=t.followFile?new On(r,n,t.followFile):null,o=io(t.updateCheck===!1?()=>Promise.resolve(null):t.fetchLatestVersion),i=new Cn(t.settingsFile??null),a=new Hn(n),c=new Map,l=rr(),u=t.symbols??null,f=u===null?null:{pool:ei(u),gate:rr(1,4),extensions:u.extensions};function h(w){let x=c.get(w);if(x)return x;let _=new sn,b={registry:r,sse:e,daemonEvents:n,follow:s,settings:i,discovery:a,apiMode:w,version:o,symbols:f,httpPort:v};if(co(_,b),lo(_,b),Eo(_,b),ko(_,b),No(_,b),Co(_,b),w==="full")Lo(_,b);return Jo(_,b),ti(_,b),gi(_,b,l),wi(_,b),yi(_,b),c.set(w,_),_}let p=(w)=>t.apiMode??(w==="tcp"?"web":"full");s?.start(),a.setRoots(i.load().watchRoots);let d=t.webRoot?gr(t.webRoot):void 0,m=new Set,y=[];function v(){for(let w of y){let x=w.server.address();if(x!==null&&typeof x==="object")return x.port}return null}function A(w){let x=h(w),_=bi.createServer((b,ct)=>{for(let[tt,me]of Object.entries(xr))ct.setHeader(tt,me);if(br(_.address())){let tt=Sr(b);if(tt){S(ct,tt.status,{error:tt.message});return}}x.handle(b,ct,d).catch((tt)=>{T(`${b.method??"GET"} ${b.url??"/"} escaped the router`,tt),ct.end()})});return _.on("connection",(b)=>{m.add(b),b.on("close",()=>m.delete(b))}),_}async function I(w,x){let _=w==="unix"?x.socketPath??null:null;if(_){if(await Gu(_))throw Error(`diffstalkerd already running at ${_}`);vt.rmSync(_,{force:!0})}let b={server:A(p(w)),socketPath:_};y.push(b),await new Promise((ct,tt)=>{let me=(Mi)=>tt(Mi);b.server.once("error",me);let Ye=()=>{if(b.server.removeListener("error",me),_)vt.chmodSync(_,384);ct()};if(w==="fd")b.server.listen({fd:x.fd},Ye);else if(_)process.umask(63),b.server.listen(_,Ye);else b.server.listen(x.port,"127.0.0.1",Ye)})}function P(w){return new Promise((x,_)=>{w.server.close((b)=>{if(w.socketPath)vt.rmSync(w.socketPath,{force:!0});if(b&&b.code!=="ERR_SERVER_NOT_RUNNING")_(b);else x()})})}return{address(){return y[0]?.server.address()??null},addresses(){return y.map((w)=>w.server.address()).filter((w)=>w!==null)},getRepo(w){return r.getRepo(w)},async openRepo(w){let{handle:x}=await $e(r,w);return{id:x.id,path:x.path}},async listen(w){let x=[];if(w.fd!==void 0)x.push("fd");if(w.socketPath)x.push("unix");if(w.port!==void 0)x.push("tcp");if(x.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let _ of x)await I(_,w)},close(){s?.dispose(),a.dispose(),e.destroy(),n.destroy(),r.disposeAll();for(let x of m)x.destroy();let w=f?.pool.dispose()??Promise.resolve();return Promise.all([w,...y.splice(0).map(P)]).then(()=>{})}}}import*as sr from"node:fs";import*as Yt from"node:path";import*as Ai from"node:crypto";import{createRequire as qu}from"node:module";var xi=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 vi(){return[...xi.keys()]}function Uu(t){let e=t.slice(t.lastIndexOf("/")+1),n=e.lastIndexOf(".");if(n<=0)return"";return e.slice(n).toLowerCase()}function ki(t){return xi.get(Uu(t))??null}var Xu="diffstalkerd-grammars";function zu(t){return Ai.createHash("sha256").update(t).digest("hex")}function Ju(t){try{let e=JSON.parse(sr.readFileSync(Yt.join(t,"checksums.json"),"utf8"));if(typeof e.webTreeSitterVersion!=="string"||typeof e.files!=="object")return null;return e}catch{return null}}var Ri="0.26.11";function Yu(t,e,n){for(let[r,s]of Object.entries(e.files)){let o;try{o=sr.readFileSync(Yt.join(t,r))}catch{return n(`grammars: missing ${r}`),!1}if(zu(o)!==s)return n(`grammars: checksum mismatch for ${r}`),!1}return!0}function Ku(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 _i(t,e=()=>{}){let n=Ju(t);if(n===null)return e(`grammars: no readable checksums.json in ${t}`),null;if(n.webTreeSitterVersion!==Ri)return e(`grammars: built for web-tree-sitter ${n.webTreeSitterVersion}, this daemon bundles ${Ri} — symbols disabled`),null;if(!Yu(t,n,e))return null;let r=Ku(n),s=vi().filter((o)=>{let i=ki(`x${o}`);return i!==null&&r.has(i.grammar)});if(s.length===0)return e("grammars: no usable grammar found"),null;return{grammarDir:t,queryDir:Yt.join(t,"queries"),extensions:s}}function Ii(t,e=()=>{}){if(t!==null)return _i(t,e);try{let r=qu(import.meta.url).resolve(`${Xu}/checksums.json`);return _i(Yt.dirname(r),e)}catch{return null}}var Di="diffstalkerd.sock";function Qu(t){return t===void 0?Di:`${t}.sock`}var Zu=3,Pi=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
|
|
37
|
+
`)},Ks),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 $c}from"chokidar";import{EventEmitter as Oc}from"node:events";class On extends Oc{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=Y(t);return Oe.isAbsolute(e)?e:Oe.resolve(e)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let t=wt.readFileSync(this.targetFile,"utf-8"),e=tn(t);if(e&&e!==this.lastReadPath){let n=this.processContent(e);this.lastReadPath=n,this.updateState({path:n,rawContent:e})}}catch(t){if(t.code==="ENOENT")return;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=tn(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=$c(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 Qs={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class Nn{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 On(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)Tn(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 Zs(){return{watchRoots:[]}}var Cn=16;function Nc(t){let e=t.trim();if(!e)throw Error("Watch directory cannot be empty");let n=Y(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 to(t){if(t.length>Cn)throw Error(`Too many watch directories (max ${Cn})`);let e=new Set,n=[];for(let r of t){let s=Nc(r);if(e.has(s))continue;e.add(s),n.push(s)}return n}function Cc(t){let e=Zs();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,Cn);return e}class Ln{file;current=Zs();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=Cc(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)}
|
|
38
|
+
`,{mode:384}),U.renameSync(e,this.file)}catch(n){throw U.rmSync(e,{force:!0}),n}return this.current}}import*as so from"node:path";import{watch as zc}from"chokidar";import*as z from"node:fs/promises";import*as O from"node:path";var Lc=2,Hc=500,Bc=new Set(["node_modules","vendor","target","dist","build","venv","__pycache__"]);async function eo(t){try{return await z.stat(O.join(t,".git")),!0}catch{return!1}}async function jc(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 Wc(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 Gc(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 Uc(t){let e=await jc(t);if(e===null)return null;let[n,r]=await Promise.all([Wc(e),Gc(e)]);return{path:t,name:O.basename(t),branch:n,lastActivity:r}}function qc(t){if(!t.isDirectory())return!1;if(t.name.startsWith("."))return!1;return!Bc.has(t.name)}async function no(t){let e=await Hn(t);return Promise.all(e.map(async(n)=>({name:O.basename(n),path:n,isRepo:await eo(n)})))}async function Hn(t){return(await z.readdir(t,{withFileTypes:!0})).filter(qc).map((n)=>O.join(t,n.name)).sort()}async function Xc(t,e,n){let r=[],s=[];for(let o of t){if(r.length>=n)return{repos:r,next:s,capped:!0};if(await eo(o)){r.push(o);continue}if(!e)continue;try{s.push(...await Hn(o))}catch{}}return{repos:r,next:s,capped:!1}}async function ro(t,e={}){let n=e.depth??Lc,r=e.limit??Hc,s=await Hn(t),o=[],i=!1;for(let c=1;c<=n&&s.length>0&&!i;c++){let l=await Xc(s,c<n,r-o.length);o.push(...l.repos),i=l.capped,s=l.next.sort()}return{repos:(await Promise.all(o.map(Uc))).filter((c)=>c!==null),capped:i}}var Jc=300;function Yc(t){let e=so.basename(t);return e.startsWith(".")&&e!=="."||e==="node_modules"}class Bn{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 ro(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=zc(t,{persistent:!0,ignoreInitial:!0,depth:1,ignored:Yc});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())},Jc),e.timer.unref?.()}broadcast(){if(this.disposed)return;this.hub.broadcast("discovery-change",this.state)}}import*as co from"node:fs";import{execFile as Kc}from"node:child_process";import*as ft from"node:fs";import*as rt from"node:path";import{fileURLToPath as Vc}from"node:url";var oo={method:"unknown",package:null,command:null},le="diffstalkerd",Qc=3000,Zc=["paru","yay"],tl=[{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 el(t,e){let n=t.split(rt.sep).join("/").replace(/\/+$/,"");for(let s of tl){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(Zc);return{method:"pacman",package:r,command:s?`${s} -S ${r}`:`sudo pacman -Syu ${r}`}}return oo}var nl={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)=>{Kc("pacman",["-Qoq","--",t],{timeout:Qc},(n,r)=>{if(n)return e(null);let s=r.trim().split(`
|
|
39
|
+
`)[0]?.trim();e(s?s:null)})})},writable(t){try{return ft.accessSync(t,ft.constants.W_OK),!0}catch{return!1}}};function rl(){let t=rt.dirname(Vc(new URL("../package.json",import.meta.url)));try{return ft.realpathSync(t)}catch{return t}}function io(t=rl(),e=nl){let n=null;return{info(){return n??=el(t,e).catch((r)=>(v("Install detection failed",r,{dir:t}),oo)),n}}}var sl="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",ol=21600000,il=300000,al=5000;function jn(){try{let t=co.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 cl(){let t=await fetch(sl,{headers:{accept:"application/json"},signal:AbortSignal.timeout(al)});if(!t.ok)return null;let e=await t.json();return typeof e.latest==="string"?e.latest:null}function ao(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());if(!e)return null;return[Number(e[1]),Number(e[2]),Number(e[3])]}function ll(t,e){if(t===null||e===null)return"unknown";let n=ao(t),r=ao(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 lo(t=cl,e=jn(),n=io()){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?il:ol;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:ll(e,i),install:a}}}}import*as uo from"node:os";function fo(t,e){t.get("/health",({res:n})=>{S(n,200,{ok:!0,ready:!0,home:uo.homedir(),http:{port:e.httpPort()},symbols:{extensions:e.symbols?.extensions??[]}})})}function ho(t,e){t.get("/version",async({res:n})=>{S(n,200,await e.version.state())})}import*as vo 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 mo(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 mo(q(t,e),e)}function Un(t,e){let n=t.get(e);return n===null?null:mo(n,e)}function go(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 wo(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 qn(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 yo(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?ms:void 0}function bo(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 po(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=po(r,e,n);if(!s)await t.refresh(),r=await st(t),s=po(r,e,n);if(!s)throw new m(404,`File not in status: ${e}`);return s}function Gn(t,e){return t===e||t.startsWith(e+N.sep)}function Xn(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(Xn))throw new m(400,`Path addresses the git directory: ${e}`);return r}async function So(t){try{return await Nt.promises.realpath(t)}catch{return null}}var Wn=new WeakMap;async function ul(t){let e=Wn.get(t);if(!e)e=(async()=>{let n=await E(t.path).raw(["rev-parse","--absolute-git-dir"]);return await Nt.promises.realpath(n.trim())})(),Wn.set(t,e),e.catch(()=>Wn.delete(t));try{return await e}catch(n){throw new m(500,"Cannot resolve the git directory for this repository",{cause:n})}}async function St(t,e){let n=await Nt.promises.realpath(N.resolve(t.path)),r=await So(N.join(t.path,e));if(r===null)return;if(!Gn(r,n))throw new m(400,`Path escapes repository root: ${e}`);if(Gn(r,await ul(t)))throw new m(400,`Path addresses the git directory: ${e}`)}async function Eo(t,e){let n=await Nt.promises.realpath(N.resolve(t)),r=[];for(let s of e){let o=await So(N.join(t,s.path));if(o===null||Gn(o,n))r.push(s)}return r}function Ne(t){return t?.code??null}async function zn(t){let e;try{e=await Nt.promises.stat(t)}catch(n){let r=Ne(n);if(r==="ENOENT"||r==="ENOTDIR")return null;throw n}if(e.isDirectory())return"a directory";if(e.isFile())return"a file";if(e.isFIFO())return"a FIFO";if(e.isSocket())return"a socket";return"a device"}function fl(t){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test(t)?409:500}function xo(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 xo(fl(r),r);await t.refresh(),S(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 dl(t){return hl.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 xo(dl(o.error),o.error);S(e,200,{state:at(i.state),result:o.lastResult})}function pl(t){if(t.reason==="not-a-repo"&&!vo.existsSync(t.requested))return new m(404,`No such directory: ${t.requested}`,{cause:t});return new m(400,t.message,{cause:t})}function ko(t,e){let{registry:n}=e;t.get("/repos",({res:r})=>{let s=n.listRepos().map((o)=>({id:o.id,path:o.path,branch:o.manager.workingTree.state.status?.branch.current??null}));S(r,200,s)}),t.post("/repos",async({body:r,res:s})=>{let o=q(r,"path"),i;try{i=await $e(n,o)}catch(a){if(a instanceof Fe)throw pl(a);throw a}S(s,i.created?201:200,{id:i.handle.id,path:i.handle.path})}),t.get("/resolve",async({query:r,res:s})=>{let o=Q(r),i=await _e(o,{mustExist:!0});if(!i.ok&&i.reason==="not-absolute")throw new m(400,`Repo path must be absolute: ${i.requested}`);S(s,200,{openable:i.ok,root:i.ok?i.root:null})}),t.get("/repos/:id/worktrees",async({params:r,res:s})=>{let o=k(n,r.id);S(s,200,await xn(o.path))}),t.get("/worktrees",async({query:r,res:s})=>{S(s,200,await xn(Q(r)))}),t.delete("/repos/:id",({params:r,res:s})=>{Ct(n,r.id),n.closeRepo(r.id),S(s,200,{})})}function Ro(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 _o(t){return t.trim()}async function ml(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 Ao(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),S(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 p=(await st(a.manager.workingTree)).files.some((g)=>g.path===c&&g.status==="untracked");if(p&&l)throw new m(400,`staged=true is meaningless for untracked file: ${c} (untracked files have no staged diff)`);h=u!==void 0&&!p,f=p?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);S(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")gl(t,e)}function gl(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=yo(s,"amend"),l=i.manager.workingTree,u=await ml(l),f=Ro(a,u,c);if(!f.valid)throw new m(400,f.error??"Invalid commit");await ot(l,o,()=>l.commit(_o(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 wl=1000,Ce="refs/heads/",Io="refs/remotes/";async function Do(t,e,n){let r=["for-each-ref","--format=%(objectname) %(refname) %(symref)",`--no-merged=${e}`];if(n!==void 0)r.push(`--contains=${n}`);r.push("refs/heads","refs/remotes");let s=await t.raw(r),o=[];for(let i of s.split(`
|
|
40
|
+
`)){if(!i)continue;let[a,c,l]=i.split(" ");if(l)continue;if(c.startsWith(Ce))o.push({tip:a,name:c.slice(Ce.length),local:!0});else if(c.startsWith(Io))o.push({tip:a,name:c.slice(Io.length),local:!1})}return o}function yl(t){return new Map(t.filter((e)=>e.local).map((e)=>[e.name,e.tip]))}function Mo(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 bl(t){return new Set(t.filter((e)=>!e.local).map((e)=>e.name.slice(e.name.indexOf("/")+1)))}function To(t,e){return!t.local||e.has(t.name)}async function Fo(t,e,n){return(await t.raw(["rev-list","--first-parent",`--max-count=${wl}`,"--end-of-options",`${e}..${n}`])).split(`
|
|
41
|
+
`).filter(Boolean).reverse()}async function Sl(t){let e=await t.raw(["rev-parse","HEAD","--symbolic-full-name","HEAD"]),[n,r]=e.split(`
|
|
42
|
+
`),s=r.startsWith(Ce)?r.slice(Ce.length):null;return{tip:n,name:s??"HEAD",branch:s}}async function Po(t,e){if(e.length<2)return e;return(await t.raw(["merge-base","--independent","--end-of-options",...e])).split(`
|
|
43
|
+
`).filter(Boolean)}function El(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 $o(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=El(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 xl(t,e,n,r,s,o){let i=Mo(await Do(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 Po(t,a);if(c.length>1){let u=[...new Set(i.filter((f)=>To(f,o)).map((f)=>f.tip))];if(u.length>0)c=await Po(t,u)}if(c.length!==1)return{layers:[],forked:!0};let l=await Fo(t,n,c[0]);return{layers:$o(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 Oo(t,e){let n=E(t),r=await Sl(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([Do(n,e),Fo(n,s,r.tip)]),a=yl(o),c=bl(o),l=new Map,u=new Set;for(let d of Mo(o,a)){let p=l.get(d.tip);if(p)p.push(d);else l.set(d.tip,[d]);if(To(d,c))u.add(d.tip)}let f=$o(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 xl(n,e,r.tip,a,l,c);return{trunk:e,layers:vl([...f,...h.layers],u),forkedAbove:h.forked}}function Jn(t){if(!/^[0-9a-f]{4,40}$/i.test(t))throw new m(400,`Invalid commit hash: ${t}`);return t}async function No(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 kl(t){let e=await yn(t);if(e&&await nt(t,e))return e;if(Pt(t)){let n=await ae(t);if(n&&await nt(t,n))return n}throw new m(422,"No usable base branch")}async function Le(t,e){let n=Un(e,"base");if(n===null)return kl(t);if(!await nt(t,n))throw new m(400,`Unknown base ref: ${n}`);return n}async function Kn(t,e){let n=Un(e,"head");if(n===null)return;if(!await nt(t,n))throw new m(400,`Unknown head ref: ${n}`);return n}function Co(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 Rl=new Set(["staged","unstaged","both","untracked"]);function _l(t){let e=t.get("uncommitted");if(e===null)return null;if(!Rl.has(e))throw new m(400,`Invalid "uncommitted" (expected staged, unstaged, both or untracked): ${e}`);return e}function Al(t){return{staged:j(t,"staged",!1),unstaged:j(t,"unstaged",!1),untracked:j(t,"untracked",!1)}}function Il(t){if(t.unstaged&&!t.staged)throw new m(400,"unstaged needs staged too (unstaged edits sit on top of staged ones)")}function Lo(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=bo(s,"count",100,5000);S(o,200,await Vr(i.path,a))}),t.get("/repos/:id/commits/:hash",async({params:r,res:s})=>{let o=k(n,r.id),i=Jn(r.hash),a=await Qr(o.path,i);if(a===null)throw new m(404,`Unknown commit: ${i}`);S(s,200,a)}),t.get("/repos/:id/commits/:hash/diff",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=Jn(r.hash);await No(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 vs(i.path,a);S(o,200,u)}),t.get("/repos/:id/commits/:hash/files",async({params:r,res:s})=>{let o=k(n,r.id),i=Jn(r.hash);await No(o.path,i),S(s,200,await xs(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=_l(s);if(Co(s,l!==null),l==="untracked"){S(o,200,await gt(i.path,a));return}let u=await Le(i.path,s),f=l===null?{kind:"compare",base:u,head:await Kn(i.path,s)}:{kind:"compare-uncommitted",mergeBase:await Yn(()=>Es(i.path,u)),tip:l==="staged"?"index":"worktree"};S(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);S(s,200,{message:await Ur(o.path)})}),t.get("/repos/:id/branches",async({params:r,res:s})=>{let o=k(n,r.id);S(s,200,await es(o.path))}),t.get("/repos/:id/base-branches",async({params:r,res:s})=>{let o=k(n,r.id);S(s,200,await wn(o.path))}),t.get("/repos/:id/compare/base",async({params:r,res:s})=>{let o=k(n,r.id);S(s,200,{base:await yn(o.path)})}),e.apiMode==="full")t.put("/repos/:id/compare/base",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=yt(s,"branch");if(!await nt(i.path,a))throw new m(400,`Not a valid base ref: ${a}`);fs(i.path,a),S(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 Le(i.path,s),c=await Kn(i.path,s),l=await Yn(()=>Ss(i.path,a,c));S(o,200,{baseBranch:a,commits:l})}),t.get("/repos/:id/compare/stack",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=await Le(i.path,s);S(o,200,await Oo(i.path,a))}),t.get("/repos/:id/compare",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=Al(s);Co(s,a.staged||a.unstaged||a.untracked),Il(a);let c=await Le(i.path,s),l=await Kn(i.path,s),u=await Yn(()=>ks(i.path,c,a,l));S(o,200,u)})}function Pl(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 Ho(t,e){let{registry:n}=e;t.get("/repos/:id/journal",({params:r,query:s,res:o})=>{let i=k(n,r.id),a=Pl(s);S(o,200,pr(i.manager.journal.journalStore,a))})}function Bo(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=wo(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=qn(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=qn(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 Ge from"node:fs";import*as fe from"node:path";import*as Vn from"node:fs";var He=Vn.constants.O_RDONLY|(Vn.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 jo=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 Be(t,e){return t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function Qn(t,e){return(t[e]<<8)+t[e+1]}function je(t,e){return t[e]+(t[e+1]<<8)}function Wo(t,e){return String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3])}function D(t){return{ok:!1,refusal:t}}function Gt(t){return D(t?"malformed":"header-not-found")}function Zn(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 Dl=[137,80,78,71,13,10,26,10],Ml=[255,216,255],Tl=Bt("GIF87a"),Fl=Bt("GIF89a"),Z=Bt("ftyp");function J(t){return{offset:8,bytes:Bt(t)}}var $l=[{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 Ol(t){return $l.some((e)=>jt(t,e.offset,e.bytes)&&(e.brand===void 0||jt(t,e.brand.offset,e.brand.bytes)))}var Nl={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},Cl=26;function Ll(t,e,n){if(t.length<Cl)return Gt(n);if(Be(t,8)!==13)return D("malformed");if(Wo(t,12)!=="IHDR")return D("malformed");let r=Be(t,16),s=Be(t,20),o=Zn(r,s);if(o)return D(o);let i=Nl[t[25]];if(!i||!i.includes(t[24]))return D("malformed");let a=Hl(t,n);if(a)return a;return{ok:!0,info:{format:"png",mime:"image/png",width:r,height:s,bytes:e}}}function Hl(t,e){let n=8;for(let r=0;r<256;r++){if(n+8>t.length)return Gt(e);let s=Be(t,n),o=Wo(t,n+4);if(o==="IDAT")return null;if(o==="acTL")return D("animation");if(o==="iCCP"&&s>65536)return D("malformed");let i=n+12+s;if(i<=n||!Number.isSafeInteger(i))return D("malformed");n=i}return D("malformed")}var Bl=218,jl=226,Wl=new Set([219,238,192,193,194,196]);function Gl(t){return t>=224&&t<=239||Wl.has(t)}function Ul(t){return t===1||t>=208&&t<=217}function ql(t){return t>=192&&t<=207&&t!==196&&t!==200&&t!==204}var Xl=new Set([192,193,194]);function zl(t,e,n){if(t.length<4)return Gt(n);if(!Gl(t[3]))return D("malformed");return Kl(t,e,n)}function Jl(t,e,n,r,s){if(!Xl.has(n))return D("malformed");if(e+9>t.length)return Gt(s);let o=Qn(t,e+5),i=Qn(t,e+7),a=Zn(i,o);if(a)return D(a);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:i,height:o,bytes:r}}}function Yl(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(Ul(n))return{kind:"skip",next:e+2};if(n===Bl)return{kind:"malformed"};if(e+4>t.length)return{kind:"ran-out"};let r=Qn(t,e+2);if(r<2)return{kind:"malformed"};if(ql(n))return{kind:"sof",marker:n};return{kind:"segment",marker:n,length:r}}function Kl(t,e,n){let r=2,s=0;for(let o=0;o<1024;o++){let i=Yl(t,r);if(i.kind==="ran-out")return Gt(n);if(i.kind==="malformed")return D("malformed");if(i.kind==="sof")return Jl(t,r,i.marker,e,n);if(i.kind==="skip"){r=i.next;continue}if(i.marker===jl){if(s+=i.length-2,s>65536)return D("malformed")}r+=2+i.length}return D("malformed")}var Vl=59,Ql=44,Zl=33;function Go(t){return(t&128)===0?0:3*(1<<(t&7)+1)}function tu(t,e,n){if(e>2097152)return D("too-large");if(!n)return D("header-not-found");if(t.length<13)return Gt(n);let r=je(t,6),s=je(t,8),o=Zn(r,s);if(o)return D(o);let i={pos:13+Go(t[10]),left:8192,pixels:0,overBudget:!1},a=eu(t,i);if(a===null)return D("malformed");if(a<1)return D("malformed");if(a>256)return D("too-many-pixels");if(i.overBudget)return D("too-many-pixels");if(a*r*s>33554432)return D("too-many-pixels");let c={format:"gif",mime:"image/gif",width:r,height:s,bytes:e};if(a>1)c.frames=a;return{ok:!0,info:c}}function eu(t,e){let n=0;while(e.left-- >0){if(e.pos>=t.length)return null;let r=t[e.pos];if(r===Vl)return n;let s=r===Ql;if(!(s?ru(t,e):nu(t,e,r)))return null;if(s&&++n>256)return n;if(e.overBudget)return n}return null}function nu(t,e,n){if(n!==Zl)return!1;return e.pos+=2,Uo(t,e)}function ru(t,e){if(e.pos+10>t.length)return!1;su(e,je(t,e.pos+5),je(t,e.pos+7));let n=t[e.pos+9];return e.pos+=10+Go(n)+1,Uo(t,e)}function su(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 Uo(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 qo(t){return jt(t,0,Tl)||jt(t,0,Fl)}function Ut(t,e,n){if(e>8388608)return D("too-large");if(jt(t,0,Dl))return Ll(t,e,n);if(jt(t,0,Ml))return zl(t,e,n);if(qo(t))return tu(t,e,n);if(Ol(t))return D("unsupported-format");return D("not-an-image")}function We(t,e){return qo(t)?Math.min(e,2097152):65536}function tr(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 ou=1048576,Xo=5000;class he extends Error{constructor(t){super(`Not a regular file: ${t}`);this.name="NotRegularFileError"}}async function Jo(t,e,n,r){let s=n?.hideHidden??!0,o=n?.hideGitignored??!0,i=fe.join(t,e),a=await Ge.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 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 iu=16;async function au(t,e){let n=await Ht(t,0,Math.min(iu,e)),r=Ut(n,e,n.length>=e);if(!r.ok&&r.refusal==="too-large")return{head:n,result:r};let s=Math.min(We(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 cu(t,e){return t.ok?{image:t.info,refusal:null,version:e}:{image:null,refusal:t.refusal,version:e}}function zo(t,e){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:t,totalLines:0,media:e}}function er(t,e){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:t,totalLines:0,media:e}}function lu(t,e){let n=t.toString("utf-8"),r=n.split(`
|
|
44
|
+
`),s=!1;if(r.length>Xo)n=r.slice(0,Xo).join(`
|
|
45
|
+
`),s=!0;return{content:n,binary:!1,truncated:s,tooLarge:!1,size:e,totalLines:r.length}}async function uu(t,e){let n=await t.stat();if(!n.isFile())throw new he(e);let r=n.size;if(r>Wt)return er(r);let{head:s,result:o}=await au(t,r),i=cu(o,`${r}-${n.mtimeMs}`);if(o.ok)return zo(r,i);if(r>ou)return er(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)?zo(r,i):lu(a,r)}async function Yo(t,e){let n=fe.join(t,e),r=await Ge.promises.stat(n);if(!r.isFile())throw new he(e);if(r.size>Wt)return er(r.size);let s=await Ge.promises.open(n,He);try{return await uu(s,e)}finally{await s.close()}}import*as nr from"node:path";function Ko(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 St(c,h);let d=await st(c.manager.workingTree),p=tr(d.files),g;try{g=await Jo(c.path,h,{hideHidden:!u,hideGitignored:!f},p)}catch(y){let A=Ne(y);if(A==="ENOENT"||A==="ENOTDIR"){let I=await zn(nr.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)=>!Xn(y.name));S(a,200,await Eo(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 St(c,u);try{let f=await Yo(c.path,u);S(a,200,await s(f,u,j(i,"symbols",!1)))}catch(f){if(f instanceof he){let d=await zn(nr.join(c.path,u));throw new m(400,`Not a regular file (${d??"unknown"}): ${l}`,{cause:f})}let h=Ne(f);if(h==="ENOENT"||h==="ENOTDIR")throw new m(404,`No such file: ${l}`,{cause:f});throw f}}),t.get("/repos/:id/files",async({params:o,res:i})=>{let a=k(n,o.id);S(i,200,await ls(a.path))})}var Ue=3,fu=20,Vo=500,hu=500,du=4194304,Qo=400;class qe extends Error{constructor(){super(`Query must be at least ${Ue} characters`);this.name="GrepQueryTooShortError"}}class qt extends Error{constructor(t){super(t);this.name="GrepQueryInvalidError"}}var Zo={matches:[],capped:!1,incomplete:!1,binarySkipped:0};function pu(t){return t===t.toLowerCase()}function rr(t){return Buffer.from(t).toString("utf8")}function mu(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 ti(t,e=hu){let n=[],r=new Map,s=0,o=!1,i=0;while(i<t.length){let a=mu(t,i);if(a===null)break;if(i=a.next,a.contentBytes.includes(0)){s+=1;continue}let c=Number.parseInt(rr(a.lineBytes),10);if(!Number.isSafeInteger(c)||c<1)continue;if(n.length>=e){o=!0;break}let l=rr(a.pathBytes),u=r.get(l)??0;if(u>=fu){o=!0;continue}r.set(l,u+1);let f=rr(a.contentBytes),h=f.length>Qo;n.push({path:l,line:c,text:h?f.slice(0,Qo):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",...pu(t)?["-i"]:[],"-e",t,"--untracked","--","."]}async function ei(t,e){if(e.length<Ue)throw new qe;if(e.length>Vo)throw new qt(`Query must be at most ${Vo} characters`);if(e.includes("\x00"))throw new qt("Query cannot contain a NUL byte");if(e.includes(`
|
|
46
|
+
`))throw new qt("Query cannot span lines — this searches for literal text");try{return ti(await ye(t,gu(e),du))}catch(n){let r=n;if(r.code===1)return Zo;if(r.killed===!0||r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...r.stdout?ti(r.stdout):Zo,incomplete:!0};throw n}}function ni(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 ei(i.path,a);S(o,200,c)}catch(c){if(c instanceof qe)throw new m(400,`Query must be at least ${Ue} characters`,{cause:c});if(c instanceof qt)throw new m(400,c.message,{cause:c});throw c}})}import{Worker as wu}from"node:worker_threads";var yu=1000,bu=64,Su={status:"unavailable",reason:"deadline"},de={status:"unavailable",reason:"error"};function Eu(){let t=import.meta.url;return t.endsWith(".ts")?new URL("./symbolWorker.ts",t):new URL("./symbolWorker.js",t)}function ri(t){let e=t.timeoutMs??yu,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>bu){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 wu(Eu(),{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){v("Cannot start the symbol worker",b,{path:h}),p(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",P),g.off("exit",w),it)l();p(b)},I=(b)=>{if(b.seq!==R)return;A(b.outcome,!1)},P=(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(Su,!0)},e);x.unref?.(),g.on("message",I),g.on("error",P),g.on("exit",w);let _={seq:R,relPath:h,content:d};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 d=h.lastIndexOf(".");if(d<=h.lastIndexOf("/"))return!1;return n.has(h.slice(d).toLowerCase())},async extract(h,d){if(i)return de;let p=`${h}\x00${d}`,g=a.get(p);if(g!==void 0)return c(p,g),g;let R=o.then(()=>f(h,d));o=R.catch(()=>{return});let y=await R;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 xu}from"node:child_process";import*as oi from"node:fs";import*as ii 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 Et extends Error{constructor(t){super(`Unsafe blob path: ${t}`);this.name="UnsafeBlobPathError"}}var Xe=65536,ai=/^[0-9a-f]{40}([0-9a-f]{24})?$/,vu=new Set(["100644","100755"]);function ku(t){if(t==="")throw new Et("empty");if(t.includes("\x00"))throw new Et("contains NUL");if(t.startsWith("-"))throw new Et('starts with "-"');if(t.startsWith(":"))throw new Et('starts with ":"')}function ze(t,e,n){return ye(t,[...ee,...e],n)}function ci(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 li(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 Ru=1;async function _u(t){let e;try{e=(await ze(t,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],Xe)).toString("utf8").trim()}catch(n){if(n?.code===Ru)return null;throw n}return ai.test(e)?e:null}async function Au(t,e){let n=await _u(t);if(n===null)return null;let r=await ze(t,["ls-tree","-z","--full-tree","-l",n,"--",e],Xe),s=li(ci(r),e);if(s===null||s.length!==4)return null;return{mode:s[0],oid:s[2],sizeText:s[3]}}async function Iu(t,e){let n=await ze(t,["ls-files","--stage","-z","--",e],Xe),r=li(ci(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 ui(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 Pu(t,e,n){let r=await ze(t,["cat-file","-s",e],Xe);return ui(r.toString("utf8").trim(),n)}var si=Buffer.alloc(0);function fi(t,e){let n=si,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=si,r=!1}}}function Du(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=xu("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",d),g.on("error",d),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"),d(Error(`git cat-file blob timed out for ${e}`))},cn);if(l={want:g,resolve:R,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 Mu(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Tu(t,e,n){let r=ii.join(t,e),s;try{s=await oi.promises.open(r,He)}catch(o){if(Mu(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=fi(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 Fu(t,e,n,r){let s=e==="head"?await Au(t,n):await Iu(t,n);if(s===null)return null;if(!vu.has(s.mode))throw new Xt(n);if(!ai.test(s.oid))throw Error(`git reported a malformed object id for ${n}`);let o=s.oid,i=s.sizeText===null?await Pu(t,o,n):ui(s.sizeText,n);if(i>r)throw new zt(n,i);let a=Du(t,o),c=fi(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 hi(t,e,n,r){if(ku(n),e==="worktree")return Tu(t,n,r);return Fu(t,e,n,r)}var $u=["worktree","index","head"],Ou=16,Nu=jo,Cu=Wt,Lu=["too-large","too-many-pixels"];function Hu(t){let e=t.get("side");if(e===null||!$u.includes(e))throw new m(400,'Invalid "side" (expected worktree, index or head)');return e}function gi(t){if(t instanceof Xt)throw new m(400,t.message,{cause:t});if(t instanceof Et)throw new m(400,t.message,{cause:t});if(t instanceof zt)throw new m(413,t.message,{cause:t});throw t}async function di(t,e){let n=await t.read(e);return{bytes:n,sniff:Ut(n,t.size,n.length>=t.size)}}async function Bu(t,e){let{size:n}=t,r=await t.read(Ou),s=Ut(r,n,r.length>=n);if(!s.ok&&s.refusal==="too-large")return{bytes:r,sniff:s};let o=Math.min(We(r,n),n),i=await di(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 di(t,n)}async function wi(t,e,n,r){let s=await hi(t,e,n,Wt);if(s===null)return null;try{let{bytes:o,sniff:i}=await Bu(s,r);return{bytes:o,size:s.size,oid:s.oid,version:s.version,sniff:i}}finally{await s.close()}}function ju(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 Wu(t){let e=Lu.includes(t)?413:415;return new m(e,`Image not served: ${t}`)}function Gu(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 Uu(t,e,n){return{path:t.path,side:t.side,bytes:e,oid:null,image:null,refusal:n,version:""}}async function pi(t,e){let n=bt(t.path,e.path);await St(t,n);let r;try{r=await wi(t.path,e.side,n,Nu)}catch(s){if(s instanceof zt)return Uu(e,s.size,"too-large");if(s instanceof Xt)return null;gi(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 qu(t,e){return e.writableEnded||e.destroyed===!0||t.destroyed===!0}async function mi(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),qu(e,n))return s(),!1;return!0}function yi(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 St(c,u),!await mi(n,i,a))return;let f=await Lt(c.manager.workingTree,u,l),h=Gu(f,l),d={old:h.old===null?null:await pi(c,h.old),new:h.new===null?null:await pi(c,h.new)};S(a,200,d)}),t.get("/repos/:id/blob",async({params:s,query:o,req:i,res:a})=>{let c=k(r,s.id),l=vr(i);if(l)throw new m(l.status,l.message);let u=Hu(o),f=bt(c.path,Q(o));if(await St(c,f),!await mi(n,i,a))return;let h;try{h=await wi(c.path,u,f,Cu)}catch(p){gi(p)}if(h===null)throw new m(404,`No such blob on side ${u}: ${f}`);if(!h.sniff.ok)throw Wu(h.sniff.refusal);let d=ju(u,h.sniff.info.mime,h.oid);mr(a,200,h.bytes,d)})}function bi(t,e){let{registry:n,sse:r,daemonEvents:s,follow:o}=e;t.get("/events",({req:i,res:a,query:c})=>{let l=n.listRepos().map((f)=>({id:f.id,path:f.path}));s.subscribe(i,a,l);let u=c.get("repo");if(!u)return;r.attach(u,n.getRepo(u)?.manager??null,i,a)}),t.get("/follow",({res:i})=>{S(i,200,o?o.state:Qs)})}import*as sr from"node:os";import*as Jt from"node:path";function Si(t,e){let{settings:n,discovery:r,daemonEvents:s}=e,o=()=>({...n.settings,persisted:n.persisted});t.get("/settings",({res:i})=>{S(i,200,o())}),t.put("/settings",async({body:i,res:a})=>{let c=go(i,"watchRoots"),l;try{l=to(c)}catch(f){throw new m(400,f instanceof Error?f.message:String(f),{cause:f})}try{n.save({...n.settings,watchRoots:l})}catch(f){let h=f instanceof Error?f.message:String(f);throw new m(500,`Could not save settings: ${h}`,{cause:f})}await r.setRoots(l);let u=o();s.broadcast("settings-change",u),S(a,200,u)}),t.get("/discovered",({res:i})=>{S(i,200,r.state)}),t.get("/browse",async({query:i,res:a})=>{let c=i.get("path"),l=c?Y(c):sr.homedir();if(!Jt.isAbsolute(l))throw new m(400,`Path must be absolute: ${c}`);let u=Jt.resolve(l),f;try{f=await no(u)}catch(d){throw new m(404,`Cannot read directory: ${u}`,{cause:d})}let h=Jt.dirname(u);S(a,200,{path:u,parent:h===u?null:h,home:sr.homedir(),entries:f})}),t.post("/discovered/rescan",async({res:i})=>{S(i,200,await r.rescan())})}function or(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 Xu(t){if(!xt.existsSync(t))return Promise.resolve(!1);return new Promise((e)=>{try{let n=xi.connect(t);n.once("connect",()=>{n.destroy(),e(!0)}),n.once("error",()=>{n.destroy(),e(!1)})}catch{e(!1)}})}function vi(t={}){let e=new Fn,n=new $n,r=new Mn({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 Nn(r,n,t.followFile):null,o=lo(t.updateCheck===!1?()=>Promise.resolve(null):t.fetchLatestVersion),i=new Ln(t.settingsFile??null),a=new Bn(n),c=new Map,l=or(),u=t.symbols??null,f=u===null?null:{pool:ri(u),gate:or(1,4),extensions:u.extensions};function h(w){let x=c.get(w);if(x)return x;let _=new sn,b={registry:r,sse:e,daemonEvents:n,follow:s,settings:i,discovery:a,apiMode:w,version:o,symbols:f,httpPort:y};if(fo(_,b),ho(_,b),ko(_,b),Ao(_,b),Lo(_,b),Ho(_,b),w==="full")Bo(_,b);return Ko(_,b),ni(_,b),yi(_,b,l),bi(_,b),Si(_,b),c.set(w,_),_}let d=(w)=>t.apiMode??(w==="tcp"?"web":"full");s?.start(),a.setRoots(i.load().watchRoots);let p=t.webRoot?yr(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),_=Ei.createServer((b,it)=>{for(let[tt,pe]of Object.entries(kr))it.setHeader(tt,pe);if(Er(_.address())){let tt=xr(b);if(tt){S(it,tt.status,{error:tt.message});return}}x.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,x){let _=w==="unix"?x.socketPath??null:null;if(_){if(await Xu(_))throw Error(`diffstalkerd already running at ${_}`);xt.rmSync(_,{force:!0})}let b={server:A(d(w)),socketPath:_};R.push(b),await new Promise((it,tt)=>{let pe=(Fi)=>tt(Fi);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 P(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 $e(r,w);return{id:x.id,path:x.path}},async listen(w){let x=[];if(w.fd!==void 0)x.push("fd");if(w.socketPath)x.push("unix");if(w.port!==void 0)x.push("tcp");if(x.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let _ of x)await I(_,w)},close(){s?.dispose(),a.dispose(),e.destroy(),n.destroy(),r.disposeAll();for(let x of g)x.destroy();let w=f?.pool.dispose()??Promise.resolve();return Promise.all([w,...R.splice(0).map(P)]).then(()=>{})}}}import*as ir from"node:fs";import*as Yt from"node:path";import*as Pi from"node:crypto";import{createRequire as Ju}from"node:module";var ki=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 Ri(){return[...ki.keys()]}function zu(t){let e=t.slice(t.lastIndexOf("/")+1),n=e.lastIndexOf(".");if(n<=0)return"";return e.slice(n).toLowerCase()}function _i(t){return ki.get(zu(t))??null}var Yu="diffstalkerd-grammars";function Ku(t){return Pi.createHash("sha256").update(t).digest("hex")}function Vu(t){try{let e=JSON.parse(ir.readFileSync(Yt.join(t,"checksums.json"),"utf8"));if(typeof e.webTreeSitterVersion!=="string"||typeof e.files!=="object")return null;return e}catch{return null}}var Ai="0.26.11";function Qu(t,e,n){for(let[r,s]of Object.entries(e.files)){let o;try{o=ir.readFileSync(Yt.join(t,r))}catch{return n(`grammars: missing ${r}`),!1}if(Ku(o)!==s)return n(`grammars: checksum mismatch for ${r}`),!1}return!0}function Zu(t){let e=new Set;for(let n of Object.keys(t.files)){let r=/^tree-sitter-(.+)\.wasm$/.exec(n);if(r!==null&&t.files[`queries/${r[1]}.scm`]!==void 0)e.add(r[1])}return e}function Ii(t,e=()=>{}){let n=Vu(t);if(n===null)return e(`grammars: no readable checksums.json in ${t}`),null;if(n.webTreeSitterVersion!==Ai)return e(`grammars: built for web-tree-sitter ${n.webTreeSitterVersion}, this daemon bundles ${Ai} — symbols disabled`),null;if(!Qu(t,n,e))return null;let r=Zu(n),s=Ri().filter((o)=>{let i=_i(`x${o}`);return i!==null&&r.has(i.grammar)});if(s.length===0)return e("grammars: no usable grammar found"),null;return{grammarDir:t,queryDir:Yt.join(t,"queries"),extensions:s}}function Di(t,e=()=>{}){if(t!==null)return Ii(t,e);try{let r=Ju(import.meta.url).resolve(`${Yu}/checksums.json`);return Ii(Yt.dirname(r),e)}catch{return null}}var Ti="diffstalkerd.sock";function ef(t){return t===void 0?Ti:`${t}.sock`}var nf=3,Mi=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
|
|
47
47
|
|
|
48
48
|
Usage: diffstalkerd [options] [REPO_PATH...]
|
|
49
49
|
|
|
@@ -55,7 +55,7 @@ Arguments:
|
|
|
55
55
|
|
|
56
56
|
Options:
|
|
57
57
|
--socket PATH Bind a unix socket at PATH
|
|
58
|
-
(default: $XDG_RUNTIME_DIR/diffstalker/${
|
|
58
|
+
(default: $XDG_RUNTIME_DIR/diffstalker/${Ti})
|
|
59
59
|
--instance NAME Bind <NAME>.sock in the runtime dir, so several
|
|
60
60
|
daemons can run side by side (default: the shared
|
|
61
61
|
socket every client looks for first)
|
|
@@ -75,6 +75,6 @@ Options:
|
|
|
75
75
|
ignored follow target) to stderr
|
|
76
76
|
--version, -v Print the running version and exit
|
|
77
77
|
--help, -h Show this help
|
|
78
|
-
`;function Kt(t,e,n){let r=t[e];if(r===void 0||r.startsWith("--"))throw Error(`${n} requires a value`);return r}function
|
|
78
|
+
`;function Kt(t,e,n){let r=t[e];if(r===void 0||r.startsWith("--"))throw Error(`${n} requires a value`);return r}function rf(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 sf(t){let e={};for(let n=0;n<t.length;n++){let r=t[n];switch(r){case"--help":case"-h":return"help";case"--version":case"-v":return"version";case"--socket":e.socketPath=Kt(t,++n,"--socket");break;case"--instance":e.instance=Kt(t,++n,"--instance");break;case"--no-socket":e.noSocket=!0;break;case"--port":if(e.port=Number(Kt(t,++n,"--port")),!Number.isInteger(e.port)||e.port<0)throw Error("--port requires a non-negative integer");break;case"--follow-file":e.followFile=Kt(t,++n,"--follow-file");break;case"--no-follow":e.noFollow=!0;break;case"--web-root":e.webRoot=Kt(t,++n,"--web-root");break;case"--grammars":e.grammarsDir=Kt(t,++n,"--grammars");break;case"--no-update-check":e.noUpdateCheck=!0;break;case"--debug":e.debug=!0;break;default:rf(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 of(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function af(t){if(t.noSocket||t.socketPath!==void 0)return;if(of()){t.fd=nf;return}let e=ur();if(!e){if(t.port!==void 0){console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set; binding the TCP port only.
|
|
79
79
|
Pass --socket PATH to also accept CLI connections.`);return}console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set and no --socket/--port given.
|
|
80
|
-
Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}Je.mkdirSync(e,{recursive:!0,mode:448}),t.socketPath=Vt.join(e,
|
|
80
|
+
Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}Je.mkdirSync(e,{recursive:!0,mode:448}),t.socketPath=Vt.join(e,ef(t.instance))}function cf(t){let e=t??tf(new URL("web/",import.meta.url));if(Je.existsSync(e))return e;console.error(`diffstalkerd: web UI assets not found at ${e}; serving API only`);return}function lf(t){console.error(`diffstalkerd: web UI at http://diffstalker.localhost:${t}/`)}async function uf(t,e){for(let n of e){let r=Vt.resolve(Y(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 ff(){process.title="diffstalkerd";let t;try{t=sf(process.argv.slice(2))}catch(u){console.error(u instanceof Error?u.message:String(u)),console.error(Mi),process.exit(2)}if(t==="help"){console.log(Mi);return}if(t==="version"){let u=jn();if(u===null)console.error("diffstalkerd: version unknown (package.json unreadable)"),process.exit(1);console.log(u);return}hr(t.debug??!1),af(t);let e=t.noFollow?void 0:t.followFile??Vt.join(kt(),"target"),n=cf(t.webRoot),r=Di(t.grammarsDir??process.env.DIFFSTALKER_GRAMMARS_DIR??null,(u)=>console.error(`diffstalkerd: ${u}`)),s=vi({followFile:e,settingsFile:Vt.join(lr(),"daemon.json"),webRoot:n,symbols:r,updateCheck:!t.noUpdateCheck});await uf(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)lf(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))}ff().catch((t)=>{console.error(t instanceof Error?t.message:String(t)),process.exit(1)});export{sf as parseArgs};
|