diffstalkerd 0.13.13 → 0.13.14
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 +26 -0
- package/README.md +32 -5
- package/dist/index.js +43 -43
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,32 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [0.13.14] - 2026-11-11
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- **The daemon no longer works for repos nobody is looking at.** A repo
|
|
13
|
+
kept open by follow mode, or kept for ten minutes after its last tab
|
|
14
|
+
closed, refreshed on every file change with no one to see it. With a
|
|
15
|
+
large uncommitted diff and a process writing into the repo, that cost
|
|
16
|
+
about a third of a CPU core around the clock. Such a repo now only notes
|
|
17
|
+
that it changed, and catches up when a client opens it or asks for it.
|
|
18
|
+
- **Watching a repo costs one watch per folder, not per file.** The
|
|
19
|
+
watcher put an inotify watch on every file and re-read a whole folder,
|
|
20
|
+
every entry, on each change in it: a folder of 7,500 files written to
|
|
21
|
+
every few seconds cost over a second of CPU per write. Folders git
|
|
22
|
+
ignores are no longer watched at all, now including `build/`-style
|
|
23
|
+
rules, the global ignore file and a worktree's `info/exclude`.
|
|
24
|
+
- **Git's own writes are watched, not polled.** The index, HEAD and refs
|
|
25
|
+
of every open repo were checked ten times a second. A background status
|
|
26
|
+
also no longer rewrites the index, so it cannot make a git command in
|
|
27
|
+
your terminal fail on `index.lock`.
|
|
28
|
+
- **Refreshes are spaced out under constant writes.** A repo that keeps
|
|
29
|
+
changing refreshes at most once a second, and spends at most a fifth of
|
|
30
|
+
its time refreshing however large its diff.
|
|
31
|
+
- **A large diff is read once per refresh, not twice,** when nothing is
|
|
32
|
+
staged.
|
|
33
|
+
|
|
8
34
|
## [0.13.13] - 2026-11-02
|
|
9
35
|
|
|
10
36
|
### Fixed
|
package/README.md
CHANGED
|
@@ -173,6 +173,29 @@ An always-warm service answers the probe immediately. The daemon also has no
|
|
|
173
173
|
idle timeout — it holds watchers on open repos and is meant to stay warm for
|
|
174
174
|
the session — so lazy activation buys little here.
|
|
175
175
|
|
|
176
|
+
### Background work
|
|
177
|
+
|
|
178
|
+
Staying warm must not mean staying busy. An open repo costs one inotify
|
|
179
|
+
watch per directory git does not ignore (`.gitignore` files, the repo's
|
|
180
|
+
`info/exclude` and the user's `core.excludesFile` all count), and none per
|
|
181
|
+
file. Git's own writes (index, HEAD, refs, packed-refs) are seen through
|
|
182
|
+
watches on the git dirs, not by polling, and the daemon's git runs with
|
|
183
|
+
`GIT_OPTIONAL_LOCKS=0`, so a refresh never rewrites the index behind the
|
|
184
|
+
user's back.
|
|
185
|
+
|
|
186
|
+
A file change refreshes a repo only while a client **views** it: while it
|
|
187
|
+
has at least one SSE subscriber (`GET /repos/:id/events` or
|
|
188
|
+
`GET /events?repo=`). A repo nobody views — one kept open by follow mode
|
|
189
|
+
with no client attached, or one lingering after its release — only marks
|
|
190
|
+
itself stale. Its first new subscriber, and any read that serves its state
|
|
191
|
+
(`GET /status`, the whole-tree `GET /diff`, `GET /journal`), refreshes it
|
|
192
|
+
first; `GET /repos` reads its branch from the HEAD file instead. Change-driven refreshes of a viewed repo are spaced out: a burst
|
|
193
|
+
settles for 100 ms, and the next one starts no sooner than 1 s, or four
|
|
194
|
+
times the last refresh's duration, after the last one ended. A repo with a
|
|
195
|
+
huge diff and a process writing into it all day therefore spends at most a
|
|
196
|
+
fifth of its time refreshing. Explicit actions (stage, commit, fetch, …)
|
|
197
|
+
refresh at once.
|
|
198
|
+
|
|
176
199
|
## API
|
|
177
200
|
|
|
178
201
|
Current surface. All bodies are JSON; errors are non-2xx with `{"error": "..."}`.
|
|
@@ -205,7 +228,7 @@ with a 400 so they can never be parsed as git flags.
|
|
|
205
228
|
| GET | `/version` | `{current, latest, status, install, restart}` — the running version against npm's `latest` dist-tag (`current` \| `outdated` \| `ahead` \| `unknown`). The npm lookup is cached (6h, 5min after a failure) and only ever runs when this endpoint is called; `--no-update-check` skips it, leaving `latest: null`. `install` is `{method, package, command}` — how this daemon was installed (`npm` \| `bun` \| `pnpm` \| `yarn` \| `pacman` \| `unknown`) and the one command that updates it, detected once from where the daemon's own files live. An install nothing owns reports `unknown` with a null command rather than a guess. `restart` is the command that restarts this daemon (`systemctl --user restart diffstalkerd`, or `sudo systemctl restart …` for a system unit), set only when systemd started this very process (`$SYSTEMD_EXEC_PID` is its pid) and `/proc/self/cgroup` names a plain `.service` unit; otherwise null |
|
|
206
229
|
| GET | `/repos` | List open repos (`id`, `path`, `branch`) |
|
|
207
230
|
| POST | `/repos` | Open a repo: `{"path": "/abs/path"}` → `{id, path}` (201 created, 200 already open or still kept warm after its release). 400 for a relative path or a directory that is not a git repository, 404 when the path does not exist. One missing last segment under a repo still opens the repo above it (`<repo>/nope` opens `<repo>`); a path missing more than one level deep (`<repo>/nope/deeper`) is a 404 |
|
|
208
|
-
| DELETE | `/repos/:id` | Close a repo (refcounted per open). At zero it is closed for every client at once (`repo-closed`, gone from `GET /repos`), but the daemon keeps its
|
|
231
|
+
| DELETE | `/repos/:id` | Close a repo (refcounted per open). At zero it is closed for every client at once (`repo-closed`, gone from `GET /repos`), but the daemon keeps its watchers and last state for 10 minutes (up to 4 such repos) so a reopen in that window is warm; it refreshes only once a client views it again |
|
|
209
232
|
| GET | `/repos/:id/worktrees` | Registered worktrees (`path`, `branch`, `head`, `isBare`, `lastActivity`, `aheadOfBase`): main worktree, linked worktrees, and the bare entry in a bare-worktree layout |
|
|
210
233
|
| GET | `/worktrees?path=` | Same as above, but for a raw filesystem path instead of an already-opened repo id (e.g. a recently-visited repo a client hasn't opened on this daemon) |
|
|
211
234
|
| GET | `/resolve?path=` | `{openable, root}` — can this exact path be opened, and as which worktree, without opening it. Same resolver as `POST /repos`, but the path must EXIST (git resolves a missing path to its parent worktree, which would make a typo look openable). A relative path is a 400; not-a-repo is a 200 answer |
|
|
@@ -270,9 +293,11 @@ returns the repo to its pre-operation state — no shell required. The
|
|
|
270
293
|
failing mutation refreshes the shared state before it answers, so the
|
|
271
294
|
`state-change` event carries the wedge too, and `/status` serves that same
|
|
272
295
|
cached state rather than re-reading the git dir. For an operation started
|
|
273
|
-
from a shell the value lags by the watcher's
|
|
274
|
-
(roughly 150–250 ms after HEAD or the index changes
|
|
275
|
-
|
|
296
|
+
from a shell the value of a viewed repo lags by the watcher's settle time
|
|
297
|
+
plus one refresh (roughly 150–250 ms after HEAD or the index changes, up to
|
|
298
|
+
about a second when another refresh just ended): a `/status` read in that
|
|
299
|
+
window still shows the previous value. An unviewed repo refreshes for the
|
|
300
|
+
read itself. A failed git operation's
|
|
276
301
|
`{error}` is git's own message (a rejected push, a patch that does not
|
|
277
302
|
apply); the daemon log records the same text.
|
|
278
303
|
|
|
@@ -361,7 +386,9 @@ clients apply them atomically.
|
|
|
361
386
|
The journal store lives above the repo's manager lifecycle: closing a
|
|
362
387
|
repo's last client (a browser F5) keeps the store, so a reopen resumes the
|
|
363
388
|
same chronology under the same epoch, even after the lingering manager is
|
|
364
|
-
disposed.
|
|
389
|
+
disposed. A repo journals while a client views it. Unviewed (lingering, or
|
|
390
|
+
followed with no client attached) it observes nothing, and the next refresh
|
|
391
|
+
records everything that changed meanwhile in one observation.
|
|
365
392
|
Stores are LRU-capped daemon-wide; the store of an open or lingering repo
|
|
366
393
|
is never evicted.
|
|
367
394
|
|
package/dist/index.js
CHANGED
|
@@ -1,52 +1,52 @@
|
|
|
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 L(t,e,n){if(!wr)return;sn("debug",t,n,e===void 0?void 0:rn(e,{stacks:!1}))}function E(t,e,n){sn("warn",t,n,e===void 0?void 0:rn(e,{stacks:!1}))}function T(t,e,n){sn("error",t,n,e===void 0?void 0:rn(e))}import*as Ci from"node:http";import*as vt from"node:fs";import*as Ni from"node:net";function on(t){let e={};for(let[n,r]of t)e[n]=r;return e}function ia(t){if(!t)return null;return{staged:on(t.staged),unstaged:on(t.unstaged)}}function at(t){return{status:t.status,hunkCounts:ia(t.hunkCounts),error:t.error,stashList:t.stashList,operationInProgress:t.operationInProgress,mtimes:t.mtimes?on(t.mtimes):null}}function Er(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 Zt(t){if(t instanceof Date)return t.toISOString();if(t instanceof Map){let e={};for(let[n,r]of t)e[String(n)]=Zt(r);return e}if(Array.isArray(t))return t.map(Zt);if(t!==null&&typeof t==="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=Zt(r);return e}return t}var aa=1048576;class m extends Error{status;constructor(t,e,n){super(e,n);this.status=t,this.name="HttpError"}}function v(t,e,n){let r=JSON.stringify(Zt(n));t.writeHead(e,{"content-type":"application/json"}),t.end(r)}function Sr(t,e,n,r){t.writeHead(e,{...r,"content-length":String(n.byteLength)}),t.end(n)}function ca(t,e){if(t.segments.length!==e.length)return null;let n={};for(let r=0;r<t.segments.length;r++){let s=t.segments[r];if(s.startsWith(":"))try{n[s.slice(1)]=decodeURIComponent(e[r])}catch{throw new m(400,`Malformed percent-encoding in path: ${e[r]}`)}else if(s!==e[r])return null}return n}async function la(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>aa)throw new m(413,"Request body too large");e.push(o)}let r=Buffer.concat(e).toString("utf-8");if(!r.trim())return;try{return JSON.parse(r)}catch{throw new m(400,"Invalid JSON body")}}class an{routes=[];get(t,e){this.add("GET",t,e)}post(t,e){this.add("POST",t,e)}put(t,e){this.add("PUT",t,e)}delete(t,e){this.add("DELETE",t,e)}add(t,e,n){this.routes.push({method:t,segments:e.split("/").filter(Boolean),handler:n})}match(t,e){for(let n of this.routes){if(n.method!==t)continue;let r=ca(n,e);if(r)return{handler:n.handler,params:r}}return null}async handle(t,e,n){try{let r=new URL(t.url??"/","http://localhost"),s=r.pathname.split("/").filter(Boolean),o=t.method??"GET",i=this.match(o,s);if(!i){if(n&&o==="GET"){await n(t,e,r.pathname);return}throw new m(404,`Unknown route: ${o} ${r.pathname}`)}let a=await la(t);await i.handler({req:t,res:e,params:i.params,query:r.searchParams,body:a})}catch(r){let s=`${t.method??"GET"} ${t.url??"/"}`;if(e.headersSent){T(`${s} failed after the response headers were sent`,r),e.end();return}if(r instanceof m){ua(s,r),v(e,r.status,{error:r.message});return}T(`${s} -> 500`,r),v(e,500,{error:"Internal server error"})}}}function ua(t,e){let n=`${t} -> ${e.status} ${e.message}`;if(e.cause!==void 0||e.status>=500)E(n,e.cause);else L(n)}import*as cn from"node:fs";import*as X from"node:path";var fa=new Set(["health","version","repos","resolve","worktrees","events","follow","settings","discovered","browse"]),ha={".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"},vr="no-cache",da="public, max-age=31536000, immutable";async function xr(t,e,n){let r;try{r=await cn.promises.readFile(e)}catch(s){throw new m(404,`Not found: ${X.basename(e)}`,{cause:s})}t.writeHead(200,{"content-type":ha[X.extname(e)]??"application/octet-stream","cache-control":n,"content-length":r.length}),t.end(r)}function kr(t){let e=X.resolve(t);return async(n,r,s)=>{let o;try{o=decodeURIComponent(s)}catch{throw new m(400,`Malformed percent-encoding in path: ${s}`)}if(o.includes("\x00"))throw new m(400,"Invalid path");let i=o.split("/").filter(Boolean);if(i.length>0&&fa.has(i[0]))throw new m(404,`Unknown route: GET ${s}`);let a=i.length>0?X.resolve(e,i.join("/")):e;if(a!==e&&!a.startsWith(e+X.sep))throw new m(403,"Forbidden");if((await cn.promises.stat(a).catch(()=>null))?.isFile()){await xr(r,a,i[0]==="assets"?da:vr);return}await xr(r,X.join(e,"index.html"),vr)}}function pa(t){try{let e=new URL(`http://${t}`).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function ma(t){try{let e=new URL(t).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function _r(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 ga(t){return t.length>10&&t.endsWith(".localhost")}function Rr(t){return t==="localhost"||t==="::1"||ga(t)||_r(t)}function wa(t){return t==="::1"||_r(t)}function Ar(t){if(t===null)return!1;if(typeof t==="string")return!0;return wa(t.address)}function Ir(t){let e=t.headers.host;if(e!==void 0){let i=pa(e);if(i===null||!Rr(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=ma(o);if(i===null||!Rr(i))return{status:403,message:"Cross-origin request blocked"}}return null}function Dr(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 Pr={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Referrer-Policy":"no-referrer","Cross-Origin-Resource-Policy":"same-origin","Content-Security-Policy":["default-src 'self'","script-src 'self'","style-src 'self' 'unsafe-inline'","img-src 'self' data:","font-src 'self' data:","connect-src 'self'","object-src 'none'","frame-src 'none'","child-src 'none'","media-src 'none'","worker-src 'none'","form-action 'none'","base-uri 'self'","frame-ancestors 'none'"].join("; ")};import{createHash as Qc}from"node:crypto";class Tr{repoPath;queue=[];isProcessing=!1;pendingMutations=0;refreshScheduled=!1;constructor(t){this.repoPath=t}enqueue(t){return new Promise((e,n)=>{this.queue.push({execute:t,resolve:e,reject:n}),this.processNext()})}enqueueMutation(t){return this.pendingMutations++,this.enqueue(t).finally(()=>{this.pendingMutations--})}hasPendingMutations(){return this.pendingMutations>0}scheduleRefresh(t){if(this.pendingMutations>0)return;if(this.refreshScheduled)return;this.refreshScheduled=!0,this.enqueue(async()=>{this.refreshScheduled=!1,await t()}).catch((e)=>{T("Scheduled refresh threw",e,{repo:this.repoPath}),this.refreshScheduled=!1})}isBusy(){return this.isProcessing||this.queue.length>0}async processNext(){if(this.isProcessing||this.queue.length===0)return;this.isProcessing=!0;let t=this.queue.shift();try{let e=await t.execute();t.resolve(e)}catch(e){t.reject(e instanceof Error?e:Error(String(e)))}finally{this.isProcessing=!1,this.processNext()}}}var ln=new Map;function Mr(t){let e=ln.get(t);if(!e)e=new Tr(t),ln.set(t,e);return e}function Fr(t){ln.delete(t)}import*as B from"node:path";import*as U from"node:fs";import{execFileSync as Ic}from"node:child_process";import{watch as eo}from"chokidar";import{EventEmitter as Dc}from"node:events";import no from"ignore";import{execFile as xa}from"node:child_process";import{promisify as ka}from"node:util";import{simpleGit as Ra}from"simple-git";import*as Y from"node:fs";import*as ee from"node:path";import{execFileSync as ya}from"node:child_process";var ba=[["*.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 Ea(){return`# Generated by diffstalker: turns on git's built-in funcname drivers.
|
|
1
|
+
var ca=Object.create;var{getPrototypeOf:la,defineProperty:yr,getOwnPropertyNames:ua}=Object;var br=Object.prototype.hasOwnProperty;function fa(t){return this[t]}var ha,da,pa=(t,e,n)=>{var r=t!=null&&typeof t==="object";if(r){var s=e?ha??=new WeakMap:da??=new WeakMap,o=s.get(t);if(o)return o}n=t!=null?ca(la(t)):{};let i=e||!t||!t.__esModule||!br.call(t,"default")?yr(n,"default",{value:t,enumerable:!0}):n;if(t&&typeof t==="object"||typeof t==="function"){for(let a of ua(t))if(!br.call(i,a))yr(i,a,{get:fa.bind(t,a),enumerable:!0})}if(r)s.set(t,i);return i};var ma=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var po=ma(function(gd,ho){var H=-1,L=1,P=0;function pe(t,e,n,r,s){if(t===e){if(t)return[[P,t]];return[]}if(n!=null){var o=Xc(t,e,n);if(o)return o}var i=$n(t,e),a=t.substring(0,i);t=t.substring(i),e=e.substring(i),i=Ce(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=Lc(t,e);if(a)l.unshift([P,a]);if(c)l.push([P,c]);if(Nn(l,s),r)Wc(l);return l}function Lc(t,e){var n;if(!t)return[[L,e]];if(!e)return[[H,t]];var r=t.length>e.length?t:e,s=t.length>e.length?e:t,o=r.indexOf(s);if(o!==-1){if(n=[[L,r.substring(0,o)],[P,s],[L,r.substring(o+s.length)]],t.length>e.length)n[0][0]=n[2][0]=H;return n}if(s.length===1)return[[H,t],[L,e]];var i=Bc(t,e);if(i){var a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],h=pe(a,l),d=pe(c,u);return h.concat([[P,f]],d)}return Hc(t,e)}function Hc(t,e){var n=t.length,r=e.length,s=Math.ceil((n+r)/2),o=s,i=2*s,a=Array(i),c=Array(i);for(var l=0;l<i;l++)a[l]=-1,c[l]=-1;a[o+1]=0,c[o+1]=0;var u=n-r,f=u%2!==0,h=0,d=0,p=0,g=0;for(var E=0;E<s;E++){for(var w=-E+h;w<=E-d;w+=2){var _=o+w,D;if(w===-E||w!==E&&a[_-1]<a[_+1])D=a[_+1];else D=a[_-1]+1;var I=D-w;while(D<n&&I<r&&t.charAt(D)===e.charAt(I))D++,I++;if(a[_]=D,D>n)d+=2;else if(I>r)h+=2;else if(f){var y=o+u-w;if(y>=0&&y<i&&c[y]!==-1){var x=n-c[y];if(D>=x)return ro(t,e,D,I)}}}for(var A=-E+p;A<=E-g;A+=2){var y=o+A,x;if(A===-E||A!==E&&c[y-1]<c[y+1])x=c[y+1];else x=c[y-1]+1;var S=x-A;while(x<n&&S<r&&t.charAt(n-x-1)===e.charAt(r-S-1))x++,S++;if(c[y]=x,x>n)g+=2;else if(S>r)p+=2;else if(!f){var _=o+u-A;if(_>=0&&_<i&&a[_]!==-1){var D=a[_],I=o+D-_;if(x=n-x,D>=x)return ro(t,e,D,I)}}}}return[[H,t],[L,e]]}function ro(t,e,n,r){var s=t.substring(0,n),o=e.substring(0,r),i=t.substring(n),a=e.substring(r),c=pe(s,o),l=pe(i,a);return c.concat(l)}function $n(t,e){if(!t||!e||t.charAt(0)!==e.charAt(0))return 0;var n=0,r=Math.min(t.length,e.length),s=r,o=0;while(n<s){if(t.substring(o,s)==e.substring(o,s))n=s,o=n;else r=s;s=Math.floor((r-n)/2+n)}if(co(t.charCodeAt(s-1)))s--;return s}function so(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 Ce(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(lo(t.charCodeAt(t.length-s)))s--;return s}function Bc(t,e){var n=t.length>e.length?t:e,r=t.length>e.length?e:t;if(n.length<4||r.length*2<n.length)return null;function s(d,p,g){var E=d.substring(g,g+Math.floor(d.length/4)),w=-1,_="",D,I,y,x;while((w=p.indexOf(E,w+1))!==-1){var A=$n(d.substring(g),p.substring(w)),S=Ce(d.substring(0,g),p.substring(0,w));if(_.length<S+A)_=p.substring(w-S,w)+p.substring(w,w+A),D=d.substring(0,g-S),I=d.substring(g+A),y=p.substring(0,w-S),x=p.substring(w+A)}if(_.length*2>=d.length)return[D,I,y,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 Wc(t){var e=!1,n=[],r=0,s=null,o=0,i=0,a=0,c=0,l=0;while(o<t.length){if(t[o][0]==P)n[r++]=o,i=c,a=l,c=0,l=0,s=t[o][1];else{if(t[o][0]==L)c+=t[o][1].length;else l+=t[o][1].length;if(s&&s.length<=Math.max(i,a)&&s.length<=Math.max(c,l))t.splice(n[r-1],0,[H,s]),t[n[r-1]+1][0]=L,r--,r--,o=r>0?n[r-1]:-1,i=0,a=0,c=0,l=0,s=null,e=!0}o++}if(e)Nn(t);jc(t),o=1;while(o<t.length){if(t[o-1][0]==H&&t[o][0]==L){var u=t[o-1][1],f=t[o][1],h=so(u,f),d=so(f,u);if(h>=d){if(h>=u.length/2||h>=f.length/2)t.splice(o,0,[P,f.substring(0,h)]),t[o-1][1]=u.substring(0,u.length-h),t[o+1][1]=f.substring(h),o++}else if(d>=u.length/2||d>=f.length/2)t.splice(o,0,[P,u.substring(0,d)]),t[o-1][0]=L,t[o-1][1]=f.substring(0,f.length-d),t[o+1][0]=H,t[o+1][1]=u.substring(d),o++;o++}o++}}var oo=/[^a-zA-Z0-9]/,io=/\s/,ao=/[\r\n]/,Gc=/\n\r?\n$/,Uc=/^\r?\n\r?\n/;function jc(t){function e(d,p){if(!d||!p)return 6;var g=d.charAt(d.length-1),E=p.charAt(0),w=g.match(oo),_=E.match(oo),D=w&&g.match(io),I=_&&E.match(io),y=D&&g.match(ao),x=I&&E.match(ao),A=y&&d.match(Gc),S=x&&p.match(Uc);if(A||S)return 5;else if(y||x)return 4;else if(w&&!D&&I)return 3;else if(D||I)return 2;else if(w||_)return 1;return 0}var n=1;while(n<t.length-1){if(t[n-1][0]==P&&t[n+1][0]==P){var r=t[n-1][1],s=t[n][1],o=t[n+1][1],i=Ce(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 Nn(t,e){t.push([P,""]);var n=0,r=0,s=0,o="",i="",a;while(n<t.length){if(n<t.length-1&&!t[n][1]){t.splice(n,1);continue}switch(t[n][0]){case L:s++,i+=t[n][1],n++;break;case H:r++,o+=t[n][1],n++;break;case P:var c=n-s-r-1;if(e){if(c>=0&&fo(t[c][1])){var l=t[c][1].slice(-1);if(t[c][1]=t[c][1].slice(0,-1),o=l+o,i=l+i,!t[c][1]){t.splice(c,1),n--;var u=c-1;if(t[u]&&t[u][0]===L)s++,i=t[u][1]+i,u--;if(t[u]&&t[u][0]===H)r++,o=t[u][1]+o,u--;c=u}}if(uo(t[n][1])){var l=t[n][1].charAt(0);t[n][1]=t[n][1].slice(1),o+=l,i+=l}}if(n<t.length-1&&!t[n][1]){t.splice(n,1);break}if(o.length>0||i.length>0){if(o.length>0&&i.length>0){if(a=$n(i,o),a!==0){if(c>=0)t[c][1]+=i.substring(0,a);else t.splice(0,0,[P,i.substring(0,a)]),n++;i=i.substring(a),o=o.substring(a)}if(a=Ce(i,o),a!==0)t[n][1]=i.substring(i.length-a)+t[n][1],i=i.substring(0,i.length-a),o=o.substring(0,o.length-a)}var f=s+r;if(o.length===0&&i.length===0)t.splice(n-f,f),n=n-f;else if(o.length===0)t.splice(n-f,f,[L,i]),n=n-f+1;else if(i.length===0)t.splice(n-f,f,[H,o]),n=n-f+1;else t.splice(n-f,f,[H,o],[L,i]),n=n-f+2}if(n!==0&&t[n-1][0]===P)t[n-1][1]+=t[n][1],t.splice(n,1);else n++;s=0,r=0,o="",i="";break}}if(t[t.length-1][1]==="")t.pop();var h=!1;n=1;while(n<t.length-1){if(t[n-1][0]===P&&t[n+1][0]===P){if(t[n][1].substring(t[n][1].length-t[n-1][1].length)===t[n-1][1])t[n][1]=t[n-1][1]+t[n][1].substring(0,t[n][1].length-t[n-1][1].length),t[n+1][1]=t[n-1][1]+t[n+1][1],t.splice(n-1,1),h=!0;else if(t[n][1].substring(0,t[n+1][1].length)==t[n+1][1])t[n-1][1]+=t[n+1][1],t[n][1]=t[n][1].substring(t[n+1][1].length)+t[n+1][1],t.splice(n+1,1),h=!0}n++}if(h)Nn(t,e)}function co(t){return t>=55296&&t<=56319}function lo(t){return t>=56320&&t<=57343}function uo(t){return lo(t.charCodeAt(0))}function fo(t){return co(t.charCodeAt(t.length-1))}function qc(t){var e=[];for(var n=0;n<t.length;n++)if(t[n][1].length>0)e.push(t[n]);return e}function Cn(t,e,n,r){if(fo(t)||uo(r))return null;return qc([[P,t],[H,e],[L,n],[P,r]])}function Xc(t,e,n){var r=typeof n==="number"?{index:n,length:0}:n.oldRange,s=typeof n==="number"?null:n.newRange,o=t.length,i=e.length;if(r.length===0&&(s===null||s.length===0)){var a=r.index,c=t.slice(0,a),l=t.slice(a),u=s?s.index:null;t:{var f=a+i-o;if(u!==null&&u!==f)break t;if(f<0||f>i)break t;var h=e.slice(0,f),d=e.slice(f);if(d!==l)break t;var p=Math.min(a,f),g=c.slice(0,p),E=h.slice(0,p);if(g!==E)break t;var w=c.slice(p),_=h.slice(p);return Cn(g,w,_,l)}t:{if(u!==null&&u!==a)break t;var D=a,h=e.slice(0,D),d=e.slice(D);if(h!==c)break t;var I=Math.min(o-D,i-D),y=l.slice(l.length-I),x=d.slice(d.length-I);if(y!==x)break t;var w=l.slice(0,l.length-I),_=d.slice(0,d.length-I);return Cn(c,w,_,y)}}if(r.length>0&&s&&s.length===0)t:{var g=t.slice(0,r.index),y=t.slice(r.index+r.length),p=g.length,I=y.length;if(i<p+I)break t;var E=e.slice(0,p),x=e.slice(i-I);if(g!==E||y!==x)break t;var w=t.slice(p,o-I),_=e.slice(p,i-I);return Cn(g,w,_,y)}return null}function $e(t,e,n,r){return pe(t,e,n,r,!0)}$e.INSERT=L;$e.DELETE=H;$e.EQUAL=P;ho.exports=$e});import*as en from"node:fs";import*as ee from"node:path";import{fileURLToPath as th}from"node:url";import*as rn from"node:os";import*as _t from"node:path";var sn="diffstalker";function ne(){return process.env.XDG_CONFIG_HOME||_t.join(rn.homedir(),".config")}function Er(){return _t.join(ne(),sn)}function At(){return _t.join(process.env.XDG_CACHE_HOME||_t.join(rn.homedir(),".cache"),sn)}function Sr(){return process.env.XDG_RUNTIME_DIR?_t.join(process.env.XDG_RUNTIME_DIR,sn):null}import*as Re from"node:fs";import*as ve from"node:path";import*as on from"node:os";function z(t){if(t.startsWith("~/"))return ve.join(on.homedir(),t.slice(2));if(t==="~")return on.homedir();return t}function xe(t){let e=ve.dirname(t);if(!Re.existsSync(e))Re.mkdirSync(e,{recursive:!0})}function an(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 Rr=!1;function vr(t){Rr=t}function xr(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 ga=/(\w+:\/\/)[^/\s@]+@/g;function wa(t){return t.replace(ga,"$1***@")}function ya(t){if(!t)return"";let e=[];for(let[n,r]of Object.entries(t)){if(r===void 0)continue;let s=xr(String(r));e.push(`${n}=${/\s/.test(s)||s===""?JSON.stringify(s):s}`)}return e.length===0?"":` ${e.join(" ")}`}function ba(t){if(t instanceof Error)return`${t.name}: ${t.message}`;return String(t)}function cn(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:ba(r);n.push(o+i),r=r instanceof Error?r.cause:void 0}return n.join(`
|
|
4
|
+
`)}function ln(t,e,n,r){let s=`${new Date().toISOString()} ${t.padEnd(5)} ${xr(e)}${ya(n)}`,o=r?`
|
|
5
|
+
${r.replace(/^/gm," ")}`:"";process.stderr.write(wa(`${s}${o}
|
|
6
|
+
`))}function N(t,e,n){if(!Rr)return;ln("debug",t,n,e===void 0?void 0:cn(e,{stacks:!1}))}function b(t,e,n){ln("warn",t,n,e===void 0?void 0:cn(e,{stacks:!1}))}function M(t,e,n){ln("error",t,n,e===void 0?void 0:cn(e))}import*as Ki from"node:http";import*as kt from"node:fs";import*as Yi from"node:net";function un(t){let e={};for(let[n,r]of t)e[n]=r;return e}function Ea(t){if(!t)return null;return{staged:un(t.staged),unstaged:un(t.unstaged)}}function lt(t){return{status:t.status,hunkCounts:Ea(t.hunkCounts),error:t.error,stashList:t.stashList,operationInProgress:t.operationInProgress,mtimes:t.mtimes?un(t.mtimes):null}}function kr(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 re(t){if(t instanceof Date)return t.toISOString();if(t instanceof Map){let e={};for(let[n,r]of t)e[String(n)]=re(r);return e}if(Array.isArray(t))return t.map(re);if(t!==null&&typeof t==="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=re(r);return e}return t}var Sa=1048576;class m extends Error{status;constructor(t,e,n){super(e,n);this.status=t,this.name="HttpError"}}function v(t,e,n){let r=JSON.stringify(re(n));t.writeHead(e,{"content-type":"application/json"}),t.end(r)}function _r(t,e,n,r){t.writeHead(e,{...r,"content-length":String(n.byteLength)}),t.end(n)}function Ra(t,e){if(t.segments.length!==e.length)return null;let n={};for(let r=0;r<t.segments.length;r++){let s=t.segments[r];if(s.startsWith(":"))try{n[s.slice(1)]=decodeURIComponent(e[r])}catch{throw new m(400,`Malformed percent-encoding in path: ${e[r]}`)}else if(s!==e[r])return null}return n}async function va(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>Sa)throw new m(413,"Request body too large");e.push(o)}let r=Buffer.concat(e).toString("utf-8");if(!r.trim())return;try{return JSON.parse(r)}catch{throw new m(400,"Invalid JSON body")}}class fn{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=Ra(n,e);if(r)return{handler:n.handler,params:r}}return null}async handle(t,e,n){try{let r=new URL(t.url??"/","http://localhost"),s=r.pathname.split("/").filter(Boolean),o=t.method??"GET",i=this.match(o,s);if(!i){if(n&&o==="GET"){await n(t,e,r.pathname);return}throw new m(404,`Unknown route: ${o} ${r.pathname}`)}let a=await va(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){M(`${s} failed after the response headers were sent`,r),e.end();return}if(r instanceof m){xa(s,r),v(e,r.status,{error:r.message});return}M(`${s} -> 500`,r),v(e,500,{error:"Internal server error"})}}}function xa(t,e){let n=`${t} -> ${e.status} ${e.message}`;if(e.cause!==void 0||e.status>=500)b(n,e.cause);else N(n)}import*as hn from"node:fs";import*as j from"node:path";var ka=new Set(["health","version","repos","resolve","worktrees","events","follow","settings","discovered","browse"]),_a={".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"},Ar="no-cache",Aa="public, max-age=31536000, immutable";async function Dr(t,e,n){let r;try{r=await hn.promises.readFile(e)}catch(s){throw new m(404,`Not found: ${j.basename(e)}`,{cause:s})}t.writeHead(200,{"content-type":_a[j.extname(e)]??"application/octet-stream","cache-control":n,"content-length":r.length}),t.end(r)}function Ir(t){let e=j.resolve(t);return async(n,r,s)=>{let o;try{o=decodeURIComponent(s)}catch{throw new m(400,`Malformed percent-encoding in path: ${s}`)}if(o.includes("\x00"))throw new m(400,"Invalid path");let i=o.split("/").filter(Boolean);if(i.length>0&&ka.has(i[0]))throw new m(404,`Unknown route: GET ${s}`);let a=i.length>0?j.resolve(e,i.join("/")):e;if(a!==e&&!a.startsWith(e+j.sep))throw new m(403,"Forbidden");if((await hn.promises.stat(a).catch(()=>null))?.isFile()){await Dr(r,a,i[0]==="assets"?Aa:Ar);return}await Dr(r,j.join(e,"index.html"),Ar)}}function Da(t){try{let e=new URL(`http://${t}`).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function Ia(t){try{let e=new URL(t).hostname.toLowerCase();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}catch{return null}}function Mr(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 Ta(t){return t.length>10&&t.endsWith(".localhost")}function Tr(t){return t==="localhost"||t==="::1"||Ta(t)||Mr(t)}function Ma(t){return t==="::1"||Mr(t)}function Pr(t){if(t===null)return!1;if(typeof t==="string")return!0;return Ma(t.address)}function Fr(t){let e=t.headers.host;if(e!==void 0){let i=Da(e);if(i===null||!Tr(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=Ia(o);if(i===null||!Tr(i))return{status:403,message:"Cross-origin request blocked"}}return null}function Cr(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 $r={"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 Rl}from"node:crypto";class Nr{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)=>{M("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 dn=new Map;function Or(t){let e=dn.get(t);if(!e)e=new Nr(t),dn.set(t,e);return e}function Lr(t){dn.delete(t)}import*as me from"node:path";import*as bt from"node:fs";import{EventEmitter as Jc}from"node:events";import*as tt from"node:fs";import*as ut from"node:path";function Hr(t,e){return t===""?e:`${t}/${e}`}function Br(t){let e=t.lastIndexOf("/");return e===-1?"":t.slice(0,e)}function pn(t,e){return t===e||e===""||t.startsWith(`${e}/`)}class se{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:ut.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(Br(t))}async directoryInode(t){try{let e=await(t===""?tt.promises.stat:tt.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 tt.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=ut.basename(this.abs(t));for(let s of e){if(s.name===r)this.namesakes.add(t);let o=Hr(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=tt.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=Hr(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 tt.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=ut.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=Br(t);if(ut.basename(t)!==ut.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===""?tt.promises.stat:tt.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(pn(e,t))n.close(),this.watches.delete(e),this.inodes.delete(e);for(let e of this.skipped)if(pn(e,t))this.skipped.delete(e);for(let e of this.namesakes)if(pn(e,t))this.namesakes.delete(e)}}import*as jr from"node:fs";import*as et from"node:path";import{execFile as ja}from"node:child_process";import{promisify as qa}from"node:util";import Gr from"ignore";import{execFile as Oa}from"node:child_process";import{promisify as La}from"node:util";import{simpleGit as Ha}from"simple-git";import*as K from"node:fs";import*as ie from"node:path";import{execFileSync as Pa}from"node:child_process";var Fa=[["*.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 Ca(){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
|
+
`+Fa.map(([e,n])=>`${e} diff=${n}`).join(`
|
|
9
9
|
`)+`
|
|
10
|
-
`}var
|
|
11
|
-
`))if(c.length>0)i.add(c);return i}function
|
|
10
|
+
`}var oe=null,dt=null;function $a(){if(dt!==null)return dt;try{if(Pa("git",["config","--get","core.attributesFile"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:process.env}).trim()!=="")return dt=!0,!0}catch(t){if(t.status!==1)return b("git config core.attributesFile failed; funcname drivers are off",t),dt=!0,!0}return dt=K.existsSync(ie.join(ne(),"git","attributes")),dt}function Wr(){if(oe!==null)return oe;if($a())return null;let t=ie.join(At(),"funcname.gitattributes"),e=Ca();try{let n=null;try{n=K.readFileSync(t,"utf8")}catch{n=null}if(n!==e)K.mkdirSync(ie.dirname(t),{recursive:!0}),Na(t,e);return oe=t,oe}catch(n){return b("Cannot write the attributes file; funcname drivers are off",n,{file:t}),oe=null,dt=!0,null}}function Na(t,e){let n=`${t}.${process.pid}.tmp`;K.writeFileSync(n,e,"utf8"),K.renameSync(n,t)}var Ba=La(Oa);function ft(){return{...process.env,LC_ALL:"C",LANG:"C",GIT_OPTIONAL_LOCKS:"0"}}var ae=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"],mn=5000;async function ke(t,e,n){let{stdout:r}=await Ba("git",e,{cwd:t,env:ft(),encoding:"buffer",maxBuffer:n,timeout:mn,windowsHide:!0});return r}var Wa={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0},Ga=1e4,Ua=600000;function R(t,e={}){let n=Wr(),r=["diff.mnemonicPrefix=false","diff.noprefix=false"];if(n!==null)r.push(`core.attributesFile=${n}`);let s=ft();return Ha({baseDir:t,unsafe:Wa,allowEnvironment:Object.keys(s),timeout:{block:e.longRunning===!0?Ua:Ga},config:r}).env(s)}var Xa=qa(ja),za=47;function Ur(t,e){if(e==="")return t;if(t.startsWith(e)&&t.charCodeAt(e.length)===za)return t.slice(e.length+1);return null}class qr{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=Ur(t,s);if(i===null)continue;let a=o.checkIgnore(e?`${i}/`:i);if(!a.ignored&&!a.unignored)continue;let c=Ur(r,s);if(c&&o.checkIgnore(`${c}/`).rule===a.rule)continue;return a.ignored}return!1}}function Xr(t,e){try{return jr.readFileSync(t,"utf-8")}catch(n){if(n.code!=="ENOENT")b(`Failed to read ${t}`,n,{repo:e});return null}}async function zr(t,e){let{stdout:n}=await Xa("git",e,{cwd:t,env:ft(),encoding:"utf-8",maxBuffer:67108864});return n}async function Ja(t){try{let e=(await zr(t,["config","--path","--get","core.excludesFile"])).trim();if(e)return et.resolve(t,e)}catch(e){if(e.code!==1)return b("git config core.excludesFile failed; global ignore rules are not applied",e,{repo:t}),null}return et.join(ne(),"git","ignore")}async function Ka(t){let e=new Map,n;try{n=await zr(t,["ls-files","-z","--cached","--others","--exclude-standard","**/.gitignore"])}catch(r){return b("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=Xr(et.join(t,r),t);if(s!==null)e.set(et.posix.dirname(r),s)}return e}async function gn(t,e){let[n,r]=await Promise.all([Ka(t),Ja(t)]),s=[...n].sort(([i],[a])=>a.split("/").length-i.split("/").length).map(([i,a])=>({dir:i,rules:Gr().add(a)})),o=[et.join(t,".gitignore"),et.join(e,"info","exclude"),...r===null?[]:[r]];for(let i of o){let a=Xr(i,t);if(a!==null)s.push({dir:"",rules:Gr().add(a)})}return new qr(s)}import{execFileSync as sc}from"node:child_process";import*as ue from"node:fs";import*as bn from"node:path";async function Dt(t,e){if(e.length===0)return new Set;let n=R(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))b("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
|
+
`))if(c.length>0)i.add(c);return i}function pt(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 _e(t){let e=0;for(let n of t)e+=n.content.length+1;return e}var Ya=5000,ce=262144,Vr="Large file — diff not shown";function Va(t){return String(t).replace(/\B(?=(\d{3})+(?!\d))/g,",")}function Qa(t){let e=t/1048576;if(e>=1)return`${e.toFixed(1)} MB`;return`${Math.round(t/1024)} KB`}function wn(t,e){let n=Qa(t),r=e===void 0?n:`${n}, ${Va(e)} lines`;return`${Vr} (${r})`}function Jr(t){if(t.length===0)return 0;let e=1,n=-1;while((n=t.indexOf(`
|
|
14
|
+
`,n+1))!==-1)e++;return e}function Kr(t,e,n){let r=t.split(`
|
|
15
|
+
`),s=r.findIndex((i)=>i.startsWith("@@"));return`${[...r.slice(0,s===-1?4:s),wn(e,n)].join(`
|
|
16
16
|
`)}
|
|
17
|
-
`}function
|
|
18
|
-
`);if(e.length>1&&e[e.length-1]==="")e.pop();let n=[],r=0,s=0;for(let o of e)if(
|
|
19
|
-
`))if(r.startsWith("diff --git")){let s=
|
|
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 nt(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<=ce){let i=Jr(s);if(i<=Ya)return s;return n=!0,Kr(s,o,i)}return n=!0,Kr(s,o,Jr(s))});return n?r.join(""):t}function Za(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(Vr)}function tc(t){return t.startsWith("\\ ")}function Qr(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 rt(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(Za(o))n.push({type:"header",content:o});else if(tc(o))n.push({type:"context",content:o});else if(o.startsWith("@@")){let i=Qr(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 Ae(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=mt(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 Zr=new Map([["a",7],["b",8],["f",12],["n",10],["r",13],["t",9],["v",11],["\\",92],['"',34]]),ec=new Map([...Zr].map(([t,e])=>[e,t]));function Yr(t){return t<32||t===127||t>=128||t===34||t===92}function It(t){let e=new TextEncoder().encode(t);if(!e.some(Yr))return t;let n='"';for(let r of e){let s=ec.get(r);if(s!==void 0)n+=`\\${s}`;else if(Yr(r))n+=`\\${r.toString(8).padStart(3,"0")}`;else n+=String.fromCharCode(r)}return`${n}"`}function nc(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=Zr.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 rc(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 mt(t){if(!t.startsWith("diff --git "))return null;let n=t.slice(11);if(n.endsWith('"')){let s=rc(n);if(s===-1)return null;let o=nc(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 le(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 yn(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 Tt(t){return t instanceof Error?t.message:String(t)}function es(t){return/does not have any commits yet|bad default revision/i.test(Tt(t))}var oc=ce;async function ic(t,e){try{let n=bn.join(t,e),r=await ue.promises.stat(n);if(!r.isFile())return null;if(r.size>oc)return null;return(await ue.promises.readFile(n,"utf-8")).split(`
|
|
20
|
+
`).filter((o)=>o.length>0).length}catch{return null}}var ac=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function cc(t,e){return ac.has(`${t}${e}`)}function ts(t,e){return e?"conflicted":lc(t)}function lc(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 En(t){let e=R(t);if(!await e.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let r=await e.status(),s=[],o=new Set,i=r.files.filter((p)=>p.working_dir==="?").map((p)=>p.path),a=await Dt(t,i);for(let p of r.files){if(p.index==="!"||p.working_dir==="!"||a.has(p.path))continue;let g=`${p.path}-${p.index!==" "&&p.index!=="?"}`;if(o.has(g))continue;o.add(g);let E=cc(p.index,p.working_dir);if(p.index&&p.index!==" "&&p.index!=="?"){let w=ts(p.index,E);s.push({path:p.path,status:w,staged:!0,...p.from&&(w==="renamed"||w==="copied")?{originalPath:p.from}:{}})}if(p.working_dir&&p.working_dir!==" ")s.push({path:p.path,status:ts(p.working_dir,E),staged:!1})}let c=(p)=>e.diff([...p,"--numstat","-z"]).catch((g)=>(b(`git diff ${p.join(" ")} --numstat failed in ${t}: ${Tt(g)}`),"")),[l,u]=await Promise.all([c(["--cached"]),c([])]),f=le(l),h=le(u);for(let p of s){let g=p.staged?f.get(p.path):h.get(p.path);if(g)p.insertions=g.additions,p.deletions=g.deletions}let d=s.filter((p)=>p.status==="untracked");if(d.length>0){let p=await Promise.all(d.map((g)=>ic(t,g.path)));for(let g=0;g<d.length;g++){let E=p[g];if(E===null)continue;d[g].insertions=E,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 ns(t,e){await R(t).add(["--",e])}async function rs(t,e){await R(t).reset(["HEAD","--",e])}async function ss(t){await R(t).add("-A")}async function os(t){await R(t).reset(["HEAD"])}async function is(t,e){await R(t).checkout(["--",e])}async function as(t,e){await R(t).clean("f",["--",e])}async function cs(t,e,n=!1){if(!(await R(t,{longRunning:!0}).commit(e,void 0,n?{"--amend":null}:void 0)).commit)throw Error("Nothing to commit: no staged changes")}async function ls(t){let e=R(t);try{return(await e.log({n:1})).latest?.message||""}catch(n){if(!es(n))b(`git log for the HEAD message failed in ${t}: ${Tt(n)}`);return""}}function us(t,e,n){sc("git",["apply","--cached",...n?["--reverse"]:[],"--unidiff-zero"],{cwd:t,input:e,encoding:"utf-8",env:ft(),stdio:["pipe","pipe","pipe"]})}function fs(t,e){us(t,e,!1)}function hs(t,e){us(t,e,!0)}async function ds(t){let r=(await R(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 ps(t){return await R(t,{longRunning:!0}).fetch(),"Fetch complete"}async function ms(t){let n=await R(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 gs(t,e=50){let n=R(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(!es(r))b(`git log failed in ${t}: ${Tt(r)}`);return[]}}async function ws(t,e){let n=R(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 Sn(t){let e=R(t);try{return(await e.stashList()).all.map((r,s)=>({index:s,message:r.message}))}catch(n){return b(`git stash list failed in ${t}, reporting no stashes: ${Tt(n)}`),[]}}async function ys(t,e){let n=R(t),r=["push"];if(e)r.push("-m",e);return await n.stash(r),"Stashed"}async function bs(t,e=0){let n=R(t);await n.stash(["pop",`stash@{${e}}`]);let r=(await n.raw(["diff","--name-only","--diff-filter=U"])).trim();if(r)throw Error(`Stash pop hit conflicts in: ${r.split(`
|
|
23
|
+
`).join(", ")}`);return"Stash popped"}async function Es(t){let n=await R(t).branchLocal();return n.all.map((r)=>({name:r,current:r===n.current,tracking:n.branches[r]?.label||void 0}))}async function Ss(t,e){return await R(t).raw(["switch","--",e]),`Switched to ${e}`}async function Rs(t,e){return await R(t).raw(["switch","-c",e]),`Created ${e}`}async function vs(t,e=1){return await R(t).reset(["--soft",`HEAD~${e}`]),"Reset done"}async function xs(t,e){return await R(t,{longRunning:!0}).raw(["cherry-pick","--end-of-options",e]),"Cherry-picked"}async function ks(t,e){return await R(t,{longRunning:!0}).raw(["revert","--no-edit","--end-of-options",e]),"Reverted"}async function Mt(t){let e=R(t),n;try{n=(await e.raw(["rev-parse","--absolute-git-dir"])).trim()}catch(s){return b(`git rev-parse --absolute-git-dir failed in ${t}: ${Tt(s)}`),null}let r=(s)=>ue.existsSync(bn.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 _s(t){let e=await Mt(t);if(!e)throw Error("No operation in progress to abort");return await R(t).raw([e,"--abort"]),`Aborted ${e}`}async function As(t){return await R(t,{longRunning:!0}).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function Ds(t){return(await R(t).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((r)=>r.length>0)}import*as gt from"node:fs";import*as $t from"node:path";import*as Pt from"node:fs";import*as fe from"node:path";function Rn(){return fe.join(At(),"base-branches.json")}function Is(){let t=Rn();try{return JSON.parse(Pt.readFileSync(t,"utf-8"))}catch(e){if(e.code!=="ENOENT")b("Ignoring the base-branch cache",e,{file:t});return{}}}function uc(t){xe(Rn()),Pt.writeFileSync(Rn(),JSON.stringify(t,null,2)+`
|
|
24
|
+
`)}function Ft(t){let e=Is(),n=fe.resolve(t);return e[n]}function Ts(t,e){let n=Object.fromEntries(Object.entries(Is()).filter(([s])=>Pt.existsSync(s))),r=fe.resolve(t);n[r]=e,uc(n)}function he(t){let e=Math.min(t.length,8192);for(let n=0;n<e;n++)if(t[n]===0)return!0;return!1}var Ms={staged:!1,unstaged:!1,untracked:!1};class De extends Error{constructor(t){super(`No common history with ${t}`);this.name="NoCommonHistoryError"}}var wt=3,$s=1e5;function Ie(t){return t instanceof Error?t.message:String(t)}function Te(t,e,n){b(`${t} failed in ${e}, answering an empty diff: ${Ie(n)}`)}async function Ns(t,e,n=!1,r={}){let s=R(t);try{let o=[`-U${r.context??wt}`];if(n)o.push("--cached");o.push("--",e);let i=nt(await s.diff(o));return{lines:rt(i)}}catch(o){return Te(`git diff${n?" --cached":""} -- ${e}`,t,o),{lines:[]}}}async function Os(t,e){let n=R(t),r=[`-U${wt}`];if(e)r.push("--cached");return{lines:rt(nt(await n.diff(r)))}}var fc="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Ls="(unborn)",hc=/unknown revision|ambiguous argument 'HEAD'|needed a single revision/i;async function Me(t){let e=R(t);try{return(await e.raw(["rev-parse","HEAD"])).trim()}catch(n){let r=n instanceof Error?n.message:String(n);if(hc.test(r))return Ls;throw n}}async function Hs(t,e){let n=R(t),s=(e??await Me(t))===Ls?fc:"HEAD",o=nt(await n.raw(["diff",`-U${wt}`,s,"--"]));return{lines:rt(o)}}var dc=ce;function vn(t,e={}){let n=It(`a/${t}`),r=It(`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 pc(t,e){return{lines:[...vn(t),{type:"header",content:wn(e)}]}}function mc(t){return{lines:vn(t,{binary:!0})}}function gc(t,e){let n=$t.resolve(t),r=$t.resolve(n,e);if(r!==n&&!r.startsWith(n+$t.sep))return null;let s,o;try{s=gt.realpathSync(r),o=gt.realpathSync(n)}catch{return null}if(s!==o&&!s.startsWith(o+$t.sep))return null;let i=gt.statSync(s);if(!i.isFile())return null;return{path:r,size:i.size}}async function yt(t,e){try{let n=gc(t,e);if(n===null)return{lines:[]};if(n.size>dc)return pc(e,n.size);let r=gt.readFileSync(n.path);if(he(r))return mc(e);let s=r.toString("utf-8"),o=vn(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=
|
|
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[a,c,l=""]=i.split(" ");if(a)r.set(a,{commit:c,symref:l})}let o=[];for(let i of n){let a=`${
|
|
30
|
-
`);return
|
|
31
|
-
`)[0],author:
|
|
32
|
-
`)}async 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 An(t){try{if(V.statSync(t).isDirectory())return t;return N.dirname(t)}catch{let e=N.dirname(t);return e!==t&&V.existsSync(e)?e:null}}var Ac=ta(Zs(),1);function to(t){return pt(t)}function Te(t){let e=new Map,n=null;for(let s of t.lines){if(s.type==="header"&&s.content.startsWith("diff --git")){let o=to(s.content);if(o!==null)n=e.get(o)??[],e.set(o,n);else n=null}n?.push(s)}let r=new Map;for(let[s,o]of e)r.set(s,{lines:o});return r}var Me="diffstalker-journal: oversize untracked snapshot omitted";var Pc=262144,Tc=new Set(["EACCES","EPERM","ENOENT"]),Tn=47;function Mc(t,e){if(e==="")return t;if(t.startsWith(e)&&t.charCodeAt(e.length)===Tn)return t.slice(e.length+1);return null}function Fc(t){let e=t?.code;return typeof e==="string"&&Tc.has(e)}function $c(){return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1}}class Fe extends Dc{repoPath;queue;hunkTimes;gitWatcher=null;workingDirWatcher=null;ignorers=new Map;_state={status:null,isLoading:!1,error:null,hunkCounts:null,stashList:[],operationInProgress:null,mtimes:null};constructor(t,e){super();this.repoPath=t,this.queue=e,this.hunkTimes=new Rn(t)}get state(){return this._state}_wholeTreeDiffs=null;fullRefreshRunning=!1;diffWaiters=[];async wholeTreeDiffs(){if(this._wholeTreeDiffs)return this._wholeTreeDiffs;let t=new Promise((e)=>this.diffWaiters.push(e));if(!this.fullRefreshRunning)this.refresh().catch((e)=>{T("Refresh for whole-tree diffs threw",e,{repo:this.repoPath})});return await t,this._wholeTreeDiffs}settleDiffWaiters(){let t=this.diffWaiters;this.diffWaiters=[];for(let e of t)e()}get unavailable(){return this._state.status?.isRepo===!1?this.unavailableReason:null}unavailableReason=null;updateState(t){this._state={...this._state,...t},this.emit("state-change",this._state)}setError(t){this.updateState({error:t})}clearError(){if(this._state.error!==null)this.updateState({error:null})}stampDiff(t){this.hunkTimes.stamp(t)}loadGitignores(){let t=new Map,e=no();e.add(".git");let n=B.join(this.repoPath,".gitignore");if(U.existsSync(n))e.add(U.readFileSync(n,"utf-8"));let r=B.join(this.repoPath,".git","info","exclude");if(U.existsSync(r))e.add(U.readFileSync(r,"utf-8"));t.set("",e);try{let s=Ic("git",["ls-files","-z","--cached","--others","--exclude-standard","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:ct(),stdio:["ignore","pipe","pipe"]});for(let o of s.split("\x00")){if(!o||o===".gitignore")continue;if(!o.endsWith(".gitignore"))continue;let i=B.dirname(o),a=B.join(this.repoPath,o);try{let c=U.readFileSync(a,"utf-8"),l=no();l.add(c),t.set(i,l)}catch(c){E(`Failed to read ${a}`,c,{repo:this.repoPath})}}}catch(s){E("git ls-files failed; nested .gitignore files are not applied",s,{repo:this.repoPath})}return t}startWatching(){let t=Ws(this.repoPath);if(t===null)return;let e=B.join(t.gitDir,"index"),n=B.join(t.gitDir,"HEAD"),r=B.join(t.commonDir,"refs"),s=B.join(t.commonDir,"packed-refs"),o=B.join(this.repoPath,".gitignore");this.gitWatcher=eo([e,n,r,s,o],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=eo(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(a)=>this.isIgnored(a),awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let i=()=>this.scheduleRefresh();this.gitWatcher.on("change",(a)=>{if(a===o)this.ignorers=this.loadGitignores();i()}),this.gitWatcher.on("add",i),this.gitWatcher.on("unlink",i),this.gitWatcher.on("error",(a)=>{this.logWatchError("Git dir watcher error",a),this.setError(`Git watcher error: ${a instanceof Error?a.message:String(a)}`)}),this.workingDirWatcher.on("change",i),this.workingDirWatcher.on("add",i),this.workingDirWatcher.on("unlink",i),this.workingDirWatcher.on("error",(a)=>{this.logWatchError("Working dir watcher error",a),this.setError(`Working dir watcher error: ${a instanceof Error?a.message:String(a)}`)})}isIgnored(t){let e=this.relativeToRoot(t);if(e==="")return!1;for(let[n,r]of this.ignorers){let s=Mc(e,n);if(s!==null&&r.ignores(s))return!0}return!1}relativeToRoot(t){let e=this.repoPath.length;if(this.repoPath.charCodeAt(e-1)===Tn)e--;let n=t.length;if(t.charCodeAt(n-1)===Tn)n--;return n<=e?"":t.slice(e+1,n)}logWatchError(t,e){if(Fc(e))L(t,e,{repo:this.repoPath});else E(t,e,{repo:this.repoPath})}dispose(){let t=(e)=>(n)=>E(`Failed to close the ${e} watcher`,n,{repo:this.repoPath});this.gitWatcher?.close().catch(t("git dir")),this.workingDirWatcher?.close().catch(t("working dir")),this.settleDiffWaiters()}statMtimes(t){let e=new Map;for(let n of t.files){if(e.has(n.path))continue;try{e.set(n.path,U.statSync(B.join(this.repoPath,n.path)).mtimeMs)}catch{}}return e}pendingRefreshKind=null;scheduleRefresh(){this.requestRefresh("full")}scheduleStatusRefresh(){this.requestRefresh("status")}requestRefresh(t){if(this.pendingRefreshKind!==null){if(t==="full")this.pendingRefreshKind="full";return}if(this.queue.hasPendingMutations())return;this.pendingRefreshKind=t,this.queue.scheduleRefresh(async()=>{let e=this.pendingRefreshKind??"full";if(this.pendingRefreshKind=null,e==="full")await this.doRefresh();else await this.doStatusRefresh()})}notARepo(t,e){if(this._state.status?.isRepo!==!1)E(`${e} (was open as one)`,void 0,{repo:this.repoPath});this.unavailableReason=e,this._wholeTreeDiffs=null,this.updateState({status:t,isLoading:!1,error:e})}refreshFailed(t,e){if(!U.existsSync(this.repoPath)){this.notARepo($c(),"Repository directory no longer exists");return}E(t,e,{repo:this.repoPath}),this.updateState({isLoading:!1,error:e instanceof Error?e.message:"Unknown error"})}async doStatusRefresh(){try{let t=await pn(this.repoPath);if(!t.isRepo){this.notARepo(t,"Not a git repository");return}this._wholeTreeDiffs=null,this.updateState({status:t,mtimes:this.statMtimes(t),isLoading:!1})}catch(t){this.refreshFailed("Status refresh failed",t)}}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.fullRefreshRunning=!0;try{await this.readFullState()}finally{this.fullRefreshRunning=!1,this.settleDiffWaiters()}}async readFullState(){this.updateState({isLoading:!0,error:null});let t=Date.now(),e=await _e(this.repoPath).catch((n)=>(L("HEAD oid unreadable; journal observation skipped",n,{repo:this.repoPath}),null));try{let n=await pn(this.repoPath);if(!n.isRepo){this.notARepo(n,"Not a git repository");return}let r=this.snapshotJournalGuard(n),[s,o,{stashList:i,operation:a},c]=await Promise.all([le(this.repoPath,void 0,!1),le(this.repoPath,void 0,!0),r,this.gatherJournalInputs(n,e,t,r)]),l={unstaged:ve(dt(s.lines)),staged:ve(dt(o.lines))};this.hunkTimes.stampTree([s,o]);let u=this.statMtimes(n);if(this._wholeTreeDiffs={unstaged:s,staged:o},this.updateState({status:n,hunkCounts:l,stashList:i,operationInProgress:a,mtimes:u,isLoading:!1}),c!==null)this.emit("journal-observation",{status:n,headDiff:c.headDiff,headOid:c.headOid,stashCount:c.stashCount,operationInProgress:c.operationInProgress,mtimes:c.mtimes,at:Date.now()})}catch(n){this.refreshFailed("Refresh failed",n)}}async snapshotJournalGuard(t){let[e,n]=await Promise.all([It(this.repoPath),mn(this.repoPath)]);return{operation:e,stashList:n,mtimes:this.statMtimes(t)}}static journalGuardMoved(t,e){if(t.operation!==e.operation||t.stashList.length!==e.stashList.length)return!0;if(t.mtimes.size!==e.mtimes.size)return!0;for(let[n,r]of t.mtimes)if(e.mtimes.get(n)!==r)return!0;return!1}sectionWrittenDuringGather(t,e,n){let r=new Set(e);for(let s of t.files)if(s.status==="untracked")r.add(s.path);for(let s of r)try{let o=U.statSync(B.join(this.repoPath,s));if(Math.floor(o.mtimeMs)>n)return!0}catch{}return!1}async gatherJournalInputs(t,e,n,r){if(e===null)return null;try{let s=await r,o=await ks(this.repoPath,e),i=new Set(Te(o).keys()),a=[...o.lines];await this.appendUntrackedSections(t,i,a);let c=await _e(this.repoPath);if(e!==c)return null;let l=await this.snapshotJournalGuard(t);if(Fe.journalGuardMoved(s,l))return null;if(this.sectionWrittenDuringGather(t,i,n))return null;return{headDiff:{lines:a},headOid:c,stashCount:l.stashList.length,operationInProgress:l.operation,mtimes:l.mtimes}}catch(s){return L("Journal observation skipped: git read failed",s,{repo:this.repoPath}),null}}async appendUntrackedSections(t,e,n){let r=new Set;for(let s of t.files){if(s.status!=="untracked"||r.has(s.path)||e.has(s.path))continue;r.add(s.path);let o;try{o=U.statSync(B.join(this.repoPath,s.path))}catch{continue}if(!o.isFile())continue;if(o.size>Pc){this.appendOversizeSection(s.path,o,n);continue}let i=await gt(this.repoPath,s.path);if(i.lines.length===0)continue;n.push(...i.lines)}}appendOversizeSection(t,e,n){let r=[`diff --git ${_t("a/"+t)} ${_t("b/"+t)}`,"new file mode 100644",`${Me} size=${e.size} mtime=${Math.round(e.mtimeMs)}`];n.push(...r.map((s)=>({type:"header",content:s})))}failed(t,e,n){E(`Failed to ${t}`,e,{repo:this.repoPath,file:n}),this.updateState({error:`Failed to ${t}: ${e instanceof Error?e.message:String(e)}`})}async stage(t){try{await this.queue.enqueueMutation(()=>Ur(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(()=>Gr(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()=>Qr(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.failed("stage hunk",e)}}async unstageHunk(t){try{await this.queue.enqueueMutation(async()=>Zr(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.failed("unstage hunk",e)}}async discard(t){if(t.staged)return;let e=t.status==="untracked"?()=>Jr(this.repoPath,t.path):()=>zr(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(()=>qr(this.repoPath)),await this.refresh()}catch(t){this.failed("stage all",t)}}async unstageAll(){try{await this.queue.enqueueMutation(()=>Xr(this.repoPath)),await this.refresh()}catch(t){this.failed("unstage all",t)}}async commit(t,e=!1){try{await this.queue.enqueue(()=>Kr(this.repoPath,t,e)),await this.refresh()}catch(n){this.failed("commit",n)}}async loadStashList(){try{let t=await this.queue.enqueue(()=>mn(this.repoPath));this.updateState({stashList:t})}catch(t){E("Failed to load the stash list",t,{repo:this.repoPath})}}}import{EventEmitter as Cc}from"node:events";class Mn extends Cc{repoPath;queue;callbacks;_remoteState={operation:null,inProgress:!1,error:null,lastResult:null};constructor(t,e,n){super();this.repoPath=t,this.queue=e,this.callbacks=n}get remoteState(){return this._remoteState}updateRemoteState(t){this._remoteState={...this._remoteState,...t},this.emit("remote-state-change",this._remoteState)}async runRemoteOperation(t,e){this.updateRemoteState({operation:t,inProgress:!0,error:null,lastResult:null});try{let n=await this.queue.enqueue(e);this.updateRemoteState({inProgress:!1,lastResult:n}),this.callbacks.scheduleRefresh()}catch(n){E(`git ${t} failed`,n,{repo:this.repoPath});let r=n instanceof Error?n.message:String(n);this.updateRemoteState({inProgress:!1,error:r})}return this._remoteState}async push(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("push",()=>ts(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>es(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>ns(this.repoPath))}async stash(t){if(this._remoteState.inProgress)return null;let e=await this.runRemoteOperation("stash",()=>os(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",()=>is(this.repoPath,t));return await this.callbacks.loadStashList(),e}async switchBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>cs(this.repoPath,t))}async createBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>ls(this.repoPath,t))}async softReset(t=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>us(this.repoPath,t))}async cherryPick(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>fs(this.repoPath,t))}async revertCommit(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>hs(this.repoPath,t))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>ds(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>ps(this.repoPath))}}import{EventEmitter as Nc}from"node:events";import{randomBytes as Oc}from"node:crypto";var Lc=262144,Bc=500,Hc=16777216,oo=Number.MAX_SAFE_INTEGER,Wc=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function jc(t){let e=Wc.exec(t);if(!e)return null;return{oldStart:parseInt(e[1],10),oldCount:e[2]!==void 0?parseInt(e[2],10):1}}function Uc(t,e){let n=jc(e);if(!n)return[];let r=n.oldCount===0?n.oldStart+1:n.oldStart,s=[],o=null;for(let i of t){let a=i.content[0];if(a==="\\")continue;if(a==="-")o=Gc(o,r),r++;else if(a==="+")o=o??{hasDel:!1,delStart:0,delEnd:0,anchor:r-1};else ro(s,o),o=null,r++}return ro(s,o),s}function Gc(t,e){if(!t)return{hasDel:!0,delStart:e,delEnd:e,anchor:e-1};if(!t.hasDel)t.hasDel=!0,t.delStart=e;return t.delEnd=e,t}function ro(t,e){if(!e)return;t.push(e.hasDel?[2*e.delStart,2*e.delEnd]:[2*e.anchor,2*e.anchor+2])}function $n(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>=oo)return{start:0,count:0};let r=Math.ceil(e/2),s=Math.floor(n/2);return{start:r,count:s-r+1}}function qc(t){let e=[],n=null,r=[],s=null;for(let i of t.lines)if(i.type==="hunk")s={header:i,body:[]},r.push(s);else if(s)s.body.push(i);else if(e.push(i),i.content.startsWith("rename from "))n=i.content.slice(12);if(r.length===0){let i=e.some((a)=>a.content.startsWith(Me));return{hunks:[{runs:[[0,oo]],bodyHash:Ae([dt(t.lines)]),ins:0,del:0,span:{start:0,count:0},diff:t,oversize:i}],renamedFrom:n,hunkless:!0}}return{hunks:r.map(({header:i,body:a})=>{let c=Uc(a,i.content),l=[],u=0,f=0;for(let d of a){let p=d.content[0];if(p==="\\")continue;if(p==="+")u++,l.push(d.content);else if(p==="-")f++,l.push(d.content)}let h=[...e,i,...a];return{runs:c,bodyHash:Ae(l),ins:u,del:f,span:$n(c),diff:{lines:h}}}),renamedFrom:n,hunkless:!1}}function Fn(t){return Buffer.from(t,"utf8").toString("utf8")}function Xc(t){if(t.oversize===!0)return null;if(Se(t.diff.lines)>Lc)return null;return{lines:t.diff.lines.map((e)=>({...e,content:Fn(e.content)}))}}function zc(t,e,n){if(t===0&&e>0)return"shrunk";let r=t+e;if(r>n)return"expanded";if(r<n)return"shrunk";return"edited"}function so(t,e){let n=[];return t.forEach((r,s)=>{for(let[o,i]of r.runs)n.push({lo:o,hi:i,node:e+s})}),n.sort((r,s)=>r.lo-s.lo),n}function Jc(t,e){let n=Array.from({length:t.length+e.length},(c,l)=>l),r=(c)=>{while(n[c]!==c)n[c]=n[n[c]],c=n[c];return c},s=(c,l)=>{let u=r(c),f=r(l);if(u!==f)n[u]=f},o=so(t,0),i=so(e,t.length),a=0;for(let c of o){while(a<i.length&&i[a].hi<c.lo)a++;for(let l=a;l<i.length&&i[l].lo<=c.hi;l++)s(c.node,i[l].node)}return n.map((c,l)=>r(l))}function Kc(t,e){let n=Jc(t,e),r=new Map,s=(o)=>{let i=r.get(o);if(!i)i={prevIdx:[],nextIdx:[],minLo:1/0},r.set(o,i);return i};return t.forEach((o,i)=>{let a=s(n[i]);a.prevIdx.push(i);for(let[c]of o.runs)if(c<a.minLo)a.minLo=c}),e.forEach((o,i)=>{let a=s(n[t.length+i]);a.nextIdx.push(i);for(let[c]of o.runs)if(c<a.minLo)a.minLo=c}),[...r.values()].sort((o,i)=>o.minLo-i.minLo)}function Yc(t,e,n){let r=[],s=e.map(()=>null),o=n;for(let i of Kc(t,e)){let a=i.prevIdx.map((f)=>t[f]),c=i.nextIdx.map((f)=>e[f]);if(a.length===1&&c.length===1&&a[0].bodyHash===c[0].bodyHash){let f=c[0];s[i.nextIdx[0]]={seq:a[0].seq,runs:f.runs,bodyHash:f.bodyHash,ins:f.ins,del:f.del};continue}if(c.length===0){for(let f of a)r.push({seq:o++,kind:"reverted",span:$n(f.runs),stats:{insertions:0,deletions:0},diff:null,supersedes:[f.seq],siblings:1});continue}let l=a.map((f)=>f.seq),u=a.reduce((f,h)=>f+h.ins+h.del,0);for(let f of i.nextIdx){let h=e[f],d={seq:o++,kind:a.length===0?"created":zc(h.ins,h.del,u),span:h.span,stats:{insertions:h.ins,deletions:h.del},diff:Xc(h),supersedes:[...l],siblings:c.length};r.push(d),s[f]={seq:d.seq,runs:h.runs,bodyHash:h.bodyHash,ins:h.ins,del:h.del}}}return{entries:r,nextLive:s.filter((i)=>i!==null)}}function Vc(t,e){let n=Array(t.length).fill(!1),r=Array(e.length).fill(null);for(let a=0;a<e.length;a++){let c=t.findIndex((l,u)=>!n[u]&&l.bodyHash===e[a].bodyHash);if(c!==-1)n[c]=!0,r[a]=t[c].seq}for(let a=0;a<e.length;a++){if(r[a]!==null)continue;let c=n.findIndex((l)=>!l);if(c!==-1)n[c]=!0,r[a]=t[c].seq}let s=t[t.length-1].seq,o=e.map((a,c)=>({seq:r[c]??s,runs:a.runs,bodyHash:a.bodyHash,ins:a.ins,del:a.del})),i=t.filter((a,c)=>!n[c]).map((a)=>a.seq);return{carried:o,retired:i}}function $e(){return{entries:[],epoch:`${Date.now().toString(36)}-${Oc(4).toString("hex")}`,nextSeq:1,prunedBefore:0,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class Cn extends Nc{store;constructor(t){super();this.store=t}get journalStore(){return this.store}observe(t){try{this.doObserve(t)}catch(e){T("Journal observation skipped: classifier threw",e)}}doObserve(t){let e=[];if(this.store.lastHeadOid===null){if(t.operationInProgress===null)this.seed(t,e)}else if(this.handleOperations(t,e));else if(t.headOid!==this.store.lastHeadOid)this.rebaseline(t,e);else this.classify(t,e);if(e.length>0)this.store.entries.push(...e),this.emit("append",e),this.pruneStore()}pruneStore(){let t=new Set;for(let e of this.store.live.values())for(let n of e)t.add(n.seq);this.pruneBodies(t),this.pruneEntries(t)}pruneBodies(t){let e=0;for(let n of this.store.entries)if(n.type==="hunk"&&n.diff!==null)e+=Se(n.diff.lines);for(let n of this.store.entries){if(e<=Hc)return;if(n.type!=="hunk"||n.diff===null||t.has(n.seq))continue;e-=Se(n.diff.lines),n.diff=null}}pruneEntries(t){let e=this.store.entries,n=-Bc;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}=Vc(o,i.hunks);n.push(...c),r.set(s,a)}return{resolves:n,newLive:r}}classify(t,e){let{files:n,deferred:r}=this.parseObservation(t);this.handleRenames(t,n,e),this.handleDisappearances(t,n,r,e);for(let[s,{hunks:o,renamedFrom:i,hunkless:a}]of n){let c=this.store.live.get(s)??[];if(a&&i!==null&&c.length>0)continue;this.classifyPath(s,c,o,t,!1,e)}this.store.lastBranch=t.status.branch.current,this.store.lastStashCount=t.stashCount}handleRenames(t,e,n){for(let[r,s]of e){let o=s.renamedFrom;if(o===null||o===r)continue;if(!this.store.live.has(o)||e.has(o))continue;let i=(this.store.live.get(r)??[]).map((a)=>a.seq);this.store.live.set(r,this.store.live.get(o)),this.store.live.delete(o),n.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor(t,r),path:r,status:"renamed",kind:"renamed",span:{start:0,count:0},stats:{insertions:0,deletions:0},diff:null,supersedes:i,siblings:1,seeded:!1})}}handleDisappearances(t,e,n,r){let s=[...this.store.live.keys()].filter((o)=>!e.has(o)&&!n.has(o));if(s.length===0)return;if(t.stashCount>this.store.lastStashCount){let o=s.flatMap((i)=>this.store.live.get(i).map((a)=>a.seq));r.push(this.boundary("stash","stash",o,t.at));for(let i of s)this.store.live.delete(i);return}for(let o of s){let i=this.store.live.get(o);r.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor(t,o),path:o,status:this.statusOf(t,o),kind:"reverted",span:$n(i.flatMap((a)=>a.runs)),stats:{insertions:0,deletions:0},diff:null,supersedes:i.map((a)=>a.seq),siblings:1,seeded:!1}),this.store.live.delete(o)}}classifyPath(t,e,n,r,s,o){let{entries:i,nextLive:a}=Yc(e,n,this.store.nextSeq);this.store.nextSeq+=i.length;let c=this.tsFor(r,t),l=this.statusOf(r,t);for(let u of i){let f={type:"hunk",seq:u.seq,ts:c,path:t,status:l,kind:u.kind==="created"&&l==="renamed"?"renamed":u.kind,span:u.span,stats:u.stats,diff:u.diff,supersedes:u.supersedes,siblings:u.siblings,seeded:s};o.push(f)}if(a.length>0)this.store.live.set(t,a);else this.store.live.delete(t)}parseObservation(t){let e=new Map;for(let[r,s]of Te(t.headDiff))e.set(Fn(r),qc(s));let n=new Set;for(let r of t.status.files)if(r.status==="untracked"&&!e.has(r.path))n.add(r.path);return{files:e,deferred:n}}boundary(t,e,n,r){return{type:"boundary",seq:this.store.nextSeq++,ts:r,kind:t,label:Fn(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 Nn{workingTree;remote;journal;repoPath;constructor(t,e){this.repoPath=t;let n=Mr(t);this.workingTree=new Fe(t,n),this.remote=new Mn(t,n,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new Cn(e??$e()),this.workingTree.on("journal-observation",(r)=>this.journal.observe(r))}dispose(){this.workingTree.dispose(),Fr(this.repoPath)}}function Zc(t){return Qc("sha256").update(t).digest("hex").slice(0,12)}var tl=32,el=600000,nl=4;class io{cap;stores=new Map;constructor(t=tl){this.cap=t}acquire(t){let e=this.stores.get(t);if(e)this.stores.delete(t);else e=$e();return this.stores.set(t,e),e}prune(t){if(this.stores.size<=this.cap)return;for(let e of this.stores.keys()){if(this.stores.size<=this.cap)return;if(t(e))continue;this.stores.delete(e)}}has(t){return this.stores.has(t)}get size(){return this.stores.size}}class Ce extends Error{reason;requested;constructor(t,e){super(t==="not-absolute"?`Repo path must be absolute: ${e}`:`Not a git repository: ${e}`);this.reason=t,this.requested=e,this.name="RepoOpenRefused"}}class On{events;byId=new Map;byPath=new Map;lingering=new Map;journalStores=new io;lingerMs;lingerCap;constructor(t={},e={}){this.events=t,this.lingerMs=e.lingerMs??el,this.lingerCap=e.lingerCap??nl}async openRepo(t){let e=await Ie(t,{mustExist:!1});if(!e.ok)throw new Ce(e.reason,e.requested);let n=e.root,r=this.byPath.get(n);if(r)return r.refCount++,{handle:r,created:!1};let s=this.takeLingering(n);if(s)return s.refCount=1,this.byId.set(s.id,s),this.byPath.set(n,s),this.journalStores.acquire(s.id),s.manager.workingTree.scheduleRefresh(),this.events.onOpened?.(s),{handle:s,created:!1};let o=Zc(n),i=new Nn(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 Ln(t){t.manager.workingTree.refresh().catch((e)=>{T("First refresh threw",e,{repo:t.path})})}async function Ne(t,e){let n=await t.openRepo(e);if(n.created)Ln(n.handle);return n}var co=25000;function Ct(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=pt(o),l=nt(c);if(l!==c)return{lines:rt(l)};return{lines:o}}catch(n){return Te(`reading untracked file ${e}`,t,n),{lines:[]}}}var de="refs/remotes/";async function Bs(t){let e=R(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(de))continue;let f=u.slice(de.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){b(`git log for base-branch discovery failed in ${t}: ${Ie(s)}`)}return r}var Ps=["upstream","origin"];function Fs(t){let e=Ps.indexOf(t);return e===-1?Ps.length:e}async function xn(t){let e=R(t),n=(await e.raw(["remote"])).split(`
|
|
28
|
+
`).filter(Boolean),r=new Map,s=await e.raw(["for-each-ref","--format=%(refname) %(objectname) %(symref)",de]);for(let i of s.split(`
|
|
29
|
+
`)){let[a,c,l=""]=i.split(" ");if(a)r.set(a,{commit:c,symref:l})}let o=[];for(let i of n){let a=`${de}${i}/`,c=r.get(`${a}HEAD`)?.symref,l=c&&r.has(c)?c:[`${a}main`,`${a}master`].find((u)=>r.has(u));if(l)o.push({remote:i,ref:l,commit:r.get(l).commit})}return o}async function kn(t,e,n="HEAD"){let r=await R(t).raw(["rev-list","--count",`${e}..${n}`]);return parseInt(r.trim(),10)}function _n(t){let e=[...t].sort((n,r)=>n.ahead-r.ahead||Fs(n.remote)-Fs(r.remote)||(n.remote<r.remote?-1:1))[0];return e?{branch:e.ref.slice(de.length),ahead:e.ahead}:null}async function wc(t){try{let e=await xn(t),n=await Promise.all(e.map(async({remote:r,ref:s})=>({remote:r,ref:s,ahead:await kn(t,s)})));return _n(n)}catch(e){return b(`default base-branch discovery failed in ${t}: ${Ie(e)}`),null}}async function An(t){return(await wc(t))?.branch??null}async function Dn(t){return Ft(t)??await An(t)}async function st(t,e){let n=R(t);try{return await n.raw(["cat-file","-e","--end-of-options",`${e}^{commit}`]),!0}catch{return!1}}function yc(t){let e=t.indexOf(`
|
|
30
|
+
`);return mt(e===-1?t:t.slice(0,e))}function Ws(t,e,n){let r=le(t),s=new Map;for(let a of yn(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=yc(a);if(c===null)continue;let l=rt(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 bc(t,e,n){let r=R(t);return Gs(r,e,r.status(),n)}async function Gs(t,e,n,r="HEAD",s){let o=await In(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(Ct(i,["--numstat","-z"])),t.raw(Ct(i,["--name-status","-z"])),t.raw(Ct(i,[`-U${wt}`])).then(nt),n,t.log({from:o,to:r})]),h=Ws(a,c,l),d=0,p=0;for(let w of h)d+=w.additions,p+=w.deletions;let g=u.length,E=f.all.map((w)=>({hash:w.hash,shortHash:w.hash.slice(0,7),message:w.message.split(`
|
|
31
|
+
`)[0],author:w.author_name,date:new Date(w.date),refs:w.refs||""}));return{baseBranch:e,stats:{filesChanged:h.length,additions:d,deletions:p},files:h,commits:E,uncommittedCount:g}}async function Us(t,e,n="HEAD"){let r=R(t),s=await In(r,e,n),o=await r.raw(["rev-list","--count","--end-of-options",`${s}..${n}`]);return Number.parseInt(o.trim(),10)}async function js(t,e,n="HEAD"){return In(R(t),e,n)}async function In(t,e,n){let r=(await t.raw(["merge-base","--end-of-options",e,n])).trim();if(!r)throw new De(e);return r}function Ct(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 Ec(t,e,n){let r=R(t),s=Ct(e,["--name-status","-z","-M","--diff-filter=R"]),o;try{o=await r.raw(s)}catch(i){return b(`rename lookup for ${n} failed in ${t}: ${Ie(i)}`),null}return yn(o).find((i)=>i.path===n)?.oldPath??null}async function Tn(t,e,n,r={}){let s=R(t),o=r.context??wt;try{let i=await Ec(t,e,n),a=i===null?[n]:[i,n],c=Ct(e,["-M",`-U${o}`]),l=nt(await s.raw([...c,"--",...a]));return{lines:rt(l)}}catch(i){return Te(`git ${Ct(e,[]).join(" ")} -- ${n}`,t,i),{lines:[]}}}async function qs(t,e){let n=R(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${wt}`]).then(nt)]);return Ws(s,o,i)}async function Xs(t,e){let n=R(t);try{let r=nt(await n.raw(["show","--format=",`-U${wt}`,"--end-of-options",e]));return{lines:rt(r)}}catch(r){return Te(`git show ${e}`,t,r),{lines:[]}}}function Sc(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 Cs(t){return t!==""&&t!==" "&&t!=="?"&&t!=="!"}function Rc(t,e,n){let r=new Set,s=new Set;for(let o of e.files){if(Cs(o.index)){if(r.add(o.path),o.from)r.add(o.from)}if(n==="worktree"&&Cs(o.working_dir))s.add(o.path)}return t.map((o)=>{let i=vc(r.has(o.path),s.has(o.path));return i===null?o:{...o,uncommitted:i}})}function vc(t,e){if(t&&e)return"both";if(t)return"staged";if(e)return"unstaged";return null}async function xc(t,e){let n=e.files.filter((o)=>o.working_dir==="?").map((o)=>o.path),r=await Dt(t,n),s=[];for(let o of n){if(r.has(o))continue;let i=await yt(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 zs(t,e,n=Ms,r){let s=Sc(n);if(s===null&&!n.untracked)return bc(t,e,r);if(r!==void 0)throw Error("Uncommitted work can only be compared against HEAD, not a named head");let o=R(t),i=o.status(),[a,c,l]=await Promise.all([Gs(o,e,i,"HEAD",s??void 0),i,n.untracked?i.then((h)=>xc(t,h)):[]]),f=[...s===null?a.files:Rc(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 Ks from"node:fs";import*as Ys from"node:path";function Pe(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 Js(t){let e=[],n="",r=null,s=()=>{if(r&&n)e.push({file:n,key:`${n}\x00${Pe(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=mt(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 Mn{repoPath;stamps=new Map;constructor(t){this.repoPath=t}stamp(t){if(t)this.stampHunks(Js(t))}stampTree(t){let e=t.flatMap((r)=>Js(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 Ks.statSync(Ys.join(this.repoPath,t)).mtimeMs}catch{return Date.now()}}}import*as Y from"node:fs";import*as O from"node:path";async function kc(t){let e=Fn(t);if(!e)return null;try{let n=R(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 N("rev-parse failed",n,{dir:e}),null}}async function Fe(t,{mustExist:e}){let n=z(t);if(!O.isAbsolute(n))return{ok:!1,reason:"not-absolute",requested:n};if(e&&!Vs(n))return{ok:!1,reason:"not-a-repo",requested:n};let r=await kc(n);if(r)return{ok:!0,root:r};let s=Oc(await _c(n));return s?{ok:!0,root:s.path}:{ok:!1,reason:"not-a-repo",requested:n}}function Vs(t){try{return Y.statSync(t).isDirectory()}catch{return!1}}async function _c(t){let e=Fn(t);if(!e)return[];try{let n=R(e);return no(await n.raw(["worktree","list","--porcelain"]))}catch(n){return N("worktree list failed",n,{dir:e}),[]}}async function Pn(t){let e=Fn(t);if(!e)return[];try{let r=await R(e).raw(["worktree","list","--porcelain"]),s=no(r),o=await Nc(e,s);return s.map((i)=>({...i,lastActivity:i.isBare?null:Ac(to(i.path)),aheadOfBase:o.get(i.path)??null}))}catch(n){return N("worktree list failed",n,{dir:e}),[]}}function Ac(t){return Number.isFinite(t)?t:null}class Qs{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 Dc=8,Zs=new Qs(Dc),Ic=512,Nt=new Map,Tc=/^0+$/;function Mc(t,e){if(Nt.delete(t),Nt.set(t,e),Nt.size>Ic)Nt.delete(Nt.keys().next().value)}function Pc(t,e){return[t,...e.map((n)=>`${n.ref}=${n.commit}`).sort()].join(`
|
|
32
|
+
`)}async function Fc(t,e,n){let r=await Promise.all(n.map(async({remote:s,ref:o,commit:i})=>({remote:s,ref:o,ahead:await Zs.run(()=>kn(t,i,e))})));return _n(r)?.ahead??null}async function Cc(t,e){if(t.head===null||Tc.test(t.head))return null;let n=Pc(t.head,e),r=Nt.get(t.path);if(r!==void 0&&r.key===n)return r.ahead;try{let s=await Fc(t.path,t.head,e);return Mc(t.path,{key:n,ahead:s}),s}catch(s){return b("default base-branch count failed",s,{worktree:t.path}),null}}async function $c(t,e){try{let n=R(t),r=await Zs.run(()=>n.raw(["rev-list","--count","--end-of-options",`${e}..HEAD`]));return parseInt(r.trim(),10)}catch{return null}}async function Nc(t,e){let n;try{n=await xn(t)}catch(s){b("default base-branch discovery failed",s,{repo:t}),n=null}let r=await Promise.all(e.filter((s)=>!s.isBare&&Vs(s.path)).map(async(s)=>{let o=Ft(s.path),i=null;if(o!==void 0)i=await $c(s.path,o);else if(n!==null)i=await Cc(s,n);return i===null?null:[s.path,i]}));return new Map(r.filter((s)=>s!==null))}function Oc(t){let e=null,n=-1/0;for(let r of t){if(r.isBare)continue;let s=to(r.path);if(s>n)n=s,e=r}return e}function to(t){let e=eo(t),n=e?[O.join(e,"index"),O.join(e,"HEAD")]:[t],r=-1/0;for(let s of n)try{let o=Y.statSync(s).mtimeMs;if(o>r)r=o}catch{}return r}function eo(t){let e=O.join(t,".git");try{if(Y.statSync(e).isDirectory())return e;let n=Y.readFileSync(e,"utf8").match(/^gitdir:\s*(.+)$/m);if(!n)return null;let r=n[1].trim();return O.isAbsolute(r)?r:O.resolve(t,r)}catch{return null}}function Ot(t){let e=eo(t);if(e===null)return null;let n=e;try{let r=Y.readFileSync(O.join(e,"commondir"),"utf8").trim();if(r)n=O.isAbsolute(r)?r:O.resolve(e,r)}catch{}return{gitDir:e,commonDir:n}}function no(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 Fn(t){try{if(Y.statSync(t).isDirectory())return t;return O.dirname(t)}catch{let e=O.dirname(t);return e!==t&&Y.existsSync(e)?e:null}}var zc=pa(po(),1);function mo(t){return mt(t)}function Ne(t){let e=new Map,n=null;for(let s of t.lines){if(s.type==="header"&&s.content.startsWith("diff --git")){let o=mo(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 Oe="diffstalker-journal: oversize untracked snapshot omitted";var Kc=262144,Yc=new Set(["EACCES","EPERM","ENOENT","ENOTDIR"]),Vc=new Set(["index","HEAD","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","rebase-merge","rebase-apply"]),Qc=100,Zc=1000,tl=4;function el(t,e,n){return Math.max(Qc,wo(t,e,n))}function wo(t,e,n){return e+Math.max(Zc,tl*n)-t}function go(t){return t===".git"||t.endsWith("/.git")}function nl(t){let e=t?.code;return typeof e==="string"&&Yc.has(e)}function rl(){return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1}}class Le extends Jc{repoPath;queue;hunkTimes;watchers=[];treeWatcher=null;watchGeneration=0;ignoreRules=null;reloadingRules=!1;reloadRulesAgain=!1;disposed=!1;viewed=!1;_stale=!0;changeTimer=null;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 Mn(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)=>{M("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=Ot(this.repoPath);if(t===null)return;let e=++this.watchGeneration;this.watchGitDirs(t),this.watchWorkingTree(t,e).catch((n)=>{M("Starting the working tree watcher threw",n,{repo:this.repoPath})})}reviveWatchers(){if(this.disposed||!this.watchers.some((t)=>t.rootGone))return;N("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(Vc.has(s))this.onRepoChange()},r=(s)=>this.onWatchError("Git dir watcher error",s);if(this.watchers.push(new se(t.commonDir,{skipDir:(s)=>!(s==="info"||s==="refs"||s.startsWith("refs/")),onChange:(s)=>{if(e(s),t.gitDir===t.commonDir)n(s)},onError:r})),t.gitDir!==t.commonDir)this.watchers.push(new se(t.gitDir,{skipDir:()=>!0,onChange:n,onError:r}));for(let s of this.watchers)s.start().catch((o)=>{M("Starting a git dir watcher threw",o,{repo:this.repoPath})})}async watchWorkingTree(t,e){let n=await gn(this.repoPath,t.commonDir);if(this.disposed||e!==this.watchGeneration)return;this.ignoreRules=n;let r=new se(this.repoPath,{skipDir:(s)=>go(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(go(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=Ot(this.repoPath);if(t===null||this.treeWatcher===null)return;this.reloadingRules=!0;try{do{if(this.reloadRulesAgain=!1,this.ignoreRules=await gn(this.repoPath,t.commonDir),this.disposed)return;await this.treeWatcher.resync()}while(this.reloadRulesAgain&&!this.disposed)}catch(e){M("Reloading the ignore rules threw",e,{repo:this.repoPath})}finally{this.reloadingRules=!1}}onWatchError(t,e){if(nl(e)){N(t,e,{repo:this.repoPath});return}b(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,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(el(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=wo(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,bt.statSync(me.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)b(`${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(!bt.existsSync(this.repoPath)){this.notARepo(rl(),"Repository directory no longer exists");return}b(t,e,{repo:this.repoPath}),this.updateState({isLoading:!1,error:e instanceof Error?e.message:"Unknown error"})}async doStatusRefresh(){try{let t=await En(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 Me(this.repoPath).catch((n)=>(N("HEAD oid unreadable; journal observation skipped",n,{repo:this.repoPath}),null));try{let n=await En(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=(_)=>Os(this.repoPath,_).catch((D)=>(b(`Whole-tree diff${_?" --cached":""} failed`,D,{repo:this.repoPath}),i??=D instanceof Error?D.message:String(D),null)),c=await a(!0),l=a(!1),f=c!==null&&c.lines.length===0&&n.files.every((_)=>!_.staged&&_.status!=="conflicted")?async()=>{let _=await l;if(_===null)throw Error("the unstaged diff failed");return _}:(_)=>Hs(this.repoPath,_),[h,d]=await Promise.all([l,this.gatherJournalInputs(n,e,t,r,f)]),p=h??{lines:[]},g=c??{lines:[]},E={unstaged:Ae(pt(p.lines)),staged:Ae(pt(g.lines))};this.hunkTimes.stampTree([p,g]);let w=this.statMtimes(n);if(this._wholeTreeDiffs={unstaged:p,staged:g},this.updateState({status:n,hunkCounts:E,stashList:s,operationInProgress:o,mtimes:w,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([Mt(this.repoPath),Sn(this.repoPath)]);return{operation:e,stashList:n,mtimes:this.statMtimes(t),index:this.indexIdentity()}}gitDirs;indexIdentity(){if(this.gitDirs===void 0)this.gitDirs=Ot(this.repoPath);if(this.gitDirs===null)return null;try{let t=bt.statSync(me.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=bt.statSync(me.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(Ne(o).keys()),a=[...o.lines];await this.appendUntrackedSections(t,i,a);let c=await Me(this.repoPath);if(e!==c)return null;let l=await this.snapshotJournalGuard(t);if(Le.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 N("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=bt.statSync(me.join(this.repoPath,s.path))}catch{continue}if(!o.isFile())continue;if(o.size>Kc){this.appendOversizeSection(s.path,o,n);continue}let i=await yt(this.repoPath,s.path);if(i.lines.length===0)continue;n.push(...i.lines)}}appendOversizeSection(t,e,n){let r=[`diff --git ${It("a/"+t)} ${It("b/"+t)}`,"new file mode 100644",`${Oe} size=${e.size} mtime=${Math.round(e.mtimeMs)}`];n.push(...r.map((s)=>({type:"header",content:s})))}failed(t,e,n){b(`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(()=>ns(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(()=>rs(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()=>fs(this.repoPath,t)),this.scheduleRefresh()}catch(e){await this.refresh(),this.failed("stage hunk",e)}}async unstageHunk(t){try{await this.queue.enqueueMutation(async()=>hs(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"?()=>as(this.repoPath,t.path):()=>is(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(()=>ss(this.repoPath)),await this.refresh()}catch(t){this.failed("stage all",t)}}async unstageAll(){try{await this.queue.enqueueMutation(()=>os(this.repoPath)),await this.refresh()}catch(t){this.failed("unstage all",t)}}async commit(t,e=!1){try{await this.queue.enqueue(()=>cs(this.repoPath,t,e)),await this.refresh()}catch(n){this.failed("commit",n)}}async loadStashList(){try{let t=await this.queue.enqueue(()=>Sn(this.repoPath));this.updateState({stashList:t})}catch(t){b("Failed to load the stash list",t,{repo:this.repoPath})}}}import{EventEmitter as sl}from"node:events";class On extends sl{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){b(`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",()=>ds(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>ps(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>ms(this.repoPath))}async stash(t){if(this._remoteState.inProgress)return null;let e=await this.runRemoteOperation("stash",()=>ys(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",()=>bs(this.repoPath,t));return await this.callbacks.loadStashList(),e}async switchBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>Ss(this.repoPath,t))}async createBranch(t){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>Rs(this.repoPath,t))}async softReset(t=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>vs(this.repoPath,t))}async cherryPick(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>xs(this.repoPath,t))}async revertCommit(t){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>ks(this.repoPath,t))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>_s(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>As(this.repoPath))}}import{EventEmitter as ol}from"node:events";import{randomBytes as il}from"node:crypto";var al=262144,cl=500,ll=16777216,Eo=Number.MAX_SAFE_INTEGER,ul=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function fl(t){let e=ul.exec(t);if(!e)return null;return{oldStart:parseInt(e[1],10),oldCount:e[2]!==void 0?parseInt(e[2],10):1}}function hl(t,e){let n=fl(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=dl(o,r),r++;else if(a==="+")o=o??{hasDel:!1,delStart:0,delEnd:0,anchor:r-1};else yo(s,o),o=null,r++}return yo(s,o),s}function dl(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 yo(t,e){if(!e)return;t.push(e.hasDel?[2*e.delStart,2*e.delEnd]:[2*e.anchor,2*e.anchor+2])}function Hn(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>=Eo)return{start:0,count:0};let r=Math.ceil(e/2),s=Math.floor(n/2);return{start:r,count:s-r+1}}function pl(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(Oe));return{hunks:[{runs:[[0,Eo]],bodyHash:Pe([pt(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=hl(a,i.content),l=[],u=0,f=0;for(let d of a){let p=d.content[0];if(p==="\\")continue;if(p==="+")u++,l.push(d.content);else if(p==="-")f++,l.push(d.content)}let h=[...e,i,...a];return{runs:c,bodyHash:Pe(l),ins:u,del:f,span:Hn(c),diff:{lines:h}}}),renamedFrom:n,hunkless:!1}}function Ln(t){return Buffer.from(t,"utf8").toString("utf8")}function ml(t){if(t.oversize===!0)return null;if(_e(t.diff.lines)>al)return null;return{lines:t.diff.lines.map(gl)}}function gl(t){let e={type:t.type,content:Ln(t.content)};if(t.oldLineNum!==void 0)e.oldLineNum=t.oldLineNum;if(t.newLineNum!==void 0)e.newLineNum=t.newLineNum;return e}function wl(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 bo(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 yl(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=bo(t,0),i=bo(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 bl(t,e){let n=yl(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 El(t,e,n){let r=[],s=e.map(()=>null),o=n;for(let i of bl(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:Hn(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":wl(h.ins,h.del,u),span:h.span,stats:{insertions:h.ins,deletions:h.del},diff:ml(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 Sl(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 He(){return{entries:[],epoch:`${Date.now().toString(36)}-${il(4).toString("hex")}`,nextSeq:1,prunedBefore:0,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class Bn extends ol{store;constructor(t){super();this.store=t}get journalStore(){return this.store}observe(t){try{this.doObserve(t)}catch(e){M("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+=_e(n.diff.lines);for(let n of this.store.entries){if(e<=ll)return;if(n.type!=="hunk"||n.diff===null||t.has(n.seq))continue;e-=_e(n.diff.lines),n.diff=null}}pruneEntries(t){let e=this.store.entries,n=-cl;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}=Sl(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:Hn(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}=El(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 Ne(t.headDiff))e.set(Ln(r),pl(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:Ln(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 Wn{workingTree;remote;journal;repoPath;constructor(t,e){this.repoPath=t;let n=Or(t);this.workingTree=new Le(t,n),this.remote=new On(t,n,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new Bn(e??He()),this.workingTree.on("journal-observation",(r)=>this.journal.observe(r))}dispose(){this.workingTree.dispose(),Lr(this.repoPath)}}function vl(t){return Rl("sha256").update(t).digest("hex").slice(0,12)}var xl=32,kl=600000,_l=4;class So{cap;stores=new Map;constructor(t=xl){this.cap=t}acquire(t){let e=this.stores.get(t);if(e)this.stores.delete(t);else e=He();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 Be 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 Gn{events;byId=new Map;byPath=new Map;lingering=new Map;journalStores=new So;lingerMs;lingerCap;constructor(t={},e={}){this.events=t,this.lingerMs=e.lingerMs??kl,this.lingerCap=e.lingerCap??_l}async openRepo(t){let e=await Fe(t,{mustExist:!1});if(!e.ok)throw new Be(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=vl(n),i=new Wn(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 Al(t){t.manager.workingTree.refresh().catch((e)=>{M("First refresh threw",e,{repo:t.path})})}async function We(t,e){let n=await t.openRepo(e);if(n.created)Al(n.handle);return n}var vo=25000;function Lt(t,e,n){t.write(`event: ${e}
|
|
34
34
|
data: ${n}
|
|
35
35
|
|
|
36
|
-
`)}function
|
|
36
|
+
`)}function xo(t){t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"})}function Ro(t,e){Lt(t,"repo-missing",JSON.stringify({id:e}))}class Un{channels=new Map;subscribe(t,e,n,r){xo(r),this.join(t,e,n,r,{owned:!0})}attach(t,e,n,r){if(!e){Ro(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(lt(l));if(u===c.lastData)return;c.lastData=u;for(let f of a.keys())Lt(f,"state-change",u)},journalListener:(l)=>{let u=JSON.stringify({epoch:e.journal.journalStore.epoch,entries:l});for(let f of a.keys())Lt(f,"journal-append",u)},keepAlive:setInterval(()=>{for(let[l,{owned:u}]of a)if(u)l.write(`: ping
|
|
37
37
|
|
|
38
|
-
`)},
|
|
38
|
+
`)},vo),lastData:null};e.workingTree.on("state-change",c.listener),e.journal.on("append",c.journalListener),c.keepAlive.unref(),o=c,this.channels.set(t,o)}o.subscribers.set(r,s),n.on("close",()=>this.unsubscribe(t,r));let i=JSON.stringify(lt(e.workingTree.state));Lt(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),clearInterval(e.keepAlive);for(let[n,{owned:r}]of e.subscribers)if(r)n.end();else Ro(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 jn{subscribers=new Set;keepAlive=null;subscribe(t,e,n){if(xo(e),this.subscribers.add(e),!this.keepAlive)this.keepAlive=setInterval(()=>{for(let r of this.subscribers)r.write(`: ping
|
|
39
39
|
|
|
40
|
-
`)},
|
|
41
|
-
`,{mode:384}),G.renameSync(e,this.file)}catch(n){throw G.rmSync(e,{force:!0}),n}return this.current}}import*as
|
|
42
|
-
`)[0]?.trim();e(s?s:null)})})},writable(t){try{return ft.accessSync(t,ft.constants.W_OK),!0}catch{return!1}}};function Al(){let t=rt.dirname(Sl(new URL("../package.json",import.meta.url)));try{return ft.realpathSync(t)}catch{return t}}function bo(t=Al(),e=_l){let n=null;return{info(){return n??=Rl(t,e).catch((r)=>(E("Install detection failed",r,{dir:t}),yo)),n}}}import*as Eo from"node:fs";var Il=/^[A-Za-z0-9:_.@-]+\.service$/,Dl=/^user@\d+\.service$/,Pl=/^0::(.*)$/m;function Tl(t){let e=Pl.exec(t);if(e===null)return null;let n=e[1].split("/"),r=n.at(-1)??"";if(!Il.test(r))return null;let s=r.slice(0,-8);return n.some((o)=>Dl.test(o))?`systemctl --user restart ${s}`:`sudo systemctl restart ${s}`}function So(t=process.pid,e=process.env,n=()=>Eo.readFileSync("/proc/self/cgroup","utf-8")){if(e.SYSTEMD_EXEC_PID!==String(t))return null;try{return Tl(n())}catch(r){return E("Cannot read /proc/self/cgroup to name the systemd unit",r),null}}var Ml="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",Fl=21600000,$l=300000,Cl=5000;function zn(){try{let t=xo.readFileSync(new URL("../package.json",import.meta.url),"utf-8"),e=JSON.parse(t);return typeof e.version==="string"?e.version:null}catch(t){return E("Cannot read the daemon version from its package.json",t),null}}async function Nl(){let t=await fetch(Ml,{headers:{accept:"application/json"},signal:AbortSignal.timeout(Cl)});if(!t.ok)return null;let e=await t.json();return typeof e.latest==="string"?e.latest:null}function vo(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());if(!e)return null;return[Number(e[1]),Number(e[2]),Number(e[3])]}function Ol(t,e){if(t===null||e===null)return"unknown";let n=vo(t),r=vo(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 ko(t=Nl,e=zn(),n=bo(),r=So()){let s=null,o=null;function i(){if(s&&Date.now()<s.expiresAt)return Promise.resolve(s.value);if(o)return o;return o=t().catch((a)=>(L("Latest version lookup failed",a),null)).then((a)=>{let c=a===null?$l:Fl;return s={value:a,expiresAt:Date.now()+c},o=null,a}),o}return{async state(){let[a,c]=await Promise.all([i(),n.info()]);return{current:e,latest:a,status:Ol(e,a),install:c,restart:r}}}}import*as Ro from"node:os";function _o(t,e){t.get("/health",({res:n})=>{v(n,200,{ok:!0,ready:!0,home:Ro.homedir(),http:{port:e.httpPort()},symbols:{extensions:e.symbols?.extensions??[]}})})}function Ao(t,e){t.get("/version",async({res:n})=>{v(n,200,await e.version.state())})}import*as Oo from"node:fs";import*as Ot from"node:fs";import*as C from"node:path";function Lt(t,e){let n=t.getRepo(e);if(!n)throw new m(404,`Unknown repo id: ${e}`);return n}function R(t,e){let n=Lt(t,e),r=n.manager.workingTree.unavailable;if(r!==null)throw new m(410,r);return n}function q(t,e,n){if(typeof t!=="object"||t===null)throw new m(400,`Expected a JSON body with "${e}"`);let r=t[e];if(typeof r!=="string"||!n?.allowEmpty&&r.length===0)throw new m(400,`Missing "${e}" (string) in body`);return r}function Do(t,e){if(t.length===0)throw new m(400,`Invalid "${e}" (expected a ref)`);if(t.startsWith("-"))throw new m(400,`Invalid "${e}" (must not start with "-"): ${t}`);return t}function yt(t,e){return Do(q(t,e),e)}function Yn(t,e){let n=t.get(e);return n===null?null:Do(n,e)}function Po(t,e){if(typeof t!=="object"||t===null)throw new m(400,`Expected a JSON body with "${e}"`);let n=t[e];if(!Array.isArray(n)||n.some((r)=>typeof r!=="string"))throw new m(400,`Missing "${e}" (array of strings) in body`);return n}function To(t,e){if(typeof t!=="object"||t===null)return;let n=t[e];if(n===void 0)return;if(typeof n!=="string"||n.length===0)throw new m(400,`Invalid "${e}" (expected a non-empty string)`);return n}function Vn(t,e,n){if(typeof t!=="object"||t===null)return n.fallback;let r=t[e];if(r===void 0)return n.fallback;if(typeof r!=="number"||!Number.isInteger(r)||r<n.min)throw new m(400,`Invalid "${e}" (expected an integer >= ${n.min})`);return r}function Mo(t,e){if(typeof t!=="object"||t===null)return!1;let n=t[e];if(n===void 0)return!1;if(typeof n!=="boolean")throw new m(400,`Invalid "${e}" (expected a boolean)`);return n}function W(t,e,n){let r=t.get(e);if(r===null){if(n===void 0)throw new m(400,`Missing "${e}" query parameter (expected true or false)`);return n}if(r==="true")return!0;if(r==="false")return!1;throw new m(400,`Invalid "${e}" (expected true or false): ${r}`)}function Q(t){let e=t.get("path");if(!e)throw new m(400,'Missing "path" query parameter');return e}function he(t,e){let n=W(t,"whole",!1);if(n&&!e)throw new m(400,"whole=true requires a path (one file at a time)");return n?vs:void 0}function Fo(t,e,n,r){let s=t.get(e);if(s===null)return n;let o=Number(s);if(!Number.isInteger(o)||o<1)throw new m(400,`Invalid "${e}" (expected a positive integer): ${s}`);if(r!==void 0&&o>r)throw new m(400,`Invalid "${e}" (must be <= ${r}): ${s}`);return o}async function st(t){if(!t.state.status)await t.refresh();let e=t.state.status;if(!e)throw new m(500,"Repository status unavailable");return e}function Io(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 Bt(t,e,n){let r=await st(t),s=Io(r,e,n);if(!s)await t.refresh(),r=await st(t),s=Io(r,e,n);if(!s)throw new m(404,`File not in status: ${e}`);return s}function Kn(t,e){return t===e||t.startsWith(e+C.sep)}function Qn(t){return t.replace(/[. ]+$/,"").toLowerCase()===".git"}function bt(t,e){if(e.length===0)throw new m(400,"Empty path");if(e.includes("\x00"))throw new m(400,"Path contains a NUL byte");let n=C.resolve(t),r=C.relative(n,C.resolve(n,e));if(r==="")throw new m(400,`Path resolves to the repository root: ${e}`);if(C.isAbsolute(r)||r===".."||r.startsWith(`..${C.sep}`))throw new m(400,`Path escapes repository root: ${e}`);if(r.startsWith("-"))throw new m(400,`Path must not start with "-": ${e}`);if(r.startsWith(":"))throw new m(400,`Path must not start with ":": ${e}`);if(r.split(C.sep).some(Qn))throw new m(400,`Path addresses the git directory: ${e}`);return r}async function $o(t){try{return await Ot.promises.realpath(t)}catch{return null}}var Jn=new WeakMap;async function Ll(t){let e=Jn.get(t);if(!e)e=(async()=>{let n=await x(t.path).raw(["rev-parse","--absolute-git-dir"]);return await Ot.promises.realpath(n.trim())})(),Jn.set(t,e),e.catch(()=>Jn.delete(t));try{return await e}catch(n){throw new m(500,"Cannot resolve the git directory for this repository",{cause:n})}}async function Et(t,e){let n=await Ot.promises.realpath(C.resolve(t.path)),r=await $o(C.join(t.path,e));if(r===null)return;if(!Kn(r,n))throw new m(400,`Path escapes repository root: ${e}`);if(Kn(r,await Ll(t)))throw new m(400,`Path addresses the git directory: ${e}`)}async function Co(t,e){let n=await Ot.promises.realpath(C.resolve(t)),r=[];for(let s of e){let o=await $o(C.join(t,s.path));if(o===null||Kn(o,n))r.push(s)}return r}function Le(t){return t?.code??null}async function Zn(t){let e;try{e=await Ot.promises.stat(t)}catch(n){let r=Le(n);if(r==="ENOENT"||r==="ENOTDIR")return null;throw n}if(e.isDirectory())return"a directory";if(e.isFile())return"a file";if(e.isFIFO())return"a FIFO";if(e.isSocket())return"a socket";return"a device"}function Bl(t){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test(t)?409:500}function No(t,e){return new m(t,e)}async function ot(t,e,n){t.clearError(),await n();let r=t.state.error;if(r)throw No(Bl(r),r);await t.refresh(),v(e,200,{state:at(t.state)})}var Hl=/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged|no tracking information|no upstream|no configured push destination/i;function Wl(t){return Hl.test(t)?409:500}async function j(t,e,n){let r=t.manager.remote,s=()=>new m(409,`A ${r.remoteState.operation??"remote"} operation is already in progress`);if(r.remoteState.inProgress)throw s();let o=await n();if(o===null)throw s();let i=t.manager.workingTree;if(await i.refresh(),o.error)throw No(Wl(o.error),o.error);v(e,200,{state:at(i.state),result:o.lastResult})}function jl(t){if(t.reason==="not-a-repo"&&!Oo.existsSync(t.requested))return new m(404,`No such directory: ${t.requested}`,{cause:t});return new m(400,t.message,{cause:t})}function Lo(t,e){let{registry:n}=e;t.get("/repos",({res:r})=>{let s=n.listRepos().map((o)=>({id:o.id,path:o.path,branch:o.manager.workingTree.state.status?.branch.current??null}));v(r,200,s)}),t.post("/repos",async({body:r,res:s})=>{let o=q(r,"path"),i;try{i=await Ne(n,o)}catch(a){if(a instanceof Ce)throw jl(a);throw a}v(s,i.created?201:200,{id:i.handle.id,path:i.handle.path})}),t.get("/resolve",async({query:r,res:s})=>{let o=Q(r),i=await Ie(o,{mustExist:!0});if(!i.ok&&i.reason==="not-absolute")throw new m(400,`Repo path must be absolute: ${i.requested}`);v(s,200,{openable:i.ok,root:i.ok?i.root:null})}),t.get("/repos/:id/worktrees",async({params:r,res:s})=>{let o=R(n,r.id);v(s,200,await _n(o.path))}),t.get("/worktrees",async({query:r,res:s})=>{v(s,200,await _n(Q(r)))}),t.delete("/repos/:id",({params:r,res:s})=>{Lt(n,r.id),n.closeRepo(r.id),v(s,200,{})})}function Bo(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 Ho(t){return t.trim()}async function Ul(t){let e=(r)=>r.filter((s)=>s.staged).length,n=e((await st(t)).files);if(n===0)await t.refresh(),n=e((await st(t)).files);return n}function Wo(t,e){let{registry:n,sse:r}=e;if(t.get("/repos/:id/status",async({params:s,res:o})=>{let i=Lt(n,s.id);await st(i.manager.workingTree),v(o,200,at(i.manager.workingTree.state))}),t.get("/repos/:id/diff",async({params:s,query:o,res:i})=>{let a=R(n,s.id),c=a.manager.workingTree,l=o.get("path")??void 0,u=W(o,"staged",!1),f=he(o,l);if(!l){let S=await c.wholeTreeDiffs();if(!S){let y=c.unavailable;throw new m(y?410:500,y??"Repository diff unavailable")}v(i,200,u?S.staged:S.unstaged);return}let d=(await st(c)).files.some((S)=>S.path===l&&S.status==="untracked");if(d&&u)throw new m(400,`staged=true is meaningless for untracked file: ${l} (untracked files have no staged diff)`);let p=f!==void 0&&!d,g=d?await gt(a.path,l):await le(a.path,l,u,{context:f});if(!p)c.stampDiff(g);v(i,200,g)}),t.post("/repos/:id/stage",async({params:s,body:o,res:i})=>{let a=R(n,s.id),c=q(o,"path"),l=a.manager.workingTree,u=await Bt(l,c,!1);await ot(l,i,()=>l.stage(u))}),t.post("/repos/:id/unstage",async({params:s,body:o,res:i})=>{let a=R(n,s.id),c=q(o,"path"),l=a.manager.workingTree,u=await Bt(l,c,!0);await ot(l,i,()=>l.unstage(u))}),t.get("/repos/:id/events",({params:s,req:o,res:i})=>{let a=Lt(n,s.id);r.subscribe(s.id,a.manager,o,i)}),e.apiMode==="full")Gl(t,e)}function Gl(t,e){let{registry:n}=e;t.post("/repos/:id/stage-all",async({params:r,res:s})=>{let i=R(n,r.id).manager.workingTree;await ot(i,s,()=>i.stageAll())}),t.post("/repos/:id/unstage-all",async({params:r,res:s})=>{let i=R(n,r.id).manager.workingTree;await ot(i,s,()=>i.unstageAll())}),t.post("/repos/:id/discard",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"path"),c=i.manager.workingTree,l=await Bt(c,a,!1);if(l.staged)throw new m(409,`Cannot discard a staged file: ${a} (unstage it first)`);await ot(c,o,()=>c.discard(l))}),t.post("/repos/:id/commit",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"message",{allowEmpty:!0}),c=Mo(s,"amend"),l=i.manager.workingTree,u=await Ul(l),f=Bo(a,u,c);if(!f.valid)throw new m(400,f.error??"Invalid commit");await ot(l,o,()=>l.commit(Ho(a),c))}),t.post("/repos/:id/stage-hunk",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"patch"),c=i.manager.workingTree;await ot(c,o,()=>c.stageHunk(a))}),t.post("/repos/:id/unstage-hunk",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"patch"),c=i.manager.workingTree;await ot(c,o,()=>c.unstageHunk(a))})}var ql=1000,Be="refs/heads/",jo="refs/remotes/";async function Go(t,e,n){let r=["for-each-ref","--format=%(objectname) %(refname) %(symref)",`--no-merged=${e}`];if(n!==void 0)r.push(`--contains=${n}`);r.push("refs/heads","refs/remotes");let s=await t.raw(r),o=[];for(let i of s.split(`
|
|
43
|
-
`)){if(!i)continue;let[a,c,l]=i.split(" ");if(l)continue;if(c.startsWith(
|
|
44
|
-
`).filter(Boolean).reverse()}async function
|
|
45
|
-
`),s=r.startsWith(
|
|
46
|
-
`).filter(Boolean)}function Kl(t,e,n){if(t.length===0)return null;let r=t.filter((c)=>c.local).map((c)=>c.name).sort(),s=t.filter((c)=>!c.local).map((c)=>c.name).sort(),o=[...r,...s],i=[...r.filter((c)=>n.has(c)),...s,...r.filter((c)=>!n.has(c))];return{name:e!==null&&r.includes(e)?e:i.find((c)=>!c.startsWith("-"))??i[0],refs:o}}function Jo(t,e,n,r){let s=[],o=-1;for(let i=0;i<t.length;i++){let a=t[i],c=a===n?.tip,l=Kl(e.get(a)??[],n?.branch??null,r)??(c?{name:n.name,refs:[]}:null);if(l===null)continue;s.push({...l,tip:a,commits:i-o,isHead:c}),o=i}return s}async function Yl(t,e,n,r,s,o){let i=qo(await Go(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 Uo(t,a);if(c.length>1){let u=[...new Set(i.filter((f)=>Xo(f,o)).map((f)=>f.tip))];if(u.length>0)c=await Uo(t,u)}if(c.length!==1)return{layers:[],forked:!0};let l=await zo(t,n,c[0]);return{layers:Jo(l,s,null,o),forked:!1}}function Vl(t,e){let n=[],r=!1;for(let s of[...t].reverse()){let o=e.has(s.tip);if(r&&!o&&!s.isHead){n[n.length-1].commits+=s.commits;continue}if(n.push({...s}),o)r=!0}return n.reverse()}async function Ko(t,e){let n=x(t),r=await Jl(n),s=(await n.raw(["merge-base","--end-of-options",e,r.tip])).trim();if(!s)return{trunk:e,layers:[],forkedAbove:!1};let[o,i]=await Promise.all([Go(n,e),zo(n,s,r.tip)]),a=Xl(o),c=zl(o),l=new Map,u=new Set;for(let d of qo(o,a)){let p=l.get(d.tip);if(p)p.push(d);else l.set(d.tip,[d]);if(Xo(d,c))u.add(d.tip)}let f=Jo(i,l,r,c);if(!f.some((d)=>d.isHead))f.push({name:r.name,refs:[],tip:r.tip,commits:0,isHead:!0});let h=await Yl(n,e,r.tip,a,l,c);return{trunk:e,layers:Vl([...f,...h.layers],u),forkedAbove:h.forked}}function tr(t){if(!/^[0-9a-f]{4,40}$/i.test(t))throw new m(400,`Invalid commit hash: ${t}`);return t}async function Yo(t,e){if(!await nt(t,e))throw new m(404,`Unknown commit: ${e}`)}async function er(t){try{return await t()}catch(e){if(e instanceof xe)throw new m(422,e.message,{cause:e});throw e}}async function Ql(t){let e=await vn(t);if(e&&await nt(t,e))return e;if(Pt(t)){let n=await Sn(t);if(n&&await nt(t,n))return n}throw new m(422,"No usable base branch")}async function He(t,e){let n=Yn(e,"base");if(n===null)return Ql(t);if(!await nt(t,n))throw new m(400,`Unknown base ref: ${n}`);return n}async function nr(t,e){let n=Yn(e,"head");if(n===null)return;if(!await nt(t,n))throw new m(400,`Unknown head ref: ${n}`);return n}function Vo(t,e){if(e&&t.get("head")!==null)throw new m(400,"head cannot be combined with uncommitted work (it only exists against HEAD)")}var Zl=new Set(["staged","unstaged","both","untracked"]);function tu(t){let e=t.get("uncommitted");if(e===null)return null;if(!Zl.has(e))throw new m(400,`Invalid "uncommitted" (expected staged, unstaged, both or untracked): ${e}`);return e}function eu(t){return{staged:W(t,"staged",!1),unstaged:W(t,"unstaged",!1),untracked:W(t,"untracked",!1)}}function nu(t){if(t.unstaged&&!t.staged)throw new m(400,"unstaged needs staged too (unstaged edits sit on top of staged ones)")}function Qo(t,e){let{registry:n}=e;if(t.get("/repos/:id/history",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=Fo(s,"count",100,5000);v(o,200,await rs(i.path,a))}),t.get("/repos/:id/commits/:hash",async({params:r,res:s})=>{let o=R(n,r.id),i=tr(r.hash),a=await ss(o.path,i);if(a===null)throw new m(404,`Unknown commit: ${i}`);v(s,200,a)}),t.get("/repos/:id/commits/:hash/diff",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=tr(r.hash);await Yo(i.path,a);let c=s.get("path")??void 0,l=he(s,c),u=c?await kn(i.path,{kind:"commit",hash:a},c,{context:l}):await Ts(i.path,a);v(o,200,u)}),t.get("/repos/:id/commits/:hash/files",async({params:r,res:s})=>{let o=R(n,r.id),i=tr(r.hash);await Yo(o.path,i),v(s,200,await Ps(o.path,i))}),t.get("/repos/:id/compare/file",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=Q(s),c=he(s,a),l=tu(s);if(Vo(s,l!==null),l==="untracked"){v(o,200,await gt(i.path,a));return}let u=await He(i.path,s),f=l===null?{kind:"compare",base:u,head:await nr(i.path,s)}:{kind:"compare-uncommitted",mergeBase:await er(()=>Ds(i.path,u)),tip:l==="staged"?"index":"worktree"};v(o,200,await kn(i.path,f,a,{context:c}))}),t.get("/repos/:id/head-message",async({params:r,res:s})=>{let o=R(n,r.id);v(s,200,{message:await Yr(o.path)})}),t.get("/repos/:id/branches",async({params:r,res:s})=>{let o=R(n,r.id);v(s,200,await as(o.path))}),t.get("/repos/:id/base-branches",async({params:r,res:s})=>{let o=R(n,r.id);v(s,200,await Rs(o.path))}),t.get("/repos/:id/compare/base",async({params:r,res:s})=>{let o=R(n,r.id);v(s,200,{base:await vn(o.path)})}),e.apiMode==="full")t.put("/repos/:id/compare/base",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=yt(s,"branch");if(!await nt(i.path,a))throw new m(400,`Not a valid base ref: ${a}`);ws(i.path,a),v(o,200,{base:a})});t.get("/repos/:id/compare/count",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=await He(i.path,s),c=await nr(i.path,s),l=await er(()=>Is(i.path,a,c));v(o,200,{baseBranch:a,commits:l})}),t.get("/repos/:id/compare/stack",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=await He(i.path,s);v(o,200,await Ko(i.path,a))}),t.get("/repos/:id/compare",async({params:r,query:s,res:o})=>{let i=R(n,r.id),a=eu(s);Vo(s,a.staged||a.unstaged||a.untracked),nu(a);let c=await He(i.path,s),l=await nr(i.path,s),u=await er(()=>Ms(i.path,c,a,l));v(o,200,u)})}function ru(t){let e=t.get("since");if(e===null)return 0;if(!/^\d+$/.test(e))throw new m(400,`Invalid "since" (expected a non-negative integer): ${e}`);return Number(e)}function Zo(t,e){let{registry:n}=e;t.get("/repos/:id/journal",({params:r,query:s,res:o})=>{let i=R(n,r.id),a=ru(s);v(o,200,Er(i.manager.journal.journalStore,a))})}function ti(t,e){let{registry:n}=e;t.post("/repos/:id/push",async({params:r,res:s})=>{let o=R(n,r.id);await j(o,s,()=>o.manager.remote.push())}),t.post("/repos/:id/fetch",async({params:r,res:s})=>{let o=R(n,r.id);await j(o,s,()=>o.manager.remote.fetchRemote())}),t.post("/repos/:id/pull",async({params:r,res:s})=>{let o=R(n,r.id);await j(o,s,()=>o.manager.remote.pullRebase())}),t.post("/repos/:id/stash",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=To(s,"message");await j(i,o,()=>i.manager.remote.stash(a))}),t.post("/repos/:id/stash-pop",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=Vn(s,"index",{min:0,fallback:0});await j(i,o,()=>i.manager.remote.stashPop(a))}),t.post("/repos/:id/switch-branch",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=yt(s,"name");await j(i,o,()=>i.manager.remote.switchBranch(a))}),t.post("/repos/:id/create-branch",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=yt(s,"name");await j(i,o,()=>i.manager.remote.createBranch(a))}),t.post("/repos/:id/soft-reset",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=Vn(s,"count",{min:1,fallback:1});if(!await nt(i.path,`HEAD~${a}`))throw new m(400,`Cannot soft-reset ${a} commit(s): HEAD~${a} does not exist`);await j(i,o,()=>i.manager.remote.softReset(a))}),t.post("/repos/:id/cherry-pick",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=yt(s,"hash");await j(i,o,()=>i.manager.remote.cherryPick(a))}),t.post("/repos/:id/revert",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=yt(s,"hash");await j(i,o,()=>i.manager.remote.revertCommit(a))}),t.post("/repos/:id/abort",async({params:r,res:s})=>{let o=R(n,r.id);if(!await It(o.path))throw new m(409,"No operation in progress to abort");await j(o,s,()=>o.manager.remote.abortOperation())}),t.post("/repos/:id/rebase-continue",async({params:r,res:s})=>{let o=R(n,r.id);if(await It(o.path)!=="rebase")throw new m(409,"No rebase in progress to continue");await j(o,s,()=>o.manager.remote.rebaseContinue())})}import*as qe from"node:fs";import*as de from"node:path";import*as rr from"node:fs";var We=rr.constants.O_RDONLY|(rr.constants.O_NONBLOCK??0);async function Ht(t,e,n){let r=Buffer.alloc(n),s=0;while(s<n){let{bytesRead:o}=await t.read(r,s,n-s,e+s);if(o===0)break;s+=o}return s===n?r:r.subarray(0,s)}var Ut=8388608;var ei=65536;function Wt(t){return Array.from(t,(e)=>e.charCodeAt(0))}function jt(t,e,n){if(e+n.length>t.length)return!1;for(let r=0;r<n.length;r++)if(t[e+r]!==n[r])return!1;return!0}function je(t,e){return t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function sr(t,e){return(t[e]<<8)+t[e+1]}function Ue(t,e){return t[e]+(t[e+1]<<8)}function ni(t,e){return String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3])}function P(t){return{ok:!1,refusal:t}}function Gt(t){return P(t?"malformed":"header-not-found")}function or(t,e){if(t<1||e<1)return"malformed";if(t>8192||e>8192)return"too-many-pixels";if(t*e>16777216)return"too-many-pixels";return null}var su=[137,80,78,71,13,10,26,10],ou=[255,216,255],iu=Wt("GIF87a"),au=Wt("GIF89a"),Z=Wt("ftyp");function J(t){return{offset:8,bytes:Wt(t)}}var cu=[{label:"webp",offset:0,bytes:Wt("RIFF"),brand:J("WEBP")},{label:"avif",offset:4,bytes:Z,brand:J("avif")},{label:"avis",offset:4,bytes:Z,brand:J("avis")},{label:"heic",offset:4,bytes:Z,brand:J("heic")},{label:"heix",offset:4,bytes:Z,brand:J("heix")},{label:"heim",offset:4,bytes:Z,brand:J("heim")},{label:"heis",offset:4,bytes:Z,brand:J("heis")},{label:"hevc",offset:4,bytes:Z,brand:J("hevc")},{label:"hevx",offset:4,bytes:Z,brand:J("hevx")},{label:"mif1",offset:4,bytes:Z,brand:J("mif1")},{label:"msf1",offset:4,bytes:Z,brand:J("msf1")},{label:"tiff-le",offset:0,bytes:[73,73,42,0]},{label:"tiff-be",offset:0,bytes:[77,77,0,42]},{label:"bmp",offset:0,bytes:Wt("BM")},{label:"ico",offset:0,bytes:[0,0,1,0]},{label:"cur",offset:0,bytes:[0,0,2,0]},{label:"jxl-codestream",offset:0,bytes:[255,10]},{label:"jxl-container",offset:0,bytes:[0,0,0,12,74,88,76,32,13,10,135,10]}];function lu(t){return cu.some((e)=>jt(t,e.offset,e.bytes)&&(e.brand===void 0||jt(t,e.brand.offset,e.brand.bytes)))}var uu={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},fu=26;function hu(t,e,n){if(t.length<fu)return Gt(n);if(je(t,8)!==13)return P("malformed");if(ni(t,12)!=="IHDR")return P("malformed");let r=je(t,16),s=je(t,20),o=or(r,s);if(o)return P(o);let i=uu[t[25]];if(!i||!i.includes(t[24]))return P("malformed");let a=du(t,n);if(a)return a;return{ok:!0,info:{format:"png",mime:"image/png",width:r,height:s,bytes:e}}}function du(t,e){let n=8;for(let r=0;r<256;r++){if(n+8>t.length)return Gt(e);let s=je(t,n),o=ni(t,n+4);if(o==="IDAT")return null;if(o==="acTL")return P("animation");if(o==="iCCP"&&s>65536)return P("malformed");let i=n+12+s;if(i<=n||!Number.isSafeInteger(i))return P("malformed");n=i}return P("malformed")}var pu=218,mu=226,gu=new Set([219,238,192,193,194,196]);function wu(t){return t>=224&&t<=239||gu.has(t)}function yu(t){return t===1||t>=208&&t<=217}function bu(t){return t>=192&&t<=207&&t!==196&&t!==200&&t!==204}var Eu=new Set([192,193,194]);function Su(t,e,n){if(t.length<4)return Gt(n);if(!wu(t[3]))return P("malformed");return ku(t,e,n)}function vu(t,e,n,r,s){if(!Eu.has(n))return P("malformed");if(e+9>t.length)return Gt(s);let o=sr(t,e+5),i=sr(t,e+7),a=or(i,o);if(a)return P(a);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:i,height:o,bytes:r}}}function xu(t,e){if(e+1>=t.length)return{kind:"ran-out"};if(t[e]!==255)return{kind:"malformed"};let n=t[e+1];if(n===255)return{kind:"skip",next:e+1};if(yu(n))return{kind:"skip",next:e+2};if(n===pu)return{kind:"malformed"};if(e+4>t.length)return{kind:"ran-out"};let r=sr(t,e+2);if(r<2)return{kind:"malformed"};if(bu(n))return{kind:"sof",marker:n};return{kind:"segment",marker:n,length:r}}function ku(t,e,n){let r=2,s=0;for(let o=0;o<1024;o++){let i=xu(t,r);if(i.kind==="ran-out")return Gt(n);if(i.kind==="malformed")return P("malformed");if(i.kind==="sof")return vu(t,r,i.marker,e,n);if(i.kind==="skip"){r=i.next;continue}if(i.marker===mu){if(s+=i.length-2,s>65536)return P("malformed")}r+=2+i.length}return P("malformed")}var Ru=59,_u=44,Au=33;function ri(t){return(t&128)===0?0:3*(1<<(t&7)+1)}function Iu(t,e,n){if(e>2097152)return P("too-large");if(!n)return P("header-not-found");if(t.length<13)return Gt(n);let r=Ue(t,6),s=Ue(t,8),o=or(r,s);if(o)return P(o);let i={pos:13+ri(t[10]),left:8192,pixels:0,overBudget:!1},a=Du(t,i);if(a===null)return P("malformed");if(a<1)return P("malformed");if(a>256)return P("too-many-pixels");if(i.overBudget)return P("too-many-pixels");if(a*r*s>33554432)return P("too-many-pixels");let c={format:"gif",mime:"image/gif",width:r,height:s,bytes:e};if(a>1)c.frames=a;return{ok:!0,info:c}}function Du(t,e){let n=0;while(e.left-- >0){if(e.pos>=t.length)return null;let r=t[e.pos];if(r===Ru)return n;let s=r===_u;if(!(s?Tu(t,e):Pu(t,e,r)))return null;if(s&&++n>256)return n;if(e.overBudget)return n}return null}function Pu(t,e,n){if(n!==Au)return!1;return e.pos+=2,si(t,e)}function Tu(t,e){if(e.pos+10>t.length)return!1;Mu(e,Ue(t,e.pos+5),Ue(t,e.pos+7));let n=t[e.pos+9];return e.pos+=10+ri(n)+1,si(t,e)}function Mu(t,e,n){let r=e*n;if(e>8192||n>8192||r>16777216){t.overBudget=!0;return}if(t.pixels+=r,t.pixels>33554432)t.overBudget=!0}function si(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 oi(t){return jt(t,0,iu)||jt(t,0,au)}function qt(t,e,n){if(e>8388608)return P("too-large");if(jt(t,0,su))return hu(t,e,n);if(jt(t,0,ou))return Su(t,e,n);if(oi(t))return Iu(t,e,n);if(lu(t))return P("unsupported-format");return P("not-an-image")}function Ge(t,e){return oi(t)?Math.min(e,2097152):65536}function ir(t){let e={files:new Map,directories:new Set};for(let n of t){e.files.set(n.path,{status:n.status,staged:n.staged});let r=n.path.split("/"),s="";for(let o=0;o<r.length-1;o++)s=s?`${s}/${r[o]}`:r[o],e.directories.add(s);e.directories.add("")}return e}var Fu=1048576,ii=5000;class pe extends Error{constructor(t){super(`Not a regular file: ${t}`);this.name="NotRegularFileError"}}async function ci(t,e,n,r){let s=n?.hideHidden??!0,o=n?.hideGitignored??!0,i=de.join(t,e),a=await qe.promises.readdir(i,{withFileTypes:!0}),c=a.map((f)=>e?de.join(e,f.name):f.name),l=o?await Rt(t,c):new Set,u=[];for(let f of a){if(s&&f.name.startsWith("."))continue;let h=e?de.join(e,f.name):f.name;if(o&&l.has(h))continue;let d=f.isDirectory(),p={name:f.name,path:h,type:d?"dir":"file"};if(r)if(d){if(r.directories.has(h))p.hasChanges=!0}else{let g=r.files.get(h);if(g)p.gitStatus=g.status,p.staged=g.staged}u.push(p)}return u.sort((f,h)=>{if(f.type==="dir"&&h.type!=="dir")return-1;if(f.type!=="dir"&&h.type==="dir")return 1;return f.name.localeCompare(h.name)}),u}var $u=16;async function Cu(t,e){let n=await Ht(t,0,Math.min($u,e)),r=qt(n,e,n.length>=e);if(!r.ok&&r.refusal==="too-large")return{head:n,result:r};let s=Math.min(Ge(n,e),e),o=s<=n.length?n.subarray(0,s):Buffer.concat([n,await Ht(t,n.length,s-n.length)]);return{head:o,result:qt(o,e,o.length>=e)}}function Nu(t,e){return t.ok?{image:t.info,refusal:null,version:e}:{image:null,refusal:t.refusal,version:e}}function ai(t,e){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:t,totalLines:0,media:e}}function ar(t,e){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:t,totalLines:0,media:e}}function Ou(t,e){let n=t.toString("utf-8"),r=n.split(`
|
|
47
|
-
`),s=!1;if(r.length>
|
|
48
|
-
`),s=!0;return{content:n,binary:!1,truncated:s,tooLarge:!1,size:e,totalLines:r.length}}async function
|
|
49
|
-
`))throw new Xt("Query cannot span lines — this searches for literal text");try{return pi(await Ee(t,Gu(e),Wu))}catch(n){let r=n;if(r.code===1)return di;if(r.killed===!0||r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...r.stdout?pi(r.stdout):di,incomplete:!0};throw n}}function gi(t,e){let{registry:n}=e;t.post("/repos/:id/search",async({params:r,body:s,res:o})=>{let i=R(n,r.id),a=q(s,"query");try{let c=await mi(i.path,a);v(o,200,c)}catch(c){if(c instanceof ze)throw new m(400,`Query must be at least ${Xe} characters`,{cause:c});if(c instanceof Xt)throw new m(400,c.message,{cause:c});throw c}})}import{Worker as qu}from"node:worker_threads";var Xu=1000,zu=64,Ju={status:"unavailable",reason:"deadline"},me={status:"unavailable",reason:"error"};function Ku(){let t=import.meta.url;return t.endsWith(".ts")?new URL("./symbolWorker.ts",t):new URL("./symbolWorker.js",t)}function wi(t){let e=t.timeoutMs??Xu,n=new Set(t.extensions),r=null,s=0,o=Promise.resolve(),i=!1,a=new Map;function c(h,d){a.delete(h),a.set(h,d);while(a.size>zu){let p=a.keys().next().value;if(p===void 0)break;a.delete(p)}}function l(){let h=r;if(r=null,h!==null)h.terminate()}function u(){let h=new qu(Ku(),{workerData:{grammarDir:t.grammarDir,queryDir:t.queryDir}});return h.unref(),h}function f(h,d){return new Promise((p)=>{if(r===null)try{r=u()}catch(b){E("Cannot start the symbol worker",b,{path:h}),p(me);return}let g=r,S=++s,y=!1,A=(b,it)=>{if(y)return;if(y=!0,clearTimeout(k),g.off("message",I),g.off("error",D),g.off("exit",w),it)l();p(b)},I=(b)=>{if(b.seq!==S)return;A(b.outcome,!1)},D=(b)=>{E("Symbol worker failed; discarding it",b,{path:h}),A(me,!0)},w=(b)=>{E(`Symbol worker exited with code ${b}; discarding it`,void 0,{path:h}),A(me,!0)},k=setTimeout(()=>{E(`Symbol extraction passed its ${e}ms deadline; discarding the worker`,void 0,{path:h}),A(Ju,!0)},e);k.unref?.(),g.on("message",I),g.on("error",D),g.on("exit",w);let _={seq:S,relPath:h,content:d};try{g.postMessage(_)}catch(b){E("Cannot send a file to the symbol worker; discarding it",b,{path:h}),A(me,!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 me;let p=`${h}\x00${d}`,g=a.get(p);if(g!==void 0)return c(p,g),g;let S=o.then(()=>f(h,d));o=S.catch(()=>{return});let y=await S;return c(p,y),y},async dispose(){i=!0;let h=r;if(r=null,a.clear(),h!==null)await h.terminate()}}}import{spawn as Yu}from"node:child_process";import*as bi from"node:fs";import*as Ei from"node:path";class zt extends Error{constructor(t){super(`Not a regular blob: ${t}`);this.name="NotRegularBlobError"}}class Jt extends Error{size;constructor(t,e){super(`Blob too large: ${t} (${e} bytes)`);this.name="BlobTooLargeError",this.size=e}}class St extends Error{constructor(t){super(`Unsafe blob path: ${t}`);this.name="UnsafeBlobPathError"}}var Je=65536,Si=/^[0-9a-f]{40}([0-9a-f]{24})?$/,Vu=new Set(["100644","100755"]);function Qu(t){if(t==="")throw new St("empty");if(t.includes("\x00"))throw new St("contains NUL");if(t.startsWith("-"))throw new St('starts with "-"');if(t.startsWith(":"))throw new St('starts with ":"')}function Ke(t,e,n){return Ee(t,[...ne,...e],n)}function vi(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 xi(t,e){let n=Buffer.from(e,"utf8");for(let r of t){let s=r.indexOf(9);if(s<0)continue;if(!r.subarray(s+1).equals(n))continue;return r.subarray(0,s).toString("utf8").trim().split(/\s+/)}return null}var Zu=1;async function tf(t){let e;try{e=(await Ke(t,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],Je)).toString("utf8").trim()}catch(n){if(n?.code===Zu)return null;throw n}return Si.test(e)?e:null}async function ef(t,e){let n=await tf(t);if(n===null)return null;let r=await Ke(t,["ls-tree","-z","--full-tree","-l",n,"--",e],Je),s=xi(vi(r),e);if(s===null||s.length!==4)return null;return{mode:s[0],oid:s[2],sizeText:s[3]}}async function nf(t,e){let n=await Ke(t,["ls-files","--stage","-z","--",e],Je),r=xi(vi(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 ki(t,e){let n=Number.parseInt(t,10);if(!Number.isSafeInteger(n)||n<0)throw Error(`git reported a malformed size for ${e}`);return n}async function rf(t,e,n){let r=await Ke(t,["cat-file","-s",e],Je);return ki(r.toString("utf8").trim(),n)}var yi=Buffer.alloc(0);function Ri(t,e){let n=yi,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=yi,r=!1}}}function sf(t,e){let n=null,r=[],s=0,o=!1,i=null,a=null,c=!1,l=null,u=()=>o&&i!==null,f=()=>{if(r.length!==1){let g=Buffer.concat(r,s);r.length=0,r.push(g)}return r[0]};function h(){if(l===null)return;if(a===null&&u()&&i?.signal===null&&i.code!==0)a=Error(`git cat-file blob failed for ${e} (exit ${i.code??"null"})`);if(a===null&&s<l.want&&!u())return;let g=l;if(l=null,clearTimeout(g.timer),n?.stdout?.pause(),a!==null)g.reject(a);else g.resolve(f().subarray(0,Math.min(g.want,s)))}function d(g){a??=g,h()}function p(){let g=Yu("git",[...ne,"cat-file","blob",e],{cwd:t,env:ct(),stdio:["ignore","pipe","ignore"],windowsHide:!0});n=g,g.stdout?.on("data",(S)=>{if(c)return;r.push(S),s+=S.length,h()}),g.stdout?.on("end",()=>{o=!0,h()}),g.stdout?.on("error",d),g.on("error",d),g.on("close",(S,y)=>{i={code:S,signal:y},h()})}return{read(g){if(a!==null)return Promise.reject(a);if(c)return Promise.reject(Error(`read after close for ${e}`));if(g<=s||u())return Promise.resolve(f().subarray(0,Math.min(g,s)));if(l!==null)return Promise.reject(Error(`concurrent read of ${e}`));return new Promise((S,y)=>{let A=setTimeout(()=>{n?.kill("SIGKILL"),d(Error(`git cat-file blob timed out for ${e}`))},un);if(l={want:g,resolve:S,reject:y,timer:A},n===null)p();else n.stdout?.resume()})},release(){if(c=!0,l!==null)d(Error(`git cat-file blob closed while reading ${e}`));r.length=0,s=0,n?.kill("SIGKILL"),n=null}}}function of(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function af(t,e,n){let r=Ei.join(t,e),s;try{s=await bi.promises.open(r,We)}catch(o){if(of(o))return null;throw o}try{let o=await s.stat();if(!o.isFile())throw new zt(e);if(o.size>n)throw new Jt(e,o.size);let i=o.size,a=Ri(i,async(c,l)=>{let u=await Ht(s,l.length,c-l.length);return l.length===0?u:Buffer.concat([l,u])});return{oid:null,size:i,version:`${i}-${o.mtimeMs}`,read:(c)=>a.read(c),close:()=>(a.release(),s.close())}}catch(o){try{await s.close()}catch{}throw o}}async function cf(t,e,n,r){let s=e==="head"?await ef(t,n):await nf(t,n);if(s===null)return null;if(!Vu.has(s.mode))throw new zt(n);if(!Si.test(s.oid))throw Error(`git reported a malformed object id for ${n}`);let o=s.oid,i=s.sizeText===null?await rf(t,o,n):ki(s.sizeText,n);if(i>r)throw new Jt(n,i);let a=sf(t,o),c=Ri(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 _i(t,e,n,r){if(Qu(n),e==="worktree")return af(t,n,r);return cf(t,e,n,r)}var lf=["worktree","index","head"],uf=16,ff=ei,hf=Ut,df=["too-large","too-many-pixels"];function pf(t){let e=t.get("side");if(e===null||!lf.includes(e))throw new m(400,'Invalid "side" (expected worktree, index or head)');return e}function Pi(t){if(t instanceof zt)throw new m(400,t.message,{cause:t});if(t instanceof St)throw new m(400,t.message,{cause:t});if(t instanceof Jt)throw new m(413,t.message,{cause:t});throw t}async function Ai(t,e){let n=await t.read(e);return{bytes:n,sniff:qt(n,t.size,n.length>=t.size)}}async function mf(t,e){let{size:n}=t,r=await t.read(uf),s=qt(r,n,r.length>=n);if(!s.ok&&s.refusal==="too-large")return{bytes:r,sniff:s};let o=Math.min(Ge(r,n),n),i=await Ai(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 Ai(t,n)}async function Ti(t,e,n,r){let s=await _i(t,e,n,Ut);if(s===null)return null;try{let{bytes:o,sniff:i}=await mf(s,r);return{bytes:o,size:s.size,oid:s.oid,version:s.version,sniff:i}}finally{await s.close()}}function gf(t,e,n){let r={"content-type":e,"content-disposition":"inline","x-content-type-options":"nosniff","cross-origin-resource-policy":"same-origin",vary:"sec-fetch-site, sec-fetch-dest","cache-control":t==="worktree"?"no-store":"private, no-cache"};if(t!=="worktree"&&n!==null)r.etag=`"${n}"`;return r}function wf(t){let e=df.includes(t)?413:415;return new m(e,`Image not served: ${t}`)}function yf(t,e){let n=t.originalPath??t.path;switch(t.status){case"untracked":return{old:null,new:{side:"worktree",path:t.path}};case"added":return{old:null,new:{side:e?"index":"worktree",path:t.path}};case"deleted":return{old:{side:e?"head":"index",path:n},new:null};default:return e?{old:{side:"head",path:n},new:{side:"index",path:t.path}}:{old:{side:"index",path:n},new:{side:"worktree",path:t.path}}}}function bf(t,e,n){return{path:t.path,side:t.side,bytes:e,oid:null,image:null,refusal:n,version:""}}async function Ii(t,e){let n=bt(t.path,e.path);await Et(t,n);let r;try{r=await Ti(t.path,e.side,n,ff)}catch(s){if(s instanceof Jt)return bf(e,s.size,"too-large");if(s instanceof zt)return null;Pi(s)}if(r===null)return null;return{path:e.path,side:e.side,bytes:r.size,oid:r.oid,version:r.version,image:r.sniff.ok?r.sniff.info:null,refusal:r.sniff.ok?null:r.sniff.refusal}}function Ef(t,e){return e.writableEnded||e.destroyed===!0||t.destroyed===!0}async function Di(t,e,n){let r=t.acquire();if(r===null)throw new m(503,"Too many image requests in flight");let s=await r;if(n.once("finish",s),n.once("close",s),e.once("close",s),Ef(e,n))return s(),!1;return!0}function Mi(t,e,n){let{registry:r}=e;t.get("/repos/:id/media",async({params:s,query:o,req:i,res:a})=>{let c=R(r,s.id),l=W(o,"staged"),u=bt(c.path,Q(o));if(await Et(c,u),!await Di(n,i,a))return;let f=await Bt(c.manager.workingTree,u,l),h=yf(f,l),d={old:h.old===null?null:await Ii(c,h.old),new:h.new===null?null:await Ii(c,h.new)};v(a,200,d)}),t.get("/repos/:id/blob",async({params:s,query:o,req:i,res:a})=>{let c=R(r,s.id),l=Dr(i);if(l)throw new m(l.status,l.message);let u=pf(o),f=bt(c.path,Q(o));if(await Et(c,f),!await Di(n,i,a))return;let h;try{h=await Ti(c.path,u,f,hf)}catch(p){Pi(p)}if(h===null)throw new m(404,`No such blob on side ${u}: ${f}`);if(!h.sniff.ok)throw wf(h.sniff.refusal);let d=gf(u,h.sniff.info.mime,h.oid);Sr(a,200,h.bytes,d)})}function Fi(t,e){let{registry:n,sse:r,daemonEvents:s,follow:o}=e;t.get("/events",({req:i,res:a,query:c})=>{let l=n.listRepos().map((f)=>({id:f.id,path:f.path}));s.subscribe(i,a,l);let u=c.get("repo");if(!u)return;r.attach(u,n.getRepo(u)?.manager??null,i,a)}),t.get("/follow",({res:i})=>{v(i,200,o?o.state:uo)})}import*as ur from"node:os";import*as Kt from"node:path";function $i(t,e){let{settings:n,discovery:r,daemonEvents:s}=e,o=()=>({...n.settings,persisted:n.persisted});t.get("/settings",({res:i})=>{v(i,200,o())}),t.put("/settings",async({body:i,res:a})=>{let c=Po(i,"watchRoots"),l;try{l=ho(c)}catch(f){throw new m(400,f instanceof Error?f.message:String(f),{cause:f})}try{n.save({...n.settings,watchRoots:l})}catch(f){let h=f instanceof Error?f.message:String(f);throw new m(500,`Could not save settings: ${h}`,{cause:f})}await r.setRoots(l);let u=o();s.broadcast("settings-change",u),v(a,200,u)}),t.get("/discovered",({res:i})=>{v(i,200,r.state)}),t.get("/browse",async({query:i,res:a})=>{let c=i.get("path"),l=c?K(c):ur.homedir();if(!Kt.isAbsolute(l))throw new m(400,`Path must be absolute: ${c}`);let u=Kt.resolve(l),f;try{f=await mo(u)}catch(d){throw new m(404,`Cannot read directory: ${u}`,{cause:d})}let h=Kt.dirname(u);v(a,200,{path:u,parent:h===u?null:h,home:ur.homedir(),entries:f})}),t.post("/discovered/rescan",async({res:i})=>{v(i,200,await r.rescan())})}function fr(t=4,e=64){let n=0,r=[];function s(){let o=!1;return()=>{if(o)return;o=!0;let i=r.shift();if(i)i(s());else n--}}return{acquire(){if(n<t)return n++,Promise.resolve(s());if(r.length>=e)return null;return new Promise((o)=>{r.push(o)})},get active(){return n},get queued(){return r.length}}}function Sf(t){if(!vt.existsSync(t))return Promise.resolve(!1);return new Promise((e)=>{try{let n=Ni.connect(t);n.once("connect",()=>{n.destroy(),e(!0)}),n.once("error",()=>{n.destroy(),e(!1)})}catch{e(!1)}})}function Oi(t={}){let e=new Bn,n=new Hn,r=new On({onOpened:(w)=>n.broadcast("repo-opened",{id:w.id,path:w.path}),onClosed:(w)=>{e.closeRepo(w),n.broadcast("repo-closed",{id:w})}}),s=t.followFile?new jn(r,n,t.followFile):null,o=ko(t.updateCheck===!1?()=>Promise.resolve(null):t.fetchLatestVersion),i=new Gn(t.settingsFile??null),a=new Xn(n),c=new Map,l=fr(),u=t.symbols??null,f=u===null?null:{pool:wi(u),gate:fr(1,4),extensions:u.extensions};function h(w){let k=c.get(w);if(k)return k;let _=new an,b={registry:r,sse:e,daemonEvents:n,follow:s,settings:i,discovery:a,apiMode:w,version:o,symbols:f,httpPort:y};if(_o(_,b),Ao(_,b),Lo(_,b),Wo(_,b),Qo(_,b),Zo(_,b),w==="full")ti(_,b);return ui(_,b),gi(_,b),Mi(_,b,l),Fi(_,b),$i(_,b),c.set(w,_),_}let d=(w)=>t.apiMode??(w==="tcp"?"web":"full");s?.start(),a.setRoots(i.load().watchRoots);let p=t.webRoot?kr(t.webRoot):void 0,g=new Set,S=[];function y(){for(let w of S){let k=w.server.address();if(k!==null&&typeof k==="object")return k.port}return null}function A(w){let k=h(w),_=Ci.createServer((b,it)=>{for(let[tt,ge]of Object.entries(Pr))it.setHeader(tt,ge);if(Ar(_.address())){let tt=Ir(b);if(tt){v(it,tt.status,{error:tt.message});return}}k.handle(b,it,p).catch((tt)=>{T(`${b.method??"GET"} ${b.url??"/"} escaped the router`,tt),it.end()})});return _.on("connection",(b)=>{g.add(b),b.on("close",()=>g.delete(b))}),_}async function I(w,k){let _=w==="unix"?k.socketPath??null:null;if(_){if(await Sf(_))throw Error(`diffstalkerd already running at ${_}`);vt.rmSync(_,{force:!0})}let b={server:A(d(w)),socketPath:_};S.push(b),await new Promise((it,tt)=>{let ge=(zi)=>tt(zi);b.server.once("error",ge);let Ve=()=>{if(b.server.removeListener("error",ge),_)vt.chmodSync(_,384);it()};if(w==="fd")b.server.listen({fd:k.fd},Ve);else if(_)process.umask(63),b.server.listen(_,Ve);else b.server.listen(k.port,"127.0.0.1",Ve)})}function D(w){return new Promise((k,_)=>{w.server.close((b)=>{if(w.socketPath)vt.rmSync(w.socketPath,{force:!0});if(b&&b.code!=="ERR_SERVER_NOT_RUNNING")_(b);else k()})})}return{address(){return S[0]?.server.address()??null},addresses(){return S.map((w)=>w.server.address()).filter((w)=>w!==null)},getRepo(w){return r.getRepo(w)},async openRepo(w){let{handle:k}=await Ne(r,w);return{id:k.id,path:k.path}},async listen(w){let k=[];if(w.fd!==void 0)k.push("fd");if(w.socketPath)k.push("unix");if(w.port!==void 0)k.push("tcp");if(k.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let _ of k)await I(_,w)},close(){s?.dispose(),a.dispose(),e.destroy(),n.destroy(),r.disposeAll();for(let k of g)k.destroy();let w=f?.pool.dispose()??Promise.resolve();return Promise.all([w,...S.splice(0).map(D)]).then(()=>{})}}}import*as hr from"node:fs";import*as Yt from"node:path";import*as Ui from"node:crypto";import{createRequire as xf}from"node:module";var Li=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 Bi(){return[...Li.keys()]}function vf(t){let e=t.slice(t.lastIndexOf("/")+1),n=e.lastIndexOf(".");if(n<=0)return"";return e.slice(n).toLowerCase()}function Hi(t){return Li.get(vf(t))??null}var kf="diffstalkerd-grammars";function Rf(t){return Ui.createHash("sha256").update(t).digest("hex")}function _f(t){try{let e=JSON.parse(hr.readFileSync(Yt.join(t,"checksums.json"),"utf8"));if(typeof e.webTreeSitterVersion!=="string"||typeof e.files!=="object")return null;return e}catch{return null}}var Wi="0.26.11";function Af(t,e,n){for(let[r,s]of Object.entries(e.files)){let o;try{o=hr.readFileSync(Yt.join(t,r))}catch{return n(`grammars: missing ${r}`),!1}if(Rf(o)!==s)return n(`grammars: checksum mismatch for ${r}`),!1}return!0}function If(t){let e=new Set;for(let n of Object.keys(t.files)){let r=/^tree-sitter-(.+)\.wasm$/.exec(n);if(r!==null&&t.files[`queries/${r[1]}.scm`]!==void 0)e.add(r[1])}return e}function ji(t,e=()=>{}){let n=_f(t);if(n===null)return e(`grammars: no readable checksums.json in ${t}`),null;if(n.webTreeSitterVersion!==Wi)return e(`grammars: built for web-tree-sitter ${n.webTreeSitterVersion}, this daemon bundles ${Wi} — symbols disabled`),null;if(!Af(t,n,e))return null;let r=If(n),s=Bi().filter((o)=>{let i=Hi(`x${o}`);return i!==null&&r.has(i.grammar)});if(s.length===0)return e("grammars: no usable grammar found"),null;return{grammarDir:t,queryDir:Yt.join(t,"queries"),extensions:s}}function Gi(t,e=()=>{}){if(t!==null)return ji(t,e);try{let r=xf(import.meta.url).resolve(`${kf}/checksums.json`);return ji(Yt.dirname(r),e)}catch{return null}}var Xi="diffstalkerd.sock";function Pf(t){return t===void 0?Xi:`${t}.sock`}var Tf=3,qi=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
|
|
40
|
+
`)},vo),this.keepAlive.unref();t.on("close",()=>{if(this.subscribers.delete(e),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),Lt(e,"snapshot",JSON.stringify(n))}broadcast(t,e){let n=JSON.stringify(e);for(let r of this.subscribers)Lt(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 Et from"node:fs";import*as Ge from"node:path";import{watch as Dl}from"chokidar";import{EventEmitter as Il}from"node:events";var Tl=100;class qn extends Il{cooldownMs;targetFile;watcher=null;cooldownTimer=null;eventDuringCooldown=!1;lastReadPath=null;_state={path:null,rawContent:null};constructor(t,e=Tl){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=z(t);return Ge.isAbsolute(e)?e:Ge.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=Et.readFileSync(this.targetFile,"utf-8"),e=an(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;b("Cannot read the follow hook file",t,{file:this.targetFile})}}start(){if(xe(this.targetFile),!Et.existsSync(this.targetFile))Et.writeFileSync(this.targetFile,"");try{let t=Et.readFileSync(this.targetFile,"utf-8"),e=an(t);if(e){let n=this.processContent(e);this.lastReadPath=n,this._state={path:n,rawContent:e}}}catch(t){b("Cannot read the follow hook file",t,{file:this.targetFile})}this.watcher=Dl(this.targetFile,{persistent:!0,ignoreInitial:!0}),this.watcher.on("change",()=>this.onFileEvent()),this.watcher.on("add",()=>this.onFileEvent()),this.watcher.on("error",(t)=>{b("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)=>{b("Failed to close the follow hook file watcher",t,{file:this.targetFile})}),this.watcher=null}}var ko={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class Xn{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 qn(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)=>{M("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){N("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 G from"node:fs";import*as Ht from"node:path";function _o(){return{watchRoots:[]}}var zn=16;function Ml(t){let e=t.trim();if(!e)throw Error("Watch directory cannot be empty");let n=z(e);if(!Ht.isAbsolute(n))throw Error(`Watch directory must be absolute: ${t}`);let r=Ht.resolve(n),s;try{s=G.statSync(r)}catch{throw Error(`No such directory: ${r}`)}if(!s.isDirectory())throw Error(`Not a directory: ${r}`);return r}function Ao(t){if(t.length>zn)throw Error(`Too many watch directories (max ${zn})`);let e=new Set,n=[];for(let r of t){let s=Ml(r);if(e.has(s))continue;e.add(s),n.push(s)}return n}function Pl(t){let e=_o();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,zn);return e}class Jn{file;current=_o();constructor(t){this.file=t}get settings(){return this.current}get persisted(){return this.file!==null}load(){if(!this.file)return this.current;let t;try{t=G.readFileSync(this.file,"utf-8")}catch(e){if(e.code!=="ENOENT")M("Cannot read the settings file; running with defaults",e,{file:this.file});return this.current}try{this.current=Pl(JSON.parse(t))}catch(e){b("Ignoring the settings file: not valid JSON",e,{file:this.file})}return this.current}save(t){if(this.current=t,!this.file)return this.current;G.mkdirSync(Ht.dirname(this.file),{recursive:!0});let e=`${this.file}.${process.pid}.tmp`;try{G.writeFileSync(e,`${JSON.stringify(this.current,null,2)}
|
|
41
|
+
`,{mode:384}),G.renameSync(e,this.file)}catch(n){throw G.rmSync(e,{force:!0}),n}return this.current}}import*as Mo from"node:path";import{watch as Wl}from"chokidar";import*as q from"node:fs/promises";import*as F from"node:path";var Fl=2,Cl=500,$l=new Set(["node_modules","vendor","target","dist","build","venv","__pycache__"]);async function Do(t){try{return await q.stat(F.join(t,".git")),!0}catch{return!1}}async function Nl(t){let e=F.join(t,".git"),n;try{n=await q.stat(e)}catch{return null}if(n.isDirectory())return e;try{let r=await q.readFile(e,"utf-8"),s=/^gitdir:\s*(.+)$/m.exec(r);if(!s)return null;let o=s[1].trim(),i=F.isAbsolute(o)?o:F.resolve(t,o);return await q.stat(i),i}catch{return null}}async function Kn(t){let e;try{e=(await q.readFile(F.join(t,"HEAD"),"utf-8")).trim()}catch{return null}let n=/^ref:\s*refs\/heads\/(.+)$/.exec(e);if(n)return n[1].trim();if(/^[0-9a-f]{40}$/i.test(e))return e.slice(0,7);return null}async function Ol(t){let e=[t];try{let o=await q.readdir(F.join(t,"worktrees"));e.push(...o.map((i)=>F.join(t,"worktrees",i)))}catch{}let n=e.flatMap((o)=>[F.join(o,"index"),F.join(o,"HEAD")]),s=(await Promise.all(n.map(async(o)=>{try{return(await q.stat(o)).mtimeMs}catch{return null}}))).filter((o)=>o!==null);return s.length===0?null:Math.max(...s)}async function Ll(t){let e=await Nl(t);if(e===null)return null;let[n,r]=await Promise.all([Kn(e),Ol(e)]);return{path:t,name:F.basename(t),branch:n,lastActivity:r}}function Hl(t){if(!t.isDirectory())return!1;if(t.name.startsWith("."))return!1;return!$l.has(t.name)}async function Io(t){let e=await Yn(t);return Promise.all(e.map(async(n)=>({name:F.basename(n),path:n,isRepo:await Do(n)})))}async function Yn(t){return(await q.readdir(t,{withFileTypes:!0})).filter(Hl).map((n)=>F.join(t,n.name)).sort()}async function Bl(t,e,n){let r=[],s=[];for(let o of t){if(r.length>=n)return{repos:r,next:s,capped:!0};if(await Do(o)){r.push(o);continue}if(!e)continue;try{s.push(...await Yn(o))}catch{}}return{repos:r,next:s,capped:!1}}async function To(t,e={}){let n=e.depth??Fl,r=e.limit??Cl,s=await Yn(t),o=[],i=!1;for(let c=1;c<=n&&s.length>0&&!i;c++){let l=await Bl(s,c<n,r-o.length);o.push(...l.repos),i=l.capped,s=l.next.sort()}return{repos:(await Promise.all(o.map(Ll))).filter((c)=>c!==null),capped:i}}var Gl=300;function Ul(t){let e=Mo.basename(t);return e.startsWith(".")&&e!=="."||e==="node_modules"}class Vn{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)=>{b("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 To(t);e.state={path:t,repos:n.repos,error:null,capped:n.capped}}catch(n){b("Watch directory scan failed",n,{root:t}),e.state={path:t,repos:[],error:n instanceof Error?n.message:String(n),capped:!1}}}startWatching(t){let e=this.roots.get(t);if(!e||e.watcher)return;let n=Wl(t,{persistent:!0,ignoreInitial:!0,depth:1,ignored:Ul});n.on("error",(r)=>{b("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())},Gl),e.timer.unref?.()}broadcast(){if(this.disposed)return;this.hub.broadcast("discovery-change",this.state)}}import*as Oo from"node:fs";import{execFile as jl}from"node:child_process";import*as ht from"node:fs";import*as ot from"node:path";import{fileURLToPath as ql}from"node:url";var Po={method:"unknown",package:null,command:null},ge="diffstalkerd",Xl=3000,zl=["paru","yay"],Jl=[{method:"bun",pattern:/\/install\/global\/node_modules\/diffstalkerd$/,command:`bun add -g ${ge}`},{method:"pnpm",pattern:/\/pnpm\/global\/\d+\/node_modules\/diffstalkerd$/,command:`pnpm add -g ${ge}`},{method:"yarn",pattern:/\/yarn\/global\/node_modules\/diffstalkerd$/,command:`yarn global add ${ge}`},{method:"npm",pattern:/\/lib\/node_modules\/diffstalkerd$/,command:`npm install -g ${ge}`}];async function Kl(t,e){let n=t.split(ot.sep).join("/").replace(/\/+$/,"");for(let s of Jl){if(!s.pattern.test(n))continue;let o=e.writable(t)?"":"sudo ";return{method:s.method,package:ge,command:`${o}${s.command}`}}let r=await e.pacmanOwner(ot.join(t,"package.json"));if(r!==null){let s=e.onPath(zl);return{method:"pacman",package:r,command:s?`${s} -S ${r}`:`sudo pacman -Syu ${r}`}}return Po}var Yl={onPath(t){let e=(process.env.PATH??"").split(ot.delimiter).filter(Boolean);for(let n of t)for(let r of e)try{return ht.accessSync(ot.join(r,n),ht.constants.X_OK),n}catch{}return null},pacmanOwner(t){return new Promise((e)=>{jl("pacman",["-Qoq","--",t],{timeout:Xl},(n,r)=>{if(n)return e(null);let s=r.trim().split(`
|
|
42
|
+
`)[0]?.trim();e(s?s:null)})})},writable(t){try{return ht.accessSync(t,ht.constants.W_OK),!0}catch{return!1}}};function Vl(){let t=ot.dirname(ql(new URL("../package.json",import.meta.url)));try{return ht.realpathSync(t)}catch{return t}}function Fo(t=Vl(),e=Yl){let n=null;return{info(){return n??=Kl(t,e).catch((r)=>(b("Install detection failed",r,{dir:t}),Po)),n}}}import*as Co from"node:fs";var Ql=/^[A-Za-z0-9:_.@-]+\.service$/,Zl=/^user@\d+\.service$/,tu=/^0::(.*)$/m;function eu(t){let e=tu.exec(t);if(e===null)return null;let n=e[1].split("/"),r=n.at(-1)??"";if(!Ql.test(r))return null;let s=r.slice(0,-8);return n.some((o)=>Zl.test(o))?`systemctl --user restart ${s}`:`sudo systemctl restart ${s}`}function $o(t=process.pid,e=process.env,n=()=>Co.readFileSync("/proc/self/cgroup","utf-8")){if(e.SYSTEMD_EXEC_PID!==String(t))return null;try{return eu(n())}catch(r){return b("Cannot read /proc/self/cgroup to name the systemd unit",r),null}}var nu="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",ru=21600000,su=300000,ou=5000;function Qn(){try{let t=Oo.readFileSync(new URL("../package.json",import.meta.url),"utf-8"),e=JSON.parse(t);return typeof e.version==="string"?e.version:null}catch(t){return b("Cannot read the daemon version from its package.json",t),null}}async function iu(){let t=await fetch(nu,{headers:{accept:"application/json"},signal:AbortSignal.timeout(ou)});if(!t.ok)return null;let e=await t.json();return typeof e.latest==="string"?e.latest:null}function No(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());if(!e)return null;return[Number(e[1]),Number(e[2]),Number(e[3])]}function au(t,e){if(t===null||e===null)return"unknown";let n=No(t),r=No(e);if(!n||!r)return"unknown";for(let s=0;s<n.length;s++){if(n[s]<r[s])return"outdated";if(n[s]>r[s])return"ahead"}return"current"}function Lo(t=iu,e=Qn(),n=Fo(),r=$o()){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)=>(N("Latest version lookup failed",a),null)).then((a)=>{let c=a===null?su:ru;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:au(e,a),install:c,restart:r}}}}import*as Ho from"node:os";function Bo(t,e){t.get("/health",({res:n})=>{v(n,200,{ok:!0,ready:!0,home:Ho.homedir(),http:{port:e.httpPort()},symbols:{extensions:e.symbols?.extensions??[]}})})}function Wo(t,e){t.get("/version",async({res:n})=>{v(n,200,await e.version.state())})}import*as Vo from"node:fs";import*as Bt from"node:fs";import*as C from"node:path";function Wt(t,e){let n=t.getRepo(e);if(!n)throw new m(404,`Unknown repo id: ${e}`);return n}function k(t,e){let n=Wt(t,e),r=n.manager.workingTree.unavailable;if(r!==null)throw new m(410,r);return n}function U(t,e,n){if(typeof t!=="object"||t===null)throw new m(400,`Expected a JSON body with "${e}"`);let r=t[e];if(typeof r!=="string"||!n?.allowEmpty&&r.length===0)throw new m(400,`Missing "${e}" (string) in body`);return r}function Uo(t,e){if(t.length===0)throw new m(400,`Invalid "${e}" (expected a ref)`);if(t.startsWith("-"))throw new m(400,`Invalid "${e}" (must not start with "-"): ${t}`);return t}function St(t,e){return Uo(U(t,e),e)}function er(t,e){let n=t.get(e);return n===null?null:Uo(n,e)}function jo(t,e){if(typeof t!=="object"||t===null)throw new m(400,`Expected a JSON body with "${e}"`);let n=t[e];if(!Array.isArray(n)||n.some((r)=>typeof r!=="string"))throw new m(400,`Missing "${e}" (array of strings) in body`);return n}function qo(t,e){if(typeof t!=="object"||t===null)return;let n=t[e];if(n===void 0)return;if(typeof n!=="string"||n.length===0)throw new m(400,`Invalid "${e}" (expected a non-empty string)`);return n}function nr(t,e,n){if(typeof t!=="object"||t===null)return n.fallback;let r=t[e];if(r===void 0)return n.fallback;if(typeof r!=="number"||!Number.isInteger(r)||r<n.min)throw new m(400,`Invalid "${e}" (expected an integer >= ${n.min})`);return r}function Xo(t,e){if(typeof t!=="object"||t===null)return!1;let n=t[e];if(n===void 0)return!1;if(typeof n!=="boolean")throw new m(400,`Invalid "${e}" (expected a boolean)`);return n}function B(t,e,n){let r=t.get(e);if(r===null){if(n===void 0)throw new m(400,`Missing "${e}" query parameter (expected true or false)`);return n}if(r==="true")return!0;if(r==="false")return!1;throw new m(400,`Invalid "${e}" (expected true or false): ${r}`)}function V(t){let e=t.get("path");if(!e)throw new m(400,'Missing "path" query parameter');return e}function we(t,e){let n=B(t,"whole",!1);if(n&&!e)throw new m(400,"whole=true requires a path (one file at a time)");return n?$s:void 0}function zo(t,e,n,r){let s=t.get(e);if(s===null)return n;let o=Number(s);if(!Number.isInteger(o)||o<1)throw new m(400,`Invalid "${e}" (expected a positive integer): ${s}`);if(r!==void 0&&o>r)throw new m(400,`Invalid "${e}" (must be <= ${r}): ${s}`);return o}async function it(t){if(await t.catchUp(),!t.state.status)await t.refresh();let e=t.state.status;if(!e)throw new m(500,"Repository status unavailable");return e}function Go(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 Gt(t,e,n){let r=await it(t),s=Go(r,e,n);if(!s)await t.refresh(),r=await it(t),s=Go(r,e,n);if(!s)throw new m(404,`File not in status: ${e}`);return s}function tr(t,e){return t===e||t.startsWith(e+C.sep)}function rr(t){return t.replace(/[. ]+$/,"").toLowerCase()===".git"}function Rt(t,e){if(e.length===0)throw new m(400,"Empty path");if(e.includes("\x00"))throw new m(400,"Path contains a NUL byte");let n=C.resolve(t),r=C.relative(n,C.resolve(n,e));if(r==="")throw new m(400,`Path resolves to the repository root: ${e}`);if(C.isAbsolute(r)||r===".."||r.startsWith(`..${C.sep}`))throw new m(400,`Path escapes repository root: ${e}`);if(r.startsWith("-"))throw new m(400,`Path must not start with "-": ${e}`);if(r.startsWith(":"))throw new m(400,`Path must not start with ":": ${e}`);if(r.split(C.sep).some(rr))throw new m(400,`Path addresses the git directory: ${e}`);return r}async function Jo(t){try{return await Bt.promises.realpath(t)}catch{return null}}var Zn=new WeakMap;async function cu(t){let e=Zn.get(t);if(!e)e=(async()=>{let n=await R(t.path).raw(["rev-parse","--absolute-git-dir"]);return await Bt.promises.realpath(n.trim())})(),Zn.set(t,e),e.catch(()=>Zn.delete(t));try{return await e}catch(n){throw new m(500,"Cannot resolve the git directory for this repository",{cause:n})}}async function vt(t,e){let n=await Bt.promises.realpath(C.resolve(t.path)),r=await Jo(C.join(t.path,e));if(r===null)return;if(!tr(r,n))throw new m(400,`Path escapes repository root: ${e}`);if(tr(r,await cu(t)))throw new m(400,`Path addresses the git directory: ${e}`)}async function Ko(t,e){let n=await Bt.promises.realpath(C.resolve(t)),r=[];for(let s of e){let o=await Jo(C.join(t,s.path));if(o===null||tr(o,n))r.push(s)}return r}function Ue(t){return t?.code??null}async function sr(t){let e;try{e=await Bt.promises.stat(t)}catch(n){let r=Ue(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 lu(t){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test(t)?409:500}function Yo(t,e){return new m(t,e)}async function at(t,e,n){t.clearError(),await n();let r=t.state.error;if(r)throw Yo(lu(r),r);await t.refresh(),v(e,200,{state:lt(t.state)})}var uu=/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged|no tracking information|no upstream|no configured push destination/i;function fu(t){return uu.test(t)?409:500}async function W(t,e,n){let r=t.manager.remote,s=()=>new m(409,`A ${r.remoteState.operation??"remote"} operation is already in progress`);if(r.remoteState.inProgress)throw s();let o=await n();if(o===null)throw s();let i=t.manager.workingTree;if(await i.refresh(),o.error)throw Yo(fu(o.error),o.error);v(e,200,{state:lt(i.state),result:o.lastResult})}function hu(t){if(t.reason==="not-a-repo"&&!Vo.existsSync(t.requested))return new m(404,`No such directory: ${t.requested}`,{cause:t});return new m(400,t.message,{cause:t})}async function du(t,e){let n=e.state.status;if(n&&!e.stale)return n.branch.current;let r=Ot(t);return r===null?null:Kn(r.gitDir)}function Qo(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 du(o.path,o.manager.workingTree)})));v(r,200,s)}),t.post("/repos",async({body:r,res:s})=>{let o=U(r,"path"),i;try{i=await We(n,o)}catch(a){if(a instanceof Be)throw hu(a);throw a}v(s,i.created?201:200,{id:i.handle.id,path:i.handle.path})}),t.get("/resolve",async({query:r,res:s})=>{let o=V(r),i=await Fe(o,{mustExist:!0});if(!i.ok&&i.reason==="not-absolute")throw new m(400,`Repo path must be absolute: ${i.requested}`);v(s,200,{openable:i.ok,root:i.ok?i.root:null})}),t.get("/repos/:id/worktrees",async({params:r,res:s})=>{let o=k(n,r.id);v(s,200,await Pn(o.path))}),t.get("/worktrees",async({query:r,res:s})=>{v(s,200,await Pn(V(r)))}),t.delete("/repos/:id",({params:r,res:s})=>{Wt(n,r.id),n.closeRepo(r.id),v(s,200,{})})}function Zo(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 ti(t){return t.trim()}async function pu(t){let e=(r)=>r.filter((s)=>s.staged).length,n=e((await it(t)).files);if(n===0)await t.refresh(),n=e((await it(t)).files);return n}function ei(t,e){let{registry:n,sse:r}=e;if(t.get("/repos/:id/status",async({params:s,res:o})=>{let i=Wt(n,s.id);await it(i.manager.workingTree),v(o,200,lt(i.manager.workingTree.state))}),t.get("/repos/:id/diff",async({params:s,query:o,res:i})=>{let a=k(n,s.id),c=a.manager.workingTree,l=o.get("path")??void 0,u=B(o,"staged",!1),f=we(o,l);if(!l){let E=await c.wholeTreeDiffs();if(!E){let w=c.unavailable;throw new m(w?410:500,w??"Repository diff unavailable")}v(i,200,u?E.staged:E.unstaged);return}let d=(await it(c)).files.some((E)=>E.path===l&&E.status==="untracked");if(d&&u)throw new m(400,`staged=true is meaningless for untracked file: ${l} (untracked files have no staged diff)`);let p=f!==void 0&&!d,g=d?await yt(a.path,l):await Ns(a.path,l,u,{context:f});if(!p)c.stampDiff(g);v(i,200,g)}),t.post("/repos/:id/stage",async({params:s,body:o,res:i})=>{let a=k(n,s.id),c=U(o,"path"),l=a.manager.workingTree,u=await Gt(l,c,!1);await at(l,i,()=>l.stage(u))}),t.post("/repos/:id/unstage",async({params:s,body:o,res:i})=>{let a=k(n,s.id),c=U(o,"path"),l=a.manager.workingTree,u=await Gt(l,c,!0);await at(l,i,()=>l.unstage(u))}),t.get("/repos/:id/events",({params:s,req:o,res:i})=>{let a=Wt(n,s.id);r.subscribe(s.id,a.manager,o,i)}),e.apiMode==="full")mu(t,e)}function mu(t,e){let{registry:n}=e;t.post("/repos/:id/stage-all",async({params:r,res:s})=>{let i=k(n,r.id).manager.workingTree;await at(i,s,()=>i.stageAll())}),t.post("/repos/:id/unstage-all",async({params:r,res:s})=>{let i=k(n,r.id).manager.workingTree;await at(i,s,()=>i.unstageAll())}),t.post("/repos/:id/discard",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=U(s,"path"),c=i.manager.workingTree,l=await Gt(c,a,!1);if(l.staged)throw new m(409,`Cannot discard a staged file: ${a} (unstage it first)`);await at(c,o,()=>c.discard(l))}),t.post("/repos/:id/commit",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=U(s,"message",{allowEmpty:!0}),c=Xo(s,"amend"),l=i.manager.workingTree,u=await pu(l),f=Zo(a,u,c);if(!f.valid)throw new m(400,f.error??"Invalid commit");await at(l,o,()=>l.commit(ti(a),c))}),t.post("/repos/:id/stage-hunk",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=U(s,"patch"),c=i.manager.workingTree;await at(c,o,()=>c.stageHunk(a))}),t.post("/repos/:id/unstage-hunk",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=U(s,"patch"),c=i.manager.workingTree;await at(c,o,()=>c.unstageHunk(a))})}var gu=1000,je="refs/heads/",ni="refs/remotes/";async function si(t,e,n){let r=["for-each-ref","--format=%(objectname) %(refname) %(symref)",`--no-merged=${e}`];if(n!==void 0)r.push(`--contains=${n}`);r.push("refs/heads","refs/remotes");let s=await t.raw(r),o=[];for(let i of s.split(`
|
|
43
|
+
`)){if(!i)continue;let[a,c,l]=i.split(" ");if(l)continue;if(c.startsWith(je))o.push({tip:a,name:c.slice(je.length),local:!0});else if(c.startsWith(ni))o.push({tip:a,name:c.slice(ni.length),local:!1})}return o}function wu(t){return new Map(t.filter((e)=>e.local).map((e)=>[e.name,e.tip]))}function oi(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 yu(t){return new Set(t.filter((e)=>!e.local).map((e)=>e.name.slice(e.name.indexOf("/")+1)))}function ii(t,e){return!t.local||e.has(t.name)}async function ai(t,e,n){return(await t.raw(["rev-list","--first-parent",`--max-count=${gu}`,"--end-of-options",`${e}..${n}`])).split(`
|
|
44
|
+
`).filter(Boolean).reverse()}async function bu(t){let e=await t.raw(["rev-parse","HEAD","--symbolic-full-name","HEAD"]),[n,r]=e.split(`
|
|
45
|
+
`),s=r.startsWith(je)?r.slice(je.length):null;return{tip:n,name:s??"HEAD",branch:s}}async function ri(t,e){if(e.length<2)return e;return(await t.raw(["merge-base","--independent","--end-of-options",...e])).split(`
|
|
46
|
+
`).filter(Boolean)}function Eu(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 ci(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=Eu(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 Su(t,e,n,r,s,o){let i=oi(await si(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 ri(t,a);if(c.length>1){let u=[...new Set(i.filter((f)=>ii(f,o)).map((f)=>f.tip))];if(u.length>0)c=await ri(t,u)}if(c.length!==1)return{layers:[],forked:!0};let l=await ai(t,n,c[0]);return{layers:ci(l,s,null,o),forked:!1}}function Ru(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 li(t,e){let n=R(t),r=await bu(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([si(n,e),ai(n,s,r.tip)]),a=wu(o),c=yu(o),l=new Map,u=new Set;for(let d of oi(o,a)){let p=l.get(d.tip);if(p)p.push(d);else l.set(d.tip,[d]);if(ii(d,c))u.add(d.tip)}let f=ci(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 Su(n,e,r.tip,a,l,c);return{trunk:e,layers:Ru([...f,...h.layers],u),forkedAbove:h.forked}}function or(t){if(!/^[0-9a-f]{4,40}$/i.test(t))throw new m(400,`Invalid commit hash: ${t}`);return t}async function ui(t,e){if(!await st(t,e))throw new m(404,`Unknown commit: ${e}`)}async function ir(t){try{return await t()}catch(e){if(e instanceof De)throw new m(422,e.message,{cause:e});throw e}}async function vu(t){let e=await Dn(t);if(e&&await st(t,e))return e;if(Ft(t)){let n=await An(t);if(n&&await st(t,n))return n}throw new m(422,"No usable base branch")}async function qe(t,e){let n=er(e,"base");if(n===null)return vu(t);if(!await st(t,n))throw new m(400,`Unknown base ref: ${n}`);return n}async function ar(t,e){let n=er(e,"head");if(n===null)return;if(!await st(t,n))throw new m(400,`Unknown head ref: ${n}`);return n}function fi(t,e){if(e&&t.get("head")!==null)throw new m(400,"head cannot be combined with uncommitted work (it only exists against HEAD)")}var xu=new Set(["staged","unstaged","both","untracked"]);function ku(t){let e=t.get("uncommitted");if(e===null)return null;if(!xu.has(e))throw new m(400,`Invalid "uncommitted" (expected staged, unstaged, both or untracked): ${e}`);return e}function _u(t){return{staged:B(t,"staged",!1),unstaged:B(t,"unstaged",!1),untracked:B(t,"untracked",!1)}}function Au(t){if(t.unstaged&&!t.staged)throw new m(400,"unstaged needs staged too (unstaged edits sit on top of staged ones)")}function hi(t,e){let{registry:n}=e;if(t.get("/repos/:id/history",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=zo(s,"count",100,5000);v(o,200,await gs(i.path,a))}),t.get("/repos/:id/commits/:hash",async({params:r,res:s})=>{let o=k(n,r.id),i=or(r.hash),a=await ws(o.path,i);if(a===null)throw new m(404,`Unknown commit: ${i}`);v(s,200,a)}),t.get("/repos/:id/commits/:hash/diff",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=or(r.hash);await ui(i.path,a);let c=s.get("path")??void 0,l=we(s,c),u=c?await Tn(i.path,{kind:"commit",hash:a},c,{context:l}):await Xs(i.path,a);v(o,200,u)}),t.get("/repos/:id/commits/:hash/files",async({params:r,res:s})=>{let o=k(n,r.id),i=or(r.hash);await ui(o.path,i),v(s,200,await qs(o.path,i))}),t.get("/repos/:id/compare/file",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=V(s),c=we(s,a),l=ku(s);if(fi(s,l!==null),l==="untracked"){v(o,200,await yt(i.path,a));return}let u=await qe(i.path,s),f=l===null?{kind:"compare",base:u,head:await ar(i.path,s)}:{kind:"compare-uncommitted",mergeBase:await ir(()=>js(i.path,u)),tip:l==="staged"?"index":"worktree"};v(o,200,await Tn(i.path,f,a,{context:c}))}),t.get("/repos/:id/head-message",async({params:r,res:s})=>{let o=k(n,r.id);v(s,200,{message:await ls(o.path)})}),t.get("/repos/:id/branches",async({params:r,res:s})=>{let o=k(n,r.id);v(s,200,await Es(o.path))}),t.get("/repos/:id/base-branches",async({params:r,res:s})=>{let o=k(n,r.id);v(s,200,await Bs(o.path))}),t.get("/repos/:id/compare/base",async({params:r,res:s})=>{let o=k(n,r.id);v(s,200,{base:await Dn(o.path)})}),e.apiMode==="full")t.put("/repos/:id/compare/base",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=St(s,"branch");if(!await st(i.path,a))throw new m(400,`Not a valid base ref: ${a}`);Ts(i.path,a),v(o,200,{base:a})});t.get("/repos/:id/compare/count",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=await qe(i.path,s),c=await ar(i.path,s),l=await ir(()=>Us(i.path,a,c));v(o,200,{baseBranch:a,commits:l})}),t.get("/repos/:id/compare/stack",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=await qe(i.path,s);v(o,200,await li(i.path,a))}),t.get("/repos/:id/compare",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=_u(s);fi(s,a.staged||a.unstaged||a.untracked),Au(a);let c=await qe(i.path,s),l=await ar(i.path,s),u=await ir(()=>zs(i.path,c,a,l));v(o,200,u)})}function Du(t){let e=t.get("since");if(e===null)return 0;if(!/^\d+$/.test(e))throw new m(400,`Invalid "since" (expected a non-negative integer): ${e}`);return Number(e)}function di(t,e){let{registry:n}=e;t.get("/repos/:id/journal",async({params:r,query:s,res:o})=>{let i=k(n,r.id),a=Du(s);await i.manager.workingTree.catchUp(),v(o,200,kr(i.manager.journal.journalStore,a))})}function pi(t,e){let{registry:n}=e;t.post("/repos/:id/push",async({params:r,res:s})=>{let o=k(n,r.id);await W(o,s,()=>o.manager.remote.push())}),t.post("/repos/:id/fetch",async({params:r,res:s})=>{let o=k(n,r.id);await W(o,s,()=>o.manager.remote.fetchRemote())}),t.post("/repos/:id/pull",async({params:r,res:s})=>{let o=k(n,r.id);await W(o,s,()=>o.manager.remote.pullRebase())}),t.post("/repos/:id/stash",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=qo(s,"message");await W(i,o,()=>i.manager.remote.stash(a))}),t.post("/repos/:id/stash-pop",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=nr(s,"index",{min:0,fallback:0});await W(i,o,()=>i.manager.remote.stashPop(a))}),t.post("/repos/:id/switch-branch",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=St(s,"name");await W(i,o,()=>i.manager.remote.switchBranch(a))}),t.post("/repos/:id/create-branch",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=St(s,"name");await W(i,o,()=>i.manager.remote.createBranch(a))}),t.post("/repos/:id/soft-reset",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=nr(s,"count",{min:1,fallback:1});if(!await st(i.path,`HEAD~${a}`))throw new m(400,`Cannot soft-reset ${a} commit(s): HEAD~${a} does not exist`);await W(i,o,()=>i.manager.remote.softReset(a))}),t.post("/repos/:id/cherry-pick",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=St(s,"hash");await W(i,o,()=>i.manager.remote.cherryPick(a))}),t.post("/repos/:id/revert",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=St(s,"hash");await W(i,o,()=>i.manager.remote.revertCommit(a))}),t.post("/repos/:id/abort",async({params:r,res:s})=>{let o=k(n,r.id);if(!await Mt(o.path))throw new m(409,"No operation in progress to abort");await W(o,s,()=>o.manager.remote.abortOperation())}),t.post("/repos/:id/rebase-continue",async({params:r,res:s})=>{let o=k(n,r.id);if(await Mt(o.path)!=="rebase")throw new m(409,"No rebase in progress to continue");await W(o,s,()=>o.manager.remote.rebaseContinue())})}import*as Ye from"node:fs";import*as ye from"node:path";import*as cr from"node:fs";var Xe=cr.constants.O_RDONLY|(cr.constants.O_NONBLOCK??0);async function Ut(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 Xt=8388608;var mi=65536;function jt(t){return Array.from(t,(e)=>e.charCodeAt(0))}function qt(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 ze(t,e){return t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function lr(t,e){return(t[e]<<8)+t[e+1]}function Je(t,e){return t[e]+(t[e+1]<<8)}function gi(t,e){return String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3])}function T(t){return{ok:!1,refusal:t}}function zt(t){return T(t?"malformed":"header-not-found")}function ur(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 Iu=[137,80,78,71,13,10,26,10],Tu=[255,216,255],Mu=jt("GIF87a"),Pu=jt("GIF89a"),Q=jt("ftyp");function X(t){return{offset:8,bytes:jt(t)}}var Fu=[{label:"webp",offset:0,bytes:jt("RIFF"),brand:X("WEBP")},{label:"avif",offset:4,bytes:Q,brand:X("avif")},{label:"avis",offset:4,bytes:Q,brand:X("avis")},{label:"heic",offset:4,bytes:Q,brand:X("heic")},{label:"heix",offset:4,bytes:Q,brand:X("heix")},{label:"heim",offset:4,bytes:Q,brand:X("heim")},{label:"heis",offset:4,bytes:Q,brand:X("heis")},{label:"hevc",offset:4,bytes:Q,brand:X("hevc")},{label:"hevx",offset:4,bytes:Q,brand:X("hevx")},{label:"mif1",offset:4,bytes:Q,brand:X("mif1")},{label:"msf1",offset:4,bytes:Q,brand:X("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:jt("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 Cu(t){return Fu.some((e)=>qt(t,e.offset,e.bytes)&&(e.brand===void 0||qt(t,e.brand.offset,e.brand.bytes)))}var $u={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},Nu=26;function Ou(t,e,n){if(t.length<Nu)return zt(n);if(ze(t,8)!==13)return T("malformed");if(gi(t,12)!=="IHDR")return T("malformed");let r=ze(t,16),s=ze(t,20),o=ur(r,s);if(o)return T(o);let i=$u[t[25]];if(!i||!i.includes(t[24]))return T("malformed");let a=Lu(t,n);if(a)return a;return{ok:!0,info:{format:"png",mime:"image/png",width:r,height:s,bytes:e}}}function Lu(t,e){let n=8;for(let r=0;r<256;r++){if(n+8>t.length)return zt(e);let s=ze(t,n),o=gi(t,n+4);if(o==="IDAT")return null;if(o==="acTL")return T("animation");if(o==="iCCP"&&s>65536)return T("malformed");let i=n+12+s;if(i<=n||!Number.isSafeInteger(i))return T("malformed");n=i}return T("malformed")}var Hu=218,Bu=226,Wu=new Set([219,238,192,193,194,196]);function Gu(t){return t>=224&&t<=239||Wu.has(t)}function Uu(t){return t===1||t>=208&&t<=217}function ju(t){return t>=192&&t<=207&&t!==196&&t!==200&&t!==204}var qu=new Set([192,193,194]);function Xu(t,e,n){if(t.length<4)return zt(n);if(!Gu(t[3]))return T("malformed");return Ku(t,e,n)}function zu(t,e,n,r,s){if(!qu.has(n))return T("malformed");if(e+9>t.length)return zt(s);let o=lr(t,e+5),i=lr(t,e+7),a=ur(i,o);if(a)return T(a);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:i,height:o,bytes:r}}}function Ju(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(Uu(n))return{kind:"skip",next:e+2};if(n===Hu)return{kind:"malformed"};if(e+4>t.length)return{kind:"ran-out"};let r=lr(t,e+2);if(r<2)return{kind:"malformed"};if(ju(n))return{kind:"sof",marker:n};return{kind:"segment",marker:n,length:r}}function Ku(t,e,n){let r=2,s=0;for(let o=0;o<1024;o++){let i=Ju(t,r);if(i.kind==="ran-out")return zt(n);if(i.kind==="malformed")return T("malformed");if(i.kind==="sof")return zu(t,r,i.marker,e,n);if(i.kind==="skip"){r=i.next;continue}if(i.marker===Bu){if(s+=i.length-2,s>65536)return T("malformed")}r+=2+i.length}return T("malformed")}var Yu=59,Vu=44,Qu=33;function wi(t){return(t&128)===0?0:3*(1<<(t&7)+1)}function Zu(t,e,n){if(e>2097152)return T("too-large");if(!n)return T("header-not-found");if(t.length<13)return zt(n);let r=Je(t,6),s=Je(t,8),o=ur(r,s);if(o)return T(o);let i={pos:13+wi(t[10]),left:8192,pixels:0,overBudget:!1},a=tf(t,i);if(a===null)return T("malformed");if(a<1)return T("malformed");if(a>256)return T("too-many-pixels");if(i.overBudget)return T("too-many-pixels");if(a*r*s>33554432)return T("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 tf(t,e){let n=0;while(e.left-- >0){if(e.pos>=t.length)return null;let r=t[e.pos];if(r===Yu)return n;let s=r===Vu;if(!(s?nf(t,e):ef(t,e,r)))return null;if(s&&++n>256)return n;if(e.overBudget)return n}return null}function ef(t,e,n){if(n!==Qu)return!1;return e.pos+=2,yi(t,e)}function nf(t,e){if(e.pos+10>t.length)return!1;rf(e,Je(t,e.pos+5),Je(t,e.pos+7));let n=t[e.pos+9];return e.pos+=10+wi(n)+1,yi(t,e)}function rf(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 yi(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 bi(t){return qt(t,0,Mu)||qt(t,0,Pu)}function Jt(t,e,n){if(e>8388608)return T("too-large");if(qt(t,0,Iu))return Ou(t,e,n);if(qt(t,0,Tu))return Xu(t,e,n);if(bi(t))return Zu(t,e,n);if(Cu(t))return T("unsupported-format");return T("not-an-image")}function Ke(t,e){return bi(t)?Math.min(e,2097152):65536}function fr(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 sf=1048576,Ei=5000;class be extends Error{constructor(t){super(`Not a regular file: ${t}`);this.name="NotRegularFileError"}}async function Ri(t,e,n,r){let s=n?.hideHidden??!0,o=n?.hideGitignored??!0,i=ye.join(t,e),a=await Ye.promises.readdir(i,{withFileTypes:!0}),c=a.map((f)=>e?ye.join(e,f.name):f.name),l=o?await Dt(t,c):new Set,u=[];for(let f of a){if(s&&f.name.startsWith("."))continue;let h=e?ye.join(e,f.name):f.name;if(o&&l.has(h))continue;let d=f.isDirectory(),p={name:f.name,path:h,type:d?"dir":"file"};if(r)if(d){if(r.directories.has(h))p.hasChanges=!0}else{let g=r.files.get(h);if(g)p.gitStatus=g.status,p.staged=g.staged}u.push(p)}return u.sort((f,h)=>{if(f.type==="dir"&&h.type!=="dir")return-1;if(f.type!=="dir"&&h.type==="dir")return 1;return f.name.localeCompare(h.name)}),u}var of=16;async function af(t,e){let n=await Ut(t,0,Math.min(of,e)),r=Jt(n,e,n.length>=e);if(!r.ok&&r.refusal==="too-large")return{head:n,result:r};let s=Math.min(Ke(n,e),e),o=s<=n.length?n.subarray(0,s):Buffer.concat([n,await Ut(t,n.length,s-n.length)]);return{head:o,result:Jt(o,e,o.length>=e)}}function cf(t,e){return t.ok?{image:t.info,refusal:null,version:e}:{image:null,refusal:t.refusal,version:e}}function Si(t,e){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:t,totalLines:0,media:e}}function hr(t,e){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:t,totalLines:0,media:e}}function lf(t,e){let n=t.toString("utf-8"),r=n.split(`
|
|
47
|
+
`),s=!1;if(r.length>Ei)n=r.slice(0,Ei).join(`
|
|
48
|
+
`),s=!0;return{content:n,binary:!1,truncated:s,tooLarge:!1,size:e,totalLines:r.length}}async function uf(t,e){let n=await t.stat();if(!n.isFile())throw new be(e);let r=n.size;if(r>Xt)return hr(r);let{head:s,result:o}=await af(t,r),i=cf(o,`${r}-${n.mtimeMs}`);if(o.ok)return Si(r,i);if(r>sf)return hr(r,he(s)?i:void 0);let a=s.length>=r?s:Buffer.concat([s,await Ut(t,s.length,r-s.length)]);return he(a)?Si(r,i):lf(a,r)}async function vi(t,e){let n=ye.join(t,e),r=await Ye.promises.stat(n);if(!r.isFile())throw new be(e);if(r.size>Xt)return hr(r.size);let s=await Ye.promises.open(n,Xe);try{return await uf(s,e)}finally{await s.close()}}import*as dr from"node:path";function xi(t,e){let{registry:n,symbols:r}=e;async function s(o,i,a){if(!a)return o;if(o.binary||o.tooLarge)return o;if(r===null)return{...o,symbols:{status:"unavailable",reason:"error"}};if(!r.pool.supported(i))return{...o,symbols:{status:"unsupported",reason:"language"}};let c=r.gate.acquire();if(c===null)throw new m(503,"Symbol extraction busy");try{return{...o,symbols:await r.pool.extract(i,o.content)}}finally{(await c)()}}t.get("/repos/:id/tree",async({params:o,query:i,res:a})=>{let c=k(n,o.id),l=i.get("dir")??"",u=B(i,"hidden",!1),f=B(i,"ignored",!1),h=l===""?"":Rt(c.path,l);await vt(c,h);let d=await it(c.manager.workingTree),p=fr(d.files),g;try{g=await Ri(c.path,h,{hideHidden:!u,hideGitignored:!f},p)}catch(w){let _=Ue(w);if(_==="ENOENT"||_==="ENOTDIR"){let D=await sr(dr.join(c.path,h));if(D===null)throw new m(404,`No such directory: ${l||"/"}`,{cause:w});throw new m(400,`Not a directory (${D}): ${l}`,{cause:w})}throw w}let E=g.filter((w)=>!rr(w.name));v(a,200,await Ko(c.path,E))}),t.get("/repos/:id/file",async({params:o,query:i,res:a})=>{let c=k(n,o.id),l=V(i),u=Rt(c.path,l);await vt(c,u);try{let f=await vi(c.path,u);v(a,200,await s(f,u,B(i,"symbols",!1)))}catch(f){if(f instanceof be){let d=await sr(dr.join(c.path,u));throw new m(400,`Not a regular file (${d??"unknown"}): ${l}`,{cause:f})}let h=Ue(f);if(h==="ENOENT"||h==="ENOTDIR")throw new m(404,`No such file: ${l}`,{cause:f});throw f}}),t.get("/repos/:id/files",async({params:o,res:i})=>{let a=k(n,o.id);v(i,200,await Ds(a.path))})}var Ve=3,ff=20,ki=500,hf=500,df=4194304,_i=400;class Qe extends Error{constructor(){super(`Query must be at least ${Ve} characters`);this.name="GrepQueryTooShortError"}}class Kt extends Error{constructor(t){super(t);this.name="GrepQueryInvalidError"}}var Ai={matches:[],capped:!1,incomplete:!1,binarySkipped:0};function pf(t){return t===t.toLowerCase()}function pr(t){return Buffer.from(t).toString("utf8")}function mf(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 Di(t,e=hf){let n=[],r=new Map,s=0,o=!1,i=0;while(i<t.length){let a=mf(t,i);if(a===null)break;if(i=a.next,a.contentBytes.includes(0)){s+=1;continue}let c=Number.parseInt(pr(a.lineBytes),10);if(!Number.isSafeInteger(c)||c<1)continue;if(n.length>=e){o=!0;break}let l=pr(a.pathBytes),u=r.get(l)??0;if(u>=ff){o=!0;continue}r.set(l,u+1);let f=pr(a.contentBytes),h=f.length>_i;n.push({path:l,line:c,text:h?f.slice(0,_i):f,truncated:h})}return{matches:n,capped:o,incomplete:!1,binarySkipped:s}}function gf(t){return[...ae,"grep","--no-textconv","--no-recurse-submodules","--full-name","--no-color","--no-column","-I","-n","-z","-F",...pf(t)?["-i"]:[],"-e",t,"--untracked","--","."]}async function Ii(t,e){if(e.length<Ve)throw new Qe;if(e.length>ki)throw new Kt(`Query must be at most ${ki} characters`);if(e.includes("\x00"))throw new Kt("Query cannot contain a NUL byte");if(e.includes(`
|
|
49
|
+
`))throw new Kt("Query cannot span lines — this searches for literal text");try{return Di(await ke(t,gf(e),df))}catch(n){let r=n;if(r.code===1)return Ai;if(r.killed===!0||r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...r.stdout?Di(r.stdout):Ai,incomplete:!0};throw n}}function Ti(t,e){let{registry:n}=e;t.post("/repos/:id/search",async({params:r,body:s,res:o})=>{let i=k(n,r.id),a=U(s,"query");try{let c=await Ii(i.path,a);v(o,200,c)}catch(c){if(c instanceof Qe)throw new m(400,`Query must be at least ${Ve} characters`,{cause:c});if(c instanceof Kt)throw new m(400,c.message,{cause:c});throw c}})}import{Worker as wf}from"node:worker_threads";var yf=1000,bf=64,Ef={status:"unavailable",reason:"deadline"},Ee={status:"unavailable",reason:"error"};function Sf(){let t=import.meta.url;return t.endsWith(".ts")?new URL("./symbolWorker.ts",t):new URL("./symbolWorker.js",t)}function Mi(t){let e=t.timeoutMs??yf,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>bf){let p=a.keys().next().value;if(p===void 0)break;a.delete(p)}}function l(){let h=r;if(r=null,h!==null)h.terminate()}function u(){let h=new wf(Sf(),{workerData:{grammarDir:t.grammarDir,queryDir:t.queryDir}});return h.unref(),h}function f(h,d){return new Promise((p)=>{if(r===null)try{r=u()}catch(S){b("Cannot start the symbol worker",S,{path:h}),p(Ee);return}let g=r,E=++s,w=!1,_=(S,ct)=>{if(w)return;if(w=!0,clearTimeout(x),g.off("message",D),g.off("error",I),g.off("exit",y),ct)l();p(S)},D=(S)=>{if(S.seq!==E)return;_(S.outcome,!1)},I=(S)=>{b("Symbol worker failed; discarding it",S,{path:h}),_(Ee,!0)},y=(S)=>{b(`Symbol worker exited with code ${S}; discarding it`,void 0,{path:h}),_(Ee,!0)},x=setTimeout(()=>{b(`Symbol extraction passed its ${e}ms deadline; discarding the worker`,void 0,{path:h}),_(Ef,!0)},e);x.unref?.(),g.on("message",D),g.on("error",I),g.on("exit",y);let A={seq:E,relPath:h,content:d};try{g.postMessage(A)}catch(S){b("Cannot send a file to the symbol worker; discarding it",S,{path:h}),_(Ee,!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 Ee;let p=`${h}\x00${d}`,g=a.get(p);if(g!==void 0)return c(p,g),g;let E=o.then(()=>f(h,d));o=E.catch(()=>{return});let w=await E;return c(p,w),w},async dispose(){i=!0;let h=r;if(r=null,a.clear(),h!==null)await h.terminate()}}}import{spawn as Rf}from"node:child_process";import*as Fi from"node:fs";import*as Ci from"node:path";class Yt extends Error{constructor(t){super(`Not a regular blob: ${t}`);this.name="NotRegularBlobError"}}class Vt extends Error{size;constructor(t,e){super(`Blob too large: ${t} (${e} bytes)`);this.name="BlobTooLargeError",this.size=e}}class xt extends Error{constructor(t){super(`Unsafe blob path: ${t}`);this.name="UnsafeBlobPathError"}}var Ze=65536,$i=/^[0-9a-f]{40}([0-9a-f]{24})?$/,vf=new Set(["100644","100755"]);function xf(t){if(t==="")throw new xt("empty");if(t.includes("\x00"))throw new xt("contains NUL");if(t.startsWith("-"))throw new xt('starts with "-"');if(t.startsWith(":"))throw new xt('starts with ":"')}function tn(t,e,n){return ke(t,[...ae,...e],n)}function Ni(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 Oi(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 kf=1;async function _f(t){let e;try{e=(await tn(t,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],Ze)).toString("utf8").trim()}catch(n){if(n?.code===kf)return null;throw n}return $i.test(e)?e:null}async function Af(t,e){let n=await _f(t);if(n===null)return null;let r=await tn(t,["ls-tree","-z","--full-tree","-l",n,"--",e],Ze),s=Oi(Ni(r),e);if(s===null||s.length!==4)return null;return{mode:s[0],oid:s[2],sizeText:s[3]}}async function Df(t,e){let n=await tn(t,["ls-files","--stage","-z","--",e],Ze),r=Oi(Ni(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 Li(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 If(t,e,n){let r=await tn(t,["cat-file","-s",e],Ze);return Li(r.toString("utf8").trim(),n)}var Pi=Buffer.alloc(0);function Hi(t,e){let n=Pi,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=Pi,r=!1}}}function Tf(t,e){let n=null,r=[],s=0,o=!1,i=null,a=null,c=!1,l=null,u=()=>o&&i!==null,f=()=>{if(r.length!==1){let g=Buffer.concat(r,s);r.length=0,r.push(g)}return r[0]};function h(){if(l===null)return;if(a===null&&u()&&i?.signal===null&&i.code!==0)a=Error(`git cat-file blob failed for ${e} (exit ${i.code??"null"})`);if(a===null&&s<l.want&&!u())return;let g=l;if(l=null,clearTimeout(g.timer),n?.stdout?.pause(),a!==null)g.reject(a);else g.resolve(f().subarray(0,Math.min(g.want,s)))}function d(g){a??=g,h()}function p(){let g=Rf("git",[...ae,"cat-file","blob",e],{cwd:t,env:ft(),stdio:["ignore","pipe","ignore"],windowsHide:!0});n=g,g.stdout?.on("data",(E)=>{if(c)return;r.push(E),s+=E.length,h()}),g.stdout?.on("end",()=>{o=!0,h()}),g.stdout?.on("error",d),g.on("error",d),g.on("close",(E,w)=>{i={code:E,signal:w},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((E,w)=>{let _=setTimeout(()=>{n?.kill("SIGKILL"),d(Error(`git cat-file blob timed out for ${e}`))},mn);if(l={want:g,resolve:E,reject:w,timer:_},n===null)p();else n.stdout?.resume()})},release(){if(c=!0,l!==null)d(Error(`git cat-file blob closed while reading ${e}`));r.length=0,s=0,n?.kill("SIGKILL"),n=null}}}function Mf(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Pf(t,e,n){let r=Ci.join(t,e),s;try{s=await Fi.promises.open(r,Xe)}catch(o){if(Mf(o))return null;throw o}try{let o=await s.stat();if(!o.isFile())throw new Yt(e);if(o.size>n)throw new Vt(e,o.size);let i=o.size,a=Hi(i,async(c,l)=>{let u=await Ut(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 Ff(t,e,n,r){let s=e==="head"?await Af(t,n):await Df(t,n);if(s===null)return null;if(!vf.has(s.mode))throw new Yt(n);if(!$i.test(s.oid))throw Error(`git reported a malformed object id for ${n}`);let o=s.oid,i=s.sizeText===null?await If(t,o,n):Li(s.sizeText,n);if(i>r)throw new Vt(n,i);let a=Tf(t,o),c=Hi(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 Bi(t,e,n,r){if(xf(n),e==="worktree")return Pf(t,n,r);return Ff(t,e,n,r)}var Cf=["worktree","index","head"],$f=16,Nf=mi,Of=Xt,Lf=["too-large","too-many-pixels"];function Hf(t){let e=t.get("side");if(e===null||!Cf.includes(e))throw new m(400,'Invalid "side" (expected worktree, index or head)');return e}function ji(t){if(t instanceof Yt)throw new m(400,t.message,{cause:t});if(t instanceof xt)throw new m(400,t.message,{cause:t});if(t instanceof Vt)throw new m(413,t.message,{cause:t});throw t}async function Wi(t,e){let n=await t.read(e);return{bytes:n,sniff:Jt(n,t.size,n.length>=t.size)}}async function Bf(t,e){let{size:n}=t,r=await t.read($f),s=Jt(r,n,r.length>=n);if(!s.ok&&s.refusal==="too-large")return{bytes:r,sniff:s};let o=Math.min(Ke(r,n),n),i=await Wi(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 Wi(t,n)}async function qi(t,e,n,r){let s=await Bi(t,e,n,Xt);if(s===null)return null;try{let{bytes:o,sniff:i}=await Bf(s,r);return{bytes:o,size:s.size,oid:s.oid,version:s.version,sniff:i}}finally{await s.close()}}function Wf(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 Gf(t){let e=Lf.includes(t)?413:415;return new m(e,`Image not served: ${t}`)}function Uf(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 jf(t,e,n){return{path:t.path,side:t.side,bytes:e,oid:null,image:null,refusal:n,version:""}}async function Gi(t,e){let n=Rt(t.path,e.path);await vt(t,n);let r;try{r=await qi(t.path,e.side,n,Nf)}catch(s){if(s instanceof Vt)return jf(e,s.size,"too-large");if(s instanceof Yt)return null;ji(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 qf(t,e){return e.writableEnded||e.destroyed===!0||t.destroyed===!0}async function Ui(t,e,n){let r=t.acquire();if(r===null)throw new m(503,"Too many image requests in flight");let s=await r;if(n.once("finish",s),n.once("close",s),e.once("close",s),qf(e,n))return s(),!1;return!0}function Xi(t,e,n){let{registry:r}=e;t.get("/repos/:id/media",async({params:s,query:o,req:i,res:a})=>{let c=k(r,s.id),l=B(o,"staged"),u=Rt(c.path,V(o));if(await vt(c,u),!await Ui(n,i,a))return;let f=await Gt(c.manager.workingTree,u,l),h=Uf(f,l),d={old:h.old===null?null:await Gi(c,h.old),new:h.new===null?null:await Gi(c,h.new)};v(a,200,d)}),t.get("/repos/:id/blob",async({params:s,query:o,req:i,res:a})=>{let c=k(r,s.id),l=Cr(i);if(l)throw new m(l.status,l.message);let u=Hf(o),f=Rt(c.path,V(o));if(await vt(c,f),!await Ui(n,i,a))return;let h;try{h=await qi(c.path,u,f,Of)}catch(p){ji(p)}if(h===null)throw new m(404,`No such blob on side ${u}: ${f}`);if(!h.sniff.ok)throw Gf(h.sniff.refusal);let d=Wf(u,h.sniff.info.mime,h.oid);_r(a,200,h.bytes,d)})}function zi(t,e){let{registry:n,sse:r,daemonEvents:s,follow:o}=e;t.get("/events",({req:i,res:a,query:c})=>{let l=n.listRepos().map((f)=>({id:f.id,path:f.path}));s.subscribe(i,a,l);let u=c.get("repo");if(!u)return;r.attach(u,n.getRepo(u)?.manager??null,i,a)}),t.get("/follow",({res:i})=>{v(i,200,o?o.state:ko)})}import*as mr from"node:os";import*as Qt from"node:path";function Ji(t,e){let{settings:n,discovery:r,daemonEvents:s}=e,o=()=>({...n.settings,persisted:n.persisted});t.get("/settings",({res:i})=>{v(i,200,o())}),t.put("/settings",async({body:i,res:a})=>{let c=jo(i,"watchRoots"),l;try{l=Ao(c)}catch(f){throw new m(400,f instanceof Error?f.message:String(f),{cause:f})}try{n.save({...n.settings,watchRoots:l})}catch(f){let h=f instanceof Error?f.message:String(f);throw new m(500,`Could not save settings: ${h}`,{cause:f})}await r.setRoots(l);let u=o();s.broadcast("settings-change",u),v(a,200,u)}),t.get("/discovered",({res:i})=>{v(i,200,r.state)}),t.get("/browse",async({query:i,res:a})=>{let c=i.get("path"),l=c?z(c):mr.homedir();if(!Qt.isAbsolute(l))throw new m(400,`Path must be absolute: ${c}`);let u=Qt.resolve(l),f;try{f=await Io(u)}catch(d){throw new m(404,`Cannot read directory: ${u}`,{cause:d})}let h=Qt.dirname(u);v(a,200,{path:u,parent:h===u?null:h,home:mr.homedir(),entries:f})}),t.post("/discovered/rescan",async({res:i})=>{v(i,200,await r.rescan())})}function gr(t=4,e=64){let n=0,r=[];function s(){let o=!1;return()=>{if(o)return;o=!0;let i=r.shift();if(i)i(s());else n--}}return{acquire(){if(n<t)return n++,Promise.resolve(s());if(r.length>=e)return null;return new Promise((o)=>{r.push(o)})},get active(){return n},get queued(){return r.length}}}function Xf(t){if(!kt.existsSync(t))return Promise.resolve(!1);return new Promise((e)=>{try{let n=Yi.connect(t);n.once("connect",()=>{n.destroy(),e(!0)}),n.once("error",()=>{n.destroy(),e(!1)})}catch{e(!1)}})}function Vi(t={}){let e=new Un,n=new jn,r=new Gn({onOpened:(y)=>n.broadcast("repo-opened",{id:y.id,path:y.path}),onClosed:(y)=>{e.closeRepo(y),n.broadcast("repo-closed",{id:y})}}),s=t.followFile?new Xn(r,n,t.followFile):null,o=Lo(t.updateCheck===!1?()=>Promise.resolve(null):t.fetchLatestVersion),i=new Jn(t.settingsFile??null),a=new Vn(n),c=new Map,l=gr(),u=t.symbols??null,f=u===null?null:{pool:Mi(u),gate:gr(1,4),extensions:u.extensions};function h(y){let x=c.get(y);if(x)return x;let A=new fn,S={registry:r,sse:e,daemonEvents:n,follow:s,settings:i,discovery:a,apiMode:y,version:o,symbols:f,httpPort:w};if(Bo(A,S),Wo(A,S),Qo(A,S),ei(A,S),hi(A,S),di(A,S),y==="full")pi(A,S);return xi(A,S),Ti(A,S),Xi(A,S,l),zi(A,S),Ji(A,S),c.set(y,A),A}let d=(y)=>t.apiMode??(y==="tcp"?"web":"full");s?.start(),a.setRoots(i.load().watchRoots);let p=t.webRoot?Ir(t.webRoot):void 0,g=new Set,E=[];function w(){for(let y of E){let x=y.server.address();if(x!==null&&typeof x==="object")return x.port}return null}function _(y){let x=h(y),A=Ki.createServer((S,ct)=>{for(let[Z,Se]of Object.entries($r))ct.setHeader(Z,Se);if(Pr(A.address())){let Z=Fr(S);if(Z){v(ct,Z.status,{error:Z.message});return}}x.handle(S,ct,p).catch((Z)=>{M(`${S.method??"GET"} ${S.url??"/"} escaped the router`,Z),ct.end()})});return A.on("connection",(S)=>{g.add(S),S.on("close",()=>g.delete(S))}),A}async function D(y,x){let A=y==="unix"?x.socketPath??null:null;if(A){if(await Xf(A))throw Error(`diffstalkerd already running at ${A}`);kt.rmSync(A,{force:!0})}let S={server:_(d(y)),socketPath:A};E.push(S),await new Promise((ct,Z)=>{let Se=(aa)=>Z(aa);S.server.once("error",Se);let nn=()=>{if(S.server.removeListener("error",Se),A)kt.chmodSync(A,384);ct()};if(y==="fd")S.server.listen({fd:x.fd},nn);else if(A)process.umask(63),S.server.listen(A,nn);else S.server.listen(x.port,"127.0.0.1",nn)})}function I(y){return new Promise((x,A)=>{y.server.close((S)=>{if(y.socketPath)kt.rmSync(y.socketPath,{force:!0});if(S&&S.code!=="ERR_SERVER_NOT_RUNNING")A(S);else x()})})}return{address(){return E[0]?.server.address()??null},addresses(){return E.map((y)=>y.server.address()).filter((y)=>y!==null)},getRepo(y){return r.getRepo(y)},async openRepo(y){let{handle:x}=await We(r,y);return{id:x.id,path:x.path}},async listen(y){let x=[];if(y.fd!==void 0)x.push("fd");if(y.socketPath)x.push("unix");if(y.port!==void 0)x.push("tcp");if(x.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let A of x)await D(A,y)},close(){s?.dispose(),a.dispose(),e.destroy(),n.destroy(),r.disposeAll();for(let x of g)x.destroy();let y=f?.pool.dispose()??Promise.resolve();return Promise.all([y,...E.splice(0).map(I)]).then(()=>{})}}}import*as wr from"node:fs";import*as Zt from"node:path";import*as ra from"node:crypto";import{createRequire as Jf}from"node:module";var Qi=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 Zi(){return[...Qi.keys()]}function zf(t){let e=t.slice(t.lastIndexOf("/")+1),n=e.lastIndexOf(".");if(n<=0)return"";return e.slice(n).toLowerCase()}function ta(t){return Qi.get(zf(t))??null}var Kf="diffstalkerd-grammars";function Yf(t){return ra.createHash("sha256").update(t).digest("hex")}function Vf(t){try{let e=JSON.parse(wr.readFileSync(Zt.join(t,"checksums.json"),"utf8"));if(typeof e.webTreeSitterVersion!=="string"||typeof e.files!=="object")return null;return e}catch{return null}}var ea="0.26.11";function Qf(t,e,n){for(let[r,s]of Object.entries(e.files)){let o;try{o=wr.readFileSync(Zt.join(t,r))}catch{return n(`grammars: missing ${r}`),!1}if(Yf(o)!==s)return n(`grammars: checksum mismatch for ${r}`),!1}return!0}function Zf(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 na(t,e=()=>{}){let n=Vf(t);if(n===null)return e(`grammars: no readable checksums.json in ${t}`),null;if(n.webTreeSitterVersion!==ea)return e(`grammars: built for web-tree-sitter ${n.webTreeSitterVersion}, this daemon bundles ${ea} — symbols disabled`),null;if(!Qf(t,n,e))return null;let r=Zf(n),s=Zi().filter((o)=>{let i=ta(`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:Zt.join(t,"queries"),extensions:s}}function sa(t,e=()=>{}){if(t!==null)return na(t,e);try{let r=Jf(import.meta.url).resolve(`${Kf}/checksums.json`);return na(Zt.dirname(r),e)}catch{return null}}var ia="diffstalkerd.sock";function eh(t){return t===void 0?ia:`${t}.sock`}var nh=3,oa=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
|
|
50
50
|
|
|
51
51
|
Usage: diffstalkerd [options] [REPO_PATH...]
|
|
52
52
|
|
|
@@ -58,7 +58,7 @@ Arguments:
|
|
|
58
58
|
|
|
59
59
|
Options:
|
|
60
60
|
--socket PATH Bind a unix socket at PATH
|
|
61
|
-
(default: $XDG_RUNTIME_DIR/diffstalker/${
|
|
61
|
+
(default: $XDG_RUNTIME_DIR/diffstalker/${ia})
|
|
62
62
|
--instance NAME Bind <NAME>.sock in the runtime dir, so several
|
|
63
63
|
daemons can run side by side (default: the shared
|
|
64
64
|
socket every client looks for first)
|
|
@@ -78,6 +78,6 @@ Options:
|
|
|
78
78
|
ignored follow target) to stderr
|
|
79
79
|
--version, -v Print the running version and exit
|
|
80
80
|
--help, -h Show this help
|
|
81
|
-
`;function
|
|
81
|
+
`;function te(t,e,n){let r=t[e];if(r===void 0||r.startsWith("--"))throw Error(`${n} requires a value`);return r}function rh(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 sh(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=te(t,++n,"--socket");break;case"--instance":e.instance=te(t,++n,"--instance");break;case"--no-socket":e.noSocket=!0;break;case"--port":if(e.port=Number(te(t,++n,"--port")),!Number.isInteger(e.port)||e.port<0)throw Error("--port requires a non-negative integer");break;case"--follow-file":e.followFile=te(t,++n,"--follow-file");break;case"--no-follow":e.noFollow=!0;break;case"--web-root":e.webRoot=te(t,++n,"--web-root");break;case"--grammars":e.grammarsDir=te(t,++n,"--grammars");break;case"--no-update-check":e.noUpdateCheck=!0;break;case"--debug":e.debug=!0;break;default:rh(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 oh(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function ih(t){if(t.noSocket||t.socketPath!==void 0)return;if(oh()){t.fd=nh;return}let e=Sr();if(!e){if(t.port!==void 0){console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set; binding the TCP port only.
|
|
82
82
|
Pass --socket PATH to also accept CLI connections.`);return}console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set and no --socket/--port given.
|
|
83
|
-
Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}
|
|
83
|
+
Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}en.mkdirSync(e,{recursive:!0,mode:448}),t.socketPath=ee.join(e,eh(t.instance))}function ah(t){let e=t??th(new URL("web/",import.meta.url));if(en.existsSync(e))return e;console.error(`diffstalkerd: web UI assets not found at ${e}; serving API only`);return}function ch(t){console.error(`diffstalkerd: web UI at http://diffstalker.localhost:${t}/`)}async function lh(t,e){for(let n of e){let r=ee.resolve(z(n));try{let s=await t.openRepo(r);console.error(`diffstalkerd opened ${s.path}`)}catch(s){console.error(`diffstalkerd: cannot open ${r}: ${s instanceof Error?s.message:String(s)}`),await t.close().catch(()=>{}),process.exit(1)}}}async function uh(){process.title="diffstalkerd";let t;try{t=sh(process.argv.slice(2))}catch(u){console.error(u instanceof Error?u.message:String(u)),console.error(oa),process.exit(2)}if(t==="help"){console.log(oa);return}if(t==="version"){let u=Qn();if(u===null)console.error("diffstalkerd: version unknown (package.json unreadable)"),process.exit(1);console.log(u);return}vr(t.debug??!1),ih(t);let e=t.noFollow?void 0:t.followFile??ee.join(At(),"target"),n=ah(t.webRoot),r=sa(t.grammarsDir??process.env.DIFFSTALKER_GRAMMARS_DIR??null,(u)=>console.error(`diffstalkerd: ${u}`)),s=Vi({followFile:e,settingsFile:ee.join(Er(),"daemon.json"),webRoot:n,symbols:r,updateCheck:!t.noUpdateCheck});await lh(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)ch(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)=>{M(`${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))}uh().catch((t)=>{console.error(t instanceof Error?t.message:String(t)),process.exit(1)});export{sh as parseArgs};
|