diffstalkerd 0.14.3 → 0.14.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +1 -1
- package/dist/index.js +66 -65
- package/dist/web/assets/index-DSz-HF_d.js +29 -0
- package/dist/web/assets/{index-GxZ4XP1Z.css → index-G43GV-Jm.css} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/web/assets/index-BoTqAumP.js +0 -29
package/dist/index.js
CHANGED
|
@@ -1,92 +1,93 @@
|
|
|
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
|
|
5
|
-
${r.replace(/^/gm," ")}`:"";process.stderr.write(
|
|
6
|
-
`))}function G(t,e,n){if(!$s)return;Vn("debug",t,n,e===void 0?void 0:Kn(e,{stacks:!1}))}function w(t,e,n){Vn("warn",t,n,e===void 0?void 0:Kn(e,{stacks:!1}))}function C(t,e,n){Vn("error",t,n,e===void 0?void 0:Kn(e))}import*as ul from"node:http";import*as Xt from"node:fs";import*as fl from"node:net";function Qn(t){let e={};for(let[n,r]of t)e[n]=r;return e}function Ol(t){if(!t)return null;return{staged:Qn(t.staged),unstaged:Qn(t.unstaged)}}function kt(t){return{status:t.status,hunkCounts:Ol(t.hunkCounts),error:t.error,stashList:t.stashList,operationInProgress:t.operationInProgress,mtimes:t.mtimes?Qn(t.mtimes):null}}function Hs(t,e){let n=e>0?t.entries.filter((r)=>r.seq>e):t.entries;return{epoch:t.epoch,prunedBefore:t.prunedBefore,entries:n}}function Ae(t){if(t instanceof Date)return t.toISOString();if(t instanceof Map){let e={};for(let[n,r]of t)e[String(n)]=Ae(r);return e}if(Array.isArray(t))return t.map(Ae);if(t!==null&&typeof t==="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=Ae(r);return e}return t}var Nl=1048576;class p extends Error{status;constructor(t,e,n){super(e,n);this.status=t,this.name="HttpError"}}function E(t,e,n){let r=JSON.stringify(Ae(n));t.writeHead(e,{"content-type":"application/json"}),t.end(r)}function Ws(t,e,n,r){t.writeHead(e,{...r,"content-length":String(n.byteLength)}),t.end(n)}function $l(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 p(400,`Malformed percent-encoding in path: ${e[r]}`)}else if(s!==e[r])return null}return n}async function Ll(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>Nl)throw new p(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 p(400,"Invalid JSON body")}}class Zn{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=$l(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 p(404,`Unknown route: ${o} ${r.pathname}`)}let a=await Ll(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){C(`${s} failed after the response headers were sent`,r),e.end();return}if(r instanceof p){Bl(s,r),E(e,r.status,{error:r.message});return}C(`${s} -> 500`,r),E(e,500,{error:"Internal server error"})}}}function Bl(t,e){let n=`${t} -> ${e.status} ${e.message}`;if(e.cause!==void 0||e.status>=500)w(n,e.cause);else G(n)}import*as tr from"node:fs";import*as nt from"node:path";var Hl=new Set(["health","version","repos","resolve","worktrees","events","follow","settings","discovered","browse","work"]),Wl=new Set(["work"]);function Gl(t){if(t.length===0||!Hl.has(t[0]))return!1;return!(t.length===1&&Wl.has(t[0]))}var Ul={".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"},Gs="no-cache",jl="public, max-age=31536000, immutable";async function Us(t,e,n){let r;try{r=await tr.promises.readFile(e)}catch(s){throw new p(404,`Not found: ${nt.basename(e)}`,{cause:s})}t.writeHead(200,{"content-type":Ul[nt.extname(e)]??"application/octet-stream","cache-control":n,"content-length":r.length}),t.end(r)}function js(t){let e=nt.resolve(t);return async(n,r,s)=>{let o;try{o=decodeURIComponent(s)}catch{throw new p(400,`Malformed percent-encoding in path: ${s}`)}if(o.includes("\x00"))throw new p(400,"Invalid path");let i=o.split("/").filter(Boolean);if(Gl(i))throw new p(404,`Unknown route: GET ${s}`);let a=i.length>0?nt.resolve(e,i.join("/")):e;if(a!==e&&!a.startsWith(e+nt.sep))throw new p(403,"Forbidden");if((await tr.promises.stat(a).catch(()=>null))?.isFile()){await Us(r,a,i[0]==="assets"?jl:Gs);return}await Us(r,nt.join(e,"index.html"),Gs)}}function ql(t){try{let e=new URL(`http://${t}`).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function Xl(t){try{let e=new URL(t).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function Xs(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 zl(t){return t.length>10&&t.endsWith(".localhost")}function qs(t){return t==="localhost"||t==="::1"||zl(t)||Xs(t)}function Jl(t){return t==="::1"||Xs(t)}function zs(t){if(t===null)return!1;if(typeof t==="string")return!0;return Jl(t.address)}function Js(t){let e=t.headers.host;if(e!==void 0){let i=ql(e);if(i===null||!qs(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=Xl(o);if(i===null||!qs(i))return{status:403,message:"Cross-origin request blocked"}}return null}function Ys(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 Ks={"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 ch}from"node:crypto";class Vs{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)=>{C("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 er=new Map;function Qs(t){let e=er.get(t);if(!e)e=new Vs(t),er.set(t,e);return e}function Zs(t){er.delete(t)}import*as We from"node:path";import*as Lt from"node:fs";import{EventEmitter as Mf}from"node:events";import*as ht from"node:fs";import*as xt from"node:path";function to(t,e){return t===""?e:`${t}/${e}`}function eo(t){let e=t.lastIndexOf("/");return e===-1?"":t.slice(0,e)}function nr(t,e){return t===e||e===""||t.startsWith(`${e}/`)}class De{root;options;watches=new Map;inodes=new Map;skipped=new Set;inspecting=new Set;reinspect=new Set;namesakes=new Set;closed=!1;_rootGone=!1;limitReported=!1;constructor(t,e){this.root=t,this.options=e}get watchedDirs(){return this.watches.size}get rootGone(){return this._rootGone}start(){return this._rootGone=!1,this.crawl("")}close(){this.closed=!0;for(let t of this.watches.values())t.close();this.watches.clear(),this.inodes.clear(),this.skipped.clear(),this.namesakes.clear()}async resync(){this.limitReported=!1;for(let t of[...this.watches.keys()])if(t!==""&&this.watches.has(t)&&this.options.skipDir(t))this.unwatchTree(t),this.skipped.add(t);for(let t of[...this.skipped]){if(this.closed)return;if(this.skipped.has(t)&&!this.options.skipDir(t))this.skipped.delete(t),await this.crawl(t)}}abs(t){return t===""?this.root:xt.join(this.root,t)}async crawl(t){let e=[t];while(e.length>0&&!this.closed){let n=e.pop();if(this.watches.has(n))continue;let r=await this.directoryInode(n);if(r===null&&n==="")this._rootGone=!0;if(r===null||this.closed||!this.parentWatched(n)||!this.watch(n,r))continue;for(let s of await this.subdirsToWatch(n))e.push(s)}}parentWatched(t){return t===""||this.watches.has(eo(t))}async directoryInode(t){try{let e=await(t===""?ht.promises.stat:ht.promises.lstat)(this.abs(t));return e.isDirectory()?e.ino:null}catch(e){return this.options.onError(e,t),null}}async subdirsToWatch(t){let e;try{e=await ht.promises.readdir(this.abs(t),{withFileTypes:!0})}catch(s){return this.options.onError(s,t),[]}if(this.closed||!this.watches.has(t))return[];let n=[],r=xt.basename(this.abs(t));for(let s of e){if(s.name===r)this.namesakes.add(t);let o=to(t,s.name);if(!s.isDirectory()||this.watches.has(o)||this.skipped.has(o))continue;if(this.options.skipDir(o))this.skipped.add(o);else n.push(o)}return n}watch(t,e){if(this.watches.has(t))return!1;let n;try{n=ht.watch(this.abs(t),{persistent:!1},(r,s)=>this.onEvent(t,r,s))}catch(r){if(r.code==="ENOSPC"){if(!this.limitReported)this.options.onError(r,t);return this.limitReported=!0,!1}return this.options.onError(r,t),!1}return n.on("error",(r)=>{if(this.watches.get(t)===n)this.watches.delete(t),this.inodes.delete(t);n.close(),this.options.onError(r,t)}),this.watches.set(t,n),this.inodes.set(t,e),!0}onEvent(t,e,n){if(this.closed)return;if(n===null){this.options.onChange(t,!0);return}let r=to(t,n.toString());if(e==="rename"){this.inspect(r);return}this.options.onChange(r,this.watches.has(r)||this.skipped.has(r))}async inspect(t){if(this.inspecting.has(t)){this.reinspect.add(t);return}this.inspecting.add(t);try{do{this.reinspect.delete(t);let{isDir:e,gone:n}=await this.settle(t);if(this.closed)return;if(await this.checkOwnEvent(t,n),this.closed)return;this.options.onChange(t,e)}while(this.reinspect.has(t))}finally{this.inspecting.delete(t)}}async settle(t){let e=null;try{e=await ht.promises.lstat(this.abs(t))}catch{}if(this.closed)return{isDir:!1,gone:e===null};let n=this.watches.has(t)||this.skipped.has(t);if(e===null||!e.isDirectory()){if(n)this.unwatchTree(t);return{isDir:e===null&&n,gone:e===null}}if(this.watches.has(t)&&this.inodes.get(t)!==e.ino)this.unwatchTree(t);let r=xt.posix.dirname(t);if(!this.watches.has(t)&&!this.skipped.has(t)&&this.watches.has(r==="."?"":r))if(this.options.skipDir(t))this.skipped.add(t);else await this.crawl(t);return{isDir:!0,gone:!1}}async checkOwnEvent(t,e){let n=eo(t);if(xt.basename(t)!==xt.basename(this.abs(n)))return;if(!e)this.namesakes.add(n);else if(this.namesakes.has(n))this.namesakes.delete(n);else await this.revalidate(n)}async revalidate(t){let e=null;try{e=await(t===""?ht.promises.stat:ht.promises.lstat)(this.abs(t))}catch{}if(this.closed)return;if(this.unwatchTree(t),!e?.isDirectory()){if(t==="")this._rootGone=!0;return}if(t!==""&&this.options.skipDir(t))this.skipped.add(t);else await this.crawl(t)}unwatchTree(t){for(let[e,n]of this.watches)if(nr(e,t))n.close(),this.watches.delete(e),this.inodes.delete(e);for(let e of this.skipped)if(nr(e,t))this.skipped.delete(e);for(let e of this.namesakes)if(nr(e,t))this.namesakes.delete(e)}}import*as oo from"node:fs";import*as pt from"node:path";import{execFile as au}from"node:child_process";import{promisify as cu}from"node:util";import ro from"ignore";import{execFile as tu}from"node:child_process";import{promisify as eu}from"node:util";import{simpleGit as nu}from"simple-git";import*as it from"node:fs";import*as Ie from"node:path";import{execFileSync as Yl}from"node:child_process";var Kl=[["*.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 Vl(){return`# Generated by diffstalker: turns on git's built-in funcname drivers.
|
|
1
|
+
var xl=Object.create;var{getPrototypeOf:vl,defineProperty:Fs,getOwnPropertyNames:_l}=Object;var Os=Object.prototype.hasOwnProperty;function Al(t){return this[t]}var Dl,Tl,Il=(t,e,n)=>{var r=t!=null&&typeof t==="object";if(r){var s=e?Dl??=new WeakMap:Tl??=new WeakMap,o=s.get(t);if(o)return o}n=t!=null?xl(vl(t)):{};let i=e||!t||!t.__esModule||!Os.call(t,"default")?Fs(n,"default",{value:t,enumerable:!0}):n;if(t&&typeof t==="object"||typeof t==="function"){for(let a of _l(t))if(!Os.call(i,a))Fs(i,a,{get:Al.bind(t,a),enumerable:!0})}if(r)s.set(t,i);return i};var Ml=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ui=Ml(function(xw,Gi){var Y=-1,z=1,B=0;function Ue(t,e,n,r,s){if(t===e){if(t)return[[B,t]];return[]}if(n!=null){var o=If(t,e,n);if(o)return o}var i=Br(t,e),a=t.substring(0,i);t=t.substring(i),e=e.substring(i),i=bn(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=Sf(t,e);if(a)l.unshift([B,a]);if(c)l.push([B,c]);if(Hr(l,s),r)vf(l);return l}function Sf(t,e){var n;if(!t)return[[z,e]];if(!e)return[[Y,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=[[z,r.substring(0,o)],[B,s],[z,r.substring(o+s.length)]],t.length>e.length)n[0][0]=n[2][0]=Y;return n}if(s.length===1)return[[Y,t],[z,e]];var i=xf(t,e);if(i){var a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],h=Ue(a,l),d=Ue(c,u);return h.concat([[B,f]],d)}return kf(t,e)}function kf(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,m=0,g=0;for(var R=0;R<s;R++){for(var y=-R+h;y<=R-d;y+=2){var x=o+y,v;if(y===-R||y!==R&&a[x-1]<a[x+1])v=a[x+1];else v=a[x-1]+1;var D=v-y;while(v<n&&D<r&&t.charAt(v)===e.charAt(D))v++,D++;if(a[x]=v,v>n)d+=2;else if(D>r)h+=2;else if(f){var T=o+u-y;if(T>=0&&T<i&&c[T]!==-1){var I=n-c[T];if(v>=I)return Pi(t,e,v,D)}}}for(var W=-R+m;W<=R-g;W+=2){var T=o+W,I;if(W===-R||W!==R&&c[T-1]<c[T+1])I=c[T+1];else I=c[T-1]+1;var b=I-W;while(I<n&&b<r&&t.charAt(n-I-1)===e.charAt(r-b-1))I++,b++;if(c[T]=I,I>n)g+=2;else if(b>r)m+=2;else if(!f){var x=o+u-W;if(x>=0&&x<i&&a[x]!==-1){var v=a[x],D=o+v-x;if(I=n-I,v>=I)return Pi(t,e,v,D)}}}}return[[Y,t],[z,e]]}function Pi(t,e,n,r){var s=t.substring(0,n),o=e.substring(0,r),i=t.substring(n),a=e.substring(r),c=Ue(s,o),l=Ue(i,a);return c.concat(l)}function Br(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(Li(t.charCodeAt(s-1)))s--;return s}function Fi(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 bn(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(Bi(t.charCodeAt(t.length-s)))s--;return s}function xf(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,m,g){var R=d.substring(g,g+Math.floor(d.length/4)),y=-1,x="",v,D,T,I;while((y=m.indexOf(R,y+1))!==-1){var W=Br(d.substring(g),m.substring(y)),b=bn(d.substring(0,g),m.substring(0,y));if(x.length<b+W)x=m.substring(y-b,y)+m.substring(y,y+W),v=d.substring(0,g-b),D=d.substring(g+W),T=m.substring(0,y-b),I=m.substring(y+W)}if(x.length*2>=d.length)return[v,D,T,I,x];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 vf(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]==B)n[r++]=o,i=c,a=l,c=0,l=0,s=t[o][1];else{if(t[o][0]==z)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,[Y,s]),t[n[r-1]+1][0]=z,r--,r--,o=r>0?n[r-1]:-1,i=0,a=0,c=0,l=0,s=null,e=!0}o++}if(e)Hr(t);Df(t),o=1;while(o<t.length){if(t[o-1][0]==Y&&t[o][0]==z){var u=t[o-1][1],f=t[o][1],h=Fi(u,f),d=Fi(f,u);if(h>=d){if(h>=u.length/2||h>=f.length/2)t.splice(o,0,[B,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,[B,u.substring(0,d)]),t[o-1][0]=z,t[o-1][1]=f.substring(0,f.length-d),t[o+1][0]=Y,t[o+1][1]=u.substring(d),o++;o++}o++}}var Oi=/[^a-zA-Z0-9]/,Ni=/\s/,$i=/[\r\n]/,_f=/\n\r?\n$/,Af=/^\r?\n\r?\n/;function Df(t){function e(d,m){if(!d||!m)return 6;var g=d.charAt(d.length-1),R=m.charAt(0),y=g.match(Oi),x=R.match(Oi),v=y&&g.match(Ni),D=x&&R.match(Ni),T=v&&g.match($i),I=D&&R.match($i),W=T&&d.match(_f),b=I&&m.match(Af);if(W||b)return 5;else if(T||I)return 4;else if(y&&!v&&D)return 3;else if(v||D)return 2;else if(y||x)return 1;return 0}var n=1;while(n<t.length-1){if(t[n-1][0]==B&&t[n+1][0]==B){var r=t[n-1][1],s=t[n][1],o=t[n+1][1],i=bn(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 Hr(t,e){t.push([B,""]);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 z:s++,i+=t[n][1],n++;break;case Y:r++,o+=t[n][1],n++;break;case B:var c=n-s-r-1;if(e){if(c>=0&&Wi(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]===z)s++,i=t[u][1]+i,u--;if(t[u]&&t[u][0]===Y)r++,o=t[u][1]+o,u--;c=u}}if(Hi(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=Br(i,o),a!==0){if(c>=0)t[c][1]+=i.substring(0,a);else t.splice(0,0,[B,i.substring(0,a)]),n++;i=i.substring(a),o=o.substring(a)}if(a=bn(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,[z,i]),n=n-f+1;else if(i.length===0)t.splice(n-f,f,[Y,o]),n=n-f+1;else t.splice(n-f,f,[Y,o],[z,i]),n=n-f+2}if(n!==0&&t[n-1][0]===B)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]===B&&t[n+1][0]===B){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)Hr(t,e)}function Li(t){return t>=55296&&t<=56319}function Bi(t){return t>=56320&&t<=57343}function Hi(t){return Bi(t.charCodeAt(0))}function Wi(t){return Li(t.charCodeAt(t.length-1))}function Tf(t){var e=[];for(var n=0;n<t.length;n++)if(t[n][1].length>0)e.push(t[n]);return e}function Lr(t,e,n,r){if(Wi(t)||Hi(r))return null;return Tf([[B,t],[Y,e],[z,n],[B,r]])}function If(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 m=Math.min(a,f),g=c.slice(0,m),R=h.slice(0,m);if(g!==R)break t;var y=c.slice(m),x=h.slice(m);return Lr(g,y,x,l)}t:{if(u!==null&&u!==a)break t;var v=a,h=e.slice(0,v),d=e.slice(v);if(h!==c)break t;var D=Math.min(o-v,i-v),T=l.slice(l.length-D),I=d.slice(d.length-D);if(T!==I)break t;var y=l.slice(0,l.length-D),x=d.slice(0,d.length-D);return Lr(c,y,x,T)}}if(r.length>0&&s&&s.length===0)t:{var g=t.slice(0,r.index),T=t.slice(r.index+r.length),m=g.length,D=T.length;if(i<m+D)break t;var R=e.slice(0,m),I=e.slice(i-D);if(g!==R||T!==I)break t;var y=t.slice(m,o-D),x=e.slice(m,i-D);return Lr(g,y,x,T)}return null}function Rn(t,e,n,r){return Ue(t,e,n,r,!0)}Rn.INSERT=z;Rn.DELETE=Y;Rn.EQUAL=B;Gi.exports=Rn});import*as Kn from"node:fs";import*as Jt from"node:path";import{fileURLToPath as ng}from"node:url";import*as Ze from"node:os";import*as St from"node:path";var tn="diffstalker";function De(){return process.env.XDG_CONFIG_HOME||St.join(Ze.homedir(),".config")}function Ns(){return St.join(De(),tn)}function Yt(){return St.join(process.env.XDG_CACHE_HOME||St.join(Ze.homedir(),".cache"),tn)}function $s(){return St.join(process.env.XDG_STATE_HOME||St.join(Ze.homedir(),".local","state"),tn)}function Ls(){return process.env.XDG_RUNTIME_DIR?St.join(process.env.XDG_RUNTIME_DIR,tn):null}import*as en from"node:fs";import*as nn from"node:path";import*as Vn from"node:os";function ot(t){if(t.startsWith("~/"))return nn.join(Vn.homedir(),t.slice(2));if(t==="~")return Vn.homedir();return t}function rn(t){let e=nn.dirname(t);if(!en.existsSync(e))en.mkdirSync(e,{recursive:!0})}function Qn(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 Bs=!1;function Hs(t){Bs=t}function Ws(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 Cl=/(\w+:\/\/)[^/\s@]+@/g;function Pl(t){return t.replace(Cl,"$1***@")}function Fl(t){if(!t)return"";let e=[];for(let[n,r]of Object.entries(t)){if(r===void 0)continue;let s=Ws(String(r));e.push(`${n}=${/\s/.test(s)||s===""?JSON.stringify(s):s}`)}return e.length===0?"":` ${e.join(" ")}`}function Ol(t){if(t instanceof Error)return`${t.name}: ${t.message}`;return String(t)}function Zn(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:Ol(r);n.push(o+i),r=r instanceof Error?r.cause:void 0}return n.join(`
|
|
4
|
+
`)}function tr(t,e,n,r){let s=`${new Date().toISOString()} ${t.padEnd(5)} ${Ws(e)}${Fl(n)}`,o=r?`
|
|
5
|
+
${r.replace(/^/gm," ")}`:"";process.stderr.write(Pl(`${s}${o}
|
|
6
|
+
`))}function G(t,e,n){if(!Bs)return;tr("debug",t,n,e===void 0?void 0:Zn(e,{stacks:!1}))}function w(t,e,n){tr("warn",t,n,e===void 0?void 0:Zn(e,{stacks:!1}))}function C(t,e,n){tr("error",t,n,e===void 0?void 0:Zn(e))}import*as fl from"node:http";import*as zt from"node:fs";import*as hl from"node:net";function er(t){let e={};for(let[n,r]of t)e[n]=r;return e}function Nl(t){if(!t)return null;return{staged:er(t.staged),unstaged:er(t.unstaged)}}function kt(t){return{status:t.status,hunkCounts:Nl(t.hunkCounts),error:t.error,stashList:t.stashList,operationInProgress:t.operationInProgress,mtimes:t.mtimes?er(t.mtimes):null}}function Gs(t,e){let n=e>0?t.entries.filter((r)=>r.seq>e):t.entries;return{epoch:t.epoch,prunedBefore:t.prunedBefore,entries:n}}function Te(t){if(t instanceof Date)return t.toISOString();if(t instanceof Map){let e={};for(let[n,r]of t)e[String(n)]=Te(r);return e}if(Array.isArray(t))return t.map(Te);if(t!==null&&typeof t==="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=Te(r);return e}return t}var $l=1048576;class p extends Error{status;constructor(t,e,n){super(e,n);this.status=t,this.name="HttpError"}}function E(t,e,n){let r=JSON.stringify(Te(n));t.writeHead(e,{"content-type":"application/json"}),t.end(r)}function Us(t,e,n,r){t.writeHead(e,{...r,"content-length":String(n.byteLength)}),t.end(n)}function Ll(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 p(400,`Malformed percent-encoding in path: ${e[r]}`)}else if(s!==e[r])return null}return n}async function Bl(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>$l)throw new p(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 p(400,"Invalid JSON body")}}class nr{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=Ll(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 p(404,`Unknown route: ${o} ${r.pathname}`)}let a=await Bl(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){C(`${s} failed after the response headers were sent`,r),e.end();return}if(r instanceof p){Hl(s,r),E(e,r.status,{error:r.message});return}C(`${s} -> 500`,r),E(e,500,{error:"Internal server error"})}}}function Hl(t,e){let n=`${t} -> ${e.status} ${e.message}`;if(e.cause!==void 0||e.status>=500)w(n,e.cause);else G(n)}import*as rr from"node:fs";import*as nt from"node:path";var Wl=new Set(["health","version","repos","resolve","worktrees","events","follow","settings","discovered","browse","work"]),Gl=new Set(["work"]);function Ul(t){if(t.length===0||!Wl.has(t[0]))return!1;return!(t.length===1&&Gl.has(t[0]))}var jl={".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"},js="no-cache",ql="public, max-age=31536000, immutable";async function qs(t,e,n){let r;try{r=await rr.promises.readFile(e)}catch(s){throw new p(404,`Not found: ${nt.basename(e)}`,{cause:s})}t.writeHead(200,{"content-type":jl[nt.extname(e)]??"application/octet-stream","cache-control":n,"content-length":r.length}),t.end(r)}function Xs(t){let e=nt.resolve(t);return async(n,r,s)=>{let o;try{o=decodeURIComponent(s)}catch{throw new p(400,`Malformed percent-encoding in path: ${s}`)}if(o.includes("\x00"))throw new p(400,"Invalid path");let i=o.split("/").filter(Boolean);if(Ul(i))throw new p(404,`Unknown route: GET ${s}`);let a=i.length>0?nt.resolve(e,i.join("/")):e;if(a!==e&&!a.startsWith(e+nt.sep))throw new p(403,"Forbidden");if((await rr.promises.stat(a).catch(()=>null))?.isFile()){await qs(r,a,i[0]==="assets"?ql:js);return}await qs(r,nt.join(e,"index.html"),js)}}function Xl(t){try{let e=new URL(`http://${t}`).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function zl(t){try{let e=new URL(t).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function Js(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 Jl(t){return t.length>10&&t.endsWith(".localhost")}function zs(t){return t==="localhost"||t==="::1"||Jl(t)||Js(t)}function Kl(t){return t==="::1"||Js(t)}function Ks(t){if(t===null)return!1;if(typeof t==="string")return!0;return Kl(t.address)}function Ys(t){let e=t.headers.host;if(e!==void 0){let i=Xl(e);if(i===null||!zs(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=zl(o);if(i===null||!zs(i))return{status:403,message:"Cross-origin request blocked"}}return null}function Vs(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 Qs={"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 lh}from"node:crypto";class Zs{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)=>{C("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 sr=new Map;function to(t){let e=sr.get(t);if(!e)e=new Zs(t),sr.set(t,e);return e}function eo(t){sr.delete(t)}import*as je from"node:path";import*as Lt from"node:fs";import{EventEmitter as Cf}from"node:events";import*as ht from"node:fs";import*as xt from"node:path";function no(t,e){return t===""?e:`${t}/${e}`}function ro(t){let e=t.lastIndexOf("/");return e===-1?"":t.slice(0,e)}function or(t,e){return t===e||e===""||t.startsWith(`${e}/`)}class Ie{root;options;watches=new Map;inodes=new Map;skipped=new Set;inspecting=new Set;reinspect=new Set;namesakes=new Set;closed=!1;_rootGone=!1;limitReported=!1;constructor(t,e){this.root=t,this.options=e}get watchedDirs(){return this.watches.size}get rootGone(){return this._rootGone}start(){return this._rootGone=!1,this.crawl("")}close(){this.closed=!0;for(let t of this.watches.values())t.close();this.watches.clear(),this.inodes.clear(),this.skipped.clear(),this.namesakes.clear()}async resync(){this.limitReported=!1;for(let t of[...this.watches.keys()])if(t!==""&&this.watches.has(t)&&this.options.skipDir(t))this.unwatchTree(t),this.skipped.add(t);for(let t of[...this.skipped]){if(this.closed)return;if(this.skipped.has(t)&&!this.options.skipDir(t))this.skipped.delete(t),await this.crawl(t)}}abs(t){return t===""?this.root:xt.join(this.root,t)}async crawl(t){let e=[t];while(e.length>0&&!this.closed){let n=e.pop();if(this.watches.has(n))continue;let r=await this.directoryInode(n);if(r===null&&n==="")this._rootGone=!0;if(r===null||this.closed||!this.parentWatched(n)||!this.watch(n,r))continue;for(let s of await this.subdirsToWatch(n))e.push(s)}}parentWatched(t){return t===""||this.watches.has(ro(t))}async directoryInode(t){try{let e=await(t===""?ht.promises.stat:ht.promises.lstat)(this.abs(t));return e.isDirectory()?e.ino:null}catch(e){return this.options.onError(e,t),null}}async subdirsToWatch(t){let e;try{e=await ht.promises.readdir(this.abs(t),{withFileTypes:!0})}catch(s){return this.options.onError(s,t),[]}if(this.closed||!this.watches.has(t))return[];let n=[],r=xt.basename(this.abs(t));for(let s of e){if(s.name===r)this.namesakes.add(t);let o=no(t,s.name);if(!s.isDirectory()||this.watches.has(o)||this.skipped.has(o))continue;if(this.options.skipDir(o))this.skipped.add(o);else n.push(o)}return n}watch(t,e){if(this.watches.has(t))return!1;let n;try{n=ht.watch(this.abs(t),{persistent:!1},(r,s)=>this.onEvent(t,r,s))}catch(r){if(r.code==="ENOSPC"){if(!this.limitReported)this.options.onError(r,t);return this.limitReported=!0,!1}return this.options.onError(r,t),!1}return n.on("error",(r)=>{if(this.watches.get(t)===n)this.watches.delete(t),this.inodes.delete(t);n.close(),this.options.onError(r,t)}),this.watches.set(t,n),this.inodes.set(t,e),!0}onEvent(t,e,n){if(this.closed)return;if(n===null){this.options.onChange(t,!0);return}let r=no(t,n.toString());if(e==="rename"){this.inspect(r);return}this.options.onChange(r,this.watches.has(r)||this.skipped.has(r))}async inspect(t){if(this.inspecting.has(t)){this.reinspect.add(t);return}this.inspecting.add(t);try{do{this.reinspect.delete(t);let{isDir:e,gone:n}=await this.settle(t);if(this.closed)return;if(await this.checkOwnEvent(t,n),this.closed)return;this.options.onChange(t,e)}while(this.reinspect.has(t))}finally{this.inspecting.delete(t)}}async settle(t){let e=null;try{e=await ht.promises.lstat(this.abs(t))}catch{}if(this.closed)return{isDir:!1,gone:e===null};let n=this.watches.has(t)||this.skipped.has(t);if(e===null||!e.isDirectory()){if(n)this.unwatchTree(t);return{isDir:e===null&&n,gone:e===null}}if(this.watches.has(t)&&this.inodes.get(t)!==e.ino)this.unwatchTree(t);let r=xt.posix.dirname(t);if(!this.watches.has(t)&&!this.skipped.has(t)&&this.watches.has(r==="."?"":r))if(this.options.skipDir(t))this.skipped.add(t);else await this.crawl(t);return{isDir:!0,gone:!1}}async checkOwnEvent(t,e){let n=ro(t);if(xt.basename(t)!==xt.basename(this.abs(n)))return;if(!e)this.namesakes.add(n);else if(this.namesakes.has(n))this.namesakes.delete(n);else await this.revalidate(n)}async revalidate(t){let e=null;try{e=await(t===""?ht.promises.stat:ht.promises.lstat)(this.abs(t))}catch{}if(this.closed)return;if(this.unwatchTree(t),!e?.isDirectory()){if(t==="")this._rootGone=!0;return}if(t!==""&&this.options.skipDir(t))this.skipped.add(t);else await this.crawl(t)}unwatchTree(t){for(let[e,n]of this.watches)if(or(e,t))n.close(),this.watches.delete(e),this.inodes.delete(e);for(let e of this.skipped)if(or(e,t))this.skipped.delete(e);for(let e of this.namesakes)if(or(e,t))this.namesakes.delete(e)}}import*as ao from"node:fs";import*as pt from"node:path";import{execFile as cu}from"node:child_process";import{promisify as lu}from"node:util";import oo from"ignore";import{execFile as eu}from"node:child_process";import{promisify as nu}from"node:util";import{simpleGit as ru}from"simple-git";import*as it from"node:fs";import*as Ce from"node:path";import{execFileSync as Yl}from"node:child_process";var Vl=[["*.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 Ql(){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
|
+
`+Vl.map(([e,n])=>`${e} diff=${n}`).join(`
|
|
9
9
|
`)+`
|
|
10
|
-
`}var
|
|
10
|
+
`}var Me=null,It=null;function Zl(){if(It!==null)return It;try{if(Yl("git",["config","--get","core.attributesFile"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:process.env}).trim()!=="")return It=!0,!0}catch(t){if(t.status!==1)return w("git config core.attributesFile failed; funcname drivers are off",t),It=!0,!0}return It=it.existsSync(Ce.join(De(),"git","attributes")),It}function so(){if(Me!==null)return Me;if(Zl())return null;let t=Ce.join(Yt(),"funcname.gitattributes"),e=Ql();try{let n=null;try{n=it.readFileSync(t,"utf8")}catch{n=null}if(n!==e)it.mkdirSync(Ce.dirname(t),{recursive:!0}),tu(t,e);return Me=t,Me}catch(n){return w("Cannot write the attributes file; funcname drivers are off",n,{file:t}),Me=null,It=!0,null}}function tu(t,e){let n=`${t}.${process.pid}.tmp`;it.writeFileSync(n,e,"utf8"),it.renameSync(n,t)}var su=nu(eu);function vt(){return{...process.env,LC_ALL:"C",LANG:"C",GIT_OPTIONAL_LOCKS:"0"}}var dt=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"],ir=5000;async function _t(t,e,n){let{stdout:r}=await su("git",e,{cwd:t,env:vt(),encoding:"buffer",maxBuffer:n,timeout:ir,windowsHide:!0});return r}var ou={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0},iu=1e4,au=600000;function k(t,e={}){let n=so(),r=["diff.mnemonicPrefix=false","diff.noprefix=false"];if(n!==null)r.push(`core.attributesFile=${n}`);let s=vt();return ru({baseDir:t,unsafe:ou,allowEnvironment:Object.keys(s),timeout:{block:e.longRunning===!0?au:iu},config:r}).env(s)}var uu=lu(cu),fu=47;function io(t,e){if(e==="")return t;if(t.startsWith(e)&&t.charCodeAt(e.length)===fu)return t.slice(e.length+1);return null}class co{sources;constructor(t){this.sources=t}ignores(t,e){if(t==="")return!1;let n=t.indexOf("/");while(n!==-1){if(this.verdict(t.slice(0,n),!0))return!0;n=t.indexOf("/",n+1)}return this.verdict(t,e)}verdict(t,e){let n=t.lastIndexOf("/"),r=n===-1?"":t.slice(0,n);for(let{dir:s,rules:o}of this.sources){let i=io(t,s);if(i===null)continue;let a=o.checkIgnore(e?`${i}/`:i);if(!a.ignored&&!a.unignored)continue;let c=io(r,s);if(c&&o.checkIgnore(`${c}/`).rule===a.rule)continue;return a.ignored}return!1}}function lo(t,e){try{return ao.readFileSync(t,"utf-8")}catch(n){if(n.code!=="ENOENT")w(`Failed to read ${t}`,n,{repo:e});return null}}async function uo(t,e){let{stdout:n}=await uu("git",e,{cwd:t,env:vt(),encoding:"utf-8",maxBuffer:67108864});return n}async function hu(t){try{let e=(await uo(t,["config","--path","--get","core.excludesFile"])).trim();if(e)return pt.resolve(t,e)}catch(e){if(e.code!==1)return w("git config core.excludesFile failed; global ignore rules are not applied",e,{repo:t}),null}return pt.join(De(),"git","ignore")}async function du(t){let e=new Map,n;try{n=await uo(t,["ls-files","-z","--cached","--others","--exclude-standard","**/.gitignore"])}catch(r){return w("git ls-files failed; nested .gitignore files are not applied",r,{repo:t}),e}for(let r of n.split("\x00")){if(!r.endsWith("/.gitignore"))continue;let s=lo(pt.join(t,r),t);if(s!==null)e.set(pt.posix.dirname(r),s)}return e}async function ar(t,e){let[n,r]=await Promise.all([du(t),hu(t)]),s=[...n].sort(([i],[a])=>a.split("/").length-i.split("/").length).map(([i,a])=>({dir:i,rules:oo().add(a)})),o=[pt.join(t,".gitignore"),pt.join(e,"info","exclude"),...r===null?[]:[r]];for(let i of o){let a=lo(i,t);if(a!==null)s.push({dir:"",rules:oo().add(a)})}return new co(s)}import{execFileSync as Su}from"node:child_process";import*as Oe from"node:fs";import*as ur from"node:path";async function Vt(t,e){if(e.length===0)return new Set;let n=k(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))w("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 Mt(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
|
|
15
|
-
`),s=r.findIndex((i)=>i.startsWith("@@"));return`${[...r.slice(0,s===-1?4:s),
|
|
13
|
+
`}function sn(t){let e=0;for(let n of t)e+=n.content.length+1;return e}var pu=5000,Pe=262144,mo="Large file — diff not shown";function mu(t){return String(t).replace(/\B(?=(\d{3})+(?!\d))/g,",")}function gu(t){let e=t/1048576;if(e>=1)return`${e.toFixed(1)} MB`;return`${Math.round(t/1024)} KB`}function cr(t,e){let n=gu(t),r=e===void 0?n:`${n}, ${mu(e)} lines`;return`${mo} (${r})`}function fo(t){if(t.length===0)return 0;let e=1,n=-1;while((n=t.indexOf(`
|
|
14
|
+
`,n+1))!==-1)e++;return e}function ho(t,e,n){let r=t.split(`
|
|
15
|
+
`),s=r.findIndex((i)=>i.startsWith("@@"));return`${[...r.slice(0,s===-1?4:s),cr(e,n)].join(`
|
|
16
16
|
`)}
|
|
17
|
-
`}function mt(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<=
|
|
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=Ct(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
|
|
23
|
-
`).join(", ")}`);return"Stash popped"}async function
|
|
24
|
-
`)}function
|
|
17
|
+
`}function mt(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<=Pe){let i=fo(s);if(i<=pu)return s;return n=!0,ho(s,o,i)}return n=!0,ho(s,o,fo(s))});return n?r.join(""):t}function wu(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(mo)}function yu(t){return t.startsWith("\\ ")}function go(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 gt(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(wu(o))n.push({type:"header",content:o});else if(yu(o))n.push({type:"context",content:o});else if(o.startsWith("@@")){let i=go(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 on(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=Ct(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 wo=new Map([["a",7],["b",8],["f",12],["n",10],["r",13],["t",9],["v",11],["\\",92],['"',34]]),Eu=new Map([...wo].map(([t,e])=>[e,t]));function po(t){return t<32||t===127||t>=128||t===34||t===92}function Qt(t){let e=new TextEncoder().encode(t);if(!e.some(po))return t;let n='"';for(let r of e){let s=Eu.get(r);if(s!==void 0)n+=`\\${s}`;else if(po(r))n+=`\\${r.toString(8).padStart(3,"0")}`;else n+=String.fromCharCode(r)}return`${n}"`}function bu(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=wo.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 Ru(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 Ct(t){if(!t.startsWith("diff --git "))return null;let n=t.slice(11);if(n.endsWith('"')){let s=Ru(n);if(s===-1)return null;let o=bu(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 Fe(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 lr(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 Zt(t){return t instanceof Error?t.message:String(t)}function Eo(t){return/does not have any commits yet|bad default revision/i.test(Zt(t))}var ku=Pe;async function xu(t,e){try{let n=ur.join(t,e),r=await Oe.promises.stat(n);if(!r.isFile())return null;if(r.size>ku)return null;return(await Oe.promises.readFile(n,"utf-8")).split(`
|
|
20
|
+
`).filter((o)=>o.length>0).length}catch{return null}}var vu=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function _u(t,e){return vu.has(`${t}${e}`)}function yo(t,e){return e?"conflicted":Au(t)}function Au(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 fr(t){let e=k(t);if(!await e.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let r=await e.status(),s=[],o=new Set,i=r.files.filter((m)=>m.working_dir==="?").map((m)=>m.path),a=await Vt(t,i);for(let m of r.files){if(m.index==="!"||m.working_dir==="!"||a.has(m.path))continue;let g=`${m.path}-${m.index!==" "&&m.index!=="?"}`;if(o.has(g))continue;o.add(g);let R=_u(m.index,m.working_dir);if(m.index&&m.index!==" "&&m.index!=="?"){let y=yo(m.index,R);s.push({path:m.path,status:y,staged:!0,...m.from&&(y==="renamed"||y==="copied")?{originalPath:m.from}:{}})}if(m.working_dir&&m.working_dir!==" ")s.push({path:m.path,status:yo(m.working_dir,R),staged:!1})}let c=(m)=>e.diff([...m,"--numstat","-z"]).catch((g)=>(w(`git diff ${m.join(" ")} --numstat failed in ${t}: ${Zt(g)}`),"")),[l,u]=await Promise.all([c(["--cached"]),c([])]),f=Fe(l),h=Fe(u);for(let m of s){let g=m.staged?f.get(m.path):h.get(m.path);if(g)m.insertions=g.additions,m.deletions=g.deletions}let d=s.filter((m)=>m.status==="untracked");if(d.length>0){let m=await Promise.all(d.map((g)=>xu(t,g.path)));for(let g=0;g<d.length;g++){let R=m[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 bo(t,e){await k(t).add(["--",e])}async function Ro(t,e){await k(t).reset(["HEAD","--",e])}async function So(t){await k(t).add("-A")}async function ko(t){await k(t).reset(["HEAD"])}async function xo(t,e){await k(t).checkout(["--",e])}async function vo(t,e){await k(t).clean("f",["--",e])}async function _o(t,e,n=!1){if(!(await k(t,{longRunning:!0}).commit(e,void 0,n?{"--amend":null}:void 0)).commit)throw Error("Nothing to commit: no staged changes")}async function Ao(t){let e=k(t);try{return(await e.log({n:1})).latest?.message||""}catch(n){if(!Eo(n))w(`git log for the HEAD message failed in ${t}: ${Zt(n)}`);return""}}function Do(t,e,n){Su("git",["apply","--cached",...n?["--reverse"]:[],"--unidiff-zero"],{cwd:t,input:e,encoding:"utf-8",env:vt(),stdio:["pipe","pipe","pipe"]})}function To(t,e){Do(t,e,!1)}function Io(t,e){Do(t,e,!0)}async function Mo(t){let r=(await k(t,{longRunning:!0}).push()).pushed;if(r.length===0)return"Everything up-to-date";return r.map((s)=>`${s.local} → ${s.remote}`).join(", ")}async function Co(t){return await k(t,{longRunning:!0}).fetch(),"Fetch complete"}async function Po(t){let n=await k(t,{longRunning:!0}).pull(["--rebase"]);if(n.summary.changes===0&&n.summary.insertions===0&&n.summary.deletions===0)return"Already up-to-date";return`${n.summary.changes} file(s) changed`}async function Fo(t,e=50){let n=k(t);try{return(await n.log({n:e})).all.map((s)=>({hash:s.hash,shortHash:s.hash.slice(0,7),message:s.message.split(`
|
|
21
|
+
`)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}))}catch(r){if(!Eo(r))w(`git log failed in ${t}: ${Zt(r)}`);return[]}}async function Oo(t,e){let n=k(t);try{let s=(await n.log(["--no-walk",e])).all[0];if(!s)return null;return{hash:s.hash,shortHash:s.hash.slice(0,7),message:s.message.split(`
|
|
22
|
+
`)[0],author:s.author_name,date:new Date(s.date),refs:s.refs||""}}catch{return null}}async function hr(t){let e=k(t);try{return(await e.stashList()).all.map((r,s)=>({index:s,message:r.message}))}catch(n){return w(`git stash list failed in ${t}, reporting no stashes: ${Zt(n)}`),[]}}async function No(t,e){let n=k(t),r=["push"];if(e)r.push("-m",e);return await n.stash(r),"Stashed"}async function $o(t,e=0){let n=k(t);await n.stash(["pop",`stash@{${e}}`]);let r=(await n.raw(["diff","--name-only","--diff-filter=U"])).trim();if(r)throw Error(`Stash pop hit conflicts in: ${r.split(`
|
|
23
|
+
`).join(", ")}`);return"Stash popped"}async function Lo(t){let n=await k(t).branchLocal();return n.all.map((r)=>({name:r,current:r===n.current,tracking:n.branches[r]?.label||void 0}))}async function Bo(t,e){return await k(t).raw(["switch","--",e]),`Switched to ${e}`}async function Ho(t,e){return await k(t).raw(["switch","-c",e]),`Created ${e}`}async function Wo(t,e=1){return await k(t).reset(["--soft",`HEAD~${e}`]),"Reset done"}async function Go(t,e){return await k(t,{longRunning:!0}).raw(["cherry-pick","--end-of-options",e]),"Cherry-picked"}async function Uo(t,e){return await k(t,{longRunning:!0}).raw(["revert","--no-edit","--end-of-options",e]),"Reverted"}async function te(t){let e=k(t),n;try{n=(await e.raw(["rev-parse","--absolute-git-dir"])).trim()}catch(s){return w(`git rev-parse --absolute-git-dir failed in ${t}: ${Zt(s)}`),null}let r=(s)=>Oe.existsSync(ur.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 jo(t){let e=await te(t);if(!e)throw Error("No operation in progress to abort");return await k(t).raw([e,"--abort"]),`Aborted ${e}`}async function qo(t){return await k(t,{longRunning:!0}).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function Xo(t){return(await k(t).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((r)=>r.length>0)}import*as Pt from"node:fs";import*as re from"node:path";import*as ee from"node:fs";import*as Ne from"node:path";function dr(){return Ne.join(Yt(),"base-branches.json")}function zo(){let t=dr();try{return JSON.parse(ee.readFileSync(t,"utf-8"))}catch(e){if(e.code!=="ENOENT")w("Ignoring the base-branch cache",e,{file:t});return{}}}function Du(t){rn(dr()),ee.writeFileSync(dr(),JSON.stringify(t,null,2)+`
|
|
24
|
+
`)}function an(t){return $e()(t)}function $e(){let t=zo();return(e)=>t[Ne.resolve(e)]}function Jo(t,e){let n=Object.fromEntries(Object.entries(zo()).filter(([s])=>ee.existsSync(s))),r=Ne.resolve(t);n[r]=e,Du(n)}function Le(t){let e=Math.min(t.length,8192);for(let n=0;n<e;n++)if(t[n]===0)return!0;return!1}var Ko={staged:!1,unstaged:!1,untracked:!1};class cn extends Error{constructor(t){super(`No common history with ${t}`);this.name="NoCommonHistoryError"}}var Ft=3,Zo=1e5;function ln(t){return t instanceof Error?t.message:String(t)}function un(t,e,n){w(`${t} failed in ${e}, answering an empty diff: ${ln(n)}`)}async function ti(t,e,n=!1,r={}){let s=k(t);try{let o=[`-U${r.context??Ft}`];if(n)o.push("--cached");o.push("--",e);let i=mt(await s.diff(o));return{lines:gt(i)}}catch(o){return un(`git diff${n?" --cached":""} -- ${e}`,t,o),{lines:[]}}}async function ei(t,e){let n=k(t),r=[`-U${Ft}`];if(e)r.push("--cached");return{lines:gt(mt(await n.diff(r)))}}var Tu="4b825dc642cb6eb9a060e54bf8d69288fbee4904",ni="(unborn)",Iu=/unknown revision|ambiguous argument 'HEAD'|needed a single revision/i;async function fn(t){let e=k(t);try{return(await e.raw(["rev-parse","HEAD"])).trim()}catch(n){let r=n instanceof Error?n.message:String(n);if(Iu.test(r))return ni;throw n}}async function ri(t,e){let n=k(t),s=(e??await fn(t))===ni?Tu:"HEAD",o=mt(await n.raw(["diff",`-U${Ft}`,s,"--"]));return{lines:gt(o)}}var Mu=Pe;function pr(t,e={}){let n=Qt(`a/${t}`),r=Qt(`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 Cu(t,e){return{lines:[...pr(t),{type:"header",content:cr(e)}]}}function Pu(t){return{lines:pr(t,{binary:!0})}}function Fu(t,e){let n=re.resolve(t),r=re.resolve(n,e);if(r!==n&&!r.startsWith(n+re.sep))return null;let s,o;try{s=Pt.realpathSync(r),o=Pt.realpathSync(n)}catch{return null}if(s!==o&&!s.startsWith(o+re.sep))return null;let i=Pt.statSync(s);if(!i.isFile())return null;return{path:r,size:i.size}}async function Ot(t,e){try{let n=Fu(t,e);if(n===null)return{lines:[]};if(n.size>Mu)return Cu(e,n.size);let r=Pt.readFileSync(n.path);if(Le(r))return Pu(e);let s=r.toString("utf-8"),o=pr(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=Mt(o),l=mt(c);if(l!==c)return{lines:gt(l)};return{lines:o}}catch(n){return
|
|
27
|
-
`)){let c=o.exec(a);if(c)for(let l of c[1].split(",")){let u=l.trim().replace(/^.*-> /,"");if(!u.startsWith(
|
|
28
|
-
`).filter(Boolean),r=new Map,s=await e.raw(["for-each-ref","--format=%(refname) %(objectname) %(symref)"
|
|
29
|
-
`)){let[i,a,c=""]=o.split(" ");if(i)r.set(i,{commit:a,symref:c})}return
|
|
30
|
-
`);return Ct(e===-1?t:t.slice(0,e))}function
|
|
31
|
-
`)[0],author:y.author_name,date:new Date(y.date),refs:y.refs||""}));return{baseBranch:e,stats:{filesChanged:h.length,additions:d,deletions:m},files:h,commits:R,uncommittedCount:g}}async function
|
|
32
|
-
`),"utf8").toString("utf8"),o=Nt.get(s);if(o!==void 0)return Nt.delete(s),Nt.set(s,o),o;let i=await r();if(Nt.set(s,i),Nt.size>Yu)Nt.delete(Nt.keys().next().value);return i}function
|
|
33
|
-
`))if(r.startsWith("worktree ")){if(n)e.push(n);n={path:r.slice(9).trim(),branch:null,head:null,isBare:!1,isMain:e.length===0}}else if(!n)continue;else if(r.startsWith("HEAD "))n.head=r.slice(5).trim();else if(r.startsWith("branch "))n.branch=r.slice(7).trim().replace(/^refs\/heads\//,"");else if(r==="bare")n.isBare=!0;if(n)e.push(n);return e}function
|
|
34
|
-
`);return Mr(r,oe,o.bytes),Mr(r,Le,i),gn(e,{...s,top:o,adopted:{bytes:i}})}function pf(t,e){if(t.branch===e.branch)return 0;return t.branch<e.branch?-1:1}function Tr(t){return t!==null&&t.bytes.toString("utf8").trim()!==""}function mf(t,e){let n=At(t,oe,!0),r=At(t,Le,!0),s=At(t,Ar,!0),o=At(t,Dr,!0),i=[n,r,s,o].filter((a)=>a!==null);if(i.length===0)return null;return{branch:e,hasTop:Tr(n),hasSuggested:Tr(s),hasAi:Tr(o),top:mn(n),adoptedUnedited:xi(n,r),mtime:Math.max(...i.map((a)=>a.mtimeMs))}}function gf(t,e){try{return mf(t,e)}catch(n){if(!(n instanceof Dt)&&ce(n)===null)throw n;let r=n instanceof Dt?N.join(t,n.file):t;return w("Draft left out of the scan",n,{file:r}),null}}async function wf(t){try{return await P.promises.readdir(t,{withFileTypes:!0})}catch(e){let n=ce(e);if(n==="ENOENT"||n==="ENOTDIR")return null;if(n===null)throw e;return w("Draft directory left out of the scan",e,{file:t}),null}}function yf(t,e){if(e.depth>=cf)return[];return t.filter((n)=>n.isDirectory()).map((n)=>({rel:e.rel===""?n.name:`${e.rel}/${n.name}`,depth:e.depth+1}))}function Ef(t,e){return t!==""&&e.some((n)=>n.isFile()&&dn.includes(n.name))&&Ri(t)===null}function bf(t){try{return Cr(t,N.resolve(Be(t))),!0}catch(e){if(!(e instanceof $t))throw e;return w("Drafts left out of the scan",e,{file:Be(t)}),!1}}async function Ti(t){if(!bf(t))return[];let e=Be(t),n=[],r=[{rel:"",depth:0}];for(let s=0;r.length>0&&s<af;s++){let o=r.pop(),i=N.join(e,o.rel),a=await wf(i);if(a===null)continue;r.push(...yf(a,o));let c=Ef(o.rel,a)?gf(i,o.rel):null;if(c!==null)n.push(c)}return n.sort(pf)}var Ir=`${hn.join("/")}/`;function Ii(t,e){if(t===hn[0]||t===Ir.slice(0,-1))return{branch:"",prefix:!0};if(!t.startsWith(Ir))return null;let n=t.slice(Ir.length);if(n==="")return{branch:"",prefix:!0};if(e)return{branch:n,prefix:!0};let r=n.lastIndexOf("/");if(r<=0)return null;if(!dn.includes(n.slice(r+1)))return null;return{branch:n.slice(0,r),prefix:!1}}var If=Tl(Wi(),1);function Gi(t){return Ct(t)}function En(t){let e=new Map,n=null;for(let s of t.lines){if(s.type==="header"&&s.content.startsWith("diff --git")){let o=Gi(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 bn="diffstalker-journal: oversize untracked snapshot omitted";var Cf=100,Pf="diffstalker",Ui="diffstalker/pr";function Ff(t){return t==="info"||t==="refs"||t.startsWith("refs/")||t===Pf||t===Ui||t.startsWith(`${Ui}/`)}var Of=262144,Nf=new Set(["EACCES","EPERM","ENOENT","ENOTDIR"]),$f=new Set(["index","HEAD","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","rebase-merge","rebase-apply"]),Lf=100,Bf=1000,Hf=4;function Wf(t,e,n){return Math.max(Lf,qi(t,e,n))}function qi(t,e,n){return e+Math.max(Bf,Hf*n)-t}function ji(t){return t===".git"||t.endsWith("/.git")}function Gf(t){let e=t?.code;return typeof e==="string"&&Nf.has(e)}function Uf(){return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1}}class Rn extends Mf{repoPath;queue;hunkTimes;watchers=[];treeWatcher=null;watchGeneration=0;ignoreRules=null;reloadingRules=!1;reloadRulesAgain=!1;disposed=!1;viewed=!1;_stale=!0;changeTimer=null;draftTimers=new Map;changedDuringRefresh=!1;lastFullRefreshEnd=0;lastFullRefreshMs=0;_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 Er(t)}get state(){return this._state}_wholeTreeDiffs=null;fullRefreshRunning=!1;fullRefreshesBegun=0;refreshWaiters=[];async wholeTreeDiffs(){if(await this.catchUp(),this._wholeTreeDiffs)return this._wholeTreeDiffs;if(this.fullRefreshRunning)await this.fullRefreshEnding(this.fullRefreshesBegun-1);else await this.freshFullRefresh();return this._wholeTreeDiffs}async catchUp(){if(this._stale)await this.freshFullRefresh();else if(this._state.status===null&&this.fullRefreshRunning)await this.fullRefreshEnding(this.fullRefreshesBegun-1)}freshFullRefresh(){let t=this.fullRefreshEnding(this.fullRefreshesBegun);if(this.pendingRefreshKind!=="full")this.refresh().catch((e)=>{C("Refresh for a read threw",e,{repo:this.repoPath})});return t}fullRefreshEnding(t){return new Promise((e)=>this.refreshWaiters.push({after:t,resolve:e}))}settleRefreshWaiters(t){let e=this.refreshWaiters;this.refreshWaiters=[];for(let n of e)if(t===null||t>n.after)n.resolve();else this.refreshWaiters.push(n)}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)}startWatching(){let t=Y(this.repoPath);if(t===null)return;let e=++this.watchGeneration;this.watchGitDirs(t),this.watchWorkingTree(t,e).catch((n)=>{C("Starting the working tree watcher threw",n,{repo:this.repoPath})})}reviveWatchers(){if(this.disposed||!this.watchers.some((t)=>t.rootGone))return;G("Watching again: a watched root came back",void 0,{repo:this.repoPath});for(let t of this.watchers)t.close();this.watchers=[],this.treeWatcher=null,this.gitDirs=void 0,this.startWatching()}watchGitDirs(t){let e=(s)=>{if(s.endsWith(".lock"))return;if(s==="info/exclude"||s==="info")this.reloadIgnoreRules(),this.onRepoChange();else if(s==="packed-refs"||s==="refs"||s.startsWith("refs/"))this.onRepoChange()},n=(s)=>{if($f.has(s))this.onRepoChange()},r=(s)=>this.onWatchError("Git dir watcher error",s);if(this.watchers.push(new De(t.commonDir,{skipDir:(s)=>!Ff(s),onChange:(s,o)=>{let i=Ii(s,o);if(i!==null){this.noteDraftChange(i);return}if(e(s),t.gitDir===t.commonDir)n(s)},onError:r})),t.gitDir!==t.commonDir)this.watchers.push(new De(t.gitDir,{skipDir:()=>!0,onChange:n,onError:r}));for(let s of this.watchers)s.start().catch((o)=>{C("Starting a git dir watcher threw",o,{repo:this.repoPath})})}noteDraftChange(t){if(this.disposed)return;let e=`${t.prefix}:${t.branch}`;if(this.draftTimers.has(e))return;let n=setTimeout(()=>{if(this.draftTimers.delete(e),!this.disposed)this.emit("draft-change",t)},Cf);n.unref(),this.draftTimers.set(e,n)}async watchWorkingTree(t,e){let n=await sr(this.repoPath,t.commonDir);if(this.disposed||e!==this.watchGeneration)return;this.ignoreRules=n;let r=new De(this.repoPath,{skipDir:(s)=>ji(s)||this.ignored(s,!0),onChange:(s,o)=>this.onWorkingTreeEntry(s,o),onError:(s)=>this.onWatchError("Working dir watcher error",s)});this.treeWatcher=r,this.watchers.push(r),await r.start()}ignored(t,e){return this.ignoreRules?.ignores(t,e)??!1}onWorkingTreeEntry(t,e){if(t===""){this.onRepoChange();return}if(ji(t))return;if(t===".gitignore"||t.endsWith("/.gitignore"))this.reloadIgnoreRules();else if(this.ignored(t,e))return;this.onRepoChange()}async reloadIgnoreRules(){if(this.reloadingRules){this.reloadRulesAgain=!0;return}let t=Y(this.repoPath);if(t===null||this.treeWatcher===null)return;this.reloadingRules=!0;try{do{if(this.reloadRulesAgain=!1,this.ignoreRules=await sr(this.repoPath,t.commonDir),this.disposed)return;await this.treeWatcher.resync()}while(this.reloadRulesAgain&&!this.disposed)}catch(e){C("Reloading the ignore rules threw",e,{repo:this.repoPath})}finally{this.reloadingRules=!1}}onWatchError(t,e){if(Gf(e)){G(t,e,{repo:this.repoPath});return}w(t,e,{repo:this.repoPath}),this.setError(`${t}: ${e instanceof Error?e.message:String(e)}`)}dispose(){this.disposed=!0;for(let t of this.watchers)t.close();if(this.watchers=[],this.treeWatcher=null,this.changeTimer!==null)clearTimeout(this.changeTimer);this.changeTimer=null;for(let t of this.draftTimers.values())clearTimeout(t);this.draftTimers.clear(),this.settleRefreshWaiters(null)}get stale(){return this._stale}markStale(){this._stale=!0,this._wholeTreeDiffs=null}setViewed(t){if(this.viewed=t,t&&this._stale)this.requestRefresh("full")}onRepoChange(){if(this.disposed)return;if(!this.viewed){this.markStale();return}this.scheduleChangeRefresh()}scheduleChangeRefresh(){if(this.changeTimer!==null)return;this.armChangeTimer(Wf(performance.now(),this.lastFullRefreshEnd,this.lastFullRefreshMs))}armChangeTimer(t){this.changeTimer=setTimeout(()=>{this.changeTimer=null,this.runChangeRefresh()},t)}runChangeRefresh(){if(this.disposed)return;if(!this.viewed){this.markStale();return}if(this.pendingRefreshKind==="full")return;if(this.fullRefreshRunning||this.queue.hasPendingMutations()){this.changedDuringRefresh=!0;return}let t=qi(performance.now(),this.lastFullRefreshEnd,this.lastFullRefreshMs);if(t>0){this.armChangeTimer(t);return}this.requestRefresh("full")}resumeDeferredChange(){if(!this.changedDuringRefresh)return;this.changedDuringRefresh=!1,this.scheduleChangeRefresh()}statMtimes(t){let e=new Map;for(let n of t.files){if(e.has(n.path))continue;try{e.set(n.path,Lt.statSync(We.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)w(`${e} (was open as one)`,void 0,{repo:this.repoPath});this.unavailableReason=e,this._wholeTreeDiffs=null,this.updateState({status:t,isLoading:!1,error:e})}refreshFailed(t,e){if(!Lt.existsSync(this.repoPath)){this.notARepo(Uf(),"Repository directory no longer exists");return}w(t,e,{repo:this.repoPath}),this.updateState({isLoading:!1,error:e instanceof Error?e.message:"Unknown error"})}async doStatusRefresh(){try{let t=await cr(this.repoPath);if(!t.isRepo){this.notARepo(t,"Not a git repository");return}this._wholeTreeDiffs=null,this.updateState({status:t,mtimes:this.statMtimes(t),isLoading:!1})}catch(t){this.refreshFailed("Status refresh failed",t)}finally{this.resumeDeferredChange()}}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.fullRefreshRunning=!0;let t=++this.fullRefreshesBegun;this._stale=!1;let e=performance.now();try{await this.readFullState()}finally{this.fullRefreshRunning=!1,this.lastFullRefreshEnd=performance.now(),this.lastFullRefreshMs=this.lastFullRefreshEnd-e,this.settleRefreshWaiters(t),this.resumeDeferredChange()}}async readFullState(){this.updateState({isLoading:!0,error:null});let t=Date.now(),e=await cn(this.repoPath).catch((n)=>(G("HEAD oid unreadable; journal observation skipped",n,{repo:this.repoPath}),null));try{let n=await cr(this.repoPath);if(!n.isRepo){this.notARepo(n,"Not a git repository");return}this.reviveWatchers();let r=await this.snapshotJournalGuard(n),{stashList:s,operation:o}=r,i=null,a=(x)=>Zo(this.repoPath,x).catch((v)=>(w(`Whole-tree diff${x?" --cached":""} failed`,v,{repo:this.repoPath}),i??=v instanceof Error?v.message:String(v),null)),c=await a(!0),l=a(!1),f=c!==null&&c.lines.length===0&&n.files.every((x)=>!x.staged&&x.status!=="conflicted")?async()=>{let x=await l;if(x===null)throw Error("the unstaged diff failed");return x}:(x)=>ei(this.repoPath,x),[h,d]=await Promise.all([l,this.gatherJournalInputs(n,e,t,r,f)]),m=h??{lines:[]},g=c??{lines:[]},R={unstaged:nn(Mt(m.lines)),staged:nn(Mt(g.lines))};this.hunkTimes.stampTree([m,g]);let y=this.statMtimes(n);if(this._wholeTreeDiffs={unstaged:m,staged:g},this.updateState({status:n,hunkCounts:R,stashList:s,operationInProgress:o,mtimes:y,isLoading:!1,error:i}),d!==null)this.emit("journal-observation",{status:n,headDiff:d.headDiff,headOid:d.headOid,stashCount:d.stashCount,operationInProgress:d.operationInProgress,mtimes:d.mtimes,at:Date.now()})}catch(n){this.refreshFailed("Refresh failed",n)}}async snapshotJournalGuard(t){let[e,n]=await Promise.all([Zt(this.repoPath),lr(this.repoPath)]);return{operation:e,stashList:n,mtimes:this.statMtimes(t),index:this.indexIdentity()}}gitDirs;indexIdentity(){if(this.gitDirs===void 0)this.gitDirs=Y(this.repoPath);if(this.gitDirs===null)return null;try{let t=Lt.statSync(We.join(this.gitDirs.gitDir,"index"));return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return null}}static journalGuardMoved(t,e){if(t.operation!==e.operation||t.stashList.length!==e.stashList.length)return!0;if(t.index!==e.index)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=Lt.statSync(We.join(this.repoPath,s));if(Math.floor(o.mtimeMs)>n)return!0}catch{}return!1}async gatherJournalInputs(t,e,n,r,s){if(e===null)return null;try{let o=await s(e),i=new Set(En(o).keys()),a=[...o.lines];await this.appendUntrackedSections(t,i,a);let c=await cn(this.repoPath);if(e!==c)return null;let l=await this.snapshotJournalGuard(t);if(Rn.journalGuardMoved(r,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(o){return G("Journal observation skipped: git read failed",o,{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=Lt.statSync(We.join(this.repoPath,s.path))}catch{continue}if(!o.isFile())continue;if(o.size>Of){this.appendOversizeSection(s.path,o,n);continue}let i=await Ot(this.repoPath,s.path);if(i.lines.length===0)continue;n.push(...i.lines)}}appendOversizeSection(t,e,n){let r=[`diff --git ${Vt("a/"+t)} ${Vt("b/"+t)}`,"new file mode 100644",`${bn} size=${e.size} mtime=${Math.round(e.mtimeMs)}`];n.push(...r.map((s)=>({type:"header",content:s})))}failed(t,e,n){w(`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(()=>yo(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(()=>Eo(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()=>Ao(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.failed("stage hunk",e)}}async unstageHunk(t){try{await this.queue.enqueueMutation(async()=>Do(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"?()=>ko(this.repoPath,t.path):()=>So(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(()=>bo(this.repoPath)),await this.refresh()}catch(t){this.failed("stage all",t)}}async unstageAll(){try{await this.queue.enqueueMutation(()=>Ro(this.repoPath)),await this.refresh()}catch(t){this.failed("unstage all",t)}}async commit(t,e=!1){try{await this.queue.enqueue(()=>xo(this.repoPath,t,e)),await this.refresh()}catch(n){this.failed("commit",n)}}async loadStashList(){try{let t=await this.queue.enqueue(()=>lr(this.repoPath));this.updateState({stashList:t})}catch(t){w("Failed to load the stash list",t,{repo:this.repoPath})}}}import{EventEmitter as jf}from"node:events";class Br extends jf{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){w(`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",()=>To(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>Io(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>Mo(this.repoPath))}async stash(t){if(this._remoteState.inProgress)return null;let e=await this.runRemoteOperation("stash",()=>Fo(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",()=>Oo(this.repoPath,t));return await this.callbacks.loadStashList(),e}async switchBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>$o(this.repoPath,t))}async createBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>Lo(this.repoPath,t))}async softReset(t=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>Bo(this.repoPath,t))}async cherryPick(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>Ho(this.repoPath,t))}async revertCommit(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>Wo(this.repoPath,t))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>Go(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>Uo(this.repoPath))}}import{EventEmitter as qf}from"node:events";import{randomBytes as Xf}from"node:crypto";var zf=262144,Jf=500,Yf=16777216,Ji=Number.MAX_SAFE_INTEGER,Kf=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function Vf(t){let e=Kf.exec(t);if(!e)return null;return{oldStart:parseInt(e[1],10),oldCount:e[2]!==void 0?parseInt(e[2],10):1}}function Qf(t,e){let n=Vf(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=Zf(o,r),r++;else if(a==="+")o=o??{hasDel:!1,delStart:0,delEnd:0,anchor:r-1};else Xi(s,o),o=null,r++}return Xi(s,o),s}function Zf(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 Xi(t,e){if(!e)return;t.push(e.hasDel?[2*e.delStart,2*e.delEnd]:[2*e.anchor,2*e.anchor+2])}function Wr(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>=Ji)return{start:0,count:0};let r=Math.ceil(e/2),s=Math.floor(n/2);return{start:r,count:s-r+1}}function th(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(bn));return{hunks:[{runs:[[0,Ji]],bodyHash:ln([Mt(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=Qf(a,i.content),l=[],u=0,f=0;for(let d of a){let m=d.content[0];if(m==="\\")continue;if(m==="+")u++,l.push(d.content);else if(m==="-")f++,l.push(d.content)}let h=[...e,i,...a];return{runs:c,bodyHash:ln(l),ins:u,del:f,span:Wr(c),diff:{lines:h}}}),renamedFrom:n,hunkless:!1}}function Hr(t){return Buffer.from(t,"utf8").toString("utf8")}function eh(t){if(t.oversize===!0)return null;if(en(t.diff.lines)>zf)return null;return{lines:t.diff.lines.map(nh)}}function nh(t){let e={type:t.type,content:Hr(t.content)};if(t.oldLineNum!==void 0)e.oldLineNum=t.oldLineNum;if(t.newLineNum!==void 0)e.newLineNum=t.newLineNum;return e}function rh(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 zi(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 sh(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=zi(t,0),i=zi(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 oh(t,e){let n=sh(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 ih(t,e,n){let r=[],s=e.map(()=>null),o=n;for(let i of oh(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:Wr(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":rh(h.ins,h.del,u),span:h.span,stats:{insertions:h.ins,deletions:h.del},diff:eh(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 ah(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 Sn(){return{entries:[],epoch:`${Date.now().toString(36)}-${Xf(4).toString("hex")}`,nextSeq:1,prunedBefore:0,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class Gr extends qf{store;constructor(t){super();this.store=t}get journalStore(){return this.store}observe(t){try{this.doObserve(t)}catch(e){C("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+=en(n.diff.lines);for(let n of this.store.entries){if(e<=Yf)return;if(n.type!=="hunk"||n.diff===null||t.has(n.seq))continue;e-=en(n.diff.lines),n.diff=null}}pruneEntries(t){let e=this.store.entries,n=-Jf;for(let r of e)if(!t.has(r.seq))n++;if(n<=0)return;this.store.entries=e.filter((r)=>{if(n===0||t.has(r.seq))return!0;return n--,this.store.prunedBefore=r.seq,!1})}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}=ah(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:Wr(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}=ih(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 En(t.headDiff))e.set(Hr(r),th(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:Hr(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 Ur{workingTree;remote;journal;repoPath;constructor(t,e){this.repoPath=t;let n=Qs(t);this.workingTree=new Rn(t,n),this.remote=new Br(t,n,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new Gr(e??Sn()),this.workingTree.on("journal-observation",(r)=>this.journal.observe(r))}dispose(){this.workingTree.dispose(),Zs(this.repoPath)}}function lh(t){return ch("sha256").update(t).digest("hex").slice(0,12)}var uh=32,fh=600000,hh=4;class Yi{cap;stores=new Map;constructor(t=uh){this.cap=t}acquire(t){let e=this.stores.get(t);if(e)this.stores.delete(t);else e=Sn();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 kn 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 jr{events;byId=new Map;byPath=new Map;lingering=new Map;journalStores=new Yi;lingerMs;lingerCap;constructor(t={},e={}){this.events=t,this.lingerMs=e.lingerMs??fh,this.lingerCap=e.lingerCap??hh}async openRepo(t){let e=await un(t,{mustExist:!1});if(!e.ok)throw new kn(e.reason,e.requested);let n=e.root,r=this.byPath.get(n);if(r)return r.refCount++,{handle:r,created:!1};let s=this.takeLingering(n);if(s)return s.refCount=1,this.byId.set(s.id,s),this.byPath.set(n,s),this.journalStores.acquire(s.id),s.manager.workingTree.markStale(),this.events.onOpened?.(s),{handle:s,created:!1};let o=lh(n),i=new Ur(n,this.journalStores.acquire(o));i.workingTree.startWatching();let a={id:o,path:n,manager:i,refCount:1};return this.byId.set(a.id,a),this.byPath.set(n,a),this.pruneJournalStores(),this.events.onOpened?.(a),{handle:a,created:!0}}takeLingering(t){let e=this.lingering.get(t);if(!e)return null;if(clearTimeout(e.timer),this.lingering.delete(t),e.handle.manager.workingTree.unavailable)return e.handle.manager.dispose(),null;return e.handle}pruneJournalStores(){let t=new Set([...this.lingering.values()].map((e)=>e.handle.id));this.journalStores.prune((e)=>this.byId.has(e)||t.has(e))}getRepo(t){return this.byId.get(t)}listRepos(){return[...this.byId.values()]}closeRepo(t){let e=this.byId.get(t);if(!e)return!1;if(e.refCount--,e.refCount>0)return!1;return this.byId.delete(e.id),this.byPath.delete(e.path),this.linger(e),this.events.onClosed?.(e.id),!0}linger(t){if(this.lingering.size>=this.lingerCap){let n=this.lingering.keys().next().value;this.disposeLingering(n)}let e=setTimeout(()=>this.disposeLingering(t.path),this.lingerMs);e.unref(),this.lingering.set(t.path,{handle:t,timer:e})}disposeLingering(t){let e=this.lingering.get(t);if(!e)return;clearTimeout(e.timer),this.lingering.delete(t),e.handle.manager.dispose()}disposeAll(){for(let t of this.byId.values())t.manager.dispose();this.byId.clear(),this.byPath.clear();for(let t of[...this.lingering.keys()])this.disposeLingering(t)}}function dh(t){t.manager.workingTree.refresh().catch((e)=>{C("First refresh threw",e,{repo:t.path})})}async function xn(t,e){let n=await t.openRepo(e);if(n.created)dh(n.handle);return n}var Vi=25000;function Bt(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=Mt(o),l=mt(c);if(l!==c)return{lines:gt(l)};return{lines:o}}catch(n){return un(`reading untracked file ${e}`,t,n),{lines:[]}}}var Be="refs/remotes/";async function si(t){let e=k(t),n=new Set,r=[];try{let s=await e.raw(["log","--oneline","--decorate=full","--all","-n","200"]),o=/\(([^)]+)\)/g;for(let a of s.split(`
|
|
27
|
+
`)){let c=o.exec(a);if(c)for(let l of c[1].split(",")){let u=l.trim().replace(/^.*-> /,"");if(!u.startsWith(Be))continue;let f=u.slice(Be.length);if(f.endsWith("/HEAD")||n.has(f))continue;n.add(f),r.push(f)}o.lastIndex=0}let i=(a)=>{let c=a.split("/").slice(1).join("/");return c==="main"||c==="master"};r.sort((a,c)=>Number(i(c))-Number(i(a)))}catch(s){w(`git log for base-branch discovery failed in ${t}: ${ln(s)}`)}return r}var Yo=["upstream","origin"];function Vo(t){let e=Yo.indexOf(t);return e===-1?Yo.length:e}async function mr(t){let e=k(t),n=(await e.raw(["remote"])).split(`
|
|
28
|
+
`).filter(Boolean),r=new Map,s=await e.raw(["for-each-ref","--format=%(refname) %(objectname) %(symref)",Be]);for(let o of s.split(`
|
|
29
|
+
`)){let[i,a,c=""]=o.split(" ");if(i)r.set(i,{commit:a,symref:c})}return gr(n,r)}function gr(t,e){let n=[];for(let r of t){let s=`${Be}${r}/`,o=e.get(`${s}HEAD`)?.symref,i=o&&e.has(o)?o:[`${s}main`,`${s}master`].find((a)=>e.has(a));if(i)n.push({remote:r,ref:i,commit:e.get(i).commit})}return n}async function Ou(t,e,n="HEAD"){let r=await k(t).raw(["rev-list","--count",`${e}..${n}`]);return parseInt(r.trim(),10)}function wr(t){let e=[...t].sort((n,r)=>n.ahead-r.ahead||Vo(n.remote)-Vo(r.remote)||(n.remote<r.remote?-1:1))[0];return e?{branch:e.ref.slice(Be.length),ahead:e.ahead}:null}async function Nu(t){try{let e=await mr(t),n=await Promise.all(e.map(async({remote:r,ref:s})=>({remote:r,ref:s,ahead:await Ou(t,s)})));return wr(n)}catch(e){return w(`default base-branch discovery failed in ${t}: ${ln(e)}`),null}}async function yr(t){return(await Nu(t))?.branch??null}async function Er(t){return an(t)??await yr(t)}async function wt(t,e){let n=k(t);try{return await n.raw(["cat-file","-e","--end-of-options",`${e}^{commit}`]),!0}catch{return!1}}function $u(t){let e=t.indexOf(`
|
|
30
|
+
`);return Ct(e===-1?t:t.slice(0,e))}function oi(t,e,n){let r=Fe(t),s=new Map;for(let a of lr(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=$u(a);if(c===null)continue;let l=gt(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 Lu(t,e,n){let r=k(t);return ii(r,e,r.status(),n)}async function ii(t,e,n,r="HEAD",s){let o=await br(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(ne(i,["--numstat","-z"])),t.raw(ne(i,["--name-status","-z"])),t.raw(ne(i,[`-U${Ft}`])).then(mt),n,t.log({from:o,to:r})]),h=oi(a,c,l),d=0,m=0;for(let y of h)d+=y.additions,m+=y.deletions;let g=u.length,R=f.all.map((y)=>({hash:y.hash,shortHash:y.hash.slice(0,7),message:y.message.split(`
|
|
31
|
+
`)[0],author:y.author_name,date:new Date(y.date),refs:y.refs||""}));return{baseBranch:e,stats:{filesChanged:h.length,additions:d,deletions:m},files:h,commits:R,uncommittedCount:g}}async function ai(t,e,n="HEAD"){let r=k(t),s=await br(r,e,n),o=await r.raw(["rev-list","--count","--end-of-options",`${s}..${n}`]);return Number.parseInt(o.trim(),10)}async function ci(t,e,n="HEAD"){return br(k(t),e,n)}async function br(t,e,n){let r=(await t.raw(["merge-base","--end-of-options",e,n])).trim();if(!r)throw new cn(e);return r}function ne(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 Bu(t,e,n){let r=k(t),s=ne(e,["--name-status","-z","-M","--diff-filter=R"]),o;try{o=await r.raw(s)}catch(i){return w(`rename lookup for ${n} failed in ${t}: ${ln(i)}`),null}return lr(o).find((i)=>i.path===n)?.oldPath??null}async function Rr(t,e,n,r={}){let s=k(t),o=r.context??Ft;try{let i=await Bu(t,e,n),a=i===null?[n]:[i,n],c=ne(e,["-M",`-U${o}`]),l=mt(await s.raw([...c,"--",...a]));return{lines:gt(l)}}catch(i){return un(`git ${ne(e,[]).join(" ")} -- ${n}`,t,i),{lines:[]}}}async function li(t,e){let n=k(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${Ft}`]).then(mt)]);return oi(s,o,i)}async function ui(t,e){let n=k(t);try{let r=mt(await n.raw(["show","--format=",`-U${Ft}`,"--end-of-options",e]));return{lines:gt(r)}}catch(r){return un(`git show ${e}`,t,r),{lines:[]}}}function Hu(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 Qo(t){return t!==""&&t!==" "&&t!=="?"&&t!=="!"}function Wu(t,e,n){let r=new Set,s=new Set;for(let o of e.files){if(Qo(o.index)){if(r.add(o.path),o.from)r.add(o.from)}if(n==="worktree"&&Qo(o.working_dir))s.add(o.path)}return t.map((o)=>{let i=Gu(r.has(o.path),s.has(o.path));return i===null?o:{...o,uncommitted:i}})}function Gu(t,e){if(t&&e)return"both";if(t)return"staged";if(e)return"unstaged";return null}async function Uu(t,e){let n=e.files.filter((o)=>o.working_dir==="?").map((o)=>o.path),r=await Vt(t,n),s=[];for(let o of n){if(r.has(o))continue;let i=await Ot(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 fi(t,e,n=Ko,r){let s=Hu(n);if(s===null&&!n.untracked)return Lu(t,e,r);if(r!==void 0)throw Error("Uncommitted work can only be compared against HEAD, not a named head");let o=k(t),i=o.status(),[a,c,l]=await Promise.all([ii(o,e,i,"HEAD",s??void 0),i,n.untracked?i.then((h)=>Uu(t,h)):[]]),f=[...s===null?a.files:Wu(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 di from"node:fs";import*as pi from"node:path";function hn(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 hi(t){let e=[],n="",r=null,s=()=>{if(r&&n)e.push({file:n,key:`${n}\x00${hn(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=Ct(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 Sr{repoPath;stamps=new Map;constructor(t){this.repoPath=t}stamp(t){if(t)this.stampHunks(hi(t))}stampTree(t){let e=t.flatMap((r)=>hi(r));this.stampHunks(e);let n=new Set(e.map((r)=>r.key));for(let r of this.stamps.keys())if(!n.has(r))this.stamps.delete(r)}stampHunks(t){let e=new Map;for(let n of 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}}mtimeOf(t){try{return di.statSync(pi.join(this.repoPath,t)).mtimeMs}catch{return Date.now()}}}import*as at from"node:fs";import*as X from"node:path";async function ju(t){let e=Ar(t);if(!e)return null;try{let n=k(e);if((await n.raw(["rev-parse","--is-bare-repository"])).trim()==="true")return null;return(await n.raw(["rev-parse","--show-toplevel"])).trim()||null}catch(n){return G("rev-parse failed",n,{dir:e}),null}}async function dn(t,{mustExist:e}){let n=ot(t);if(!X.isAbsolute(n))return{ok:!1,reason:"not-absolute",requested:n};if(e&&!mi(n))return{ok:!1,reason:"not-a-repo",requested:n};let r=await ju(n);if(r)return{ok:!0,root:r};let s=rf(await kr(n));return s?{ok:!0,root:s.path}:{ok:!1,reason:"not-a-repo",requested:n}}function mi(t){try{return at.statSync(t).isDirectory()}catch{return!1}}async function kr(t,{pooled:e=!1}={}){let n=Ar(t);if(!n)return[];try{return await gi(n,e)}catch(r){return G("worktree list failed",r,{dir:n}),[]}}async function gi(t,e){let n=()=>k(t).raw(["worktree","list","--porcelain"]);return sf(await(e?pn.run(n):n()))}async function xr(t){return(await Xu(t)).map(qu)}function qu({baseBranch:t,...e}){return e}async function Xu(t){let e=Ar(t);if(!e)return[];let n;try{n=await gi(e,!1)}catch(r){return G("worktree list failed",r,{dir:e}),[]}return vr(n,await zu(e),$e())}async function zu(t){try{return await mr(t)}catch(e){return w("default base-branch discovery failed",e,{repo:t}),null}}async function vr(t,e,n){let r=await nf(t,e,n);return t.map((s)=>({...s,lastActivity:s.isBare?null:Ju(yi(s.path)),aheadOfBase:r.get(s.path)?.ahead??null,baseBranch:r.get(s.path)?.base??null}))}function Ju(t){return Number.isFinite(t)?t:null}class wi{size;active=0;waiting=[];constructor(t){this.size=t}async run(t){if(this.active>=this.size)await new Promise((e)=>this.waiting.push(e));this.active++;try{return await t()}finally{this.active--,this.waiting.shift()?.()}}}var Ku=8,pn=new wi(Ku);function He(t){return pn.run(t)}var Yu=8192,Nt=new Map,Vu=1048576,Qu=/^0+$/;async function Zu(t,e,n,r){let s=Buffer.from([t,e,...[...n].sort()].join(`
|
|
32
|
+
`),"utf8").toString("utf8"),o=Nt.get(s);if(o!==void 0)return Nt.delete(s),Nt.set(s,o),o;let i=await r();if(Nt.set(s,i),Nt.size>Yu)Nt.delete(Nt.keys().next().value);return i}function _r(t,e,n){return Zu(t,e,n,async()=>{let r=await pn.run(()=>_t(t,[...dt,"rev-list","--count",e,"--not",...n],Vu));return parseInt(r.toString("utf8").trim(),10)})}async function tf(t,e){if(t.head===null||Qu.test(t.head))return null;let n=t.head;try{let r=await Promise.all(e.map(async({remote:o,ref:i,commit:a})=>({remote:o,ref:i,ahead:await _r(t.path,n,[a])}))),s=wr(r);return s===null?null:{ahead:s.ahead,base:s.branch}}catch(r){return w("default base-branch count failed",r,{worktree:t.path}),null}}async function ef(t,e){try{let n=k(t),r=await pn.run(()=>n.raw(["rev-list","--count","--end-of-options",`${e}..HEAD`]));return parseInt(r.trim(),10)}catch{return null}}async function nf(t,e,n){let r=await Promise.all(t.filter((s)=>!s.isBare&&mi(s.path)).map(async(s)=>{let o=n(s.path),i=null;if(o!==void 0){let a=await ef(s.path,o);i=a===null?null:{ahead:a,base:o}}else if(e!==null)i=await tf(s,e);return i===null?null:[s.path,i]}));return new Map(r.filter((s)=>s!==null))}function rf(t){let e=null,n=-1/0;for(let r of t){if(r.isBare)continue;let s=yi(r.path);if(s>n)n=s,e=r}return e}function yi(t){let e=Ei(t),n=e?[X.join(e,"HEAD"),X.join(e,"logs","HEAD")]:[t],r=-1/0;for(let s of n)try{let o=at.statSync(s).mtimeMs;if(o>r)r=o}catch{}return r}function Ei(t){let e=X.join(t,".git");try{if(at.statSync(e).isDirectory())return e;let n=at.readFileSync(e,"utf8").match(/^gitdir:\s*(.+)$/m);if(!n)return null;let r=n[1].trim();return X.isAbsolute(r)?r:X.resolve(t,r)}catch{return null}}function K(t){let e=Ei(t);if(e===null)return null;let n=e;try{let r=at.readFileSync(X.join(e,"commondir"),"utf8").trim();if(r)n=X.isAbsolute(r)?r:X.resolve(e,r)}catch{}return{gitDir:e,commonDir:n}}function sf(t){let e=[],n=null;for(let r of t.split(`
|
|
33
|
+
`))if(r.startsWith("worktree ")){if(n)e.push(n);n={path:r.slice(9).trim(),branch:null,head:null,isBare:!1,isMain:e.length===0}}else if(!n)continue;else if(r.startsWith("HEAD "))n.head=r.slice(5).trim();else if(r.startsWith("branch "))n.branch=r.slice(7).trim().replace(/^refs\/heads\//,"");else if(r==="bare")n.isBare=!0;if(n)e.push(n);return e}function Ar(t){try{if(at.statSync(t).isDirectory())return t;return X.dirname(t)}catch{let e=X.dirname(t);return e!==t&&at.existsSync(e)?e:null}}import*as P from"node:fs";import*as N from"node:path";import{createHash as of}from"node:crypto";import*as Dr from"node:fs";var se=Dr.constants.O_RDONLY|(Dr.constants.O_NONBLOCK??0);async function oe(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 mn=["diffstalker","pr"],ie="top.md",Tr="top.suggested.md",Ir="ai.md",We="adopted",gn=["top.md","top.suggested.md","ai.md","adopted"],bi="absent",ae=262144,Ri=10,wn=300;class $t extends Error{constructor(t){super(t);this.name="DraftBranchError"}}class Dt extends Error{file;constructor(t,e){super(e);this.file=t,this.name="DraftFileError"}}class ce extends Error{constructor(t){super(t);this.name="DraftConflictError"}}var af=255,cf=500,lf=8,uf=se|P.constants.O_NOFOLLOW;function ki(t){if(t.length===0)return"Branch name is empty";if(t.length>af)return"Branch name is too long";if(t.startsWith("-"))return'Branch name must not start with "-"';if(/[\x00-\x1f\x7f]/.test(t))return"Branch name contains a control character";if(t.includes("\\"))return"Branch name contains a backslash";if(t.startsWith("/")||t.endsWith("/"))return'Branch name must not start or end with "/"';for(let e of t.split("/")){if(e==="")return"Branch name has an empty path component";if(e.startsWith("."))return'Branch name has a path component that starts with "."';if(e.endsWith(".lock"))return'Branch name has a path component that ends in ".lock"';if(gn.includes(e.toLowerCase()))return`Branch name has a path component named like a draft file (${e})`}return null}function Ge(t){return N.join(t,...mn)}function le(t){return t?.code??null}function xi(t,e){return t.startsWith(e+N.sep)}function Fr(t,e){let n=N.resolve(t),r=n;for(let s of N.relative(n,e).split(N.sep)){r=N.join(r,s);let o;try{o=P.lstatSync(r)}catch(i){let a=le(i);if(a==="ENOENT"||a==="ENOTDIR")return;throw i}if(o.isSymbolicLink())throw new $t(`${N.relative(n,r)} is a symbolic link`);if(!o.isDirectory())return}}async function Or(t,e){let n=ki(e);if(n!==null)throw new $t(n);let r=N.resolve(Ge(t)),s=N.resolve(r,...e.split("/"));if(!xi(s,r))throw new $t("Branch name leaves the drafts directory");return Fr(t,s),s}function ff(t,e){if(!e.isFile())throw new Dt(t,`${t} is not a regular file`);if(e.size>ae)throw new Dt(t,`${t} is larger than ${ae} bytes`)}function At(t,e,n){let r;try{r=P.openSync(N.join(t,e),uf)}catch(s){let o=le(s);if(o==="ENOENT"||o==="ENOTDIR")return null;if(o==="ELOOP")throw new Dt(e,`${e} is a symbolic link`);throw s}try{let s=P.fstatSync(r);if(ff(e,s),!n)return{bytes:Buffer.alloc(0),mtimeMs:s.mtimeMs};let o=Buffer.alloc(s.size),i=0;while(i<o.length){let a=P.readSync(r,o,i,o.length-i,i);if(a===0)break;i+=a}return{bytes:i===o.length?o:o.subarray(0,i),mtimeMs:s.mtimeMs}}finally{P.closeSync(r)}}function Nr(t){return of("sha256").update(t).digest("hex")}function vi(t){return t===null?bi:Nr(t.bytes)}function yn(t){return t===null?null:t.bytes.toString("utf8")}function _i(t,e){return t!==null&&e!==null&&e.bytes.toString("utf8").trim()===Nr(t.bytes)}function Ai(t){return{top:At(t,ie,!0),adopted:At(t,We,!0),suggested:At(t,Tr,!0),ai:At(t,Ir,!0)}}function En(t,e){return{branch:t,top:yn(e.top),suggested:yn(e.suggested),ai:yn(e.ai),adoptedUnedited:_i(e.top,e.adopted),version:vi(e.top)}}async function $r(t,e){return En(e,Ai(await Or(t,e)))}var hf=0;function Pr(t,e,n){let r=N.join(t,`.${e}.${process.pid}.${++hf}.tmp`);try{P.writeFileSync(r,n,{flag:"wx"}),P.renameSync(r,N.join(t,e))}catch(s){throw P.rmSync(r,{force:!0}),s}}function df(t,e){P.mkdirSync(e,{recursive:!0}),Fr(t,e)}function Si(t){try{P.unlinkSync(t)}catch(e){if(le(e)!=="ENOENT")throw e}}function pf(t,e){for(let n=e;xi(n,t);n=N.dirname(n))try{P.rmdirSync(n)}catch(r){let s=le(r);if(s==="ENOENT")continue;if(s==="ENOTEMPTY"||s==="EEXIST"||s==="ENOTDIR")return;throw r}}function Di(t,e){let n=Ai(t);if(vi(n.top)!==e)throw new ce("Draft changed elsewhere");return n}async function Ti(t,e,n,r){let s=await Or(t,e),o=Di(s,r);if(n.trim()==="")return Si(N.join(s,ie)),Si(N.join(s,We)),pf(N.resolve(Ge(t)),s),En(e,{...o,top:null,adopted:null});let i=Buffer.from(n,"utf8");return df(t,s),Pr(s,ie,i),En(e,{...o,top:{bytes:i}})}async function Ii(t,e,n){let r=await Or(t,e),s=Di(r,n);if(s.top!==null&&s.top.bytes.toString("utf8").trim()!=="")throw new ce("top.md is not empty");let o=s.suggested;if(o===null||o.bytes.toString("utf8").trim()==="")throw new ce("No suggestion to start from");let i=Buffer.from(`${Nr(o.bytes)}
|
|
34
|
+
`);return Pr(r,ie,o.bytes),Pr(r,We,i),En(e,{...s,top:o,adopted:{bytes:i}})}function mf(t,e){if(t.branch===e.branch)return 0;return t.branch<e.branch?-1:1}function Mr(t){return t!==null&&t.bytes.toString("utf8").trim()!==""}function gf(t,e){let n=At(t,ie,!0),r=At(t,We,!0),s=At(t,Tr,!0),o=At(t,Ir,!0),i=[n,r,s,o].filter((a)=>a!==null);if(i.length===0)return null;return{branch:e,hasTop:Mr(n),hasSuggested:Mr(s),hasAi:Mr(o),top:yn(n),adoptedUnedited:_i(n,r),mtime:Math.max(...i.map((a)=>a.mtimeMs))}}function wf(t,e){try{return gf(t,e)}catch(n){if(!(n instanceof Dt)&&le(n)===null)throw n;let r=n instanceof Dt?N.join(t,n.file):t;return w("Draft left out of the scan",n,{file:r}),null}}async function yf(t){try{return await P.promises.readdir(t,{withFileTypes:!0})}catch(e){let n=le(e);if(n==="ENOENT"||n==="ENOTDIR")return null;if(n===null)throw e;return w("Draft directory left out of the scan",e,{file:t}),null}}function Ef(t,e){if(e.depth>=lf)return[];return t.filter((n)=>n.isDirectory()).map((n)=>({rel:e.rel===""?n.name:`${e.rel}/${n.name}`,depth:e.depth+1}))}function bf(t,e){return t!==""&&e.some((n)=>n.isFile()&&gn.includes(n.name))&&ki(t)===null}function Rf(t){try{return Fr(t,N.resolve(Ge(t))),!0}catch(e){if(!(e instanceof $t))throw e;return w("Drafts left out of the scan",e,{file:Ge(t)}),!1}}async function Mi(t){if(!Rf(t))return[];let e=Ge(t),n=[],r=[{rel:"",depth:0}];for(let s=0;r.length>0&&s<cf;s++){let o=r.pop(),i=N.join(e,o.rel),a=await yf(i);if(a===null)continue;r.push(...Ef(a,o));let c=bf(o.rel,a)?wf(i,o.rel):null;if(c!==null)n.push(c)}return n.sort(mf)}var Cr=`${mn.join("/")}/`;function Ci(t,e){if(t===mn[0]||t===Cr.slice(0,-1))return{branch:"",prefix:!0};if(!t.startsWith(Cr))return null;let n=t.slice(Cr.length);if(n==="")return{branch:"",prefix:!0};if(e)return{branch:n,prefix:!0};let r=n.lastIndexOf("/");if(r<=0)return null;if(!gn.includes(n.slice(r+1)))return null;return{branch:n.slice(0,r),prefix:!1}}var Mf=Il(Ui(),1);function ji(t){return Ct(t)}function Sn(t){let e=new Map,n=null;for(let s of t.lines){if(s.type==="header"&&s.content.startsWith("diff --git")){let o=ji(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 kn="diffstalker-journal: oversize untracked snapshot omitted";var Pf=100,Ff="diffstalker",qi="diffstalker/pr";function Of(t){return t==="info"||t==="refs"||t.startsWith("refs/")||t===Ff||t===qi||t.startsWith(`${qi}/`)}var Nf=262144,$f=new Set(["EACCES","EPERM","ENOENT","ENOTDIR"]),Lf=new Set(["index","HEAD","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","rebase-merge","rebase-apply"]),Bf=100,Hf=1000,Wf=4;function Gf(t,e,n){return Math.max(Bf,zi(t,e,n))}function zi(t,e,n){return e+Math.max(Hf,Wf*n)-t}function Xi(t){return t===".git"||t.endsWith("/.git")}function Uf(t){let e=t?.code;return typeof e==="string"&&$f.has(e)}function jf(){return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1}}class xn extends Cf{repoPath;queue;hunkTimes;watchers=[];treeWatcher=null;watchGeneration=0;ignoreRules=null;reloadingRules=!1;reloadRulesAgain=!1;disposed=!1;viewed=!1;_stale=!0;changeTimer=null;draftTimers=new Map;changedDuringRefresh=!1;lastFullRefreshEnd=0;lastFullRefreshMs=0;_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 Sr(t)}get state(){return this._state}_wholeTreeDiffs=null;fullRefreshRunning=!1;fullRefreshesBegun=0;refreshWaiters=[];async wholeTreeDiffs(){if(await this.catchUp(),this._wholeTreeDiffs)return this._wholeTreeDiffs;if(this.fullRefreshRunning)await this.fullRefreshEnding(this.fullRefreshesBegun-1);else await this.freshFullRefresh();return this._wholeTreeDiffs}async catchUp(){if(this._stale)await this.freshFullRefresh();else if(this._state.status===null&&this.fullRefreshRunning)await this.fullRefreshEnding(this.fullRefreshesBegun-1)}freshFullRefresh(){let t=this.fullRefreshEnding(this.fullRefreshesBegun);if(this.pendingRefreshKind!=="full")this.refresh().catch((e)=>{C("Refresh for a read threw",e,{repo:this.repoPath})});return t}fullRefreshEnding(t){return new Promise((e)=>this.refreshWaiters.push({after:t,resolve:e}))}settleRefreshWaiters(t){let e=this.refreshWaiters;this.refreshWaiters=[];for(let n of e)if(t===null||t>n.after)n.resolve();else this.refreshWaiters.push(n)}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)}startWatching(){let t=K(this.repoPath);if(t===null)return;let e=++this.watchGeneration;this.watchGitDirs(t),this.watchWorkingTree(t,e).catch((n)=>{C("Starting the working tree watcher threw",n,{repo:this.repoPath})})}reviveWatchers(){if(this.disposed||!this.watchers.some((t)=>t.rootGone))return;G("Watching again: a watched root came back",void 0,{repo:this.repoPath});for(let t of this.watchers)t.close();this.watchers=[],this.treeWatcher=null,this.gitDirs=void 0,this.startWatching()}watchGitDirs(t){let e=(s)=>{if(s.endsWith(".lock"))return;if(s==="info/exclude"||s==="info")this.reloadIgnoreRules(),this.onRepoChange();else if(s==="packed-refs"||s==="refs"||s.startsWith("refs/"))this.onRepoChange()},n=(s)=>{if(Lf.has(s))this.onRepoChange()},r=(s)=>this.onWatchError("Git dir watcher error",s);if(this.watchers.push(new Ie(t.commonDir,{skipDir:(s)=>!Of(s),onChange:(s,o)=>{let i=Ci(s,o);if(i!==null){this.noteDraftChange(i);return}if(e(s),t.gitDir===t.commonDir)n(s)},onError:r})),t.gitDir!==t.commonDir)this.watchers.push(new Ie(t.gitDir,{skipDir:()=>!0,onChange:n,onError:r}));for(let s of this.watchers)s.start().catch((o)=>{C("Starting a git dir watcher threw",o,{repo:this.repoPath})})}noteDraftChange(t){if(this.disposed)return;let e=`${t.prefix}:${t.branch}`;if(this.draftTimers.has(e))return;let n=setTimeout(()=>{if(this.draftTimers.delete(e),!this.disposed)this.emit("draft-change",t)},Pf);n.unref(),this.draftTimers.set(e,n)}async watchWorkingTree(t,e){let n=await ar(this.repoPath,t.commonDir);if(this.disposed||e!==this.watchGeneration)return;this.ignoreRules=n;let r=new Ie(this.repoPath,{skipDir:(s)=>Xi(s)||this.ignored(s,!0),onChange:(s,o)=>this.onWorkingTreeEntry(s,o),onError:(s)=>this.onWatchError("Working dir watcher error",s)});this.treeWatcher=r,this.watchers.push(r),await r.start()}ignored(t,e){return this.ignoreRules?.ignores(t,e)??!1}onWorkingTreeEntry(t,e){if(t===""){this.onRepoChange();return}if(Xi(t))return;if(t===".gitignore"||t.endsWith("/.gitignore"))this.reloadIgnoreRules();else if(this.ignored(t,e))return;this.onRepoChange()}async reloadIgnoreRules(){if(this.reloadingRules){this.reloadRulesAgain=!0;return}let t=K(this.repoPath);if(t===null||this.treeWatcher===null)return;this.reloadingRules=!0;try{do{if(this.reloadRulesAgain=!1,this.ignoreRules=await ar(this.repoPath,t.commonDir),this.disposed)return;await this.treeWatcher.resync()}while(this.reloadRulesAgain&&!this.disposed)}catch(e){C("Reloading the ignore rules threw",e,{repo:this.repoPath})}finally{this.reloadingRules=!1}}onWatchError(t,e){if(Uf(e)){G(t,e,{repo:this.repoPath});return}w(t,e,{repo:this.repoPath}),this.setError(`${t}: ${e instanceof Error?e.message:String(e)}`)}dispose(){this.disposed=!0;for(let t of this.watchers)t.close();if(this.watchers=[],this.treeWatcher=null,this.changeTimer!==null)clearTimeout(this.changeTimer);this.changeTimer=null;for(let t of this.draftTimers.values())clearTimeout(t);this.draftTimers.clear(),this.settleRefreshWaiters(null)}get stale(){return this._stale}markStale(){this._stale=!0,this._wholeTreeDiffs=null}setViewed(t){if(this.viewed=t,t&&this._stale)this.requestRefresh("full")}onRepoChange(){if(this.disposed)return;if(!this.viewed){this.markStale();return}this.scheduleChangeRefresh()}scheduleChangeRefresh(){if(this.changeTimer!==null)return;this.armChangeTimer(Gf(performance.now(),this.lastFullRefreshEnd,this.lastFullRefreshMs))}armChangeTimer(t){this.changeTimer=setTimeout(()=>{this.changeTimer=null,this.runChangeRefresh()},t)}runChangeRefresh(){if(this.disposed)return;if(!this.viewed){this.markStale();return}if(this.pendingRefreshKind==="full")return;if(this.fullRefreshRunning||this.queue.hasPendingMutations()){this.changedDuringRefresh=!0;return}let t=zi(performance.now(),this.lastFullRefreshEnd,this.lastFullRefreshMs);if(t>0){this.armChangeTimer(t);return}this.requestRefresh("full")}resumeDeferredChange(){if(!this.changedDuringRefresh)return;this.changedDuringRefresh=!1,this.scheduleChangeRefresh()}statMtimes(t){let e=new Map;for(let n of t.files){if(e.has(n.path))continue;try{e.set(n.path,Lt.statSync(je.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)w(`${e} (was open as one)`,void 0,{repo:this.repoPath});this.unavailableReason=e,this._wholeTreeDiffs=null,this.updateState({status:t,isLoading:!1,error:e})}refreshFailed(t,e){if(!Lt.existsSync(this.repoPath)){this.notARepo(jf(),"Repository directory no longer exists");return}w(t,e,{repo:this.repoPath}),this.updateState({isLoading:!1,error:e instanceof Error?e.message:"Unknown error"})}async doStatusRefresh(){try{let t=await fr(this.repoPath);if(!t.isRepo){this.notARepo(t,"Not a git repository");return}this._wholeTreeDiffs=null,this.updateState({status:t,mtimes:this.statMtimes(t),isLoading:!1})}catch(t){this.refreshFailed("Status refresh failed",t)}finally{this.resumeDeferredChange()}}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.fullRefreshRunning=!0;let t=++this.fullRefreshesBegun;this._stale=!1;let e=performance.now();try{await this.readFullState()}finally{this.fullRefreshRunning=!1,this.lastFullRefreshEnd=performance.now(),this.lastFullRefreshMs=this.lastFullRefreshEnd-e,this.settleRefreshWaiters(t),this.resumeDeferredChange()}}async readFullState(){this.updateState({isLoading:!0,error:null});let t=Date.now(),e=await fn(this.repoPath).catch((n)=>(G("HEAD oid unreadable; journal observation skipped",n,{repo:this.repoPath}),null));try{let n=await fr(this.repoPath);if(!n.isRepo){this.notARepo(n,"Not a git repository");return}this.reviveWatchers();let r=await this.snapshotJournalGuard(n),{stashList:s,operation:o}=r,i=null,a=(x)=>ei(this.repoPath,x).catch((v)=>(w(`Whole-tree diff${x?" --cached":""} failed`,v,{repo:this.repoPath}),i??=v instanceof Error?v.message:String(v),null)),c=await a(!0),l=a(!1),f=c!==null&&c.lines.length===0&&n.files.every((x)=>!x.staged&&x.status!=="conflicted")?async()=>{let x=await l;if(x===null)throw Error("the unstaged diff failed");return x}:(x)=>ri(this.repoPath,x),[h,d]=await Promise.all([l,this.gatherJournalInputs(n,e,t,r,f)]),m=h??{lines:[]},g=c??{lines:[]},R={unstaged:on(Mt(m.lines)),staged:on(Mt(g.lines))};this.hunkTimes.stampTree([m,g]);let y=this.statMtimes(n);if(this._wholeTreeDiffs={unstaged:m,staged:g},this.updateState({status:n,hunkCounts:R,stashList:s,operationInProgress:o,mtimes:y,isLoading:!1,error:i}),d!==null)this.emit("journal-observation",{status:n,headDiff:d.headDiff,headOid:d.headOid,stashCount:d.stashCount,operationInProgress:d.operationInProgress,mtimes:d.mtimes,at:Date.now()})}catch(n){this.refreshFailed("Refresh failed",n)}}async snapshotJournalGuard(t){let[e,n]=await Promise.all([te(this.repoPath),hr(this.repoPath)]);return{operation:e,stashList:n,mtimes:this.statMtimes(t),index:this.indexIdentity()}}gitDirs;indexIdentity(){if(this.gitDirs===void 0)this.gitDirs=K(this.repoPath);if(this.gitDirs===null)return null;try{let t=Lt.statSync(je.join(this.gitDirs.gitDir,"index"));return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return null}}static journalGuardMoved(t,e){if(t.operation!==e.operation||t.stashList.length!==e.stashList.length)return!0;if(t.index!==e.index)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=Lt.statSync(je.join(this.repoPath,s));if(Math.floor(o.mtimeMs)>n)return!0}catch{}return!1}async gatherJournalInputs(t,e,n,r,s){if(e===null)return null;try{let o=await s(e),i=new Set(Sn(o).keys()),a=[...o.lines];await this.appendUntrackedSections(t,i,a);let c=await fn(this.repoPath);if(e!==c)return null;let l=await this.snapshotJournalGuard(t);if(xn.journalGuardMoved(r,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(o){return G("Journal observation skipped: git read failed",o,{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=Lt.statSync(je.join(this.repoPath,s.path))}catch{continue}if(!o.isFile())continue;if(o.size>Nf){this.appendOversizeSection(s.path,o,n);continue}let i=await Ot(this.repoPath,s.path);if(i.lines.length===0)continue;n.push(...i.lines)}}appendOversizeSection(t,e,n){let r=[`diff --git ${Qt("a/"+t)} ${Qt("b/"+t)}`,"new file mode 100644",`${kn} size=${e.size} mtime=${Math.round(e.mtimeMs)}`];n.push(...r.map((s)=>({type:"header",content:s})))}failed(t,e,n){w(`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(()=>bo(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(()=>Ro(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()=>To(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.failed("stage hunk",e)}}async unstageHunk(t){try{await this.queue.enqueueMutation(async()=>Io(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"?()=>vo(this.repoPath,t.path):()=>xo(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(()=>So(this.repoPath)),await this.refresh()}catch(t){this.failed("stage all",t)}}async unstageAll(){try{await this.queue.enqueueMutation(()=>ko(this.repoPath)),await this.refresh()}catch(t){this.failed("unstage all",t)}}async commit(t,e=!1){try{await this.queue.enqueue(()=>_o(this.repoPath,t,e)),await this.refresh()}catch(n){this.failed("commit",n)}}async loadStashList(){try{let t=await this.queue.enqueue(()=>hr(this.repoPath));this.updateState({stashList:t})}catch(t){w("Failed to load the stash list",t,{repo:this.repoPath})}}}import{EventEmitter as qf}from"node:events";class Wr extends qf{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){w(`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",()=>Mo(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>Co(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>Po(this.repoPath))}async stash(t){if(this._remoteState.inProgress)return null;let e=await this.runRemoteOperation("stash",()=>No(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",()=>$o(this.repoPath,t));return await this.callbacks.loadStashList(),e}async switchBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>Bo(this.repoPath,t))}async createBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>Ho(this.repoPath,t))}async softReset(t=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>Wo(this.repoPath,t))}async cherryPick(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>Go(this.repoPath,t))}async revertCommit(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>Uo(this.repoPath,t))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>jo(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>qo(this.repoPath))}}import{EventEmitter as Xf}from"node:events";import{randomBytes as zf}from"node:crypto";var Jf=262144,Kf=500,Yf=16777216,Yi=Number.MAX_SAFE_INTEGER,Vf=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function Qf(t){let e=Vf.exec(t);if(!e)return null;return{oldStart:parseInt(e[1],10),oldCount:e[2]!==void 0?parseInt(e[2],10):1}}function Zf(t,e){let n=Qf(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=th(o,r),r++;else if(a==="+")o=o??{hasDel:!1,delStart:0,delEnd:0,anchor:r-1};else Ji(s,o),o=null,r++}return Ji(s,o),s}function th(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 Ji(t,e){if(!e)return;t.push(e.hasDel?[2*e.delStart,2*e.delEnd]:[2*e.anchor,2*e.anchor+2])}function Ur(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>=Yi)return{start:0,count:0};let r=Math.ceil(e/2),s=Math.floor(n/2);return{start:r,count:s-r+1}}function eh(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(kn));return{hunks:[{runs:[[0,Yi]],bodyHash:hn([Mt(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=Zf(a,i.content),l=[],u=0,f=0;for(let d of a){let m=d.content[0];if(m==="\\")continue;if(m==="+")u++,l.push(d.content);else if(m==="-")f++,l.push(d.content)}let h=[...e,i,...a];return{runs:c,bodyHash:hn(l),ins:u,del:f,span:Ur(c),diff:{lines:h}}}),renamedFrom:n,hunkless:!1}}function Gr(t){return Buffer.from(t,"utf8").toString("utf8")}function nh(t){if(t.oversize===!0)return null;if(sn(t.diff.lines)>Jf)return null;return{lines:t.diff.lines.map(rh)}}function rh(t){let e={type:t.type,content:Gr(t.content)};if(t.oldLineNum!==void 0)e.oldLineNum=t.oldLineNum;if(t.newLineNum!==void 0)e.newLineNum=t.newLineNum;return e}function sh(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 Ki(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 oh(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=Ki(t,0),i=Ki(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 ih(t,e){let n=oh(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 ah(t,e,n){let r=[],s=e.map(()=>null),o=n;for(let i of ih(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:Ur(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":sh(h.ins,h.del,u),span:h.span,stats:{insertions:h.ins,deletions:h.del},diff:nh(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 ch(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 vn(){return{entries:[],epoch:`${Date.now().toString(36)}-${zf(4).toString("hex")}`,nextSeq:1,prunedBefore:0,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class jr extends Xf{store;constructor(t){super();this.store=t}get journalStore(){return this.store}observe(t){try{this.doObserve(t)}catch(e){C("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+=sn(n.diff.lines);for(let n of this.store.entries){if(e<=Yf)return;if(n.type!=="hunk"||n.diff===null||t.has(n.seq))continue;e-=sn(n.diff.lines),n.diff=null}}pruneEntries(t){let e=this.store.entries,n=-Kf;for(let r of e)if(!t.has(r.seq))n++;if(n<=0)return;this.store.entries=e.filter((r)=>{if(n===0||t.has(r.seq))return!0;return n--,this.store.prunedBefore=r.seq,!1})}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}=ch(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:Ur(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}=ah(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 Sn(t.headDiff))e.set(Gr(r),eh(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:Gr(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 qr{workingTree;remote;journal;repoPath;constructor(t,e){this.repoPath=t;let n=to(t);this.workingTree=new xn(t,n),this.remote=new Wr(t,n,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new jr(e??vn()),this.workingTree.on("journal-observation",(r)=>this.journal.observe(r))}dispose(){this.workingTree.dispose(),eo(this.repoPath)}}function uh(t){return lh("sha256").update(t).digest("hex").slice(0,12)}var fh=32,hh=600000,dh=4;class Vi{cap;stores=new Map;constructor(t=fh){this.cap=t}acquire(t){let e=this.stores.get(t);if(e)this.stores.delete(t);else e=vn();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 _n 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 Xr{events;byId=new Map;byPath=new Map;lingering=new Map;journalStores=new Vi;lingerMs;lingerCap;constructor(t={},e={}){this.events=t,this.lingerMs=e.lingerMs??hh,this.lingerCap=e.lingerCap??dh}async openRepo(t){let e=await dn(t,{mustExist:!1});if(!e.ok)throw new _n(e.reason,e.requested);let n=e.root,r=this.byPath.get(n);if(r)return r.refCount++,{handle:r,created:!1};let s=this.takeLingering(n);if(s)return s.refCount=1,this.byId.set(s.id,s),this.byPath.set(n,s),this.journalStores.acquire(s.id),s.manager.workingTree.markStale(),this.events.onOpened?.(s),{handle:s,created:!1};let o=uh(n),i=new qr(n,this.journalStores.acquire(o));i.workingTree.startWatching();let a={id:o,path:n,manager:i,refCount:1};return this.byId.set(a.id,a),this.byPath.set(n,a),this.pruneJournalStores(),this.events.onOpened?.(a),{handle:a,created:!0}}takeLingering(t){let e=this.lingering.get(t);if(!e)return null;if(clearTimeout(e.timer),this.lingering.delete(t),e.handle.manager.workingTree.unavailable)return e.handle.manager.dispose(),null;return e.handle}pruneJournalStores(){let t=new Set([...this.lingering.values()].map((e)=>e.handle.id));this.journalStores.prune((e)=>this.byId.has(e)||t.has(e))}getRepo(t){return this.byId.get(t)}listRepos(){return[...this.byId.values()]}closeRepo(t){let e=this.byId.get(t);if(!e)return!1;if(e.refCount--,e.refCount>0)return!1;return this.byId.delete(e.id),this.byPath.delete(e.path),this.linger(e),this.events.onClosed?.(e.id),!0}linger(t){if(this.lingering.size>=this.lingerCap){let n=this.lingering.keys().next().value;this.disposeLingering(n)}let e=setTimeout(()=>this.disposeLingering(t.path),this.lingerMs);e.unref(),this.lingering.set(t.path,{handle:t,timer:e})}disposeLingering(t){let e=this.lingering.get(t);if(!e)return;clearTimeout(e.timer),this.lingering.delete(t),e.handle.manager.dispose()}disposeAll(){for(let t of this.byId.values())t.manager.dispose();this.byId.clear(),this.byPath.clear();for(let t of[...this.lingering.keys()])this.disposeLingering(t)}}function ph(t){t.manager.workingTree.refresh().catch((e)=>{C("First refresh threw",e,{repo:t.path})})}async function An(t,e){let n=await t.openRepo(e);if(n.created)ph(n.handle);return n}var Zi=25000;function Bt(t,e,n){t.write(`event: ${e}
|
|
35
35
|
data: ${n}
|
|
36
36
|
|
|
37
|
-
`)}function
|
|
37
|
+
`)}function ta(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Qi(t,e){Bt(t,"repo-missing",JSON.stringify({id:e}))}class zr{channels=new Map;subscribe(t,e,n,r){ta(r),this.join(t,e,n,r,{owned:!0})}attach(t,e,n,r){if(!e){Qi(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(kt(l));if(u===c.lastData)return;c.lastData=u;for(let f of a.keys())Bt(f,"state-change",u)},journalListener:(l)=>{let u=JSON.stringify({epoch:e.journal.journalStore.epoch,entries:l});for(let f of a.keys())Bt(f,"journal-append",u)},draftListener:(l)=>{let u=JSON.stringify(l);for(let f of a.keys())Bt(f,"draft-change",u)},keepAlive:setInterval(()=>{for(let[l,{owned:u}]of a)if(u)l.write(`: ping
|
|
38
38
|
|
|
39
|
-
`)},
|
|
39
|
+
`)},Zi),lastData:null};e.workingTree.on("state-change",c.listener),e.journal.on("append",c.journalListener),e.workingTree.on("draft-change",c.draftListener),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(kt(e.workingTree.state));Bt(r,s.owned?"snapshot":"repo-snapshot",i),e.workingTree.setViewed(!0)}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.setViewed(!1),e.manager.workingTree.off("state-change",e.listener),e.manager.journal.off("append",e.journalListener),e.manager.workingTree.off("draft-change",e.draftListener),clearInterval(e.keepAlive);for(let[n,{owned:r}]of e.subscribers)if(r)n.end();else Qi(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 Jr{subscribers=new Set;keepAlive=null;subscribe(t,e,n){if(ta(e),this.subscribers.add(e),!this.keepAlive)this.keepAlive=setInterval(()=>{for(let r of this.subscribers)r.write(`: ping
|
|
40
40
|
|
|
41
|
-
`)},
|
|
42
|
-
`,{mode:384}),tt.renameSync(e,this.file)}catch(n){throw tt.rmSync(e,{force:!0}),n}return this.current}}import*as
|
|
43
|
-
`)[0]?.trim();e(s?s:null)})})},writable(t){try{return Tt.accessSync(t,Tt.constants.W_OK),!0}catch{return!1}}};function Nh(){let t=yt.dirname(Mh(new URL("../package.json",import.meta.url)));try{return Tt.realpathSync(t)}catch{return t}}function aa(t=Nh(),e=ts){let n=null;return{info(){return n??=Oh(t,e).catch((r)=>(w("Install detection failed",r,{dir:t}),ia)),n}}}import*as ca from"node:fs";var $h=/^[A-Za-z0-9:_.@-]+\.service$/,Lh=/^user@\d+\.service$/,Bh=/^0::(.*)$/m;function Hh(t){let e=Bh.exec(t);if(e===null)return null;let n=e[1].split("/"),r=n.at(-1)??"";if(!$h.test(r))return null;let s=r.slice(0,-8);return n.some((o)=>Lh.test(o))?`systemctl --user restart ${s}`:`sudo systemctl restart ${s}`}function la(t=process.pid,e=process.env,n=()=>ca.readFileSync("/proc/self/cgroup","utf-8")){if(e.SYSTEMD_EXEC_PID!==String(t))return null;try{return Hh(n())}catch(r){return w("Cannot read /proc/self/cgroup to name the systemd unit",r),null}}var Wh="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",Gh=21600000,Uh=300000,jh=5000;function es(){try{let t=fa.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 w("Cannot read the daemon version from its package.json",t),null}}async function qh(){let t=await fetch(Wh,{headers:{accept:"application/json"},signal:AbortSignal.timeout(jh)});if(!t.ok)return null;let e=await t.json();return typeof e.latest==="string"?e.latest:null}function ua(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());if(!e)return null;return[Number(e[1]),Number(e[2]),Number(e[3])]}function Xh(t,e){if(t===null||e===null)return"unknown";let n=ua(t),r=ua(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 ha(t=qh,e=es(),n=aa(),r=la()){let s=null,o=null;function i(){if(s&&Date.now()<s.expiresAt)return Promise.resolve(s.value);if(o)return o;return o=t().catch((a)=>(G("Latest version lookup failed",a),null)).then((a)=>{let c=a===null?Uh:Gh;return s={value:a,expiresAt:Date.now()+c},o=null,a}),o}return{async state(){let[a,c]=await Promise.all([i(),n.info()]);return{current:e,latest:a,status:Xh(e,a),install:c,restart:r}}}}import*as da from"node:os";function pa(t,e){t.get("/health",({res:n})=>{E(n,200,{ok:!0,ready:!0,home:da.homedir(),http:{port:e.httpPort()},symbols:{extensions:e.symbols?.extensions??[]},gh:e.prs.ghAvailable()})})}function ma(t,e){t.get("/version",async({res:n})=>{E(n,200,await e.version.state())})}import*as va from"node:fs";import*as ue from"node:fs";import*as j from"node:path";function fe(t,e){let n=t.getRepo(e);if(!n)throw new p(404,`Unknown repo id: ${e}`);return n}function S(t,e){let n=fe(t,e),r=n.manager.workingTree.unavailable;if(r!==null)throw new p(410,r);return n}function L(t,e,n){if(typeof t!=="object"||t===null)throw new p(400,`Expected a JSON body with "${e}"`);let r=t[e];if(typeof r!=="string"||!n?.allowEmpty&&r.length===0)throw new p(400,`Missing "${e}" (string) in body`);return r}function wa(t,e){if(t.length===0)throw new p(400,`Invalid "${e}" (expected a ref)`);if(t.startsWith("-"))throw new p(400,`Invalid "${e}" (must not start with "-"): ${t}`);return t}function et(t,e){return wa(L(t,e),e)}function Ue(t,e){let n=t.get(e);return n===null?null:wa(n,e)}function ya(t,e){if(typeof t!=="object"||t===null)throw new p(400,`Expected a JSON body with "${e}"`);let n=t[e];if(!Array.isArray(n)||n.some((r)=>typeof r!=="string"))throw new p(400,`Missing "${e}" (array of strings) in body`);return n}function Ea(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 p(400,`Invalid "${e}" (expected a non-empty string)`);return n}function ss(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 p(400,`Invalid "${e}" (expected an integer >= ${n.min})`);return r}function ba(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 p(400,`Invalid "${e}" (expected a boolean)`);return n}function V(t,e,n){let r=t.get(e);if(r===null){if(n===void 0)throw new p(400,`Missing "${e}" query parameter (expected true or false)`);return n}if(r==="true")return!0;if(r==="false")return!1;throw new p(400,`Invalid "${e}" (expected true or false): ${r}`)}function ct(t){let e=t.get("path");if(!e)throw new p(400,'Missing "path" query parameter');return e}function je(t,e){let n=V(t,"whole",!1);if(n&&!e)throw new p(400,"whole=true requires a path (one file at a time)");return n?Vo:void 0}function Ra(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 p(400,`Invalid "${e}" (expected a positive integer): ${s}`);if(r!==void 0&&o>r)throw new p(400,`Invalid "${e}" (must be <= ${r}): ${s}`);return o}async function Et(t){if(await t.catchUp(),!t.state.status)await t.refresh();let e=t.state.status;if(!e)throw new p(500,"Repository status unavailable");return e}function ga(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 he(t,e,n){let r=await Et(t),s=ga(r,e,n);if(!s)await t.refresh(),r=await Et(t),s=ga(r,e,n);if(!s)throw new p(404,`File not in status: ${e}`);return s}function rs(t,e){return t===e||t.startsWith(e+j.sep)}function os(t){return t.replace(/[. ]+$/,"").toLowerCase()===".git"}function Wt(t,e){if(e.length===0)throw new p(400,"Empty path");if(e.includes("\x00"))throw new p(400,"Path contains a NUL byte");let n=j.resolve(t),r=j.relative(n,j.resolve(n,e));if(r==="")throw new p(400,`Path resolves to the repository root: ${e}`);if(j.isAbsolute(r)||r===".."||r.startsWith(`..${j.sep}`))throw new p(400,`Path escapes repository root: ${e}`);if(r.startsWith("-"))throw new p(400,`Path must not start with "-": ${e}`);if(r.startsWith(":"))throw new p(400,`Path must not start with ":": ${e}`);if(r.split(j.sep).some(os))throw new p(400,`Path addresses the git directory: ${e}`);return r}async function Sa(t){try{return await ue.promises.realpath(t)}catch{return null}}var ns=new WeakMap;async function zh(t){let e=ns.get(t);if(!e)e=(async()=>{let n=await k(t.path).raw(["rev-parse","--absolute-git-dir"]);return await ue.promises.realpath(n.trim())})(),ns.set(t,e),e.catch(()=>ns.delete(t));try{return await e}catch(n){throw new p(500,"Cannot resolve the git directory for this repository",{cause:n})}}async function Gt(t,e){let n=await ue.promises.realpath(j.resolve(t.path)),r=await Sa(j.join(t.path,e));if(r===null)return;if(!rs(r,n))throw new p(400,`Path escapes repository root: ${e}`);if(rs(r,await zh(t)))throw new p(400,`Path addresses the git directory: ${e}`)}async function ka(t,e){let n=await ue.promises.realpath(j.resolve(t)),r=[];for(let s of e){let o=await Sa(j.join(t,s.path));if(o===null||rs(o,n))r.push(s)}return r}function _n(t){return t?.code??null}async function is(t){let e;try{e=await ue.promises.stat(t)}catch(n){let r=_n(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 Jh(t){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test(t)?409:500}function xa(t,e){return new p(t,e)}async function bt(t,e,n){t.clearError(),await n();let r=t.state.error;if(r)throw xa(Jh(r),r);await t.refresh(),E(e,200,{state:kt(t.state)})}var Yh=/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged|no tracking information|no upstream|no configured push destination/i;function Kh(t){return Yh.test(t)?409:500}async function Q(t,e,n){let r=t.manager.remote,s=()=>new p(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 xa(Kh(o.error),o.error);E(e,200,{state:kt(i.state),result:o.lastResult})}function Vh(t){if(t.reason==="not-a-repo"&&!va.existsSync(t.requested))return new p(404,`No such directory: ${t.requested}`,{cause:t});return new p(400,t.message,{cause:t})}async function Qh(t,e){let n=e.state.status;if(n&&!e.stale)return n.branch.current;let r=Y(t);return r===null?null:Vr(r.gitDir)}function _a(t,e){let{registry:n}=e;t.get("/repos",async({res:r})=>{let s=await Promise.all(n.listRepos().map(async(o)=>({id:o.id,path:o.path,branch:await Qh(o.path,o.manager.workingTree)})));E(r,200,s)}),t.post("/repos",async({body:r,res:s})=>{let o=L(r,"path"),i;try{i=await xn(n,o)}catch(a){if(a instanceof kn)throw Vh(a);throw a}E(s,i.created?201:200,{id:i.handle.id,path:i.handle.path})}),t.get("/resolve",async({query:r,res:s})=>{let o=ct(r),i=await un(o,{mustExist:!0});if(!i.ok&&i.reason==="not-absolute")throw new p(400,`Repo path must be absolute: ${i.requested}`);E(s,200,{openable:i.ok,root:i.ok?i.root:null})}),t.get("/repos/:id/worktrees",async({params:r,res:s})=>{let o=S(n,r.id);E(s,200,await Rr(o.path))}),t.get("/worktrees",async({query:r,res:s})=>{E(s,200,await Rr(ct(r)))}),t.delete("/repos/:id",({params:r,res:s})=>{fe(n,r.id),n.closeRepo(r.id),E(s,200,{})})}function Aa(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 Da(t){return t.trim()}async function Zh(t){let e=(r)=>r.filter((s)=>s.staged).length,n=e((await Et(t)).files);if(n===0)await t.refresh(),n=e((await Et(t)).files);return n}function Ta(t,e){let{registry:n,sse:r}=e;if(t.get("/repos/:id/status",async({params:s,res:o})=>{let i=fe(n,s.id);await Et(i.manager.workingTree),E(o,200,kt(i.manager.workingTree.state))}),t.get("/repos/:id/diff",async({params:s,query:o,res:i})=>{let a=S(n,s.id),c=a.manager.workingTree,l=o.get("path")??void 0,u=V(o,"staged",!1),f=je(o,l);if(!l){let R=await c.wholeTreeDiffs();if(!R){let y=c.unavailable;throw new p(y?410:500,y??"Repository diff unavailable")}E(i,200,u?R.staged:R.unstaged);return}let d=(await Et(c)).files.some((R)=>R.path===l&&R.status==="untracked");if(d&&u)throw new p(400,`staged=true is meaningless for untracked file: ${l} (untracked files have no staged diff)`);let m=f!==void 0&&!d,g=d?await Ot(a.path,l):await Qo(a.path,l,u,{context:f});if(!m)c.stampDiff(g);E(i,200,g)}),t.post("/repos/:id/stage",async({params:s,body:o,res:i})=>{let a=S(n,s.id),c=L(o,"path"),l=a.manager.workingTree,u=await he(l,c,!1);await bt(l,i,()=>l.stage(u))}),t.post("/repos/:id/unstage",async({params:s,body:o,res:i})=>{let a=S(n,s.id),c=L(o,"path"),l=a.manager.workingTree,u=await he(l,c,!0);await bt(l,i,()=>l.unstage(u))}),t.get("/repos/:id/events",({params:s,req:o,res:i})=>{let a=fe(n,s.id);r.subscribe(s.id,a.manager,o,i)}),e.apiMode==="full")td(t,e)}function td(t,e){let{registry:n}=e;t.post("/repos/:id/stage-all",async({params:r,res:s})=>{let i=S(n,r.id).manager.workingTree;await bt(i,s,()=>i.stageAll())}),t.post("/repos/:id/unstage-all",async({params:r,res:s})=>{let i=S(n,r.id).manager.workingTree;await bt(i,s,()=>i.unstageAll())}),t.post("/repos/:id/discard",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=L(s,"path"),c=i.manager.workingTree,l=await he(c,a,!1);if(l.staged)throw new p(409,`Cannot discard a staged file: ${a} (unstage it first)`);await bt(c,o,()=>c.discard(l))}),t.post("/repos/:id/commit",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=L(s,"message",{allowEmpty:!0}),c=ba(s,"amend"),l=i.manager.workingTree,u=await Zh(l),f=Aa(a,u,c);if(!f.valid)throw new p(400,f.error??"Invalid commit");await bt(l,o,()=>l.commit(Da(a),c))}),t.post("/repos/:id/stage-hunk",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=L(s,"patch"),c=i.manager.workingTree;await bt(c,o,()=>c.stageHunk(a))}),t.post("/repos/:id/unstage-hunk",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=L(s,"patch"),c=i.manager.workingTree;await bt(c,o,()=>c.unstageHunk(a))})}var ed=1000,An="refs/heads/",Ia="refs/remotes/";async function Ca(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(`
|
|
44
|
-
`)){if(!i)continue;let[a,c,l]=i.split(" ");if(l)continue;if(c.startsWith(
|
|
45
|
-
`).filter(Boolean).reverse()}async function
|
|
46
|
-
`),s=r.startsWith(
|
|
47
|
-
`).filter(Boolean)}function od(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 Na(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=od(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 id(t,e,n,r,s,o){let i=Pa(await Ca(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 Ma(t,a);if(c.length>1){let u=[...new Set(i.filter((f)=>Fa(f,o)).map((f)=>f.tip))];if(u.length>0)c=await Ma(t,u)}if(c.length!==1)return{layers:[],forked:!0};let l=await Oa(t,n,c[0]);return{layers:Na(l,s,null,o),forked:!1}}function ad(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 $a(t,e){let n=k(t),r=await sd(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([Ca(n,e),Oa(n,s,r.tip)]),a=nd(o),c=rd(o),l=new Map,u=new Set;for(let d of Pa(o,a)){let m=l.get(d.tip);if(m)m.push(d);else l.set(d.tip,[d]);if(Fa(d,c))u.add(d.tip)}let f=Na(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 id(n,e,r.tip,a,l,c);return{trunk:e,layers:ad([...f,...h.layers],u),forkedAbove:h.forked}}function as(t){if(!/^[0-9a-f]{4,40}$/i.test(t))throw new p(400,`Invalid commit hash: ${t}`);return t}async function La(t,e){if(!await wt(t,e))throw new p(404,`Unknown commit: ${e}`)}async function cs(t){try{return await t()}catch(e){if(e instanceof sn)throw new p(422,e.message,{cause:e});throw e}}async function cd(t){let e=await gr(t);if(e&&await wt(t,e))return e;if(rn(t)){let n=await mr(t);if(n&&await wt(t,n))return n}throw new p(422,"No usable base branch")}async function Dn(t,e){let n=Ue(e,"base");if(n===null)return cd(t);if(!await wt(t,n))throw new p(400,`Unknown base ref: ${n}`);return n}async function ls(t,e){let n=Ue(e,"head");if(n===null)return;if(!await wt(t,n))throw new p(400,`Unknown head ref: ${n}`);return n}function Ba(t,e){if(e&&t.get("head")!==null)throw new p(400,"head cannot be combined with uncommitted work (it only exists against HEAD)")}var ld=new Set(["staged","unstaged","both","untracked"]);function ud(t){let e=t.get("uncommitted");if(e===null)return null;if(!ld.has(e))throw new p(400,`Invalid "uncommitted" (expected staged, unstaged, both or untracked): ${e}`);return e}function fd(t){return{staged:V(t,"staged",!1),unstaged:V(t,"unstaged",!1),untracked:V(t,"untracked",!1)}}function hd(t){if(t.unstaged&&!t.staged)throw new p(400,"unstaged needs staged too (unstaged edits sit on top of staged ones)")}function Ha(t,e){let{registry:n}=e;if(t.get("/repos/:id/history",async({params:r,query:s,res:o})=>{let i=S(n,r.id),a=Ra(s,"count",100,5000);E(o,200,await Co(i.path,a))}),t.get("/repos/:id/commits/:hash",async({params:r,res:s})=>{let o=S(n,r.id),i=as(r.hash),a=await Po(o.path,i);if(a===null)throw new p(404,`Unknown commit: ${i}`);E(s,200,a)}),t.get("/repos/:id/commits/:hash/diff",async({params:r,query:s,res:o})=>{let i=S(n,r.id),a=as(r.hash);await La(i.path,a);let c=s.get("path")??void 0,l=je(s,c),u=c?await yr(i.path,{kind:"commit",hash:a},c,{context:l}):await ci(i.path,a);E(o,200,u)}),t.get("/repos/:id/commits/:hash/files",async({params:r,res:s})=>{let o=S(n,r.id),i=as(r.hash);await La(o.path,i),E(s,200,await ai(o.path,i))}),t.get("/repos/:id/compare/file",async({params:r,query:s,res:o})=>{let i=S(n,r.id),a=ct(s),c=je(s,a),l=ud(s);if(Ba(s,l!==null),l==="untracked"){E(o,200,await Ot(i.path,a));return}let u=await Dn(i.path,s),f=l===null?{kind:"compare",base:u,head:await ls(i.path,s)}:{kind:"compare-uncommitted",mergeBase:await cs(()=>ii(i.path,u)),tip:l==="staged"?"index":"worktree"};E(o,200,await yr(i.path,f,a,{context:c}))}),t.get("/repos/:id/head-message",async({params:r,res:s})=>{let o=S(n,r.id);E(s,200,{message:await vo(o.path)})}),t.get("/repos/:id/branches",async({params:r,res:s})=>{let o=S(n,r.id);E(s,200,await No(o.path))}),t.get("/repos/:id/base-branches",async({params:r,res:s})=>{let o=S(n,r.id);E(s,200,await ni(o.path))}),t.get("/repos/:id/compare/base",async({params:r,res:s})=>{let o=S(n,r.id);E(s,200,{base:await gr(o.path)})}),e.apiMode==="full")t.put("/repos/:id/compare/base",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=et(s,"branch");if(!await wt(i.path,a))throw new p(400,`Not a valid base ref: ${a}`);Xo(i.path,a),E(o,200,{base:a})});t.get("/repos/:id/compare/count",async({params:r,query:s,res:o})=>{let i=S(n,r.id),a=await Dn(i.path,s),c=await ls(i.path,s),l=await cs(()=>oi(i.path,a,c));E(o,200,{baseBranch:a,commits:l})}),t.get("/repos/:id/compare/stack",async({params:r,query:s,res:o})=>{let i=S(n,r.id),a=await Dn(i.path,s);E(o,200,await $a(i.path,a))}),t.get("/repos/:id/compare",async({params:r,query:s,res:o})=>{let i=S(n,r.id),a=fd(s);Ba(s,a.staged||a.unstaged||a.untracked),hd(a);let c=await Dn(i.path,s),l=await ls(i.path,s),u=await cs(()=>li(i.path,c,a,l));E(o,200,u)})}function dd(t){let e=t.get("since");if(e===null)return 0;if(!/^\d+$/.test(e))throw new p(400,`Invalid "since" (expected a non-negative integer): ${e}`);return Number(e)}function Wa(t,e){let{registry:n}=e;t.get("/repos/:id/journal",async({params:r,query:s,res:o})=>{let i=S(n,r.id),a=dd(s);await i.manager.workingTree.catchUp(),E(o,200,Hs(i.manager.journal.journalStore,a))})}function Ga(t,e){let{registry:n}=e;t.post("/repos/:id/push",async({params:r,res:s})=>{let o=S(n,r.id);await Q(o,s,()=>o.manager.remote.push())}),t.post("/repos/:id/fetch",async({params:r,res:s})=>{let o=S(n,r.id);await Q(o,s,()=>o.manager.remote.fetchRemote())}),t.post("/repos/:id/pull",async({params:r,res:s})=>{let o=S(n,r.id);await Q(o,s,()=>o.manager.remote.pullRebase())}),t.post("/repos/:id/stash",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=Ea(s,"message");await Q(i,o,()=>i.manager.remote.stash(a))}),t.post("/repos/:id/stash-pop",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=ss(s,"index",{min:0,fallback:0});await Q(i,o,()=>i.manager.remote.stashPop(a))}),t.post("/repos/:id/switch-branch",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=et(s,"name");await Q(i,o,()=>i.manager.remote.switchBranch(a))}),t.post("/repos/:id/create-branch",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=et(s,"name");await Q(i,o,()=>i.manager.remote.createBranch(a))}),t.post("/repos/:id/soft-reset",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=ss(s,"count",{min:1,fallback:1});if(!await wt(i.path,`HEAD~${a}`))throw new p(400,`Cannot soft-reset ${a} commit(s): HEAD~${a} does not exist`);await Q(i,o,()=>i.manager.remote.softReset(a))}),t.post("/repos/:id/cherry-pick",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=et(s,"hash");await Q(i,o,()=>i.manager.remote.cherryPick(a))}),t.post("/repos/:id/revert",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=et(s,"hash");await Q(i,o,()=>i.manager.remote.revertCommit(a))}),t.post("/repos/:id/abort",async({params:r,res:s})=>{let o=S(n,r.id);if(!await Zt(o.path))throw new p(409,"No operation in progress to abort");await Q(o,s,()=>o.manager.remote.abortOperation())}),t.post("/repos/:id/rebase-continue",async({params:r,res:s})=>{let o=S(n,r.id);if(await Zt(o.path)!=="rebase")throw new p(409,"No rebase in progress to continue");await Q(o,s,()=>o.manager.remote.rebaseContinue())})}import*as Cn from"node:fs";import*as qe from"node:path";var me=8388608;var Ua=65536;function de(t){return Array.from(t,(e)=>e.charCodeAt(0))}function pe(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 Tn(t,e){return t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function us(t,e){return(t[e]<<8)+t[e+1]}function In(t,e){return t[e]+(t[e+1]<<8)}function ja(t,e){return String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3])}function F(t){return{ok:!1,refusal:t}}function ge(t){return F(t?"malformed":"header-not-found")}function fs(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 pd=[137,80,78,71,13,10,26,10],md=[255,216,255],gd=de("GIF87a"),wd=de("GIF89a"),lt=de("ftyp");function st(t){return{offset:8,bytes:de(t)}}var yd=[{label:"webp",offset:0,bytes:de("RIFF"),brand:st("WEBP")},{label:"avif",offset:4,bytes:lt,brand:st("avif")},{label:"avis",offset:4,bytes:lt,brand:st("avis")},{label:"heic",offset:4,bytes:lt,brand:st("heic")},{label:"heix",offset:4,bytes:lt,brand:st("heix")},{label:"heim",offset:4,bytes:lt,brand:st("heim")},{label:"heis",offset:4,bytes:lt,brand:st("heis")},{label:"hevc",offset:4,bytes:lt,brand:st("hevc")},{label:"hevx",offset:4,bytes:lt,brand:st("hevx")},{label:"mif1",offset:4,bytes:lt,brand:st("mif1")},{label:"msf1",offset:4,bytes:lt,brand:st("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:de("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 Ed(t){return yd.some((e)=>pe(t,e.offset,e.bytes)&&(e.brand===void 0||pe(t,e.brand.offset,e.brand.bytes)))}var bd={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},Rd=26;function Sd(t,e,n){if(t.length<Rd)return ge(n);if(Tn(t,8)!==13)return F("malformed");if(ja(t,12)!=="IHDR")return F("malformed");let r=Tn(t,16),s=Tn(t,20),o=fs(r,s);if(o)return F(o);let i=bd[t[25]];if(!i||!i.includes(t[24]))return F("malformed");let a=kd(t,n);if(a)return a;return{ok:!0,info:{format:"png",mime:"image/png",width:r,height:s,bytes:e}}}function kd(t,e){let n=8;for(let r=0;r<256;r++){if(n+8>t.length)return ge(e);let s=Tn(t,n),o=ja(t,n+4);if(o==="IDAT")return null;if(o==="acTL")return F("animation");if(o==="iCCP"&&s>65536)return F("malformed");let i=n+12+s;if(i<=n||!Number.isSafeInteger(i))return F("malformed");n=i}return F("malformed")}var xd=218,vd=226,_d=new Set([219,238,192,193,194,196]);function Ad(t){return t>=224&&t<=239||_d.has(t)}function Dd(t){return t===1||t>=208&&t<=217}function Td(t){return t>=192&&t<=207&&t!==196&&t!==200&&t!==204}var Id=new Set([192,193,194]);function Md(t,e,n){if(t.length<4)return ge(n);if(!Ad(t[3]))return F("malformed");return Fd(t,e,n)}function Cd(t,e,n,r,s){if(!Id.has(n))return F("malformed");if(e+9>t.length)return ge(s);let o=us(t,e+5),i=us(t,e+7),a=fs(i,o);if(a)return F(a);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:i,height:o,bytes:r}}}function Pd(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(Dd(n))return{kind:"skip",next:e+2};if(n===xd)return{kind:"malformed"};if(e+4>t.length)return{kind:"ran-out"};let r=us(t,e+2);if(r<2)return{kind:"malformed"};if(Td(n))return{kind:"sof",marker:n};return{kind:"segment",marker:n,length:r}}function Fd(t,e,n){let r=2,s=0;for(let o=0;o<1024;o++){let i=Pd(t,r);if(i.kind==="ran-out")return ge(n);if(i.kind==="malformed")return F("malformed");if(i.kind==="sof")return Cd(t,r,i.marker,e,n);if(i.kind==="skip"){r=i.next;continue}if(i.marker===vd){if(s+=i.length-2,s>65536)return F("malformed")}r+=2+i.length}return F("malformed")}var Od=59,Nd=44,$d=33;function qa(t){return(t&128)===0?0:3*(1<<(t&7)+1)}function Ld(t,e,n){if(e>2097152)return F("too-large");if(!n)return F("header-not-found");if(t.length<13)return ge(n);let r=In(t,6),s=In(t,8),o=fs(r,s);if(o)return F(o);let i={pos:13+qa(t[10]),left:8192,pixels:0,overBudget:!1},a=Bd(t,i);if(a===null)return F("malformed");if(a<1)return F("malformed");if(a>256)return F("too-many-pixels");if(i.overBudget)return F("too-many-pixels");if(a*r*s>33554432)return F("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 Bd(t,e){let n=0;while(e.left-- >0){if(e.pos>=t.length)return null;let r=t[e.pos];if(r===Od)return n;let s=r===Nd;if(!(s?Wd(t,e):Hd(t,e,r)))return null;if(s&&++n>256)return n;if(e.overBudget)return n}return null}function Hd(t,e,n){if(n!==$d)return!1;return e.pos+=2,Xa(t,e)}function Wd(t,e){if(e.pos+10>t.length)return!1;Gd(e,In(t,e.pos+5),In(t,e.pos+7));let n=t[e.pos+9];return e.pos+=10+qa(n)+1,Xa(t,e)}function Gd(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 Xa(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 za(t){return pe(t,0,gd)||pe(t,0,wd)}function we(t,e,n){if(e>8388608)return F("too-large");if(pe(t,0,pd))return Sd(t,e,n);if(pe(t,0,md))return Md(t,e,n);if(za(t))return Ld(t,e,n);if(Ed(t))return F("unsupported-format");return F("not-an-image")}function Mn(t,e){return za(t)?Math.min(e,2097152):65536}function hs(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 Ud=1048576,Ja=5000;class Xe extends Error{constructor(t){super(`Not a regular file: ${t}`);this.name="NotRegularFileError"}}async function Ka(t,e,n,r){let s=n?.hideHidden??!0,o=n?.hideGitignored??!0,i=qe.join(t,e),a=await Cn.promises.readdir(i,{withFileTypes:!0}),c=a.map((f)=>e?qe.join(e,f.name):f.name),l=o?await Kt(t,c):new Set,u=[];for(let f of a){if(s&&f.name.startsWith("."))continue;let h=e?qe.join(e,f.name):f.name;if(o&&l.has(h))continue;let d=f.isDirectory(),m={name:f.name,path:h,type:d?"dir":"file"};if(r)if(d){if(r.directories.has(h))m.hasChanges=!0}else{let g=r.files.get(h);if(g)m.gitStatus=g.status,m.staged=g.staged}u.push(m)}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 jd=16;async function qd(t,e){let n=await se(t,0,Math.min(jd,e)),r=we(n,e,n.length>=e);if(!r.ok&&r.refusal==="too-large")return{head:n,result:r};let s=Math.min(Mn(n,e),e),o=s<=n.length?n.subarray(0,s):Buffer.concat([n,await se(t,n.length,s-n.length)]);return{head:o,result:we(o,e,o.length>=e)}}function Xd(t,e){return t.ok?{image:t.info,refusal:null,version:e}:{image:null,refusal:t.refusal,version:e}}function Ya(t,e){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:t,totalLines:0,media:e}}function ds(t,e){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:t,totalLines:0,media:e}}function zd(t,e){let n=t.toString("utf-8"),r=n.split(`
|
|
48
|
-
`),s=!1;if(r.length>
|
|
49
|
-
`),s=!0;return{content:n,binary:!1,truncated:s,tooLarge:!1,size:e,totalLines:r.length}}async function
|
|
50
|
-
`))throw new ye("Query cannot span lines — this searches for literal text");try{return nc(await _t(t,tp(e),Vd))}catch(n){let r=n;if(r.code===1)return ec;if(r.killed===!0||r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...r.stdout?nc(r.stdout):ec,incomplete:!0};throw n}}function sc(t,e){let{registry:n}=e;t.post("/repos/:id/search",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=L(s,"query");try{let c=await rc(i.path,a);E(o,200,c)}catch(c){if(c instanceof Fn)throw new p(400,`Query must be at least ${Pn} characters`,{cause:c});if(c instanceof ye)throw new p(400,c.message,{cause:c});throw c}})}import{Worker as ep}from"node:worker_threads";var np=1000,rp=64,sp={status:"unavailable",reason:"deadline"},ze={status:"unavailable",reason:"error"};function op(){let t=import.meta.url;return t.endsWith(".ts")?new URL("./symbolWorker.ts",t):new URL("./symbolWorker.js",t)}function oc(t){let e=t.timeoutMs??np,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>rp){let m=a.keys().next().value;if(m===void 0)break;a.delete(m)}}function l(){let h=r;if(r=null,h!==null)h.terminate()}function u(){let h=new ep(op(),{workerData:{grammarDir:t.grammarDir,queryDir:t.queryDir}});return h.unref(),h}function f(h,d){return new Promise((m)=>{if(r===null)try{r=u()}catch(b){w("Cannot start the symbol worker",b,{path:h}),m(ze);return}let g=r,R=++s,y=!1,x=(b,M)=>{if(y)return;if(y=!0,clearTimeout(I),g.off("message",v),g.off("error",D),g.off("exit",T),M)l();m(b)},v=(b)=>{if(b.seq!==R)return;x(b.outcome,!1)},D=(b)=>{w("Symbol worker failed; discarding it",b,{path:h}),x(ze,!0)},T=(b)=>{w(`Symbol worker exited with code ${b}; discarding it`,void 0,{path:h}),x(ze,!0)},I=setTimeout(()=>{w(`Symbol extraction passed its ${e}ms deadline; discarding the worker`,void 0,{path:h}),x(sp,!0)},e);I.unref?.(),g.on("message",v),g.on("error",D),g.on("exit",T);let W={seq:R,relPath:h,content:d};try{g.postMessage(W)}catch(b){w("Cannot send a file to the symbol worker; discarding it",b,{path:h}),x(ze,!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 ze;let m=`${h}\x00${d}`,g=a.get(m);if(g!==void 0)return c(m,g),g;let R=o.then(()=>f(h,d));o=R.catch(()=>{return});let y=await R;return c(m,y),y},async dispose(){i=!0;let h=r;if(r=null,a.clear(),h!==null)await h.terminate()}}}import{spawn as ip}from"node:child_process";import*as ac from"node:fs";import*as cc from"node:path";class Ee extends Error{constructor(t){super(`Not a regular blob: ${t}`);this.name="NotRegularBlobError"}}class be extends Error{size;constructor(t,e){super(`Blob too large: ${t} (${e} bytes)`);this.name="BlobTooLargeError",this.size=e}}class Ut extends Error{constructor(t){super(`Unsafe blob path: ${t}`);this.name="UnsafeBlobPathError"}}var On=65536,lc=/^[0-9a-f]{40}([0-9a-f]{24})?$/,ap=new Set(["100644","100755"]);function cp(t){if(t==="")throw new Ut("empty");if(t.includes("\x00"))throw new Ut("contains NUL");if(t.startsWith("-"))throw new Ut('starts with "-"');if(t.startsWith(":"))throw new Ut('starts with ":"')}function Nn(t,e,n){return _t(t,[...dt,...e],n)}function uc(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 fc(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 lp=1;async function up(t){let e;try{e=(await Nn(t,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],On)).toString("utf8").trim()}catch(n){if(n?.code===lp)return null;throw n}return lc.test(e)?e:null}async function fp(t,e){let n=await up(t);if(n===null)return null;let r=await Nn(t,["ls-tree","-z","--full-tree","-l",n,"--",e],On),s=fc(uc(r),e);if(s===null||s.length!==4)return null;return{mode:s[0],oid:s[2],sizeText:s[3]}}async function hp(t,e){let n=await Nn(t,["ls-files","--stage","-z","--",e],On),r=fc(uc(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 hc(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 dp(t,e,n){let r=await Nn(t,["cat-file","-s",e],On);return hc(r.toString("utf8").trim(),n)}var ic=Buffer.alloc(0);function dc(t,e){let n=ic,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=ic,r=!1}}}function pp(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 m(){let g=ip("git",[...dt,"cat-file","blob",e],{cwd:t,env:vt(),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 x=setTimeout(()=>{n?.kill("SIGKILL"),d(Error(`git cat-file blob timed out for ${e}`))},rr);if(l={want:g,resolve:R,reject:y,timer:x},n===null)m();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 mp(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function gp(t,e,n){let r=cc.join(t,e),s;try{s=await ac.promises.open(r,re)}catch(o){if(mp(o))return null;throw o}try{let o=await s.stat();if(!o.isFile())throw new Ee(e);if(o.size>n)throw new be(e,o.size);let i=o.size,a=dc(i,async(c,l)=>{let u=await se(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 wp(t,e,n,r){let s=e==="head"?await fp(t,n):await hp(t,n);if(s===null)return null;if(!ap.has(s.mode))throw new Ee(n);if(!lc.test(s.oid))throw Error(`git reported a malformed object id for ${n}`);let o=s.oid,i=s.sizeText===null?await dp(t,o,n):hc(s.sizeText,n);if(i>r)throw new be(n,i);let a=pp(t,o),c=dc(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 pc(t,e,n,r){if(cp(n),e==="worktree")return gp(t,n,r);return wp(t,e,n,r)}var yp=["worktree","index","head"],Ep=16,bp=Ua,Rp=me,Sp=["too-large","too-many-pixels"];function kp(t){let e=t.get("side");if(e===null||!yp.includes(e))throw new p(400,'Invalid "side" (expected worktree, index or head)');return e}function yc(t){if(t instanceof Ee)throw new p(400,t.message,{cause:t});if(t instanceof Ut)throw new p(400,t.message,{cause:t});if(t instanceof be)throw new p(413,t.message,{cause:t});throw t}async function mc(t,e){let n=await t.read(e);return{bytes:n,sniff:we(n,t.size,n.length>=t.size)}}async function xp(t,e){let{size:n}=t,r=await t.read(Ep),s=we(r,n,r.length>=n);if(!s.ok&&s.refusal==="too-large")return{bytes:r,sniff:s};let o=Math.min(Mn(r,n),n),i=await mc(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 mc(t,n)}async function Ec(t,e,n,r){let s=await pc(t,e,n,me);if(s===null)return null;try{let{bytes:o,sniff:i}=await xp(s,r);return{bytes:o,size:s.size,oid:s.oid,version:s.version,sniff:i}}finally{await s.close()}}function vp(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 _p(t){let e=Sp.includes(t)?413:415;return new p(e,`Image not served: ${t}`)}function Ap(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 Dp(t,e,n){return{path:t.path,side:t.side,bytes:e,oid:null,image:null,refusal:n,version:""}}async function gc(t,e){let n=Wt(t.path,e.path);await Gt(t,n);let r;try{r=await Ec(t.path,e.side,n,bp)}catch(s){if(s instanceof be)return Dp(e,s.size,"too-large");if(s instanceof Ee)return null;yc(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 Tp(t,e){return e.writableEnded||e.destroyed===!0||t.destroyed===!0}async function wc(t,e,n){let r=t.acquire();if(r===null)throw new p(503,"Too many image requests in flight");let s=await r;if(n.once("finish",s),n.once("close",s),e.once("close",s),Tp(e,n))return s(),!1;return!0}function bc(t,e,n){let{registry:r}=e;t.get("/repos/:id/media",async({params:s,query:o,req:i,res:a})=>{let c=S(r,s.id),l=V(o,"staged"),u=Wt(c.path,ct(o));if(await Gt(c,u),!await wc(n,i,a))return;let f=await he(c.manager.workingTree,u,l),h=Ap(f,l),d={old:h.old===null?null:await gc(c,h.old),new:h.new===null?null:await gc(c,h.new)};E(a,200,d)}),t.get("/repos/:id/blob",async({params:s,query:o,req:i,res:a})=>{let c=S(r,s.id),l=Ys(i);if(l)throw new p(l.status,l.message);let u=kp(o),f=Wt(c.path,ct(o));if(await Gt(c,f),!await wc(n,i,a))return;let h;try{h=await Ec(c.path,u,f,Rp)}catch(m){yc(m)}if(h===null)throw new p(404,`No such blob on side ${u}: ${f}`);if(!h.sniff.ok)throw _p(h.sniff.refusal);let d=vp(u,h.sniff.info.mime,h.oid);Ws(a,200,h.bytes,d)})}function Rc(t,e){let{registry:n,sse:r,daemonEvents:s,follow:o}=e;t.get("/events",({req:i,res:a,query:c})=>{let l=n.listRepos().map((f)=>({id:f.id,path:f.path}));s.subscribe(i,a,l);let u=c.get("repo");if(!u)return;r.attach(u,n.getRepo(u)?.manager??null,i,a)}),t.get("/follow",({res:i})=>{E(i,200,o?o.state:Zi)})}import*as gs from"node:os";import*as Re from"node:path";function Sc(t,e){let{settings:n,discovery:r,daemonEvents:s}=e,o=()=>({...n.settings,persisted:n.persisted});t.get("/settings",({res:i})=>{E(i,200,o())}),t.put("/settings",async({body:i,res:a})=>{let c=ya(i,"watchRoots"),l;try{l=ea(c)}catch(f){throw new p(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 p(500,`Could not save settings: ${h}`,{cause:f})}await r.setRoots(l);let u=o();s.broadcast("settings-change",u),E(a,200,u)}),t.get("/discovered",({res:i})=>{E(i,200,r.state)}),t.get("/browse",async({query:i,res:a})=>{let c=i.get("path"),l=c?ot(c):gs.homedir();if(!Re.isAbsolute(l))throw new p(400,`Path must be absolute: ${c}`);let u=Re.resolve(l),f;try{f=await ra(u)}catch(d){throw new p(404,`Cannot read directory: ${u}`,{cause:d})}let h=Re.dirname(u);E(a,200,{path:u,parent:h===u?null:h,home:gs.homedir(),entries:f})}),t.post("/discovered/rescan",async({res:i})=>{E(i,200,await r.rescan())})}function ws(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}}}import{execFile as Pp}from"node:child_process";function Ip(){return new RegExp("\\{\\{[^{}\\n]+\\}\\}","g")}function Mp(t){let e=[];for(let n of t.matchAll(Ip()))e.push({start:n.index,end:n.index+n[0].length});return e}function kc(t){return Mp(t).length}function ys(t){return t.replace(/\r\n/g,`
|
|
51
|
-
`).trim()}function
|
|
41
|
+
`)},Zi),this.keepAlive.unref();t.on("close",()=>{if(this.subscribers.delete(e),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),Bt(e,"snapshot",JSON.stringify(n))}broadcast(t,e){let n=JSON.stringify(e);for(let r of this.subscribers)Bt(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 Ht from"node:fs";import*as Dn from"node:path";import{watch as mh}from"chokidar";import{EventEmitter as gh}from"node:events";var wh=100;class Kr extends gh{cooldownMs;targetFile;watcher=null;cooldownTimer=null;eventDuringCooldown=!1;lastReadPath=null;_state={path:null,rawContent:null};constructor(t,e=wh){super();this.cooldownMs=e,this.targetFile=t}get state(){return this._state}updateState(t){this._state={...this._state,...t},this.emit("path-change",this._state)}processContent(t){if(!t)return null;let e=ot(t);return Dn.isAbsolute(e)?e:Dn.resolve(e)}onFileEvent(){if(this.cooldownTimer){this.eventDuringCooldown=!0;return}this.readTarget(),this.startCooldown()}startCooldown(){this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null;let t=this.eventDuringCooldown;if(this.eventDuringCooldown=!1,this.readTarget(),t)this.startCooldown()},this.cooldownMs)}readTarget(){try{let t=Ht.readFileSync(this.targetFile,"utf-8"),e=Qn(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;w("Cannot read the follow hook file",t,{file:this.targetFile})}}start(){if(rn(this.targetFile),!Ht.existsSync(this.targetFile))Ht.writeFileSync(this.targetFile,"");try{let t=Ht.readFileSync(this.targetFile,"utf-8"),e=Qn(t);if(e){let n=this.processContent(e);this.lastReadPath=n,this._state={path:n,rawContent:e}}}catch(t){w("Cannot read the follow hook file",t,{file:this.targetFile})}this.watcher=mh(this.targetFile,{persistent:!0,ignoreInitial:!0}),this.watcher.on("change",()=>this.onFileEvent()),this.watcher.on("add",()=>this.onFileEvent()),this.watcher.on("error",(t)=>{w("Follow hook file watcher error",t,{file:this.targetFile})})}stop(){if(this.cooldownTimer)clearTimeout(this.cooldownTimer),this.cooldownTimer=null;if(this.eventDuringCooldown=!1,this.watcher)this.watcher.close().catch((t)=>{w("Failed to close the follow hook file watcher",t,{file:this.targetFile})}),this.watcher=null}}var ea={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class Yr{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 Kr(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)=>{C("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){G("Follow target ignored",n,{path:t.path});return}if(this.disposed){this.registry.closeRepo(e.handle.id);return}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 tt from"node:fs";import*as ue from"node:path";function na(){return{watchRoots:[]}}var Vr=16;function yh(t){let e=t.trim();if(!e)throw Error("Watch directory cannot be empty");let n=ot(e);if(!ue.isAbsolute(n))throw Error(`Watch directory must be absolute: ${t}`);let r=ue.resolve(n),s;try{s=tt.statSync(r)}catch{throw Error(`No such directory: ${r}`)}if(!s.isDirectory())throw Error(`Not a directory: ${r}`);return r}function ra(t){if(t.length>Vr)throw Error(`Too many watch directories (max ${Vr})`);let e=new Set,n=[];for(let r of t){let s=yh(r);if(e.has(s))continue;e.add(s),n.push(s)}return n}function Eh(t){let e=na();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,Vr);return e}class Qr{file;current=na();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=tt.readFileSync(this.file,"utf-8")}catch(e){if(e.code!=="ENOENT")C("Cannot read the settings file; running with defaults",e,{file:this.file});return this.current}try{this.current=Eh(JSON.parse(t))}catch(e){w("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;tt.mkdirSync(ue.dirname(this.file),{recursive:!0});let e=`${this.file}.${process.pid}.tmp`;try{tt.writeFileSync(e,`${JSON.stringify(this.current,null,2)}
|
|
42
|
+
`,{mode:384}),tt.renameSync(e,this.file)}catch(n){throw tt.rmSync(e,{force:!0}),n}return this.current}}import*as aa from"node:path";import{watch as Dh}from"chokidar";import*as rt from"node:fs/promises";import*as U from"node:path";var bh=2,Rh=500,Sh=new Set(["node_modules","vendor","target","dist","build","venv","__pycache__"]);async function sa(t){try{return await rt.stat(U.join(t,".git")),!0}catch{return!1}}async function kh(t){let e=U.join(t,".git"),n;try{n=await rt.stat(e)}catch{return null}if(n.isDirectory())return e;try{let r=await rt.readFile(e,"utf-8"),s=/^gitdir:\s*(.+)$/m.exec(r);if(!s)return null;let o=s[1].trim(),i=U.isAbsolute(o)?o:U.resolve(t,o);return await rt.stat(i),i}catch{return null}}async function Zr(t){let e;try{e=(await rt.readFile(U.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 xh(t){let e=[t];try{let o=await rt.readdir(U.join(t,"worktrees"));e.push(...o.map((i)=>U.join(t,"worktrees",i)))}catch{}let n=e.flatMap((o)=>[U.join(o,"HEAD"),U.join(o,"logs","HEAD")]),s=(await Promise.all(n.map(async(o)=>{try{return(await rt.stat(o)).mtimeMs}catch{return null}}))).filter((o)=>o!==null);return s.length===0?null:Math.max(...s)}async function vh(t){let e=await kh(t);if(e===null)return null;let[n,r]=await Promise.all([Zr(e),xh(e)]);return{path:t,name:U.basename(t),branch:n,lastActivity:r}}function _h(t){if(!t.isDirectory())return!1;if(t.name.startsWith("."))return!1;return!Sh.has(t.name)}async function oa(t){let e=await ts(t);return Promise.all(e.map(async(n)=>({name:U.basename(n),path:n,isRepo:await sa(n)})))}async function ts(t){return(await rt.readdir(t,{withFileTypes:!0})).filter(_h).map((n)=>U.join(t,n.name)).sort()}async function Ah(t,e,n){let r=[],s=[];for(let o of t){if(r.length>=n)return{repos:r,next:s,capped:!0};if(await sa(o)){r.push(o);continue}if(!e)continue;try{s.push(...await ts(o))}catch{}}return{repos:r,next:s,capped:!1}}async function ia(t,e={}){let n=e.depth??bh,r=e.limit??Rh,s=await ts(t),o=[],i=!1;for(let c=1;c<=n&&s.length>0&&!i;c++){let l=await Ah(s,c<n,r-o.length);o.push(...l.repos),i=l.capped,s=l.next.sort()}return{repos:(await Promise.all(o.map(vh))).filter((c)=>c!==null),capped:i}}var Th=300;function Ih(t){let e=aa.basename(t);return e.startsWith(".")&&e!=="."||e==="node_modules"}class es{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)=>{w("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 ia(t);e.state={path:t,repos:n.repos,error:null,capped:n.capped}}catch(n){w("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=Dh(t,{persistent:!0,ignoreInitial:!0,depth:1,ignored:Ih});n.on("error",(r)=>{w("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())},Th),e.timer.unref?.()}broadcast(){if(this.disposed)return;this.hub.broadcast("discovery-change",this.state)}}import*as da from"node:fs";import{execFile as Mh}from"node:child_process";import*as Tt from"node:fs";import*as yt from"node:path";import{fileURLToPath as Ch}from"node:url";var ca={method:"unknown",package:null,command:null},qe="diffstalkerd",Ph=3000,Fh=["paru","yay"],Oh=[{method:"bun",pattern:/\/install\/global\/node_modules\/diffstalkerd$/,command:`bun add -g ${qe}`},{method:"pnpm",pattern:/\/pnpm\/global\/\d+\/node_modules\/diffstalkerd$/,command:`pnpm add -g ${qe}`},{method:"yarn",pattern:/\/yarn\/global\/node_modules\/diffstalkerd$/,command:`yarn global add ${qe}`},{method:"npm",pattern:/\/lib\/node_modules\/diffstalkerd$/,command:`npm install -g ${qe}`}];async function Nh(t,e){let n=t.split(yt.sep).join("/").replace(/\/+$/,"");for(let s of Oh){if(!s.pattern.test(n))continue;let o=e.writable(t)?"":"sudo ";return{method:s.method,package:qe,command:`${o}${s.command}`}}let r=await e.pacmanOwner(yt.join(t,"package.json"));if(r!==null){let s=e.onPath(Fh);return{method:"pacman",package:r,command:s?`${s} -S ${r}`:`sudo pacman -Syu ${r}`}}return ca}var ns={onPath(t){let e=(process.env.PATH??"").split(yt.delimiter).filter(Boolean);for(let n of t)for(let r of e)try{return Tt.accessSync(yt.join(r,n),Tt.constants.X_OK),n}catch{}return null},pacmanOwner(t){return new Promise((e)=>{Mh("pacman",["-Qoq","--",t],{timeout:Ph},(n,r)=>{if(n)return e(null);let s=r.trim().split(`
|
|
43
|
+
`)[0]?.trim();e(s?s:null)})})},writable(t){try{return Tt.accessSync(t,Tt.constants.W_OK),!0}catch{return!1}}};function $h(){let t=yt.dirname(Ch(new URL("../package.json",import.meta.url)));try{return Tt.realpathSync(t)}catch{return t}}function la(t=$h(),e=ns){let n=null;return{info(){return n??=Nh(t,e).catch((r)=>(w("Install detection failed",r,{dir:t}),ca)),n}}}import*as ua from"node:fs";var Lh=/^[A-Za-z0-9:_.@-]+\.service$/,Bh=/^user@\d+\.service$/,Hh=/^0::(.*)$/m;function Wh(t){let e=Hh.exec(t);if(e===null)return null;let n=e[1].split("/"),r=n.at(-1)??"";if(!Lh.test(r))return null;let s=r.slice(0,-8);return n.some((o)=>Bh.test(o))?`systemctl --user restart ${s}`:`sudo systemctl restart ${s}`}function fa(t=process.pid,e=process.env,n=()=>ua.readFileSync("/proc/self/cgroup","utf-8")){if(e.SYSTEMD_EXEC_PID!==String(t))return null;try{return Wh(n())}catch(r){return w("Cannot read /proc/self/cgroup to name the systemd unit",r),null}}var Gh="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",Uh=21600000,jh=300000,qh=5000;function rs(){try{let t=da.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 w("Cannot read the daemon version from its package.json",t),null}}async function Xh(){let t=await fetch(Gh,{headers:{accept:"application/json"},signal:AbortSignal.timeout(qh)});if(!t.ok)return null;let e=await t.json();return typeof e.latest==="string"?e.latest:null}function ha(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());if(!e)return null;return[Number(e[1]),Number(e[2]),Number(e[3])]}function zh(t,e){if(t===null||e===null)return"unknown";let n=ha(t),r=ha(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 pa(t=Xh,e=rs(),n=la(),r=fa()){let s=null,o=null;function i(){if(s&&Date.now()<s.expiresAt)return Promise.resolve(s.value);if(o)return o;return o=t().catch((a)=>(G("Latest version lookup failed",a),null)).then((a)=>{let c=a===null?jh:Uh;return s={value:a,expiresAt:Date.now()+c},o=null,a}),o}return{async state(){let[a,c]=await Promise.all([i(),n.info()]);return{current:e,latest:a,status:zh(e,a),install:c,restart:r}}}}import*as ma from"node:os";function ga(t,e){t.get("/health",({res:n})=>{E(n,200,{ok:!0,ready:!0,home:ma.homedir(),http:{port:e.httpPort()},symbols:{extensions:e.symbols?.extensions??[]},gh:e.prs.ghAvailable()})})}function wa(t,e){t.get("/version",async({res:n})=>{E(n,200,await e.version.state())})}import*as Aa from"node:fs";import*as fe from"node:fs";import*as j from"node:path";function he(t,e){let n=t.getRepo(e);if(!n)throw new p(404,`Unknown repo id: ${e}`);return n}function S(t,e){let n=he(t,e),r=n.manager.workingTree.unavailable;if(r!==null)throw new p(410,r);return n}function L(t,e,n){if(typeof t!=="object"||t===null)throw new p(400,`Expected a JSON body with "${e}"`);let r=t[e];if(typeof r!=="string"||!n?.allowEmpty&&r.length===0)throw new p(400,`Missing "${e}" (string) in body`);return r}function Ea(t,e){if(t.length===0)throw new p(400,`Invalid "${e}" (expected a ref)`);if(t.startsWith("-"))throw new p(400,`Invalid "${e}" (must not start with "-"): ${t}`);return t}function et(t,e){return Ea(L(t,e),e)}function Xe(t,e){let n=t.get(e);return n===null?null:Ea(n,e)}function ba(t,e){if(typeof t!=="object"||t===null)throw new p(400,`Expected a JSON body with "${e}"`);let n=t[e];if(!Array.isArray(n)||n.some((r)=>typeof r!=="string"))throw new p(400,`Missing "${e}" (array of strings) in body`);return n}function Ra(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 p(400,`Invalid "${e}" (expected a non-empty string)`);return n}function is(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 p(400,`Invalid "${e}" (expected an integer >= ${n.min})`);return r}function Sa(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 p(400,`Invalid "${e}" (expected a boolean)`);return n}function V(t,e,n){let r=t.get(e);if(r===null){if(n===void 0)throw new p(400,`Missing "${e}" query parameter (expected true or false)`);return n}if(r==="true")return!0;if(r==="false")return!1;throw new p(400,`Invalid "${e}" (expected true or false): ${r}`)}function ct(t){let e=t.get("path");if(!e)throw new p(400,'Missing "path" query parameter');return e}function ze(t,e){let n=V(t,"whole",!1);if(n&&!e)throw new p(400,"whole=true requires a path (one file at a time)");return n?Zo:void 0}function ka(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 p(400,`Invalid "${e}" (expected a positive integer): ${s}`);if(r!==void 0&&o>r)throw new p(400,`Invalid "${e}" (must be <= ${r}): ${s}`);return o}async function Et(t){if(await t.catchUp(),!t.state.status)await t.refresh();let e=t.state.status;if(!e)throw new p(500,"Repository status unavailable");return e}function ya(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 de(t,e,n){let r=await Et(t),s=ya(r,e,n);if(!s)await t.refresh(),r=await Et(t),s=ya(r,e,n);if(!s)throw new p(404,`File not in status: ${e}`);return s}function os(t,e){return t===e||t.startsWith(e+j.sep)}function as(t){return t.replace(/[. ]+$/,"").toLowerCase()===".git"}function Wt(t,e){if(e.length===0)throw new p(400,"Empty path");if(e.includes("\x00"))throw new p(400,"Path contains a NUL byte");let n=j.resolve(t),r=j.relative(n,j.resolve(n,e));if(r==="")throw new p(400,`Path resolves to the repository root: ${e}`);if(j.isAbsolute(r)||r===".."||r.startsWith(`..${j.sep}`))throw new p(400,`Path escapes repository root: ${e}`);if(r.startsWith("-"))throw new p(400,`Path must not start with "-": ${e}`);if(r.startsWith(":"))throw new p(400,`Path must not start with ":": ${e}`);if(r.split(j.sep).some(as))throw new p(400,`Path addresses the git directory: ${e}`);return r}async function xa(t){try{return await fe.promises.realpath(t)}catch{return null}}var ss=new WeakMap;async function Jh(t){let e=ss.get(t);if(!e)e=(async()=>{let n=await k(t.path).raw(["rev-parse","--absolute-git-dir"]);return await fe.promises.realpath(n.trim())})(),ss.set(t,e),e.catch(()=>ss.delete(t));try{return await e}catch(n){throw new p(500,"Cannot resolve the git directory for this repository",{cause:n})}}async function Gt(t,e){let n=await fe.promises.realpath(j.resolve(t.path)),r=await xa(j.join(t.path,e));if(r===null)return;if(!os(r,n))throw new p(400,`Path escapes repository root: ${e}`);if(os(r,await Jh(t)))throw new p(400,`Path addresses the git directory: ${e}`)}async function va(t,e){let n=await fe.promises.realpath(j.resolve(t)),r=[];for(let s of e){let o=await xa(j.join(t,s.path));if(o===null||os(o,n))r.push(s)}return r}function Tn(t){return t?.code??null}async function cs(t){let e;try{e=await fe.promises.stat(t)}catch(n){let r=Tn(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 Kh(t){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test(t)?409:500}function _a(t,e){return new p(t,e)}async function bt(t,e,n){t.clearError(),await n();let r=t.state.error;if(r)throw _a(Kh(r),r);await t.refresh(),E(e,200,{state:kt(t.state)})}var Yh=/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged|no tracking information|no upstream|no configured push destination/i;function Vh(t){return Yh.test(t)?409:500}async function Q(t,e,n){let r=t.manager.remote,s=()=>new p(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 _a(Vh(o.error),o.error);E(e,200,{state:kt(i.state),result:o.lastResult})}function Qh(t){if(t.reason==="not-a-repo"&&!Aa.existsSync(t.requested))return new p(404,`No such directory: ${t.requested}`,{cause:t});return new p(400,t.message,{cause:t})}async function Zh(t,e){let n=e.state.status;if(n&&!e.stale)return n.branch.current;let r=K(t);return r===null?null:Zr(r.gitDir)}function Da(t,e){let{registry:n}=e;t.get("/repos",async({res:r})=>{let s=await Promise.all(n.listRepos().map(async(o)=>({id:o.id,path:o.path,branch:await Zh(o.path,o.manager.workingTree)})));E(r,200,s)}),t.post("/repos",async({body:r,res:s})=>{let o=L(r,"path"),i;try{i=await An(n,o)}catch(a){if(a instanceof _n)throw Qh(a);throw a}E(s,i.created?201:200,{id:i.handle.id,path:i.handle.path})}),t.get("/resolve",async({query:r,res:s})=>{let o=ct(r),i=await dn(o,{mustExist:!0});if(!i.ok&&i.reason==="not-absolute")throw new p(400,`Repo path must be absolute: ${i.requested}`);E(s,200,{openable:i.ok,root:i.ok?i.root:null})}),t.get("/repos/:id/worktrees",async({params:r,res:s})=>{let o=S(n,r.id);E(s,200,await xr(o.path))}),t.get("/worktrees",async({query:r,res:s})=>{E(s,200,await xr(ct(r)))}),t.delete("/repos/:id",({params:r,res:s})=>{he(n,r.id),n.closeRepo(r.id),E(s,200,{})})}function Ta(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 Ia(t){return t.trim()}async function td(t){let e=(r)=>r.filter((s)=>s.staged).length,n=e((await Et(t)).files);if(n===0)await t.refresh(),n=e((await Et(t)).files);return n}function Ma(t,e){let{registry:n,sse:r}=e;if(t.get("/repos/:id/status",async({params:s,res:o})=>{let i=he(n,s.id);await Et(i.manager.workingTree),E(o,200,kt(i.manager.workingTree.state))}),t.get("/repos/:id/diff",async({params:s,query:o,res:i})=>{let a=S(n,s.id),c=a.manager.workingTree,l=o.get("path")??void 0,u=V(o,"staged",!1),f=ze(o,l);if(!l){let R=await c.wholeTreeDiffs();if(!R){let y=c.unavailable;throw new p(y?410:500,y??"Repository diff unavailable")}E(i,200,u?R.staged:R.unstaged);return}let d=(await Et(c)).files.some((R)=>R.path===l&&R.status==="untracked");if(d&&u)throw new p(400,`staged=true is meaningless for untracked file: ${l} (untracked files have no staged diff)`);let m=f!==void 0&&!d,g=d?await Ot(a.path,l):await ti(a.path,l,u,{context:f});if(!m)c.stampDiff(g);E(i,200,g)}),t.post("/repos/:id/stage",async({params:s,body:o,res:i})=>{let a=S(n,s.id),c=L(o,"path"),l=a.manager.workingTree,u=await de(l,c,!1);await bt(l,i,()=>l.stage(u))}),t.post("/repos/:id/unstage",async({params:s,body:o,res:i})=>{let a=S(n,s.id),c=L(o,"path"),l=a.manager.workingTree,u=await de(l,c,!0);await bt(l,i,()=>l.unstage(u))}),t.get("/repos/:id/events",({params:s,req:o,res:i})=>{let a=he(n,s.id);r.subscribe(s.id,a.manager,o,i)}),e.apiMode==="full")ed(t,e)}function ed(t,e){let{registry:n}=e;t.post("/repos/:id/stage-all",async({params:r,res:s})=>{let i=S(n,r.id).manager.workingTree;await bt(i,s,()=>i.stageAll())}),t.post("/repos/:id/unstage-all",async({params:r,res:s})=>{let i=S(n,r.id).manager.workingTree;await bt(i,s,()=>i.unstageAll())}),t.post("/repos/:id/discard",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=L(s,"path"),c=i.manager.workingTree,l=await de(c,a,!1);if(l.staged)throw new p(409,`Cannot discard a staged file: ${a} (unstage it first)`);await bt(c,o,()=>c.discard(l))}),t.post("/repos/:id/commit",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=L(s,"message",{allowEmpty:!0}),c=Sa(s,"amend"),l=i.manager.workingTree,u=await td(l),f=Ta(a,u,c);if(!f.valid)throw new p(400,f.error??"Invalid commit");await bt(l,o,()=>l.commit(Ia(a),c))}),t.post("/repos/:id/stage-hunk",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=L(s,"patch"),c=i.manager.workingTree;await bt(c,o,()=>c.stageHunk(a))}),t.post("/repos/:id/unstage-hunk",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=L(s,"patch"),c=i.manager.workingTree;await bt(c,o,()=>c.unstageHunk(a))})}var nd=1000,In="refs/heads/",Ca="refs/remotes/";async function Fa(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(r),o=[];for(let i of s.split(`
|
|
44
|
+
`)){if(!i)continue;let[a,c,l]=i.split(" ");if(l)continue;if(c.startsWith(In))o.push({tip:a,name:c.slice(In.length),local:!0});else if(c.startsWith(Ca))o.push({tip:a,name:c.slice(Ca.length),local:!1})}return o}function rd(t){return new Map(t.filter((e)=>e.local).map((e)=>[e.name,e.tip]))}function Oa(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 sd(t){return new Set(t.filter((e)=>!e.local).map((e)=>e.name.slice(e.name.indexOf("/")+1)))}function Na(t,e){return!t.local||e.has(t.name)}async function $a(t,e,n){return(await t(["rev-list","--first-parent",`--max-count=${nd}`,"--end-of-options",`${e}..${n}`])).split(`
|
|
45
|
+
`).filter(Boolean).reverse()}async function od(t){let e=await t(["rev-parse","HEAD","--symbolic-full-name","HEAD"]),[n,r]=e.split(`
|
|
46
|
+
`),s=r.startsWith(In)?r.slice(In.length):null;return{tip:n,name:s??"HEAD",branch:s}}async function Pa(t,e){if(e.length<2)return e;return(await t(["merge-base","--independent","--end-of-options",...e])).split(`
|
|
47
|
+
`).filter(Boolean)}function id(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 La(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=id(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 ad(t,e,n,r,s,o){let i=Oa(await Fa(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 Pa(t,a);if(c.length>1){let u=[...new Set(i.filter((f)=>Na(f,o)).map((f)=>f.tip))];if(u.length>0)c=await Pa(t,u)}if(c.length!==1)return{layers:[],forked:!0};let l=await $a(t,n,c[0]);return{layers:La(l,s,null,o),forked:!1}}function cd(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()}function ld(t,e){let n=k(t);if(!e)return(r)=>n.raw(r);return(r)=>He(()=>n.raw(r))}async function Mn(t,e,{pooled:n=!1}={}){let r=ld(t,n),s=await od(r),o=(await r(["merge-base","--end-of-options",e,s.tip])).trim();if(!o)return{trunk:e,layers:[],forkedAbove:!1};let[i,a]=await Promise.all([Fa(r,e),$a(r,o,s.tip)]),c=rd(i),l=sd(i),u=new Map,f=new Set;for(let m of Oa(i,c)){let g=u.get(m.tip);if(g)g.push(m);else u.set(m.tip,[m]);if(Na(m,l))f.add(m.tip)}let h=La(a,u,s,l);if(!h.some((m)=>m.isHead))h.push({name:s.name,refs:[],tip:s.tip,commits:0,isHead:!0});let d=await ad(r,e,s.tip,c,u,l);return{trunk:e,layers:cd([...h,...d.layers],f),forkedAbove:d.forked}}function ls(t){if(!/^[0-9a-f]{4,40}$/i.test(t))throw new p(400,`Invalid commit hash: ${t}`);return t}async function Ba(t,e){if(!await wt(t,e))throw new p(404,`Unknown commit: ${e}`)}async function us(t){try{return await t()}catch(e){if(e instanceof cn)throw new p(422,e.message,{cause:e});throw e}}async function ud(t){let e=await Er(t);if(e&&await wt(t,e))return e;if(an(t)){let n=await yr(t);if(n&&await wt(t,n))return n}throw new p(422,"No usable base branch")}async function Cn(t,e){let n=Xe(e,"base");if(n===null)return ud(t);if(!await wt(t,n))throw new p(400,`Unknown base ref: ${n}`);return n}async function fs(t,e){let n=Xe(e,"head");if(n===null)return;if(!await wt(t,n))throw new p(400,`Unknown head ref: ${n}`);return n}function Ha(t,e){if(e&&t.get("head")!==null)throw new p(400,"head cannot be combined with uncommitted work (it only exists against HEAD)")}var fd=new Set(["staged","unstaged","both","untracked"]);function hd(t){let e=t.get("uncommitted");if(e===null)return null;if(!fd.has(e))throw new p(400,`Invalid "uncommitted" (expected staged, unstaged, both or untracked): ${e}`);return e}function dd(t){return{staged:V(t,"staged",!1),unstaged:V(t,"unstaged",!1),untracked:V(t,"untracked",!1)}}function pd(t){if(t.unstaged&&!t.staged)throw new p(400,"unstaged needs staged too (unstaged edits sit on top of staged ones)")}function Wa(t,e){let{registry:n}=e;if(t.get("/repos/:id/history",async({params:r,query:s,res:o})=>{let i=S(n,r.id),a=ka(s,"count",100,5000);E(o,200,await Fo(i.path,a))}),t.get("/repos/:id/commits/:hash",async({params:r,res:s})=>{let o=S(n,r.id),i=ls(r.hash),a=await Oo(o.path,i);if(a===null)throw new p(404,`Unknown commit: ${i}`);E(s,200,a)}),t.get("/repos/:id/commits/:hash/diff",async({params:r,query:s,res:o})=>{let i=S(n,r.id),a=ls(r.hash);await Ba(i.path,a);let c=s.get("path")??void 0,l=ze(s,c),u=c?await Rr(i.path,{kind:"commit",hash:a},c,{context:l}):await ui(i.path,a);E(o,200,u)}),t.get("/repos/:id/commits/:hash/files",async({params:r,res:s})=>{let o=S(n,r.id),i=ls(r.hash);await Ba(o.path,i),E(s,200,await li(o.path,i))}),t.get("/repos/:id/compare/file",async({params:r,query:s,res:o})=>{let i=S(n,r.id),a=ct(s),c=ze(s,a),l=hd(s);if(Ha(s,l!==null),l==="untracked"){E(o,200,await Ot(i.path,a));return}let u=await Cn(i.path,s),f=l===null?{kind:"compare",base:u,head:await fs(i.path,s)}:{kind:"compare-uncommitted",mergeBase:await us(()=>ci(i.path,u)),tip:l==="staged"?"index":"worktree"};E(o,200,await Rr(i.path,f,a,{context:c}))}),t.get("/repos/:id/head-message",async({params:r,res:s})=>{let o=S(n,r.id);E(s,200,{message:await Ao(o.path)})}),t.get("/repos/:id/branches",async({params:r,res:s})=>{let o=S(n,r.id);E(s,200,await Lo(o.path))}),t.get("/repos/:id/base-branches",async({params:r,res:s})=>{let o=S(n,r.id);E(s,200,await si(o.path))}),t.get("/repos/:id/compare/base",async({params:r,res:s})=>{let o=S(n,r.id);E(s,200,{base:await Er(o.path)})}),e.apiMode==="full")t.put("/repos/:id/compare/base",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=et(s,"branch");if(!await wt(i.path,a))throw new p(400,`Not a valid base ref: ${a}`);Jo(i.path,a),E(o,200,{base:a})});t.get("/repos/:id/compare/count",async({params:r,query:s,res:o})=>{let i=S(n,r.id),a=await Cn(i.path,s),c=await fs(i.path,s),l=await us(()=>ai(i.path,a,c));E(o,200,{baseBranch:a,commits:l})}),t.get("/repos/:id/compare/stack",async({params:r,query:s,res:o})=>{let i=S(n,r.id),a=await Cn(i.path,s);E(o,200,await Mn(i.path,a))}),t.get("/repos/:id/compare",async({params:r,query:s,res:o})=>{let i=S(n,r.id),a=dd(s);Ha(s,a.staged||a.unstaged||a.untracked),pd(a);let c=await Cn(i.path,s),l=await fs(i.path,s),u=await us(()=>fi(i.path,c,a,l));E(o,200,u)})}function md(t){let e=t.get("since");if(e===null)return 0;if(!/^\d+$/.test(e))throw new p(400,`Invalid "since" (expected a non-negative integer): ${e}`);return Number(e)}function Ga(t,e){let{registry:n}=e;t.get("/repos/:id/journal",async({params:r,query:s,res:o})=>{let i=S(n,r.id),a=md(s);await i.manager.workingTree.catchUp(),E(o,200,Gs(i.manager.journal.journalStore,a))})}function Ua(t,e){let{registry:n}=e;t.post("/repos/:id/push",async({params:r,res:s})=>{let o=S(n,r.id);await Q(o,s,()=>o.manager.remote.push())}),t.post("/repos/:id/fetch",async({params:r,res:s})=>{let o=S(n,r.id);await Q(o,s,()=>o.manager.remote.fetchRemote())}),t.post("/repos/:id/pull",async({params:r,res:s})=>{let o=S(n,r.id);await Q(o,s,()=>o.manager.remote.pullRebase())}),t.post("/repos/:id/stash",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=Ra(s,"message");await Q(i,o,()=>i.manager.remote.stash(a))}),t.post("/repos/:id/stash-pop",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=is(s,"index",{min:0,fallback:0});await Q(i,o,()=>i.manager.remote.stashPop(a))}),t.post("/repos/:id/switch-branch",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=et(s,"name");await Q(i,o,()=>i.manager.remote.switchBranch(a))}),t.post("/repos/:id/create-branch",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=et(s,"name");await Q(i,o,()=>i.manager.remote.createBranch(a))}),t.post("/repos/:id/soft-reset",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=is(s,"count",{min:1,fallback:1});if(!await wt(i.path,`HEAD~${a}`))throw new p(400,`Cannot soft-reset ${a} commit(s): HEAD~${a} does not exist`);await Q(i,o,()=>i.manager.remote.softReset(a))}),t.post("/repos/:id/cherry-pick",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=et(s,"hash");await Q(i,o,()=>i.manager.remote.cherryPick(a))}),t.post("/repos/:id/revert",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=et(s,"hash");await Q(i,o,()=>i.manager.remote.revertCommit(a))}),t.post("/repos/:id/abort",async({params:r,res:s})=>{let o=S(n,r.id);if(!await te(o.path))throw new p(409,"No operation in progress to abort");await Q(o,s,()=>o.manager.remote.abortOperation())}),t.post("/repos/:id/rebase-continue",async({params:r,res:s})=>{let o=S(n,r.id);if(await te(o.path)!=="rebase")throw new p(409,"No rebase in progress to continue");await Q(o,s,()=>o.manager.remote.rebaseContinue())})}import*as Nn from"node:fs";import*as Je from"node:path";var ge=8388608;var ja=65536;function pe(t){return Array.from(t,(e)=>e.charCodeAt(0))}function me(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 Pn(t,e){return t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function hs(t,e){return(t[e]<<8)+t[e+1]}function Fn(t,e){return t[e]+(t[e+1]<<8)}function qa(t,e){return String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3])}function F(t){return{ok:!1,refusal:t}}function we(t){return F(t?"malformed":"header-not-found")}function ds(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 gd=[137,80,78,71,13,10,26,10],wd=[255,216,255],yd=pe("GIF87a"),Ed=pe("GIF89a"),lt=pe("ftyp");function st(t){return{offset:8,bytes:pe(t)}}var bd=[{label:"webp",offset:0,bytes:pe("RIFF"),brand:st("WEBP")},{label:"avif",offset:4,bytes:lt,brand:st("avif")},{label:"avis",offset:4,bytes:lt,brand:st("avis")},{label:"heic",offset:4,bytes:lt,brand:st("heic")},{label:"heix",offset:4,bytes:lt,brand:st("heix")},{label:"heim",offset:4,bytes:lt,brand:st("heim")},{label:"heis",offset:4,bytes:lt,brand:st("heis")},{label:"hevc",offset:4,bytes:lt,brand:st("hevc")},{label:"hevx",offset:4,bytes:lt,brand:st("hevx")},{label:"mif1",offset:4,bytes:lt,brand:st("mif1")},{label:"msf1",offset:4,bytes:lt,brand:st("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:pe("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 Rd(t){return bd.some((e)=>me(t,e.offset,e.bytes)&&(e.brand===void 0||me(t,e.brand.offset,e.brand.bytes)))}var Sd={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},kd=26;function xd(t,e,n){if(t.length<kd)return we(n);if(Pn(t,8)!==13)return F("malformed");if(qa(t,12)!=="IHDR")return F("malformed");let r=Pn(t,16),s=Pn(t,20),o=ds(r,s);if(o)return F(o);let i=Sd[t[25]];if(!i||!i.includes(t[24]))return F("malformed");let a=vd(t,n);if(a)return a;return{ok:!0,info:{format:"png",mime:"image/png",width:r,height:s,bytes:e}}}function vd(t,e){let n=8;for(let r=0;r<256;r++){if(n+8>t.length)return we(e);let s=Pn(t,n),o=qa(t,n+4);if(o==="IDAT")return null;if(o==="acTL")return F("animation");if(o==="iCCP"&&s>65536)return F("malformed");let i=n+12+s;if(i<=n||!Number.isSafeInteger(i))return F("malformed");n=i}return F("malformed")}var _d=218,Ad=226,Dd=new Set([219,238,192,193,194,196]);function Td(t){return t>=224&&t<=239||Dd.has(t)}function Id(t){return t===1||t>=208&&t<=217}function Md(t){return t>=192&&t<=207&&t!==196&&t!==200&&t!==204}var Cd=new Set([192,193,194]);function Pd(t,e,n){if(t.length<4)return we(n);if(!Td(t[3]))return F("malformed");return Nd(t,e,n)}function Fd(t,e,n,r,s){if(!Cd.has(n))return F("malformed");if(e+9>t.length)return we(s);let o=hs(t,e+5),i=hs(t,e+7),a=ds(i,o);if(a)return F(a);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:i,height:o,bytes:r}}}function Od(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(Id(n))return{kind:"skip",next:e+2};if(n===_d)return{kind:"malformed"};if(e+4>t.length)return{kind:"ran-out"};let r=hs(t,e+2);if(r<2)return{kind:"malformed"};if(Md(n))return{kind:"sof",marker:n};return{kind:"segment",marker:n,length:r}}function Nd(t,e,n){let r=2,s=0;for(let o=0;o<1024;o++){let i=Od(t,r);if(i.kind==="ran-out")return we(n);if(i.kind==="malformed")return F("malformed");if(i.kind==="sof")return Fd(t,r,i.marker,e,n);if(i.kind==="skip"){r=i.next;continue}if(i.marker===Ad){if(s+=i.length-2,s>65536)return F("malformed")}r+=2+i.length}return F("malformed")}var $d=59,Ld=44,Bd=33;function Xa(t){return(t&128)===0?0:3*(1<<(t&7)+1)}function Hd(t,e,n){if(e>2097152)return F("too-large");if(!n)return F("header-not-found");if(t.length<13)return we(n);let r=Fn(t,6),s=Fn(t,8),o=ds(r,s);if(o)return F(o);let i={pos:13+Xa(t[10]),left:8192,pixels:0,overBudget:!1},a=Wd(t,i);if(a===null)return F("malformed");if(a<1)return F("malformed");if(a>256)return F("too-many-pixels");if(i.overBudget)return F("too-many-pixels");if(a*r*s>33554432)return F("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 Wd(t,e){let n=0;while(e.left-- >0){if(e.pos>=t.length)return null;let r=t[e.pos];if(r===$d)return n;let s=r===Ld;if(!(s?Ud(t,e):Gd(t,e,r)))return null;if(s&&++n>256)return n;if(e.overBudget)return n}return null}function Gd(t,e,n){if(n!==Bd)return!1;return e.pos+=2,za(t,e)}function Ud(t,e){if(e.pos+10>t.length)return!1;jd(e,Fn(t,e.pos+5),Fn(t,e.pos+7));let n=t[e.pos+9];return e.pos+=10+Xa(n)+1,za(t,e)}function jd(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 za(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 Ja(t){return me(t,0,yd)||me(t,0,Ed)}function ye(t,e,n){if(e>8388608)return F("too-large");if(me(t,0,gd))return xd(t,e,n);if(me(t,0,wd))return Pd(t,e,n);if(Ja(t))return Hd(t,e,n);if(Rd(t))return F("unsupported-format");return F("not-an-image")}function On(t,e){return Ja(t)?Math.min(e,2097152):65536}function ps(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 qd=1048576,Ka=5000;class Ke extends Error{constructor(t){super(`Not a regular file: ${t}`);this.name="NotRegularFileError"}}async function Va(t,e,n,r){let s=n?.hideHidden??!0,o=n?.hideGitignored??!0,i=Je.join(t,e),a=await Nn.promises.readdir(i,{withFileTypes:!0}),c=a.map((f)=>e?Je.join(e,f.name):f.name),l=o?await Vt(t,c):new Set,u=[];for(let f of a){if(s&&f.name.startsWith("."))continue;let h=e?Je.join(e,f.name):f.name;if(o&&l.has(h))continue;let d=f.isDirectory(),m={name:f.name,path:h,type:d?"dir":"file"};if(r)if(d){if(r.directories.has(h))m.hasChanges=!0}else{let g=r.files.get(h);if(g)m.gitStatus=g.status,m.staged=g.staged}u.push(m)}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 Xd=16;async function zd(t,e){let n=await oe(t,0,Math.min(Xd,e)),r=ye(n,e,n.length>=e);if(!r.ok&&r.refusal==="too-large")return{head:n,result:r};let s=Math.min(On(n,e),e),o=s<=n.length?n.subarray(0,s):Buffer.concat([n,await oe(t,n.length,s-n.length)]);return{head:o,result:ye(o,e,o.length>=e)}}function Jd(t,e){return t.ok?{image:t.info,refusal:null,version:e}:{image:null,refusal:t.refusal,version:e}}function Ya(t,e){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:t,totalLines:0,media:e}}function ms(t,e){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:t,totalLines:0,media:e}}function Kd(t,e){let n=t.toString("utf-8"),r=n.split(`
|
|
48
|
+
`),s=!1;if(r.length>Ka)n=r.slice(0,Ka).join(`
|
|
49
|
+
`),s=!0;return{content:n,binary:!1,truncated:s,tooLarge:!1,size:e,totalLines:r.length}}async function Yd(t,e){let n=await t.stat();if(!n.isFile())throw new Ke(e);let r=n.size;if(r>ge)return ms(r);let{head:s,result:o}=await zd(t,r),i=Jd(o,`${r}-${n.mtimeMs}`);if(o.ok)return Ya(r,i);if(r>qd)return ms(r,Le(s)?i:void 0);let a=s.length>=r?s:Buffer.concat([s,await oe(t,s.length,r-s.length)]);return Le(a)?Ya(r,i):Kd(a,r)}async function Qa(t,e){let n=Je.join(t,e),r=await Nn.promises.stat(n);if(!r.isFile())throw new Ke(e);if(r.size>ge)return ms(r.size);let s=await Nn.promises.open(n,se);try{return await Yd(s,e)}finally{await s.close()}}import*as gs from"node:path";function Za(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 p(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=S(n,o.id),l=i.get("dir")??"",u=V(i,"hidden",!1),f=V(i,"ignored",!1),h=l===""?"":Wt(c.path,l);await Gt(c,h);let d=await Et(c.manager.workingTree),m=ps(d.files),g;try{g=await Va(c.path,h,{hideHidden:!u,hideGitignored:!f},m)}catch(y){let x=Tn(y);if(x==="ENOENT"||x==="ENOTDIR"){let v=await cs(gs.join(c.path,h));if(v===null)throw new p(404,`No such directory: ${l||"/"}`,{cause:y});throw new p(400,`Not a directory (${v}): ${l}`,{cause:y})}throw y}let R=g.filter((y)=>!as(y.name));E(a,200,await va(c.path,R))}),t.get("/repos/:id/file",async({params:o,query:i,res:a})=>{let c=S(n,o.id),l=ct(i),u=Wt(c.path,l);await Gt(c,u);try{let f=await Qa(c.path,u);E(a,200,await s(f,u,V(i,"symbols",!1)))}catch(f){if(f instanceof Ke){let d=await cs(gs.join(c.path,u));throw new p(400,`Not a regular file (${d??"unknown"}): ${l}`,{cause:f})}let h=Tn(f);if(h==="ENOENT"||h==="ENOTDIR")throw new p(404,`No such file: ${l}`,{cause:f});throw f}}),t.get("/repos/:id/files",async({params:o,res:i})=>{let a=S(n,o.id);E(i,200,await Xo(a.path))})}var $n=3,Vd=20,tc=500,Qd=500,Zd=4194304,ec=400;class Ln extends Error{constructor(){super(`Query must be at least ${$n} characters`);this.name="GrepQueryTooShortError"}}class Ee extends Error{constructor(t){super(t);this.name="GrepQueryInvalidError"}}var nc={matches:[],capped:!1,incomplete:!1,binarySkipped:0};function tp(t){return t===t.toLowerCase()}function ws(t){return Buffer.from(t).toString("utf8")}function ep(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 rc(t,e=Qd){let n=[],r=new Map,s=0,o=!1,i=0;while(i<t.length){let a=ep(t,i);if(a===null)break;if(i=a.next,a.contentBytes.includes(0)){s+=1;continue}let c=Number.parseInt(ws(a.lineBytes),10);if(!Number.isSafeInteger(c)||c<1)continue;if(n.length>=e){o=!0;break}let l=ws(a.pathBytes),u=r.get(l)??0;if(u>=Vd){o=!0;continue}r.set(l,u+1);let f=ws(a.contentBytes),h=f.length>ec;n.push({path:l,line:c,text:h?f.slice(0,ec):f,truncated:h})}return{matches:n,capped:o,incomplete:!1,binarySkipped:s}}function np(t){return[...dt,"grep","--no-textconv","--no-recurse-submodules","--full-name","--no-color","--no-column","-I","-n","-z","-F",...tp(t)?["-i"]:[],"-e",t,"--untracked","--","."]}async function sc(t,e){if(e.length<$n)throw new Ln;if(e.length>tc)throw new Ee(`Query must be at most ${tc} characters`);if(e.includes("\x00"))throw new Ee("Query cannot contain a NUL byte");if(e.includes(`
|
|
50
|
+
`))throw new Ee("Query cannot span lines — this searches for literal text");try{return rc(await _t(t,np(e),Zd))}catch(n){let r=n;if(r.code===1)return nc;if(r.killed===!0||r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...r.stdout?rc(r.stdout):nc,incomplete:!0};throw n}}function oc(t,e){let{registry:n}=e;t.post("/repos/:id/search",async({params:r,body:s,res:o})=>{let i=S(n,r.id),a=L(s,"query");try{let c=await sc(i.path,a);E(o,200,c)}catch(c){if(c instanceof Ln)throw new p(400,`Query must be at least ${$n} characters`,{cause:c});if(c instanceof Ee)throw new p(400,c.message,{cause:c});throw c}})}import{Worker as rp}from"node:worker_threads";var sp=1000,op=64,ip={status:"unavailable",reason:"deadline"},Ye={status:"unavailable",reason:"error"};function ap(){let t=import.meta.url;return t.endsWith(".ts")?new URL("./symbolWorker.ts",t):new URL("./symbolWorker.js",t)}function ic(t){let e=t.timeoutMs??sp,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>op){let m=a.keys().next().value;if(m===void 0)break;a.delete(m)}}function l(){let h=r;if(r=null,h!==null)h.terminate()}function u(){let h=new rp(ap(),{workerData:{grammarDir:t.grammarDir,queryDir:t.queryDir}});return h.unref(),h}function f(h,d){return new Promise((m)=>{if(r===null)try{r=u()}catch(b){w("Cannot start the symbol worker",b,{path:h}),m(Ye);return}let g=r,R=++s,y=!1,x=(b,M)=>{if(y)return;if(y=!0,clearTimeout(I),g.off("message",v),g.off("error",D),g.off("exit",T),M)l();m(b)},v=(b)=>{if(b.seq!==R)return;x(b.outcome,!1)},D=(b)=>{w("Symbol worker failed; discarding it",b,{path:h}),x(Ye,!0)},T=(b)=>{w(`Symbol worker exited with code ${b}; discarding it`,void 0,{path:h}),x(Ye,!0)},I=setTimeout(()=>{w(`Symbol extraction passed its ${e}ms deadline; discarding the worker`,void 0,{path:h}),x(ip,!0)},e);I.unref?.(),g.on("message",v),g.on("error",D),g.on("exit",T);let W={seq:R,relPath:h,content:d};try{g.postMessage(W)}catch(b){w("Cannot send a file to the symbol worker; discarding it",b,{path:h}),x(Ye,!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 Ye;let m=`${h}\x00${d}`,g=a.get(m);if(g!==void 0)return c(m,g),g;let R=o.then(()=>f(h,d));o=R.catch(()=>{return});let y=await R;return c(m,y),y},async dispose(){i=!0;let h=r;if(r=null,a.clear(),h!==null)await h.terminate()}}}import{spawn as cp}from"node:child_process";import*as cc from"node:fs";import*as lc from"node:path";class be extends Error{constructor(t){super(`Not a regular blob: ${t}`);this.name="NotRegularBlobError"}}class Re extends Error{size;constructor(t,e){super(`Blob too large: ${t} (${e} bytes)`);this.name="BlobTooLargeError",this.size=e}}class Ut extends Error{constructor(t){super(`Unsafe blob path: ${t}`);this.name="UnsafeBlobPathError"}}var Bn=65536,uc=/^[0-9a-f]{40}([0-9a-f]{24})?$/,lp=new Set(["100644","100755"]);function up(t){if(t==="")throw new Ut("empty");if(t.includes("\x00"))throw new Ut("contains NUL");if(t.startsWith("-"))throw new Ut('starts with "-"');if(t.startsWith(":"))throw new Ut('starts with ":"')}function Hn(t,e,n){return _t(t,[...dt,...e],n)}function fc(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 hc(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 fp=1;async function hp(t){let e;try{e=(await Hn(t,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],Bn)).toString("utf8").trim()}catch(n){if(n?.code===fp)return null;throw n}return uc.test(e)?e:null}async function dp(t,e){let n=await hp(t);if(n===null)return null;let r=await Hn(t,["ls-tree","-z","--full-tree","-l",n,"--",e],Bn),s=hc(fc(r),e);if(s===null||s.length!==4)return null;return{mode:s[0],oid:s[2],sizeText:s[3]}}async function pp(t,e){let n=await Hn(t,["ls-files","--stage","-z","--",e],Bn),r=hc(fc(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 dc(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 mp(t,e,n){let r=await Hn(t,["cat-file","-s",e],Bn);return dc(r.toString("utf8").trim(),n)}var ac=Buffer.alloc(0);function pc(t,e){let n=ac,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=ac,r=!1}}}function gp(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 m(){let g=cp("git",[...dt,"cat-file","blob",e],{cwd:t,env:vt(),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 x=setTimeout(()=>{n?.kill("SIGKILL"),d(Error(`git cat-file blob timed out for ${e}`))},ir);if(l={want:g,resolve:R,reject:y,timer:x},n===null)m();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 wp(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function yp(t,e,n){let r=lc.join(t,e),s;try{s=await cc.promises.open(r,se)}catch(o){if(wp(o))return null;throw o}try{let o=await s.stat();if(!o.isFile())throw new be(e);if(o.size>n)throw new Re(e,o.size);let i=o.size,a=pc(i,async(c,l)=>{let u=await oe(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 Ep(t,e,n,r){let s=e==="head"?await dp(t,n):await pp(t,n);if(s===null)return null;if(!lp.has(s.mode))throw new be(n);if(!uc.test(s.oid))throw Error(`git reported a malformed object id for ${n}`);let o=s.oid,i=s.sizeText===null?await mp(t,o,n):dc(s.sizeText,n);if(i>r)throw new Re(n,i);let a=gp(t,o),c=pc(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 mc(t,e,n,r){if(up(n),e==="worktree")return yp(t,n,r);return Ep(t,e,n,r)}var bp=["worktree","index","head"],Rp=16,Sp=ja,kp=ge,xp=["too-large","too-many-pixels"];function vp(t){let e=t.get("side");if(e===null||!bp.includes(e))throw new p(400,'Invalid "side" (expected worktree, index or head)');return e}function Ec(t){if(t instanceof be)throw new p(400,t.message,{cause:t});if(t instanceof Ut)throw new p(400,t.message,{cause:t});if(t instanceof Re)throw new p(413,t.message,{cause:t});throw t}async function gc(t,e){let n=await t.read(e);return{bytes:n,sniff:ye(n,t.size,n.length>=t.size)}}async function _p(t,e){let{size:n}=t,r=await t.read(Rp),s=ye(r,n,r.length>=n);if(!s.ok&&s.refusal==="too-large")return{bytes:r,sniff:s};let o=Math.min(On(r,n),n),i=await gc(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 gc(t,n)}async function bc(t,e,n,r){let s=await mc(t,e,n,ge);if(s===null)return null;try{let{bytes:o,sniff:i}=await _p(s,r);return{bytes:o,size:s.size,oid:s.oid,version:s.version,sniff:i}}finally{await s.close()}}function Ap(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 Dp(t){let e=xp.includes(t)?413:415;return new p(e,`Image not served: ${t}`)}function Tp(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 Ip(t,e,n){return{path:t.path,side:t.side,bytes:e,oid:null,image:null,refusal:n,version:""}}async function wc(t,e){let n=Wt(t.path,e.path);await Gt(t,n);let r;try{r=await bc(t.path,e.side,n,Sp)}catch(s){if(s instanceof Re)return Ip(e,s.size,"too-large");if(s instanceof be)return null;Ec(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 Mp(t,e){return e.writableEnded||e.destroyed===!0||t.destroyed===!0}async function yc(t,e,n){let r=t.acquire();if(r===null)throw new p(503,"Too many image requests in flight");let s=await r;if(n.once("finish",s),n.once("close",s),e.once("close",s),Mp(e,n))return s(),!1;return!0}function Rc(t,e,n){let{registry:r}=e;t.get("/repos/:id/media",async({params:s,query:o,req:i,res:a})=>{let c=S(r,s.id),l=V(o,"staged"),u=Wt(c.path,ct(o));if(await Gt(c,u),!await yc(n,i,a))return;let f=await de(c.manager.workingTree,u,l),h=Tp(f,l),d={old:h.old===null?null:await wc(c,h.old),new:h.new===null?null:await wc(c,h.new)};E(a,200,d)}),t.get("/repos/:id/blob",async({params:s,query:o,req:i,res:a})=>{let c=S(r,s.id),l=Vs(i);if(l)throw new p(l.status,l.message);let u=vp(o),f=Wt(c.path,ct(o));if(await Gt(c,f),!await yc(n,i,a))return;let h;try{h=await bc(c.path,u,f,kp)}catch(m){Ec(m)}if(h===null)throw new p(404,`No such blob on side ${u}: ${f}`);if(!h.sniff.ok)throw Dp(h.sniff.refusal);let d=Ap(u,h.sniff.info.mime,h.oid);Us(a,200,h.bytes,d)})}function Sc(t,e){let{registry:n,sse:r,daemonEvents:s,follow:o}=e;t.get("/events",({req:i,res:a,query:c})=>{let l=n.listRepos().map((f)=>({id:f.id,path:f.path}));s.subscribe(i,a,l);let u=c.get("repo");if(!u)return;r.attach(u,n.getRepo(u)?.manager??null,i,a)}),t.get("/follow",({res:i})=>{E(i,200,o?o.state:ea)})}import*as ys from"node:os";import*as Se from"node:path";function kc(t,e){let{settings:n,discovery:r,daemonEvents:s}=e,o=()=>({...n.settings,persisted:n.persisted});t.get("/settings",({res:i})=>{E(i,200,o())}),t.put("/settings",async({body:i,res:a})=>{let c=ba(i,"watchRoots"),l;try{l=ra(c)}catch(f){throw new p(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 p(500,`Could not save settings: ${h}`,{cause:f})}await r.setRoots(l);let u=o();s.broadcast("settings-change",u),E(a,200,u)}),t.get("/discovered",({res:i})=>{E(i,200,r.state)}),t.get("/browse",async({query:i,res:a})=>{let c=i.get("path"),l=c?ot(c):ys.homedir();if(!Se.isAbsolute(l))throw new p(400,`Path must be absolute: ${c}`);let u=Se.resolve(l),f;try{f=await oa(u)}catch(d){throw new p(404,`Cannot read directory: ${u}`,{cause:d})}let h=Se.dirname(u);E(a,200,{path:u,parent:h===u?null:h,home:ys.homedir(),entries:f})}),t.post("/discovered/rescan",async({res:i})=>{E(i,200,await r.rescan())})}function Es(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}}}import{execFile as Op}from"node:child_process";function Cp(){return new RegExp("\\{\\{[^{}\\n]+\\}\\}","g")}function Pp(t){let e=[];for(let n of t.matchAll(Cp()))e.push({start:n.index,end:n.index+n[0].length});return e}function xc(t){return Pp(t).length}function bs(t){return t.replace(/\r\n/g,`
|
|
51
|
+
`).trim()}function Fp(t,e){for(let n=e;n<t.length;n++){if(t[n].trim()==="")continue;return t[n].startsWith("<details>")}return!1}function vc(t){let e=t.replace(/\r\n/g,`
|
|
52
52
|
`).split(`
|
|
53
|
-
`),n=
|
|
54
|
-
`).trim()}function
|
|
53
|
+
`),n=_c(e);return e.slice(0,n??e.length).join(`
|
|
54
|
+
`).trim()}function _c(t){for(let e=0;e<t.length;e++)if(t[e]==="---"&&Fp(t,e+1))return e;return null}function Ac(t,e){let n=t.replace(/\r\n/g,`
|
|
55
55
|
`).split(`
|
|
56
|
-
`),r=
|
|
56
|
+
`),r=_c(n),s=bs(e);if(r===null)return s;let o=n.slice(r).join(`
|
|
57
57
|
`);return s===""?o:`${s}
|
|
58
58
|
|
|
59
|
-
${o}`}var
|
|
60
|
-
`).find((n)=>n.trim()!=="");return e===void 0?null:e.trim().slice(0,
|
|
61
|
-
headRefName headRefOid baseRefName ${
|
|
59
|
+
${o}`}var Rs=20000,Np=33554432,$p=100,Cc=200,ks=10,Lp=3,Bp=600000,Hp=["api","graphql","--input","-"];class q extends Error{kind;constructor(t,e,n){super(e,n);this.kind=t,this.name="GhError"}}function Wp(t){let e=t.split(`
|
|
60
|
+
`).find((n)=>n.trim()!=="");return e===void 0?null:e.trim().slice(0,Cc)}function Pc(){return{available:()=>ns.onPath(["gh"])!==null,run:(t,e,n)=>new Promise((r,s)=>{Op("gh",[...t],{timeout:e,maxBuffer:Np,windowsHide:!0,encoding:"utf8",env:{...process.env,GH_PROMPT_DISABLED:"1",GH_NO_UPDATE_NOTIFIER:"1",NO_COLOR:"1"}},(i,a,c)=>{if(!i)r(a);else if(i.code==="ENOENT")s(new q("missing","gh not found"));else if(i.code===4)s(new q("logged-out","gh is not logged in"));else if(i.killed)s(new q("failed","gh timed out"));else s(new q("failed",Wp(c)??`gh failed (exit ${i.code})`))}).stdin?.end(n??"")})}}var Ve="author { __typename login }",Fc=`number title url state isDraft merged mergedAt closedAt updatedAt
|
|
61
|
+
headRefName headRefOid baseRefName ${Ve}
|
|
62
62
|
headRepositoryOwner { login }
|
|
63
|
-
repository { nameWithOwner }`,
|
|
63
|
+
repository { nameWithOwner }`,Oc=`${Fc}
|
|
64
64
|
reviewDecision mergeable
|
|
65
|
-
commits(last: 1) { nodes { commit { committedDate statusCheckRollup { state } } } }`,
|
|
65
|
+
commits(last: 1) { nodes { commit { committedDate statusCheckRollup { state } } } }`,Gp=`body
|
|
66
66
|
reviewRequests(first: 20) { totalCount nodes { requestedReviewer {
|
|
67
67
|
__typename ... on User { login } ... on Team { slug } } } }
|
|
68
|
-
latestOpinionatedReviews(first: 20) { nodes { ${
|
|
69
|
-
reviews(last: 20) { nodes { ${
|
|
70
|
-
comments(last: 20) { nodes { ${
|
|
71
|
-
reviewThreads(first: 100) { nodes { isResolved comments(last: 1) { nodes { ${
|
|
72
|
-
${
|
|
68
|
+
latestOpinionatedReviews(first: 20) { nodes { ${Ve} state } }
|
|
69
|
+
reviews(last: 20) { nodes { ${Ve} state submittedAt } }
|
|
70
|
+
comments(last: 20) { nodes { ${Ve} createdAt } }
|
|
71
|
+
reviewThreads(first: 100) { nodes { isResolved comments(last: 1) { nodes { ${Ve} createdAt } } } }`,Nc=`fragment Pr on PullRequest { id ${Oc}
|
|
72
|
+
${Gp} }`;function $c(t,e){return`query($q: String!, $after: String) {${e?`
|
|
73
73
|
viewer { login }`:""}
|
|
74
|
-
search(query: $q, type: ISSUE, first: ${
|
|
74
|
+
search(query: $q, type: ISSUE, first: ${$p}, after: $after) {
|
|
75
75
|
pageInfo { hasNextPage endCursor }
|
|
76
76
|
nodes { ... on PullRequest { ${t} } }
|
|
77
77
|
}
|
|
78
|
-
}`}var
|
|
78
|
+
}`}var Dc=$c(Oc,!0),Up=$c(Fc,!1);function jp(t){let e=Array.from({length:t},(s,o)=>o),n=e.map((s)=>`$owner${s}: String!, $name${s}: String!, $number${s}: Int!`),r=e.map((s)=>` p${s}: repository(owner: $owner${s}, name: $name${s}) { pullRequest(number: $number${s}) { ...Pr } }`);return`query(${n.join(", ")}) {
|
|
79
79
|
${r.join(`
|
|
80
80
|
`)}
|
|
81
81
|
}
|
|
82
|
-
${
|
|
82
|
+
${Nc}`}var qp=Array.from({length:ks},(t,e)=>jp(e+1)),Xp=`mutation($id: ID!, $body: String!) {
|
|
83
83
|
updatePullRequest(input: { pullRequestId: $id, body: $body }) { pullRequest { ...Pr } }
|
|
84
84
|
}
|
|
85
|
-
${Oc}`,qp="is:pr author:@me is:open",Xp="is:pr is:open review-requested:@me",zp="is:pr author:@me is:closed sort:updated-desc",Jp=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;function Yp(t){let e=new Date(t-$p),n=(s)=>String(s).padStart(2,"0"),r=`${e.getUTCFullYear()}-${n(e.getUTCMonth()+1)}-${n(e.getUTCDate())}T${n(e.getUTCHours())}:${n(e.getUTCMinutes())}:${n(e.getUTCSeconds())}Z`;if(!Jp.test(r))throw new q("failed","The clock gave no usable date");return`is:pr author:@me is:closed updated:>=${r} sort:updated-desc`}var Kp=/^[A-Za-z0-9+/=_:][A-Za-z0-9+/=_:-]{0,199}$/,Vp=/^([A-Za-z0-9_.-]{1,100})\/([A-Za-z0-9_.-]{1,100})$/;function J(t){return new q("failed",`GitHub answered in an unexpected shape (${t})`)}function O(t,e){if(typeof t!=="object"||t===null||Array.isArray(t))throw J(e);return t}function H(t,e){let n=t[e];if(typeof n!=="string")throw J(e);return n}function Se(t,e){let n=t[e];if(n===null)return null;if(typeof n!=="string")throw J(e);return n}function $n(t,e){let n=t[e];if(typeof n!=="boolean")throw J(e);return n}function Qp(t){let e;try{e=JSON.parse(t)}catch{throw new q("failed","gh answered with something that is not JSON")}return O(e,"answer")}function Zp(t){if(t.data!==null&&t.data!==void 0)return O(t.data,"data");let e=t.errors;if(Array.isArray(e)&&e.length>0){let n=e[0]?.message;if(typeof n==="string")throw new q("failed",n.slice(0,Mc))}throw J("data")}function tm(t){let e=H(t,"state");if($n(t,"merged")||e==="MERGED")return"merged";if(e==="CLOSED")return"closed";if(e==="OPEN")return"open";throw J("state")}function jt(t,e){let n=O(t[e],e).nodes;if(!Array.isArray(n))throw J(`${e}.nodes`);return n}function ks(t){if(t.author===null)return null;let e=O(t.author,"author");if(e.__typename==="Bot")return null;return H(e,"login")}var em={APPROVED:"approved",CHANGES_REQUESTED:"changes-requested",COMMENTED:"reviewed"};function nm(t){let e=[];for(let n of jt(t,"reviews")){let r=O(n,"review"),s=em[H(r,"state")],o=Se(r,"submittedAt"),i=ks(r);if(s!==void 0&&o!==null&&i!==null)e.push({kind:s,author:i,at:o})}return e}function $c(t){let e=O(t,"comment"),n=ks(e);return n===null?null:{kind:"commented",author:n,at:H(e,"createdAt")}}function rm(t){let e=[],n=0;for(let r of jt(t,"reviewThreads")){let s=O(r,"review thread");if(!$n(s,"isResolved"))n+=1;for(let o of jt(s,"comments")){let i=$c(o);if(i!==null)e.push(i)}}return{events:e,unresolved:n}}function sm(t){let e=new Set;return t.sort((n,r)=>Date.parse(r.at)-Date.parse(n.at)).filter((n)=>{let r=`${n.kind}|${n.author}|${n.at.slice(0,16)}`;if(e.has(r))return!1;return e.add(r),!0}).slice(0,Ei)}var om={APPROVED:"approved",CHANGES_REQUESTED:"changes-requested",REVIEW_REQUIRED:"review-required"},im={SUCCESS:"success",FAILURE:"failure",ERROR:"failure",PENDING:"pending",EXPECTED:"pending"};function am(t){let e=jt(t,"commits")[0];if(e===void 0)return{committedAt:null,checks:null};let n=O(O(e,"commit node").commit,"commit"),r=n.statusCheckRollup,s=r===null?null:im[H(O(r,"statusCheckRollup"),"state")]??null;return{committedAt:Se(n,"committedDate"),checks:s}}function cm(t){let e=O(t,"review request").requestedReviewer;if(e===null)return null;let n=O(e,"requestedReviewer");if(typeof n.login==="string")return n.login;if(typeof n.slug==="string")return`team:${n.slug}`;return null}function lm(t){let e=[];for(let n of jt(t,"latestOpinionatedReviews")){let r=O(n,"review"),s=ks(r);if(s!==null&&H(r,"state")==="CHANGES_REQUESTED")e.push(s)}return e}function Lc(t){let e=Se(t,"reviewDecision"),n=am(t);return{decision:e===null?null:om[e]??null,checks:n.checks,headCommittedAt:n.committedAt,conflicting:H(t,"mergeable")==="CONFLICTING"}}function um(t){let e=rm(t),r=O(t.reviewRequests,"reviewRequests").totalCount;if(typeof r!=="number")throw J("reviewRequests.totalCount");let s=jt(t,"reviewRequests").map(cm).filter((i)=>i!==null),o=jt(t,"comments").map($c).filter((i)=>i!==null);return{...Lc(t),unresolvedThreads:e.unresolved,pendingReviewers:r,requestedReviewers:s,changesRequestedBy:lm(t),events:sm([...nm(t),...o,...e.events])}}function xs(t){let e=O(t,"pull request"),n=e.number;if(typeof n!=="number"||!Number.isInteger(n)||n<1)throw J("number");let r=H(e,"url");if(!r.startsWith("https://"))throw J("url");let s=e.headRepositoryOwner===null?null:H(O(e.headRepositoryOwner,"headRepositoryOwner"),"login"),o=H(O(e.repository,"repository"),"nameWithOwner");return{number:n,title:H(e,"title"),url:r,state:tm(e),isDraft:$n(e,"isDraft"),mergedAt:Se(e,"mergedAt"),closedAt:Se(e,"closedAt"),updatedAt:H(e,"updatedAt"),body:null,headRefName:H(e,"headRefName"),headRefOid:H(e,"headRefOid"),baseRefName:H(e,"baseRefName"),progress:null,headOwner:s,author:e.author===null?null:H(O(e.author,"author"),"login"),reviewRequested:!1,repo:o,repoKey:o.toLowerCase()}}function Dc(t){return{pr:xs(t),live:Lc(O(t,"pull request"))}}function Bc(t){let e=O(t,"pull request");return{id:H(e,"id"),pr:{...xs(e),body:H(e,"body"),progress:um(e)}}}function fm(t,e){let n=O(t,"search"),r=O(n.pageInfo,"pageInfo");if(!Array.isArray(n.nodes))throw J("nodes");return{items:n.nodes.map(e),hasNextPage:$n(r,"hasNextPage"),endCursor:Se(r,"endCursor")}}async function vs(t,e,n,r){let s=JSON.stringify({query:e,variables:n});return Zp(Qp(await t.run(Lp,r,s)))}async function Ss(t,e,n,r,s){let o=[],i,a=null;for(;;){let c=await vs(t,e,{q:n,after:a},s());i??=c;let l=fm(c.search,r);if(o.push(...l.items),!l.hasNextPage||o.length>=pn)return{items:o.slice(0,pn),capped:l.hasNextPage,first:i};if(l.endCursor===null||!Kp.test(l.endCursor))throw J("endCursor");a=l.endCursor}}function hm(t){let e=Vp.exec(t.repo);if(e===null)throw J("nameWithOwner");return{owner:e[1],name:e[2]}}async function Hc(t,e,n){let r={};e.forEach((o,i)=>{let{owner:a,name:c}=hm(o);r[`owner${i}`]=a,r[`name${i}`]=c,r[`number${i}`]=o.number});let s=await vs(t,Up[e.length-1],r,n);return e.map((o,i)=>{let a=O(s[`p${i}`],"repository").pullRequest;if(a===null)throw new q("failed","GitHub no longer has this PR");return Bc(a)})}function Rt(t){return`${t.repoKey}#${t.number}`}function dm(t,e){return t!==void 0&&t.updatedAt===e.updatedAt&&t.headRefOid===e.headRefOid}async function pm(t,e,n,r){let s=[];for(let u=0;u<e.length;u+=Rs)s.push(e.slice(u,u+Rs));let o=0,i=!1,a=async()=>{while(!i&&o<s.length){let u=s[o++];try{(await Hc(t,u,r())).forEach((h,d)=>n.set(Rt(u[d]),h.pr))}catch(f){throw i=!0,f}}},c=Array.from({length:Math.min(Np,s.length)},a),l=(await Promise.allSettled(c)).find((u)=>u.status==="rejected");if(l!==void 0)throw l.reason}function bs(t,e){let n=Number(e.state==="open")-Number(t.state==="open");if(n!==0)return n;let r=Date.parse(e.updatedAt)-Date.parse(t.updatedAt);if(r!==0&&!Number.isNaN(r))return r;if(t.repoKey!==e.repoKey)return t.repoKey<e.repoKey?-1:1;return t.number-e.number}function Tc(t){let e=new Map;for(let n of t){let r=Rt(n),s=e.get(r);if(s===void 0||Date.parse(n.updatedAt)>Date.parse(s.updatedAt))e.set(r,n)}return[...e.values()]}async function mm(t,e,n){let[r,s]=await Promise.all([Ss(t,Ac,qp,Dc,n),Ss(t,Ac,Xp,Dc,n)]),o=s.items.map(({pr:l,live:u})=>({pr:{...l,reviewRequested:!0},live:u})),i=[...r.items,...o],a=new Map;for(let{pr:l}of i)if(!dm(e.get(Rt(l)),l))a.set(Rt(l),l);return await pm(t,[...a.values()],e,n),{prs:i.map(({pr:l,live:u})=>{let f=e.get(Rt(l));if(f===void 0)throw J("details");return{...l,body:f.body,progress:{...f.progress,...u}}}),viewer:H(O(r.first.viewer,"viewer"),"login"),capped:r.capped,read:a.size}}var Ic={missing:"gh-missing","logged-out":"gh-logged-out",failed:"error"};class Ln extends Error{constructor(){super("The PR's top zone changed on GitHub since it was shown. Check again first.");this.name="TopZoneChangedError"}}function Wc(t,e=Date.now){let n={status:"never",message:null,checkedAt:null,viewer:null,prs:[],capped:!1},r=null,s=new Map,o=null;async function i(u){let f=e(),h=o===null?zp:Yp(o.since),d=performance.now()+Es,m=()=>{let v=Math.floor(d-performance.now());if(v<=0)throw new q("failed","gh timed out");return v},[g,R]=await Promise.all([mm(u,s,m),Ss(u,Wp,h,xs,m)]),y=Tc([...R.items,...o?.prs??[]]).sort(bs).slice(0,pn);o={prs:y,since:f};let x=new Set(g.prs.map(Rt));for(let v of s.keys())if(!x.has(v))s.delete(v);return G("PR refresh",void 0,{readWhole:g.read,closedFound:R.items.length}),{status:"ok",message:null,checkedAt:e(),viewer:g.viewer,prs:Tc([...g.prs,...y]).sort(bs),capped:g.capped}}async function a(){if(t===null)return n={...n,status:"gh-missing",message:null},n;try{n=await i(t)}catch(u){if(u instanceof q)w("PR refresh failed",u,{status:Ic[u.kind]}),n={...n,status:Ic[u.kind],message:u.kind==="failed"?u.message:null};else C("PR refresh threw",u),n={...n,status:"error",message:"Unexpected failure reading the PRs"}}return n}function c(u){s.set(Rt(u),u);let f=(d)=>Rt(d)===Rt(u),h=n.prs.some(f)?n.prs.map((d)=>f(d)?u:d):[u,...n.prs];return n={...n,prs:h.sort(bs)},u}async function l(u){if(t===null)throw new q("missing","gh not found");let[f]=await Hc(t,[u],Es);return f}return{snapshot:()=>n,async checkOne(u){return c((await l(u)).pr)},async setTopZone(u,f,h){let d=await l(u);if(c(d.pr),d.pr.state!=="open")throw new q("failed","The PR is not open");if(xc(d.pr.body)!==ys(h))throw new Ln;let m=await vs(t,jp,{id:d.id,body:_c(d.pr.body,f)},Es),g=O(m.updatePullRequest,"updatePullRequest").pullRequest;return G("PR top zone updated",void 0,{pr:`${d.pr.repo}#${d.pr.number}`}),c(Bc(g).pr)},refresh(){return r??=a().finally(()=>{r=null}),r},prFor(u,f){let h=new Set(u.map((d)=>d.toLowerCase()));return n.prs.find((d)=>h.has(d.repoKey)&&d.headRefName===f)??null},ghAvailable:()=>t?.available()??!1}}import*as ut from"node:fs";import*as qc from"node:path";var ke=2000,Xc=4096,zc=512,gm=["track","dismiss","drop","undismiss"];function Bn(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function _s(t){return typeof t==="string"&&t.length>=1&&t.length<=Xc&&!t.includes("\x00")}function Jc(t){return typeof t==="string"&&t.length<=zc}function Gc(t){return typeof t==="number"&&Number.isFinite(t)}function Yc(t){if(!Bn(t))throw new p(400,'Expected a JSON body with "key" and "action"');let{key:e,action:n,fingerprint:r,prune:s}=t;if(!_s(e))throw new p(400,`Invalid "key" (a string of 1 to ${Xc} characters, no NUL)`);if(typeof n!=="string"||!gm.includes(n))throw new p(400,'Invalid "action" (track, dismiss, drop or undismiss)');if(r!==void 0&&!Jc(r))throw new p(400,`Invalid "fingerprint" (a string of at most ${zc} characters)`);if(n==="dismiss"&&r===void 0)throw new p(400,'"dismiss" needs a "fingerprint"');if(s!==void 0&&(!Array.isArray(s)||s.length>ke||!s.every(_s)))throw new p(400,`Invalid "prune" (at most ${ke} keys)`);let o={key:e,action:n};if(r!==void 0)o.fingerprint=r;if(s!==void 0)o.prune=s;return o}function Uc(t,e){let n=new Map;if(!Bn(t))return n;for(let[r,s]of Object.entries(t)){if(n.size>=ke)break;let o=_s(r)&&Bn(s)?e(s):null;if(o!==null)n.set(r,o)}return n}function wm(t){let e=Bn(t)?t:{};return{tracked:Uc(e.tracked,(n)=>Gc(n.at)?{at:n.at}:null),dismissed:Uc(e.dismissed,(n)=>Jc(n.fingerprint)&&Gc(n.at)?{fingerprint:n.fingerprint,at:n.at}:null)}}function ym(t){let e;try{e=ut.readFileSync(t,"utf-8")}catch(n){if(n.code!=="ENOENT")C("Cannot read the work marks file; using none",n,{file:t});return{}}try{return JSON.parse(e)}catch(n){return w("Ignoring the work marks file: not valid JSON",n,{file:t}),{}}}function jc(t,e){return{tracked:Object.fromEntries(t),dismissed:Object.fromEntries(e)}}class As{file;tracked=new Map;dismissed=new Map;constructor(t){this.file=t}get marks(){return jc(this.tracked,this.dismissed)}load(){if(this.file===null)return this.marks;return{tracked:this.tracked,dismissed:this.dismissed}=wm(ym(this.file)),this.marks}apply(t,e){this.load();let n=new Map(this.tracked),r=new Map(this.dismissed);for(let s of t.prune??[])n.delete(s),r.delete(s);switch(t.action){case"track":n.set(t.key,{at:e});break;case"drop":n.delete(t.key);break;case"dismiss":r.set(t.key,{fingerprint:t.fingerprint??"",at:e});break;case"undismiss":r.delete(t.key);break}if(n.size>ke||r.size>ke)throw new p(400,`Too many marks (at most ${ke} of each kind)`);return this.persist(jc(n,r)),this.tracked=n,this.dismissed=r,this.marks}persist(t){if(this.file===null)return;ut.mkdirSync(qc.dirname(this.file),{recursive:!0});let e=`${this.file}.${process.pid}.tmp`;try{ut.writeFileSync(e,`${JSON.stringify(t,null,2)}
|
|
86
|
-
`,{mode:384}),ut.renameSync(e,this.file)}catch(n){throw ut.rmSync(e,{force:!0}),n}}}import*as
|
|
87
|
-
`)){if(!
|
|
88
|
-
`)){let s=r.indexOf(" ");if(s===-1)continue;let o=
|
|
89
|
-
`).filter(Boolean)}catch(e){return w("default base-branch discovery failed",e,{repo:t}),null}}async function Fm(t,e,n){let[r,s]=await Promise.all([Im(t),Pm(t)]),o=s===null?null:dr(s,r.remotes);return Promise.all([Sr(e,o,n),Cm(t,r)])}function Om(t,e){if(t.isBare)return t.path;let n=Y(t.path)??Y(e);if(n===null)throw Error(`Cannot find the git dir of ${e}`);return n.commonDir}async function el(t){let e=await br(t,{pooled:!0});if(e.length===0)return null;let n=e.find((h)=>h.isMain)??e[0],r=n.path,s=Om(n,t),[o,[i,{branches:a,capped:c}],l,u]=await Promise.all([Promise.all(e.map(Am)),Fm(t,e,Oe()),Ts(t),Ti(s)]),f=i.map((h,d)=>({path:h.path,branch:h.branch,head:h.head,isMain:h.isMain,isBare:h.isBare,lastActivity:h.lastActivity,changedAt:o[d].changedAt,aheadOfBase:h.aheadOfBase,base:h.baseBranch,uncommitted:o[d].uncommitted}));return{path:t,root:r,name:Dm(n),worktrees:f,branches:a,branchesCapped:c,identities:l,drafts:u}}function Nm(t){let e=new Set;for(let n of t.discovery.state.roots)for(let r of n.repos)e.add(r.path);for(let n of t.registry.listRepos())e.add(n.path);return e}var $m=5000;function Lm(t){let e=Y(t);if(e===null)return null;try{return nl.realpathSync(e.commonDir)}catch{return null}}function rl(t=el,e=Lm,n=$m){let r=new Map;function s(o,i){let a={facts:t(i),done:!1,answered:new Set};r.set(o,a);let c=()=>{if(r.get(o)===a)r.delete(o)};return a.facts.then(()=>{a.done=!0,setTimeout(c,n).unref()},c),a}return async(o)=>{let i=e(o)??o,a=r.get(i);if(a===void 0||a.done&&a.answered.has(o))a=s(i,o);a.answered.add(o);let c=await a.facts;return c===null?null:{...c,path:o}}}function sl(t,e,n){let{prs:r,workMarks:s}=e;t.post("/work/repo",async({body:o,res:i})=>{let a=L(o,"path");if(!Un.isAbsolute(a))throw new p(400,`Repo path must be absolute: ${a}`);let c=Un.resolve(a);if(!Nm(e).has(c))throw new p(404,`Not a discovered or open repo: ${c}`);let l;try{l=await n(c)}catch(u){throw new p(500,`Could not scan ${c}`,{cause:u})}if(l===null)throw new p(404,`Not a git repository: ${c}`);E(i,200,l)}),t.get("/work/prs",({res:o})=>{E(o,200,r.snapshot())}),t.post("/work/prs/refresh",async({res:o})=>{E(o,200,await r.refresh())}),t.get("/work/marks",({res:o})=>{E(o,200,s.load())}),t.put("/work/marks",({body:o,res:i})=>{let a=Yc(o),c;try{c=s.apply(a,Date.now())}catch(l){if(l instanceof p)throw l;let u=l instanceof Error?l.message:String(l);throw new p(500,`Could not save marks: ${u}`,{cause:l})}E(i,200,c)})}function ol(t){let e=Ue(t,"branch");if(e===null)throw new p(400,'Missing "branch" query parameter');return e}function jn(t){let e=Y(t.path);if(e===null)throw new p(500,"Cannot find the git directory of this repository");return e.commonDir}async function qn(t,e){try{return await t()}catch(n){if(n instanceof $t)throw new p(400,n.message);if(n instanceof ae)throw new p(409,n.message);if(n instanceof Dt)throw new p(422,n.message);throw new p(500,e,{cause:n})}}async function cl(t){try{return await Ts(t.path)}catch(e){throw new p(500,"Could not read the remotes",{cause:e})}}async function il(t,e,n){let r=t.prFor(await cl(e),n);if(r===null)throw new p(404,"No PR is known for this branch");return r}function al(t){if(t instanceof Ln)return new p(409,t.message);if(t instanceof q){let e=t.kind==="failed"?502:503;return new p(e,t.message,{cause:t})}return new p(500,"Could not reach GitHub",{cause:t})}function Is(t,e){let n=t.snapshot();return{pr:e,status:n.status,message:n.message,checkedAt:n.checkedAt,viewer:n.viewer}}function ll(t,e){let{registry:n,prs:r}=e;t.get("/repos/:id/draft",async({params:s,query:o,res:i})=>{let a=S(n,s.id),c=ol(o),l=jn(a);E(i,200,await qn(()=>Or(l,c),"Could not read the draft"))}),t.put("/repos/:id/draft",async({params:s,body:o,res:i})=>{let a=S(n,s.id),c=et(o,"branch"),l=L(o,"top",{allowEmpty:!0}),u=L(o,"version");if(Buffer.byteLength(l,"utf8")>ie)throw new p(413,`Draft is larger than ${ie} bytes`);let f=jn(a),h=await qn(()=>Ai(f,c,l,u),"Could not save the draft");E(i,200,h)}),t.post("/repos/:id/draft/adopt",async({params:s,body:o,res:i})=>{let a=S(n,s.id),c=et(o,"branch"),l=L(o,"version"),u=jn(a),f=await qn(()=>Di(u,c,l),"Could not save the draft");E(i,200,f)}),t.get("/repos/:id/pr",async({params:s,query:o,res:i})=>{let a=S(n,s.id),c=ol(o),l=r.prFor(await cl(a),c);E(i,200,Is(r,l))}),t.post("/repos/:id/pr/check",async({params:s,body:o,res:i})=>{let a=S(n,s.id),c=et(o,"branch"),l=await il(r,a,c),u;try{u=await r.checkOne(l)}catch(f){throw al(f)}E(i,200,Is(r,u))}),t.post("/repos/:id/pr/top",async({params:s,body:o,res:i})=>{let a=S(n,s.id),c=et(o,"branch"),l=L(o,"version"),u=L(o,"expectedTop",{allowEmpty:!0}),f=jn(a),h=await qn(()=>Or(f,c),"Could not read the draft");if(h.version!==l)throw new p(409,"top.md changed since it was shown");let d=h.top??"";if(d.trim()==="")throw new p(422,"top.md is empty: there is nothing to send");if(kc(d)>0)throw new p(422,"top.md still has a {{...}} placeholder");let m=await il(r,a,c);if(m.state!=="open")throw new p(409,"The PR is not open");let g;try{g=await r.setTopZone(m,d,u)}catch(R){throw al(R)}E(i,200,Is(r,g))})}function Bm(t){if(!Xt.existsSync(t))return Promise.resolve(!1);return new Promise((e)=>{try{let n=fl.connect(t);n.once("connect",()=>{n.destroy(),e(!0)}),n.once("error",()=>{n.destroy(),e(!1)})}catch{e(!1)}})}function hl(t={}){let e=new qr,n=new Xr,r=new jr({onOpened:(b)=>n.broadcast("repo-opened",{id:b.id,path:b.path}),onClosed:(b)=>{e.closeRepo(b),n.broadcast("repo-closed",{id:b})}}),s=t.followFile?new Jr(r,n,t.followFile):null,o=ha(t.updateCheck===!1?()=>Promise.resolve(null):t.fetchLatestVersion),i=new Kr(t.settingsFile??null),a=new Zr(n),c=new Map,l=ws(),u=Wc(t.gh??null),f=new As(t.workMarksFile??null),h=rl(),d=t.symbols??null,m=d===null?null:{pool:oc(d),gate:ws(1,4),extensions:d.extensions};function g(b){let M=c.get(b);if(M)return M;let _=new Zn,A={registry:r,sse:e,daemonEvents:n,follow:s,settings:i,discovery:a,apiMode:b,version:o,symbols:m,httpPort:D,prs:u,workMarks:f};if(pa(_,A),ma(_,A),_a(_,A),Ta(_,A),Ha(_,A),Wa(_,A),b==="full")Ga(_,A);return Qa(_,A),sc(_,A),bc(_,A,l),Rc(_,A),Sc(_,A),sl(_,A,h),ll(_,A),c.set(b,_),_}let R=(b)=>t.apiMode??(b==="tcp"?"web":"full");s?.start(),a.setRoots(i.load().watchRoots);let y=t.webRoot?js(t.webRoot):void 0,x=new Set,v=[];function D(){for(let b of v){let M=b.server.address();if(M!==null&&typeof M==="object")return M.port}return null}function T(b){let M=g(b),_=ul.createServer((A,Jt)=>{for(let[ft,Ye]of Object.entries(Ks))Jt.setHeader(ft,Ye);if(zs(_.address())){let ft=Js(A);if(ft){E(Jt,ft.status,{error:ft.message});return}}M.handle(A,Jt,y).catch((ft)=>{C(`${A.method??"GET"} ${A.url??"/"} escaped the router`,ft),Jt.end()})});return _.on("connection",(A)=>{x.add(A),A.on("close",()=>x.delete(A))}),_}async function I(b,M){let _=b==="unix"?M.socketPath??null:null;if(_){if(await Bm(_))throw Error(`diffstalkerd already running at ${_}`);Xt.rmSync(_,{force:!0})}let A={server:T(R(b)),socketPath:_};v.push(A),await new Promise((Jt,ft)=>{let Ye=(Sl)=>ft(Sl);A.server.once("error",Ye);let zn=()=>{if(A.server.removeListener("error",Ye),_)Xt.chmodSync(_,384);Jt()};if(b==="fd")A.server.listen({fd:M.fd},zn);else if(_)process.umask(63),A.server.listen(_,zn);else A.server.listen(M.port,"127.0.0.1",zn)})}function W(b){return new Promise((M,_)=>{b.server.close((A)=>{if(b.socketPath)Xt.rmSync(b.socketPath,{force:!0});if(A&&A.code!=="ERR_SERVER_NOT_RUNNING")_(A);else M()})})}return{address(){return v[0]?.server.address()??null},addresses(){return v.map((b)=>b.server.address()).filter((b)=>b!==null)},getRepo(b){return r.getRepo(b)},async openRepo(b){let{handle:M}=await xn(r,b);return{id:M.id,path:M.path}},async listen(b){let M=[];if(b.fd!==void 0)M.push("fd");if(b.socketPath)M.push("unix");if(b.port!==void 0)M.push("tcp");if(M.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let _ of M)await I(_,b)},close(){s?.dispose(),a.dispose(),e.destroy(),n.destroy(),r.disposeAll();for(let M of x)M.destroy();let b=m?.pool.dispose()??Promise.resolve();return Promise.all([b,...v.splice(0).map(W)]).then(()=>{})}}}import*as Ms from"node:fs";import*as xe from"node:path";import*as yl from"node:crypto";import{createRequire as Wm}from"node:module";var dl=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 pl(){return[...dl.keys()]}function Hm(t){let e=t.slice(t.lastIndexOf("/")+1),n=e.lastIndexOf(".");if(n<=0)return"";return e.slice(n).toLowerCase()}function ml(t){return dl.get(Hm(t))??null}var Gm="diffstalkerd-grammars";function Um(t){return yl.createHash("sha256").update(t).digest("hex")}function jm(t){try{let e=JSON.parse(Ms.readFileSync(xe.join(t,"checksums.json"),"utf8"));if(typeof e.webTreeSitterVersion!=="string"||typeof e.files!=="object")return null;return e}catch{return null}}var gl="0.26.11";function qm(t,e,n){for(let[r,s]of Object.entries(e.files)){let o;try{o=Ms.readFileSync(xe.join(t,r))}catch{return n(`grammars: missing ${r}`),!1}if(Um(o)!==s)return n(`grammars: checksum mismatch for ${r}`),!1}return!0}function Xm(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 wl(t,e=()=>{}){let n=jm(t);if(n===null)return e(`grammars: no readable checksums.json in ${t}`),null;if(n.webTreeSitterVersion!==gl)return e(`grammars: built for web-tree-sitter ${n.webTreeSitterVersion}, this daemon bundles ${gl} — symbols disabled`),null;if(!qm(t,n,e))return null;let r=Xm(n),s=pl().filter((o)=>{let i=ml(`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:xe.join(t,"queries"),extensions:s}}function El(t,e=()=>{}){if(t!==null)return wl(t,e);try{let r=Wm(import.meta.url).resolve(`${Gm}/checksums.json`);return wl(xe.dirname(r),e)}catch{return null}}var Rl="diffstalkerd.sock";function Jm(t){return t===void 0?Rl:`${t}.sock`}var Ym=3,bl=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
|
|
85
|
+
${Nc}`,zp="is:pr author:@me is:open",Jp="is:pr is:open review-requested:@me",Kp="is:pr author:@me is:closed sort:updated-desc",Yp=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;function Vp(t){let e=new Date(t-Bp),n=(s)=>String(s).padStart(2,"0"),r=`${e.getUTCFullYear()}-${n(e.getUTCMonth()+1)}-${n(e.getUTCDate())}T${n(e.getUTCHours())}:${n(e.getUTCMinutes())}:${n(e.getUTCSeconds())}Z`;if(!Yp.test(r))throw new q("failed","The clock gave no usable date");return`is:pr author:@me is:closed updated:>=${r} sort:updated-desc`}var Qp=/^[A-Za-z0-9+/=_:][A-Za-z0-9+/=_:-]{0,199}$/,Zp=/^([A-Za-z0-9_.-]{1,100})\/([A-Za-z0-9_.-]{1,100})$/;function J(t){return new q("failed",`GitHub answered in an unexpected shape (${t})`)}function O(t,e){if(typeof t!=="object"||t===null||Array.isArray(t))throw J(e);return t}function H(t,e){let n=t[e];if(typeof n!=="string")throw J(e);return n}function ke(t,e){let n=t[e];if(n===null)return null;if(typeof n!=="string")throw J(e);return n}function Wn(t,e){let n=t[e];if(typeof n!=="boolean")throw J(e);return n}function tm(t){let e;try{e=JSON.parse(t)}catch{throw new q("failed","gh answered with something that is not JSON")}return O(e,"answer")}function em(t){if(t.data!==null&&t.data!==void 0)return O(t.data,"data");let e=t.errors;if(Array.isArray(e)&&e.length>0){let n=e[0]?.message;if(typeof n==="string")throw new q("failed",n.slice(0,Cc))}throw J("data")}function nm(t){let e=H(t,"state");if(Wn(t,"merged")||e==="MERGED")return"merged";if(e==="CLOSED")return"closed";if(e==="OPEN")return"open";throw J("state")}function jt(t,e){let n=O(t[e],e).nodes;if(!Array.isArray(n))throw J(`${e}.nodes`);return n}function vs(t){if(t.author===null)return null;let e=O(t.author,"author");if(e.__typename==="Bot")return null;return H(e,"login")}var rm={APPROVED:"approved",CHANGES_REQUESTED:"changes-requested",COMMENTED:"reviewed"};function sm(t){let e=[];for(let n of jt(t,"reviews")){let r=O(n,"review"),s=rm[H(r,"state")],o=ke(r,"submittedAt"),i=vs(r);if(s!==void 0&&o!==null&&i!==null)e.push({kind:s,author:i,at:o})}return e}function Lc(t){let e=O(t,"comment"),n=vs(e);return n===null?null:{kind:"commented",author:n,at:H(e,"createdAt")}}function om(t){let e=[],n=0;for(let r of jt(t,"reviewThreads")){let s=O(r,"review thread");if(!Wn(s,"isResolved"))n+=1;for(let o of jt(s,"comments")){let i=Lc(o);if(i!==null)e.push(i)}}return{events:e,unresolved:n}}function im(t){let e=new Set;return t.sort((n,r)=>Date.parse(r.at)-Date.parse(n.at)).filter((n)=>{let r=`${n.kind}|${n.author}|${n.at.slice(0,16)}`;if(e.has(r))return!1;return e.add(r),!0}).slice(0,Ri)}var am={APPROVED:"approved",CHANGES_REQUESTED:"changes-requested",REVIEW_REQUIRED:"review-required"},cm={SUCCESS:"success",FAILURE:"failure",ERROR:"failure",PENDING:"pending",EXPECTED:"pending"};function lm(t){let e=jt(t,"commits")[0];if(e===void 0)return{committedAt:null,checks:null};let n=O(O(e,"commit node").commit,"commit"),r=n.statusCheckRollup,s=r===null?null:cm[H(O(r,"statusCheckRollup"),"state")]??null;return{committedAt:ke(n,"committedDate"),checks:s}}function um(t){let e=O(t,"review request").requestedReviewer;if(e===null)return null;let n=O(e,"requestedReviewer");if(typeof n.login==="string")return n.login;if(typeof n.slug==="string")return`team:${n.slug}`;return null}function fm(t){let e=[];for(let n of jt(t,"latestOpinionatedReviews")){let r=O(n,"review"),s=vs(r);if(s!==null&&H(r,"state")==="CHANGES_REQUESTED")e.push(s)}return e}function Bc(t){let e=ke(t,"reviewDecision"),n=lm(t);return{decision:e===null?null:am[e]??null,checks:n.checks,headCommittedAt:n.committedAt,conflicting:H(t,"mergeable")==="CONFLICTING"}}function hm(t){let e=om(t),r=O(t.reviewRequests,"reviewRequests").totalCount;if(typeof r!=="number")throw J("reviewRequests.totalCount");let s=jt(t,"reviewRequests").map(um).filter((i)=>i!==null),o=jt(t,"comments").map(Lc).filter((i)=>i!==null);return{...Bc(t),unresolvedThreads:e.unresolved,pendingReviewers:r,requestedReviewers:s,changesRequestedBy:fm(t),events:im([...sm(t),...o,...e.events])}}function _s(t){let e=O(t,"pull request"),n=e.number;if(typeof n!=="number"||!Number.isInteger(n)||n<1)throw J("number");let r=H(e,"url");if(!r.startsWith("https://"))throw J("url");let s=e.headRepositoryOwner===null?null:H(O(e.headRepositoryOwner,"headRepositoryOwner"),"login"),o=H(O(e.repository,"repository"),"nameWithOwner");return{number:n,title:H(e,"title"),url:r,state:nm(e),isDraft:Wn(e,"isDraft"),mergedAt:ke(e,"mergedAt"),closedAt:ke(e,"closedAt"),updatedAt:H(e,"updatedAt"),body:null,headRefName:H(e,"headRefName"),headRefOid:H(e,"headRefOid"),baseRefName:H(e,"baseRefName"),progress:null,headOwner:s,author:e.author===null?null:H(O(e.author,"author"),"login"),reviewRequested:!1,repo:o,repoKey:o.toLowerCase()}}function Tc(t){return{pr:_s(t),live:Bc(O(t,"pull request"))}}function Hc(t){let e=O(t,"pull request");return{id:H(e,"id"),pr:{..._s(e),body:H(e,"body"),progress:hm(e)}}}function dm(t,e){let n=O(t,"search"),r=O(n.pageInfo,"pageInfo");if(!Array.isArray(n.nodes))throw J("nodes");return{items:n.nodes.map(e),hasNextPage:Wn(r,"hasNextPage"),endCursor:ke(r,"endCursor")}}async function As(t,e,n,r){let s=JSON.stringify({query:e,variables:n});return em(tm(await t.run(Hp,r,s)))}async function xs(t,e,n,r,s){let o=[],i,a=null;for(;;){let c=await As(t,e,{q:n,after:a},s());i??=c;let l=dm(c.search,r);if(o.push(...l.items),!l.hasNextPage||o.length>=wn)return{items:o.slice(0,wn),capped:l.hasNextPage,first:i};if(l.endCursor===null||!Qp.test(l.endCursor))throw J("endCursor");a=l.endCursor}}function pm(t){let e=Zp.exec(t.repo);if(e===null)throw J("nameWithOwner");return{owner:e[1],name:e[2]}}async function Wc(t,e,n){let r={};e.forEach((o,i)=>{let{owner:a,name:c}=pm(o);r[`owner${i}`]=a,r[`name${i}`]=c,r[`number${i}`]=o.number});let s=await As(t,qp[e.length-1],r,n);return e.map((o,i)=>{let a=O(s[`p${i}`],"repository").pullRequest;if(a===null)throw new q("failed","GitHub no longer has this PR");return Hc(a)})}function Rt(t){return`${t.repoKey}#${t.number}`}function mm(t,e){return t!==void 0&&t.updatedAt===e.updatedAt&&t.headRefOid===e.headRefOid}async function gm(t,e,n,r){let s=[];for(let u=0;u<e.length;u+=ks)s.push(e.slice(u,u+ks));let o=0,i=!1,a=async()=>{while(!i&&o<s.length){let u=s[o++];try{(await Wc(t,u,r())).forEach((h,d)=>n.set(Rt(u[d]),h.pr))}catch(f){throw i=!0,f}}},c=Array.from({length:Math.min(Lp,s.length)},a),l=(await Promise.allSettled(c)).find((u)=>u.status==="rejected");if(l!==void 0)throw l.reason}function Ss(t,e){let n=Number(e.state==="open")-Number(t.state==="open");if(n!==0)return n;let r=Date.parse(e.updatedAt)-Date.parse(t.updatedAt);if(r!==0&&!Number.isNaN(r))return r;if(t.repoKey!==e.repoKey)return t.repoKey<e.repoKey?-1:1;return t.number-e.number}function Ic(t){let e=new Map;for(let n of t){let r=Rt(n),s=e.get(r);if(s===void 0||Date.parse(n.updatedAt)>Date.parse(s.updatedAt))e.set(r,n)}return[...e.values()]}async function wm(t,e,n){let[r,s]=await Promise.all([xs(t,Dc,zp,Tc,n),xs(t,Dc,Jp,Tc,n)]),o=s.items.map(({pr:l,live:u})=>({pr:{...l,reviewRequested:!0},live:u})),i=[...r.items,...o],a=new Map;for(let{pr:l}of i)if(!mm(e.get(Rt(l)),l))a.set(Rt(l),l);return await gm(t,[...a.values()],e,n),{prs:i.map(({pr:l,live:u})=>{let f=e.get(Rt(l));if(f===void 0)throw J("details");return{...l,body:f.body,progress:{...f.progress,...u}}}),viewer:H(O(r.first.viewer,"viewer"),"login"),capped:r.capped,read:a.size}}var Mc={missing:"gh-missing","logged-out":"gh-logged-out",failed:"error"};class Gn extends Error{constructor(){super("The PR's top zone changed on GitHub since it was shown. Check again first.");this.name="TopZoneChangedError"}}function Gc(t,e=Date.now){let n={status:"never",message:null,checkedAt:null,viewer:null,prs:[],capped:!1},r=null,s=new Map,o=null;async function i(u){let f=e(),h=o===null?Kp:Vp(o.since),d=performance.now()+Rs,m=()=>{let v=Math.floor(d-performance.now());if(v<=0)throw new q("failed","gh timed out");return v},[g,R]=await Promise.all([wm(u,s,m),xs(u,Up,h,_s,m)]),y=Ic([...R.items,...o?.prs??[]]).sort(Ss).slice(0,wn);o={prs:y,since:f};let x=new Set(g.prs.map(Rt));for(let v of s.keys())if(!x.has(v))s.delete(v);return G("PR refresh",void 0,{readWhole:g.read,closedFound:R.items.length}),{status:"ok",message:null,checkedAt:e(),viewer:g.viewer,prs:Ic([...g.prs,...y]).sort(Ss),capped:g.capped}}async function a(){if(t===null)return n={...n,status:"gh-missing",message:null},n;try{n=await i(t)}catch(u){if(u instanceof q)w("PR refresh failed",u,{status:Mc[u.kind]}),n={...n,status:Mc[u.kind],message:u.kind==="failed"?u.message:null};else C("PR refresh threw",u),n={...n,status:"error",message:"Unexpected failure reading the PRs"}}return n}function c(u){s.set(Rt(u),u);let f=(d)=>Rt(d)===Rt(u),h=n.prs.some(f)?n.prs.map((d)=>f(d)?u:d):[u,...n.prs];return n={...n,prs:h.sort(Ss)},u}async function l(u){if(t===null)throw new q("missing","gh not found");let[f]=await Wc(t,[u],Rs);return f}return{snapshot:()=>n,async checkOne(u){return c((await l(u)).pr)},async setTopZone(u,f,h){let d=await l(u);if(c(d.pr),d.pr.state!=="open")throw new q("failed","The PR is not open");if(vc(d.pr.body)!==bs(h))throw new Gn;let m=await As(t,Xp,{id:d.id,body:Ac(d.pr.body,f)},Rs),g=O(m.updatePullRequest,"updatePullRequest").pullRequest;return G("PR top zone updated",void 0,{pr:`${d.pr.repo}#${d.pr.number}`}),c(Hc(g).pr)},refresh(){return r??=a().finally(()=>{r=null}),r},prFor(u,f){let h=new Set(u.map((d)=>d.toLowerCase()));return n.prs.find((d)=>h.has(d.repoKey)&&d.headRefName===f)??null},ghAvailable:()=>t?.available()??!1}}import*as ut from"node:fs";import*as Xc from"node:path";var xe=2000,zc=4096,Jc=512,ym=["track","dismiss","drop","undismiss"];function Un(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function Ds(t){return typeof t==="string"&&t.length>=1&&t.length<=zc&&!t.includes("\x00")}function Kc(t){return typeof t==="string"&&t.length<=Jc}function Uc(t){return typeof t==="number"&&Number.isFinite(t)}function Yc(t){if(!Un(t))throw new p(400,'Expected a JSON body with "key" and "action"');let{key:e,action:n,fingerprint:r,prune:s}=t;if(!Ds(e))throw new p(400,`Invalid "key" (a string of 1 to ${zc} characters, no NUL)`);if(typeof n!=="string"||!ym.includes(n))throw new p(400,'Invalid "action" (track, dismiss, drop or undismiss)');if(r!==void 0&&!Kc(r))throw new p(400,`Invalid "fingerprint" (a string of at most ${Jc} characters)`);if(n==="dismiss"&&r===void 0)throw new p(400,'"dismiss" needs a "fingerprint"');if(s!==void 0&&(!Array.isArray(s)||s.length>xe||!s.every(Ds)))throw new p(400,`Invalid "prune" (at most ${xe} keys)`);let o={key:e,action:n};if(r!==void 0)o.fingerprint=r;if(s!==void 0)o.prune=s;return o}function jc(t,e){let n=new Map;if(!Un(t))return n;for(let[r,s]of Object.entries(t)){if(n.size>=xe)break;let o=Ds(r)&&Un(s)?e(s):null;if(o!==null)n.set(r,o)}return n}function Em(t){let e=Un(t)?t:{};return{tracked:jc(e.tracked,(n)=>Uc(n.at)?{at:n.at}:null),dismissed:jc(e.dismissed,(n)=>Kc(n.fingerprint)&&Uc(n.at)?{fingerprint:n.fingerprint,at:n.at}:null)}}function bm(t){let e;try{e=ut.readFileSync(t,"utf-8")}catch(n){if(n.code!=="ENOENT")C("Cannot read the work marks file; using none",n,{file:t});return{}}try{return JSON.parse(e)}catch(n){return w("Ignoring the work marks file: not valid JSON",n,{file:t}),{}}}function qc(t,e){return{tracked:Object.fromEntries(t),dismissed:Object.fromEntries(e)}}class Ts{file;tracked=new Map;dismissed=new Map;constructor(t){this.file=t}get marks(){return qc(this.tracked,this.dismissed)}load(){if(this.file===null)return this.marks;return{tracked:this.tracked,dismissed:this.dismissed}=Em(bm(this.file)),this.marks}apply(t,e){this.load();let n=new Map(this.tracked),r=new Map(this.dismissed);for(let s of t.prune??[])n.delete(s),r.delete(s);switch(t.action){case"track":n.set(t.key,{at:e});break;case"drop":n.delete(t.key);break;case"dismiss":r.set(t.key,{fingerprint:t.fingerprint??"",at:e});break;case"undismiss":r.delete(t.key);break}if(n.size>xe||r.size>xe)throw new p(400,`Too many marks (at most ${xe} of each kind)`);return this.persist(qc(n,r)),this.tracked=n,this.dismissed=r,this.marks}persist(t){if(this.file===null)return;ut.mkdirSync(Xc.dirname(this.file),{recursive:!0});let e=`${this.file}.${process.pid}.tmp`;try{ut.writeFileSync(e,`${JSON.stringify(t,null,2)}
|
|
86
|
+
`,{mode:384}),ut.renameSync(e,this.file)}catch(n){throw ut.rmSync(e,{force:!0}),n}}}import*as rl from"node:fs";import*as Xn from"node:path";import{createHash as Sm}from"node:crypto";import*as jn from"node:fs";import*as Xt from"node:path";var Vc=/^[A-Za-z0-9._-]+$/;function Rm(t){let e=/^git@([^:/]+):(.*)$/.exec(t);if(e)return e[1].toLowerCase()==="github.com"?e[2]:null;let n=/^ssh:\/\/git@([^/]+)\/(.*)$/.exec(t);if(n)return n[1].toLowerCase()==="github.com"?n[2]:null;let r=/^https:\/\/(?:[^@/]*@)?([^/@]+)\/(.*)$/i.exec(t);if(r)return r[1].toLowerCase()==="github.com"?r[2]:null;return null}function Qc(t){let e=Rm(t.trim());if(e===null)return null;let r=e.replace(/\/$/,"").replace(/\.git$/,"").split("/");if(r.length!==2)return null;let[s,o]=r;if(!Vc.test(s)||!Vc.test(o))return null;return{owner:s,name:o}}function Zc(t){return`${t.owner}/${t.name}`.toLowerCase()}var km=500,xm=200,vm=16777216,_m=16777216,el=1048576,tl="refs/heads/",Is="refs/remotes/";function ve(t){return Buffer.from(t,"utf8").toString("utf8")}function qn(t,e,n){return He(async()=>(await _t(t,[...dt,...e],n)).toString("utf8"))}function Am(t){let e=t.split("\x00"),n=[];for(let r=0;r<e.length;r++){let s=e[r];if(s.length<3)continue;if(n.push(s.slice(3)),/[RC]/.test(s.slice(0,2)))r++}return n}function Dm(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Tm(t,e){let n=e.slice(0,xm).map((i)=>Xt.join(t,i)),r=await Promise.allSettled(n.map((i)=>jn.promises.lstat(i))),s=null,o=null;for(let i=0;i<r.length;i++){let a=r[i];if(a.status==="fulfilled"){if(s===null||a.value.mtimeMs>s)s=a.value.mtimeMs}else if(!Dm(a.reason)&&o===null)o={file:n[i],err:a.reason}}if(o!==null)w("Work scan: cannot read a changed file",o.err,{worktree:t,file:o.file});return s}async function Im(t){if(t.isBare||!jn.existsSync(t.path))return{uncommitted:null,changedAt:null};let e;try{e=await qn(t.path,["status","--porcelain","-z","--untracked-files=all"],vm)}catch(s){return w("Work scan: status failed",s,{worktree:t.path}),{uncommitted:null,changedAt:null}}let n=Am(e);if(n.length===0)return{uncommitted:0,changedAt:null};let r=await He(()=>Tm(t.path,n));return{uncommitted:n.length,changedAt:r}}function Mm(t){let e=Xt.basename(t.path);return t.isBare&&e.startsWith(".")?Xt.basename(Xt.dirname(t.path)):e}function Cm(t,e){if(t===e)return 0;return t<e?-1:1}function Pm(t){let e=Number(t);return t===""||!Number.isFinite(e)?null:e*1000}async function Fm(t){let e=await qn(t,["for-each-ref","--format=%(objectname) %(committerdate:unix) %(refname) %(symref)","refs/heads","refs/remotes"],_m),n=[],r=new Map,s=new Map;for(let i of e.split(`
|
|
87
|
+
`)){if(!i)continue;let[a,c,l,u=""]=i.split(" ");if(l.startsWith(Is))s.set(l,{commit:a,symref:u});if(u)continue;if(l.startsWith(tl))n.push({name:ve(l.slice(tl.length)),tip:ve(a),committedAt:Pm(c)});else if(l.startsWith(Is)){let f=l.slice(Is.length),h=ve(f.slice(f.indexOf("/")+1)),d=r.get(h)??[];d.push(ve(a)),r.set(h,d)}}n.sort((i,a)=>Cm(i.name,a.name));let o=Sm("sha256").update(e).digest("hex");return{locals:n,copies:r,remotes:s,digest:o}}async function Om(t,e,n){if(n.includes(e))return 0;return _r(t,e,n)}async function Nm(t,{locals:e,copies:n}){let r=e.slice(0,km);return{branches:await Promise.all(r.map(async({name:o,tip:i,committedAt:a})=>{let c=n.get(o);if(c===void 0)return{name:o,tip:i,remoteCopy:!1,unpushed:null,committedAt:a};let l=await Om(t,i,c);return{name:o,tip:i,remoteCopy:!0,unpushed:l,committedAt:a}})),capped:e.length>r.length}}async function Ms(t){let e;try{e=await qn(t,["config","--get-regexp","^remote\\..*\\.url$"],el)}catch(r){let s=r;if(s.code===1&&(s.stdout?.length??0)===0)return[];throw r}let n=new Set;for(let r of e.split(`
|
|
88
|
+
`)){let s=r.indexOf(" ");if(s===-1)continue;let o=Qc(r.slice(s+1));if(o!==null)n.add(Zc(o))}return[...n]}async function $m(t){try{return(await qn(t,["remote"],el)).split(`
|
|
89
|
+
`).filter(Boolean)}catch(e){return w("default base-branch discovery failed",e,{repo:t}),null}}async function Lm(t,e,n){let[r,s]=await Promise.all([Fm(t),$m(t)]),o=s===null?null:gr(s,r.remotes),[i,a]=await Promise.all([vr(e,o,n),Nm(t,r)]);return{counted:i,branches:a,refs:r}}var Bm=1024,qt=new Map;function Hm(t){if(t.isBare||t.branch===null||t.head===null||t.baseBranch===null)return!1;if(t.aheadOfBase===0)return!1;return t.branch!==t.baseBranch.slice(t.baseBranch.indexOf("/")+1)}function Wm(t,e){let n=new Map(e.locals.map((s)=>[s.name,s.tip])),r=new Set;for(let s of t){let o=n.get(s.name)===s.tip;r.add(ve(o?s.name:s.name.slice(s.name.indexOf("/")+1)))}return[...r]}async function Gm(t,e){if(!Hm(t))return null;let n=ve([t.path,t.branch,t.baseBranch,t.head,e.digest].join(`
|
|
90
|
+
`)),r=qt.get(n);if(r!==void 0)return qt.delete(n),qt.set(n,r),r;let s;try{let o=Wm((await Mn(t.path,t.baseBranch,{pooled:!0})).layers,e);s=o.length<2?null:o}catch(o){return w("Work scan: stack read failed",o,{worktree:t.path}),null}if(qt.set(n,s),qt.size>Bm){let o=qt.keys().next().value;if(o!==void 0)qt.delete(o)}return s}async function Um(t,e){let n=await Promise.all(t.map((s)=>Gm(s,e))),r=[];return n.forEach((s,o)=>{if(s!==null)r.push({worktree:t[o].path,layers:s})}),r}function jm(t,e){if(t.isBare)return t.path;let n=K(t.path)??K(e);if(n===null)throw Error(`Cannot find the git dir of ${e}`);return n.commonDir}async function nl(t){let e=await kr(t,{pooled:!0});if(e.length===0)return null;let n=e.find((d)=>d.isMain)??e[0],r=n.path,s=jm(n,t),[o,{counted:i,branches:a,refs:c},l,u]=await Promise.all([Promise.all(e.map(Im)),Lm(t,e,$e()),Ms(t),Mi(s)]),f=await Um(i,c),h=i.map((d,m)=>({path:d.path,branch:d.branch,head:d.head,isMain:d.isMain,isBare:d.isBare,lastActivity:d.lastActivity,changedAt:o[m].changedAt,aheadOfBase:d.aheadOfBase,base:d.baseBranch,uncommitted:o[m].uncommitted}));return{path:t,root:r,name:Mm(n),worktrees:h,branches:a.branches,branchesCapped:a.capped,identities:l,drafts:u,stacks:f}}function qm(t){let e=new Set;for(let n of t.discovery.state.roots)for(let r of n.repos)e.add(r.path);for(let n of t.registry.listRepos())e.add(n.path);return e}var Xm=5000;function zm(t){let e=K(t);if(e===null)return null;try{return rl.realpathSync(e.commonDir)}catch{return null}}function sl(t=nl,e=zm,n=Xm){let r=new Map;function s(o,i){let a={facts:t(i),done:!1,answered:new Set};r.set(o,a);let c=()=>{if(r.get(o)===a)r.delete(o)};return a.facts.then(()=>{a.done=!0,setTimeout(c,n).unref()},c),a}return async(o)=>{let i=e(o)??o,a=r.get(i);if(a===void 0||a.done&&a.answered.has(o))a=s(i,o);a.answered.add(o);let c=await a.facts;return c===null?null:{...c,path:o}}}function ol(t,e,n){let{prs:r,workMarks:s}=e;t.post("/work/repo",async({body:o,res:i})=>{let a=L(o,"path");if(!Xn.isAbsolute(a))throw new p(400,`Repo path must be absolute: ${a}`);let c=Xn.resolve(a);if(!qm(e).has(c))throw new p(404,`Not a discovered or open repo: ${c}`);let l;try{l=await n(c)}catch(u){throw new p(500,`Could not scan ${c}`,{cause:u})}if(l===null)throw new p(404,`Not a git repository: ${c}`);E(i,200,l)}),t.get("/work/prs",({res:o})=>{E(o,200,r.snapshot())}),t.post("/work/prs/refresh",async({res:o})=>{E(o,200,await r.refresh())}),t.get("/work/marks",({res:o})=>{E(o,200,s.load())}),t.put("/work/marks",({body:o,res:i})=>{let a=Yc(o),c;try{c=s.apply(a,Date.now())}catch(l){if(l instanceof p)throw l;let u=l instanceof Error?l.message:String(l);throw new p(500,`Could not save marks: ${u}`,{cause:l})}E(i,200,c)})}function il(t){let e=Xe(t,"branch");if(e===null)throw new p(400,'Missing "branch" query parameter');return e}function zn(t){let e=K(t.path);if(e===null)throw new p(500,"Cannot find the git directory of this repository");return e.commonDir}async function Jn(t,e){try{return await t()}catch(n){if(n instanceof $t)throw new p(400,n.message);if(n instanceof ce)throw new p(409,n.message);if(n instanceof Dt)throw new p(422,n.message);throw new p(500,e,{cause:n})}}async function ll(t){try{return await Ms(t.path)}catch(e){throw new p(500,"Could not read the remotes",{cause:e})}}async function al(t,e,n){let r=t.prFor(await ll(e),n);if(r===null)throw new p(404,"No PR is known for this branch");return r}function cl(t){if(t instanceof Gn)return new p(409,t.message);if(t instanceof q){let e=t.kind==="failed"?502:503;return new p(e,t.message,{cause:t})}return new p(500,"Could not reach GitHub",{cause:t})}function Cs(t,e){let n=t.snapshot();return{pr:e,status:n.status,message:n.message,checkedAt:n.checkedAt,viewer:n.viewer}}function ul(t,e){let{registry:n,prs:r}=e;t.get("/repos/:id/draft",async({params:s,query:o,res:i})=>{let a=S(n,s.id),c=il(o),l=zn(a);E(i,200,await Jn(()=>$r(l,c),"Could not read the draft"))}),t.put("/repos/:id/draft",async({params:s,body:o,res:i})=>{let a=S(n,s.id),c=et(o,"branch"),l=L(o,"top",{allowEmpty:!0}),u=L(o,"version");if(Buffer.byteLength(l,"utf8")>ae)throw new p(413,`Draft is larger than ${ae} bytes`);let f=zn(a),h=await Jn(()=>Ti(f,c,l,u),"Could not save the draft");E(i,200,h)}),t.post("/repos/:id/draft/adopt",async({params:s,body:o,res:i})=>{let a=S(n,s.id),c=et(o,"branch"),l=L(o,"version"),u=zn(a),f=await Jn(()=>Ii(u,c,l),"Could not save the draft");E(i,200,f)}),t.get("/repos/:id/pr",async({params:s,query:o,res:i})=>{let a=S(n,s.id),c=il(o),l=r.prFor(await ll(a),c);E(i,200,Cs(r,l))}),t.post("/repos/:id/pr/check",async({params:s,body:o,res:i})=>{let a=S(n,s.id),c=et(o,"branch"),l=await al(r,a,c),u;try{u=await r.checkOne(l)}catch(f){throw cl(f)}E(i,200,Cs(r,u))}),t.post("/repos/:id/pr/top",async({params:s,body:o,res:i})=>{let a=S(n,s.id),c=et(o,"branch"),l=L(o,"version"),u=L(o,"expectedTop",{allowEmpty:!0}),f=zn(a),h=await Jn(()=>$r(f,c),"Could not read the draft");if(h.version!==l)throw new p(409,"top.md changed since it was shown");let d=h.top??"";if(d.trim()==="")throw new p(422,"top.md is empty: there is nothing to send");if(xc(d)>0)throw new p(422,"top.md still has a {{...}} placeholder");let m=await al(r,a,c);if(m.state!=="open")throw new p(409,"The PR is not open");let g;try{g=await r.setTopZone(m,d,u)}catch(R){throw cl(R)}E(i,200,Cs(r,g))})}function Jm(t){if(!zt.existsSync(t))return Promise.resolve(!1);return new Promise((e)=>{try{let n=hl.connect(t);n.once("connect",()=>{n.destroy(),e(!0)}),n.once("error",()=>{n.destroy(),e(!1)})}catch{e(!1)}})}function dl(t={}){let e=new zr,n=new Jr,r=new Xr({onOpened:(b)=>n.broadcast("repo-opened",{id:b.id,path:b.path}),onClosed:(b)=>{e.closeRepo(b),n.broadcast("repo-closed",{id:b})}}),s=t.followFile?new Yr(r,n,t.followFile):null,o=pa(t.updateCheck===!1?()=>Promise.resolve(null):t.fetchLatestVersion),i=new Qr(t.settingsFile??null),a=new es(n),c=new Map,l=Es(),u=Gc(t.gh??null),f=new Ts(t.workMarksFile??null),h=sl(),d=t.symbols??null,m=d===null?null:{pool:ic(d),gate:Es(1,4),extensions:d.extensions};function g(b){let M=c.get(b);if(M)return M;let _=new nr,A={registry:r,sse:e,daemonEvents:n,follow:s,settings:i,discovery:a,apiMode:b,version:o,symbols:m,httpPort:D,prs:u,workMarks:f};if(ga(_,A),wa(_,A),Da(_,A),Ma(_,A),Wa(_,A),Ga(_,A),b==="full")Ua(_,A);return Za(_,A),oc(_,A),Rc(_,A,l),Sc(_,A),kc(_,A),ol(_,A,h),ul(_,A),c.set(b,_),_}let R=(b)=>t.apiMode??(b==="tcp"?"web":"full");s?.start(),a.setRoots(i.load().watchRoots);let y=t.webRoot?Xs(t.webRoot):void 0,x=new Set,v=[];function D(){for(let b of v){let M=b.server.address();if(M!==null&&typeof M==="object")return M.port}return null}function T(b){let M=g(b),_=fl.createServer((A,Kt)=>{for(let[ft,Qe]of Object.entries(Qs))Kt.setHeader(ft,Qe);if(Ks(_.address())){let ft=Ys(A);if(ft){E(Kt,ft.status,{error:ft.message});return}}M.handle(A,Kt,y).catch((ft)=>{C(`${A.method??"GET"} ${A.url??"/"} escaped the router`,ft),Kt.end()})});return _.on("connection",(A)=>{x.add(A),A.on("close",()=>x.delete(A))}),_}async function I(b,M){let _=b==="unix"?M.socketPath??null:null;if(_){if(await Jm(_))throw Error(`diffstalkerd already running at ${_}`);zt.rmSync(_,{force:!0})}let A={server:T(R(b)),socketPath:_};v.push(A),await new Promise((Kt,ft)=>{let Qe=(kl)=>ft(kl);A.server.once("error",Qe);let Yn=()=>{if(A.server.removeListener("error",Qe),_)zt.chmodSync(_,384);Kt()};if(b==="fd")A.server.listen({fd:M.fd},Yn);else if(_)process.umask(63),A.server.listen(_,Yn);else A.server.listen(M.port,"127.0.0.1",Yn)})}function W(b){return new Promise((M,_)=>{b.server.close((A)=>{if(b.socketPath)zt.rmSync(b.socketPath,{force:!0});if(A&&A.code!=="ERR_SERVER_NOT_RUNNING")_(A);else M()})})}return{address(){return v[0]?.server.address()??null},addresses(){return v.map((b)=>b.server.address()).filter((b)=>b!==null)},getRepo(b){return r.getRepo(b)},async openRepo(b){let{handle:M}=await An(r,b);return{id:M.id,path:M.path}},async listen(b){let M=[];if(b.fd!==void 0)M.push("fd");if(b.socketPath)M.push("unix");if(b.port!==void 0)M.push("tcp");if(M.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let _ of M)await I(_,b)},close(){s?.dispose(),a.dispose(),e.destroy(),n.destroy(),r.disposeAll();for(let M of x)M.destroy();let b=m?.pool.dispose()??Promise.resolve();return Promise.all([b,...v.splice(0).map(W)]).then(()=>{})}}}import*as Ps from"node:fs";import*as _e from"node:path";import*as El from"node:crypto";import{createRequire as Ym}from"node:module";var pl=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 ml(){return[...pl.keys()]}function Km(t){let e=t.slice(t.lastIndexOf("/")+1),n=e.lastIndexOf(".");if(n<=0)return"";return e.slice(n).toLowerCase()}function gl(t){return pl.get(Km(t))??null}var Vm="diffstalkerd-grammars";function Qm(t){return El.createHash("sha256").update(t).digest("hex")}function Zm(t){try{let e=JSON.parse(Ps.readFileSync(_e.join(t,"checksums.json"),"utf8"));if(typeof e.webTreeSitterVersion!=="string"||typeof e.files!=="object")return null;return e}catch{return null}}var wl="0.26.11";function tg(t,e,n){for(let[r,s]of Object.entries(e.files)){let o;try{o=Ps.readFileSync(_e.join(t,r))}catch{return n(`grammars: missing ${r}`),!1}if(Qm(o)!==s)return n(`grammars: checksum mismatch for ${r}`),!1}return!0}function eg(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 yl(t,e=()=>{}){let n=Zm(t);if(n===null)return e(`grammars: no readable checksums.json in ${t}`),null;if(n.webTreeSitterVersion!==wl)return e(`grammars: built for web-tree-sitter ${n.webTreeSitterVersion}, this daemon bundles ${wl} — symbols disabled`),null;if(!tg(t,n,e))return null;let r=eg(n),s=ml().filter((o)=>{let i=gl(`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:_e.join(t,"queries"),extensions:s}}function bl(t,e=()=>{}){if(t!==null)return yl(t,e);try{let r=Ym(import.meta.url).resolve(`${Vm}/checksums.json`);return yl(_e.dirname(r),e)}catch{return null}}var Sl="diffstalkerd.sock";function rg(t){return t===void 0?Sl:`${t}.sock`}var sg=3,Rl=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
|
|
90
91
|
|
|
91
92
|
Usage: diffstalkerd [options] [REPO_PATH...]
|
|
92
93
|
|
|
@@ -98,7 +99,7 @@ Arguments:
|
|
|
98
99
|
|
|
99
100
|
Options:
|
|
100
101
|
--socket PATH Bind a unix socket at PATH
|
|
101
|
-
(default: $XDG_RUNTIME_DIR/diffstalker/${
|
|
102
|
+
(default: $XDG_RUNTIME_DIR/diffstalker/${Sl})
|
|
102
103
|
--instance NAME Bind <NAME>.sock in the runtime dir, so several
|
|
103
104
|
daemons can run side by side (default: the shared
|
|
104
105
|
socket every client looks for first)
|
|
@@ -118,6 +119,6 @@ Options:
|
|
|
118
119
|
ignored follow target) to stderr
|
|
119
120
|
--version, -v Print the running version and exit
|
|
120
121
|
--help, -h Show this help
|
|
121
|
-
`;function
|
|
122
|
+
`;function Ae(t,e,n){let r=t[e];if(r===void 0||r.startsWith("--"))throw Error(`${n} requires a value`);return r}function og(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 ig(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=Ae(t,++n,"--socket");break;case"--instance":e.instance=Ae(t,++n,"--instance");break;case"--no-socket":e.noSocket=!0;break;case"--port":if(e.port=Number(Ae(t,++n,"--port")),!Number.isInteger(e.port)||e.port<0)throw Error("--port requires a non-negative integer");break;case"--follow-file":e.followFile=Ae(t,++n,"--follow-file");break;case"--no-follow":e.noFollow=!0;break;case"--web-root":e.webRoot=Ae(t,++n,"--web-root");break;case"--grammars":e.grammarsDir=Ae(t,++n,"--grammars");break;case"--no-update-check":e.noUpdateCheck=!0;break;case"--debug":e.debug=!0;break;default:og(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 ag(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function cg(t){if(t.noSocket||t.socketPath!==void 0)return;if(ag()){t.fd=sg;return}let e=Ls();if(!e){if(t.port!==void 0){console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set; binding the TCP port only.
|
|
122
123
|
Pass --socket PATH to also accept CLI connections.`);return}console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set and no --socket/--port given.
|
|
123
|
-
Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}
|
|
124
|
+
Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}Kn.mkdirSync(e,{recursive:!0,mode:448}),t.socketPath=Jt.join(e,rg(t.instance))}function lg(t){let e=t??ng(new URL("web/",import.meta.url));if(Kn.existsSync(e))return e;console.error(`diffstalkerd: web UI assets not found at ${e}; serving API only`);return}function ug(t){console.error(`diffstalkerd: web UI at http://diffstalker.localhost:${t}/`)}async function fg(t,e){for(let n of e){let r=Jt.resolve(ot(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 hg(){process.title="diffstalkerd";let t;try{t=ig(process.argv.slice(2))}catch(u){console.error(u instanceof Error?u.message:String(u)),console.error(Rl),process.exit(2)}if(t==="help"){console.log(Rl);return}if(t==="version"){let u=rs();if(u===null)console.error("diffstalkerd: version unknown (package.json unreadable)"),process.exit(1);console.log(u);return}Hs(t.debug??!1),cg(t);let e=t.noFollow?void 0:t.followFile??Jt.join(Yt(),"target"),n=lg(t.webRoot),r=bl(t.grammarsDir??process.env.DIFFSTALKER_GRAMMARS_DIR??null,(u)=>console.error(`diffstalkerd: ${u}`)),s=dl({followFile:e,settingsFile:Jt.join(Ns(),"daemon.json"),webRoot:n,symbols:r,updateCheck:!t.noUpdateCheck,gh:Pc(),workMarksFile:Jt.join($s(),"work.json")});await fg(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)ug(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)=>{C(`${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))}hg().catch((t)=>{console.error(t instanceof Error?t.message:String(t)),process.exit(1)});export{ig as parseArgs};
|